Problem: to get the Datasource in Struts1.1

Discussions

Web tier: servlets, JSP, Web frameworks: Problem: to get the Datasource in Struts1.1

  1. Problem: to get the Datasource in Struts1.1 (3 messages)

    Hi all,
    I am using tomcat 4.1.3 server and implementing a application which is fecthing the information from the Oracle database.But i am getting the following exeception while compiling the Action Class.

    cannot resolve symbol symbol : method findDataSource (<nulltype>)
    location: class org.apache.struts.action.ActionServlet
    javax.sql.DataSource dataSource = servlet.findDataSource(null);


    Here is my struts-config.xml

    <data-sources>
    <data-source>
    <set-property property="driverClass" value="oracle.jdbc.driver.OracleDriver" />
    <set-property property="url" value="jdbc:oracle:thin:@ODCTEST:1521:orcl" />
    <set-property property="maxCount" value="5"/>
    <set-property property="minCount" value="1"/>
    <set-property property="user" value="scott"/>
    <set-property property="password" value="scott"/>
    </data-source>
    </data-sources>

    Pls Help me out from this problem.

    Regards
    Sachin
  2. Checked out the ActionServlet source code, and there is indeed a findDataSource() method.


    I wonder if you have the correct struts 1.1 binaries? Do check the classpath settings or any of the ant scripts settings you might have created.

    Hope it helps,
    Raymond
  3. Hi Raaymond,
    Here is my ActionServlet.java and i didn't find findDataSource method in it. Pls do needful ASAP.

    package org.apache.struts.action;

    import java.io.IOException;
    import java.io.InputStream;
    import java.net.MalformedURLException;
    import java.net.URL;
    import java.util.*;
    import javax.servlet.*;
    import javax.servlet.http.*;
    import javax.sql.DataSource;
    import org.apache.commons.beanutils.*;
    import org.apache.commons.beanutils.converters.*;
    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.*;
    import org.apache.struts.util.*;
    import org.xml.sax.InputSource;
    import org.xml.sax.SAXException;

    // Referenced classes of package org.apache.struts.action:
    // RequestProcessor, PlugIn

    public class ActionServlet extends HttpServlet
    {

    public ActionServlet()
    {
    config = "/WEB-INF/struts-config.xml";
    configDigester = null;
    convertNull = false;
    dataSources = new FastHashMap();
    internal = null;
    internalName = "org.apache.struts.action.ActionResources";
    processor = null;
    servletMapping = null;
    servletName = null;
    }

    public void destroy()
    {
    if(log.isDebugEnabled())
    log.debug(internal.getMessage("finalizing"));
    destroyModules();
    destroyInternal();
    getServletContext().removeAttribute("org.apache.struts.action.ACTION_SERVLET");
    ClassLoader classLoader = Thread.currentThread().getContextClassLoader();
    if(classLoader == null)
    classLoader = (org.apache.struts.action.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);
    initModuleConfigFactory();
    ModuleConfig moduleConfig = initModuleConfig("", config);
    initModuleMessageResources(moduleConfig);
    initModuleDataSources(moduleConfig);
    initModulePlugIns(moduleConfig);
    moduleConfig.freeze();
    Enumeration names = getServletConfig().getInitParameterNames();
    do
    {
    if(!names.hasMoreElements())
    break;
    String name = (String)names.nextElement();
    if(name.startsWith("config/"))
    {
    String prefix = name.substring(6);
    moduleConfig = initModuleConfig(prefix, getServletConfig().getInitParameter(name));
    initModuleMessageResources(moduleConfig);
    initModuleDataSources(moduleConfig);
    initModulePlugIns(moduleConfig);
    moduleConfig.freeze();
    }
    } while(true);
    initModulePrefixes(getServletContext());
    destroyConfigDigester();
    }

    protected void initModulePrefixes(ServletContext context)
    {
    ArrayList prefixList = new ArrayList();
    Enumeration names = context.getAttributeNames();
    do
    {
    if(!names.hasMoreElements())
    break;
    String name = (String)names.nextElement();
    if(name.startsWith("org.apache.struts.action.MODULE"))
    {
    String prefix = name.substring("org.apache.struts.action.MODULE".length());
    if(prefix.length() > 0)
    prefixList.add(prefix);
    }
    } while(true);
    String prefixes[] = (String[])prefixList.toArray(new String[prefixList.size()]);
    context.setAttribute("org.apache.struts.globals.MODULE_PREFIXES", prefixes);
    }

    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))
    servletMapping = urlPattern;
    }

    public MessageResources getInternal()
    {
    return internal;
    }

    protected void destroyModules()
    {
    ArrayList values = new ArrayList();
    for(Enumeration names = getServletContext().getAttributeNames(); names.hasMoreElements(); values.add(names.nextElement()));
    Iterator keys = values.iterator();
    do
    {
    if(!keys.hasNext())
    break;
    String name = (String)keys.next();
    Object value = getServletContext().getAttribute(name);
    if(value instanceof ModuleConfig)
    {
    ModuleConfig config = (ModuleConfig)value;
    if(getProcessorForModule(config) != null)
    getProcessorForModule(config).destroy();
    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());
    }
    }
    } while(true);
    }

    protected void destroyConfigDigester()
    {
    configDigester = null;
    }

    protected void destroyInternal()
    {
    internal = null;
    }

    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
    {
    RequestProcessor processor = getProcessorForModule(config);
    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);
    String key = "org.apache.struts.action.REQUEST_PROCESSOR" + config.getPrefix();
    getServletContext().setAttribute(key, processor);
    }
    return processor;
    }

    private RequestProcessor getProcessorForModule(ModuleConfig config)
    {
    String key = "org.apache.struts.action.REQUEST_PROCESSOR" + config.getPrefix();
    return (RequestProcessor)getServletContext().getAttribute(key);
    }

    protected void initModuleConfigFactory()
    {
    String configFactory = getServletConfig().getInitParameter("configFactory");
    if(configFactory != null)
    ModuleConfigFactory.setFactoryClass(configFactory);
    }

    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);
    Digester digester = initConfigDigester();
    do
    {
    if(paths.length() <= 0)
    break;
    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(digester, path);
    } while(true);
    getServletContext().setAttribute("org.apache.struts.action.MODULE" + config.getPrefix(), config);
    FormBeanConfig fbs[] = config.findFormBeanConfigs();
    for(int i = 0; i < fbs.length; i++)
    if(fbs.getDynamic())
    fbs.getDynaActionFormClass();

    return config;
    }

    protected void parseModuleConfigFile(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);
    }
    catch(MalformedURLException e)
    {
    handleConfigException(path, e);
    }
    catch(IOException e)
    {
    handleConfigException(path, e);
    }
    catch(SAXException e)
    {
    handleConfigException(path, e);
    }
    finally
    {
    if(input != null)
    try
    {
    input.close();
    }
    catch(IOException e)
    {
    throw new UnavailableException(e.getMessage());
    }
    }
    }

    private void handleConfigException(String path, Exception e)
    throws UnavailableException
    {
    String msg = internal.getMessage("configParse", path);
    log.error(msg, e);
    throw new UnavailableException(msg);
    }

    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];
    dataSources.setFast(false);
    for(int i = 0; i < dscs.length; i++)
    {
    if(log.isDebugEnabled())
    log.debug("Initializing module path '" + config.getPrefix() + "' data source '" + dscs.getKey() + "'");
    DataSource ds = null;
    try
    {
    ds = (DataSource)RequestUtils.applicationInstance(dscs.getType());
    BeanUtils.populate(ds, dscs.getProperties());
    ds.setLogWriter(scw);
    }
    catch(Exception e)
    {
    log.error(internal.getMessage("dataSource.init", dscs.getKey()), e);
    throw new UnavailableException(internal.getMessage("dataSource.init", dscs.getKey()));
    }
    getServletContext().setAttribute(dscs.getKey() + config.getPrefix(), ds);
    dataSources.put(dscs.getKey(), ds);
    }

    dataSources.setFast(true);
    }

    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 = (PlugIn)RequestUtils.applicationInstance(plugInConfigs.getClassName());
    BeanUtils.populate(plugIns, plugInConfigs.getProperties());
    try
    {
    PropertyUtils.setProperty(plugIns, "currentPlugInConfigObject", plugInConfigs);
    }
    catch(Exception e) { }
    plugIns.init(this, config);
    }
    catch(ServletException e)
    {
    throw e;
    }
    catch(Exception e)
    {
    String errMsg = internal.getMessage("plugIn.init", plugInConfigs.getClassName());
    log(errMsg, e);
    throw new UnavailableException(errMsg);
    }

    }

    protected void initModuleMessageResources(ModuleConfig config)
    throws ServletException
    {
    MessageResourcesConfig mrcs[] = config.findMessageResourcesConfigs();
    for(int i = 0; i < mrcs.length; i++)
    {
    if(mrcs.getFactory() == null || mrcs.getParameter() == null)
    continue;
    if(log.isDebugEnabled())
    log.debug("Initializing module path '" + config.getPrefix() + "' message resources from '" + mrcs.getParameter() + "'");
    String factory = mrcs.getFactory();
    MessageResourcesFactory.setFactoryClass(factory);
    MessageResourcesFactory factoryObject = MessageResourcesFactory.createFactory();
    MessageResources resources = factoryObject.createResources(mrcs.getParameter());
    resources.setReturnNull(mrcs.getNull());
    getServletContext().setAttribute(mrcs.getKey() + config.getPrefix(), resources);
    }

    }

    protected Digester initConfigDigester()
    throws ServletException
    {
    if(configDigester != null)
    return configDigester;
    configDigester = new Digester();
    configDigester.setNamespaceAware(true);
    configDigester.setValidating(isValidating());
    configDigester.setUseContextClassLoader(true);
    configDigester.addRuleSet(new ConfigRuleSet());
    for(int i = 0; i < registrations.length; i += 2)
    {
    URL url = getClass().getResource(registrations[i + 1]);
    if(url != null)
    configDigester.register(registrations, url.toString());
    }

    addRuleSets();
    return configDigester;
    }

    private void addRuleSets()
    throws ServletException
    {
    String rulesets = getServletConfig().getInitParameter("rulesets");
    if(rulesets == null)
    rulesets = "";
    rulesets = rulesets.trim();
    String ruleset = null;
    do
    {
    if(rulesets.length() <= 0)
    break;
    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);
    configDigester.addRuleSet(instance);
    }
    catch(Exception e)
    {
    log.error("Exception configuring custom Digester RuleSet", e);
    throw new ServletException(e);
    }
    } while(true);
    }

    private boolean isValidating()
    {
    boolean validating = true;
    String value = getServletConfig().getInitParameter("validating");
    if("false".equalsIgnoreCase(value) || "no".equalsIgnoreCase(value) || "n".equalsIgnoreCase(value) || "0".equalsIgnoreCase(value))
    validating = false;
    return validating;
    }

    protected void initInternal()
    throws ServletException
    {
    try
    {
    internal = MessageResources.getMessageResources(internalName);
    }
    catch(MissingResourceException e)
    {
    log.error("Cannot load internal resources from '" + internalName + "'", e);
    throw new UnavailableException("Cannot load internal resources from '" + internalName + "'");
    }
    }

    protected void initOther()
    throws ServletException
    {
    String value = null;
    value = getServletConfig().getInitParameter("config");
    if(value != null)
    config = value;
    value = getServletConfig().getInitParameter("convertNull");
    if("true".equalsIgnoreCase(value) || "yes".equalsIgnoreCase(value) || "on".equalsIgnoreCase(value) || "y".equalsIgnoreCase(value) || "1".equalsIgnoreCase(value))
    convertNull = true;
    if(convertNull)
    {
    ConvertUtils.deregister();
    ConvertUtils.register(new BigDecimalConverter(null), java.math.BigDecimal.class);
    ConvertUtils.register(new BigIntegerConverter(null), java.math.BigInteger.class);
    ConvertUtils.register(new BooleanConverter(null), java.lang.Boolean.class);
    ConvertUtils.register(new ByteConverter(null), java.lang.Byte.class);
    ConvertUtils.register(new CharacterConverter(null), java.lang.Character.class);
    ConvertUtils.register(new DoubleConverter(null), java.lang.Double.class);
    ConvertUtils.register(new FloatConverter(null), java.lang.Float.class);
    ConvertUtils.register(new IntegerConverter(null), java.lang.Integer.class);
    ConvertUtils.register(new LongConverter(null), java.lang.Long.class);
    ConvertUtils.register(new ShortConverter(null), java.lang.Short.class);
    }
    }

    protected void initServlet()
    throws ServletException
    {
    servletName = getServletConfig().getServletName();
    Digester digester = new Digester();
    digester.push(this);
    digester.setNamespaceAware(true);
    digester.setValidating(false);
    for(int i = 0; i < registrations.length; i += 2)
    {
    URL url = getClass().getResource(registrations[i + 1]);
    if(url != null)
    digester.register(registrations, 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");
    if(input == null)
    {
    log.error(internal.getMessage("configWebXml"));
    throw new ServletException(internal.getMessage("configWebXml"));
    }
    try
    {
    digester.parse(input);
    }
    catch(IOException e)
    {
    log.error(internal.getMessage("configWebXml"), e);
    throw new ServletException(e);
    }
    catch(SAXException e)
    {
    log.error(internal.getMessage("configWebXml"), e);
    throw new ServletException(e);
    }
    finally
    {
    try
    {
    input.close();
    }
    catch(IOException e)
    {
    log.error(internal.getMessage("configWebXml"), e);
    throw new ServletException(e);
    }
    }
    if(log.isDebugEnabled())
    log.debug("Mapping for servlet '" + servletName + "' = '" + servletMapping + "'");
    if(servletMapping != null)
    getServletContext().setAttribute("org.apache.struts.action.SERVLET_MAPPING", servletMapping);
    }

    protected void process(HttpServletRequest request, HttpServletResponse response)
    throws IOException, ServletException
    {
    ModuleUtils.getInstance().selectModule(request, getServletContext());
    getRequestProcessor(getModuleConfig(request)).process(request, response);
    }

    protected String config;
    protected Digester configDigester;
    protected boolean convertNull;
    protected FastHashMap dataSources;
    protected MessageResources internal;
    protected String internalName;
    protected static Log log;
    protected RequestProcessor processor;
    protected String registrations[] = {
    "-//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", "-//Apache Software Foundation//DTD Struts Configuration 1.2//EN", "/org/apache/struts/resources/struts-config_1_2.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;
    protected String servletName;

    static
    {
    log = LogFactory.getLog(org.apache.struts.action.ActionServlet.class);
    }
    }




    Regards
    Sachin
  4. Hi Sachin,

    Dont panic man !
    Everybody goes thru this pain sometime or the other. Actually Struts has a concept of datasource manager whic creates a pool of datasource connections for any database like Oracle, MS SQL, MySQL etc.

    You just need to check your settings are correct in the struts-config.xml and retrieve the connection object whereevr you may require, ideally the Action Classes like this..

    public ActionForward
           execute(ActionMapping mapping,
                   ActionForm form,
                   HttpServletRequest request,
                   HttpServletResponse response) throws Exception
    {
     javax.sql.DataSource dataSource;
     java.sql.Connection myConnection;
     try {
      dataSource = getDataSource(request);
      myConnection = dataSource.getConnection();
      // do what you wish with myConnection
     } catch (SQLException sqle) {
        getServlet().log("Connection.process", sqle);
     } finally {
        //enclose this in a finally block to make
        //sure the connection is closed
        try {
           myConnection.close();
        } catch (SQLException e) {
           getServlet().log("Connection.close", e);
        }
       }
    }


    Best is if you can view this page at the struts site. http://struts.apache.org/faqs/database.html

    Cheers and have Fun..
    VIJAY