KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > org > compiere > db > CConnection


1 /******************************************************************************
2  * The contents of this file are subject to the Compiere License Version 1.1
3  * ("License"); You may not use this file except in compliance with the License
4  * You may obtain a copy of the License at http://www.compiere.org/license.html
5  * Software distributed under the License is distributed on an "AS IS" basis,
6  * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License for
7  * the specific language governing rights and limitations under the License.
8  * The Original Code is Compiere ERP & CRM Business Solution
9  * The Initial Developer of the Original Code is Jorg Janke and ComPiere, Inc.
10  * Portions created by Jorg Janke are Copyright (C) 1999-2001 Jorg Janke, parts
11  * created by ComPiere are Copyright (C) ComPiere, Inc.; All Rights Reserved.
12  * Contributor(s): ______________________________________.
13  *****************************************************************************/

14 package org.compiere.db;
15
16 import java.io.*;
17 import java.sql.*;
18 import java.util.*;
19
20 import javax.naming.*;
21 import javax.sql.*;
22
23 import org.compiere.Compiere;
24 import org.compiere.util.*;
25 import org.compiere.interfaces.*;
26
27 /**
28  * Compiere Connection Descriptor
29  *
30  * @author Jorg Janke
31  * @author Marek Mosiewicz<marek.mosiewicz@jotel.com.pl> - support for RMI over HTTP
32  * @version $Id: CConnection.java,v 1.35 2003/10/04 03:55:46 jjanke Exp $
33  */

