Пример #1
1
 private Connection openConnection(Class<? extends Driver> driverClass, Properties properties)
     throws Exception {
   assert properties != null;
   try {
     return DriverManager.getConnection(url, properties);
   } catch (Exception e) {
     // if the current class loader can not access the driver class, create driver class directly
     try {
       Driver driverObject = driverClass.getConstructor().newInstance();
       Connection connection = driverObject.connect(url, properties);
       if (connection == null) {
         throw new IllegalStateException(
             MessageFormat.format(
                 "Driver class {0} may not support {1}", driverClass.getName(), url));
       }
       return connection;
     } catch (RuntimeException inner) {
       LOG.debug(
           MessageFormat.format(
               "Failed to resolve driver class (internal error): {0} (on {1})",
               driverClass.getName(), driverClass.getClassLoader()),
           e);
     } catch (Exception inner) {
       LOG.debug(
           MessageFormat.format(
               "Failed to resolve driver class: {0} (on {1})",
               driverClass.getName(), driverClass.getClassLoader()),
           e);
     }
     throw e;
   }
 }
Пример #2
0
  @Override
  public Connection connect(String url, Properties info) throws SQLException {
    if (!url.startsWith("jdbc:quantumdb:")) {
      return null;
    }
    url = url.substring(0, 4) + ":" + url.substring(15, url.length());

    try {
      Class.forName("org.postgresql.Driver");
    } catch (ClassNotFoundException e) {
      throw new SQLException("Could not locate delegate driver.", e);
    }

    String version = parseVersion(url);
    if (version != null) {
      String applicationName = info.getProperty("ApplicationName");
      if (applicationName != null && !applicationName.equals("")) {
        applicationName += " - " + version;
      } else {
        applicationName = "QuantumDB driver - " + version;
      }
      info.setProperty("ApplicationName", applicationName);
    }

    this.delegate = DriverManager.getDriver(url);
    Connection connection = delegate.connect(url, info);
    QueryRewriter queryRewriter = new PostgresqlQueryRewriter();
    this.transformer = new Transformer(connection, queryRewriter, version);

    return new ProxyConnection(connection, transformer);
  }
  @Override
  public void run() {
    Connection conn = null;
    try {
      Driver d = new SimpleDriver();
      conn = d.connect("jdbc:simpledb://localhost", null);

      // conn.setTransactionIsolation(Connection.TRANSACTION_SERIALIZABLE);

      Statement stmt = conn.createStatement();

      //			try {
      //				Thread.sleep(5000);
      //			} catch (InterruptedException e) {
      //				// TODO Auto-generated catch block
      //				e.printStackTrace();
      //			}
      for (int i = 0; i < 3; i++) {
        String cmd;
        if (i % 2 == 0) cmd = "update STUDENT set MajorId=30 " + "where SName = 'amy'";
        else cmd = "update STUDENT set MajorId=20 " + "where SName = 'amy'";
        stmt.executeUpdate(cmd);
        System.out.println("Amy's major changed.");
      }
    } catch (SQLException e) {
      e.printStackTrace();
    } finally {
      try {
        System.out.println(conn.getTransactionIsolation());
        if (conn != null) conn.close();
      } catch (SQLException e) {
        e.printStackTrace();
      }
    }
  }
  public static void main(String[] args) {
    try {
      Driver d = new SimpleDriver();
      conn = d.connect("jdbc:simpledb://localhost", null);

      Reader rdr = new InputStreamReader(System.in);
      BufferedReader br = new BufferedReader(rdr);

      while (true) {
        // process one line of input
        System.out.print("\nSQL> ");
        String cmd = br.readLine().trim();
        System.out.println();
        if (cmd.startsWith("exit")) break;
        else if (cmd.startsWith("select")) doQuery(cmd);
        else doUpdate(cmd);
      }
    } catch (Exception e) {
      e.printStackTrace();
    } finally {
      try {
        if (conn != null) conn.close();
      } catch (Exception e) {
        e.printStackTrace();
      }
    }
  }
  /**
   * Open (if necessary) and return a database connection for use by this class.
   *
   * @exception SQLException if a database error occurs
   */
  protected Connection getConnection() throws SQLException {
    if (connectionURL == null)
      connectionURL = this.extraProperties.getProperty("jdbc.connectionURL");

    if (connectionName == null)
      connectionName = this.extraProperties.getProperty("jdbc.connectionName");

    if (connectionPassword == null)
      connectionPassword = this.extraProperties.getProperty("jdbc.connectionPassword");

    if (driverName == null) driverName = this.extraProperties.getProperty("jdbc.driverName");

    Connection conn = null;

    // Instantiate our database driver if necessary
    if (driver == null) {
      try {
        Class clazz = Class.forName(driverName);
        driver = (Driver) clazz.newInstance();
      } catch (Throwable e) {
        throw new SQLException(e.getMessage());
      }
    }

    // Open a new connection
    Properties props = new Properties();
    if (connectionName != null) props.put("user", connectionName);

    if (connectionPassword != null) props.put("password", connectionPassword);

    conn = driver.connect(connectionURL, props);
    conn.setAutoCommit(false);

    return (conn);
  }
