You are viewing a plain text version of this content. The canonical link for it is here.
Posted to dev@commons.apache.org by jm...@apache.org on 2004/02/05 04:23:16 UTC

cvs commit: jakarta-commons-sandbox/resources/contrib/jdbc/src/java/org/apache/commons/resources/impl JDBCResources.java JDBCResourcesFactory.java

jmitchell    2004/02/04 19:23:16

  Added:       resources/contrib/jdbc/src/java/org/apache/commons/resources/impl
                        JDBCResources.java JDBCResourcesFactory.java
  Log:
  New JDBC Resources implementation
  
  Revision  Changes    Path
  1.1                  jakarta-commons-sandbox/resources/contrib/jdbc/src/java/org/apache/commons/resources/impl/JDBCResources.java
  
  Index: JDBCResources.java
  ===================================================================
  /*
   * $Header: /home/cvs/jakarta-commons-sandbox/resources/contrib/jdbc/src/java/org/apache/commons/resources/impl/JDBCResources.java,v 1.1 2004/02/05 03:23:16 jmitchell Exp $
   * $Revision: 1.1 $
   * $Date: 2004/02/05 03:23:16 $
   *
   * ====================================================================
   *
   * The Apache Software License, Version 1.1
   *
   * Copyright (c) 1999-2003 The Apache Software Foundation.  All rights
   * reserved.
   *
   * Redistribution and use in source and binary forms, with or without
   * modification, are permitted provided that the following conditions
   * are met:
   *
   * 1. Redistributions of source code must retain the above copyright
   *    notice, this list of conditions and the following disclaimer.
   *
   * 2. Redistributions in binary form must reproduce the above copyright
   *    notice, this list of conditions and the following disclaimer in
   *    the documentation and/or other materials provided with the
   *    distribution.
   *
   * 3. The end-user documentation included with the redistribution, if
   *    any, must include the following acknowledgement:
   *       "This product includes software developed by the
   *        Apache Software Foundation (http://www.apache.org/)."
   *    Alternately, this acknowledgement may appear in the software itself,
   *    if and wherever such third-party acknowledgements normally appear.
   *
   * 4. The names, "Apache", "The Jakarta Project", "Commons", and "Apache Software
   *    Foundation" must not be used to endorse or promote products derived
   *    from this software without prior written permission. For written
   *    permission, please contact apache@apache.org.
   *
   * 5. Products derived from this software may not be called "Apache"
   *    nor may "Apache" appear in their name, without prior written
   *    permission of the Apache Software Foundation.
   *
   * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED
   * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
   * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
   * DISCLAIMED.  IN NO EVENT SHALL THE APACHE SOFTWARE FOUNDATION OR
   * ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
   * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
   * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF
   * USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
   * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
   * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
   * OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
   * SUCH DAMAGE.
   * ====================================================================
   *
   * This software consists of voluntary contributions made by many
   * individuals on behalf of the Apache Software Foundation.  For more
   * information on the Apache Software Foundation, please see
   * <http://www.apache.org/>.
   *
   */
  
  package org.apache.commons.resources.impl;
  
  import java.io.FileNotFoundException;
  import java.io.IOException;
  import java.io.InputStream;
  import java.net.URL;
  import java.sql.Connection;
  import java.sql.DriverManager;
  import java.sql.PreparedStatement;
  import java.sql.ResultSet;
  import java.sql.SQLException;
  import java.util.Locale;
  import java.util.Map;
  import java.util.Properties;
  
  import org.apache.commons.logging.Log;
  import org.apache.commons.logging.LogFactory;
  import org.apache.commons.resources.ResourcesException;
  
  /**
   * <p>Concrete implementation of 
   * {@link org.apache.commons.resources.Resources} that wraps a 
   * JDBC database connection and retrieves values for the given 
   * <code>Locale</code> and have name suffixes reflecting the 
   * <code>Locale</code> for which the document's messages apply.
   * For this specific implementation, resources are looked up in 
   * a hierarchy of database values in a manner identical to that 
   * performed by <code>java.util.ResourceBundle.getBundle().</code>.
   * 
   * </p>
   *
   * <p>The base URL passed to our constructor must contain the base name
   * of a properties file that holds the JDBC datasource configuration.</p>
   * 
   * <p>
   * The expected format of the required properties file might look like this:<br>
   * <code><pre>
   * jdbc.connect.driver               = org.gjt.mm.mysql.Driver
   * jdbc.connect.url                  = jdbc:mysql://localhost/resources
   * jdbc.connect.login                = resourcesTest
   * jdbc.connect.password             = resourcesTest
   * 
   * jdbc.sql.db                       = resources
   * jdbc.sql.table                    = resources
   * jdbc.sql.locale.column            = locale
   * jdbc.sql.key.column               = msgKey
   * jdbc.sql.val.column               = val
   * 
   * org.apache.commons.resource.CACHE = true
   * 
   * </pre></code>
   * 
   * </p>
   *
   * @author James Mitchell
   * @version $Revision: 1.1 $ $Date: 2004/02/05 03:23:16 $
   */
  public class JDBCResources extends CollectionResourcesBase {
  
      /**
       * <p>The <code>Log</code> instance for this class.</p>
       */
      private static final Log log = LogFactory.getLog(JDBCResources.class);
  
      Connection con = null;
  
      // ----------------------------------------------------------- Constructors
  
      /**
       * <p>Create a new 
       * {@link org.apache.commons.resources.Resources} instance with the specified
       * logical name and base resource URL.</p>
       *
       * @param name Logical name of the new instance
       * @param base Base URL of the JDBC configuration properties.
       */
      public JDBCResources(String name, String base) {
          super(name, base);
      }
  
  
      // ------------------------------------------------------ Protected Methods
  
  
      /**
       * <p>Return a <code>Map</code> containing the name-value mappings for
       * the specified base URL and requested <code>Locale</code>, if there
       * are any.  If there are no defined mappings for the specified
       * <code>Locale</code>, return an empty <code>Map</code> instead.</p>
       *
       * <p>Concrete subclasses must override this method to perform the
       * appropriate lookup.  A typical implementation will construct an
       * absolute URL based on the specified base URL and <code>Locale</code>,
       * retrieve the specified resource file (if any), and parse it into
       * a <code>Map</code> structure.</p>
       *
       * <p>Caching of previously retrieved <code>Map</code>s (if any) should
       * be performed by callers of this method.  Therefore, this method should
       * always attempt to retrieve the specified resource and load it
       * appropriately.</p>
       *
       * @param baseUrl Base URL of the resource files for this 
       * {@link org.apache.commons.resources.Resources} instance
       * @param locale <code>Locale</code> for which name-value mappings
       *  are requested
       */
      protected Map getLocaleMap(String baseUrl, Locale locale) {
  
          if (log.isDebugEnabled()) {
              log.debug("Loading database configuration'" + locale + "' resources from base '" +
                      baseUrl + "'");
          }
  
          Properties props = new Properties();
          //getLocaleSuffix(locale) + 
          String name = baseUrl + ".properties";
          InputStream stream = null;
  
          try {
  
              // Open an input stream to the URL for this locale (if any)
              if (log.isTraceEnabled()) {
                  log.trace("Absolute URL is '" + name + "'");
              }
              URL url = new URL(name);
              stream = url.openStream();
  
              // Parse the input stream and populate the name-value mappings map
              if (log.isTraceEnabled()) {
                  log.trace("Parsing input resource");
              }
              props.load(stream);
  
          } catch (FileNotFoundException e) {
  
              // Log and swallow this exception
              if (log.isDebugEnabled()) {
                  log.debug("No resources for locale '" + locale +
                            "' from base '" + baseUrl + "'");
              }
              props.clear();
  
          } catch (IOException e) {
  
              log.warn("IOException loading locale '" + locale +
                       "' from base '" + baseUrl + "'", e);
              props.clear();
  
          } finally {
  
              // Close the input stream that was opened earlier
              if (stream != null) {
                  try {
                      stream.close();
                  } catch (IOException e) {
                      log.error("Error closing stream.", e);
                  }
                  stream = null;
              }
  
          }
  
          // Return the populated (or empty) properties
          Properties properties = new Properties();
  		try {
  	        properties = loadData(locale, props);
  	        
  		} catch (InstantiationException e) {
              log.warn("InstantiationException: locale= '" + locale +
                       "' base= '" + baseUrl + "'", e);
          } catch (IllegalAccessException e) {
              log.warn("IllegalAccessException: locale= '" + locale +
                      "' base= '" + baseUrl + "'", e);
          } catch (ClassNotFoundException e) {
              log.warn("Specified Driver not found, make sure it is on " +
              		"the classpath: locale= '" + locale +
                      "' base= '" + baseUrl + "'", e);
          } catch (SQLException e) {
              log.warn("SQLException: locale= '" + locale +
                      "' base= '" + baseUrl + "'", e);
          }
          return properties;
  
          
  
      }
  
      /**
       * @param locale <code>Locale</code> for which name-value mappings
       *  are requested
       * @param connectionProps The connection properties used to instantiate
       * a JDBC connection.
       */
      private Properties loadData(Locale locale, Properties connectionProps) 
      	throws InstantiationException, IllegalAccessException, 
      	ClassNotFoundException, SQLException {
          
          String driver = connectionProps.getProperty("jdbc.connect.driver");
          String url    = connectionProps.getProperty("jdbc.connect.url");
          String user = connectionProps.getProperty("jdbc.connect.login");
          String pass = connectionProps.getProperty("jdbc.connect.password");
          
          String db    = connectionProps.getProperty("jdbc.sql.db");
          String table = connectionProps.getProperty("jdbc.sql.table");
          String localeColumn = connectionProps.getProperty("jdbc.sql.locale.column");
          String keyColumn    = connectionProps.getProperty("jdbc.sql.key.column");
          String valColumn    = connectionProps.getProperty("jdbc.sql.val.column");
          Properties pairs = new Properties();
          
              Class.forName(driver).newInstance();
      		con = DriverManager.getConnection(url);
      		
      		String query = "SELECT " + keyColumn + ", " + valColumn + 
      				" FROM " + table + " where " + localeColumn + "= '" + locale + "'";
      		PreparedStatement stmt = con.prepareStatement(query);
      		ResultSet rs = stmt.executeQuery();
      		
      		while (rs.next()) {
      		    pairs.put(rs.getString(keyColumn), rs.getString(valColumn));
      		}
          
          return pairs;
      }
  
  
      public void init() throws ResourcesException {
          super.init();
      }
  }
  
  
  
  1.1                  jakarta-commons-sandbox/resources/contrib/jdbc/src/java/org/apache/commons/resources/impl/JDBCResourcesFactory.java
  
  Index: JDBCResourcesFactory.java
  ===================================================================
  /*
   * $Header: /home/cvs/jakarta-commons-sandbox/resources/contrib/jdbc/src/java/org/apache/commons/resources/impl/JDBCResourcesFactory.java,v 1.1 2004/02/05 03:23:16 jmitchell Exp $
   * $Revision: 1.1 $
   * $Date: 2004/02/05 03:23:16 $
   *
   * ====================================================================
   *
   * The Apache Software License, Version 1.1
   *
   * Copyright (c) 1999-2003 The Apache Software Foundation.  All rights
   * reserved.
   *
   * Redistribution and use in source and binary forms, with or without
   * modification, are permitted provided that the following conditions
   * are met:
   *
   * 1. Redistributions of source code must retain the above copyright
   *    notice, this list of conditions and the following disclaimer.
   *
   * 2. Redistributions in binary form must reproduce the above copyright
   *    notice, this list of conditions and the following disclaimer in
   *    the documentation and/or other materials provided with the
   *    distribution.
   *
   * 3. The end-user documentation included with the redistribution, if
   *    any, must include the following acknowledgement:
   *       "This product includes software developed by the
   *        Apache Software Foundation (http://www.apache.org/)."
   *    Alternately, this acknowledgement may appear in the software itself,
   *    if and wherever such third-party acknowledgements normally appear.
   *
   * 4. The names, "Apache", "The Jakarta Project", "Commons", and "Apache Software
   *    Foundation" must not be used to endorse or promote products derived
   *    from this software without prior written permission. For written
   *    permission, please contact apache@apache.org.
   *
   * 5. Products derived from this software may not be called "Apache"
   *    nor may "Apache" appear in their name, without prior written
   *    permission of the Apache Software Foundation.
   *
   * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED
   * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
   * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
   * DISCLAIMED.  IN NO EVENT SHALL THE APACHE SOFTWARE FOUNDATION OR
   * ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
   * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
   * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF
   * USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
   * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
   * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
   * OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
   * SUCH DAMAGE.
   * ====================================================================
   *
   * This software consists of voluntary contributions made by many
   * individuals on behalf of the Apache Software Foundation.  For more
   * information on the Apache Software Foundation, please see
   * <http://www.apache.org/>.
   *
   */
  
  package org.apache.commons.resources.impl;
  
  import org.apache.commons.resources.Resources;
  import org.apache.commons.resources.ResourcesException;
  
  /**
   * <p>Concrete implementation of 
   * {@link org.apache.commons.resources.ResourcesFactory} that creates
   * {@link org.apache.commons.resources.Resources} instances that wraps 
   * a JDBC database connection and retrieves values for the given 
   * <code>Locale</code> and have name suffixes reflecting the 
   * <code>Locale</code> for which the document's messages apply.
   * For this specific implementation, resources are looked up in 
   * a hierarchy of database values in a manner identical to that 
   * performed by <code>java.util.ResourceBundle.getBundle().</code>.
   *
   * @author James Mitchell
   * @version $Revision: 1.1 $
   */
  public class JDBCResourcesFactory extends ResourcesFactoryBase {
  
  
      // ------------------------------------------------------ Protected Methods
  
  
      /**
       * <p>Create and return a new {@link org.apache.commons.resources.Resources} 
       * instance with the specified logical name, after calling its <code>init()</code>
       * method and delegating the relevant properties.</p>
       *
       * @param name Logical name of the {@link org.apache.commons.resources.Resources} 
       * instance to create
       * 
       * @param config Configuration string for this resource (if any)
       *
       * @exception ResourcesException if a {@link org.apache.commons.resources.Resources} 
       * instance of the specified logical name cannot be created.
       */
      protected Resources createResources(String name, String config)
          throws ResourcesException {
  
          Resources res = new JDBCResources(name, config);
          res.setReturnNull(isReturnNull());
          res.init();
          return (res);
  
      }
  
  
  }
  
  
  

---------------------------------------------------------------------
To unsubscribe, e-mail: commons-dev-unsubscribe@jakarta.apache.org
For additional commands, e-mail: commons-dev-help@jakarta.apache.org