1 package com.dotmarketing.db; 2 3 import java.sql.Connection ; 4 5 import javax.naming.Context ; 6 import javax.naming.InitialContext ; 7 import javax.sql.DataSource ; 8 9 import com.dotmarketing.exception.DotRuntimeException; 10 import com.dotmarketing.util.Logger; 11 12 public class DbConnectionFactory { 13 14 15 public static final String MYSQL = "MySQL"; 16 public static final String POSTGRESQL = "PostgreSQL"; 17 public static final String ORACLE = "Oracle"; 18 public static final String MSSQL = "Microsoft SQL Server"; 19 20 private static String _dbType = null; 21 22 private static ThreadLocal connectionHolder = new ThreadLocal (); 23 24 public static Connection getConnection() { 25 26 try { 27 Connection connection = (Connection ) connectionHolder.get(); 28 29 if (connection == null || connection.isClosed()) { 30 Context ctx = (Context ) new InitialContext ().lookup("java:comp/env"); 31 DataSource db = (DataSource ) ctx.lookup("jdbc/LiferayPool"); 32 connection = db.getConnection(); 33 connectionHolder.set(connection); 34 } 35 36 return connection; 37 } catch (Exception e) { 38 Logger.error(DbConnectionFactory.class, "---------- DBConnectionFactory: error getting dbconnection ---------------", e); 39 throw new DotRuntimeException(e.toString()); 40 } 41 } 42 43 public static void closeConnection() { 44 try { 45 Connection connection = (Connection ) connectionHolder.get(); 46 47 if (connection != null) { 48 if (!connection.isClosed()) 49 connection.close(); 50 connectionHolder.set(null); 51 } 52 } catch (Exception e) { 53 Logger.error(DbConnectionFactory.class, "---------- DBConnectionFactory: error closing the db dbconnection ---------------", e); 54 throw new DotRuntimeException(e.toString()); 55 } 56 57 } 58 59 public static String getDBType() { 60 61 65 66 if (_dbType != null) { 67 return _dbType; 68 } 69 70 Connection conn = getConnection(); 71 72 try { 73 _dbType = conn.getMetaData().getDatabaseProductName(); 74 75 } catch (Exception e) { 76 77 } finally { 78 try { 79 closeConnection(); 80 } catch (Exception e) { 81 82 } 83 } 84 85 return _dbType; 86 } 87 88 public static String getDBTrue() { 89 String x = getDBType(); 90 91 if (MYSQL.equals(x)) { 92 return "1"; 93 } else if (POSTGRESQL.equals(x)) { 94 return "'true'"; 95 } else if (MSSQL.equals(x)) { 96 return "1"; 97 } else if (ORACLE.equals(x)) { 98 return "1"; 99 } 100 return "true"; 101 102 } 103 104 public static String getDBFalse() { 105 String x = getDBType(); 106 107 if (MYSQL.equals(x)) { 108 return "0"; 109 } else if (POSTGRESQL.equals(x)) { 110 return "'false'"; 111 } else if (MSSQL.equals(x)) { 112 return "0"; 113 } else if (ORACLE.equals(x)) { 114 return "0"; 115 } 116 return "false"; 117 118 } 119 120 } 121 | Popular Tags |