Пример #6
0
  public static void main(String[] args) {
    Connection conn = null;
    try {
      // Step 1: connect to database server
      Driver d = new SimpleDriver();
      conn = d.connect("jdbc:simpledb://localhost", null);

      // Step 2: execute the query
      Statement stmt = conn.createStatement();
      String qry = "select SName, DName " + "from DEPT, STUDENT " + "where MajorId = DId";
      ResultSet rs = stmt.executeQuery(qry);

      // Step 3: loop through the result set
      System.out.println("Name\tMajor");
      while (rs.next()) {
        String sname = rs.getString("SName");
        String dname = rs.getString("DName");
        System.out.println(sname + "\t" + dname);
      }
      rs.close();
    } catch (SQLException e) {
      e.printStackTrace();
    } finally {
      // Step 4: close the connection
      try {
        if (conn != null) conn.close();
      } catch (SQLException e) {
        e.printStackTrace();
      }
    }
  }
Пример #7
0
  /**
   * Get a Connection to the database from the underlying driver that this DriverSpy is spying on.
   * If logging is not enabled, an actual Connection to the database returned. If logging is
   * enabled, a ConnectionSpy object which wraps the real Connection is returned.
   *
   * @param url JDBC connection URL .
   * @param info a list of arbitrary string tag/value pairs as connection arguments. Normally at
   *     least a "user" and "password" property should be included.
   * @return a <code>Connection</code> object that represents a connection to the URL.
   * @throws SQLException if a database access error occurs
   */
  public Connection connect(String url, Properties info) throws SQLException {
    Driver d = getUnderlyingDriver(url);
    if (d == null) {
      return null;
    }

    // get actual URL that the real driver expects
    // (strip off "jdbc:log4" from url)
    url = url.substring(9);

    lastUnderlyingDriverRequested = d;
    Connection c = d.connect(url, info);

    if (c == null) {
      throw new SQLException("invalid or unknown driver url: " + url);
    }
    if (log.isJdbcLoggingEnabled()) {
      ConnectionSpy cspy = new ConnectionSpy(c);
      RdbmsSpecifics r = null;
      String dclass = d.getClass().getName();
      if (dclass != null && dclass.length() > 0) {
        r = (RdbmsSpecifics) rdbmsSpecifics.get(dclass);
      }

      if (r == null) {
        r = defaultRdbmsSpecifics;
      }
      cspy.setRdbmsSpecifics(r);
      return cspy;
    } else {
      return c;
    }
  }
  /** {@inheritDoc} */
  public void connect(InetAddress address, int port, int timeout) throws IOException, Exception {
    log().info("connecting to JDBC on " + address);
    if (log().isDebugEnabled()) {
      log().debug("Loading JDBC driver: '" + getDbDriver() + "'");
    }
    Driver driver = (Driver) Class.forName(getDbDriver()).newInstance();
    if (log().isDebugEnabled()) {
      log().debug("JDBC driver loaded: '" + getDbDriver() + "'");
    }

    String url = DBTools.constructUrl(getUrl(), address.getCanonicalHostName());
    if (log().isDebugEnabled()) {
      log().debug("Constructed JDBC url: '" + url + "'");
    }

    Properties props = new Properties();
    props.setProperty("user", getUser());
    props.setProperty("password", getPassword());
    props.setProperty("timeout", String.valueOf(timeout / 1000));
    m_connection = driver.connect(url, props);

    if (log().isDebugEnabled()) {
      log()
          .debug(
              "Got database connection: '"
                  + m_connection
                  + "' ("
                  + url
                  + ", "
                  + getUser()
                  + ", "
                  + getPassword()
                  + ")");
    }
  }
