Beispiel #1
0
  private void source(JCodeModel codeModel, JDefinedClass clazz) throws SQLException, Exception {

    DatabaseMetaData dmd = conn.getMetaData();
    ResultSet rs = dmd.getColumns(null, schema.toUpperCase(), table, null);

    String productName = dmd.getDatabaseProductName();

    try {
      while (rs.next()) {
        String columnName = rs.getString("COLUMN_NAME");
        int dataType = rs.getInt("DATA_TYPE");
        int columnSize = rs.getInt("COLUMN_SIZE");
        int digits = rs.getInt("DECIMAL_DIGITS");
        String remarks = this.getColumnComment(table, columnName);

        String fieldName = toCamelCase(columnName);

        // privateなインスタンス変数
        JFieldVar field = this.field(codeModel, clazz, fieldName, dataType, columnSize, digits);
        field.javadoc().add(remarks);

        getter(clazz, field, fieldName, remarks);
        setter(codeModel, clazz, field, fieldName, remarks);
      }
    } finally {
      rs.close();
    }
  }
Beispiel #2
0
  private final void detectDialect() {
    Connection conn = null;
    try {
      conn = dataSource.getConnection();
      final DatabaseMetaData dbmd = conn.getMetaData();

      final String dbProductName = dbmd.getDatabaseProductName();

      if ("Microsoft SQL Server".equalsIgnoreCase(dbProductName)) {
        dialect = new MssqlDialect();
      } else if ("MySQL".equalsIgnoreCase(dbProductName)) {
        dialect = new MysqlDialect();
      } else if ("Oracle".equalsIgnoreCase(dbProductName)) {
        dialect = new OracleDialect();
      } else { // 默认是Oracle
        dialect = new OracleDialect();
      }
    } catch (Exception ex) {
      dialect = new OracleDialect();
    } finally {
      if (conn != null) {
        try {
          conn.close();
        } catch (Exception ex) {
        }
        conn = null;
      }
    }
  }
Beispiel #3
0
  public static SQLDialectCode discoverSQLDialect(DatabaseMetaData meta) {
    SQLDialectCode dialectCode = SQLDialectCode.UNKNOWN_DIALECT;

    try {

      String dbName = meta.getDatabaseProductName().toLowerCase();

      if (dbName.indexOf(POSTGRES_PART) != -1) {
        return SQLDialectCode.POSTGRES_DIALECT;
      } else if (dbName.indexOf(MYSQL_PART) != -1) {
        return SQLDialectCode.MYSQL_DIALECT;
      } else if (dbName.indexOf(ORACLE_PART) != -1) {
        return SQLDialectCode.ORACLE_DIALECT;
      } else if (dbName.indexOf(MSSQL_PART) != -1) {
        return SQLDialectCode.MSSQL_DIALECT;
      } else if (dbName.indexOf(HSQL_PART) != -1) {
        return SQLDialectCode.HSQL_DIALECT;
      } else if (dbName.indexOf(H2_PART) != -1) {
        return SQLDialectCode.H2_DIALECT;
      } else if (dbName.indexOf(SYBASE_SQLANY_PART) != -1) {
        return SQLDialectCode.SYBASE_SQLANYWHERE_DIALECT;
      } else if (dbName.indexOf(SQLITE_PART) != -1) {
        return SQLDialectCode.SQLITE_DIALECT;
      } else {
        return SQLDialectCode.UNKNOWN_DIALECT;
      }
    } catch (SQLException sqle) {
      // we can't do much here
    }

    return dialectCode;
  }
 private void populateMetaData(DataSource dataSource) {
   Connection connection = null;
   try {
     try {
       connection = dataSource.getConnection();
       DatabaseMetaData metaData = connection.getMetaData();
       CommonParameters.set(
           CommonParameters.DATABASE_PRODUCT_NAME, metaData.getDatabaseProductName());
       CommonParameters.set(
           CommonParameters.DATABASE_PRODUCT_VERSION, metaData.getDatabaseProductVersion());
       CommonParameters.set(
           CommonParameters.DATABASE_MINOR_VERSION, metaData.getDatabaseMinorVersion() + EMPTY);
       CommonParameters.set(
           CommonParameters.DATABASE_MAJOR_VERSION, metaData.getDatabaseMajorVersion() + EMPTY);
       CommonParameters.set(CommonParameters.DATABASE_DRIVER_NAME, metaData.getDriverName());
       CommonParameters.set(
           CommonParameters.DATABASE_DRIVER_MINOR_VERSION,
           metaData.getDriverMinorVersion() + EMPTY);
       CommonParameters.set(
           CommonParameters.DATABASE_DRIVER_MAJOR_VERSION,
           metaData.getDriverMajorVersion() + EMPTY);
       CommonParameters.set(
           CommonParameters.DATABASE_CONNECTION_CLASS_NAME,
           connection.getClass().getCanonicalName());
     } finally {
       if (connection != null) {
         connection.close();
       }
     }
   } catch (SQLException e) {
     logger.error(e.getMessage(), e);
   }
 }
