/** 初始化连接池 */
 public void initConnectionPool() {
   try {
     connectionPool = JdbcConnectionPool.create(url, username, password);
     connectionPool.setLoginTimeout(H2_LOGIN_TIMEOUT);
     connectionPool.setMaxConnections(H2_MAX_CONNECTIONS);
   } catch (Exception e) {
     log.error("init H2 JdbcConnectionPool error!", e);
   }
 }
Esempio n. 2
0
  @Test
  public void testTopLevelJdbcDataSource() throws Exception {
    final CollectingDataSink dataSink = new CollectingDataSink();
    NSysMonConfigurer.addDataSink(NSysMon.get(), dataSink);

    final DataSource dataSource =
        new NSysMonDataSource(
            JdbcConnectionPool.create("jdbc:h2:mem:demo", "sa", ""), null, NSysMon.get());

    try (Connection conn = dataSource.getConnection()) {
      final Statement stmt = conn.createStatement();
      stmt.execute("create table A (oid number primary key)");
      stmt.execute("insert into A (oid) values (1)");
      final ResultSet rs = conn.createStatement().executeQuery("select * from A");
      while (rs.next()) {
        // Just ignore the result, goal is only to generat the sql
      }
    }

    assertEquals(1, dataSink.data.size());
    final AHierarchicalData root = dataSink.data.get(0).getRootNode();
    assertEquals("jdbc:connection from pool", root.getIdentifier());

    assertEquals(3, root.getChildren().size());

    assertEquals(
        "jdbc: create table A (oid number primary key)", root.getChildren().get(0).getIdentifier());
    assertEquals("jdbc: insert into A (oid) values (1)", root.getChildren().get(1).getIdentifier());

    assertEquals("jdbc: select * from A", root.getChildren().get(2).getIdentifier());
  }
  public DLNAMediaDatabase(String name) {
    String dir = "database";
    dbName = name;
    File fileDir = new File(dir);

    if (Platform.isWindows()) {
      String profileDir = configuration.getProfileDirectory();
      url = String.format("jdbc:h2:%s\\%s/%s", profileDir, dir, dbName);
      fileDir = new File(profileDir, dir);
    } else {
      url = Constants.START_URL + dir + "/" + dbName;
    }
    dbDir = fileDir.getAbsolutePath();
    LOGGER.debug("Using database URL: " + url);
    LOGGER.info("Using database located at: " + dbDir);

    try {
      Class.forName("org.h2.Driver");
    } catch (ClassNotFoundException e) {
      LOGGER.error(null, e);
    }

    JdbcDataSource ds = new JdbcDataSource();
    ds.setURL(url);
    ds.setUser("sa");
    ds.setPassword("");
    cp = JdbcConnectionPool.create(ds);
  }
  @BeforeClass
  public static void beforeClass() {
    tested = new JdbcContentPersistenceService();
    tested.log = Logger.getLogger("test logger");

    tested.searchiskoDs =
        JdbcConnectionPool.create(
            "jdbc:h2:mem:unit-testing-jpa-persistence-service-test", "sa", "");
  }
  public void shutdown() {

    // shutdown the connection pool
    if (connectionPool != null) {
      try {
        connectionPool.dispose();
      } catch (Exception e) {
        logger.warn("Unable to dispose of connection pool: " + e.getMessage());
        if (logger.isDebugEnabled()) {
          logger.warn(StringUtils.EMPTY, e);
        }
      }
    }
  }
  public DLNAMediaDatabase(String name) {
    dbName = name;
    File profileDirectory = new File(configuration.getProfileDirectory());
    dbDir =
        new File(
                profileDirectory.isDirectory() ? configuration.getProfileDirectory() : null,
                "database")
            .getAbsolutePath();
    url = Constants.START_URL + dbDir + File.separator + dbName;
    LOGGER.debug("Using database URL: " + url);
    LOGGER.info("Using database located at: " + dbDir);

    try {
      Class.forName("org.h2.Driver");
    } catch (ClassNotFoundException e) {
      LOGGER.error(null, e);
    }

    JdbcDataSource ds = new JdbcDataSource();
    ds.setURL(url);
    ds.setUser("sa");
    ds.setPassword("");
    cp = JdbcConnectionPool.create(ds);
  }
 public Connection getConnection() throws Exception {
   return connectionPool.getConnection();
 }
  private SymfonyDbFactory() throws Exception {
    try {
      Class.forName("org.h2.Driver");
    } catch (ClassNotFoundException e) {
      Logger.logException(e);
    }

    IPath dbPath = SymfonyIndex.getDefault().getStateLocation();

    String connString = getConnectionString(dbPath);

    pool = JdbcConnectionPool.create(connString, DB_USER, DB_PASS);

    Schema schema = new Schema();
    boolean initializeSchema = false;

    int tries = 2; // Tries for opening database
    Connection connection = null;
    do {
      try {
        connection = pool.getConnection();
        try {
          Statement statement = connection.createStatement();
          try {
            statement.executeQuery("SELECT COUNT(*) FROM SERVICES WHERE 1=0;");
            initializeSchema = !schema.isCompatible();

          } catch (SQLException e) {
            // Basic table doesn't exist
            initializeSchema = true;
          } finally {
            statement.close();
          }

          if (initializeSchema) {
            connection.close();
            pool.dispose();
            // Destroy schema by removing DB (if exists)
            DeleteDbFiles.execute(dbPath.toOSString(), DB_NAME, true);

            pool = JdbcConnectionPool.create(connString, DB_USER, DB_PASS);
            connection = pool.getConnection();
            schema.initialize(connection);
          }
        } finally {
          if (connection != null) {
            connection.close();
          }
        }
      } catch (SQLException e) {

        Logger.logException(e);

        // remove corrupted DB
        try {
          DeleteDbFiles.execute(dbPath.toOSString(), DB_NAME, true);

        } catch (Exception e1) {

          Logger.logException(e1);
          throw e1;
        }
      }
    } while (connection == null && --tries > 0);
  }
 public void dispose() throws SQLException {
   if (pool != null) {
     pool.dispose();
     pool = null;
   }
 }
 public Connection createConnection() throws SQLException {
   return pool == null ? null : pool.getConnection();
 }
 /**
  * Gets a new connection from the connection pool if one is available. If not waits for a free
  * slot until timeout.<br>
  * <br>
  * <strong>Important: Every connection must be closed after use</strong>
  *
  * @return the new connection
  * @throws SQLException
  */
 public Connection getConnection() throws SQLException {
   return cp.getConnection();
 }
 private Connection getConnection() throws SQLException {
   return cp.getConnection();
 }
 @Override
 public Connection getConnection() throws SQLException {
   return pool.getConnection();
 }
 public static void realStop() {
   if (pool != null) {
     pool.dispose();
     pool = null;
   }
 }
 public static void realStart() {
   pool = JdbcConnectionPool.create("jdbc:h2:mem:dbsearch", "sa", "sa");
 }
  @Override
  public Object getObject() throws Exception {
    if (connectionPool == null) {

      // locate the repository directory
      String repositoryDirectoryPath =
          properties.getProperty(NiFiProperties.REPOSITORY_DATABASE_DIRECTORY);

      // ensure the repository directory is specified
      if (repositoryDirectoryPath == null) {
        throw new NullPointerException("Database directory must be specified.");
      }

      // create a handle to the repository directory
      File repositoryDirectory = new File(repositoryDirectoryPath);

      // create a handle to the database directory and file
      File databaseFile = new File(repositoryDirectory, AUDIT_DATABASE_FILE_NAME);
      String databaseUrl = getDatabaseUrl(databaseFile);

      // create the pool
      connectionPool =
          JdbcConnectionPool.create(databaseUrl, NF_USERNAME_PASSWORD, NF_USERNAME_PASSWORD);
      connectionPool.setMaxConnections(MAX_CONNECTIONS);

      Connection connection = null;
      ResultSet rs = null;
      Statement statement = null;
      try {
        // get a connection
        connection = connectionPool.getConnection();
        connection.setAutoCommit(false);

        // create a statement for creating/updating the database
        statement = connection.createStatement();

        // determine if the tables need to be created
        rs = connection.getMetaData().getTables(null, null, "USER", null);
        if (!rs.next()) {
          logger.info("Database not built for repository: " + databaseUrl + ".  Building now...");

          // create the tables
          statement.execute(CREATE_USER_TABLE);
          statement.execute(CREATE_AUTHORITY_TABLE);

          // seed the anonymous user
          statement.execute(INSERT_ANONYMOUS_USER);
          statement.execute(INSERT_ANONYMOUS_MONITOR_AUTHORITY);
          statement.execute(INSERT_ANONYMOUS_DFM_AUTHORITY);
          statement.execute(INSERT_ANONYMOUS_ADMIN_AUTHORITY);
          statement.execute(INSERT_ANONYMOUS_NIFI_AUTHORITY);
        } else {
          logger.info("Existing database found and connected to at: " + databaseUrl);
        }

        // close the previous result set
        RepositoryUtils.closeQuietly(rs);

        // merge in the provenance role to handle existing databases
        rs = statement.executeQuery(SELECT_ANONYMOUS_PROVENANCE_AUTHORITY);
        if (!rs.next()) {
          statement.execute(INSERT_ANONYMOUS_PROVENANCE_AUTHORITY);
        }

        // commit any changes
        connection.commit();
      } catch (SQLException sqle) {
        RepositoryUtils.rollback(connection, logger);
        throw sqle;
      } finally {
        RepositoryUtils.closeQuietly(rs);
        RepositoryUtils.closeQuietly(statement);
        RepositoryUtils.closeQuietly(connection);
      }
    }

    return connectionPool;
  }