Пример #9
0
 private void testLobInFiles() throws Exception {
   deleteDb("oldVersion");
   Connection conn;
   Statement stat;
   conn = driver.connect("jdbc:h2:" + getBaseDir() + "/oldVersion", null);
   stat = conn.createStatement();
   stat.execute("create table test(id int primary key, b blob, c clob)");
   PreparedStatement prep = conn.prepareStatement("insert into test values(?, ?, ?)");
   prep.setInt(1, 0);
   prep.setNull(2, Types.BLOB);
   prep.setNull(3, Types.CLOB);
   prep.execute();
   prep.setInt(1, 1);
   prep.setBytes(2, new byte[0]);
   prep.setString(3, "");
   prep.execute();
   prep.setInt(1, 2);
   prep.setBytes(2, new byte[5]);
   prep.setString(3, "\u1234\u1234\u1234\u1234\u1234");
   prep.execute();
   prep.setInt(1, 3);
   prep.setBytes(2, new byte[100000]);
   prep.setString(3, new String(new char[100000]));
   prep.execute();
   conn.close();
   conn = DriverManager.getConnection("jdbc:h2:" + getBaseDir() + "/oldVersion", new Properties());
   stat = conn.createStatement();
   checkResult(stat.executeQuery("select * from test order by id"));
   stat.execute("create table test2 as select * from test");
   checkResult(stat.executeQuery("select * from test2 order by id"));
   stat.execute("delete from test");
   conn.close();
 }
Пример #10
0
  public static void connectToDB() throws Exception {
    if (connection == null) {
      info = new Properties();
      info.load(new FileInputStream("src/java-test/tests.properties"));

      url = info.getProperty("url");
      driver =
          (Driver)
              Class.forName(
                      DatabaseFactory.getInstance().findDefaultDriver(url),
                      true,
                      Thread.currentThread().getContextClassLoader())
                  .newInstance();

      connection = driver.connect(url, info);

      if (connection == null) {
        throw new DatabaseException(
            "Connection could not be created to "
                + url
                + " with driver "
                + driver.getClass().getName()
                + ".  Possibly the wrong driver for the given database URL");
      }

      jdbcConnection = new JdbcConnection(connection);
    }
  }
Пример #11
0
 @Test
 public void testStateNotSupportedException() throws SQLException {
   RuntimeException runtimeException =
       new RuntimeException(new SQLException("test", HiveDriver.SQL_STATE_NOT_SUPPORTED, null));
   when(delegate.acceptsURL(testUrl)).thenReturn(true);
   when(delegate.connect(testUrl, properties)).thenThrow(runtimeException);
   assertNull(hiveDriver.connect(testUrl, properties));
   verify(delegate).connect(testUrl, properties);
 }
Пример #12
0
  /** ��ͼ����һ������ URL ����ݿ����ӡ� */
  public Connection connect(String url, Properties info) throws SQLException {
    Properties p = new Properties();
    p.putAll(info);
    Connection conn = driver.connect(url, p);

    CharsetParameter param = new CharsetParameter();
    param.setClientEncoding(this.getClientEncoding());
    param.setServerEncoding(this.getServerEncoding());
    return factory.getConnection(param, conn);
  }
