You are viewing a plain text version of this content. The canonical link for it is here.
Posted to dev@struts.apache.org by hu...@apache.org on 2006/01/21 01:21:00 UTC
svn commit: r370938 [16/50] - in /struts: action/trunk/
action/trunk/conf/java/ action/trunk/src/java/org/apache/struts/
action/trunk/src/java/org/apache/struts/action/
action/trunk/src/java/org/apache/struts/chain/
action/trunk/src/java/org/apache/str...
Modified: struts/action/trunk/src/java/org/apache/struts/util/RequestUtils.java
URL: http://svn.apache.org/viewcvs/struts/action/trunk/src/java/org/apache/struts/util/RequestUtils.java?rev=370938&r1=370937&r2=370938&view=diff
==============================================================================
--- struts/action/trunk/src/java/org/apache/struts/util/RequestUtils.java (original)
+++ struts/action/trunk/src/java/org/apache/struts/util/RequestUtils.java Fri Jan 20 16:19:02 2006
@@ -15,23 +15,8 @@
* See the License for the specific language governing permissions and
* limitations under the License.
*/
-
package org.apache.struts.util;
-import java.net.MalformedURLException;
-import java.net.URL;
-import java.util.Collections;
-import java.util.Enumeration;
-import java.util.HashMap;
-import java.util.Hashtable;
-import java.util.Locale;
-import java.util.Map;
-
-import javax.servlet.ServletContext;
-import javax.servlet.ServletException;
-import javax.servlet.http.HttpServletRequest;
-import javax.servlet.http.HttpSession;
-
import org.apache.commons.beanutils.BeanUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
@@ -47,157 +32,154 @@
import org.apache.struts.upload.MultipartRequestHandler;
import org.apache.struts.upload.MultipartRequestWrapper;
+import javax.servlet.ServletException;
+import javax.servlet.http.HttpServletRequest;
+import javax.servlet.http.HttpSession;
+import java.net.MalformedURLException;
+import java.net.URL;
+import java.util.Collections;
+import java.util.Enumeration;
+import java.util.HashMap;
+import java.util.Hashtable;
+import java.util.Locale;
+import java.util.Map;
+
/**
* <p>General purpose utility methods related to processing a servlet request
* in the Struts controller framework.</p>
*
- * @version $Rev$ $Date$
+ * @version $Rev$ $Date: 2005-11-09 00:11:45 -0500 (Wed, 09 Nov 2005)
+ * $
*/
public class RequestUtils {
-
-
// ------------------------------------------------------- Static Variables
-
/**
* <p>Commons Logging instance.</p>
*/
protected static Log log = LogFactory.getLog(RequestUtils.class);
-
// --------------------------------------------------------- Public Methods
-
/**
* <p>Create and return an absolute URL for the specified context-relative
* path, based on the server and context information in the specified
* request.</p>
*
* @param request The servlet request we are processing
- * @param path The context-relative path (must start with '/')
- *
- * @return absolute URL based on context-relative path
- *
- * @exception MalformedURLException if we cannot create an absolute URL
+ * @param path The context-relative path (must start with '/')
+ * @return absolute URL based on context-relative path
+ * @throws MalformedURLException if we cannot create an absolute URL
*/
public static URL absoluteURL(HttpServletRequest request, String path)
throws MalformedURLException {
-
return (new URL(serverURL(request), request.getContextPath() + path));
-
}
-
/**
- * <p>Return the <code>Class</code> object for the specified fully qualified
- * class name, from this web application's class loader.</p>
+ * <p>Return the <code>Class</code> object for the specified fully
+ * qualified class name, from this web application's class loader.</p>
*
* @param className Fully qualified class name to be loaded
* @return Class object
- *
- * @exception ClassNotFoundException if the class cannot be found
+ * @throws ClassNotFoundException if the class cannot be found
*/
- public static Class applicationClass(String className) throws ClassNotFoundException {
+ public static Class applicationClass(String className)
+ throws ClassNotFoundException {
return applicationClass(className, null);
}
- /**
- * <p>Return the <code>Class</code> object for the specified fully qualified
- * class name, from this web application's class loader.</p>
+ /**
+ * <p>Return the <code>Class</code> object for the specified fully
+ * qualified class name, from this web application's class loader.</p>
*
- * @param className Fully qualified class name to be loaded
+ * @param className Fully qualified class name to be loaded
* @param classLoader The desired classloader to use
* @return Class object
- *
- * @exception ClassNotFoundException if the class cannot be found
+ * @throws ClassNotFoundException if the class cannot be found
*/
- public static Class applicationClass(String className, ClassLoader classLoader)
+ public static Class applicationClass(String className,
+ ClassLoader classLoader)
throws ClassNotFoundException {
-
if (classLoader == null) {
// Look up the class loader to be used
classLoader = Thread.currentThread().getContextClassLoader();
+
if (classLoader == null) {
classLoader = RequestUtils.class.getClassLoader();
}
- }
+ }
// Attempt to load the specified class
return (classLoader.loadClass(className));
-
}
-
/**
* <p>Return a new instance of the specified fully qualified class name,
- * after loading the class from this web application's class loader.
- * The specified class <strong>MUST</strong> have a public zero-arguments
+ * after loading the class from this web application's class loader. The
+ * specified class <strong>MUST</strong> have a public zero-arguments
* constructor.</p>
*
* @param className Fully qualified class name to use
- *
* @return new instance of class
- * @exception ClassNotFoundException if the class cannot be found
- * @exception IllegalAccessException if the class or its constructor
- * is not accessible
- * @exception InstantiationException if this class represents an
- * abstract class, an interface, an array class, a primitive type,
- * or void
- * @exception InstantiationException if this class has no
- * zero-arguments constructor
+ * @throws ClassNotFoundException if the class cannot be found
+ * @throws IllegalAccessException if the class or its constructor is not
+ * accessible
+ * @throws InstantiationException if this class represents an abstract
+ * class, an interface, an array class, a
+ * primitive type, or void
+ * @throws InstantiationException if this class has no zero-arguments
+ * constructor
*/
public static Object applicationInstance(String className)
- throws ClassNotFoundException, IllegalAccessException, InstantiationException {
-
+ throws ClassNotFoundException, IllegalAccessException,
+ InstantiationException {
return applicationInstance(className, null);
}
- /**
+ /**
* <p>Return a new instance of the specified fully qualified class name,
- * after loading the class from this web application's class loader.
- * The specified class <strong>MUST</strong> have a public zero-arguments
+ * after loading the class from this web application's class loader. The
+ * specified class <strong>MUST</strong> have a public zero-arguments
* constructor.</p>
*
- * @param className Fully qualified class name to use
+ * @param className Fully qualified class name to use
* @param classLoader The desired classloader to use
- *
* @return new instance of class
- * @exception ClassNotFoundException if the class cannot be found
- * @exception IllegalAccessException if the class or its constructor
- * is not accessible
- * @exception InstantiationException if this class represents an
- * abstract class, an interface, an array class, a primitive type,
- * or void
- * @exception InstantiationException if this class has no
- * zero-arguments constructor
- */
- public static Object applicationInstance(String className, ClassLoader classLoader)
- throws ClassNotFoundException, IllegalAccessException, InstantiationException {
-
+ * @throws ClassNotFoundException if the class cannot be found
+ * @throws IllegalAccessException if the class or its constructor is not
+ * accessible
+ * @throws InstantiationException if this class represents an abstract
+ * class, an interface, an array class, a
+ * primitive type, or void
+ * @throws InstantiationException if this class has no zero-arguments
+ * constructor
+ */
+ public static Object applicationInstance(String className,
+ ClassLoader classLoader)
+ throws ClassNotFoundException, IllegalAccessException,
+ InstantiationException {
return (applicationClass(className, classLoader).newInstance());
-
}
/**
- * <p>Create (if necessary) and return an <code>ActionForm</code> instance appropriate
- * for this request. If no <code>ActionForm</code> instance is required, return
- * <code>null</code>.</p>
+ * <p>Create (if necessary) and return an <code>ActionForm</code> instance
+ * appropriate for this request. If no <code>ActionForm</code> instance
+ * is required, return <code>null</code>.</p>
*
- * @param request The servlet request we are processing
- * @param mapping The action mapping for this request
+ * @param request The servlet request we are processing
+ * @param mapping The action mapping for this request
* @param moduleConfig The configuration for this module
- * @param servlet The action servlet
- *
+ * @param servlet The action servlet
* @return ActionForm instance associated with this request
*/
- public static ActionForm createActionForm(
- HttpServletRequest request,
- ActionMapping mapping,
- ModuleConfig moduleConfig,
- ActionServlet servlet) {
-
+ public static ActionForm createActionForm(HttpServletRequest request,
+ ActionMapping mapping,
+ ModuleConfig moduleConfig,
+ ActionServlet servlet) {
// Is there a form bean associated with this mapping?
String attribute = mapping.getAttribute();
+
if (attribute == null) {
return (null);
}
@@ -205,36 +187,36 @@
// Look up the form bean configuration information to use
String name = mapping.getName();
FormBeanConfig config = moduleConfig.findFormBeanConfig(name);
+
if (config == null) {
log.warn("No FormBeanConfig found under '" + name + "'");
+
return (null);
}
- ActionForm instance = lookupActionForm(request, attribute, mapping.getScope());
+ ActionForm instance = lookupActionForm(request, attribute,
+ mapping.getScope());
// Can we recycle the existing form bean instance (if there is one)?
- if (instance != null && config.canReuse(instance)) {
+ if ((instance != null) && config.canReuse(instance)) {
return (instance);
}
return createActionForm(config, servlet);
}
-
-
- private static ActionForm lookupActionForm(HttpServletRequest request, String attribute, String scope)
- {
+ private static ActionForm lookupActionForm(HttpServletRequest request,
+ String attribute,
+ String scope) {
// Look up any existing form bean instance
if (log.isDebugEnabled()) {
- log.debug(
- " Looking for ActionForm bean instance in scope '"
- + scope
- + "' under attribute key '"
- + attribute
- + "'");
+ log.debug(" Looking for ActionForm bean instance in scope '"
+ + scope + "' under attribute key '" + attribute + "'");
}
+
ActionForm instance = null;
HttpSession session = null;
+
if ("request".equals(scope)) {
instance = (ActionForm) request.getAttribute(attribute);
} else {
@@ -246,21 +228,20 @@
}
/**
- * <p>Create and return an <code>ActionForm</code> instance appropriate
- * to the information in <code>config</code>.</p>
+ * <p>Create and return an <code>ActionForm</code> instance appropriate to
+ * the information in <code>config</code>.</p>
*
* <p>Does not perform any checks to see if an existing ActionForm exists
* which could be reused.</p>
*
- * @param config The configuration for the Form bean which is to be created.
+ * @param config The configuration for the Form bean which is to be
+ * created.
* @param servlet The action servlet
- *
* @return ActionForm instance associated with this request
*/
- public static ActionForm createActionForm(FormBeanConfig config, ActionServlet servlet)
- {
- if (config == null)
- {
+ public static ActionForm createActionForm(FormBeanConfig config,
+ ActionServlet servlet) {
+ if (config == null) {
return (null);
}
@@ -268,38 +249,37 @@
// Create and return a new form bean instance
try {
-
instance = config.createActionForm(servlet);
+
if (log.isDebugEnabled()) {
- log.debug(
- " Creating new "
- + (config.getDynamic() ? "DynaActionForm" : "ActionForm")
- + " instance of type '"
- + config.getType()
- + "'");
+ log.debug(" Creating new "
+ + (config.getDynamic() ? "DynaActionForm" :
+ "ActionForm")
+ + " instance of type '" + config.getType() + "'");
log.trace(" --> " + instance);
}
-
- } catch(Throwable t) {
- log.error(servlet.getInternal().getMessage("formBean", config.getType()), t);
+ }
+ catch (Throwable t) {
+ log.error(servlet.getInternal().getMessage("formBean",
+ config.getType()), t);
}
return (instance);
-
}
-
/**
- * <p>Look up and return current user locale, based on the specified parameters.</p>
+ * <p>Look up and return current user locale, based on the specified
+ * parameters.</p>
*
* @param request The request used to lookup the Locale
- * @param locale Name of the session attribute for our user's Locale. If this is
- * <code>null</code>, the default locale key is used for the lookup.
+ * @param locale Name of the session attribute for our user's Locale. If
+ * this is <code>null</code>, the default locale key is
+ * used for the lookup.
* @return current user locale
* @since Struts 1.2
*/
- public static Locale getUserLocale(HttpServletRequest request, String locale) {
-
+ public static Locale getUserLocale(HttpServletRequest request,
+ String locale) {
Locale userLocale = null;
HttpSession session = request.getSession(false);
@@ -318,10 +298,8 @@
}
return userLocale;
-
}
-
/**
* <p>Populate the properties of the specified JavaBean from the specified
* HTTP request, based on matching each parameter name against the
@@ -329,20 +307,17 @@
* Suitable conversion is done for argument types as described under
* <code>convert()</code>.</p>
*
- * @param bean The JavaBean whose properties are to be set
- * @param request The HTTP request whose parameters are to be used
- * to populate bean properties
- *
- * @exception ServletException if an exception is thrown while setting
- * property values
+ * @param bean The JavaBean whose properties are to be set
+ * @param request The HTTP request whose parameters are to be used to
+ * populate bean properties
+ * @throws ServletException if an exception is thrown while setting
+ * property values
*/
- public static void populate(Object bean, HttpServletRequest request) throws ServletException {
-
+ public static void populate(Object bean, HttpServletRequest request)
+ throws ServletException {
populate(bean, null, null, request);
-
}
-
/**
* <p>Populate the properties of the specified JavaBean from the specified
* HTTP request, based on matching each parameter name (plus an optional
@@ -351,34 +326,32 @@
* argument types as described under <code>setProperties</code>.</p>
*
* <p>If you specify a non-null <code>prefix</code> and a non-null
- * <code>suffix</code>, the parameter name must match <strong>both</strong>
- * conditions for its value(s) to be used in populating bean properties.
- * If the request's content type is "multipart/form-data" and the
- * method is "POST", the <code>HttpServletRequest</code> object will be wrapped in
- * a <code>MultipartRequestWrapper</code object.</p>
- *
- * @param bean The JavaBean whose properties are to be set
- * @param prefix The prefix (if any) to be prepend to bean property
- * names when looking for matching parameters
- * @param suffix The suffix (if any) to be appended to bean property
- * names when looking for matching parameters
- * @param request The HTTP request whose parameters are to be used
- * to populate bean properties
- *
- * @exception ServletException if an exception is thrown while setting
- * property values
- */
- public static void populate(
- Object bean,
- String prefix,
- String suffix,
- HttpServletRequest request)
+ * <code>suffix</code>, the parameter name must match
+ * <strong>both</strong> conditions for its value(s) to be used in
+ * populating bean properties. If the request's content type is
+ * "multipart/form-data" and the method is "POST", the
+ * <code>HttpServletRequest</code> object will be wrapped in a
+ * <code>MultipartRequestWrapper</code object.</p>
+ *
+ * @param bean The JavaBean whose properties are to be set
+ * @param prefix The prefix (if any) to be prepend to bean property names
+ * when looking for matching parameters
+ * @param suffix The suffix (if any) to be appended to bean property
+ * names when looking for matching parameters
+ * @param request The HTTP request whose parameters are to be used to
+ * populate bean properties
+ * @throws ServletException if an exception is thrown while setting
+ * property values
+ */
+ public static void populate(Object bean, String prefix, String suffix,
+ HttpServletRequest request)
throws ServletException {
-
// Build a list of relevant request parameters from this request
HashMap properties = new HashMap();
+
// Iterator of parameter names
Enumeration names = null;
+
// Map for multipart parameters
Map multipartParameters = null;
@@ -389,23 +362,21 @@
if ((contentType != null)
&& (contentType.startsWith("multipart/form-data"))
&& (method.equalsIgnoreCase("POST"))) {
-
// Get the ActionServletWrapper from the form bean
ActionServletWrapper servlet;
+
if (bean instanceof ActionForm) {
servlet = ((ActionForm) bean).getServletWrapper();
} else {
- throw new ServletException(
- "bean that's supposed to be "
+ throw new ServletException("bean that's supposed to be "
+ "populated from a multipart request is not of type "
+ "\"org.apache.struts.action.ActionForm\", but type "
- + "\""
- + bean.getClass().getName()
- + "\"");
+ + "\"" + bean.getClass().getName() + "\"");
}
// Obtain a MultipartRequestHandler
- MultipartRequestHandler multipartHandler = getMultipartHandler(request);
+ MultipartRequestHandler multipartHandler =
+ getMultipartHandler(request);
// Set the multipart request handler for our ActionForm.
// If the bean isn't an ActionForm, an exception would have been
@@ -415,22 +386,28 @@
if (multipartHandler != null) {
isMultipart = true;
+
// Set servlet and mapping info
servlet.setServletFor(multipartHandler);
- multipartHandler.setMapping(
- (ActionMapping) request.getAttribute(Globals.MAPPING_KEY));
+ multipartHandler.setMapping((ActionMapping) request
+ .getAttribute(Globals.MAPPING_KEY));
+
// Initialize multipart request class handler
multipartHandler.handleRequest(request);
+
//stop here if the maximum length has been exceeded
- Boolean maxLengthExceeded =
- (Boolean) request.getAttribute(
- MultipartRequestHandler.ATTRIBUTE_MAX_LENGTH_EXCEEDED);
- if ((maxLengthExceeded != null) && (maxLengthExceeded.booleanValue())) {
+ Boolean maxLengthExceeded = (Boolean) request
+ .getAttribute(MultipartRequestHandler.ATTRIBUTE_MAX_LENGTH_EXCEEDED);
+
+ if ((maxLengthExceeded != null)
+ && (maxLengthExceeded.booleanValue())) {
return;
}
+
//retrieve form values and put into properties
- multipartParameters = getAllParametersForMultipartRequest(
- request, multipartHandler);
+ multipartParameters =
+ getAllParametersForMultipartRequest(request,
+ multipartHandler);
names = Collections.enumeration(multipartParameters.keySet());
}
}
@@ -442,19 +419,26 @@
while (names.hasMoreElements()) {
String name = (String) names.nextElement();
String stripped = name;
+
if (prefix != null) {
if (!stripped.startsWith(prefix)) {
continue;
}
+
stripped = stripped.substring(prefix.length());
}
+
if (suffix != null) {
if (!stripped.endsWith(suffix)) {
continue;
}
- stripped = stripped.substring(0, stripped.length() - suffix.length());
+
+ stripped = stripped.substring(0,
+ stripped.length() - suffix.length());
}
+
Object parameterValue = null;
+
if (isMultipart) {
parameterValue = multipartParameters.get(name);
} else {
@@ -471,56 +455,55 @@
// Set the corresponding properties of our bean
try {
BeanUtils.populate(bean, properties);
- } catch(Exception e) {
+ }
+ catch (Exception e) {
throw new ServletException("BeanUtils.populate", e);
}
-
}
-
/**
- * <p>Try to locate a multipart request handler for this request. First, look
- * for a mapping-specific handler stored for us under an attribute. If one
- * is not present, use the global multipart handler, if there is one.</p>
+ * <p>Try to locate a multipart request handler for this request. First,
+ * look for a mapping-specific handler stored for us under an attribute.
+ * If one is not present, use the global multipart handler, if there is
+ * one.</p>
*
* @param request The HTTP request for which the multipart handler should
* be found.
- * @return the multipart handler to use, or null if none is
- * found.
- *
- * @exception ServletException if any exception is thrown while attempting
- * to locate the multipart handler.
+ * @return the multipart handler to use, or null if none is found.
+ * @throws ServletException if any exception is thrown while attempting to
+ * locate the multipart handler.
*/
- private static MultipartRequestHandler getMultipartHandler(HttpServletRequest request)
+ private static MultipartRequestHandler getMultipartHandler(
+ HttpServletRequest request)
throws ServletException {
-
MultipartRequestHandler multipartHandler = null;
- String multipartClass = (String) request.getAttribute(Globals.MULTIPART_KEY);
+ String multipartClass =
+ (String) request.getAttribute(Globals.MULTIPART_KEY);
+
request.removeAttribute(Globals.MULTIPART_KEY);
// Try to initialize the mapping specific request handler
if (multipartClass != null) {
try {
- multipartHandler = (MultipartRequestHandler) applicationInstance(multipartClass);
- } catch(ClassNotFoundException cnfe) {
- log.error(
- "MultipartRequestHandler class \""
- + multipartClass
+ multipartHandler =
+ (MultipartRequestHandler) applicationInstance(
+ multipartClass);
+ }
+ catch (ClassNotFoundException cnfe) {
+ log.error("MultipartRequestHandler class \"" + multipartClass
+ "\" in mapping class not found, "
+ "defaulting to global multipart class");
- } catch(InstantiationException ie) {
- log.error(
- "InstantiationException when instantiating "
- + "MultipartRequestHandler \""
- + multipartClass
+ }
+ catch (InstantiationException ie) {
+ log.error("InstantiationException when instantiating "
+ + "MultipartRequestHandler \"" + multipartClass
+ "\", "
+ "defaulting to global multipart class, exception: "
+ ie.getMessage());
- } catch(IllegalAccessException iae) {
- log.error(
- "IllegalAccessException when instantiating "
- + "MultipartRequestHandler \""
- + multipartClass
+ }
+ catch (IllegalAccessException iae) {
+ log.error("IllegalAccessException when instantiating "
+ + "MultipartRequestHandler \"" + multipartClass
+ "\", "
+ "defaulting to global multipart class, exception: "
+ iae.getMessage());
@@ -534,36 +517,34 @@
ModuleConfig moduleConfig =
ModuleUtils.getInstance().getModuleConfig(request);
- multipartClass = moduleConfig.getControllerConfig().getMultipartClass();
+ multipartClass =
+ moduleConfig.getControllerConfig().getMultipartClass();
// Try to initialize the global request handler
if (multipartClass != null) {
try {
- multipartHandler = (MultipartRequestHandler) applicationInstance(multipartClass);
-
- } catch(ClassNotFoundException cnfe) {
- throw new ServletException(
- "Cannot find multipart class \""
- + multipartClass
- + "\""
- + ", exception: "
+ multipartHandler =
+ (MultipartRequestHandler) applicationInstance(
+ multipartClass);
+ }
+ catch (ClassNotFoundException cnfe) {
+ throw new ServletException("Cannot find multipart class \""
+ + multipartClass + "\"" + ", exception: "
+ cnfe.getMessage());
-
- } catch(InstantiationException ie) {
+ }
+ catch (InstantiationException ie) {
throw new ServletException(
"InstantiationException when instantiating "
- + "multipart class \""
- + multipartClass
- + "\", exception: "
- + ie.getMessage());
-
- } catch(IllegalAccessException iae) {
+ + "multipart class \"" + multipartClass
+ + "\", exception: "
+ + ie.getMessage());
+ }
+ catch (IllegalAccessException iae) {
throw new ServletException(
"IllegalAccessException when instantiating "
- + "multipart class \""
- + multipartClass
- + "\", exception: "
- + iae.getMessage());
+ + "multipart class \"" + multipartClass
+ + "\", exception: "
+ + iae.getMessage());
}
if (multipartHandler != null) {
@@ -574,35 +555,39 @@
return multipartHandler;
}
-
/**
- *<p>Create a <code>Map</code> containing all of the parameters supplied for a multipart
- * request, keyed by parameter name. In addition to text and file elements
- * from the multipart body, query string parameters are included as well.</p>
- *
- * @param request The (wrapped) HTTP request whose parameters are to be
- * added to the map.
- * @param multipartHandler The multipart handler used to parse the request.
- *
+ * <p>Create a <code>Map</code> containing all of the parameters supplied
+ * for a multipart request, keyed by parameter name. In addition to text
+ * and file elements from the multipart body, query string parameters are
+ * included as well.</p>
+ *
+ * @param request The (wrapped) HTTP request whose parameters are
+ * to be added to the map.
+ * @param multipartHandler The multipart handler used to parse the
+ * request.
* @return the map containing all parameters for this multipart request.
*/
private static Map getAllParametersForMultipartRequest(
HttpServletRequest request,
MultipartRequestHandler multipartHandler) {
-
Map parameters = new HashMap();
Hashtable elements = multipartHandler.getAllElements();
Enumeration e = elements.keys();
+
while (e.hasMoreElements()) {
String key = (String) e.nextElement();
+
parameters.put(key, elements.get(key));
}
if (request instanceof MultipartRequestWrapper) {
- request = (HttpServletRequest)((MultipartRequestWrapper)request).getRequest();
+ request = (HttpServletRequest) ((MultipartRequestWrapper) request)
+ .getRequest();
e = request.getParameterNames();
+
while (e.hasMoreElements()) {
String key = (String) e.nextElement();
+
parameters.put(key, request.getParameterValues(key));
}
} else {
@@ -612,175 +597,150 @@
return parameters;
}
-
/**
* <p>Compute the printable representation of a URL, leaving off the
- * scheme/host/port part if no host is specified. This will typically
- * be the case for URLs that were originally created from relative
- * or context-relative URIs.</p>
+ * scheme/host/port part if no host is specified. This will typically be
+ * the case for URLs that were originally created from relative or
+ * context-relative URIs.</p>
*
* @param url URL to render in a printable representation
* @return printable representation of a URL
*/
public static String printableURL(URL url) {
-
if (url.getHost() != null) {
return (url.toString());
}
String file = url.getFile();
String ref = url.getRef();
+
if (ref == null) {
return (file);
} else {
StringBuffer sb = new StringBuffer(file);
+
sb.append('#');
sb.append(ref);
+
return (sb.toString());
}
-
}
-
/**
* <p>Return the context-relative URL that corresponds to the specified
- * {@link ActionConfig}, relative to the module associated
- * with the current modules's {@link ModuleConfig}.</p>
+ * {@link ActionConfig}, relative to the module associated with the
+ * current modules's {@link ModuleConfig}.</p>
*
* @param request The servlet request we are processing
- * @param action ActionConfig to be evaluated
+ * @param action ActionConfig to be evaluated
* @param pattern URL pattern used to map the controller servlet
-
- * @return context-relative URL relative to the module
- *
+ * @return context-relative URL relative to the module
* @since Struts 1.1
*/
- public static String actionURL(
- HttpServletRequest request,
- ActionConfig action,
- String pattern) {
-
+ public static String actionURL(HttpServletRequest request,
+ ActionConfig action, String pattern) {
StringBuffer sb = new StringBuffer();
+
if (pattern.endsWith("/*")) {
sb.append(pattern.substring(0, pattern.length() - 2));
sb.append(action.getPath());
-
} else if (pattern.startsWith("*.")) {
ModuleConfig appConfig =
ModuleUtils.getInstance().getModuleConfig(request);
+
sb.append(appConfig.getPrefix());
sb.append(action.getPath());
sb.append(pattern.substring(1));
-
} else {
throw new IllegalArgumentException(pattern);
}
return sb.toString();
-
}
- /**
+
+ /**
* <p>Return the context-relative URL that corresponds to the specified
- * <code>ForwardConfig</code>. The URL is calculated based on the properties
- * of the {@link ForwardConfig} instance as follows:</p>
- * <ul>
- * <li>If the <code>contextRelative</code> property is set, it is
- * assumed that the <code>path</code> property contains a path
- * that is already context-relative:
- * <ul>
- * <li>If the <code>path</code> property value starts with a slash,
- * it is returned unmodified.</li>
- * <li>If the <code>path</code> property value does not start
- * with a slash, a slash is prepended.</li>
- * </ul></li>
- * <li>Acquire the <code>forwardPattern</code> property from the
- * <code>ControllerConfig</code> for the application module used
- * to process this request. If no pattern was configured, default
- * to a pattern of <code>$M$P</code>, which is compatible with the
- * hard-coded mapping behavior in Struts 1.0.</li>
- * <li>Process the acquired <code>forwardPattern</code>, performing the
- * following substitutions:
- * <ul>
- * <li><strong>$M</strong> - Replaced by the module prefix for the
- * application module processing this request.</li>
- * <li><strong>$P</strong> - Replaced by the <code>path</code>
- * property of the specified {@link ForwardConfig}, prepended
- * with a slash if it does not start with one.</li>
- * <li><strong>$$</strong> - Replaced by a single dollar sign
- * character.</li>
- * <li><strong>$x</strong> (where "x" is any charater not listed
- * above) - Silently omit these two characters from the result
- * value. (This has the side effect of causing all other
- * $+letter combinations to be reserved.)</li>
- * </ul></li>
- * </ul>
+ * <code>ForwardConfig</code>. The URL is calculated based on the
+ * properties of the {@link ForwardConfig} instance as follows:</p> <ul>
+ * <li>If the <code>contextRelative</code> property is set, it is assumed
+ * that the <code>path</code> property contains a path that is already
+ * context-relative: <ul> <li>If the <code>path</code> property value
+ * starts with a slash, it is returned unmodified.</li> <li>If the
+ * <code>path</code> property value does not start with a slash, a slash
+ * is prepended.</li> </ul></li> <li>Acquire the <code>forwardPattern</code>
+ * property from the <code>ControllerConfig</code> for the application
+ * module used to process this request. If no pattern was configured,
+ * default to a pattern of <code>$M$P</code>, which is compatible with the
+ * hard-coded mapping behavior in Struts 1.0.</li> <li>Process the
+ * acquired <code>forwardPattern</code>, performing the following
+ * substitutions: <ul> <li><strong>$M</strong> - Replaced by the module
+ * prefix for the application module processing this request.</li>
+ * <li><strong>$P</strong> - Replaced by the <code>path</code> property of
+ * the specified {@link ForwardConfig}, prepended with a slash if it does
+ * not start with one.</li> <li><strong>$$</strong> - Replaced by a single
+ * dollar sign character.</li> <li><strong>$x</strong> (where "x" is any
+ * charater not listed above) - Silently omit these two characters from
+ * the result value. (This has the side effect of causing all other
+ * $+letter combinations to be reserved.)</li> </ul></li> </ul>
*
* @param request The servlet request we are processing
* @param forward ForwardConfig to be evaluated
- *
* @return context-relative URL
* @since Struts 1.1
*/
- public static String forwardURL(HttpServletRequest request, ForwardConfig forward) {
- return forwardURL(request,forward,null);
+ public static String forwardURL(HttpServletRequest request,
+ ForwardConfig forward) {
+ return forwardURL(request, forward, null);
}
/**
* <p>Return the context-relative URL that corresponds to the specified
- * <code>ForwardConfig</code>. The URL is calculated based on the properties
- * of the {@link ForwardConfig} instance as follows:</p>
- * <ul>
- * <li>If the <code>contextRelative</code> property is set, it is
- * assumed that the <code>path</code> property contains a path
- * that is already context-relative:
- * <ul>
- * <li>If the <code>path</code> property value starts with a slash,
- * it is returned unmodified.</li>
- * <li>If the <code>path</code> property value does not start
- * with a slash, a slash is prepended.</li>
- * </ul></li>
- * <li>Acquire the <code>forwardPattern</code> property from the
- * <code>ControllerConfig</code> for the application module used
- * to process this request. If no pattern was configured, default
- * to a pattern of <code>$M$P</code>, which is compatible with the
- * hard-coded mapping behavior in Struts 1.0.</li>
- * <li>Process the acquired <code>forwardPattern</code>, performing the
- * following substitutions:
- * <ul>
- * <li><strong>$M</strong> - Replaced by the module prefix for the
- * application module processing this request.</li>
- * <li><strong>$P</strong> - Replaced by the <code>path</code>
- * property of the specified {@link ForwardConfig}, prepended
- * with a slash if it does not start with one.</li>
- * <li><strong>$$</strong> - Replaced by a single dollar sign
- * character.</li>
- * <li><strong>$x</strong> (where "x" is any charater not listed
- * above) - Silently omit these two characters from the result
- * value. (This has the side effect of causing all other
- * $+letter combinations to be reserved.)</li>
- * </ul></li>
- * </ul>
- *
- * @param request The servlet request we are processing
- * @param forward ForwardConfig to be evaluated
- * @param moduleConfig Base forward on this module config.
- *
+ * <code>ForwardConfig</code>. The URL is calculated based on the
+ * properties of the {@link ForwardConfig} instance as follows:</p> <ul>
+ * <li>If the <code>contextRelative</code> property is set, it is assumed
+ * that the <code>path</code> property contains a path that is already
+ * context-relative: <ul> <li>If the <code>path</code> property value
+ * starts with a slash, it is returned unmodified.</li> <li>If the
+ * <code>path</code> property value does not start with a slash, a slash
+ * is prepended.</li> </ul></li> <li>Acquire the <code>forwardPattern</code>
+ * property from the <code>ControllerConfig</code> for the application
+ * module used to process this request. If no pattern was configured,
+ * default to a pattern of <code>$M$P</code>, which is compatible with the
+ * hard-coded mapping behavior in Struts 1.0.</li> <li>Process the
+ * acquired <code>forwardPattern</code>, performing the following
+ * substitutions: <ul> <li><strong>$M</strong> - Replaced by the module
+ * prefix for the application module processing this request.</li>
+ * <li><strong>$P</strong> - Replaced by the <code>path</code> property of
+ * the specified {@link ForwardConfig}, prepended with a slash if it does
+ * not start with one.</li> <li><strong>$$</strong> - Replaced by a single
+ * dollar sign character.</li> <li><strong>$x</strong> (where "x" is any
+ * charater not listed above) - Silently omit these two characters from
+ * the result value. (This has the side effect of causing all other
+ * $+letter combinations to be reserved.)</li> </ul></li> </ul>
+ *
+ * @param request The servlet request we are processing
+ * @param forward ForwardConfig to be evaluated
+ * @param moduleConfig Base forward on this module config.
* @return context-relative URL
* @since Struts 1.2
*/
- public static String forwardURL(HttpServletRequest request, ForwardConfig forward, ModuleConfig moduleConfig) {
+ public static String forwardURL(HttpServletRequest request,
+ ForwardConfig forward,
+ ModuleConfig moduleConfig) {
//load the current moduleConfig, if null
- if(moduleConfig == null) {
+ if (moduleConfig == null) {
moduleConfig = ModuleUtils.getInstance().getModuleConfig(request);
}
String path = forward.getPath();
+
//load default prefix
String prefix = moduleConfig.getPrefix();
//override prefix if supplied by forward
- if(forward.getModule() != null) {
+ if (forward.getModule() != null) {
prefix = forward.getModule();
+
if ("/".equals(prefix)) {
prefix = "";
}
@@ -789,39 +749,54 @@
StringBuffer sb = new StringBuffer();
// Calculate a context relative path for this ForwardConfig
- String forwardPattern = moduleConfig.getControllerConfig().getForwardPattern();
+ String forwardPattern = moduleConfig.getControllerConfig()
+ .getForwardPattern();
+
if (forwardPattern == null) {
// Performance optimization for previous default behavior
sb.append(prefix);
+
// smoothly insert a '/' if needed
if (!path.startsWith("/")) {
sb.append("/");
}
- sb.append(path);
+ sb.append(path);
} else {
boolean dollar = false;
+
for (int i = 0; i < forwardPattern.length(); i++) {
char ch = forwardPattern.charAt(i);
+
if (dollar) {
switch (ch) {
case 'M':
sb.append(prefix);
+
break;
+
case 'P':
+
// add '/' if needed
if (!path.startsWith("/")) {
sb.append("/");
}
+
sb.append(path);
+
break;
+
case '$':
sb.append('$');
+
break;
- default :
+
+ default:
; // Silently swallow
}
+
dollar = false;
+
continue;
} else if (ch == '$') {
dollar = true;
@@ -832,131 +807,129 @@
}
return (sb.toString());
-
}
-
/**
* <p>Return the URL representing the current request. This is equivalent
* to <code>HttpServletRequest.getRequestURL</code> in Servlet 2.3.</p>
*
* @param request The servlet request we are processing
-
* @return URL representing the current request
- * @exception MalformedURLException if a URL cannot be created
+ * @throws MalformedURLException if a URL cannot be created
*/
- public static URL requestURL(HttpServletRequest request) throws MalformedURLException {
-
+ public static URL requestURL(HttpServletRequest request)
+ throws MalformedURLException {
StringBuffer url = requestToServerUriStringBuffer(request);
- return (new URL(url.toString()));
+ return (new URL(url.toString()));
}
-
/**
* <p>Return the URL representing the scheme, server, and port number of
* the current request. Server-relative URLs can be created by simply
* appending the server-relative path (starting with '/') to this.</p>
*
* @param request The servlet request we are processing
- *
- * @return URL representing the scheme, server, and port number of
- * the current request
- * @exception MalformedURLException if a URL cannot be created
+ * @return URL representing the scheme, server, and port number of the
+ * current request
+ * @throws MalformedURLException if a URL cannot be created
*/
- public static URL serverURL(HttpServletRequest request) throws MalformedURLException {
-
+ public static URL serverURL(HttpServletRequest request)
+ throws MalformedURLException {
StringBuffer url = requestToServerStringBuffer(request);
- return (new URL(url.toString()));
+ return (new URL(url.toString()));
}
-
/**
- * <p>Return the string representing the scheme, server, and port number of
- * the current request. Server-relative URLs can be created by simply
+ * <p>Return the string representing the scheme, server, and port number
+ * of the current request. Server-relative URLs can be created by simply
* appending the server-relative path (starting with '/') to this.</p>
*
* @param request The servlet request we are processing
-
- * @return URL representing the scheme, server, and port number of
- * the current request
+ * @return URL representing the scheme, server, and port number of the
+ * current request
* @since Struts 1.2.0
*/
- public static StringBuffer requestToServerUriStringBuffer(HttpServletRequest request) {
+ public static StringBuffer requestToServerUriStringBuffer(
+ HttpServletRequest request) {
+ StringBuffer serverUri =
+ createServerUriStringBuffer(request.getScheme(),
+ request.getServerName(), request.getServerPort(),
+ request.getRequestURI());
- StringBuffer serverUri = createServerUriStringBuffer(request.getScheme(),request.getServerName(),
- request.getServerPort(),request.getRequestURI());
return serverUri;
-
}
/**
- * <p>Return <code>StringBuffer</code> representing the scheme, server, and port number of
- * the current request. Server-relative URLs can be created by simply
- * appending the server-relative path (starting with '/') to this.</p>
+ * <p>Return <code>StringBuffer</code> representing the scheme, server,
+ * and port number of the current request. Server-relative URLs can be
+ * created by simply appending the server-relative path (starting with
+ * '/') to this.</p>
*
* @param request The servlet request we are processing
- *
- * @return URL representing the scheme, server, and port number of
- * the current request
+ * @return URL representing the scheme, server, and port number of the
+ * current request
* @since Struts 1.2.0
*/
- public static StringBuffer requestToServerStringBuffer(HttpServletRequest request) {
-
- return createServerStringBuffer(request.getScheme(),request.getServerName(),request.getServerPort());
-
+ public static StringBuffer requestToServerStringBuffer(
+ HttpServletRequest request) {
+ return createServerStringBuffer(request.getScheme(),
+ request.getServerName(), request.getServerPort());
}
-
/**
- * <p>Return <code>StringBuffer</code> representing the scheme, server, and port number of
- * the current request.</p>
+ * <p>Return <code>StringBuffer</code> representing the scheme, server,
+ * and port number of the current request.</p>
*
* @param scheme The scheme name to use
* @param server The server name to use
- * @param port The port value to use
- *
+ * @param port The port value to use
* @return StringBuffer in the form scheme: server: port
* @since Struts 1.2.0
*/
- public static StringBuffer createServerStringBuffer(String scheme,String server,int port) {
-
+ public static StringBuffer createServerStringBuffer(String scheme,
+ String server,
+ int port) {
StringBuffer url = new StringBuffer();
+
if (port < 0) {
port = 80; // Work around java.net.URL bug
}
+
url.append(scheme);
url.append("://");
url.append(server);
- if ((scheme.equals("http") && (port != 80)) || (scheme.equals("https") && (port != 443))) {
+
+ if ((scheme.equals("http") && (port != 80))
+ || (scheme.equals("https") && (port != 443))) {
url.append(':');
url.append(port);
}
- return url;
+ return url;
}
-
/**
- * <p>Return <code>StringBuffer</code> representing the scheme, server, and port number of
- * the current request.</p>
+ * <p>Return <code>StringBuffer</code> representing the scheme, server,
+ * and port number of the current request.</p>
*
* @param scheme The scheme name to use
* @param server The server name to use
- * @param port The port value to use
- * @param uri The uri value to use
- *
+ * @param port The port value to use
+ * @param uri The uri value to use
* @return StringBuffer in the form scheme: server: port
* @since Struts 1.2.0
*/
- public static StringBuffer createServerUriStringBuffer(String scheme,String server,int port,String uri) {
+ public static StringBuffer createServerUriStringBuffer(String scheme,
+ String server,
+ int port,
+ String uri) {
+ StringBuffer serverUri =
+ createServerStringBuffer(scheme, server, port);
- StringBuffer serverUri = createServerStringBuffer(scheme,server,port);
serverUri.append(uri);
- return serverUri;
+ return serverUri;
}
-
-
}
Modified: struts/action/trunk/src/java/org/apache/struts/util/ResponseUtils.java
URL: http://svn.apache.org/viewcvs/struts/action/trunk/src/java/org/apache/struts/util/ResponseUtils.java?rev=370938&r1=370937&r2=370938&view=diff
==============================================================================
--- struts/action/trunk/src/java/org/apache/struts/util/ResponseUtils.java (original)
+++ struts/action/trunk/src/java/org/apache/struts/util/ResponseUtils.java Fri Jan 20 16:19:02 2006
@@ -15,108 +15,114 @@
* See the License for the specific language governing permissions and
* limitations under the License.
*/
-
package org.apache.struts.util;
+import org.apache.commons.logging.Log;
+import org.apache.commons.logging.LogFactory;
+
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.net.URLEncoder;
-import org.apache.commons.logging.Log;
-import org.apache.commons.logging.LogFactory;
-
/**
- * General purpose utility methods related to generating a servlet response
- * in the Struts controller framework.
+ * General purpose utility methods related to generating a servlet response in
+ * the Struts controller framework.
*
- * @version $Rev$ $Date$
+ * @version $Rev$ $Date: 2005-08-21 14:46:28 -0400 (Sun, 21 Aug 2005)
+ * $
*/
public class ResponseUtils {
-
- // ------------------------------------------------------- Static Variables
-
+ // ------------------------------------------------------- Static Variables
/**
* The message resources for this package.
*/
- protected static MessageResources messages =
- MessageResources.getMessageResources
- ("org.apache.struts.util.LocalStrings");
+ protected static MessageResources messages = MessageResources
+ .getMessageResources("org.apache.struts.util.LocalStrings");
/**
* Java 1.4 encode method to use instead of deprecated 1.3 version.
*/
private static Method encode = null;
-
/**
* Commons logging instance.
*/
private static final Log log = LogFactory.getLog(ResponseUtils.class);
-
-
/**
* Initialize the encode variable with the
* Java 1.4 method if available.
*/
static {
-
try {
// get version of encode method with two String args
- Class[] args = new Class[] {String.class, String.class};
+ Class[] args = new Class[]{String.class, String.class};
+
encode = URLEncoder.class.getMethod("encode", args);
- } catch (NoSuchMethodException e) {
- log.debug("Could not find Java 1.4 encode method. Using deprecated version.", e);
+ }
+ catch (NoSuchMethodException e) {
+ log.debug(
+ "Could not find Java 1.4 encode method. Using deprecated version.",
+ e);
}
}
-
-
- // --------------------------------------------------------- Public Methods
-
+ // --------------------------------------------------------- Public Methods
/**
- * Filter the specified string for characters that are senstive to
- * HTML interpreters, returning the string with these characters replaced
- * by the corresponding character entities.
+ * Filter the specified string for characters that are senstive to HTML
+ * interpreters, returning the string with these characters replaced by
+ * the corresponding character entities.
*
* @param value The string to be filtered and returned
*/
public static String filter(String value) {
-
- if (value == null || value.length() == 0) {
+ if ((value == null) || (value.length() == 0)) {
return value;
}
StringBuffer result = null;
String filtered = null;
+
for (int i = 0; i < value.length(); i++) {
filtered = null;
+
switch (value.charAt(i)) {
case '<':
filtered = "<";
+
break;
+
case '>':
filtered = ">";
+
break;
+
case '&':
filtered = "&";
+
break;
+
case '"':
filtered = """;
+
break;
+
case '\'':
filtered = "'";
+
break;
}
if (result == null) {
if (filtered != null) {
result = new StringBuffer(value.length() + 50);
+
if (i > 0) {
result.append(value.substring(0, i));
}
+
result.append(filtered);
}
} else {
@@ -128,10 +134,9 @@
}
}
- return result == null ? value : result.toString();
+ return (result == null) ? value : result.toString();
}
-
/**
* URLencodes a string assuming the character encoding is UTF-8.
*
@@ -144,32 +149,36 @@
/**
* Use the new URLEncoder.encode() method from Java 1.4 if available, else
- * use the old deprecated version. This method uses reflection to find the
- * appropriate method; if the reflection operations throw exceptions, this
- * will return the url encoded with the old URLEncoder.encode() method.
+ * use the old deprecated version. This method uses reflection to find
+ * the appropriate method; if the reflection operations throw exceptions,
+ * this will return the url encoded with the old URLEncoder.encode()
+ * method.
+ *
* @param enc The character encoding the urlencode is performed on.
* @return String The encoded url.
*/
public static String encodeURL(String url, String enc) {
try {
-
- if(enc==null || enc.length()==0) {
+ if ((enc == null) || (enc.length() == 0)) {
enc = "UTF-8";
}
// encode url with new 1.4 method and UTF-8 encoding
if (encode != null) {
- return (String) encode.invoke(null, new Object[] {url, enc});
+ return (String) encode.invoke(null, new Object[]{url, enc});
}
-
- } catch (IllegalAccessException e) {
- log.debug("Could not find Java 1.4 encode method. Using deprecated version.", e);
- } catch (InvocationTargetException e) {
- log.debug("Could not find Java 1.4 encode method. Using deprecated version.", e);
+ }
+ catch (IllegalAccessException e) {
+ log.debug(
+ "Could not find Java 1.4 encode method. Using deprecated version.",
+ e);
+ }
+ catch (InvocationTargetException e) {
+ log.debug(
+ "Could not find Java 1.4 encode method. Using deprecated version.",
+ e);
}
return URLEncoder.encode(url);
}
-
-
}
Modified: struts/action/trunk/src/java/org/apache/struts/util/ServletContextWriter.java
URL: http://svn.apache.org/viewcvs/struts/action/trunk/src/java/org/apache/struts/util/ServletContextWriter.java?rev=370938&r1=370937&r2=370938&view=diff
==============================================================================
--- struts/action/trunk/src/java/org/apache/struts/util/ServletContextWriter.java (original)
+++ struts/action/trunk/src/java/org/apache/struts/util/ServletContextWriter.java Fri Jan 20 16:19:02 2006
@@ -15,12 +15,11 @@
* See the License for the specific language governing permissions and
* limitations under the License.
*/
-
package org.apache.struts.util;
+import javax.servlet.ServletContext;
import java.io.PrintWriter;
import java.io.StringWriter;
-import javax.servlet.ServletContext;
/**
* A PrintWriter implementation that uses the logging facilities of a
@@ -29,51 +28,41 @@
* is called, or until one of the <code>println()</code> methods is called.
* Along the way, carriage return characters are skipped.
*
- * @version $Rev$ $Date$
+ * @version $Rev$ $Date: 2005-05-07 12:11:38 -0400 (Sat, 07 May 2005)
+ * $
*/
public class ServletContextWriter extends PrintWriter {
-
-
- // ----------------------------------------------------------- Constructors
-
-
- /**
- * Construct a ServletContextWriter associated with the specified
- * ServletContext instance.
- *
- * @param context The associated servlet context
- */
- public ServletContextWriter(ServletContext context) {
-
- super(new StringWriter());
- this.context = context;
-
- }
-
-
// ------------------------------------------------------------- Properties
-
/**
* The buffer into which we accumulate lines to be logged.
*/
protected StringBuffer buffer = new StringBuffer();
-
/**
* The servlet context with which we are associated.
*/
protected ServletContext context = null;
-
/**
* The error state for this stream.
*/
protected boolean error = false;
+ // ----------------------------------------------------------- Constructors
- // --------------------------------------------------------- Public Methods
+ /**
+ * Construct a ServletContextWriter associated with the specified
+ * ServletContext instance.
+ *
+ * @param context The associated servlet context
+ */
+ public ServletContextWriter(ServletContext context) {
+ super(new StringWriter());
+ this.context = context;
+ }
+ // --------------------------------------------------------- Public Methods
/**
* Flush the stream and check for its error state. <strong>IMPLEMENTATION
@@ -82,321 +71,254 @@
* <code>true</code> is if <code>setError()</code> is called.
*/
public boolean checkError() {
-
flush();
- return (error);
+ return (error);
}
-
/**
* Close the stream.
*/
public void close() {
-
flush();
-
}
-
/**
* Flush the stream.
*/
public void flush() {
-
if (buffer.length() > 0) {
context.log(buffer.toString());
buffer.setLength(0);
}
-
}
-
/**
* Print a boolean value.
*
* @param b The value to be printed
*/
public void print(boolean b) {
-
write(String.valueOf(b));
-
}
-
/**
* Print a character value.
*
* @param c The value to be printed
*/
public void print(char c) {
-
write(c);
-
}
-
/**
* Print a character array.
*
* @param c The character array to be printed
*/
- public void print(char c[]) {
-
- for (int i = 0; i < c.length; i++)
+ public void print(char[] c) {
+ for (int i = 0; i < c.length; i++) {
write(c[i]);
-
+ }
}
-
/**
* Print a double value.
*
* @param d The value to be printed
*/
public void print(double d) {
-
write(String.valueOf(d));
-
}
-
/**
* Print a float value.
*
* @param f The value to be printed
*/
public void print(float f) {
-
write(String.valueOf(f));
-
}
-
/**
* Print an integer value.
*
* @param i The value to be printed
*/
public void print(int i) {
-
write(String.valueOf(i));
-
}
-
/**
* Print a long value.
*
* @param l The value to be printed
*/
public void print(long l) {
-
write(String.valueOf(l));
-
}
-
/**
* Print an object.
*
* @param o The value to be printed
*/
public void print(Object o) {
-
write(o.toString());
-
}
-
/**
* Print a String value.
*
* @param s The value to be printed
*/
public void print(String s) {
-
int len = s.length();
- for (int i = 0; i < len; i++)
- write(s.charAt(i));
+ for (int i = 0; i < len; i++) {
+ write(s.charAt(i));
+ }
}
-
/**
* Terminate the current line and flush the buffer.
*/
public void println() {
-
flush();
-
}
-
/**
* Print a boolean value and terminate the line.
*
* @param b The value to be printed
*/
public void println(boolean b) {
-
println(String.valueOf(b));
-
}
-
/**
* Print a character value and terminate the line.
*
* @param c The value to be printed
*/
public void println(char c) {
-
write(c);
println();
-
}
-
/**
* Print a character array and terminate the line.
*
* @param c The character array to be printed
*/
- public void println(char c[]) {
-
- for (int i = 0; i < c.length; i++)
+ public void println(char[] c) {
+ for (int i = 0; i < c.length; i++) {
print(c[i]);
- println();
+ }
+ println();
}
-
/**
* Print a double value and terminate the line.
*
* @param d The value to be printed
*/
public void println(double d) {
-
println(String.valueOf(d));
-
}
-
/**
* Print a float value and terminate the line.
*
* @param f The value to be printed
*/
public void println(float f) {
-
println(String.valueOf(f));
-
}
-
/**
* Print an integer value and terminate the line.
*
* @param i The value to be printed
*/
public void println(int i) {
-
println(String.valueOf(i));
-
}
-
/**
* Print a long value and terminate the line.
*
* @param l The value to be printed
*/
public void println(long l) {
-
println(String.valueOf(l));
-
}
-
/**
* Print an object and terminate the line.
*
* @param o The value to be printed
*/
public void println(Object o) {
-
println(o.toString());
-
}
-
/**
* Print a String value and terminate the line.
*
* @param s The value to be printed
*/
public void println(String s) {
-
int len = s.length();
- for (int i = 0; i < len; i++)
+
+ for (int i = 0; i < len; i++) {
print(s.charAt(i));
- println();
+ }
+ println();
}
-
/**
* Set the error state for this stream.
*/
public void setError() {
-
this.error = true;
-
}
-
/**
* Write a single character to this stream.
*
* @param c The character to be written
*/
public void write(char c) {
-
- if (c == '\n')
+ if (c == '\n') {
flush();
- else if (c != '\r')
+ } else if (c != '\r') {
buffer.append(c);
-
+ }
}
-
/**
* Write a single character to this stream.
*
* @param c The character to be written
*/
public void write(int c) {
-
write((char) c);
-
}
-
/**
* Write an array of charaters to this stream.
*
* @param buf The character array to be written
*/
- public void write(char buf[]) {
-
- for (int i = 0; i < buf.length; i++)
+ public void write(char[] buf) {
+ for (int i = 0; i < buf.length; i++) {
write(buf[i]);
-
+ }
}
-
/**
* Write the specified subset of an array of characters to this stream.
*
@@ -404,41 +326,35 @@
* @param off The zero-relative starting offset to write
* @param len The number of characters to write
*/
- public void write(char buf[], int off, int len) {
-
- for (int i = off; i < len; i++)
+ public void write(char[] buf, int off, int len) {
+ for (int i = off; i < len; i++) {
write(buf[i]);
-
+ }
}
-
/**
* Write a String to this stream.
*
* @param s The string to be written
*/
public void write(String s) {
-
int len = s.length();
- for (int i = 0; i < len; i++)
- write(s.charAt(i));
+ for (int i = 0; i < len; i++) {
+ write(s.charAt(i));
+ }
}
-
/**
* Write the specified portion of a String to this stream.
*
- * @param s The String from which to write
+ * @param s The String from which to write
* @param off The zero-relative starting offset to write
* @param len The number of characters to write
*/
public void write(String s, int off, int len) {
-
- for (int i = off; i < len; i++)
+ for (int i = off; i < len; i++) {
write(s.charAt(i));
-
+ }
}
-
-
}
Modified: struts/action/trunk/src/java/org/apache/struts/util/TokenProcessor.java
URL: http://svn.apache.org/viewcvs/struts/action/trunk/src/java/org/apache/struts/util/TokenProcessor.java?rev=370938&r1=370937&r2=370938&view=diff
==============================================================================
--- struts/action/trunk/src/java/org/apache/struts/util/TokenProcessor.java (original)
+++ struts/action/trunk/src/java/org/apache/struts/util/TokenProcessor.java Fri Jan 20 16:19:02 2006
@@ -15,39 +15,34 @@
* See the License for the specific language governing permissions and
* limitations under the License.
*/
-
package org.apache.struts.util;
-import java.security.MessageDigest;
-import java.security.NoSuchAlgorithmException;
+import org.apache.struts.Globals;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
-
-import org.apache.struts.Globals;
+import java.security.MessageDigest;
+import java.security.NoSuchAlgorithmException;
/**
- * TokenProcessor is responsible for handling all token related functionality. The
- * methods in this class are synchronized to protect token processing from multiple
- * threads. Servlet containers are allowed to return a different HttpSession object
- * for two threads accessing the same session so it is not possible to synchronize
- * on the session.
+ * TokenProcessor is responsible for handling all token related functionality.
+ * The methods in this class are synchronized to protect token processing from
+ * multiple threads. Servlet containers are allowed to return a different
+ * HttpSession object for two threads accessing the same session so it is not
+ * possible to synchronize on the session.
*
* @since Struts 1.1
*/
public class TokenProcessor {
-
/**
* The singleton instance of this class.
*/
private static TokenProcessor instance = new TokenProcessor();
/**
- * Retrieves the singleton instance of this class.
+ * The timestamp used most recently to generate a token value.
*/
- public static TokenProcessor getInstance() {
- return instance;
- }
+ private long previous;
/**
* Protected constructor for TokenProcessor. Use TokenProcessor.getInstance()
@@ -58,22 +53,21 @@
}
/**
- * The timestamp used most recently to generate a token value.
+ * Retrieves the singleton instance of this class.
*/
- private long previous;
+ public static TokenProcessor getInstance() {
+ return instance;
+ }
/**
- * Return <code>true</code> if there is a transaction token stored in
- * the user's current session, and the value submitted as a request
- * parameter with this action matches it. Returns <code>false</code>
- * under any of the following circumstances:
- * <ul>
- * <li>No session associated with this request</li>
- * <li>No transaction token saved in the session</li>
- * <li>No transaction token included as a request parameter</li>
- * <li>The included transaction token value does not match the
- * transaction token in the user's session</li>
- * </ul>
+ * Return <code>true</code> if there is a transaction token stored in the
+ * user's current session, and the value submitted as a request parameter
+ * with this action matches it. Returns <code>false</code> under any of
+ * the following circumstances: <ul> <li>No session associated with this
+ * request</li> <li>No transaction token saved in the session</li> <li>No
+ * transaction token included as a request parameter</li> <li>The included
+ * transaction token value does not match the transaction token in the
+ * user's session</li> </ul>
*
* @param request The servlet request we are processing
*/
@@ -82,33 +76,31 @@
}
/**
- * Return <code>true</code> if there is a transaction token stored in
- * the user's current session, and the value submitted as a request
- * parameter with this action matches it. Returns <code>false</code>
- * <ul>
- * <li>No session associated with this request</li>
- * <li>No transaction token saved in the session</li>
- * <li>No transaction token included as a request parameter</li>
- * <li>The included transaction token value does not match the
- * transaction token in the user's session</li>
- * </ul>
+ * Return <code>true</code> if there is a transaction token stored in the
+ * user's current session, and the value submitted as a request parameter
+ * with this action matches it. Returns <code>false</code> <ul> <li>No
+ * session associated with this request</li> <li>No transaction token
+ * saved in the session</li> <li>No transaction token included as a
+ * request parameter</li> <li>The included transaction token value does
+ * not match the transaction token in the user's session</li> </ul>
*
* @param request The servlet request we are processing
- * @param reset Should we reset the token after checking it?
+ * @param reset Should we reset the token after checking it?
*/
- public synchronized boolean isTokenValid(
- HttpServletRequest request,
- boolean reset) {
-
+ public synchronized boolean isTokenValid(HttpServletRequest request,
+ boolean reset) {
// Retrieve the current session for this request
HttpSession session = request.getSession(false);
+
if (session == null) {
return false;
}
// Retrieve the transaction token from this session, and
// reset it if requested
- String saved = (String) session.getAttribute(Globals.TRANSACTION_TOKEN_KEY);
+ String saved =
+ (String) session.getAttribute(Globals.TRANSACTION_TOKEN_KEY);
+
if (saved == null) {
return false;
}
@@ -119,6 +111,7 @@
// Retrieve the transaction token included in this request
String token = request.getParameter(Globals.TOKEN_KEY);
+
if (token == null) {
return false;
}
@@ -128,34 +121,34 @@
/**
* Reset the saved transaction token in the user's session. This
- * indicates that transactional token checking will not be needed
- * on the next request that is submitted.
+ * indicates that transactional token checking will not be needed on the
+ * next request that is submitted.
*
* @param request The servlet request we are processing
*/
public synchronized void resetToken(HttpServletRequest request) {
-
HttpSession session = request.getSession(false);
+
if (session == null) {
return;
}
+
session.removeAttribute(Globals.TRANSACTION_TOKEN_KEY);
}
/**
- * Save a new transaction token in the user's current session, creating
- * a new session if necessary.
+ * Save a new transaction token in the user's current session, creating a
+ * new session if necessary.
*
* @param request The servlet request we are processing
*/
public synchronized void saveToken(HttpServletRequest request) {
-
HttpSession session = request.getSession();
String token = generateToken(request);
+
if (token != null) {
session.setAttribute(Globals.TRANSACTION_TOKEN_KEY, token);
}
-
}
/**
@@ -165,49 +158,54 @@
* @param request The request we are processing
*/
public synchronized String generateToken(HttpServletRequest request) {
-
HttpSession session = request.getSession();
- return generateToken(session.getId());
+ return generateToken(session.getId());
}
/**
* Generate a new transaction token, to be used for enforcing a single
* request for a particular transaction.
*
- * @param id a unique Identifier for the session or other context in
- * which this token is to be used.
+ * @param id a unique Identifier for the session or other context in which
+ * this token is to be used.
*/
public synchronized String generateToken(String id) {
-
try {
long current = System.currentTimeMillis();
+
if (current == previous) {
current++;
}
+
previous = current;
- byte now[] = new Long(current).toString().getBytes();
+
+ byte[] now = new Long(current).toString().getBytes();
MessageDigest md = MessageDigest.getInstance("MD5");
+
md.update(id.getBytes());
md.update(now);
+
return toHex(md.digest());
- } catch (NoSuchAlgorithmException e) {
+ }
+ catch (NoSuchAlgorithmException e) {
return null;
}
-
}
/**
* Convert a byte array to a String of hexadecimal digits and return it.
+ *
* @param buffer The byte array to be converted
*/
- private String toHex(byte buffer[]) {
+ private String toHex(byte[] buffer) {
StringBuffer sb = new StringBuffer(buffer.length * 2);
+
for (int i = 0; i < buffer.length; i++) {
sb.append(Character.forDigit((buffer[i] & 0xf0) >> 4, 16));
sb.append(Character.forDigit(buffer[i] & 0x0f, 16));
}
+
return sb.toString();
}
-
}
---------------------------------------------------------------------
To unsubscribe, e-mail: dev-unsubscribe@struts.apache.org
For additional commands, e-mail: dev-help@struts.apache.org