KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > org > apache > derby > impl > tools > ij > xaHelper


1 /*
2
3    Derby - Class org.apache.derby.impl.tools.ij.xaHelper
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.derby.impl.tools.ij;
23
24 import org.apache.derby.iapi.tools.i18n.LocalizedResource;
25 import java.sql.Connection JavaDoc;
26 import java.sql.SQLException JavaDoc;
27 import java.util.Locale JavaDoc;
28 import java.util.Vector JavaDoc;
29
30 import javax.transaction.xa.Xid JavaDoc;
31 import javax.transaction.xa.XAResource JavaDoc;
32 import javax.transaction.xa.XAException JavaDoc;
33 import javax.sql.PooledConnection JavaDoc;
34 import javax.sql.XAConnection JavaDoc;
35 import javax.sql.XADataSource JavaDoc;
36 import javax.sql.DataSource JavaDoc;
37 import javax.sql.ConnectionPoolDataSource JavaDoc;
38 import org.apache.derby.iapi.services.info.JVMInfo;
39
40 /*
41  * The real xa helper class. Load this class only if we know the javax classes
42  * are in the class path.
43  */

44 class xaHelper implements xaAbstractHelper
45 {
46
47     private XADataSource JavaDoc currentXADataSource;
48     private XAConnection JavaDoc currentXAConnection;
49
50     private String JavaDoc databaseName;
51
52     // non xa stuff
53
private DataSource JavaDoc currentDataSource;
54     private ConnectionPoolDataSource JavaDoc currentCPDataSource;
55     private PooledConnection JavaDoc currentPooledConnection;
56
57     private boolean isJCC;
58     private boolean isNetClient;
59     private String JavaDoc framework;
60
61   xaHelper()
62   {
63   }
64       
65       
66     public void setFramework(String JavaDoc fm)
67     {
68                 if (fm == null) {
69                     return;
70                 }
71         framework = fm.toUpperCase(Locale.ENGLISH);
72         if (framework.endsWith("NET") ||
73             framework.equals("DB2JCC"))
74             isJCC = true;
75         else if (framework.equals("DERBYNETCLIENT"))
76                  isNetClient = true;
77
78     }
79         
80     private Xid JavaDoc makeXid(int xid)
81     {
82         return new ijXid(xid, databaseName.getBytes());
83     }
84
85     public void XADataSourceStatement(ij parser, Token dbname, Token shutdown,
86                                     String JavaDoc create)
87          throws SQLException JavaDoc
88     {
89         try
90         {
91               currentXADataSource = (XADataSource JavaDoc) getXADataSource();
92
93               databaseName = parser.stringValue(dbname.image);
94               
95               if (isJCC || isNetClient)
96               {
97                 String JavaDoc hostName = System.getProperty("hostName");
98                 if ((hostName != null ) && (!hostName.equals("localhost")))
99                 {
100                     xaHelper.setDataSourceProperty(currentXADataSource,
101                                              "ServerName", hostName);
102                 }
103                 else
104                 {
105                     xaHelper.setDataSourceProperty(currentXADataSource,
106                              "ServerName", "localhost");
107                 }
108               xaHelper.setDataSourceProperty(currentXADataSource,
109                                              "portNumber", 1527);
110               
111               String JavaDoc user;
112               String JavaDoc password;
113               user = "APP";
114               password = "APP";
115               xaHelper.setDataSourceProperty(currentXADataSource,
116                                              "user", user);
117               xaHelper.setDataSourceProperty(currentXADataSource,
118                                              "password", password);
119               //xaHelper.setDataSourceProperty(currentXADataSource,
120
//"traceFile", "trace.out." + framework);
121
}
122               if (isJCC)
123               {
124                   xaHelper.setDataSourceProperty(currentXADataSource,
125                                                  "driverType", 4);
126
127                   xaHelper.setDataSourceProperty(currentXADataSource,
128                                                  "retrieveMessagesFromServerOnGetMessage", true);
129               }
130               xaHelper.setDataSourceProperty(currentXADataSource, "databaseName", databaseName);
131
132             if (shutdown != null && shutdown.toString().toLowerCase(Locale.ENGLISH).equals("shutdown"))
133             {
134                 if (isJCC || isNetClient)
135                     xaHelper.setDataSourceProperty(currentXADataSource,"databaseName", databaseName + ";shutdown=true");
136                 else
137                     xaHelper.setDataSourceProperty(currentXADataSource, "shutdownDatabase", "shutdown");
138
139                 // do a getXAConnection to shut it down */
140
currentXADataSource.getXAConnection().getConnection();
141                 currentXADataSource = null;
142                 currentXAConnection = null;
143             }
144             else if (create != null && create.toLowerCase(java.util.Locale.ENGLISH).equals("create"))
145             {
146                 if (isJCC || isNetClient)
147                     xaHelper.setDataSourceProperty(currentXADataSource,"databaseName", databaseName + ";create=true");
148                 else
149                     xaHelper.setDataSourceProperty(currentXADataSource,
150                                                    "createDatabase", "create");
151
152                 /* do a getXAConnection to create it */
153                 XAConnection JavaDoc conn = currentXADataSource.getXAConnection();
154                 conn.close();
155                 
156                 xaHelper.setDataSourceProperty(currentXADataSource, "createDatabase", null);
157             }
158         }
159         catch (Throwable JavaDoc t)
160         {
161             handleException(t);
162         }
163     }
164
165
166     public void XAConnectStatement(ij parser, Token user, Token pass, String JavaDoc id)
167          throws SQLException JavaDoc
168     {
169         try
170         {
171             if (currentXAConnection != null)
172             {
173                 try {
174                     currentXAConnection.close();
175                 } catch (SQLException JavaDoc sqle) {
176                 }
177
178                 currentXAConnection = null;
179             }
180
181             String JavaDoc username = null;
182             String JavaDoc password = "";
183
184             if (pass != null)
185                 password = parser.stringValue(pass.image);
186
187             if (user != null)
188             {
189                 username = parser.stringValue(user.image);
190
191                 currentXAConnection =
192                     currentXADataSource.getXAConnection(username, password);
193             }
194             else
195             {
196
197                 currentXAConnection = currentXADataSource.getXAConnection();
198             }
199
200         }
201         catch (Throwable JavaDoc t)
202         {
203             handleException(t);
204         }
205     }
206
207     public void XADisconnectStatement(ij parser, String JavaDoc n) throws SQLException JavaDoc
208     {
209         if (currentXAConnection == null)
210             throw ijException.noSuchConnection("XAConnection");
211         currentXAConnection.close();
212         currentXAConnection = null;
213     }
214
215     public Connection JavaDoc XAGetConnectionStatement(ij parser, String JavaDoc n) throws SQLException JavaDoc
216     {
217         try
218         {
219             return currentXAConnection.getConnection();
220         }
221         catch(Throwable JavaDoc t)
222         {
223             handleException(t);
224         }
225         return null;
226     }
227
228     public void CommitStatement(ij parser, Token onePhase, Token twoPhase,
229                                 int xid)
230          throws SQLException JavaDoc
231     {
232         try
233         {
234             currentXAConnection.getXAResource().commit(makeXid(xid), (onePhase != null));
235         }
236         catch(Throwable JavaDoc t)
237         {
238             handleException(t);
239         }
240     }
241
242     public void EndStatement(ij parser, int flag, int xid) throws SQLException JavaDoc
243     {
244         try
245         {
246             currentXAConnection.getXAResource().end(makeXid(xid), flag);
247         }
248         catch(Throwable JavaDoc t)
249         {
250             handleException(t);
251         }
252     }
253
254     public void ForgetStatement(ij parser, int xid) throws SQLException JavaDoc
255     {
256         try
257         {
258             currentXAConnection.getXAResource().forget(makeXid(xid));
259         }
260         catch(Throwable JavaDoc t)
261         {
262             handleException(t);
263         }
264     }
265
266     public void PrepareStatement(ij parser, int xid) throws SQLException JavaDoc
267     {
268         try
269         {
270             currentXAConnection.getXAResource().prepare(makeXid(xid));
271         }
272         catch(Throwable JavaDoc t)
273         {
274             handleException(t);
275         }
276     }
277
278     public ijResult RecoverStatement(ij parser, int flag) throws SQLException JavaDoc
279     {
280         Object JavaDoc[] val = null;
281
282         try
283         {
284             val = currentXAConnection.getXAResource().recover(flag);
285         }
286         catch(Throwable JavaDoc t)
287         {
288             handleException(t);
289         }
290
291         Vector JavaDoc v = new Vector JavaDoc();
292         v.addElement("");
293         v.addElement(LocalizedResource.getMessage("IJ_Reco0InDoubT", LocalizedResource.getNumber(val.length)));
294         v.addElement("");
295         for (int i = 0; i < val.length; i++)
296             v.addElement(LocalizedResource.getMessage("IJ_Tran01", LocalizedResource.getNumber(i+1), val[i].toString()));
297
298         return new ijVectorResult(v,null);
299
300     }
301
302     public void RollbackStatement(ij parser, int xid) throws SQLException JavaDoc
303     {
304         try
305         {
306             currentXAConnection.getXAResource().rollback(makeXid(xid));
307         }
308         catch(Throwable JavaDoc t)
309         {
310             handleException(t);
311         }
312
313     }
314
315     public void StartStatement(ij parser, int flag, int xid) throws SQLException JavaDoc
316     {
317         try
318         {
319             currentXAConnection.getXAResource().start(makeXid(xid), flag);
320         }
321         catch(Throwable JavaDoc t)
322         {
323             handleException(t);
324         }
325     }
326
327     private void handleException(Throwable JavaDoc t) throws SQLException JavaDoc
328     {
329         if (t instanceof SQLException JavaDoc)
330         {
331             // let ij handle it
332
throw (SQLException JavaDoc)t;
333         }
334         if (t instanceof XAException JavaDoc)
335         {
336             int errorCode = ((XAException JavaDoc)t).errorCode;
337             String JavaDoc error = LocalizedResource.getMessage("IJ_IlleValu");
338
339             // XA_RBBASE 100
340
// XA_RBROLLBACK 100
341
// XA_RBCOMMFAIL 101
342
// XA_RBDEADLOCK 102
343
// XA_RBINTEGRITY 103
344
// XA_RBOTHER 104
345
// XA_RBPROTO 105
346
// XA_RBTIMEOUT 106
347
// XA_RBTRANSIENT 107
348
// XA_RBEND 107
349
//
350
// XA_RDONLY 3
351
// XA_RETRY 4
352
// XA_HEURMIX 5
353
// XA_HEURRB 6
354
// XA_HEURCOM 7
355
// XA_HEURHAZ 8
356
// XA_NOMIGRATE 9
357
//
358
// XAER_ASYNC -2
359
// XAER_RMERR -3
360
// XAER_NOTA -4
361
// XAER_INVAL -5
362
// XAER_PROTO -6
363
// XAER_RMFAIL -7
364
// XAER_DUPID -8
365
// XAER_OUTSIDE -9
366

367             switch(errorCode)
368             {
369             case XAException.XA_HEURCOM : error = "XA_HEURCOM "; break;
370             case XAException.XA_HEURHAZ : error = "XA_HEURHAZ"; break;
371             case XAException.XA_HEURMIX : error = "XA_HEURMIX"; break;
372             case XAException.XA_HEURRB : error = "XA_HEURRB "; break;
373             case XAException.XA_NOMIGRATE : error = "XA_NOMIGRATE "; break;
374                 // case XAException.XA_RBBASE : error = "XA_RBBASE "; break;
375
case XAException.XA_RBCOMMFAIL : error = "XA_RBCOMMFAIL "; break;
376             case XAException.XA_RBDEADLOCK : error = "XA_RBDEADLOCK "; break;
377                 // case XAException.XA_RBEND : error = "XA_RBEND "; break;
378
case XAException.XA_RBINTEGRITY : error = "XA_RBINTEGRITY "; break;
379             case XAException.XA_RBOTHER : error = "XA_RBOTHER "; break;
380             case XAException.XA_RBPROTO : error = "XA_RBPROTO "; break;
381             case XAException.XA_RBROLLBACK : error = "XA_RBROLLBACK "; break;
382             case XAException.XA_RBTIMEOUT : error = "XA_RBTIMEOUT "; break;
383             case XAException.XA_RBTRANSIENT : error = "XA_RBTRANSIENT "; break;
384             case XAException.XA_RDONLY : error = "XA_RDONLY "; break;
385             case XAException.XA_RETRY : error = "XA_RETRY "; break;
386             case XAException.XAER_ASYNC : error = "XAER_ASYNC "; break;
387             case XAException.XAER_DUPID : error = "XAER_DUPID "; break;
388             case XAException.XAER_INVAL : error = "XAER_INVAL "; break;
389             case XAException.XAER_NOTA : error = "XAER_NOTA "; break;
390             case XAException.XAER_OUTSIDE : error = "XAER_OUTSIDE "; break;
391             case XAException.XAER_PROTO : error = "XAER_PROTO "; break;
392             case XAException.XAER_RMERR : error = "XAER_RMERR "; break;
393             case XAException.XAER_RMFAIL : error = "XAER_RMFAIL "; break;
394             }
395             //t.printStackTrace(System.out);
396
throw new ijException(error);
397
398         }
399         else // StandardException or run time exception, log it first
400
{
401             String JavaDoc info = LocalizedResource.getMessage("IJ_01SeeLog", t.toString(), t.getMessage());
402             // t.printStackTrace(System.out);
403
throw new ijException(info);
404         }
405     }
406
407
408     // non-xa stuff. DataSource and ConnectionPoolDataSource
409
public Connection JavaDoc DataSourceStatement(ij parser, Token dbname, Token protocol,
410                                     Token userT, Token passT, String JavaDoc id)
411          throws SQLException JavaDoc
412     {
413
414         try {
415             currentDataSource = (DataSource JavaDoc) (Class.forName("org.apache.derby.jdbc.EmbeddedDataSource").newInstance());
416         } catch (Exception JavaDoc e) {
417             throw new SQLException JavaDoc(e.toString());
418         }
419         databaseName = parser.stringValue(dbname.image);
420         xaHelper.setDataSourceProperty(currentDataSource, "databaseName", databaseName);
421         xaHelper.setDataSourceProperty(currentXADataSource, "dataSourceName", databaseName);
422         // make a connection
423
Connection JavaDoc c = null;
424         String JavaDoc username = null;
425         String JavaDoc password = "";
426
427         if (passT != null)
428             password = parser.stringValue(passT.image);
429
430         if (userT != null)
431         {
432             username = parser.stringValue(userT.image);
433             c = currentDataSource.getConnection(username, password);
434         }
435         else
436         {
437             c = currentDataSource.getConnection();
438         }
439
440         return c;
441
442     }
443
444     public void CPDataSourceStatement(ij parser, Token dbname, Token protocol)
445          throws SQLException JavaDoc
446     {
447         try {
448             currentCPDataSource = (ConnectionPoolDataSource JavaDoc) (Class.forName("org.apache.derby.jdbc.EmbeddedConnectionPoolDataSource").newInstance());
449         } catch (Exception JavaDoc e) {
450             throw new SQLException JavaDoc(e.toString());
451         }
452         databaseName = parser.stringValue(dbname.image);
453         xaHelper.setDataSourceProperty(currentCPDataSource, "databaseName", databaseName);
454     }
455
456     public void CPConnectStatement(ij parser, Token userT, Token passT, String JavaDoc n)
457          throws SQLException JavaDoc
458     {
459         String JavaDoc username = null;
460         String JavaDoc password = "";
461
462         if (passT != null)
463             password = parser.stringValue(passT.image);
464
465         if (userT != null)
466         {
467             username = parser.stringValue(userT.image);
468             currentPooledConnection =
469                 currentCPDataSource.getPooledConnection(username, password);
470         }
471         else
472         {
473             currentPooledConnection =
474                 currentCPDataSource.getPooledConnection();
475         }
476     }
477
478     public Connection JavaDoc CPGetConnectionStatement(ij parser, String JavaDoc n)
479          throws SQLException JavaDoc
480     {
481         return currentPooledConnection.getConnection();
482     }
483
484     public void CPDisconnectStatement(ij parser, String JavaDoc n) throws SQLException JavaDoc
485     {
486         if (currentPooledConnection == null)
487             throw ijException.noSuchConnection(LocalizedResource.getMessage("IJ_Pool"));
488         currentPooledConnection.close();
489         currentPooledConnection = null;
490     }
491
492     /**
493      * Get a DataSource that supports distributed transactions.
494      *
495      * @return XADataSource object
496      *
497      * @exception Exception if XaDataSource is not in class path.
498      */

499     private XADataSource JavaDoc getXADataSource() throws Exception JavaDoc
500     {
501         // We need to construct this object in this round about fashion because
502
// if we new it directly, then it will the tools.jar file to bloat.
503
try
504         {
505             if (isJCC)
506                 return (XADataSource JavaDoc)
507                     (Class.forName("com.ibm.db2.jcc.DB2XADataSource").newInstance());
508             else if (isNetClient){
509                             if (JVMInfo.JDK_ID >= JVMInfo.J2SE_16) {
510                                 //running under jdk1.6 or higher
511
// try instantiating EmbeddedXADataSource40
512
try {
513                                     return (XADataSource JavaDoc)(Class.forName(
514                                         "org.apache.derby.jdbc." +
515                                         "ClientXADataSource40").newInstance());
516                                 }
517                                 catch (ClassNotFoundException JavaDoc e) {
518                                     //probably it was not compiled with jdbc4.0
519
//support go ahead with EmbeddedXADataSource
520
}
521                             }
522                             return (XADataSource JavaDoc) (Class.forName(
523                                     "org.apache.derby.jdbc.ClientXADataSource"
524                                     ).newInstance());
525                         }
526             else {
527                             if (JVMInfo.JDK_ID >= JVMInfo.J2SE_16) {
528                                 //running under jdk1.6 or higher
529
// try instantiating EmbeddedXADataSource40
530
try {
531                                     return (XADataSource JavaDoc)(Class.forName(
532                                         "org.apache.derby.jdbc." +
533                                         "EmbeddedXADataSource40").newInstance());
534                                 }
535                                 catch (ClassNotFoundException JavaDoc e) {
536                                     //probably it was not compiled with jdbc4.0
537
//support go ahead with EmbeddedXADataSource
538
}
539                             }
540                             return (XADataSource JavaDoc)(Class.forName("org.apache.derby.jdbc.EmbeddedXADataSource").newInstance());
541                         }
542         }
543         catch(ClassNotFoundException JavaDoc cnfe) {
544             throw new ijException(LocalizedResource.getMessage("IJ_XAClass"));
545         }
546         catch (InstantiationException JavaDoc e) { }
547         catch (IllegalAccessException JavaDoc e) { }
548
549         throw new ijException(LocalizedResource.getMessage("IJ_XANoI"));
550     }
551     private static final Class JavaDoc[] STRING_P = { "".getClass() };
552     private static final Class JavaDoc[] INT_P = { Integer.TYPE };
553     private static final Class JavaDoc[] BOOLEAN_P = {Boolean.TYPE };
554
555     private static void setDataSourceProperty(Object JavaDoc ds, String JavaDoc property, int
556                                               value) throws SQLException JavaDoc
557     {
558         String JavaDoc methodName =
559             "set" + Character.toUpperCase(property.charAt(0)) + property.substring(1);
560         try {
561             java.lang.reflect.Method JavaDoc m = ds.getClass().getMethod(methodName, INT_P);
562             m.invoke(ds, new Object JavaDoc[] {new Integer JavaDoc(value)});
563         }
564         catch (Exception JavaDoc e)
565         {
566             throw new SQLException JavaDoc(property + " ???" + e.getMessage());
567         }
568         
569     }
570     
571     private static void setDataSourceProperty(Object JavaDoc ds, String JavaDoc property, String JavaDoc value) throws SQLException JavaDoc {
572
573         String JavaDoc methodName =
574             "set" + Character.toUpperCase(property.charAt(0)) + property.substring(1);
575
576         try {
577             java.lang.reflect.Method JavaDoc m = ds.getClass().getMethod(methodName, STRING_P);
578             m.invoke(ds, new Object JavaDoc[] {value});
579             return;
580         } catch (/*NoSuchMethod*/Exception JavaDoc nsme) {
581             throw new SQLException JavaDoc(property + " ???");
582             //java.lang.reflect.Method m = ds.getClass().getMethod("set" + property, INT_P);
583
//m.invoke(ds, new Object[] {Integer.valueOf(value)});
584
}
585     }
586
587 private static void setDataSourceProperty(Object JavaDoc ds, String JavaDoc property, boolean value) throws SQLException JavaDoc {
588
589         String JavaDoc methodName =
590             "set" + Character.toUpperCase(property.charAt(0)) + property.substring(1);
591
592         try {
593             java.lang.reflect.Method JavaDoc m = ds.getClass().getMethod(methodName, BOOLEAN_P);
594             m.invoke(ds, new Object JavaDoc[] {new Boolean JavaDoc(value)});
595             return;
596         } catch (Exception JavaDoc nsme) {
597             throw new SQLException JavaDoc(property + " ???");
598         }
599     }
600 }
601
602
603
604 class ijXid implements Xid JavaDoc, java.io.Serializable JavaDoc
605 {
606   private static final long serialVersionUID = 64467452100036L;
607
608     private final int format_id;
609     private final byte[] global_id;
610     private final byte[] branch_id;
611
612
613     ijXid(int xid, byte[] id)
614     {
615         format_id = xid;
616         global_id = id;
617         branch_id = id;
618         
619     }
620     /**
621      * Obtain the format id part of the Xid.
622      * <p>
623      *
624      * @return Format identifier. O means the OSI CCR format.
625      **/

626     public int getFormatId()
627     {
628         return(format_id);
629     }
630
631     /**
632      * Obtain the global transaction identifier part of XID as an array of
633      * bytes.
634      * <p>
635      *
636      * @return A byte array containing the global transaction identifier.
637      **/

638     public byte[] getGlobalTransactionId()
639     {
640         return(global_id);
641     }
642
643     /**
644      * Obtain the transaction branch qualifier part of the Xid in a byte array.
645      * <p>
646      *
647      * @return A byte array containing the branch qualifier of the transaction.
648      **/

649     public byte[] getBranchQualifier()
650     {
651         return(branch_id);
652     }
653 }
654
655
656
Popular Tags