KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > org > apache > derbyTesting > junit > TestConfiguration


1 /*
2  *
3  * Derby - Class TestConfiguration
4  *
5  * Licensed to the Apache Software Foundation (ASF) under one or more
6  * contributor license agreements. See the NOTICE file distributed with
7  * this work for additional information regarding copyright ownership.
8  * The ASF licenses this file to You under the Apache License, Version 2.0
9  * (the "License"); you may not use this file except in compliance with
10  * 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 KIND,
17  * either express or implied. See the License for the specific
18  * language governing permissions and limitations under the License.
19  */

20 package org.apache.derbyTesting.junit;
21
22 import java.io.File JavaDoc;
23 import java.lang.reflect.Method JavaDoc;
24 import java.security.*;
25 import java.sql.Connection JavaDoc;
26 import java.sql.DriverManager JavaDoc;
27 import java.sql.SQLException JavaDoc;
28 import java.util.Properties JavaDoc;
29
30 import junit.framework.Test;
31 import junit.framework.TestCase;
32
33 import org.apache.derbyTesting.functionTests.util.TestDataSourceFactory;
34
35 /**
36  * Class which holds information about the configuration of a Test.
37  */

38 public class TestConfiguration {
39     /**
40      * Default values for configurations
41      */

42     private final static String JavaDoc DEFAULT_DBNAME = "wombat";
43     private final static String JavaDoc DEFAULT_USER_NAME = "APP";
44     private final static String JavaDoc DEFAULT_USER_PASSWORD = "APP";
45     private final static int DEFAULT_PORT = 1527;
46     private final static String JavaDoc DEFAULT_FRAMEWORK = "embedded";
47     private final static String JavaDoc DEFAULT_HOSTNAME = "localhost";
48             
49     /**
50      * Keys to use to look up values in properties files.
51      */

52     private final static String JavaDoc KEY_DBNAME = "databaseName";
53     private final static String JavaDoc KEY_FRAMEWORK = "framework";
54     private final static String JavaDoc KEY_USER_PASSWORD = "password";
55     private final static String JavaDoc KEY_USER_NAME = "user";
56     private final static String JavaDoc KEY_HOSTNAME = "hostName";
57     private final static String JavaDoc KEY_PORT = "port";
58     private final static String JavaDoc KEY_VERBOSE = "derby.tests.debug";
59     private final static String JavaDoc KEY_SINGLE_LEG_XA = "derbyTesting.xa.single";
60
61     /**
62      * Possible values of system properties.
63      */

64     private final static String JavaDoc UNUSED = "file://unused/";
65
66
67     /**
68      * Default Derby test configuration object based
69      * upon system properties set by the old harness.
70      */

71     private static final TestConfiguration DERBY_HARNESS_CONFIG =
72         new TestConfiguration(getSystemProperties());
73     
74     /**
75      * Default configuration for standalone JUnit tests,
76      * an embedded configuration.
77      */

78     private static final TestConfiguration JUNIT_CONFIG
79         = new TestConfiguration();
80     
81     /**
82      * The default configuration.
83      */

84     private static final TestConfiguration DEFAULT_CONFIG;
85     
86     /**
87      * Are we running in the harness, assume so if framework
88      * was set so the
89      */

90     private static final boolean runningInDerbyHarness;
91     
92     static {
93         boolean assumeHarness = false;
94         
95         // In the harness if the default configuration according
96
// to system properties is not embedded.
97
if (!DERBY_HARNESS_CONFIG.getJDBCClient().isEmbedded())
98             assumeHarness = true;
99         
100         // Assume harness if database name is not default
101
if (!DERBY_HARNESS_CONFIG.getDatabaseName().equals(DEFAULT_DBNAME))
102             assumeHarness = true;
103         
104         // Assume harness if user name is not default
105
if (!DERBY_HARNESS_CONFIG.getUserName().equals(DEFAULT_USER_NAME))
106             assumeHarness = true;
107         
108         // If derby.system.home set externally at startup assume
109
// running in harness
110
if (BaseTestCase.getSystemProperty("derby.system.home") != null)
111             assumeHarness = true;
112         
113         // for now always assume harness - still testing this code
114
assumeHarness = true;
115
116         DEFAULT_CONFIG = assumeHarness ? DERBY_HARNESS_CONFIG : JUNIT_CONFIG;
117         runningInDerbyHarness = assumeHarness;
118         
119         if (!assumeHarness) {
120             File JavaDoc dsh = new File JavaDoc("system");
121
122             BaseTestCase.setSystemProperty("derby.system.home",
123                     dsh.getAbsolutePath());
124         }
125      }
126     
127     /**
128      * Current configuration is stored in a ThreadLocal to
129      * allow the potential for multiple tests to be running
130      * concurrently with different configurations.
131      */

132     private static final ThreadLocal JavaDoc CURRENT_CONFIG = new ThreadLocal JavaDoc() {
133         protected Object JavaDoc initialValue() {
134             return DEFAULT_CONFIG;
135         }
136     };
137    
138     /**
139      * Get this Thread's current configuraiton for running
140      * the tests.
141      * @return TestConfiguration to use.
142      */

143     public static TestConfiguration getCurrent() {
144         return (TestConfiguration) CURRENT_CONFIG.get();
145     }
146     
147     /**
148      * WORK IN PROGRESS
149      * Set this Thread's current configuration for running tests.
150      * @param config Configuration to set it to.
151      */

152     static void setCurrent(TestConfiguration config)
153     {
154         CURRENT_CONFIG.set(config);
155     }
156     /**
157      * Return a decorator for the passed in tests that sets the
158      * configuration for the client to be Derby's JDBC client
159      * and to start the network server at setUp and shut it
160      * down at tearDown.
161      * <BR>
162      * The database configuration (name etc.) is based upon
163      * the previous configuration.
164      * <BR>
165      * The previous TestConfiguration is restored at tearDown.
166      * @param tests
167      * @return
168      * @throws Exception
169      */

170     public static Test derbyClientServerDecorator(Class JavaDoc suite) throws Exception JavaDoc
171     {
172         TestConfiguration config = TestConfiguration.getCurrent();
173         
174         TestConfiguration derbyClientConfig =
175             new TestConfiguration(config, JDBCClient.DERBYNETCLIENT,
176                     DEFAULT_HOSTNAME, DEFAULT_PORT);
177         
178         TestConfiguration.setCurrent(derbyClientConfig);
179         
180         Test test = addSuiteByReflection(suite);
181         
182         TestConfiguration.setCurrent(config);
183             
184         test = new NetworkServerTestSetup(test);
185             
186         return new ChangeConfigurationSetup(derbyClientConfig, test);
187
188     }
189     private static Test addSuiteByReflection(Class JavaDoc clz) throws Exception JavaDoc
190     {
191         Method JavaDoc sm = clz.getMethod("suite", null);
192               
193         return (Test) sm.invoke(null, null);
194     }
195     
196     public static Test changeUserDecorator(Test test, String JavaDoc user, String JavaDoc password)
197     {
198         return new ChangeUserSetup(test, user, password);
199     }
200     /**
201      * Default embedded configuration
202      *
203      */

204     private TestConfiguration() {
205         this.dbName = DEFAULT_DBNAME;
206         this.userName = DEFAULT_USER_NAME;
207         this.userPassword = DEFAULT_USER_PASSWORD;
208         this.hostName = null;
209         this.port = -1;
210         this.singleLegXA = false;
211         
212         this.jdbcClient = JDBCClient.EMBEDDED;
213         url = createJDBCUrlWithDatabaseName(dbName);
214  
215     }
216
217     private TestConfiguration(TestConfiguration copy, JDBCClient client,
218             String JavaDoc hostName, int port)
219     {
220         this.dbName = copy.dbName;
221         this.userName = copy.userName;
222         this.userPassword = copy.userPassword;
223
224         this.isVerbose = copy.isVerbose;
225         this.singleLegXA = copy.singleLegXA;
226         this.port = port;
227         
228         this.jdbcClient = client;
229         this.hostName = hostName;
230         
231         this.url = createJDBCUrlWithDatabaseName(dbName);
232     }
233
234     
235     /**
236      * Obtain a new configuration identical to the passed in
237      * one except for the default user and password.
238      * @param copy Configuration to copy.
239      * @param user New default user
240      * @param password New default password.
241      */

242     TestConfiguration(TestConfiguration copy, String JavaDoc user, String JavaDoc password)
243     {
244         this.dbName = copy.dbName;
245         this.userName = user;
246         this.userPassword = password;
247
248         this.isVerbose = copy.isVerbose;
249         this.singleLegXA = copy.singleLegXA;
250         this.port = copy.port;
251         
252         this.jdbcClient = copy.jdbcClient;
253         this.hostName = copy.hostName;
254         
255         this.url = copy.url;
256     }
257
258     /**
259      * This constructor creates a TestConfiguration from a Properties object.
260      *
261      * @throws NumberFormatException if the port specification is not an integer.
262      */

263     private TestConfiguration(Properties JavaDoc props)
264         throws NumberFormatException JavaDoc {
265
266         dbName = props.getProperty(KEY_DBNAME, DEFAULT_DBNAME);
267         userName = props.getProperty(KEY_USER_NAME, DEFAULT_USER_NAME);
268         userPassword = props.getProperty(KEY_USER_PASSWORD,
269                                          DEFAULT_USER_PASSWORD);
270         hostName = props.getProperty(KEY_HOSTNAME, DEFAULT_HOSTNAME);
271         isVerbose = Boolean.valueOf(props.getProperty(KEY_VERBOSE)).booleanValue();
272         String JavaDoc portStr = props.getProperty(KEY_PORT);
273         singleLegXA = Boolean.valueOf(props.getProperty(KEY_SINGLE_LEG_XA)
274                             ).booleanValue();
275         if (portStr != null) {
276             try {
277                 port = Integer.parseInt(portStr);
278             } catch (NumberFormatException JavaDoc nfe) {
279                 // We lose stacktrace here, but it is not important.
280
throw new NumberFormatException JavaDoc(
281                         "Port number must be an integer. Value: " + portStr);
282             }
283         } else {
284             port = DEFAULT_PORT;
285         }
286         
287         String JavaDoc framework = props.getProperty(KEY_FRAMEWORK, DEFAULT_FRAMEWORK);
288         
289         if ("DerbyNetClient".equals(framework)) {
290             jdbcClient = JDBCClient.DERBYNETCLIENT;
291         } else if ("DerbyNet".equals(framework)) {
292             jdbcClient = JDBCClient.DB2CLIENT;
293         } else {
294             jdbcClient = JDBCClient.EMBEDDED;
295         }
296         url = createJDBCUrlWithDatabaseName(dbName);
297     }
298
299     /**
300      * Get the system properties in a privileged block.
301      *
302      * @return the system properties.
303      */

304     private static final Properties JavaDoc getSystemProperties() {
305         // Fetch system properties in a privileged block.
306
Properties JavaDoc sysProps = (Properties JavaDoc)AccessController.doPrivileged(
307                 new PrivilegedAction() {
308                     public Object JavaDoc run() {
309                         return System.getProperties();
310                     }
311                 });
312         return sysProps;
313     }
314
315     /**
316      * Create JDBC connection url, including the name of the database.
317      *
318      * @return JDBC connection url, without attributes.
319      */

320     private String JavaDoc createJDBCUrlWithDatabaseName(String JavaDoc name) {
321         if (jdbcClient == JDBCClient.EMBEDDED) {
322             return jdbcClient.getUrlBase() + name;
323         } else {
324             return jdbcClient.getUrlBase() + hostName + ":" + port + "/" + name;
325         }
326     }
327
328     /**
329      * Get configured JDBCClient object.
330      *
331      * @return JDBCClient
332      */

333     public JDBCClient getJDBCClient() {
334         return jdbcClient;
335     }
336     
337     
338     /**
339      * Return the jdbc url for connecting to the default database.
340      *
341      * @return JDBC url.
342      */

343     public String JavaDoc getJDBCUrl() {
344         return url;
345     }
346
347     /**
348      * Return the jdbc url for a connecting to the database.
349      *
350      * @param databaseName name of database.
351      * @return JDBC connection url, including database name.
352      */

353     public String JavaDoc getJDBCUrl(String JavaDoc databaseName) {
354         return createJDBCUrlWithDatabaseName(databaseName);
355     }
356     
357     /**
358      * Return the default database name.
359      *
360      * @return default database name.
361      */

362     public String JavaDoc getDatabaseName() {
363         return dbName;
364     }
365     
366     /**
367      * Return the user name.
368      *
369      * @return user name.
370      */

371     public String JavaDoc getUserName() {
372         return userName;
373     }
374     
375     /**
376      * Return the user password.
377      *
378      * @return user password.
379      */

380     public String JavaDoc getUserPassword() {
381         return userPassword;
382     }
383
384     /**
385      * Return the host name for the network server.
386      *
387      * @return host name.
388      */

389     public String JavaDoc getHostName() {
390         return hostName;
391     }
392
393     /**
394      * Get port number for network server.
395      *
396      * @return port number.
397      */

398     public int getPort() {
399         return port;
400     }
401     
402     /**
403      * Open connection to the default database.
404      * If the database does not exist, it will be created.
405      * A default username and password will be used for the connection.
406      *
407      * @return connection to default database.
408      */

409     public Connection JavaDoc openDefaultConnection()
410         throws SQLException JavaDoc {
411         return getDefaultConnection("create=true");
412     }
413     
414     /**
415      * Open a connection to a database.
416      * If the database does not exist, it will be created.
417      * A default username and password will be used for the connection.
418      *
419      * @param databaseName database to connect to
420      *
421      * @return connection to database.
422      */

423     public Connection JavaDoc openConnection (String JavaDoc databaseName) throws SQLException JavaDoc {
424         return getConnection(databaseName, "create=true");
425     }
426     
427     /**
428      * Get a connection to the default database using the specified connection
429      * attributes.
430      *
431      * @param connAttrs connection attributes
432      * @return connection to database.
433      * @throws SQLException
434      */

435     public Connection JavaDoc getDefaultConnection(String JavaDoc connAttrs)
436         throws SQLException JavaDoc {
437         return getConnection(getDatabaseName(), connAttrs);
438     }
439     
440     /**
441      * Get a connection to a database using the specified connection
442      * attributes.
443      *
444      * @param databaseName database to connect to
445      * @param connAttrs connection attributes
446      * @return connection to database.
447      * @throws SQLException
448      */

449     public Connection JavaDoc getConnection (String JavaDoc databaseName, String JavaDoc connAttrs)
450         throws SQLException JavaDoc {
451         Connection JavaDoc con = null;
452         JDBCClient client =getJDBCClient();
453         if (JDBC.vmSupportsJDBC2()) {
454             loadJDBCDriver(client.getJDBCDriverName());
455             if (!isSingleLegXA()) {
456                 con = DriverManager.getConnection(
457                         getJDBCUrl(databaseName) + ";" + connAttrs,
458                         getUserName(),
459                         getUserPassword());
460             }
461             else {
462                 Properties JavaDoc attrs =
463                     getDataSourcePropertiesForDatabase(databaseName, connAttrs);
464                 con = TestDataSourceFactory.getXADataSource(attrs).
465                         getXAConnection (getUserName(),
466                         getUserPassword()).getConnection();
467             }
468         } else {
469             //Use DataSource for JSR169
470
Properties JavaDoc attrs = getDataSourcePropertiesForDatabase(databaseName, connAttrs);
471             con = TestDataSourceFactory.getDataSource(attrs).getConnection();
472         }
473         return con;
474     }
475     
476     /**
477      * Set the verbosity, i.e., whether debug statements print.
478      */

479     public void setVerbosity( boolean isChatty ) { isVerbose = isChatty; }
480     
481     /**
482      * Return verbose flag.
483      *
484      * @return verbose flag.
485      */

486     public boolean isVerbose() {
487         return isVerbose;
488     }
489
490     /**
491      * <p>
492      * Return true if we classes are being loaded from jar files. For the time
493      * being, this simply tests that the JVMInfo class (common to the client and
494      * the server) comes out of a jar file.
495      * </p>
496      */

497     public static boolean loadingFromJars()
498     {
499         return SecurityManagerSetup.isJars;
500     }
501     
502     /**
503      * Is this JUnit test being run by the old harness.
504      * Temp method to ease the switch over by allowing
505      * suites to alter their behaviour based upon the
506      * need to still run under the old harness.
507      * @return
508      */

509     public static boolean runningInDerbyHarness()
510     {
511         return runningInDerbyHarness;
512     }
513
514     /**
515      * Return if it has to run under single legged xa transaction
516      * @return singleLegXA
517      */

518     public boolean isSingleLegXA () {
519         return singleLegXA;
520     }
521     
522     /**
523      * Get a folder already created where a test can
524      * write its failure information. The name of the folder,
525      * relative to ${user.dir} is:
526      * <BR>
527      * <code>
528      * fail/client/testclass/testname
529      * <code>
530      * <UL>
531      * <LI> client - value of JDBCClient.getName() for the test's configuration
532      * <LI> testclass - last element of the class name
533      * <LI> testname - value of test.getName()
534      * </UL>
535      */

536     File JavaDoc getFailureFolder(TestCase test){
537         
538         StringBuffer JavaDoc sb = new StringBuffer JavaDoc();
539       
540         sb.append("fail");
541         sb.append(File.separatorChar);
542         sb.append(getJDBCClient().getName());
543         sb.append(File.separatorChar);
544         
545         String JavaDoc className = test.getClass().getName();
546         int lastDot = className.lastIndexOf('.');
547         if (lastDot != -1)
548             className = className.substring(lastDot+1, className.length());
549         
550         sb.append(className);
551         sb.append(File.separatorChar);
552         sb.append(test.getName());
553         
554         String JavaDoc base = sb.toString().intern();
555         final File JavaDoc folder = new File JavaDoc(base);
556         
557         // Create the folder
558
// TODO: Dump this configuration in some human readable format
559
synchronized (base) {
560             
561             AccessController.doPrivileged
562             (new java.security.PrivilegedAction JavaDoc(){
563                 public Object JavaDoc run(){
564                     if (folder.exists()) {
565                         // do something
566
}
567                     return new Boolean JavaDoc(folder.mkdirs());
568                 }
569             }
570              );
571         }
572                
573         return folder;
574         
575     }
576     
577     /**
578      * Immutable data members in test configuration
579      */

580     private final String JavaDoc dbName;
581     private final String JavaDoc url;
582     private final String JavaDoc userName;
583     private final String JavaDoc userPassword;
584     private final int port;
585     private final String JavaDoc hostName;
586     private final JDBCClient jdbcClient;
587     private boolean isVerbose;
588     private final boolean singleLegXA;
589     
590
591     /**
592      * Generate properties which can be set on a
593      * <code>DataSource</code> in order to connect to the default
594      * database. If the database does not exist, it will be created.
595      *
596      * @return a <code>Properties</code> object containing server
597      * name, port number, database name and other attributes needed to
598      * connect to the default database
599      */

600     public static Properties JavaDoc getDefaultDataSourceProperties() {
601         return getDataSourcePropertiesForDatabase(
602                 getCurrent().getDatabaseName(), "create=true");
603     }
604     
605     /**
606      * Generate properties which can be set on a <code>DataSource</code>
607      * in order to connect to a database using the specified connection
608      * attributes.
609      *
610      * @param databaseName database to connect to
611      * @param connAttrs connection attributes
612      * @return
613      */

614     public static Properties JavaDoc getDataSourcePropertiesForDatabase
615         (String JavaDoc databaseName, String JavaDoc connAttrs)
616     {
617         Properties JavaDoc attrs = new Properties JavaDoc();
618         if (!(getCurrent().getJDBCClient() == JDBCClient.EMBEDDED)) {
619             attrs.setProperty("serverName", getCurrent().getHostName());
620             attrs.setProperty("portNumber", Integer.toString(getCurrent().getPort()));
621         }
622         attrs.setProperty("databaseName", databaseName);
623         attrs.setProperty("connectionAttributes", connAttrs);
624         return attrs;
625     }
626
627     /**
628      * Load the specified JDBC driver
629      *
630      * @param driverClass name of the JDBC driver class.
631      * @throws SQLException if loading the driver fails.
632      */

633     private static void loadJDBCDriver(String JavaDoc driverClass)
634         throws SQLException JavaDoc {
635         try {
636             Class.forName(driverClass).newInstance();
637         } catch (ClassNotFoundException JavaDoc cnfe) {
638             throw new SQLException JavaDoc("Failed to load JDBC driver '" +
639                                     driverClass + "': " + cnfe.getMessage());
640         } catch (IllegalAccessException JavaDoc iae) {
641             throw new SQLException JavaDoc("Failed to load JDBC driver '" +
642                                     driverClass + "': " + iae.getMessage());
643         } catch (InstantiationException JavaDoc ie) {
644             throw new SQLException JavaDoc("Failed to load JDBC driver '" +
645                                     driverClass + "': " + ie.getMessage());
646         }
647     }
648     
649     /*
650      * SecurityManager related configuration.
651      */

652     
653     /**
654      * Install the default security manager setup,
655      * for the current configuration.
656      * @throws PrivilegedActionException
657      */

658     boolean defaultSecurityManagerSetup() throws PrivilegedActionException {
659         
660         // Testing with the DB2 client has not been performed
661
// under the security manager since it's not part
662
// of Derby so no real interest in tracking down issues.
663
if (jdbcClient.isDB2Client()) {
664             SecurityManagerSetup.noSecurityManager();
665             return false;
666         } else {
667             SecurityManagerSetup.installSecurityManager();
668             return true;
669         }
670     }
671     
672         
673 }
674
Popular Tags