Beispiel #5
0
 public static void main(String[] args) throws SQLException {
   java.sql.Connection conn = JdbcUtils.getConnection();
   DatabaseMetaData dbmd = conn.getMetaData();
   System.out.println("db name: " + dbmd.getDatabaseProductName());
   System.out.println("tx: " + dbmd.supportsTransactions());
   conn.close();
 }
Beispiel #6
0
 SqlDialect get(DataSource dataSource) {
   Connection connection = null;
   try {
     connection = dataSource.getConnection();
     DatabaseMetaData metaData = connection.getMetaData();
     String productName = metaData.getDatabaseProductName();
     String productVersion = metaData.getDatabaseProductVersion();
     List key = Arrays.asList(productName, productVersion);
     SqlDialect dialect = map.get(key);
     if (dialect == null) {
       final SqlDialect.DatabaseProduct product =
           SqlDialect.getProduct(productName, productVersion);
       dialect = new SqlDialect(product, productName, metaData.getIdentifierQuoteString());
       map.put(key, dialect);
     }
     connection.close();
     connection = null;
     return dialect;
   } catch (SQLException e) {
     throw new RuntimeException(e);
   } finally {
     if (connection != null) {
       try {
         connection.close();
       } catch (SQLException e) {
         // ignore
       }
     }
   }
 }
 private void testAll(ArrayList<Database> dbs, ArrayList<Bench> tests, int size) throws Exception {
   for (int i = 0; i < dbs.size(); i++) {
     if (i > 0) {
       Thread.sleep(1000);
     }
     // calls garbage collection
     TestBase.getMemoryUsed();
     Database db = dbs.get(i);
     System.out.println("Testing the performance of " + db.getName());
     db.startServer();
     Connection conn = db.openNewConnection();
     DatabaseMetaData meta = conn.getMetaData();
     System.out.println(
         " " + meta.getDatabaseProductName() + " " + meta.getDatabaseProductVersion());
     runDatabase(db, tests, 1);
     runDatabase(db, tests, 1);
     collect = true;
     runDatabase(db, tests, size);
     conn.close();
     db.log("Executed statements", "#", db.getExecutedStatements());
     db.log("Total time", "ms", db.getTotalTime());
     int statPerSec = db.getExecutedStatements() * 1000 / db.getTotalTime();
     db.log("Statements per second", "#", statPerSec);
     System.out.println("Statements per second: " + statPerSec);
     collect = false;
     db.stopServer();
   }
 }
  public static void main(String[] args) {
    Connection con = null;
    DatabaseMetaData dbmd = null;

    try {
      Class.forName(driver);
      con = DriverManager.getConnection(url);
      System.out.println(con.toString());
      // Use the database connection somehow.

      dbmd = con.getMetaData();

      System.out.println("\n----------------------------------------------------");
      System.out.println("Database Name    = " + dbmd.getDatabaseProductName());
      System.out.println("Database Version = " + dbmd.getDatabaseProductVersion());
      System.out.println("Driver Name      = " + dbmd.getDriverName());
      System.out.println("Driver Version   = " + dbmd.getDriverVersion());
      System.out.println("Database URL     = " + dbmd.getURL());
      System.out.println("----------------------------------------------------");

    } catch (SQLException se) {
      printSQLException(se);
    } catch (ClassNotFoundException e) {
      System.out.println("JDBC Driver " + driver + " not found in CLASSPATH");
    } finally {
      if (con != null) {
        try {
          con.close();
        } catch (SQLException se) {
          printSQLException(se);
        }
      }
    }
  }
 private void logDatabaseInfo() throws ServletException {
   SessionHelper helper = RetsServer.createHelper();
   try {
     Session session = helper.beginSession();
     Connection connection = session.connection();
     DatabaseMetaData metaData = connection.getMetaData();
     LOGGER.info(
         "JDBC Driver info: "
             + metaData.getDriverName()
             + " version "
             + metaData.getDriverVersion());
     LOGGER.info(
         "JDBC DB info: "
             + metaData.getDatabaseProductName()
             + " version "
             + metaData.getDatabaseProductVersion());
   } catch (SQLException e) {
     throw new ServletException("Caught", e);
   } catch (HibernateException e) {
     throw new ServletException("Caught", e);
   } finally {
     try {
       helper.close();
     } catch (HibernateException e) {
       throw new ServletException(e);
     }
   }
 }
  /**
   * Provides information on the database.
   *
   * @param database Database
   * @throws SQLException On a SQL exception
   */
  void retrieveDatabaseInfo() throws SQLException {
    final DatabaseMetaData dbMetaData = getRetrieverConnection().getMetaData();

    final MutableDatabaseInfo dbInfo = database.getDatabaseInfo();

    dbInfo.setProductName(dbMetaData.getDatabaseProductName());
    dbInfo.setProductVersion(dbMetaData.getDatabaseProductVersion());
  }
