KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > org > apache > derbyTesting > functionTests > tests > derbynet > dataSourcePermissions_net


1 /*
2
3    Derby - Class org.apache.derbyTesting.functionTests.tests.derbynet.dataSourcePermissions_net
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, software
15    distributed under the License is distributed on an "AS IS" BASIS,
16    WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
17    See the License for the specific language governing permissions and
18    limitations under the License.
19
20  */

21
22 package org.apache.derbyTesting.functionTests.tests.derbynet;
23
24 import org.apache.derby.jdbc.EmbeddedDataSource;
25 import org.apache.derby.jdbc.EmbeddedConnectionPoolDataSource;
26 import org.apache.derby.jdbc.EmbeddedXADataSource;
27
28 import java.sql.Connection JavaDoc;
29 import java.sql.ResultSet JavaDoc;
30 import java.sql.PreparedStatement JavaDoc;
31 import java.sql.CallableStatement JavaDoc;
32 import java.sql.Statement JavaDoc;
33 import java.sql.SQLException JavaDoc;
34 import java.sql.DriverManager JavaDoc;
35
36 import javax.sql.DataSource JavaDoc;
37 import javax.sql.XADataSource JavaDoc;
38 import javax.sql.PooledConnection JavaDoc;
39 import javax.sql.XAConnection JavaDoc;
40 import javax.sql.ConnectionPoolDataSource JavaDoc;
41 import javax.transaction.xa.XAResource JavaDoc;
42 import javax.transaction.xa.XAException JavaDoc;
43 import javax.transaction.xa.Xid JavaDoc;
44 import javax.sql.ConnectionEventListener JavaDoc;
45 import javax.sql.ConnectionEvent JavaDoc;
46 import org.apache.derby.tools.JDBCDisplayUtil;
47 import org.apache.derby.tools.ij;
48 import org.apache.derby.drda.NetworkServerControl;
49 import org.apache.derbyTesting.functionTests.util.TestUtil;
50 import java.io.*;
51 import java.net.InetAddress JavaDoc;
52 import java.util.Hashtable JavaDoc;
53 import java.util.Properties JavaDoc;
54
55 import javax.naming.*;
56 import javax.naming.directory.*;
57
58 import java.lang.reflect.*;
59
60 public class dataSourcePermissions_net extends org.apache.derbyTesting.functionTests.tests.jdbcapi.dataSourcePermissions
61 {
62
63     private static int NETWORKSERVER_PORT;
64     private static String JavaDoc hostName;
65     private static NetworkServerControl networkServer = null;
66     
67     private static FileOutputStream serverOutput;
68     
69     public static void main(String JavaDoc[] args) throws Exception JavaDoc {
70
71         hostName = TestUtil.getHostName();
72         if (hostName.equals("localhost"))
73             NETWORKSERVER_PORT = 20000;
74         else
75             NETWORKSERVER_PORT = 1527;
76         
77         // Load harness properties.
78
ij.getPropertyArg(args);
79
80         // "runTest()" is going to try to connect to the database through
81
// the server at port NETWORKSERVER_PORT. Thus, we have to
82
// start the server on that port before calling runTest.
83
// Except when we are using a remote server, then we assume the port is 1527,
84
// and we assume the server has been started already
85

86         try {
87             TestUtil.loadDriver();
88         } catch (Exception JavaDoc e) {
89             e.printStackTrace();
90         }
91
92         String JavaDoc fileName = System.getProperty( "derby.system.home", "")
93             + "serverConsoleOutput.log";
94         serverOutput = new FileOutputStream(fileName);
95
96         if (hostName.equals("localhost"))
97         {
98             // Start the NetworkServer on another thread
99
networkServer = new NetworkServerControl(InetAddress.getByName("localhost"),NETWORKSERVER_PORT);
100             networkServer.start(new PrintWriter(serverOutput));
101
102             // Wait for the NetworkServer to start.
103
if (!isServerStarted(networkServer, 60))
104                 System.exit(-1);
105         }
106         
107         
108         // Now, go ahead and run the test.
109
try {
110             dataSourcePermissions_net tester =
111             new dataSourcePermissions_net();
112             tester.setProperties();
113             tester.runTest();
114             if (TestUtil.isDerbyNetClientFramework())
115                 tester.testClientDataSourceProperties();
116             new dataSourcePermissions_net().cleanUp();
117
118         } catch (Exception JavaDoc e) {
119         // if we catch an exception of some sort, we need to make sure to
120
// close our streams before returning; otherwise, we can get
121
// hangs in the harness. SO, catching all exceptions here keeps
122
// us from exiting before closing the necessary streams.
123
System.out.println("FAIL - Exiting due to unexpected error: " +
124                 e.getMessage());
125             e.printStackTrace();
126         }
127
128         // Shutdown the server.
129
if (hostName.equals("localhost"))
130         {
131             
132             networkServer.shutdown();
133             
134             // how do we do this with the new api?
135
//networkServer.join();
136
Thread.sleep(5000);
137         }
138         System.out.println("Completed dataSourcePermissions_net");
139         
140         serverOutput.close();
141
142     }
143
144
145     public dataSourcePermissions_net() {
146
147         
148     }
149     
150
151     public void setProperties() {
152         // Set required server properties.
153
System.setProperty("database",
154                            TestUtil.getJdbcUrlPrefix(hostName,
155                                                      NETWORKSERVER_PORT) +
156                            "wombat;create=true");
157         System.setProperty("ij.user", "EDWARD");
158         System.setProperty("ij.password", "noodle");
159
160     }
161
162     public String JavaDoc getJDBCUrl(String JavaDoc db, String JavaDoc attrs) {
163         // this method is accessed from subclasses - need to establish hostName
164
String JavaDoc hostName = TestUtil.getHostName();
165         if (hostName.equals("localhost"))
166             NETWORKSERVER_PORT = 20000;
167         else
168             NETWORKSERVER_PORT = 1527;
169         String JavaDoc s = TestUtil.getJdbcUrlPrefix(hostName, NETWORKSERVER_PORT)
170             + db;
171         if (attrs != null)
172             if (TestUtil.isJCCFramework())
173                 s = s + ":" + attrs + ";";
174             else
175                 s = s + ";" + attrs;
176         return s;
177
178     }
179
180     public javax.sql.DataSource JavaDoc getDS(String JavaDoc database, String JavaDoc user, String JavaDoc
181                                       password)
182     {
183         return getDS(database,user,password,null);
184     }
185
186     public javax.sql.DataSource JavaDoc getDS(String JavaDoc database, String JavaDoc user, String JavaDoc
187                                       password, Properties JavaDoc attrs)
188     {
189
190     if (attrs == null)
191         attrs = new Properties JavaDoc();
192     attrs.setProperty("databaseName", database);
193     if (user != null)
194         attrs.setProperty("user", user);
195     if (password != null)
196         attrs.setProperty("password", password);
197     attrs = addRequiredAttributes(attrs);
198     return TestUtil.getDataSource(attrs);
199     }
200
201
202
203     public javax.sql.ConnectionPoolDataSource JavaDoc getCPDS(String JavaDoc database, String JavaDoc user, String JavaDoc password) {
204         Properties JavaDoc attrs = new Properties JavaDoc();
205         attrs.setProperty("databaseName", database);
206         if (user != null)
207             attrs.setProperty("user", user);
208         if (password != null)
209             attrs.setProperty("password", password);
210         attrs = addRequiredAttributes(attrs);
211         return TestUtil.getConnectionPoolDataSource(attrs);
212     }
213
214     private Properties JavaDoc addRequiredAttributes(Properties JavaDoc attrs)
215     {
216         // this method is accessed from subclasses - need to establish hostName
217
hostName = TestUtil.getHostName();
218         if (TestUtil.isJCCFramework())
219         {
220             attrs.setProperty("driverType","4");
221             /**
222              * As per the fix of derby-410 servername should
223              * default to localhost, but for jcc it's still needed
224              */

225             attrs.setProperty("serverName",hostName);
226         }
227         /**
228          * For a remote host of course it's also needed
229          */

230         if (!hostName.equals("localhost"))
231         {
232             attrs.setProperty("serverName",hostName);
233             attrs.setProperty("portNumber", "1527");
234         }
235         else
236             attrs.setProperty("portNumber", "20000");
237         //attrs.setProperty("retrieveMessagesFromServerOnGetMessage","true");
238
return attrs;
239     }
240
241     public boolean supportsUnicodeNames() {
242         return false;
243     }
244
245     public boolean supportsPooling() {
246         return true;
247     }
248     public boolean supportsXA() {
249         return false;
250     }
251
252     public void start() {
253     }
254
255     public void shutdown() {
256         
257         try {
258             
259             DriverManager.getConnection(TestUtil.getJdbcUrlPrefix(hostName,
260                                                               NETWORKSERVER_PORT) +
261                                         "wombat;shutdown=true",
262                 "EDWARD", "noodle");
263             
264             System.out.println("FAIL - Shutdown returned connection");
265
266         } catch (SQLException JavaDoc sqle) {
267             
268             System.out.println("EXPECTED SHUTDOWN " + sqle.getMessage());
269         }
270         
271     }
272
273     protected static boolean isServerStarted(NetworkServerControl server, int ntries)
274     {
275         for (int i = 1; i <= ntries; i ++)
276         {
277             try {
278                 Thread.sleep(500);
279                 server.ping();
280                 return true;
281             }
282             catch (Exception JavaDoc e) {
283                 if (i == ntries)
284                     return false;
285             }
286         }
287         return false;
288     }
289
290     /**
291      * Test Client specific dataSource Properties
292      *
293      */

294     public void testClientDataSourceProperties() throws SQLException JavaDoc
295     {
296         testRetrieveMessageText();
297         testDescription();
298         
299         //Added for Derby-409
300
testConnectionAttributes();
301         
302         //Added for Derby-406
303
allUsernameAndPasswordTests();
304     }
305
306     /**
307      * Test property retrieveMessageText to retrieve message text
308      * Property defaults to true for Network Client but can be set to
309      * false to disable the procedure call.
310      */

311     public void testRetrieveMessageText() throws SQLException JavaDoc
312     {
313         Connection JavaDoc conn;
314         String JavaDoc retrieveMessageTextProperty = "retrieveMessageText";
315         Class JavaDoc[] argType = { Boolean.TYPE };
316         String JavaDoc methodName = TestUtil.getSetterName(retrieveMessageTextProperty);
317         Object JavaDoc[] args;
318
319         try {
320             DataSource ds = getDS("wombat", "EDWARD", "noodle");
321             Method sh = ds.getClass().getMethod(methodName, argType);
322             args = new Boolean JavaDoc[] { new Boolean JavaDoc(false) };
323             sh.invoke(ds, args);
324             conn = ds.getConnection();
325             checkMessageText(conn,"false");
326             conn.close();
327
328             // now try with retrieveMessageText = true
329
ds = getDS("wombat", "EDWARD", "noodle");
330             args = new Boolean JavaDoc[] { new Boolean JavaDoc(true) };
331             sh.invoke(ds, args);
332             conn = ds.getConnection();
333             checkMessageText(conn,"true");
334             conn.close();
335         }
336         catch (Exception JavaDoc e)
337         {
338             System.out.println("FAIL: testRetrieveMessageText() Unexpected Exception " + e.getMessage());
339             e.printStackTrace();
340         }
341     }
342
343     /**
344      * Test description property
345      */

346     public void testDescription() throws SQLException JavaDoc
347     {
348         String JavaDoc descriptionProperty = "description";
349         Class JavaDoc[] argType = { String JavaDoc.class};
350         String JavaDoc setterMethodName = TestUtil.getSetterName(descriptionProperty);
351         String JavaDoc getterMethodName = TestUtil.getGetterName(descriptionProperty);
352
353         Object JavaDoc[] args;
354
355         try {
356             String JavaDoc setDescription = "Everything you ever wanted to know about this datasource";
357             DataSource ds = getDS("wombat", "EDWARD", "noodle");
358             // Set the description
359
Method sh = ds.getClass().getMethod(setterMethodName, argType);
360             args = new Object JavaDoc[] { new String JavaDoc(setDescription) };
361             sh.invoke(ds, args);
362             // Now check it
363
sh = ds.getClass().getMethod(getterMethodName, null);
364             String JavaDoc getDescription = (String JavaDoc) sh.invoke(ds, null);
365             if (!setDescription.equals(getDescription))
366                 throw new Exception JavaDoc("getDescription() " + getDescription +
367                                     " does not match setDescription() ");
368         }
369         catch (Exception JavaDoc e)
370         {
371             System.out.println("FAIL: testDescription() Unexpected Exception " + e.getMessage());
372             e.printStackTrace();
373         }
374     }
375
376     public void checkMessageText(Connection JavaDoc conn, String JavaDoc
377                                  retrieveMessageTextValue) throws SQLException JavaDoc
378     {
379         System.out.println("** checkMessageText() with retrieveMessageText= " +
380                            retrieveMessageTextValue);
381
382         try {
383             conn.createStatement().executeQuery("SELECT * FROM APP.NOTTHERE");
384         }
385         catch (SQLException JavaDoc e)
386         {
387             String JavaDoc expectedSQLState = "42X05";
388             String JavaDoc sqlState = e.getSQLState();
389             if (sqlState == null || ! sqlState.equals(expectedSQLState))
390             {
391                 System.out.println("Incorrect SQLState. Got: " + sqlState +
392                                    " should be: " + expectedSQLState);
393                 throw e;
394             }
395             if (retrieveMessageTextValue.equals("true") )
396                 {
397                     if (e.getMessage().indexOf("does not exist") != -1)
398                         System.out.println("PASS: Message Text retrieved properly");
399                     else
400                     {
401                         System.out.println("FAIL: Message text was not retrieved");
402                         throw e;
403                     }
404                 }
405             else
406                 // retrieveMessageTextValue is false
407
if (e.getMessage().indexOf("does not exist") == -1)
408                 {
409                     System.out.println("PASS: Message text not retrieved");
410                 }
411                 else
412                 {
413                     System.out.println("FAIL: Message Text should not have been retrieved");
414                     throw e;
415                 }
416
417         }
418     }
419        
420     /**
421      * Added for Derby-409
422      *
423      * Designed to test combinations of attributes to insure that
424      * no exceptions are thrown.
425      */

426     public void testConnectionAttributes() {
427         try {
428             System.out.println("Begin connection attribute tests");
429             testDataSourceConnection("One attribute test: ",
430                     "EDWARD", "noodle", "create=true");
431             testDataSourceConnection("Another different attribute: ",
432                     "EDWARD", "noodle", "tracefile=trace.out");
433             testDataSourceConnection("Two Attributes: ",
434                     "EDWARD", "noodle", "create=true;tracefile=trace.out");
435             System.out.println("End connection attribute tests");
436         }
437         catch (Exception JavaDoc e)
438         {
439             System.out.println("FAIL: testSetConnectionAttributes() Unexpected Exception " + e.getMessage());
440             e.printStackTrace(System.out);
441         }
442     }
443     
444     /**
445      * Added for Derby-406
446      *
447      * Tests DataSource with a number of different username/password
448      * input combinations.
449      */

450     public void allUsernameAndPasswordTests() {
451         
452         try {
453             System.out.println("Begin username and password tests");
454             
455             testDataSourceConnection("Normal test: ", "EDWARD", "noodle", null);
456             
457             testDataSourceConnection("No username or password, only attributes test: ",
458                     null, null, "user=EDWARD;password=noodle");
459             
460             testDataSourceConnection("Bogus username and password, good attributes test: ",
461                     "Whatis", "theMatrix?", "user=EDWARD;password=noodle");
462             
463             testDataSourceConnection("Username, password attribute test: ",
464                     "EDWARD", null, "password=noodle");
465             
466             testDataSourceConnection("Password, username attribute test: ",
467                     null, "noodle", "user=EDWARD");
468             
469             System.out.println("Turning off authentication");
470             DataSource ds = getDS("wombat", "EDWARD", "noodle");
471             Connection JavaDoc conn = ds.getConnection();
472             CallableStatement JavaDoc cs = conn.prepareCall("CALL SYSCS_UTIL.SYSCS_SET_DATABASE_PROPERTY(?, ?)");
473             cs.setString(1, "derby.connection.requireAuthentication");
474             cs.setString(2, "false");
475             cs.execute();
476             cs.close();
477             cs = null;
478             conn.close();
479             //We have to shut down before the changes will take effect.
480
shutdown();
481             start();
482             
483             testDataSourceConnection("Username, no password test: ",
484                     "EDWARD", null, null);
485             
486             testDataSourceConnection("No username, password test: ",
487                     null, "noodle", null);
488             
489             testDataSourceConnection("No username, no password test: ",
490                     null, null, null);
491             
492             System.out.println("Turning on authentication");
493             ds = getDS("wombat", "EDWARD", "noodle");
494             conn = ds.getConnection();
495             cs = conn.prepareCall("CALL SYSCS_UTIL.SYSCS_SET_DATABASE_PROPERTY(?, ?)");
496             cs.setString(1, "derby.connection.requireAuthentication");
497             cs.setString(2, "true");
498             cs.execute();
499             cs.close();
500             cs = null;
501             conn.close();
502             shutdown();
503             start();
504             
505             System.out.println("End username and password tests");
506         }
507         catch (Exception JavaDoc e)
508         {
509             System.out.println("FAIL: allUsernameAndPasswordTests. Unexpected Exception " + e.getMessage());
510             e.printStackTrace(System.out);
511         }
512     }
513     
514     /**
515      * A method that attempts to retrieve the connection via a datasource
516      * with the given user, password and connection attributes.
517      *
518      * @param testType A string description of the type of test
519      * @param username The user
520      * @param password The Password
521      * @param attributes A string to be added to a properties object. A
522      * null string means null Property object.
523      * @throws SQLException
524      */

525     public void testDataSourceConnection(String JavaDoc testType, String JavaDoc username, String JavaDoc password, String JavaDoc attributes) throws SQLException JavaDoc {
526         try {
527             System.out.print(testType);
528             Properties JavaDoc props = null;
529             if (attributes != null) {
530                 props = new Properties JavaDoc();
531                 props.put("ConnectionAttributes", attributes);
532             }
533             DataSource ds = getDS("wombat", username, password, props);
534             Connection JavaDoc conn = ds.getConnection();
535             conn.close();
536             System.out.println("PASS.");
537         } catch (SQLException JavaDoc e) {
538             System.out.println("FAIL. Unexpected Exception: ");
539             e.printStackTrace(System.out);
540         }
541     }
542 }
543
544
545
546
547
548
549
Popular Tags