Пример #13
0
  public static Connection get(NameValuePairs nvp) {
    try {
      nvp.merge(props);

      return driver.connect(url, nvp.toProperties());
    } catch (java.sql.SQLException e) {
      e.printStackTrace();
    }
    return null;
  }
 public void close() {
   Connection connection = (Connection) getRawConnection();
   if (connection == null) {
     return;
   }
   synchronized (sDerbyConnections) {
     int count = ((Integer) sConnectionReferenceCount.get(connection)).intValue();
     if (count == 1) {
       /*
        * If this is the last reference to the connection, close the
        * connection.
        */
       String baseDBURL = getBaseDBURL();
       try {
         /* The particulars of closing the connection. */
         String driverClass =
             getDriverDefinition()
                 .getProperty(IJDBCDriverDefinitionConstants.DRIVER_CLASS_PROP_ID);
         Driver driver =
             (Driver) connection.getClass().getClassLoader().loadClass(driverClass).newInstance();
         driver.connect(
             baseDBURL + ";shutdown=true", // $NON-NLS-1$
             new Properties());
       } catch (InstantiationException e) {
         /*
          * We shouldn't see this, because we needed this to create
          * the connection
          */
       } catch (IllegalAccessException e) {
         /*
          * We shouldn't see this, because we needed this to create
          * the connection
          */
       } catch (ClassNotFoundException e) {
         /*
          * We shouldn't see this, because we needed this to create
          * the connection
          */
       } catch (SQLException e) {
         // Successfully closed the connection
         sConnectionReferenceCount.remove(connection);
         sDerbyConnections.remove(baseDBURL);
       } catch (Exception e) {
         /*
          * Can't get the driver. This might happen if the user
          * modified or deleted the driver definition in the time
          * since this connection was created.
          */
       }
     } else {
       /* Otherwise, just decrement the reference count. */
       sConnectionReferenceCount.put(connection, new Integer(--count));
     }
   }
 }
Пример #15
0
  public synchronized void serialEvent(SerialPortEvent oEvent) {

    try {
      switch (oEvent.getEventType()) {
        case SerialPortEvent.DATA_AVAILABLE:
          if (input == null) {
            System.out.println("here11");
            input = new BufferedReader(new InputStreamReader(serialPort.getInputStream()));
          }
          String inputLine = input.readLine();
          // System.out.println(input.readLine().trim());
          if (inputLine.equals("")) {
          } else {
            String url = "jdbc:mysql://localhost/secureplanet";
            Properties prop = new Properties();
            prop.setProperty("user", "root");
            prop.setProperty("password", "toor");
            Driver d = new com.mysql.jdbc.Driver();
            Connection conn = d.connect(url, prop);
            if (conn == null) {
              System.out.println("connection failed");
              return;
            }
            DatabaseMetaData dm = conn.getMetaData();
            String dbversion = dm.getDatabaseProductVersion();
            String dbname = dm.getDatabaseProductName();
            System.out.println("name:" + dbname);
            System.out.println("version:" + dbversion);

            String rfidtoken = inputLine.trim();
            Statement stmt = conn.createStatement();

            Double lat = 17.4416;
            Double lng = 78.3826;

            String sql =
                "INSERT INTO smarttracking "
                    + "VALUES ('"
                    + rfidtoken
                    + "','"
                    + lat
                    + "','"
                    + lng
                    + "')";
            stmt.executeUpdate(sql);
          }
          break;

        default:
          break;
      }
    } catch (Exception e) {
      e.printStackTrace();
    }
  }
Пример #16
0
 @Test(expected = RuntimeException.class)
 public void testException() throws SQLException {
   RuntimeException runtimeException = new RuntimeException();
   when(delegate.acceptsURL(testUrl)).thenReturn(true);
   when(delegate.connect(testUrl, properties)).thenThrow(runtimeException);
   try {
     hiveDriver.connect(testUrl, properties);
   } catch (Exception e) {
     assertEquals(runtimeException, e);
     throw e;
   }
 }
 @Override
 public Connection connect(final String url, final Properties info) throws SQLException {
   String translatedUrl = translate(url);
   for (Driver driver : getAllDrivers()) {
     if (driver.acceptsURL(translatedUrl)) {
       Connection conn = driver.connect(translatedUrl, info);
       if (conn != null) {
         return conn;
       }
     }
   }
   return null;
 }
Пример #18
0
  /**
   * 对于Weblogic连接池
   *
   * @return boolean
   */
  private boolean getWeblogicPoolConnection() {
    try {
      Driver myDriver = (Driver) (Class.forName("weblogic.jdbc.pool.Driver").newInstance());
      /*weblogic的连接池重写了close()方法*/
      con = myDriver.connect(JUrl.getJdbcUrl(), null);
      Statement stmt =
          con.createStatement(ResultSet.TYPE_SCROLL_SENSITIVE, ResultSet.CONCUR_UPDATABLE);
      stmt.execute("alter session set nls_date_format = 'YYYY-MM-DD HH24:MI:SS'");
      stmt.close();
    } catch (Exception ex) {
      System.out.println("$$$$$$$$WebLogicPool Connect Failed$$$$$");
      return false;
    }

    return true;
  }