Beispiel #11
0
 /** Creates a {@code Dialect} by connecting to the datasource to check what database is used. */
 public static Dialect createDialect(
     Connection connection, RepositoryDescriptor repositoryDescriptor) {
   DatabaseMetaData metadata;
   String databaseName;
   try {
     metadata = connection.getMetaData();
     databaseName = metadata.getDatabaseProductName();
   } catch (SQLException e) {
     throw new NuxeoException(e);
   }
   if (databaseName.contains("/")) {
     // DB2/LINUX, DB2/DARWIN, etc.
     databaseName = databaseName.substring(0, databaseName.indexOf('/'));
   }
   String dialectClassName = Framework.getProperty(DIALECT_CLASS);
   if (dialectClassName == null) {
     dialectClassName = Framework.getProperty(DIALECT_CLASS + '.' + databaseName.replace(" ", ""));
   }
   Class<? extends Dialect> dialectClass;
   if (dialectClassName == null) {
     dialectClass = DIALECTS.get(databaseName);
     if (dialectClass == null) {
       throw new NuxeoException("Unsupported database: " + databaseName);
     }
   } else {
     Class<?> klass;
     try {
       ClassLoader cl = Thread.currentThread().getContextClassLoader();
       klass = cl.loadClass(dialectClassName);
     } catch (ClassNotFoundException e) {
       throw new NuxeoException(e);
     }
     if (!Dialect.class.isAssignableFrom(klass)) {
       throw new NuxeoException("Not a Dialect: " + dialectClassName);
     }
     dialectClass = (Class<? extends Dialect>) klass;
   }
   Constructor<? extends Dialect> ctor;
   try {
     ctor = dialectClass.getConstructor(DatabaseMetaData.class, RepositoryDescriptor.class);
   } catch (ReflectiveOperationException e) {
     throw new NuxeoException("Bad constructor signature for: " + dialectClassName, e);
   }
   Dialect dialect;
   try {
     dialect = ctor.newInstance(metadata, repositoryDescriptor);
   } catch (InvocationTargetException e) {
     Throwable t = e.getTargetException();
     if (t instanceof NuxeoException) {
       throw (NuxeoException) t;
     } else {
       throw new NuxeoException(t);
     }
   } catch (ReflectiveOperationException e) {
     throw new NuxeoException("Cannot construct dialect: " + dialectClassName, e);
   }
   return dialect;
 }
  private void set(DatasourceConnection dc) {
    if (dc != null) {
      datasource = dc.getDatasource();
      try {
        DatabaseMetaData md = dc.getConnection().getMetaData();
        md.getDatabaseProductName();
        setAdditional(KeyImpl.init("DatabaseName"), md.getDatabaseProductName());
        setAdditional(KeyImpl.init("DatabaseVersion"), md.getDatabaseProductVersion());
        setAdditional(KeyImpl.init("DriverName"), md.getDriverName());
        setAdditional(KeyImpl.init("DriverVersion"), md.getDriverVersion());
        // setAdditional("url",md.getURL());

        setAdditional(KeyConstants._Datasource, dc.getDatasource().getName());

      } catch (SQLException e) {
      }
    }
  }
 public String getDatabaseProductName() throws SQLException {
   {
     try {
       return _meta.getDatabaseProductName();
     } catch (SQLException e) {
       handleException(e);
       throw new AssertionError();
     }
   }
 }
  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();
    }
  }
Beispiel #15
0
  private void loadDatabaseMetadata() {
    if (!databaseMetadataLoaded) {
      String componentName = "UNKNOWN";
      Connection con = null;
      try {
        componentName = getMetaComponent().getName();

        con = DataSourceConnectionProvider.getByComponent(componentName).getConnection();
        DatabaseMetaData metaData = con.getMetaData();
        supportsSchemasInDataManipulation = metaData.supportsSchemasInDataManipulation();
        Collection timeDateFunctions =
            Strings.toCollection(metaData.getTimeDateFunctions().toUpperCase());

        //
        // another solution instead of the use of 'if' would be to use a xml with
        //	the information of the functions from each BBDD
        if ("DB2 UDB for AS/400".equals(metaData.getDatabaseProductName())
            || "Oracle".equals(metaData.getDatabaseProductName())
            || "PostgresSQL".equals(metaData.getDatabaseProductName())) {
          supportsTranslateFunction = true;
        }
        if ("Oracle".equals(metaData.getDatabaseProductName())
            || "PostgreSQL".equals(metaData.getDatabaseProductName())) {
          supportsYearFunction = supportsMonthFunction = false;
        } else {
          supportsYearFunction = timeDateFunctions.contains("YEAR");
          supportsMonthFunction = timeDateFunctions.contains("MONTH");
        }
        databaseMetadataLoaded = true;
      } catch (Exception ex) {
        log.warn(XavaResources.getString("load_database_metadata_warning"));
      } finally {
        try {
          if (con != null) {
            con.close();
          }
        } catch (SQLException e) {
          log.warn(XavaResources.getString("close_connection_warning"));
        }
      }
    }
  }
  private void checkDataBase(DatabaseMetaData databaseMetaData) throws SQLException {
    String dataBaseName = databaseMetaData.getDatabaseProductName();

    if (!DATABASE_TEST_NAME.equalsIgnoreCase(dataBaseName))
      throw new IllegalArgumentException(
          "La base de donnée pour l'importation n'est pas du type '"
              + DATABASE_TEST_NAME
              + "' mais de type "
              + dataBaseName
              + "! Attention l'importation  supprime toutes les données dans les tables");
  }
  @Override
  protected Dialect resolveDialectInternal(DatabaseMetaData metaData) throws SQLException {
    String databaseName = metaData.getDatabaseProductName();
    int databaseMajorVersion = metaData.getDatabaseMajorVersion();

    if ("MySQL".equals(databaseName)) {
      if (5 == databaseMajorVersion) return new MySQL5InnoDBDialect();
      else return new MySQLInnoDBDialect();
    }

    return null;
  }
 /** Gets a title for the data presented in the tree node. */
 public String getTitle() {
   try {
     Connection con = conProv.getConnection();
     DatabaseMetaData dmd = con.getMetaData();
     StringBuffer sb = new StringBuffer();
     sb.append(dmd.getDatabaseProductName());
     sb.append(" - ");
     dmd = con.getMetaData();
     sb.append(conProv.getServerName());
     return sb.toString();
   } catch (Exception e) {
     return "[Not Connected]";
   }
 }
  @Test
  public void testMatchInParametersAndSqlTypeInfoWrapping() throws Exception {
    final String TABLE = "customers";
    final String USER = "******";

    ResultSet metaDataResultSet = mock(ResultSet.class);
    given(metaDataResultSet.next()).willReturn(true, false);
    given(metaDataResultSet.getString("TABLE_SCHEM")).willReturn(USER);
    given(metaDataResultSet.getString("TABLE_NAME")).willReturn(TABLE);
    given(metaDataResultSet.getString("TABLE_TYPE")).willReturn("TABLE");

    ResultSet columnsResultSet = mock(ResultSet.class);
    given(columnsResultSet.next()).willReturn(true, true, true, true, false);
    given(columnsResultSet.getString("COLUMN_NAME"))
        .willReturn("id", "name", "customersince", "version");
    given(columnsResultSet.getInt("DATA_TYPE"))
        .willReturn(Types.INTEGER, Types.VARCHAR, Types.DATE, Types.NUMERIC);
    given(columnsResultSet.getBoolean("NULLABLE")).willReturn(false, true, true, false);

    given(databaseMetaData.getDatabaseProductName()).willReturn("MyDB");
    given(databaseMetaData.getDatabaseProductName()).willReturn("1.0");
    given(databaseMetaData.getUserName()).willReturn(USER);
    given(databaseMetaData.storesLowerCaseIdentifiers()).willReturn(true);
    given(databaseMetaData.getTables(null, null, TABLE, null)).willReturn(metaDataResultSet);
    given(databaseMetaData.getColumns(null, USER, TABLE, null)).willReturn(columnsResultSet);

    MapSqlParameterSource map = new MapSqlParameterSource();
    map.addValue("id", 1);
    map.addValue("name", "Sven");
    map.addValue("customersince", new Date());
    map.addValue("version", 0);
    map.registerSqlType("customersince", Types.DATE);
    map.registerSqlType("version", Types.NUMERIC);

    context.setTableName(TABLE);
    context.processMetaData(dataSource, new ArrayList<>(), new String[] {});

    List<Object> values = context.matchInParameterValuesWithInsertColumns(map);

    assertEquals("wrong number of parameters: ", 4, values.size());
    assertTrue("id not wrapped with type info", values.get(0) instanceof Number);
    assertTrue("name not wrapped with type info", values.get(1) instanceof String);
    assertTrue("date wrapped with type info", values.get(2) instanceof SqlParameterValue);
    assertTrue("version wrapped with type info", values.get(3) instanceof SqlParameterValue);
    verify(metaDataResultSet, atLeastOnce()).next();
    verify(columnsResultSet, atLeastOnce()).next();
    verify(metaDataResultSet).close();
    verify(columnsResultSet).close();
  }
