View Javadoc
1   package org.apache.commons.jcs3.auxiliary.disk.jdbc;
2   
3   /*
4    * Licensed to the Apache Software Foundation (ASF) under one
5    * or more contributor license agreements.  See the NOTICE file
6    * distributed with this work for additional information
7    * regarding copyright ownership.  The ASF licenses this file
8    * to you under the Apache License, Version 2.0 (the
9    * "License"); you may not use this file except in compliance
10   * with the License.  You may obtain a copy of the License at
11   *
12   *   http://www.apache.org/licenses/LICENSE-2.0
13   *
14   * Unless required by applicable law or agreed to in writing,
15   * software distributed under the License is distributed on an
16   * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
17   * KIND, either express or implied.  See the License for the
18   * specific language governing permissions and limitations
19   * under the License.
20   */
21  
22  import java.sql.Connection;
23  import java.sql.DriverManager;
24  import java.util.HashSet;
25  import java.util.Map;
26  import java.util.Properties;
27  import java.util.Set;
28  import java.util.concurrent.Executors;
29  
30  import junit.framework.TestCase;
31  
32  import org.apache.commons.jcs3.engine.control.MockCompositeCacheManager;
33  import org.apache.commons.jcs3.JCS;
34  import org.apache.commons.jcs3.access.CacheAccess;
35  import org.apache.commons.jcs3.auxiliary.disk.jdbc.dsfactory.DataSourceFactory;
36  import org.apache.commons.jcs3.engine.behavior.ICacheElement;
37  import org.apache.commons.jcs3.utils.serialization.StandardSerializer;
38  import org.apache.commons.jcs3.utils.threadpool.DaemonThreadFactory;
39  
40  /**
41   * Runs basic tests for the JDBC disk cache.
42   */
43  public class JDBCDiskCacheUnitTest
44      extends TestCase
45  {
46      /** Test setup */
47      @Override
48      public void setUp()
49      {
50          JCS.setConfigFilename( "/TestJDBCDiskCache.ccf" );
51      }
52  
53      /**
54       * Test the basic JDBC disk cache functionality with a hsql backing.
55       * @throws Exception
56       */
57      public void testSimpleJDBCPutGetWithHSQL()
58          throws Exception
59      {
60          System.setProperty( "hsqldb.cache_scale", "8" );
61  
62          final String rafroot = "target";
63          final Properties p = new Properties();
64          final String driver = p.getProperty( "driver", "org.hsqldb.jdbcDriver" );
65          final String url = p.getProperty( "url", "jdbc:hsqldb:" );
66          final String database = p.getProperty( "database", rafroot + "/cache_hsql_db" );
67          final String user = p.getProperty( "user", "sa" );
68          final String password = p.getProperty( "password", "" );
69  
70          new org.hsqldb.jdbcDriver();
71          Class.forName( driver ).newInstance();
72          final Connection cConn = DriverManager.getConnection( url + database, user, password );
73  
74          HsqlSetupTableUtil.setupTABLE( cConn, "JCS_STORE2" );
75  
76          runTestForRegion( "testCache1", 200 );
77      }
78  
79      /**
80       * Adds items to cache, gets them, and removes them. The item count is more than the size of the
81       * memory cache, so items should spool to disk.
82       * <p>
83       * @param region Name of the region to access
84       * @param items
85       * @throws Exception If an error occurs
86       */
87      public void runTestForRegion( final String region, final int items )
88          throws Exception
89      {
90          final CacheAccess<String, String> jcs = JCS.getInstance( region );
91  
92  //        System.out.println( "BEFORE PUT \n" + jcs.getStats() );
93  
94          // Add items to cache
95  
96          for ( int i = 0; i <= items; i++ )
97          {
98              jcs.put( i + ":key", region + " data " + i );
99          }
100 
101 //        System.out.println( jcs.getStats() );
102 
103         Thread.sleep( 1000 );
104 
105 //        System.out.println( jcs.getStats() );
106 
107         // Test that all items are in cache
108 
109         for ( int i = 0; i <= items; i++ )
110         {
111             final String value = jcs.get( i + ":key" );
112 
113             assertEquals( "key = [" + i + ":key] value = [" + value + "]", region + " data " + i, value );
114         }
115 
116         // Test that getElements returns all the expected values
117         final Set<String> keys = new HashSet<>();
118         for ( int i = 0; i <= items; i++ )
119         {
120             keys.add( i + ":key" );
121         }
122 
123         final Map<String, ICacheElement<String, String>> elements = jcs.getCacheElements( keys );
124         for ( int i = 0; i <= items; i++ )
125         {
126             final ICacheElement<String, String> element = elements.get( i + ":key" );
127             assertNotNull( "element " + i + ":key is missing", element );
128             assertEquals( "value " + i + ":key", region + " data " + i, element.getVal() );
129         }
130 
131         // Remove all the items
132         for ( int i = 0; i <= items; i++ )
133         {
134             jcs.remove( i + ":key" );
135         }
136 
137         // Verify removal
138         for ( int i = 0; i <= items; i++ )
139         {
140             assertNull( "Removed key should be null: " + i + ":key", jcs.get( i + ":key" ) );
141         }
142     }
143 
144     /**
145      * Verfiy that it uses the pool access manager config.
146      * <p>
147      * @throws Exception
148      */
149     public void testInitializePoolAccess_withPoolName()
150         throws Exception
151     {
152         // SETUP
153         final String poolName = "testInitializePoolAccess_withPoolName";
154 
155         final String url = "jdbc:hsqldb:";
156         final String userName = "sa";
157         final String password = "";
158         final int maxActive = 10;
159         final String driverClassName = "org.hsqldb.jdbcDriver";
160 
161         final Properties props = new Properties();
162         final String prefix = JDBCDiskCacheFactory.POOL_CONFIGURATION_PREFIX
163     		+ poolName
164             + JDBCDiskCacheFactory.ATTRIBUTE_PREFIX;
165         props.put( prefix + ".url", url );
166         props.put( prefix + ".userName", userName );
167         props.put( prefix + ".password", password );
168         props.put( prefix + ".maxActive", String.valueOf( maxActive ) );
169         props.put( prefix + ".driverClassName", driverClassName );
170 
171         final JDBCDiskCacheAttributes cattr = new JDBCDiskCacheAttributes();
172         cattr.setConnectionPoolName( poolName );
173         cattr.setTableName("JCSTESTTABLE_InitializePoolAccess");
174 
175         final MockCompositeCacheManager compositeCacheManager = new MockCompositeCacheManager();
176         compositeCacheManager.setConfigurationProperties( props );
177         final JDBCDiskCacheFactory dcFactory = new JDBCDiskCacheFactory();
178         dcFactory.initialize();
179         dcFactory.setScheduledExecutorService(Executors.newScheduledThreadPool(2,
180         	new DaemonThreadFactory("JCS-JDBCDiskCacheManager-", Thread.MIN_PRIORITY)));
181 
182         final JDBCDiskCache<String, String> diskCache = dcFactory.createCache( cattr, compositeCacheManager, null, new StandardSerializer() );
183         assertNotNull( "Should have a cache instance", diskCache );
184 
185         // DO WORK
186         final DataSourceFactory result = dcFactory.getDataSourceFactory(cattr, props);
187 
188         // VERIFY
189         assertNotNull( "Should have a data source factory class", result );
190         assertEquals( "wrong name", poolName, result.getName() );
191 
192         System.setProperty( "hsqldb.cache_scale", "8" );
193 
194         final String rafroot = "target";
195         final String database = rafroot + "/cache_hsql_db";
196 
197         new org.hsqldb.jdbcDriver();
198         Class.forName( driverClassName ).newInstance();
199         final Connection cConn = DriverManager.getConnection( url + database, userName, password );
200 
201         HsqlSetupTableUtil.setupTABLE( cConn, "JCSTESTTABLE_InitializePoolAccess" );
202 
203     }
204 }