Пример #19
0
 @Override
 public void test() throws Exception {
   if (config.mvStore) {
     return;
   }
   cl = getClassLoader("file:ext/h2-1.2.127.jar");
   driver = getDriver(cl);
   if (driver == null) {
     println("not found: ext/h2-1.2.127.jar - test skipped");
     return;
   }
   Connection conn = driver.connect("jdbc:h2:mem:", null);
   assertEquals("1.2.127 (2010-01-15)", conn.getMetaData().getDatabaseProductVersion());
   conn.close();
   testLobInFiles();
   testOldClientNewServer();
 }
 @Before
 public void setup() throws SQLException {
   testUrl = "testUrl";
   majorVersion = 10;
   minorVersion = 11;
   lazyDelegatingDriver = new LazyDelegatingDriver(driverRegistry, hasRegisterDriver);
   drivers = new ArrayList<>();
   drivers.add(makeEntry(badDriverServiceReference, badDriver));
   drivers.add(makeEntry(goodDriverServiceReference, driver));
   when(driver.connect(testUrl, null)).thenReturn(connection);
   when(driver.acceptsURL(testUrl)).thenReturn(true);
   when(driver.getPropertyInfo(testUrl, null))
       .thenReturn(new DriverPropertyInfo[] {driverPropertyInfo});
   when(driver.getMajorVersion()).thenReturn(majorVersion);
   when(driver.getMinorVersion()).thenReturn(minorVersion);
   when(driver.getParentLogger()).thenReturn(logger);
   when(driverRegistry.getDrivers()).thenReturn(drivers.iterator());
 }
Пример #21
0
  @Test
  public void testRetrieveFromDriverManager() throws Exception {
    DriverManager.registerDriver(driver);

    EasyMock.expect(driver.connect((String) EasyMock.notNull(), (Properties) EasyMock.notNull()))
        .andReturn(connection);
    connection.setAutoCommit(false);
    connection.setHoldability(1);

    props.put(JdbcDataSource.DRIVER, driver.getClass().getName());
    props.put(JdbcDataSource.URL, "jdbc:fakedb");
    props.put("holdability", "HOLD_CURSORS_OVER_COMMIT");
    mockControl.replay();

    Connection conn = jdbcDataSource.createConnectionFactory(context, props).call();

    mockControl.verify();

    assertSame("connection", conn, connection);
  }
  // query HBase table for threshold for the stock symbol that was tweeted about
  private int findThresholdForStock(String hashtag) {

    int threshold = DEFAULT_ALERT_THRESHOLD;

    try {
      conn =
          phoenixDriver.connect(
              "jdbc:phoenix:sandbox.hortonworks.com:2181:/hbase-unsecure", new Properties());

      ResultSet rst =
          conn.createStatement()
              .executeQuery(
                  "select tweet_threshold from securities where lower(symbol)='" + hashtag + "'");

      while (rst.next()) {
        threshold = rst.getInt(1);
        System.out.println("Found threshold in Hbase: " + threshold + " for: " + hashtag);
      }

      if (threshold == 0) {
        System.out.println(
            "Unable to find threshold in HBase for: "
                + hashtag
                + ". Setting to default: "
                + DEFAULT_ALERT_THRESHOLD);
        threshold = DEFAULT_ALERT_THRESHOLD;
      }
    } catch (Exception e) {
      e.printStackTrace();
      throw new RuntimeException(e);

    } finally {
      try {
        if (conn != null) conn.close();
      } catch (Exception e) {
        throw new RuntimeException(e);
      }
    }

    return threshold;
  }
Пример #23
0
  /** @param args */
  public static void main(String[] args) throws Exception {

    String driverClassName = "sybase.jdbc4.sqlanywhere.IDriver";
    Class<?> c = Class.forName(driverClassName);
    Driver driver = (Driver) c.newInstance();

    String url = "jdbc:sqlanywhere:eng=kawansoft_example";

    Properties properties = new Properties();
    properties.put("user", "user1");
    properties.put("password", "password1");
    Connection connection = driver.connect(url, properties);

    if (connection == null) {
      System.err.println("driverClassName: " + driverClassName);
      System.err.println("url            : " + url);
      throw new IllegalArgumentException(
          "Connection is null after driver.connect(url, properties)!");
    } else {
      System.out.println("Connected!");
    }
  }
Пример #24
0
  @Override
  Connection openConnection(
      final File databaseDirectory,
      final String driverClasspath,
      final Map<String, String> initParams)
      throws LocalDBException {
    final String filePath = databaseDirectory.getAbsolutePath() + File.separator + "localdb-h2";
    final String connectionString =
        "jdbc:h2:split:" + filePath + ";" + makeInitStringParams(initParams);

    try {
      driver = (Driver) Class.forName(H2_CLASSPATH).newInstance();
      final Properties connectionProps = new Properties();
      final Connection connection = driver.connect(connectionString, connectionProps);
      connection.setAutoCommit(true);
      return connection;
    } catch (Throwable e) {
      final String errorMsg = "error opening DB: " + e.getMessage();
      LOGGER.error(errorMsg, e);
      throw new LocalDBException(
          new ErrorInformation(PwmError.ERROR_LOCALDB_UNAVAILABLE, errorMsg));
    }
  }
Пример #25
0
  /**
   * Open (if necessary) and return a database connection for use by this Realm.
   *
   * @throws SQLException if a database error occurs
   */
  protected Connection open() throws SQLException {

    // Do nothing if there is a database connection already open
    if (dbConnection != null) return (dbConnection);

    // Instantiate our database driver if necessary
    if (driver == null) {
      try {
        Class clazz = Class.forName(driverName);
        driver = (Driver) clazz.newInstance();
      } catch (Throwable e) {
        throw new SQLException(e.getMessage());
      }
    }

    // Open a new connection
    Properties props = new Properties();
    if (connectionName != null) props.put("user", connectionName);
    if (connectionPassword != null) props.put("password", connectionPassword);
    dbConnection = driver.connect(connectionURL, props);
    dbConnection.setAutoCommit(false);
    return (dbConnection);
  }
Пример #26
0
 protected Connection createConnection() throws SQLException {
   final Driver driverInstance = newDriver();
   final Properties info = prepareConnectionProperties();
   Connection conn = null;
   try {
     _log.info("...Connecting to database by data source:");
     conn = driverInstance.connect(_url, info);
   } catch (SQLException e) {
     String msg = "Failed to connect: url=" + _url + " user="******"The driver didn't understand the URL: " + _url;
     throw new DfJDBCException(msg);
   }
   try {
     conn.setAutoCommit(_autoCommit);
   } catch (SQLException e) {
     String msg = "Failed to set auto commit: autocommit=" + _autoCommit;
     throw new DfJDBCException(msg, e);
   }
   return conn;
 }
Пример #27
0
 @Test
 public void testSuccess() throws SQLException {
   when(delegate.acceptsURL(testUrl)).thenReturn(true);
   when(delegate.connect(testUrl, properties)).thenReturn(connection);
   assertEquals(connection, hiveDriver.connect(testUrl, properties));
 }
Пример #28
0
  /**
   * Connect to MySQL
   *
   * @return if the connection was succesful
   */
  public boolean connect() throws Exception {
    if (connection != null) {
      return true;
    }

    if (currentType == null || currentType == Type.NONE) {
      log("Invalid database engine");
      return false;
    }

    // load the database jar
    ClassLoader classLoader;

    if (currentType == Type.SQLite) {
      classLoader =
          new URLClassLoader(
              new URL[] {
                new URL(
                    "jar:file:"
                        + new File(Updater.DEST_LIBRARY_FOLDER + currentType.getDriver()).getPath()
                        + "!/")
              });
    } else {
      classLoader = Bukkit.getServer().getClass().getClassLoader();
    }

    // What class should we try to load?
    String className = "";
    if (currentType == Type.MySQL) {
      className = "com.mysql.jdbc.Driver";
    } else {
      className = "org.sqlite.JDBC";
    }

    // Load the driver class
    Driver driver = (Driver) classLoader.loadClass(className).newInstance();

    // Create the properties to pass to the driver
    Properties properties = new Properties();

    // if we're using mysql, append the database info
    if (currentType == Type.MySQL) {
      LWC lwc = LWC.getInstance();
      properties.put("autoReconnect", "true");
      properties.put("user", lwc.getConfiguration().getString("database.username"));
      properties.put("password", lwc.getConfiguration().getString("database.password"));
    }

    // Connect to the database
    try {
      connection =
          driver.connect(
              "jdbc:" + currentType.toString().toLowerCase() + ":" + getDatabasePath(), properties);
      connected = true;
      return true;
    } catch (SQLException e) {
      log("Failed to connect to " + currentType);
      e.printStackTrace();
      return false;
    }
  }
Пример #29
0
  private Connection openDB(final DBConfiguration dbConfiguration) throws DatabaseException {
    final String connectionURL = dbConfiguration.getConnectionString();
    final String jdbcClassName = dbConfiguration.getDriverClassname();

    try {
      final byte[] jdbcDriverBytes = dbConfiguration.getJdbcDriver();
      if (jdbcDriverBytes != null) {
        LOGGER.debug("loading JDBC database driver stored in configuration");
        final JarClassLoader jarClassLoader = new JarClassLoader();
        jarClassLoader.add(new ByteArrayInputStream(jdbcDriverBytes));
        final JclObjectFactory jclObjectFactory = JclObjectFactory.getInstance();

        // Create object of loaded class
        driver = (Driver) jclObjectFactory.create(jarClassLoader, jdbcClassName);

        LOGGER.debug(
            "successfully loaded JDBC database driver '"
                + jdbcClassName
                + "' from application configuration");
      }
    } catch (Throwable e) {
      final String errorMsg =
          "error registering JDBC database driver stored in configuration: " + e.getMessage();
      final ErrorInformation errorInformation =
          new ErrorInformation(PwmError.ERROR_DB_UNAVAILABLE, errorMsg);
      LOGGER.error(errorMsg, e);
      throw new DatabaseException(errorInformation);
    }

    if (driver == null) {
      try {
        LOGGER.debug("loading JDBC database driver from classpath: " + jdbcClassName);
        driver = (Driver) Class.forName(jdbcClassName).newInstance();

        LOGGER.debug("successfully loaded JDBC database driver from classpath: " + jdbcClassName);
      } catch (Throwable e) {
        final String errorMsg =
            e.getClass().getName()
                + " error loading JDBC database driver from classpath: "
                + e.getMessage();
        final ErrorInformation errorInformation =
            new ErrorInformation(PwmError.ERROR_DB_UNAVAILABLE, errorMsg);
        throw new DatabaseException(errorInformation);
      }
    }

    try {
      LOGGER.debug("opening connection to database " + connectionURL);
      final Properties connectionProperties = new Properties();
      if (dbConfiguration.getUsername() != null && !dbConfiguration.getUsername().isEmpty()) {
        connectionProperties.setProperty("user", dbConfiguration.getUsername());
      }
      if (dbConfiguration.getPassword() != null) {
        connectionProperties.setProperty(
            "password", dbConfiguration.getPassword().getStringValue());
      }
      final Connection connection = driver.connect(connectionURL, connectionProperties);

      final Map<PwmAboutProperty, String> debugProps = getConnectionDebugProperties(connection);
      ;
      LOGGER.debug(
          "successfully opened connection to database "
              + connectionURL
              + ", properties: "
              + JsonUtil.serializeMap(debugProps));

      connection.setAutoCommit(true);
      return connection;
    } catch (Throwable e) {
      final String errorMsg =
          "error connecting to database: " + Helper.readHostileExceptionMessage(e);
      final ErrorInformation errorInformation =
          new ErrorInformation(PwmError.ERROR_DB_UNAVAILABLE, errorMsg);
      if (e instanceof IOException) {
        LOGGER.error(errorInformation);
      } else {
        LOGGER.error(errorMsg, e);
      }
      throw new DatabaseException(errorInformation);
    }
  }
Пример #30
0
 public Connection connect(String u, Properties p) throws SQLException {
   return driver.connect(u, p);
 }