Beispiel #20
0
  @Signature
  public Memory getMetaData() throws SQLException {
    ArrayMemory r = new ArrayMemory();
    r.refOfIndex("userName").assign(metaData.getUserName());

    r.refOfIndex("driverName").assign(metaData.getDriverName());
    r.refOfIndex("driverVersion").assign(metaData.getDriverVersion());
    r.refOfIndex("databaseName").assign(metaData.getDatabaseProductName());
    r.refOfIndex("databaseVersion").assign(metaData.getDatabaseProductVersion());

    r.refOfIndex("catalogSeparator").assign(metaData.getCatalogSeparator());
    r.refOfIndex("catalogTerm").assign(metaData.getCatalogTerm());
    r.refOfIndex("schemaTerm").assign(metaData.getSchemaTerm());
    r.refOfIndex("procedureTerm").assign(metaData.getProcedureTerm());
    r.refOfIndex("searchStringEscape").assign(metaData.getSearchStringEscape());

    r.refOfIndex("numericFunctions").assign(metaData.getNumericFunctions());
    r.refOfIndex("stringFunctions").assign(metaData.getStringFunctions());
    r.refOfIndex("timeDateFunctions").assign(metaData.getTimeDateFunctions());
    r.refOfIndex("systemFunctions").assign(metaData.getSystemFunctions());

    r.refOfIndex("defaultTransactionIsolation").assign(metaData.getDefaultTransactionIsolation());
    r.refOfIndex("identifierQuoteString").assign(metaData.getIdentifierQuoteString());

    r.refOfIndex("maxBinaryLiteralLength").assign(metaData.getMaxBinaryLiteralLength());
    r.refOfIndex("maxCatalogNameLength").assign(metaData.getMaxCatalogNameLength());
    r.refOfIndex("maxCharLiteralLength").assign(metaData.getMaxCharLiteralLength());
    r.refOfIndex("maxConnections").assign(metaData.getMaxConnections());

    r.refOfIndex("maxColumnNameLength").assign(metaData.getMaxColumnNameLength());
    r.refOfIndex("maxColumnsInGroupBy").assign(metaData.getMaxColumnsInGroupBy());
    r.refOfIndex("maxColumnsInIndex").assign(metaData.getMaxColumnsInIndex());
    r.refOfIndex("maxColumnsInOrderBy").assign(metaData.getMaxColumnsInOrderBy());
    r.refOfIndex("maxColumnsInSelect").assign(metaData.getMaxColumnsInSelect());
    r.refOfIndex("maxColumnsInTable").assign(metaData.getMaxColumnsInTable());

    r.refOfIndex("maxCursorNameLength").assign(metaData.getMaxCursorNameLength());
    r.refOfIndex("maxIndexLength").assign(metaData.getMaxIndexLength());
    r.refOfIndex("maxProcedureNameLength").assign(metaData.getMaxProcedureNameLength());
    r.refOfIndex("maxRowSize").assign(metaData.getMaxRowSize());
    r.refOfIndex("maxSchemaNameLength").assign(metaData.getMaxSchemaNameLength());
    r.refOfIndex("maxStatementLength").assign(metaData.getMaxStatementLength());

    r.refOfIndex("maxTableNameLength").assign(metaData.getMaxTableNameLength());
    r.refOfIndex("maxTablesInSelect").assign(metaData.getMaxTablesInSelect());

    return r.toConstant();
  }
 public DatabaseInfo(DatabaseMetaData metaData) throws SQLException {
   try {
     this.productName = metaData.getDatabaseProductName();
     this.productVersion = metaData.getDatabaseProductVersion();
     this.minorVersion = metaData.getDatabaseMinorVersion();
     this.majorVersion = metaData.getDatabaseMajorVersion();
   } catch (Error e) {
     if (logger.isErrorEnabled()) {
       logger.error(
           (format(
               "JDBC Driver %s version is not applicable for Migrator, use latest version of the driver",
               metaData.getDriverVersion())));
     }
     System.exit(DRIVER_ERROR);
   }
 }
 public void dumpMetadataInfo(IConnectionConfig dbConfig) throws SQLException {
   Connection connection = ConnectionManager.getInstance().createConnection(dbConfig);
   DatabaseMetaData databaseMetaData = connection.getMetaData();
   System.out.println("Product Name: ");
   System.out.println("  " + databaseMetaData.getDatabaseProductName());
   System.out.println("SQL Keywords: ");
   System.out.println("  " + databaseMetaData.getSQLKeywords());
   System.out.println("Vendor's preferred term for \"schema\": ");
   System.out.println("  " + databaseMetaData.getSchemaTerm());
   System.out.println("Vendor's preferred term for \"Procedures\": ");
   System.out.println("  " + databaseMetaData.getProcedureTerm());
   System.out.println("String Functions: ");
   System.out.println("  " + databaseMetaData.getStringFunctions());
   System.out.println("System Functions: ");
   System.out.println("  " + databaseMetaData.getSystemFunctions());
 }
  /**
   * This method creates the real connection to database.
   *
   * @param connInfo connection information like url, username and password
   * @return a connection to the database
   * @throws DatabaseConnectionException if the connection cannot be established.
   */
  protected Connection createConnection(Properties connInfo) throws DatabaseConnectionException {
    try {
      // instantiate the Driver class
      try {
        if (connInfo.get("jdbc_class") != null) {
          Class.forName((String) connInfo.get("jdbc_class")).newInstance();
        }
      } catch (Exception e) {
        throw new DatabaseConnectionException(
            "Cannot load driver class " + connInfo.get("jdbc_class"), e);
      }

      Properties connectionInfo = new Properties();
      if (connInfo.get("jdbc_user") != null) {
        connectionInfo.put("user", connInfo.get("jdbc_user"));
      }
      if (connInfo.get("jdbc_pwd") != null) {
        connectionInfo.put("password", connInfo.get("jdbc_pwd"));
      }
      connectionInfo.put("charSet", "UTF-8");

      Connection conn =
          DriverManager.getConnection((String) connInfo.get("jdbc_url"), connectionInfo);

      // enable transaction support
      conn.setAutoCommit(false);
      conn.setTransactionIsolation(Connection.TRANSACTION_READ_COMMITTED);

      DatabaseMetaData meta = conn.getMetaData();
      logger.info(
          "Connected to "
              + connInfo.get("jdbc_url")
              + ": "
              + meta.getDatabaseProductName()
              + " "
              + meta.getDatabaseProductVersion()
              + " with driver "
              + meta.getDriverName()
              + " "
              + meta.getDriverVersion());

      return conn;
    } catch (SQLException e) {
      throw new DatabaseConnectionException(
          "Unable to create a connection to: " + connInfo.get("jdbc_url"), e);
    }
  }
 public void init(ConnectionFactory cf) throws DAOException {
   Connection conn = cf.getConnection();
   try {
     DatabaseMetaData dbmd = conn.getMetaData();
     this.setDatabaseProductName(dbmd.getDatabaseProductName());
     this.setDatabaseProductVersion(dbmd.getDatabaseProductVersion());
     this.setDriverName(dbmd.getDriverName());
     this.setDriverVersion(dbmd.getDriverVersion());
   } catch (SQLException e) {
     throw (new DAOException(e));
   } finally {
     try {
       conn.close();
     } catch (Exception e) {
       e.printStackTrace();
     }
   }
 }
  private JDBCDriverVendor getVendorFromDatabase(DataSource dataSource)
      throws JDBCRepositoryException {

    JDBCDriverVendor vendor;
    if (dataSource instanceof VendorDataSource) {
      VendorDataSource vendorDataSource = (VendorDataSource) dataSource;
      vendor = vendorDataSource.getVendor();
    } else {
      String databaseProduct = null;
      Connection con = null;
      try {
        con = dataSource.getConnection();
        DatabaseMetaData metaData = con.getMetaData();
        databaseProduct = metaData.getDatabaseProductName();
        con.close();
      } catch (SQLException sqle) {
        throw new JDBCRepositoryException(EXCEPTION_LOCALIZER.format("sql-exception"), sqle);
      }

      if (PRODUCT_ORACLE.equalsIgnoreCase(databaseProduct)) {
        vendor = JDBCDriverVendor.ORACLE8;
      } else if (databaseProduct != null
          && databaseProduct.regionMatches(true, 0, PRODUCT_DB2, 0, PRODUCT_DB2.length())) {
        vendor = JDBCDriverVendor.DB2;
      } else if (PRODUCT_MSSQL.equalsIgnoreCase(databaseProduct)) {
        vendor = JDBCDriverVendor.MSSQL_JSQL;
      } else if (PRODUCT_SYBASE.equalsIgnoreCase(databaseProduct)) {
        vendor = JDBCDriverVendor.SYBASE;
      } else if (PRODUCT_POSTGRES.equalsIgnoreCase(databaseProduct)) {
        vendor = JDBCDriverVendor.POSTGRESQL;
      } else if (PRODUCT_HYPERSONIC.equalsIgnoreCase(databaseProduct)) {
        vendor = JDBCDriverVendor.HYPERSONIC;
      } else if (PRODUCT_MYSQL.equalsIgnoreCase(databaseProduct)) {
        vendor = JDBCDriverVendor.MYSQL;
      } else if (PRODUCT_DERBY.equalsIgnoreCase(databaseProduct)) {
        vendor = JDBCDriverVendor.DERBY_SERVER;
      } else {
        throw new JDBCRepositoryException(
            EXCEPTION_LOCALIZER.format("jdbc-unknown-vendor", databaseProduct));
      }
    }
    return vendor;
  }
  /** {@inheritDoc} */
  public void setConf(Configuration conf) {

    dbConf = new DBConfiguration(conf);

    try {
      this.connection = dbConf.getConnection();
      this.connection.setAutoCommit(false);
      connection.setTransactionIsolation(Connection.TRANSACTION_SERIALIZABLE);

      DatabaseMetaData dbMeta = connection.getMetaData();
      this.dbProductName = dbMeta.getDatabaseProductName().toUpperCase();
    } catch (Exception ex) {
      throw new RuntimeException(ex);
    }

    tableName = dbConf.getInputTableName();
    fieldNames = dbConf.getInputFieldNames();
    conditions = dbConf.getInputConditions();
  }
Beispiel #27
0
  /** Initializes DatabaseFactory. */
  public static synchronized void init() {
    if (dataSource != null) {
      return;
    }

    DatabaseConfig.load();

    try {
      DatabaseConfig.DATABASE_DRIVER.newInstance();
    } catch (Exception e) {
      log.fatal("Error obtaining DB driver", e);
      throw new Error("DB Driver doesnt exist!");
    }

    connectionPool = new GenericObjectPool();

    if (DatabaseConfig.DATABASE_CONNECTIONS_MIN > DatabaseConfig.DATABASE_CONNECTIONS_MAX) {
      log.error(
          "Please check your database configuration. Minimum amount of connections is > maximum");
      DatabaseConfig.DATABASE_CONNECTIONS_MAX = DatabaseConfig.DATABASE_CONNECTIONS_MIN;
    }

    connectionPool.setMaxIdle(DatabaseConfig.DATABASE_CONNECTIONS_MIN);
    connectionPool.setMaxActive(DatabaseConfig.DATABASE_CONNECTIONS_MAX);

    /* test if connection is still valid before returning */
    connectionPool.setTestOnBorrow(true);

    try {
      dataSource = setupDataSource();
      Connection c = getConnection();
      DatabaseMetaData dmd = c.getMetaData();
      databaseName = dmd.getDatabaseProductName();
      databaseMajorVersion = dmd.getDatabaseMajorVersion();
      databaseMinorVersion = dmd.getDatabaseMinorVersion();
      c.close();
    } catch (Exception e) {
      log.fatal("Error with connection string: " + DatabaseConfig.DATABASE_URL, e);
      throw new Error("DatabaseFactory not initialized!");
    }

    log.info("Successfully connected to database");
  }
 protected void setupConnectionMetaInfo(Connection conn) throws SQLException {
   try {
     final DfConnectionMetaInfo metaInfo = new DfConnectionMetaInfo();
     final DatabaseMetaData metaData = conn.getMetaData();
     metaInfo.setProductName(metaData.getDatabaseProductName());
     metaInfo.setProductVersion(metaData.getDatabaseProductVersion());
     metaInfo.setDriverName(metaData.getDriverName());
     metaInfo.setDriverVersion(metaData.getDriverVersion());
     final int majorVersion = metaData.getJDBCMajorVersion();
     final int minorVersion = metaData.getJDBCMinorVersion();
     metaInfo.setJdbcVersion(majorVersion + "." + minorVersion);
     _log.info("  product = " + metaInfo.getProductDisp());
     _log.info("  driver  = " + metaInfo.getDriverDisp());
     _connectionMetaInfo = metaInfo;
   } catch (SQLException continued) {
     _log.info("*Failed to get connection meta: " + continued.getMessage());
     _connectionMetaInfo = null;
   }
 }
  @RequestMapping(method = RequestMethod.GET)
  public String showInformations(Model model) {
    List<Informations> info = new ArrayList<>();
    info.add(new Informations("Versão", repInfo.getProperty("repository.version")));
    info.add(new Informations("Número de documentos", Long.toString(docService.count())));

    info.add(
        new Informations(
            "Domínio",
            config.getProperty("Repositorio.hostname"),
            "Este dominio será utilizado para criar a localização dos documentos. Editar no arquivo: 'config.properties'."));
    info.add(
        new Informations(
            "Raiz do projeto", config.getProperty("Repositorio.rootPath", "/repositorio")));
    info.add(
        new Informations(
            "Porta",
            config.getProperty("Repositorio.port", "8080"),
            "Porta informada no arquivo '/WEB-INF/classes/config.properties'"));
    info.add(
        new Informations(
            "URL dos objetos",
            Config.getUrl(config) + "{id}",
            "URL que será utilizada para criar o location dos objetos. Pode ser editada em: '/WEB-INF/classes/config.properties'"));
    try {
      DatabaseMetaData databaseInfo = dataSource.getConnection().getMetaData();
      info.add(new Informations("Base de dados utilizada", databaseInfo.getDatabaseProductName()));
      info.add(
          new Informations("Versão da base de dados", databaseInfo.getDatabaseProductVersion()));
      info.add(new Informations("JDBC driver", databaseInfo.getDriverName()));
      info.add(new Informations("Versão do JDBC driver", databaseInfo.getDriverVersion()));
      info.add(new Informations("URL da base de dados", databaseInfo.getURL()));
      info.add(new Informations("Usuário da base de dados", databaseInfo.getUserName()));

    } catch (SQLException s) {
      log.error("Error getting information about database.", s);
      info.add(new Informations("Erro", "Não foi possível carregar os dados da base de dados"));
    }
    model.addAttribute("info", info);
    return "panel/show";
  }
Beispiel #30
0
 private static Map<PwmAboutProperty, String> getConnectionDebugProperties(
     final Connection connection) {
   if (connection != null) {
     try {
       final Map<PwmAboutProperty, String> returnObj = new LinkedHashMap<>();
       final DatabaseMetaData databaseMetaData = connection.getMetaData();
       returnObj.put(PwmAboutProperty.database_driverName, databaseMetaData.getDriverName());
       returnObj.put(PwmAboutProperty.database_driverVersion, databaseMetaData.getDriverVersion());
       returnObj.put(
           PwmAboutProperty.database_databaseProductName,
           databaseMetaData.getDatabaseProductName());
       returnObj.put(
           PwmAboutProperty.database_databaseProductVersion,
           databaseMetaData.getDatabaseProductVersion());
       return Collections.unmodifiableMap(returnObj);
     } catch (SQLException e) {
       LOGGER.error("error rading jdbc meta data: " + e.getMessage());
     }
   }
   return Collections.emptyMap();
 }