Advertisement
Guest User

Untitled

a guest
May 9th, 2017
72
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 1.78 KB | None | 0 0
  1. package anaman.locator;
  2.  
  3. import java.sql.Connection;
  4. import java.sql.DriverManager;
  5. import java.sql.SQLException;
  6.  
  7. import javax.activation.DataSource;
  8. import javax.naming.Context;
  9. import javax.naming.InitialContext;
  10. import javax.naming.NamingException;
  11.  
  12. import anaman.exception.AnamanException;
  13.  
  14. public class ServiceLocator {
  15.     private final String driver = "org.hsqldb.jdbcDriver";
  16.  
  17.     private final String dbPath = "C:\\Documents and Settings\\user\\Desktop\\build\\Anaman\\WebContent\\hsqldb\\anaman";
  18.     //private final String dbPath = "hsql://localhost:59999/anaman";
  19.    
  20.     private final String url = "jdbc:hsqldb:" + dbPath;
  21.     private final String user = "sa";
  22.     private final String password = "";
  23.  
  24.     private static ServiceLocator instance = new ServiceLocator();
  25.  
  26.     private ServiceLocator() {
  27.     }
  28.  
  29.     public static ServiceLocator getInstance() {
  30.         return instance;
  31.     }
  32.  
  33.     public Connection getConnection() throws AnamanException {
  34.         Connection conn = null;
  35.         try {
  36.             Class.forName(driver);
  37.             conn = DriverManager.getConnection(url, user, password);
  38.         } catch (ClassNotFoundException driver) {
  39.             System.out.println("Driver not found: " + driver.getMessage());
  40.         } catch (SQLException dataSource) {
  41.             System.out.println("Error in connecting to data source: "
  42.                     + dataSource.getMessage());
  43.         }
  44.         return conn;
  45.     }
  46.    
  47.     public DataSource getDataSource() throws AnamanException {
  48.         DataSource datasource = null;
  49.         try {
  50.             Context initContext = new InitialContext();
  51.             Context envContext = (Context)initContext.lookup("java:/comp/env");
  52.             datasource = (DataSource)envContext.lookup("jdbc/AnamanDB");
  53.         } catch (NamingException e) {
  54.             System.out.println("[AnamanServiceLocator] - error connecting to datasource: " +
  55.                     e.getExplanation());
  56.         }
  57.         return datasource;
  58.     }
  59. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement