first commit

This commit is contained in:
2025-07-28 13:56:49 +05:30
commit e9eb805edb
3438 changed files with 520990 additions and 0 deletions

View File

@@ -0,0 +1,169 @@
package org.apache.struts.action;
import java.io.IOException;
import java.util.Locale;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import javax.sql.DataSource;
import org.apache.struts.config.ModuleConfig;
import org.apache.struts.util.MessageResources;
import org.apache.struts.util.RequestUtils;
import org.apache.struts.util.TokenProcessor;
public class Action {
public static final String ACTION_SERVLET_KEY = "org.apache.struts.action.ACTION_SERVLET";
public static final String APPLICATION_KEY = "org.apache.struts.action.MODULE";
public static final String DATA_SOURCE_KEY = "org.apache.struts.action.DATA_SOURCE";
public static final String ERROR_KEY = "org.apache.struts.action.ERROR";
public static final String EXCEPTION_KEY = "org.apache.struts.action.EXCEPTION";
public static final String FORM_BEANS_KEY = "org.apache.struts.action.FORM_BEANS";
public static final String FORWARDS_KEY = "org.apache.struts.action.FORWARDS";
public static final String LOCALE_KEY = "org.apache.struts.action.LOCALE";
public static final String MAPPING_KEY = "org.apache.struts.action.mapping.instance";
public static final String MAPPINGS_KEY = "org.apache.struts.action.MAPPINGS";
public static final String MESSAGE_KEY = "org.apache.struts.action.ACTION_MESSAGE";
public static final String MESSAGES_KEY = "org.apache.struts.action.MESSAGE";
public static final String MULTIPART_KEY = "org.apache.struts.action.mapping.multipartclass";
public static final String PLUG_INS_KEY = "org.apache.struts.action.PLUG_INS";
public static final String REQUEST_PROCESSOR_KEY = "org.apache.struts.action.REQUEST_PROCESSOR";
public static final String SERVLET_KEY = "org.apache.struts.action.SERVLET_MAPPING";
public static final String TRANSACTION_TOKEN_KEY = "org.apache.struts.action.TOKEN";
private static TokenProcessor token = TokenProcessor.getInstance();
protected static Locale defaultLocale = Locale.getDefault();
protected ActionServlet servlet = null;
public ActionServlet getServlet() {
return this.servlet;
}
public void setServlet(ActionServlet servlet) {
this.servlet = servlet;
}
public ActionForward execute(ActionMapping mapping, ActionForm form, ServletRequest request, ServletResponse response) throws Exception {
return perform(mapping, form, request, response);
}
public ActionForward execute(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws Exception {
return perform(mapping, form, request, response);
}
public ActionForward perform(ActionMapping mapping, ActionForm form, ServletRequest request, ServletResponse response) throws IOException, ServletException {
try {
return perform(mapping, form, (HttpServletRequest)request, (HttpServletResponse)response);
} catch (ClassCastException e) {
return null;
}
}
public ActionForward perform(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException {
return null;
}
protected String generateToken(HttpServletRequest request) {
return token.generateToken(request);
}
protected DataSource getDataSource(HttpServletRequest request) {
return getDataSource(request, "org.apache.struts.action.DATA_SOURCE");
}
protected DataSource getDataSource(HttpServletRequest request, String key) {
ServletContext context = getServlet().getServletContext();
ModuleConfig moduleConfig = RequestUtils.getModuleConfig(request, context);
return (DataSource)context.getAttribute(key + moduleConfig.getPrefix());
}
protected Locale getLocale(HttpServletRequest request) {
HttpSession session = request.getSession();
Locale locale = (Locale)session.getAttribute("org.apache.struts.action.LOCALE");
if (locale == null)
locale = defaultLocale;
return locale;
}
protected MessageResources getResources() {
return (MessageResources)this.servlet.getServletContext().getAttribute("org.apache.struts.action.MESSAGE");
}
protected MessageResources getResources(HttpServletRequest request) {
return (MessageResources)request.getAttribute("org.apache.struts.action.MESSAGE");
}
protected MessageResources getResources(HttpServletRequest request, String key) {
ServletContext context = getServlet().getServletContext();
ModuleConfig moduleConfig = RequestUtils.getModuleConfig(request, context);
return (MessageResources)context.getAttribute(key + moduleConfig.getPrefix());
}
protected boolean isCancelled(HttpServletRequest request) {
return (request.getAttribute("org.apache.struts.action.CANCEL") != null);
}
protected boolean isTokenValid(HttpServletRequest request) {
return token.isTokenValid(request, false);
}
protected boolean isTokenValid(HttpServletRequest request, boolean reset) {
return token.isTokenValid(request, reset);
}
protected void resetToken(HttpServletRequest request) {
token.resetToken(request);
}
protected void saveErrors(HttpServletRequest request, ActionErrors errors) {
if (errors == null || errors.isEmpty()) {
request.removeAttribute("org.apache.struts.action.ERROR");
return;
}
request.setAttribute("org.apache.struts.action.ERROR", errors);
}
protected void saveMessages(HttpServletRequest request, ActionMessages messages) {
if (messages == null || messages.isEmpty()) {
request.removeAttribute("org.apache.struts.action.ACTION_MESSAGE");
return;
}
request.setAttribute("org.apache.struts.action.ACTION_MESSAGE", messages);
}
protected void saveToken(HttpServletRequest request) {
token.saveToken(request);
}
protected void setLocale(HttpServletRequest request, Locale locale) {
HttpSession session = request.getSession();
if (locale == null)
locale = defaultLocale;
session.setAttribute("org.apache.struts.action.LOCALE", locale);
}
protected String toHex(byte[] buffer) {
return token.toHex(buffer);
}
}

View File

@@ -0,0 +1,29 @@
package org.apache.struts.action;
import java.io.Serializable;
public class ActionError extends ActionMessage implements Serializable {
public ActionError(String key) {
super(key);
}
public ActionError(String key, Object value0) {
super(key, value0);
}
public ActionError(String key, Object value0, Object value1) {
super(key, value0, value1);
}
public ActionError(String key, Object value0, Object value1, Object value2) {
super(key, value0, value1, value2);
}
public ActionError(String key, Object value0, Object value1, Object value2, Object value3) {
super(key, value0, value1, value2, value3);
}
public ActionError(String key, Object[] values) {
super(key, values);
}
}

View File

@@ -0,0 +1,17 @@
package org.apache.struts.action;
import java.io.Serializable;
public class ActionErrors extends ActionMessages implements Serializable {
public static final String GLOBAL_ERROR = "org.apache.struts.action.GLOBAL_ERROR";
public ActionErrors() {}
public ActionErrors(ActionErrors messages) {
super(messages);
}
public void add(String property, ActionError error) {
add(property, error);
}
}

View File

@@ -0,0 +1,52 @@
package org.apache.struts.action;
import java.io.Serializable;
import javax.servlet.ServletRequest;
import javax.servlet.http.HttpServletRequest;
import org.apache.struts.upload.MultipartRequestHandler;
public abstract class ActionForm implements Serializable {
protected transient ActionServlet servlet = null;
protected transient MultipartRequestHandler multipartRequestHandler;
protected ActionServlet getServlet() {
return this.servlet;
}
public ActionServletWrapper getServletWrapper() {
return new ActionServletWrapper(getServlet());
}
public MultipartRequestHandler getMultipartRequestHandler() {
return this.multipartRequestHandler;
}
public void setServlet(ActionServlet servlet) {
this.servlet = servlet;
}
public void setMultipartRequestHandler(MultipartRequestHandler multipartRequestHandler) {
this.multipartRequestHandler = multipartRequestHandler;
}
public void reset(ActionMapping mapping, ServletRequest request) {
try {
reset(mapping, (HttpServletRequest)request);
} catch (ClassCastException e) {}
}
public void reset(ActionMapping mapping, HttpServletRequest request) {}
public ActionErrors validate(ActionMapping mapping, ServletRequest request) {
try {
return validate(mapping, (HttpServletRequest)request);
} catch (ClassCastException e) {
return null;
}
}
public ActionErrors validate(ActionMapping mapping, HttpServletRequest request) {
return null;
}
}

View File

@@ -0,0 +1,12 @@
package org.apache.struts.action;
import org.apache.struts.config.FormBeanConfig;
public class ActionFormBean extends FormBeanConfig {
public ActionFormBean() {}
public ActionFormBean(String name, String type) {
setName(name);
setType(type);
}
}

View File

@@ -0,0 +1,32 @@
package org.apache.struts.action;
import java.io.Serializable;
import org.apache.commons.collections.FastHashMap;
public class ActionFormBeans implements Serializable {
protected FastHashMap formBeans = new FastHashMap();
public boolean getFast() {
return this.formBeans.getFast();
}
public void setFast(boolean fast) {
this.formBeans.setFast(fast);
}
public void addFormBean(ActionFormBean formBean) {
this.formBeans.put(formBean.getName(), formBean);
}
public ActionFormBean findFormBean(String name) {
return (ActionFormBean)this.formBeans.get(name);
}
public String[] findFormBeans() {
return (String[])this.formBeans.keySet().toArray((Object[])new String[this.formBeans.size()]);
}
public void removeFormBean(ActionFormBean formBean) {
this.formBeans.remove(formBean.getName());
}
}

View File

@@ -0,0 +1,32 @@
package org.apache.struts.action;
import org.apache.struts.config.ForwardConfig;
public class ActionForward extends ForwardConfig {
public ActionForward() {
this((String)null, false);
}
public ActionForward(String path) {
this(path, false);
}
public ActionForward(String path, boolean redirect) {
setName(null);
setPath(path);
setRedirect(redirect);
}
public ActionForward(String name, String path, boolean redirect) {
setName(name);
setPath(path);
setRedirect(redirect);
}
public ActionForward(String name, String path, boolean redirect, boolean contextRelative) {
setName(name);
setPath(path);
setRedirect(redirect);
setContextRelative(contextRelative);
}
}

View File

@@ -0,0 +1,32 @@
package org.apache.struts.action;
import java.io.Serializable;
import org.apache.commons.collections.FastHashMap;
public class ActionForwards implements Serializable {
private FastHashMap forwards = new FastHashMap();
public boolean getFast() {
return this.forwards.getFast();
}
public void setFast(boolean fast) {
this.forwards.setFast(fast);
}
public void addForward(ActionForward forward) {
this.forwards.put(forward.getName(), forward);
}
public ActionForward findForward(String name) {
return (ActionForward)this.forwards.get(name);
}
public String[] findForwards() {
return (String[])this.forwards.keySet().toArray((Object[])new String[this.forwards.size()]);
}
public void removeForward(ActionForward forward) {
this.forwards.remove(forward.getName());
}
}

View File

@@ -0,0 +1,44 @@
package org.apache.struts.action;
import java.util.ArrayList;
import org.apache.struts.config.ActionConfig;
import org.apache.struts.config.ExceptionConfig;
import org.apache.struts.config.ForwardConfig;
public class ActionMapping extends ActionConfig {
public ExceptionConfig findException(Class type) {
ExceptionConfig config = null;
do {
String name = type.getName();
config = findExceptionConfig(name);
if (config != null)
return config;
config = getModuleConfig().findExceptionConfig(name);
if (config != null)
return config;
type = type.getSuperclass();
} while (type != null);
return null;
}
public ActionForward findForward(String name) {
ForwardConfig config = findForwardConfig(name);
if (config == null)
config = getModuleConfig().findForwardConfig(name);
return (ActionForward)config;
}
public String[] findForwards() {
ArrayList results = new ArrayList();
ForwardConfig[] fcs = findForwardConfigs();
for (int i = 0; i < fcs.length; i++)
results.add(fcs[i].getName());
return results.<String>toArray(new String[results.size()]);
}
public ActionForward getInputForward() {
if (getModuleConfig().getControllerConfig().getInputForward())
return findForward(getInput());
return new ActionForward(getInput());
}
}

View File

@@ -0,0 +1,64 @@
package org.apache.struts.action;
import java.io.Serializable;
import javax.servlet.ServletRequest;
import javax.servlet.http.HttpServletRequest;
import org.apache.commons.collections.FastHashMap;
public class ActionMappings implements Serializable {
protected FastHashMap mappings = new FastHashMap();
protected transient ActionServlet servlet = null;
protected ActionMapping unknown = null;
public boolean getFast() {
return this.mappings.getFast();
}
public void setFast(boolean fast) {
this.mappings.setFast(fast);
}
public ActionMapping getUnknown(ServletRequest request) {
return getUnknown((HttpServletRequest)request);
}
public ActionMapping getUnknown(HttpServletRequest request) {
if (this.unknown != null)
return this.unknown;
String[] paths = findMappings();
for (int i = 0; i < paths.length; i++) {
ActionMapping mapping = findMapping(paths[i]);
if (mapping.getUnknown()) {
this.unknown = mapping;
return mapping;
}
}
return null;
}
public ActionServlet getServlet() {
return this.servlet;
}
public void setServlet(ActionServlet servlet) {
this.servlet = servlet;
}
public void addMapping(ActionMapping mapping) {
this.mappings.put(mapping.getPath(), mapping);
}
public ActionMapping findMapping(String path) {
return (ActionMapping)this.mappings.get(path);
}
public String[] findMappings() {
return (String[])this.mappings.keySet().toArray((Object[])new String[this.mappings.size()]);
}
public void removeMapping(ActionMapping mapping) {
this.mappings.remove(mapping.getPath());
}
}

View File

@@ -0,0 +1,59 @@
package org.apache.struts.action;
import java.io.Serializable;
public class ActionMessage implements Serializable {
protected String key;
protected Object[] values;
public ActionMessage(String key) {
this.key = null;
this.values = null;
this.key = key;
this.values = null;
}
public ActionMessage(String key, Object value0) {
this.key = null;
this.values = null;
this.key = key;
this.values = new Object[] { value0 };
}
public ActionMessage(String key, Object value0, Object value1) {
this.key = null;
this.values = null;
this.key = key;
this.values = new Object[] { value0, value1 };
}
public ActionMessage(String key, Object value0, Object value1, Object value2) {
this.key = null;
this.values = null;
this.key = key;
this.values = new Object[] { value0, value1, value2 };
}
public ActionMessage(String key, Object value0, Object value1, Object value2, Object value3) {
this.key = null;
this.values = null;
this.key = key;
this.values = new Object[] { value0, value1, value2, value3 };
}
public ActionMessage(String key, Object[] values) {
this.key = null;
this.values = null;
this.key = key;
this.values = values;
}
public String getKey() {
return this.key;
}
public Object[] getValues() {
return this.values;
}
}

View File

@@ -0,0 +1,143 @@
package org.apache.struts.action;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
public class ActionMessages implements Serializable {
public static final String GLOBAL_MESSAGE = "org.apache.struts.action.GLOBAL_MESSAGE";
protected HashMap messages = new HashMap();
protected int iCount = 0;
public ActionMessages() {}
public ActionMessages(ActionMessages messages) {
add(messages);
}
public void add(String property, ActionMessage message) {
ActionMessageItem item = (ActionMessageItem)this.messages.get(property);
List list = null;
if (item == null) {
list = new ArrayList();
item = new ActionMessageItem(this, list, this.iCount++);
this.messages.put(property, item);
} else {
list = item.getList();
}
list.add(message);
}
public void add(ActionMessages messages) {
if (messages == null)
return;
Iterator props = messages.properties();
while (props.hasNext()) {
String property = props.next();
Iterator msgs = messages.get(property);
while (msgs.hasNext()) {
ActionMessage msg = msgs.next();
add(property, msg);
}
}
}
public void clear() {
this.messages.clear();
}
public boolean empty() {
return isEmpty();
}
public boolean isEmpty() {
return this.messages.isEmpty();
}
public Iterator get() {
if (this.messages.isEmpty())
return Collections.EMPTY_LIST.iterator();
ArrayList results = new ArrayList();
ArrayList actionItems = new ArrayList();
for (Iterator i = this.messages.values().iterator(); i.hasNext();)
actionItems.add(i.next());
Collections.sort(actionItems, new Comparator(this) {
private final ActionMessages this$0;
public int compare(Object o1, Object o2) {
return ((ActionMessages.ActionMessageItem)o1).getOrder() - ((ActionMessages.ActionMessageItem)o2).getOrder();
}
});
for (Iterator iterator = actionItems.iterator(); iterator.hasNext(); ) {
ActionMessageItem ami = (ActionMessageItem)iterator.next();
for (Iterator messages = ami.getList().iterator(); messages.hasNext();)
results.add(messages.next());
}
return results.iterator();
}
public Iterator get(String property) {
ActionMessageItem item = (ActionMessageItem)this.messages.get(property);
if (item == null)
return Collections.EMPTY_LIST.iterator();
return item.getList().iterator();
}
public Iterator properties() {
return this.messages.keySet().iterator();
}
public int size() {
int total = 0;
for (Iterator i = this.messages.values().iterator(); i.hasNext(); ) {
ActionMessageItem ami = i.next();
total += ami.getList().size();
}
return total;
}
public int size(String property) {
ActionMessageItem ami = (ActionMessageItem)this.messages.get(property);
if (ami == null)
return 0;
return ami.getList().size();
}
protected class ActionMessageItem implements Serializable {
protected List list;
protected int iOrder;
private final ActionMessages this$0;
public ActionMessageItem(ActionMessages this$0, List list, int iOrder) {
this.this$0 = this$0;
this.list = null;
this.iOrder = 0;
this.list = list;
this.iOrder = iOrder;
}
public List getList() {
return this.list;
}
public void setList(List list) {
this.list = list;
}
public int getOrder() {
return this.iOrder;
}
public void setOrder(int iOrder) {
this.iOrder = iOrder;
}
}
}

View File

@@ -0,0 +1,646 @@
package org.apache.struts.action;
import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;
import java.math.BigDecimal;
import java.math.BigInteger;
import java.net.MalformedURLException;
import java.net.URL;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.Enumeration;
import java.util.Iterator;
import java.util.MissingResourceException;
import javax.servlet.ServletException;
import javax.servlet.UnavailableException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.sql.DataSource;
import org.apache.commons.beanutils.BeanUtils;
import org.apache.commons.beanutils.ConvertUtils;
import org.apache.commons.beanutils.Converter;
import org.apache.commons.beanutils.PropertyUtils;
import org.apache.commons.beanutils.converters.BigDecimalConverter;
import org.apache.commons.beanutils.converters.BigIntegerConverter;
import org.apache.commons.beanutils.converters.BooleanConverter;
import org.apache.commons.beanutils.converters.ByteConverter;
import org.apache.commons.beanutils.converters.CharacterConverter;
import org.apache.commons.beanutils.converters.DoubleConverter;
import org.apache.commons.beanutils.converters.FloatConverter;
import org.apache.commons.beanutils.converters.IntegerConverter;
import org.apache.commons.beanutils.converters.LongConverter;
import org.apache.commons.beanutils.converters.ShortConverter;
import org.apache.commons.collections.FastHashMap;
import org.apache.commons.digester.Digester;
import org.apache.commons.digester.RuleSet;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.struts.config.ActionConfig;
import org.apache.struts.config.ApplicationConfig;
import org.apache.struts.config.ConfigRuleSet;
import org.apache.struts.config.ControllerConfig;
import org.apache.struts.config.DataSourceConfig;
import org.apache.struts.config.FormBeanConfig;
import org.apache.struts.config.ForwardConfig;
import org.apache.struts.config.MessageResourcesConfig;
import org.apache.struts.config.ModuleConfig;
import org.apache.struts.config.ModuleConfigFactory;
import org.apache.struts.config.PlugInConfig;
import org.apache.struts.config.impl.ModuleConfigImpl;
import org.apache.struts.util.GenericDataSource;
import org.apache.struts.util.MessageResources;
import org.apache.struts.util.MessageResourcesFactory;
import org.apache.struts.util.RequestUtils;
import org.apache.struts.util.ServletContextWriter;
import org.xml.sax.InputSource;
import org.xml.sax.SAXException;
public class ActionServlet extends HttpServlet {
protected String config = "/WEB-INF/struts-config.xml";
protected Digester configDigester = null;
protected boolean convertNull = false;
protected FastHashMap dataSources = new FastHashMap();
protected int debug = 0;
protected MessageResources internal = null;
protected String internalName = "org.apache.struts.action.ActionResources";
protected static Log log = LogFactory.getLog(ActionServlet.class);
protected RequestProcessor processor = null;
protected String[] registrations = new String[] { "-//Apache Software Foundation//DTD Struts Configuration 1.0//EN", "/org/apache/struts/resources/struts-config_1_0.dtd", "-//Apache Software Foundation//DTD Struts Configuration 1.1//EN", "/org/apache/struts/resources/struts-config_1_1.dtd", "-//Sun Microsystems, Inc.//DTD Web Application 2.2//EN", "/org/apache/struts/resources/web-app_2_2.dtd", "-//Sun Microsystems, Inc.//DTD Web Application 2.3//EN", "/org/apache/struts/resources/web-app_2_3.dtd" };
protected String servletMapping = null;
protected String servletName = null;
public void destroy() {
if (log.isDebugEnabled())
log.debug(this.internal.getMessage("finalizing"));
destroyModules();
destroyDataSources();
destroyInternal();
getServletContext().removeAttribute("org.apache.struts.action.ACTION_SERVLET");
ClassLoader classLoader = Thread.currentThread().getContextClassLoader();
if (classLoader == null)
classLoader = ActionServlet.class.getClassLoader();
try {
LogFactory.release(classLoader);
} catch (Throwable t) {}
}
public void init() throws ServletException {
initInternal();
initOther();
initServlet();
getServletContext().setAttribute("org.apache.struts.action.ACTION_SERVLET", this);
ModuleConfig moduleConfig = initModuleConfig("", this.config);
initModuleMessageResources(moduleConfig);
initModuleDataSources(moduleConfig);
initModulePlugIns(moduleConfig);
moduleConfig.freeze();
Enumeration names = getServletConfig().getInitParameterNames();
while (names.hasMoreElements()) {
String name = names.nextElement();
if (!name.startsWith("config/"))
continue;
String prefix = name.substring(6);
moduleConfig = initModuleConfig(prefix, getServletConfig().getInitParameter(name));
initModuleMessageResources(moduleConfig);
initModuleDataSources(moduleConfig);
initModulePlugIns(moduleConfig);
moduleConfig.freeze();
}
destroyConfigDigester();
}
public void doGet(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException {
process(request, response);
}
public void doPost(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException {
process(request, response);
}
public void addServletMapping(String servletName, String urlPattern) {
if (log.isDebugEnabled())
log.debug("Process servletName=" + servletName + ", urlPattern=" + urlPattern);
if (servletName == null)
return;
if (servletName.equals(this.servletName))
this.servletMapping = urlPattern;
}
public DataSource findDataSource(String key) {
if (key == null)
return (DataSource)this.dataSources.get("org.apache.struts.action.DATA_SOURCE");
return (DataSource)this.dataSources.get(key);
}
public ActionFormBean findFormBean(String name) {
ActionFormBeans afb = (ActionFormBeans)getServletContext().getAttribute("org.apache.struts.action.FORM_BEANS");
if (afb == null)
return null;
return afb.findFormBean(name);
}
public ActionForward findForward(String name) {
ActionForwards af = (ActionForwards)getServletContext().getAttribute("org.apache.struts.action.FORWARDS");
if (af == null)
return null;
return af.findForward(name);
}
public ActionMapping findMapping(String path) {
ActionMappings am = (ActionMappings)getServletContext().getAttribute("org.apache.struts.action.MAPPINGS");
if (am == null)
return null;
return am.findMapping(path);
}
public int getDebug() {
return this.debug;
}
public MessageResources getInternal() {
return this.internal;
}
public MessageResources getResources() {
return (MessageResources)getServletContext().getAttribute("org.apache.struts.action.MESSAGE");
}
public void log(String message, int level) {
if (this.debug >= level)
log(message);
}
protected void destroyApplications() {
destroyModules();
}
protected void destroyModules() {
ArrayList values = new ArrayList();
Enumeration names = getServletContext().getAttributeNames();
while (names.hasMoreElements())
values.add(names.nextElement());
Iterator keys = values.iterator();
while (keys.hasNext()) {
String name = keys.next();
Object value = getServletContext().getAttribute(name);
if (value instanceof ModuleConfig) {
ModuleConfig config = (ModuleConfig)value;
try {
getRequestProcessor(config).destroy();
} catch (ServletException e) {
log.error(e);
}
getServletContext().removeAttribute(name);
PlugIn[] plugIns = (PlugIn[])getServletContext().getAttribute("org.apache.struts.action.PLUG_INS" + config.getPrefix());
if (plugIns != null) {
for (int i = 0; i < plugIns.length; i++) {
int j = plugIns.length - i + 1;
plugIns[j].destroy();
}
getServletContext().removeAttribute("org.apache.struts.action.PLUG_INS" + config.getPrefix());
}
}
}
}
protected void destroyConfigDigester() {
this.configDigester = null;
}
protected void destroyDataSources() {
synchronized (this.dataSources) {
Iterator keys = this.dataSources.keySet().iterator();
while (keys.hasNext()) {
String key = keys.next();
getServletContext().removeAttribute(key);
DataSource dataSource = findDataSource(key);
if (dataSource instanceof GenericDataSource) {
if (log.isDebugEnabled())
log.debug(this.internal.getMessage("dataSource.destroy", key));
try {
((GenericDataSource)dataSource).close();
} catch (SQLException e) {
log.error(this.internal.getMessage("destroyDataSource", key), e);
}
}
}
this.dataSources.clear();
}
}
protected void destroyInternal() {
this.internal = null;
}
protected ApplicationConfig getApplicationConfig(HttpServletRequest request) {
return new ApplicationConfig((ModuleConfigImpl)getModuleConfig(request));
}
protected ModuleConfig getModuleConfig(HttpServletRequest request) {
ModuleConfig config = (ModuleConfig)request.getAttribute("org.apache.struts.action.MODULE");
if (config == null)
config = (ModuleConfig)getServletContext().getAttribute("org.apache.struts.action.MODULE");
return config;
}
protected synchronized RequestProcessor getRequestProcessor(ModuleConfig config) throws ServletException {
String key = "org.apache.struts.action.REQUEST_PROCESSOR" + config.getPrefix();
RequestProcessor processor = (RequestProcessor)getServletContext().getAttribute(key);
if (processor == null) {
try {
processor = (RequestProcessor)RequestUtils.applicationInstance(config.getControllerConfig().getProcessorClass());
} catch (Exception e) {
throw new UnavailableException("Cannot initialize RequestProcessor of class " + config.getControllerConfig().getProcessorClass() + ": " + e);
}
processor.init(this, config);
getServletContext().setAttribute(key, processor);
}
return processor;
}
protected ApplicationConfig initApplicationConfig(String prefix, String path) throws ServletException {
return new ApplicationConfig((ModuleConfigImpl)initModuleConfig(prefix, path));
}
protected ModuleConfig initModuleConfig(String prefix, String paths) throws ServletException {
if (log.isDebugEnabled())
log.debug("Initializing module path '" + prefix + "' configuration from '" + paths + "'");
ModuleConfigFactory factoryObject = ModuleConfigFactory.createFactory();
ModuleConfig config = factoryObject.createModuleConfig(prefix);
String mapping = getServletConfig().getInitParameter("mapping");
if (mapping != null)
config.setActionMappingClass(mapping);
Digester digester = initConfigDigester();
while (paths.length() > 0) {
digester.push(config);
String path = null;
int comma = paths.indexOf(',');
if (comma >= 0) {
path = paths.substring(0, comma).trim();
paths = paths.substring(comma + 1);
} else {
path = paths.trim();
paths = "";
}
if (path.length() < 1)
break;
parseModuleConfigFile(prefix, paths, config, digester, path);
}
FormBeanConfig[] fbs = config.findFormBeanConfigs();
for (int i = 0; i < fbs.length; i++) {
if (fbs[i].getDynamic())
DynaActionFormClass.createDynaActionFormClass(fbs[i]);
}
if (prefix.length() < 1) {
defaultControllerConfig(config);
defaultMessageResourcesConfig(config);
defaultFormBeansConfig(config);
defaultForwardsConfig(config);
defaultMappingsConfig(config);
}
return config;
}
private void parseModuleConfigFile(String prefix, String paths, ModuleConfig config, Digester digester, String path) throws UnavailableException {
InputStream input = null;
try {
URL url = getServletContext().getResource(path);
InputSource is = new InputSource(url.toExternalForm());
input = getServletContext().getResourceAsStream(path);
is.setByteStream(input);
digester.parse(is);
getServletContext().setAttribute("org.apache.struts.action.MODULE" + prefix, config);
} catch (MalformedURLException e) {
handleConfigException(paths, e);
} catch (IOException e) {
handleConfigException(paths, e);
} catch (SAXException e) {
handleConfigException(paths, e);
} finally {
if (input != null)
try {
input.close();
} catch (IOException e) {
throw new UnavailableException(e.getMessage());
}
}
}
private void handleConfigException(String paths, Exception e) throws UnavailableException {
log.error(this.internal.getMessage("configParse", paths), e);
throw new UnavailableException(this.internal.getMessage("configParse", paths));
}
protected void initApplicationDataSources(ModuleConfig config) throws ServletException {
initModuleDataSources(config);
}
protected void initModuleDataSources(ModuleConfig config) throws ServletException {
if (log.isDebugEnabled())
log.debug("Initializing module path '" + config.getPrefix() + "' data sources");
ServletContextWriter scw = new ServletContextWriter(getServletContext());
DataSourceConfig[] dscs = config.findDataSourceConfigs();
if (dscs == null)
dscs = new DataSourceConfig[0];
this.dataSources.setFast(false);
for (int i = 0; i < dscs.length; i++) {
if (log.isDebugEnabled())
log.debug("Initializing module path '" + config.getPrefix() + "' data source '" + dscs[i].getKey() + "'");
DataSource ds = null;
try {
ds = (DataSource)RequestUtils.applicationInstance(dscs[i].getType());
BeanUtils.populate(ds, dscs[i].getProperties());
if (ds instanceof GenericDataSource)
((GenericDataSource)ds).open();
ds.setLogWriter((PrintWriter)scw);
} catch (Exception e) {
log.error(this.internal.getMessage("dataSource.init", dscs[i].getKey()), e);
throw new UnavailableException(this.internal.getMessage("dataSource.init", dscs[i].getKey()));
}
getServletContext().setAttribute(dscs[i].getKey() + config.getPrefix(), ds);
this.dataSources.put(dscs[i].getKey(), ds);
}
this.dataSources.setFast(true);
if ("".equals(config.getPrefix()))
initDataSources();
}
protected void initApplicationPlugIns(ModuleConfig config) throws ServletException {
initModulePlugIns(config);
}
protected void initModulePlugIns(ModuleConfig config) throws ServletException {
if (log.isDebugEnabled())
log.debug("Initializing module path '" + config.getPrefix() + "' plug ins");
PlugInConfig[] plugInConfigs = config.findPlugInConfigs();
PlugIn[] plugIns = new PlugIn[plugInConfigs.length];
getServletContext().setAttribute("org.apache.struts.action.PLUG_INS" + config.getPrefix(), plugIns);
for (int i = 0; i < plugIns.length; i++) {
try {
plugIns[i] = (PlugIn)RequestUtils.applicationInstance(plugInConfigs[i].getClassName());
BeanUtils.populate(plugIns[i], plugInConfigs[i].getProperties());
try {
PropertyUtils.setProperty(plugIns[i], "currentPlugInConfigObject", plugInConfigs[i]);
} catch (Exception e) {}
plugIns[i].init(this, config);
} catch (ServletException e) {
throw e;
} catch (Exception e) {
String errMsg = this.internal.getMessage("plugIn.init", plugInConfigs[i].getClassName());
log(errMsg, e);
throw new UnavailableException(errMsg);
}
}
}
protected void initApplicationMessageResources(ModuleConfig config) throws ServletException {
initModuleMessageResources(config);
}
protected void initModuleMessageResources(ModuleConfig config) throws ServletException {
MessageResourcesConfig[] mrcs = config.findMessageResourcesConfigs();
for (int i = 0; i < mrcs.length; i++) {
if (mrcs[i].getFactory() != null && mrcs[i].getParameter() != null) {
if (log.isDebugEnabled())
log.debug("Initializing module path '" + config.getPrefix() + "' message resources from '" + mrcs[i].getParameter() + "'");
String factory = mrcs[i].getFactory();
MessageResourcesFactory.setFactoryClass(factory);
MessageResourcesFactory factoryObject = MessageResourcesFactory.createFactory();
MessageResources resources = factoryObject.createResources(mrcs[i].getParameter());
resources.setReturnNull(mrcs[i].getNull());
getServletContext().setAttribute(mrcs[i].getKey() + config.getPrefix(), resources);
}
}
}
protected Digester initConfigDigester() throws ServletException {
if (this.configDigester != null)
return this.configDigester;
boolean validating = true;
String value = getServletConfig().getInitParameter("validating");
if ("false".equalsIgnoreCase(value) || "no".equalsIgnoreCase(value) || "n".equalsIgnoreCase(value) || "0".equalsIgnoreCase(value))
validating = false;
this.configDigester = new Digester();
this.configDigester.setNamespaceAware(true);
this.configDigester.setValidating(validating);
this.configDigester.setUseContextClassLoader(true);
this.configDigester.addRuleSet((RuleSet)new ConfigRuleSet());
for (int i = 0; i < this.registrations.length; i += 2) {
URL url = getClass().getResource(this.registrations[i + 1]);
if (url != null)
this.configDigester.register(this.registrations[i], url.toString());
}
String rulesets = getServletConfig().getInitParameter("rulesets");
if (rulesets == null)
rulesets = "";
rulesets = rulesets.trim();
String ruleset = null;
while (rulesets.length() > 0) {
int comma = rulesets.indexOf(",");
if (comma < 0) {
ruleset = rulesets.trim();
rulesets = "";
} else {
ruleset = rulesets.substring(0, comma).trim();
rulesets = rulesets.substring(comma + 1).trim();
}
if (log.isDebugEnabled())
log.debug("Configuring custom Digester Ruleset of type " + ruleset);
try {
RuleSet instance = (RuleSet)RequestUtils.applicationInstance(ruleset);
this.configDigester.addRuleSet(instance);
} catch (Exception e) {
log.error("Exception configuring custom Digester RuleSet", e);
throw new ServletException(e);
}
}
return this.configDigester;
}
protected void initDataSources() throws ServletException {}
protected void initInternal() throws ServletException {
try {
this.internal = MessageResources.getMessageResources(this.internalName);
} catch (MissingResourceException e) {
log.error("Cannot load internal resources from '" + this.internalName + "'", e);
throw new UnavailableException("Cannot load internal resources from '" + this.internalName + "'");
}
}
protected void initOther() throws ServletException {
String value = null;
value = getServletConfig().getInitParameter("config");
if (value != null)
this.config = value;
value = getServletConfig().getInitParameter("debug");
if (value != null)
try {
this.debug = Integer.parseInt(value);
} catch (NumberFormatException e) {
this.debug = 0;
}
value = getServletConfig().getInitParameter("convertNull");
if ("true".equalsIgnoreCase(value) || "yes".equalsIgnoreCase(value) || "on".equalsIgnoreCase(value) || "y".equalsIgnoreCase(value) || "1".equalsIgnoreCase(value))
this.convertNull = true;
if (this.convertNull) {
ConvertUtils.deregister();
ConvertUtils.register((Converter)new BigDecimalConverter(null), BigDecimal.class);
ConvertUtils.register((Converter)new BigIntegerConverter(null), BigInteger.class);
ConvertUtils.register((Converter)new BooleanConverter(null), Boolean.class);
ConvertUtils.register((Converter)new ByteConverter(null), Byte.class);
ConvertUtils.register((Converter)new CharacterConverter(null), Character.class);
ConvertUtils.register((Converter)new DoubleConverter(null), Double.class);
ConvertUtils.register((Converter)new FloatConverter(null), Float.class);
ConvertUtils.register((Converter)new IntegerConverter(null), Integer.class);
ConvertUtils.register((Converter)new LongConverter(null), Long.class);
ConvertUtils.register((Converter)new ShortConverter(null), Short.class);
}
}
protected void initServlet() throws ServletException {
this.servletName = getServletConfig().getServletName();
Digester digester = new Digester();
digester.push(this);
digester.setNamespaceAware(true);
digester.setValidating(false);
for (int i = 0; i < this.registrations.length; i += 2) {
URL url = getClass().getResource(this.registrations[i + 1]);
if (url != null)
digester.register(this.registrations[i], url.toString());
}
digester.addCallMethod("web-app/servlet-mapping", "addServletMapping", 2);
digester.addCallParam("web-app/servlet-mapping/servlet-name", 0);
digester.addCallParam("web-app/servlet-mapping/url-pattern", 1);
if (log.isDebugEnabled())
log.debug("Scanning web.xml for controller servlet mapping");
InputStream input = getServletContext().getResourceAsStream("/WEB-INF/web.xml");
try {
digester.parse(input);
} catch (IOException e) {
log.error(this.internal.getMessage("configWebXml"), e);
throw new ServletException(e);
} catch (SAXException e) {
log.error(this.internal.getMessage("configWebXml"), e);
throw new ServletException(e);
} finally {
if (input != null)
try {
input.close();
} catch (IOException e) {
log.error(this.internal.getMessage("configWebXml"), e);
throw new ServletException(e);
}
}
if (log.isDebugEnabled())
log.debug("Mapping for servlet '" + this.servletName + "' = '" + this.servletMapping + "'");
if (this.servletMapping != null)
getServletContext().setAttribute("org.apache.struts.action.SERVLET_MAPPING", this.servletMapping);
}
protected void process(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException {
RequestUtils.selectModule(request, getServletContext());
getRequestProcessor(getModuleConfig(request)).process(request, response);
}
private void defaultControllerConfig(ModuleConfig config) {
String value = null;
ControllerConfig cc = config.getControllerConfig();
value = getServletConfig().getInitParameter("bufferSize");
if (value != null)
cc.setBufferSize(Integer.parseInt(value));
value = getServletConfig().getInitParameter("content");
if (value != null)
cc.setContentType(value);
value = getServletConfig().getInitParameter("locale");
if (value != null)
if ("true".equalsIgnoreCase(value) || "yes".equalsIgnoreCase(value)) {
cc.setLocale(true);
} else {
cc.setLocale(false);
}
value = getServletConfig().getInitParameter("maxFileSize");
if (value != null)
cc.setMaxFileSize(value);
value = getServletConfig().getInitParameter("nocache");
if (value != null)
if ("true".equalsIgnoreCase(value) || "yes".equalsIgnoreCase(value)) {
cc.setNocache(true);
} else {
cc.setNocache(false);
}
value = getServletConfig().getInitParameter("multipartClass");
if (value != null)
cc.setMultipartClass(value);
value = getServletConfig().getInitParameter("tempDir");
if (value != null)
cc.setTempDir(value);
}
private void defaultFormBeansConfig(ModuleConfig config) {
FormBeanConfig[] fbcs = config.findFormBeanConfigs();
ActionFormBeans afb = new ActionFormBeans();
afb.setFast(false);
for (int i = 0; i < fbcs.length; i++)
afb.addFormBean((ActionFormBean)fbcs[i]);
afb.setFast(true);
getServletContext().setAttribute("org.apache.struts.action.FORM_BEANS", afb);
}
private void defaultForwardsConfig(ModuleConfig config) {
ForwardConfig[] fcs = config.findForwardConfigs();
ActionForwards af = new ActionForwards();
af.setFast(false);
for (int i = 0; i < fcs.length; i++)
af.addForward((ActionForward)fcs[i]);
af.setFast(true);
getServletContext().setAttribute("org.apache.struts.action.FORWARDS", af);
}
private void defaultMappingsConfig(ModuleConfig config) {
ActionConfig[] acs = config.findActionConfigs();
ActionMappings am = new ActionMappings();
am.setServlet(this);
am.setFast(false);
for (int i = 0; i < acs.length; i++)
am.addMapping((ActionMapping)acs[i]);
am.setFast(true);
getServletContext().setAttribute("org.apache.struts.action.MAPPINGS", am);
}
private void defaultMessageResourcesConfig(ModuleConfig config) {
String value = null;
MessageResourcesConfig mrc = config.findMessageResourcesConfig("org.apache.struts.action.MESSAGE");
if (mrc == null) {
mrc = new MessageResourcesConfig();
mrc.setKey("org.apache.struts.action.MESSAGE");
config.addMessageResourcesConfig(mrc);
}
value = getServletConfig().getInitParameter("application");
if (value != null)
mrc.setParameter(value);
value = getServletConfig().getInitParameter("factory");
if (value != null)
mrc.setFactory(value);
value = getServletConfig().getInitParameter("null");
if (value != null)
if (value.equalsIgnoreCase("true") || value.equalsIgnoreCase("yes")) {
mrc.setNull(true);
} else {
mrc.setNull(false);
}
}
}

View File

@@ -0,0 +1,23 @@
package org.apache.struts.action;
import org.apache.struts.upload.MultipartRequestHandler;
public class ActionServletWrapper {
protected transient ActionServlet servlet = null;
public void log(String message, int level) {
this.servlet.log(message, level);
}
public void log(String message) {
this.servlet.log(message);
}
public void setServletFor(MultipartRequestHandler object) {
object.setServlet(this.servlet);
}
public ActionServletWrapper(ActionServlet servlet) {
this.servlet = servlet;
}
}

View File

@@ -0,0 +1,228 @@
package org.apache.struts.action;
import java.lang.reflect.Array;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import javax.servlet.ServletRequest;
import javax.servlet.http.HttpServletRequest;
import org.apache.commons.beanutils.ConversionException;
import org.apache.commons.beanutils.DynaBean;
import org.apache.commons.beanutils.DynaClass;
import org.apache.commons.beanutils.DynaProperty;
import org.apache.struts.config.FormBeanConfig;
import org.apache.struts.config.FormPropertyConfig;
public class DynaActionForm extends ActionForm implements DynaBean {
protected DynaActionFormClass dynaClass = null;
protected HashMap dynaValues = new HashMap();
public void initialize(ActionMapping mapping) {
String name = mapping.getName();
if (name == null)
return;
FormBeanConfig config = mapping.getModuleConfig().findFormBeanConfig(name);
if (config == null)
return;
FormPropertyConfig[] props = config.findFormPropertyConfigs();
for (int i = 0; i < props.length; i++)
set(props[i].getName(), props[i].initial());
}
public void reset(ActionMapping mapping, ServletRequest request) {
try {
reset(mapping, (HttpServletRequest)request);
} catch (ClassCastException e) {}
}
public void reset(ActionMapping mapping, HttpServletRequest request) {}
public boolean contains(String name, String key) {
Object value = this.dynaValues.get(name);
if (value == null)
throw new NullPointerException("No mapped value for '" + name + "(" + key + ")'");
if (value instanceof Map)
return ((Map)value).containsKey(key);
throw new IllegalArgumentException("Non-mapped property for '" + name + "(" + key + ")'");
}
public Object get(String name) {
Object value = this.dynaValues.get(name);
if (value != null)
return value;
Class type = getDynaProperty(name).getType();
if (type == null)
throw new NullPointerException("The type for property " + name + " is invalid");
if (!type.isPrimitive())
return value;
if (type == boolean.class)
return Boolean.FALSE;
if (type == byte.class)
return new Byte((byte)0);
if (type == char.class)
return new Character(false);
if (type == double.class)
return new Double(0.0D);
if (type == float.class)
return new Float(0.0F);
if (type == int.class)
return new Integer(0);
if (type == long.class)
return new Long(0L);
if (type == short.class)
return new Short((short)0);
return null;
}
public Object get(String name, int index) {
Object value = this.dynaValues.get(name);
if (value == null)
throw new NullPointerException("No indexed value for '" + name + "[" + index + "]'");
if (value.getClass().isArray())
return Array.get(value, index);
if (value instanceof List)
return ((List)value).get(index);
throw new IllegalArgumentException("Non-indexed property for '" + name + "[" + index + "]'");
}
public Object get(String name, String key) {
Object value = this.dynaValues.get(name);
if (value == null)
throw new NullPointerException("No mapped value for '" + name + "(" + key + ")'");
if (value instanceof Map)
return ((Map)value).get(key);
throw new IllegalArgumentException("Non-mapped property for '" + name + "(" + key + ")'");
}
public DynaClass getDynaClass() {
return this.dynaClass;
}
public Map getMap() {
return this.dynaValues;
}
public void remove(String name, String key) {
Object value = this.dynaValues.get(name);
if (value == null)
throw new NullPointerException("No mapped value for '" + name + "(" + key + ")'");
if (value instanceof Map) {
((Map)value).remove(key);
} else {
throw new IllegalArgumentException("Non-mapped property for '" + name + "(" + key + ")'");
}
}
public void set(String name, Object value) {
DynaProperty descriptor = getDynaProperty(name);
if (descriptor.getType() == null)
throw new NullPointerException("The type for property " + name + " is invalid");
if (value == null) {
if (descriptor.getType().isPrimitive())
throw new NullPointerException("Primitive value for '" + name + "'");
} else if (!isDynaAssignable(descriptor.getType(), value.getClass())) {
throw new ConversionException("Cannot assign value of type '" + value.getClass().getName() + "' to property '" + name + "' of type '" + descriptor.getType().getName() + "'");
}
this.dynaValues.put(name, value);
}
public void set(String name, int index, Object value) {
Object prop = this.dynaValues.get(name);
if (prop == null)
throw new NullPointerException("No indexed value for '" + name + "[" + index + "]'");
if (prop.getClass().isArray()) {
Array.set(prop, index, value);
} else if (prop instanceof List) {
try {
((List)prop).set(index, value);
} catch (ClassCastException e) {
throw new ConversionException(e.getMessage());
}
} else {
throw new IllegalArgumentException("Non-indexed property for '" + name + "[" + index + "]'");
}
}
public void set(String name, String key, Object value) {
Object prop = this.dynaValues.get(name);
if (prop == null)
throw new NullPointerException("No mapped value for '" + name + "(" + key + ")'");
if (prop instanceof Map) {
((Map)prop).put(key, value);
} else {
throw new IllegalArgumentException("Non-mapped property for '" + name + "(" + key + ")'");
}
}
public String toString() {
StringBuffer sb = new StringBuffer("DynaActionForm[dynaClass=");
sb.append(getDynaClass().getName());
DynaProperty[] props = getDynaClass().getDynaProperties();
if (props == null)
props = new DynaProperty[0];
for (int i = 0; i < props.length; i++) {
sb.append(',');
sb.append(props[i].getName());
sb.append('=');
Object value = get(props[i].getName());
if (value == null) {
sb.append("<NULL>");
} else if (value.getClass().isArray()) {
int n = Array.getLength(value);
sb.append("{");
for (int j = 0; j < n; j++) {
if (j > 0)
sb.append(',');
sb.append(Array.get(value, j));
}
sb.append("}");
} else if (value instanceof List) {
int n = ((List)value).size();
sb.append("{");
for (int j = 0; j < n; j++) {
if (j > 0)
sb.append(',');
sb.append(((List)value).get(j));
}
sb.append("}");
} else if (value instanceof Map) {
int n = 0;
Iterator keys = ((Map)value).keySet().iterator();
sb.append("{");
while (keys.hasNext()) {
if (n > 0)
sb.append(',');
n++;
String key = keys.next();
sb.append(key);
sb.append('=');
sb.append(((Map)value).get(key));
}
sb.append("}");
} else {
sb.append(value);
}
}
sb.append("]");
return sb.toString();
}
void setDynaActionFormClass(DynaActionFormClass dynaClass) {
this.dynaClass = dynaClass;
}
protected DynaProperty getDynaProperty(String name) {
DynaProperty descriptor = getDynaClass().getDynaProperty(name);
if (descriptor == null)
throw new IllegalArgumentException("Invalid property name '" + name + "'");
return descriptor;
}
protected boolean isDynaAssignable(Class dest, Class source) {
if (dest.isAssignableFrom(source) || (dest == boolean.class && source == Boolean.class) || (dest == byte.class && source == Byte.class) || (dest == char.class && source == Character.class) || (dest == double.class && source == Double.class) || (dest == float.class && source == Float.class) || (dest == int.class && source == Integer.class) || (dest == long.class && source == Long.class) || (dest == short.class && source == Short.class))
return true;
return false;
}
}

View File

@@ -0,0 +1,126 @@
package org.apache.struts.action;
import java.io.Serializable;
import java.util.HashMap;
import org.apache.commons.beanutils.DynaBean;
import org.apache.commons.beanutils.DynaClass;
import org.apache.commons.beanutils.DynaProperty;
import org.apache.struts.config.FormBeanConfig;
import org.apache.struts.config.FormPropertyConfig;
import org.apache.struts.config.ModuleConfig;
import org.apache.struts.util.RequestUtils;
public class DynaActionFormClass implements DynaClass, Serializable {
protected transient Class beanClass;
protected FormBeanConfig config;
protected String name;
protected DynaProperty[] properties;
protected HashMap propertiesMap;
private DynaActionFormClass(FormBeanConfig config) {
this.beanClass = null;
this.config = null;
this.name = null;
this.properties = null;
this.propertiesMap = new HashMap();
introspect(config);
}
protected static transient HashMap dynaClasses = new HashMap();
protected static String lock = "";
public String getName() {
return this.name;
}
public DynaProperty getDynaProperty(String name) {
if (name == null)
throw new IllegalArgumentException("No property name specified");
return (DynaProperty)this.propertiesMap.get(name);
}
public DynaProperty[] getDynaProperties() {
return this.properties;
}
public DynaBean newInstance() throws IllegalAccessException, InstantiationException {
DynaActionForm dynaBean = getBeanClass().newInstance();
dynaBean.setDynaActionFormClass(this);
FormPropertyConfig[] props = this.config.findFormPropertyConfigs();
for (int i = 0; i < props.length; i++)
dynaBean.set(props[i].getName(), props[i].initial());
return dynaBean;
}
public String toString() {
StringBuffer sb = new StringBuffer("DynaActionFormBean[name=");
sb.append(this.name);
DynaProperty[] props = getDynaProperties();
if (props == null)
props = new DynaProperty[0];
for (int i = 0; i < props.length; i++) {
sb.append(',');
sb.append(props[i].getName());
sb.append('/');
sb.append(props[i].getType());
}
sb.append("]");
return sb.toString();
}
public static void clear() {
synchronized (lock) {
if (dynaClasses == null)
dynaClasses = new HashMap();
dynaClasses.clear();
}
}
public static DynaActionFormClass createDynaActionFormClass(FormBeanConfig config) {
synchronized (lock) {
if (dynaClasses == null)
dynaClasses = new HashMap();
ModuleConfig moduleConfig = config.getModuleConfig();
String key = config.getName();
if (moduleConfig != null)
key = key + moduleConfig.getPrefix();
DynaActionFormClass dynaClass = (DynaActionFormClass)dynaClasses.get(key);
if (dynaClass == null) {
dynaClass = new DynaActionFormClass(config);
dynaClasses.put(key, dynaClass);
}
return dynaClass;
}
}
protected Class getBeanClass() {
if (this.beanClass == null)
introspect(this.config);
return this.beanClass;
}
protected void introspect(FormBeanConfig config) {
this.config = config;
try {
this.beanClass = RequestUtils.applicationClass(config.getType());
} catch (Throwable t) {
throw new IllegalArgumentException("Cannot instantiate ActionFormBean class '" + config.getType() + "': " + t);
}
if (!DynaActionForm.class.isAssignableFrom(this.beanClass))
throw new IllegalArgumentException("Class '" + config.getType() + "' is not a subclass of " + "'org.apache.struts.action.DynaActionForm'");
this.name = config.getName();
FormPropertyConfig[] descriptors = config.findFormPropertyConfigs();
if (descriptors == null)
descriptors = new FormPropertyConfig[0];
this.properties = new DynaProperty[descriptors.length];
for (int i = 0; i < descriptors.length; i++) {
this.properties[i] = new DynaProperty(descriptors[i].getName(), descriptors[i].getTypeClass());
this.propertiesMap.put(this.properties[i].getName(), this.properties[i]);
}
}
}

View File

@@ -0,0 +1,40 @@
package org.apache.struts.action;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.struts.config.ExceptionConfig;
import org.apache.struts.util.ModuleException;
public class ExceptionHandler {
public ActionForward execute(Exception ex, ExceptionConfig ae, ActionMapping mapping, ActionForm formInstance, HttpServletRequest request, HttpServletResponse response) throws ServletException {
ActionForward forward = null;
ActionError error = null;
String property = null;
if (ae.getPath() != null) {
forward = new ActionForward(ae.getPath());
} else {
forward = mapping.getInputForward();
}
if (ex instanceof ModuleException) {
error = ((ModuleException)ex).getError();
property = ((ModuleException)ex).getProperty();
} else {
error = new ActionError(ae.getKey(), ex.getMessage());
property = error.getKey();
}
request.setAttribute("org.apache.struts.action.EXCEPTION", ex);
storeException(request, property, error, forward, ae.getScope());
return forward;
}
protected void storeException(HttpServletRequest request, String property, ActionError error, ActionForward forward, String scope) {
ActionErrors errors = new ActionErrors();
errors.add(property, error);
if ("request".equals(scope)) {
request.setAttribute("org.apache.struts.action.ERROR", errors);
} else {
request.getSession().setAttribute("org.apache.struts.action.ERROR", errors);
}
}
}

View File

@@ -0,0 +1,10 @@
package org.apache.struts.action;
import javax.servlet.ServletException;
import org.apache.struts.config.ModuleConfig;
public interface PlugIn {
void destroy();
void init(ActionServlet paramActionServlet, ModuleConfig paramModuleConfig) throws ServletException;
}

View File

@@ -0,0 +1,414 @@
package org.apache.struts.action;
import java.io.IOException;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Locale;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.struts.config.ActionConfig;
import org.apache.struts.config.ExceptionConfig;
import org.apache.struts.config.ForwardConfig;
import org.apache.struts.config.ModuleConfig;
import org.apache.struts.upload.MultipartRequestWrapper;
import org.apache.struts.util.MessageResources;
import org.apache.struts.util.RequestUtils;
public class RequestProcessor {
public static final String INCLUDE_PATH_INFO = "javax.servlet.include.path_info";
public static final String INCLUDE_SERVLET_PATH = "javax.servlet.include.servlet_path";
protected HashMap actions = new HashMap();
protected ModuleConfig appConfig = null;
protected ModuleConfig moduleConfig = null;
protected static Log log = LogFactory.getLog(RequestProcessor.class);
protected ActionServlet servlet = null;
public void destroy() {
synchronized (this.actions) {
Iterator actions = this.actions.values().iterator();
while (actions.hasNext()) {
Action action = actions.next();
action.setServlet(null);
}
this.actions.clear();
}
this.servlet = null;
}
public void init(ActionServlet servlet, ModuleConfig moduleConfig) throws ServletException {
synchronized (this.actions) {
this.actions.clear();
}
this.servlet = servlet;
this.appConfig = moduleConfig;
this.moduleConfig = moduleConfig;
}
public void process(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException {
request = processMultipart(request);
String path = processPath(request, response);
if (path == null)
return;
if (log.isDebugEnabled())
log.debug("Processing a '" + request.getMethod() + "' for path '" + path + "'");
processLocale(request, response);
processContent(request, response);
processNoCache(request, response);
if (!processPreprocess(request, response))
return;
ActionMapping mapping = processMapping(request, response, path);
if (mapping == null)
return;
if (!processRoles(request, response, mapping))
return;
ActionForm form = processActionForm(request, response, mapping);
processPopulate(request, response, form, mapping);
if (!processValidate(request, response, form, mapping))
return;
if (!processForward(request, response, mapping))
return;
if (!processInclude(request, response, mapping))
return;
Action action = processActionCreate(request, response, mapping);
if (action == null)
return;
ActionForward forward = processActionPerform(request, response, action, form, mapping);
processForwardConfig(request, response, forward);
}
protected Action processActionCreate(HttpServletRequest request, HttpServletResponse response, ActionMapping mapping) throws IOException {
String className = mapping.getType();
if (log.isDebugEnabled())
log.debug(" Looking for Action instance for class " + className);
Action instance = null;
synchronized (this.actions) {
instance = (Action)this.actions.get(className);
if (instance != null) {
if (log.isTraceEnabled())
log.trace(" Returning existing Action instance");
return instance;
}
if (log.isTraceEnabled())
log.trace(" Creating new Action instance");
try {
instance = (Action)RequestUtils.applicationInstance(className);
} catch (Exception e) {
log.error(getInternal().getMessage("actionCreate", mapping.getPath()), e);
response.sendError(500, getInternal().getMessage("actionCreate", mapping.getPath()));
return null;
}
instance.setServlet(this.servlet);
this.actions.put(className, instance);
}
return instance;
}
protected ActionForm processActionForm(HttpServletRequest request, HttpServletResponse response, ActionMapping mapping) {
ActionForm instance = RequestUtils.createActionForm(request, mapping, this.moduleConfig, this.servlet);
if (instance == null)
return null;
if (log.isDebugEnabled())
log.debug(" Storing ActionForm bean instance in scope '" + mapping.getScope() + "' under attribute key '" + mapping.getAttribute() + "'");
if ("request".equals(mapping.getScope())) {
request.setAttribute(mapping.getAttribute(), instance);
} else {
HttpSession session = request.getSession();
session.setAttribute(mapping.getAttribute(), instance);
}
return instance;
}
protected void processActionForward(HttpServletRequest request, HttpServletResponse response, ActionForward forward) throws IOException, ServletException {
processForwardConfig(request, response, forward);
}
protected void processForwardConfig(HttpServletRequest request, HttpServletResponse response, ForwardConfig forward) throws IOException, ServletException {
if (forward == null)
return;
if (log.isDebugEnabled())
log.debug("processForwardConfig(" + forward + ")");
String forwardPath = forward.getPath();
String uri = null;
if (forwardPath.startsWith("/")) {
uri = RequestUtils.forwardURL(request, forward);
} else {
uri = forwardPath;
}
if (forward.getRedirect()) {
if (uri.startsWith("/"))
uri = request.getContextPath() + uri;
response.sendRedirect(response.encodeRedirectURL(uri));
} else {
doForward(uri, request, response);
}
}
protected ActionForward processActionPerform(HttpServletRequest request, HttpServletResponse response, Action action, ActionForm form, ActionMapping mapping) throws IOException, ServletException {
try {
return action.execute(mapping, form, request, response);
} catch (Exception e) {
return processException(request, response, e, form, mapping);
}
}
protected void processContent(HttpServletRequest request, HttpServletResponse response) {
String contentType = this.moduleConfig.getControllerConfig().getContentType();
if (contentType != null)
response.setContentType(contentType);
}
protected ActionForward processException(HttpServletRequest request, HttpServletResponse response, Exception exception, ActionForm form, ActionMapping mapping) throws IOException, ServletException {
ExceptionConfig config = mapping.findException(exception.getClass());
if (config == null) {
log.warn(getInternal().getMessage("unhandledException", exception.getClass()));
if (exception instanceof IOException)
throw (IOException)exception;
if (exception instanceof ServletException)
throw (ServletException)exception;
throw new ServletException(exception);
}
try {
ExceptionHandler handler = (ExceptionHandler)RequestUtils.applicationInstance(config.getHandler());
return handler.execute(exception, config, mapping, form, request, response);
} catch (Exception e) {
throw new ServletException(e);
}
}
protected boolean processForward(HttpServletRequest request, HttpServletResponse response, ActionMapping mapping) throws IOException, ServletException {
String forward = mapping.getForward();
if (forward == null)
return true;
internalModuleRelativeForward(forward, request, response);
return false;
}
protected boolean processInclude(HttpServletRequest request, HttpServletResponse response, ActionMapping mapping) throws IOException, ServletException {
String include = mapping.getInclude();
if (include == null)
return true;
internalModuleRelativeInclude(include, request, response);
return false;
}
protected void processLocale(HttpServletRequest request, HttpServletResponse response) {
if (!this.moduleConfig.getControllerConfig().getLocale())
return;
HttpSession session = request.getSession();
if (session.getAttribute("org.apache.struts.action.LOCALE") != null)
return;
Locale locale = request.getLocale();
if (locale != null) {
if (log.isDebugEnabled())
log.debug(" Setting user locale '" + locale + "'");
session.setAttribute("org.apache.struts.action.LOCALE", locale);
}
}
protected ActionMapping processMapping(HttpServletRequest request, HttpServletResponse response, String path) throws IOException {
ActionMapping mapping = (ActionMapping)this.moduleConfig.findActionConfig(path);
if (mapping != null) {
request.setAttribute("org.apache.struts.action.mapping.instance", mapping);
return mapping;
}
ActionConfig[] configs = this.moduleConfig.findActionConfigs();
for (int i = 0; i < configs.length; i++) {
if (configs[i].getUnknown()) {
mapping = (ActionMapping)configs[i];
request.setAttribute("org.apache.struts.action.mapping.instance", mapping);
return mapping;
}
}
log.error(getInternal().getMessage("processInvalid", path));
response.sendError(400, getInternal().getMessage("processInvalid", path));
return null;
}
protected HttpServletRequest processMultipart(HttpServletRequest request) {
if (!"POST".equalsIgnoreCase(request.getMethod()))
return request;
String contentType = request.getContentType();
if (contentType != null && contentType.startsWith("multipart/form-data"))
return (HttpServletRequest)new MultipartRequestWrapper(request);
return request;
}
protected void processNoCache(HttpServletRequest request, HttpServletResponse response) {
if (this.moduleConfig.getControllerConfig().getNocache()) {
response.setHeader("Pragma", "No-cache");
response.setHeader("Cache-Control", "no-cache");
response.setDateHeader("Expires", 1L);
}
}
protected String processPath(HttpServletRequest request, HttpServletResponse response) throws IOException {
String path = null;
path = (String)request.getAttribute("javax.servlet.include.path_info");
if (path == null)
path = request.getPathInfo();
if (path != null && path.length() > 0)
return path;
path = (String)request.getAttribute("javax.servlet.include.servlet_path");
if (path == null)
path = request.getServletPath();
String prefix = this.moduleConfig.getPrefix();
if (!path.startsWith(prefix)) {
log.error(getInternal().getMessage("processPath", request.getRequestURI()));
response.sendError(400, getInternal().getMessage("processPath", request.getRequestURI()));
return null;
}
path = path.substring(prefix.length());
int slash = path.lastIndexOf("/");
int period = path.lastIndexOf(".");
if (period >= 0 && period > slash)
path = path.substring(0, period);
return path;
}
protected void processPopulate(HttpServletRequest request, HttpServletResponse response, ActionForm form, ActionMapping mapping) throws ServletException {
if (form == null)
return;
if (log.isDebugEnabled())
log.debug(" Populating bean properties from this request");
form.setServlet(this.servlet);
form.reset(mapping, request);
if (mapping.getMultipartClass() != null)
request.setAttribute("org.apache.struts.action.mapping.multipartclass", mapping.getMultipartClass());
RequestUtils.populate(form, mapping.getPrefix(), mapping.getSuffix(), request);
if (request.getParameter("org.apache.struts.taglib.html.CANCEL") != null || request.getParameter("org.apache.struts.taglib.html.CANCEL.x") != null)
request.setAttribute("org.apache.struts.action.CANCEL", Boolean.TRUE);
}
protected boolean processPreprocess(HttpServletRequest request, HttpServletResponse response) {
return true;
}
protected boolean processRoles(HttpServletRequest request, HttpServletResponse response, ActionMapping mapping) throws IOException, ServletException {
String[] roles = mapping.getRoleNames();
if (roles == null || roles.length < 1)
return true;
for (int i = 0; i < roles.length; i++) {
if (request.isUserInRole(roles[i])) {
if (log.isDebugEnabled())
log.debug(" User '" + request.getRemoteUser() + "' has role '" + roles[i] + "', granting access");
return true;
}
}
if (log.isDebugEnabled())
log.debug(" User '" + request.getRemoteUser() + "' does not have any required role, denying access");
response.sendError(400, getInternal().getMessage("notAuthorized", mapping.getPath()));
return false;
}
protected boolean processValidate(HttpServletRequest request, HttpServletResponse response, ActionForm form, ActionMapping mapping) throws IOException, ServletException {
if (form == null)
return true;
if (request.getAttribute("org.apache.struts.action.CANCEL") != null) {
if (log.isDebugEnabled())
log.debug(" Cancelled transaction, skipping validation");
return true;
}
if (!mapping.getValidate())
return true;
if (log.isDebugEnabled())
log.debug(" Validating input form properties");
ActionErrors errors = form.validate(mapping, request);
if (errors == null || errors.isEmpty()) {
if (log.isTraceEnabled())
log.trace(" No errors detected, accepting input");
return true;
}
if (form.getMultipartRequestHandler() != null) {
if (log.isTraceEnabled())
log.trace(" Rolling back multipart request");
form.getMultipartRequestHandler().rollback();
}
String input = mapping.getInput();
if (input == null) {
if (log.isTraceEnabled())
log.trace(" Validation failed but no input form available");
response.sendError(500, getInternal().getMessage("noInput", mapping.getPath()));
return false;
}
if (log.isDebugEnabled())
log.debug(" Validation failed, returning to '" + input + "'");
request.setAttribute("org.apache.struts.action.ERROR", errors);
if (this.moduleConfig.getControllerConfig().getInputForward()) {
ForwardConfig forward = mapping.findForward(input);
processForwardConfig(request, response, forward);
} else {
internalModuleRelativeForward(input, request, response);
}
return false;
}
protected void internalModuleRelativeForward(String uri, HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException {
uri = this.moduleConfig.getPrefix() + uri;
if (log.isDebugEnabled())
log.debug(" Delegating via forward to '" + uri + "'");
doForward(uri, request, response);
}
protected void internalModuleRelativeInclude(String uri, HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException {
uri = this.moduleConfig.getPrefix() + uri;
if (log.isDebugEnabled())
log.debug(" Delegating via include to '" + uri + "'");
doInclude(uri, request, response);
}
protected void doForward(String uri, HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException {
if (request instanceof MultipartRequestWrapper)
request = ((MultipartRequestWrapper)request).getRequest();
RequestDispatcher rd = getServletContext().getRequestDispatcher(uri);
if (rd == null) {
response.sendError(500, getInternal().getMessage("requestDispatcher", uri));
return;
}
rd.forward((ServletRequest)request, (ServletResponse)response);
}
protected void doInclude(String uri, HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException {
if (request instanceof MultipartRequestWrapper)
request = ((MultipartRequestWrapper)request).getRequest();
RequestDispatcher rd = getServletContext().getRequestDispatcher(uri);
if (rd == null) {
response.sendError(500, getInternal().getMessage("requestDispatcher", uri));
return;
}
rd.include((ServletRequest)request, (ServletResponse)response);
}
public int getDebug() {
return this.servlet.getDebug();
}
protected MessageResources getInternal() {
return this.servlet.getInternal();
}
protected ServletContext getServletContext() {
return this.servlet.getServletContext();
}
protected void log(String message) {
this.servlet.log(message);
}
protected void log(String message, Throwable exception) {
this.servlet.log(message, exception);
}
}