34 public class CConnection implements Serializable
35 {
36     /** Connection */
37     private static CConnection s_cc = null;
38     /** Logger */
39     private Logger log = Logger.getCLogger (getClass());
40
41
42     /**
43      * Get/Set default client/server Connection from Ini
44      * @return Connection Descriptor
45      */

46     public static CConnection get ()
47     {
48         if (s_cc == null)
49         {
50             String JavaDoc attributes = Ini.getProperty (Ini.P_CONNECTION);
51             if (attributes == null || attributes.length () == 0)
52             {
53                 CConnectionDialog ccd = new CConnectionDialog (new CConnection ());
54                 s_cc = ccd.getConnection ();
55                 // set also in ALogin and Ctrl
56
Ini.setProperty (Ini.P_CONNECTION, s_cc.toStringLong ());
57                 Ini.saveProperties (Ini.isClient ());
58             }
59             else
60             {
61                 s_cc = new CConnection ();
62                 s_cc.setAttributes (attributes);
63             }
64         } // client
65

66         // System.out.println("CConnection.get" + s_cc.toString());
67
return s_cc;
68     } // getConnection
69

70
71     /**
72      * Get specific connection
73      * @param type database Type, e.g. Database.DB_ORACLE
74      * @param db_host db host
75      * @param db_port db port
76      * @param db_name db name
77      * @return connection
78      */

79     public static CConnection get (String JavaDoc type, String JavaDoc db_host, int db_port, String JavaDoc db_name)
80     {
81         return get (type, db_host, db_port, db_name, null, null);
82     } // get
83

84     /**
85      * Get specific client connection
86      * @param type database Type, e.g. Database.DB_ORACLE
87      * @param db_host db host
88      * @param db_port db port
89      * @param db_name db name
90      * @param db_uid db user id
91      * @param db_pwd db user password
92      * @return connection
93      */

94     public static CConnection get (String JavaDoc type, String JavaDoc db_host, int db_port,
95       String JavaDoc db_name, String JavaDoc db_uid, String JavaDoc db_pwd)
96     {
97         CConnection cc = new CConnection ();
98         cc.setAppsHost (db_host); // set Apps=DB
99
cc.setType (type);
100         cc.setDbHost (db_host);
101         cc.setDbPort (db_port);
102         cc.setDbName (db_name);
103         //
104
if (db_uid != null)
105             cc.setDbUid (db_uid);
106         if (db_pwd != null)
107             cc.setDbPwd (db_pwd);
108         return cc;
109     } // get
110

111     /*************************************************************************/
112
113     /**
114      * Set Data Source
115      * @param context context to get DataSource, e.g. java:OracleDS
116      * @param dataSourceName if null use OracleDS
117      */

118     public void setDataSource (Context context, String JavaDoc dataSourceName)
119     {
120         String JavaDoc name = null;
121         try
122         {
123             if (dataSourceName == null || dataSourceName.length () == 0)
124                 name = "java:OracleDS";
125             else
126                 name = "java:" + dataSourceName;
127             m_ds = (DataSource)context.lookup (name);
128             if (m_ds == null)
129                 log.error ("setDataSource " + name + " - not found");
130         }
131         catch (Exception JavaDoc ex)
132         {
133             log.error ("setDataSource: " + name, ex);
134         }
135     } // setDataSource
136

137     /**
138      * Set Server Connection
139      * @param ds DataSource
140      */

141     public void setDataSource (DataSource ds)
142     {
143         m_ds = ds;
144     } // setDataSource
145

146
147     /**
148      * Get Server Connection
149      * @return DataSource
150      */

151     public DataSource getDataSource ()
152     {
153         return m_ds;
154     } // getDataSource
155

156     /**
157      * Has Server Connection
158      * @return true if DataSource exists
159      */

160     public boolean isDataSource ()
161     {
162         return m_ds != null;
163     } // isDataSource
164

165     /*************************************************************************/
166
167     /**
168      * Compiere Connection
169      */

170     protected CConnection ()
171     {
172         // System.out.println("CConnection");
173
} // CConnection
174

175     /** Name of Connection */
176     private String JavaDoc m_name = "Standard";
177
178     /** Application Host */
179     private String JavaDoc m_apps_host = "dev";
180     /** Application Port */
181     private int m_apps_port = 1099;
182
183     /** Database Type */
184     private String JavaDoc m_type = Database.DB_ORACLE;
185
186     /** Database Host */
187     private String JavaDoc m_db_host = "dev";
188     /** Database Port */
189     private int m_db_port = DB_Oracle.DEFAULT_PORT;
190     /** Database name */
191     private String JavaDoc m_db_name = "dev1";
192
193     /** RMI over HTTP */
194     private boolean m_RMIoverHTTP = false;
195
196     /** In Memory connection */
197     private boolean m_bequeath = false;
198
199     /** Connection uses Firewall */
200     private boolean m_firewall = false;
201     /** Firewall host */
202     private String JavaDoc m_fw_host = "";
203     /** Firewall port */
204     private int m_fw_port = DB_Oracle.DEFAULT_CM_PORT;
205
206     /** DB User name */
207     private String JavaDoc m_db_uid = "compiere";
208     /** DB User password */
209     private String JavaDoc m_db_pwd = "compiere";
210
211     /** Database */
212     private CompiereDatabase m_db = null;
213     /** ConnectionException */
214     private Exception JavaDoc m_dbException = null;
215     private Exception JavaDoc m_appsException = null;
216
217     /** Database Connection */
218     private boolean m_okDB = false;
219     /** Apps Server Connection */
220     private boolean m_okApps = false;
221
222     /** Info */
223     private String JavaDoc[] m_info = new String JavaDoc[2];
224
225     /** Server Version */
226     private String JavaDoc m_version = null;
227
228     /** DataSource */
229     private DataSource m_ds = null;
230     /** Server Session */
231     private Server m_server = null;
232
233     /*************************************************************************/
234
235     /**
236      * Get Name
237      * @return connection name
238      */

239     public String JavaDoc getName ()
240     {
241         return m_name;
242     }
243
244     /**
245      * Set Name
246      * @param name connection name
247      */

248     public void setName (String JavaDoc name)
249     {
250         m_name = name;
251     } // setName
252

253     /**
254      * Set Name
255      */

256     protected void setName ()
257     {
258         m_name = toString ();
259     } // setName
260

261     /*************/
262
263     /**
264      * Get Application Host
265      * @return apps host
266      */

267     public String JavaDoc getAppsHost ()
268     {
269         return m_apps_host;
270     }
271
272     /**
273      * Set Application Host
274      * @param apps_host apps host
275      */

276     public void setAppsHost (String JavaDoc apps_host)
277     {
278         m_apps_host = apps_host;
279         m_name = toString ();
280         m_okApps = false;
281     }
282
283     /**
284      * Get Apps Port
285      * @return port
286      */

287     public int getAppsPort ()
288     {
289         return m_apps_port;
290     }
291
292     /**
293      * Set Apps Port
294      * @param apps_port apps port
295      */

296     public void setAppsPort (int apps_port)
297     {
298         m_apps_port = apps_port;
299         m_okApps = false;
300     }
301
302     /**
303      * Set Apps Port
304      * @param apps_portString appd port as String
305      */

306     public void setAppsPort (String JavaDoc apps_portString)
307     {
308         try
309         {
310             setAppsPort (Integer.parseInt (apps_portString));
311         }
312         catch (Exception JavaDoc e)
313         {
314             System.err.println ("CConnection.setAppsPort " + e.toString ());
315         }
316     } // setAppsPort
317

318     /**
319      * Is Application Server OK
320      * @param tryContactAgain try to contact again
321      * @return true if Apps Server exists
322      */

323     public boolean isAppsServerOK (boolean tryContactAgain)
324     {
325         if (!tryContactAgain)
326             return m_okApps;
327
328         // Get Context
329
if (m_iContext == null)
330         {
331             getInitialContext (false);
332             if (!m_okApps)
333                 return false;
334         }
335
336         // Contact it
337
try
338         {
339             StatusHome statusHome = (StatusHome)m_iContext.lookup (StatusHome.JNDI_NAME);
340             Status status = statusHome.create ();
341             m_version = status.getDateVersion ();
342             status.remove ();
343             m_okApps = true;
344         }
345         catch (Exception JavaDoc ce)
346         {
347             m_okApps = false;
348         }
349         catch (Throwable JavaDoc t)
350         {
351             m_okApps = false;
352         }
353         return m_okApps;
354     } // isAppsOK
355

356     /**
357      * Test ApplicationServer
358      * @return Exception or null
359      */

360     public Exception JavaDoc testAppsServer ()
361     {
362         if (setAppsServerInfo ())
363             testDatabase ();
364         return getAppsServerException ();
365     } // testAppsServer
366

367     /**
368      * Get Server
369      * @return Server
370      */

371     public Server getServer()
372     {
373         if (m_server == null)
374         {
375             try
376             {
377                 InitialContext ic = getInitialContext (true);
378                 ServerHome serverHome = (ServerHome)ic.lookup (ServerHome.JNDI_NAME);
379                 if (serverHome != null)
380                     m_server = serverHome.create();
381             }
382             catch (Exception JavaDoc ex)
383             {
384                 log.error("CConnection.getServer", ex);
385             }
386         }
387         return m_server;
388     } // getServer
389

390
391     /**
392      * Get Apps Server Version
393      * @return db host name
394      */

395     public String JavaDoc getServerVersion ()
396     {
397         return m_version;
398     } // getServerVersion
399

400     /*************/
401
402     /**
403      * Get Database Host name
404      * @return db host name
405      */

406     public String JavaDoc getDbHost ()
407     {
408         return m_db_host;
409     }
410
411     /**
412      * Set Database host name
413      * @param db_host db host
414      */

415     public void setDbHost (String JavaDoc db_host)
416     {
417         m_db_host = db_host;
418         m_name = toString ();
419         m_okDB = false;
420     }
421
422     /**
423      * Get Database Name (SID)
424      * @return db name
425      */

426     public String JavaDoc getDbName ()
427     {
428         return m_db_name;
429     }
430
431     /**
432      * Set Database Name (SID)
433      * @param db_name db name
434      */

435     public void setDbName (String JavaDoc db_name)
436     {
437         m_db_name = db_name;
438         m_name = toString ();
439         m_okDB = false;
440     }
441
442     /**
443      * Get DB Port
444      * @return port
445      */

446     public int getDbPort ()
447     {
448         return m_db_port;
449     }
450
451     /**
452      * Set DB Port
453      * @param db_port db port
454      */

455     public void setDbPort (int db_port)
456     {
457         m_db_port = db_port;
458         m_okDB = false;
459     }
460
461     /**
462      * Set DB Port
463      * @param db_portString db port as String
464      */

465     public void setDbPort (String JavaDoc db_portString)
466     {
467         try
468         {
469             setDbPort (Integer.parseInt (db_portString));
470         }
471         catch (Exception JavaDoc e)
472         {
473             System.err.println ("CConnection.setDbPort " + e.toString ());
474         }
475     } // setDbPort
476

477     /**
478      * Get Database Password
479      * @return db password
480      */

481     public String JavaDoc getDbPwd ()
482     {
483         return m_db_pwd;
484     }
485
486     /**
487      * Set DB password
488      * @param db_pwd db user password
489      */

490     public void setDbPwd (String JavaDoc db_pwd)
491     {
492         m_db_pwd = db_pwd;
493         m_okDB = false;
494     }
495
496     /**
497      * Get Database User
498      * @return db user
499      */

500     public String JavaDoc getDbUid ()
501     {
502         return m_db_uid;
503     }
504
505     /**
506      * Set Database User
507      * @param db_uid db user id
508      */

509     public void setDbUid (String JavaDoc db_uid)
510     {
511         m_db_uid = db_uid;
512         m_name = toString ();
513         m_okDB = false;
514     }
515
516     /**
517      * RMI over HTTP
518      * @return true if RMI over HTTP
519      */

520     public boolean isRMIoverHTTP ()
521     {
522         return m_RMIoverHTTP;
523     }
524
525     public void setRMIoverHTTP (boolean RMIoverHTTP)
526     {
527         m_RMIoverHTTP = RMIoverHTTP;
528     }
529
530     public void setRMIoverHTTP (String JavaDoc RMIoverHTTP)
531     {
532         try
533         {
534             setRMIoverHTTP (Boolean.valueOf (RMIoverHTTP).booleanValue ());
535         }
536         catch (Exception JavaDoc e)
537         {
538             System.err.println ("CConnection.setRMIoverHTTP " + e.toString ());
539         }
540     }
541
542
543     /**
544      * Is DB via Firewall
545      * @return true if via firewall
546      */

547     public boolean isViaFirewall ()
548     {
549         return m_firewall;
550     }
551
552     public void setViaFirewall (boolean viaFirewall)
553     {
554         m_firewall = viaFirewall;
555         m_okDB = false;
556     }
557
558     public void setViaFirewall (String JavaDoc viaFirewallString)
559     {
560         try
561         {
562             setViaFirewall (Boolean.valueOf (viaFirewallString).booleanValue ());
563         }
564         catch (Exception JavaDoc e)
565         {
566             System.err.println ("CConnection.setViaFirewall " + e.toString ());
567         }
568     }
569
570     public String JavaDoc getFwHost ()
571     {
572         return m_fw_host;
573     }
574
575     public void setFwHost (String JavaDoc fw_host)
576     {
577         m_fw_host = fw_host;
578         m_okDB = false;
579     }
580
581     /**
582      * Get Firewall port
583      * @return firewall port
584      */

585     public int getFwPort ()
586     {
587         return m_fw_port;
588     }
589
590     /**
591      * Set Firewall port
592      * @param fw_port firewall port
593      */

594     public void setFwPort (int fw_port)
595     {
596         m_fw_port = fw_port;
597         m_okDB = false;
598     }
599
600     /**
601      * Set Firewall port
602      * @param fw_portString firewall port as String
603      */

604     public void setFwPort (String JavaDoc fw_portString)
605     {
606         try
607         {
608             setFwPort (Integer.parseInt (fw_portString));
609         }
610         catch (Exception JavaDoc e)
611         {
612             System.err.println ("CConnection.setFwPort " + e.toString ());
613         }
614     }
615
616     /**
617      * Is it a bequeath connection
618      * @return true if bequeath connection
619      */

620     public boolean isBequeath ()
621     {
622         return m_bequeath;
623     }
624
625     /**
626      * Set Bequeath
627      * @param bequeath bequeath connection
628      */

629     public void setBequeath (boolean bequeath)
630     {
631         m_bequeath = bequeath;
632         m_okDB = false;
633     }
634
635     /**
636      * Set Bequeath
637      * @param bequeathString bequeath connection as String (true/false)
638      */

639     public void setBequeath (String JavaDoc bequeathString)
640     {
641         try
642         {
643             setBequeath (Boolean.valueOf (bequeathString).booleanValue ());
644         }
645         catch (Exception JavaDoc e)
646         {
647             System.err.println ("CConnection.setBequeath " + e.toString ());
648         }
649     }
650
651     /**
652      * Get Database Type
653      * @return database type
654      */

655     public String JavaDoc getType ()
656     {
657         return m_type;
658     }
659
660     /**
661      * Set Database Type and default settings.
662      * Checked against installed databases
663      * @param type database Type, e.g. Database.DB_ORACLE
664      */

665     public void setType (String JavaDoc type)
666     {
667         for (int i = 0; i < Database.DB_NAMES.length; i++)
668         {
669             if (Database.DB_NAMES[i].equals (type))
670             {
671                 m_type = type;
672                 m_okDB = false;
673                 break;
674             }
675         }
676         // PostgreSQL defaults
677
if (isPostgreSQL ())
678         {
679             setBequeath (false);
680             setViaFirewall (false);
681             if (getDbPort () == DB_Oracle.DEFAULT_PORT)
682                 setDbPort (DB_PostgreSQL.DEFAULT_PORT);
683         }
684         // Oracle Defaults
685
else if (isOracle ())
686         {
687             if (getDbPort () == DB_PostgreSQL.DEFAULT_PORT)
688                 setDbPort (DB_Oracle.DEFAULT_PORT);
689             setFwPort (DB_Oracle.DEFAULT_CM_PORT);
690         }
691     } // setType
692

693     /**
694      * Supports BLOB
695      * @return true if BLOB is supported
696      */

697     public boolean supportsBLOB ()
698     {
699         return m_db.supportsBLOB ();
700     } // supportsBLOB
701

702
703     /**
704      * Is Oracle DB
705      * @return true if Oracle
706      */

707     public boolean isOracle ()
708     {
709         return Database.DB_ORACLE.equals (m_type);
710     } // isOracle
711

712     /**
713      * Is PostgreSQL DB
714      * @return true if PostgreSQL
715      */

716     public boolean isPostgreSQL ()
717     {
718         return Database.DB_POSTGRESQL.equals (m_type);
719     } // isPostgreSQL
720

721     /**
722      * Is Database Connection OK
723      * @return true if database connection is OK
724      */

725     public boolean isDatabaseOK ()
726     {
727         return m_okDB;
728     } // isDatabaseOK
729

730     /**
731      * Test Database Connection.
732      * -- Example --
733      * Database: PostgreSQL - 7.1.3
734      * Driver: PostgreSQL Native Driver - PostgreSQL 7.2 JDBC2
735      * -- Example --
736      * Database: Oracle - Oracle8i Enterprise Edition Release 8.1.7.0.0 - Production With the Partitioning option JServer Release 8.1.7.0.0 - Production
737      * Driver: Oracle JDBC driver - 9.0.1.1.0
738      * @return Exception or null
739      */

740     public Exception JavaDoc testDatabase ()
741     {
742         // the actual test
743
Connection conn = getConnection (true,
744                           Connection.TRANSACTION_READ_COMMITTED);
745         if (conn != null)
746         {
747             try
748             {
749                 DatabaseMetaData dbmd = conn.getMetaData ();
750                 m_info[0] = "Database=" + dbmd.getDatabaseProductName ()
751                             + " - " + dbmd.getDatabaseProductVersion ();
752                 m_info[0] = m_info[0].replace ('\n', ' ');
753                 m_info[1] = "Driver =" + dbmd.getDriverName ()
754                             + " - " + dbmd.getDriverVersion ();
755                 m_info[1] = m_info[1].replace ('\n', ' ');
756                 System.out.println (m_info[0]);
757                 System.out.println (m_info[1]);
758                 conn.close ();
759             }
760             catch (Exception JavaDoc e)
761             {
762                 System.err.println ("CConnectiom.testDatabase - " + e);
763             }
764         }
765         return getDatabaseException (); // from opening
766
} // testDatabase
767

768     /*************************************************************************/
769
770     /**
771      * Short String representation
772      * @return appsHost{dbHost-sid-uid}
773      */

774     public String JavaDoc toString ()
775     {
776         StringBuffer JavaDoc sb = new StringBuffer JavaDoc (m_apps_host);
777         sb.append ("{").append (m_db_host)
778           .append ("-").append (m_db_name)
779           .append ("-").append (m_db_uid)
780           .append ("}");
781         return sb.toString ();
782     } // toString
783

784     /**
785      * String representation.
786      * Used also for Instanciation
787      * @see setAttributes(String) setAttributes
788      * @return string representation
789      */

790     public String JavaDoc toStringLong ()
791     {
792         StringBuffer JavaDoc sb = new StringBuffer JavaDoc ("CConnection[");
793         sb.append ("name=").append (m_name)
794           .append (",AppsHost=").append (m_apps_host)
795           .append (",AppsPort=").append (m_apps_port)
796           .append (",RMIoverHTTP=").append (m_RMIoverHTTP)
797           .append (",type=").append (m_type)
798           .append (",DBhost=").append (m_db_host)
799           .append (",DBport=").append (m_db_port)
800           .append (",DBname=").append (m_db_name)
801           .append (",BQ=").append (m_bequeath)
802           .append (",FW=").append (m_firewall)
803           .append (",FWhost=").append (m_fw_host)
804           .append (",FWport=").append (m_fw_port)
805           .append (",UID=").append (m_db_uid)
806           .append (",PWD=").append (m_db_pwd)
807           ;
808         sb.append ("]");
809         return sb.toString ();
810     } // toStringLong
811

812     /**
813      * Set Attributes from String (pases toStringLong())
814      * @param attributes attributes
815      */

816     private void setAttributes (String JavaDoc attributes)
817     {
818         try
819         {
820             setName (attributes.substring (attributes.indexOf ("name=") + 5, attributes.indexOf (",AppsHost=")));
821             setAppsHost (attributes.substring (attributes.indexOf ("AppsHost=") + 9, attributes.indexOf (",AppsPort=")));
822             if (attributes.indexOf(",RMIoverHTTP=") > 0) // new attribute, may not exist
823
{
824                 setAppsPort (attributes.substring (attributes.indexOf ("AppsPort=") + 9, attributes.indexOf (",RMIoverHTTP=")));
825                 setRMIoverHTTP (attributes.substring (attributes.indexOf ("RMIoverHTTP=") + 12, attributes.indexOf (",type=")));
826             }
827             else
828                 setAppsPort (attributes.substring (attributes.indexOf ("AppsPort=") + 9, attributes.indexOf (",type=")));
829             //
830
setType (attributes.substring (attributes.indexOf ("type=") + 5, attributes.indexOf (",DBhost=")));
831             setDbHost (attributes.substring (attributes.indexOf ("DBhost=") + 7, attributes.indexOf (",DBport=")));
832             setDbPort (attributes.substring (attributes.indexOf ("DBport=") + 7, attributes.indexOf (",DBname=")));
833             setDbName (attributes.substring (attributes.indexOf ("DBname=") + 7, attributes.indexOf (",BQ=")));
834             //
835
setBequeath (attributes.substring (attributes.indexOf ("BQ=") + 3, attributes.indexOf (",FW=")));
836             setViaFirewall (attributes.substring (attributes.indexOf ("FW=") + 3, attributes.indexOf (",FWhost=")));
837             setFwHost (attributes.substring (attributes.indexOf ("FWhost=") + 7, attributes.indexOf (",FWport=")));
838             setFwPort (attributes.substring (attributes.indexOf ("FWport=") + 7, attributes.indexOf (",UID=")));
839             //
840
setDbUid (attributes.substring (attributes.indexOf ("UID=") + 4, attributes.indexOf (",PWD=")));
841             setDbPwd (attributes.substring (attributes.indexOf ("PWD=") + 4, attributes.indexOf ("]")));
842             //
843
}
844         catch (Exception JavaDoc e)
845         {
846             System.err.println ("CConnection.setAttributes - " + attributes
847               + " - " + e.toString ());
848         }
849     } // setAttributes
850

851     /**
852      * Equals
853      * @param o object
854      * @return true if o equals this
855      */

856     public boolean equals (Object JavaDoc o)
857     {
858         if (o instanceof CConnection)
859         {
860             CConnection cc = (CConnection)o;
861             if (cc.getAppsHost ().equals (m_apps_host)
862               && cc.getAppsPort () == m_apps_port
863               && cc.getDbHost ().equals (m_db_host)
864               && cc.getDbPort () == m_db_port
865               && cc.isRMIoverHTTP() == m_RMIoverHTTP
866               && cc.getDbName ().equals (m_db_name)
867               && cc.getType ().equals (m_type)
868               && cc.getDbUid ().equals (m_db_uid)
869               && cc.getDbPwd ().equals (m_db_pwd))
870                 return true;
871         }
872         return false;
873     } // equals
874

875     /**
876      * Get Info.
877      * - Database, Driver, Status Info
878      * @return info
879      */

880     public String JavaDoc getInfo ()
881     {
882         StringBuffer JavaDoc sb = new StringBuffer JavaDoc (m_info[0]);
883         sb.append ("\n").append (m_info[1])
884           .append ("\n").append (getDatabase ().toString ())
885           .append ("\nAppsServerOK=").append (isAppsServerOK (false)).append (
886           ", DatabaseOK=").append (isDatabaseOK ());
887         return sb.toString ();
888     } // getInfo
889

890     /*************************************************************************/
891
892     /**
893      * Hashcode
894      * @return hashcode of name
895      */

896     public int hashCode ()
897     {
898         return m_name.hashCode ();
899     } // hashCode
900

901     /**
902      * Get Database
903      * @return database
904      */

905     public CompiereDatabase getDatabase ()
906     {
907         // different driver
908
if (m_db != null && !m_db.getName ().equals (m_type))
909             m_db = null;
910
911         if (m_db == null)
912         {
913             try
914             {
915                 for (int i = 0; i < Database.DB_NAMES.length; i++)
916                 {
917                     if (Database.DB_NAMES[i].equals (m_type))
918                     {
919                         m_db = (CompiereDatabase)Database.DB_CLASSES[i].
920                                newInstance ();
921                         break;
922                     }
923                 }
924             }
925             catch (Exception JavaDoc e)
926             {
927                 System.err.println ("CConnection.getDatabase " + e.toString ());
928             }
929         }
930         return m_db;
931     } // getDatabase
932

933     /**
934      * Get Connection String
935      * @return connection string
936      */

937     public String JavaDoc getConnectionURL ()
938     {
939         getDatabase (); // updates m_db
940
if (m_db != null)
941             return m_db.getConnectionURL (this);
942         else
943             return "";
944     } // getConnectionString
945

946     /**
947      * Get Server Connection - do close
948      * @param autoCommit true if autocommit connection
949      * @param trxLevel Connection transaction level
950      * @return Connection
951      */

952     public Connection getServerConnection (boolean autoCommit, int trxLevel)
953     {
954         Connection conn = null;
955         // Server Connection
956
if (m_ds != null)
957         {
958             try
959             {
960                 conn = m_ds.getConnection ();
961                 conn.setAutoCommit (autoCommit);
962                 conn.setTransactionIsolation (trxLevel);
963                 m_okDB = true;
964             }
965             catch (SQLException ex)
966             {
967                 m_dbException = ex;
968                 log.error ("createServerConnection", ex);
969             }
970         }
971
972         // Server
973
return conn;
974     } // getServerConnection
975

976
977     /**
978      * Get Connection - no not close
979      * @param autoCommit true if autocommit connection
980      * @param trxLevel Connection transaction level
981      * @return Connection
982      */

983     public Connection getConnection (boolean autoCommit, int trxLevel)
984     {
985         Connection conn = null;
986         getDatabase (); // updates m_db
987
if (m_db == null)
988             return null;
989         //
990
m_dbException = null;
991         m_okDB = false;
992         try
993         {
994             DriverManager.registerDriver (m_db.getDriver ());
995             DriverManager.setLoginTimeout (Database.CONNECTION_TIMEOUT);
996             conn = DriverManager.getConnection (getConnectionURL (), getDbUid (), getDbPwd ());
997             conn.setAutoCommit (autoCommit);
998             conn.setTransactionIsolation (trxLevel);
999             m_okDB = true;
1000        }
1001        catch (UnsatisfiedLinkError JavaDoc ule)
1002        {
1003            System.err.println ("CConection.getConnection - " + getConnectionURL ()
1004                + " - Did you set the LD_LIBRARY_PATH ? - " + ule.toString ());
1005        }
1006        catch (Exception JavaDoc ex)
1007        {
1008            m_dbException = ex;
1009            System.err.println ("CConection.getConnection - " + getConnectionURL ()
1010                + " - " + ex.toString ());
1011            ex.printStackTrace();
1012        }
1013        return conn;
1014    } // getConnection
1015

1016    /**
1017     * Get Database Exception of last connection attempt
1018     * @return Exception or null
1019     */

1020    public Exception JavaDoc getDatabaseException ()
1021    {
1022        return m_dbException;
1023    } // getConnectionException
1024

1025    /*************************************************************************/
1026
1027    private InitialContext m_iContext = null;
1028    private Hashtable m_env = null;
1029
1030    /**
1031     * Get Application Server Initial Context
1032     * @param useCache if true, use existing cache
1033     * @return Initial Context or null
1034     */

1035    public InitialContext getInitialContext (boolean useCache)
1036    {
1037        if (useCache && m_iContext != null)
1038            return m_iContext;
1039
1040        // Set Environment
1041
if (m_env == null || !useCache)
1042            m_env = getInitialEnvironment(getAppsHost(), getAppsPort(), isRMIoverHTTP());
1043        String JavaDoc connect = (String JavaDoc)m_env.get(Context.PROVIDER_URL);
1044        Env.setContext(Env.getCtx(), Context.PROVIDER_URL, connect);
1045
1046        // Get Context
1047
m_iContext = null;
1048        try
1049        {
1050            m_iContext = new InitialContext (m_env);
1051        }
1052        catch (Exception JavaDoc ex)
1053        {
1054            m_okApps = false;
1055            m_appsException = ex;
1056            if (connect == null)
1057                connect = (String JavaDoc)m_env.get(Context.PROVIDER_URL);
1058            System.err.println ("CConection.getInitialContext - " + connect
1059                + "\n - " + ex.toString ()
1060                + "\n - " + m_env);
1061            if (Log.isTraceLevel(10))
1062                ex.printStackTrace();
1063        }
1064        return m_iContext;
1065    } // getInitialContext
1066

1067    /**
1068     * Get Initial Environment
1069     * @param AppsHost host
1070     * @param AppsPort port
1071     * @param RMIoverHTTP true if tunnel through HTTP
1072     * @return environment
1073     */

1074    public static Hashtable getInitialEnvironment (String JavaDoc AppsHost, int AppsPort,
1075        boolean RMIoverHTTP)
1076    {
1077        // Set Environment
1078
Hashtable env = new Hashtable ();
1079        String JavaDoc connect = AppsHost;
1080        if (RMIoverHTTP)
1081        {
1082            env.put (Context.INITIAL_CONTEXT_FACTORY, "org.jboss.naming.HttpNamingContextFactory");
1083            if (AppsHost.indexOf("://") == -1)
1084                connect = "http://" + AppsHost + ":" + AppsPort
1085                        + "/invoker/JNDIFactory";
1086            env.put(Context.PROVIDER_URL, connect);
1087        }
1088        else
1089        {
1090            env.put (Context.INITIAL_CONTEXT_FACTORY,"org.jnp.interfaces.NamingContextFactory");
1091            if (AppsHost.indexOf("://") == -1)
1092                connect = "jnp://" + AppsHost + ":" + AppsPort;
1093            env.put (Context.PROVIDER_URL, connect);
1094        }
1095        env.put (Context.URL_PKG_PREFIXES, "org.jboss.naming:org.jnp.interfaces");
1096        // HTTP - default timeout 0
1097
env.put (org.jnp.interfaces.TimedSocketFactory.JNP_TIMEOUT, "5000"); // timeout in ms
1098
env.put (org.jnp.interfaces.TimedSocketFactory.JNP_SO_TIMEOUT, "5000");
1099        // JNP - default timeout 5 sec
1100
env.put(org.jnp.interfaces.NamingContext.JNP_DISCOVERY_TIMEOUT, "5000");
1101        return env;
1102    } // getInitialEnvironment
1103

1104    /**
1105     * Get Initial Context
1106     * @param env environment
1107     * @return Initial Context
1108     */

1109    public static InitialContext getInitialContext (Hashtable env)
1110    {
1111        InitialContext iContext = null;
1112        try
1113        {
1114            iContext = new InitialContext (env);
1115        }
1116        catch (Exception JavaDoc ex)
1117        {
1118            System.err.println ("CConection.getInitialContext - " + env.get(Context.PROVIDER_URL)
1119                + "\n - " + ex.toString ()
1120                + "\n - " + env);
1121            iContext = null;
1122            if (Log.isTraceLevel(10))
1123                ex.printStackTrace();
1124        }
1125        return iContext;
1126    } // getInitialContext
1127

1128
1129    /**
1130     * Set Application Server Status.
1131     * update okApps
1132     * @return true ik OK
1133     */

1134    private boolean setAppsServerInfo ()
1135    {
1136        m_okApps = false;
1137        m_appsException = null;
1138        //
1139
getInitialContext (false);
1140        if (m_iContext == null)
1141            return m_okApps;
1142
1143        // Prevent error trace
1144
Logger.switchLoggingOff();
1145        try
1146        {
1147            StatusHome statusHome = (StatusHome)m_iContext.lookup (StatusHome.JNDI_NAME);
1148            Status status = statusHome.create ();
1149            //
1150
updateInfo (status);
1151            //
1152
status.remove ();
1153            m_okApps = true;
1154        }
1155        catch (CommunicationException ce) // not a "real" error
1156
{
1157            // m_appsException = ce;
1158
String JavaDoc connect = (String JavaDoc)m_env.get(Context.PROVIDER_URL);
1159            System.err.println ("CConection.setAppsServerInfo - " + connect
1160                + "\n - " + ce.toString ()
1161                + "\n - " + m_env);
1162        }
1163        catch (Exception JavaDoc e)
1164        {
1165            m_appsException = e;
1166            String JavaDoc connect = (String JavaDoc)m_env.get(Context.PROVIDER_URL);
1167            System.err.println ("CConection.setAppsServerInfo - " + connect
1168                + "\n - " + e.toString ()
1169                + "\n - " + m_env);
1170        }
1171        Logger.switchLoggingOn();
1172        return m_okApps;
1173    } // setAppsServerInfo
1174

1175    /**
1176     * Get Last Exception of Apps Server Connection attempt
1177     * @return Exception or null
1178     */

1179    public Exception JavaDoc getAppsServerException ()
1180    {
1181        return m_appsException;
1182    } // getAppsServerException
1183

1184    /**
1185     * Update Connection Info from Apps Server
1186     * @param svr Apps Server Status
1187     * @throws Exception
1188     */

1189    private void updateInfo (Status svr) throws Exception JavaDoc
1190    {
1191        if (svr == null)
1192            throw new IllegalArgumentException JavaDoc ("AppsServer was NULL");
1193
1194        setDbHost (svr.getDbHost ());
1195        setDbPort (svr.getDbPort ());
1196        setDbName (svr.getDbName ());
1197        setDbUid (svr.getDbUid ());
1198        setDbPwd (svr.getDbPwd ());
1199        setBequeath (false);
1200        //
1201
setFwHost (svr.getFwHost ());
1202        setFwPort (svr.getFwPort ());
1203        if (getFwHost ().length () == 0)
1204            setViaFirewall (false);
1205        m_version = svr.getDateVersion ();
1206
1207    } // update Info
1208

1209    /**
1210     * Convert Statement
1211     * @param origStatement original statement (Oracle notation)
1212     * @return converted Statement
1213     * @throws Exception
1214     */

1215    public String JavaDoc convertStatement (String JavaDoc origStatement)
1216      throws Exception JavaDoc
1217    {
1218        // make sure we have a good database
1219
if (m_db != null && !m_db.getName ().equals (m_type))
1220            getDatabase ();
1221        if (m_db != null)
1222            return m_db.convertStatement (origStatement);
1223        throw new Exception JavaDoc (
1224          "CConnection.convertStatement - No Converstion Database");
1225    } // convertStatement
1226

1227
1228    /**
1229     * Testing
1230     * @param args ignored
1231     */

1232    public static void main (String JavaDoc[] args)
1233    {
1234        boolean server = true;
1235        if (args.length == 0)
1236            System.out.println("CConnection <server|client>");
1237        else
1238            server = "server".equals(args[0]);
1239        System.out.println("CConnection - " + (server ? "server" : "client"));
1240        //
1241
if (server)
1242        {
1243            Compiere.initClientLog();
1244            Compiere.startupServer(null);
1245        }
1246        else
1247            Compiere.startupClient();
1248        //
1249
System.out.println ("Connection = ");
1250        // CConnection[name=localhost{dev-dev1-compiere},AppsHost=localhost,AppsPort=1099,type=Oracle,DBhost=dev,DBport=1521,DBname=dev1,BQ=false,FW=false,FWhost=,FWport=1630,UID=compiere,PWD=compiere]
1251
System.out.println (Ini.getProperty (Ini.P_CONNECTION));
1252
1253        CConnection cc = CConnection.get ();
1254        System.out.println (">> " + cc.toStringLong ());
1255        Connection con = cc.getConnection (false,
1256                         Connection.TRANSACTION_READ_COMMITTED);
1257        new CConnectionDialog(cc);
1258    } // main
1259

1260} // CConnection
1261
Popular Tags