List of usage examples for java.sql DatabaseMetaData getDatabaseProductVersion
String getDatabaseProductVersion() throws SQLException;
From source file:org.apache.openjpa.jdbc.sql.HSQLDictionary.java
/** * Determine HSQLDB version either by using JDBC 3 method or, if it * is not available, by parsing the value returned by * {@linkplain DatabaseMetaData#getDatabaseProductVersion()}. *//* w ww. j ava2 s .c om*/ protected void determineHSQLDBVersion(Connection con) throws SQLException { DatabaseMetaData metaData = con.getMetaData(); if (isJDBC3) { dbMajorVersion = metaData.getDatabaseMajorVersion(); } else { // String is like "2.0.0" String productVersion = metaData.getDatabaseProductVersion(); String[] version = productVersion.split("\\."); dbMajorVersion = Integer.parseInt(version[0]); } }
From source file:org.acmsl.queryj.tools.handlers.AbstractQueryJCommandHandler.java
/** * Retrieves the database product version. * @param metadata the database metadata. * @return such information, or null if the vendor complains. *///from w w w . j a va2s.c o m @Nullable protected String retrieveDatabaseProductVersion(@NotNull final DatabaseMetaData metadata) { @Nullable String result = null; try { result = metadata.getDatabaseProductVersion(); } catch (@NotNull final Throwable throwable) { @Nullable final Log t_Log = UniqueLogFactory.getLog(AbstractQueryJCommandHandler.class); if (t_Log != null) { t_Log.info("Database vendor complained when queried about " + "its version via " + "java.sql.DatabaseMetaData.getDatabaseProductVersion()", throwable); } } return result; }
From source file:nl.nn.adapterframework.jdbc.JdbcFacade.java
public String getDatasourceInfo() throws JdbcException { String dsinfo = null;//from w w w. j av a2s .c om Connection conn = null; try { conn = getConnection(); DatabaseMetaData md = conn.getMetaData(); String product = md.getDatabaseProductName(); String productVersion = md.getDatabaseProductVersion(); String driver = md.getDriverName(); String driverVersion = md.getDriverVersion(); String url = md.getURL(); String user = md.getUserName(); if (getDatabaseType() == DbmsSupportFactory.DBMS_DB2 && "WAS".equals(IbisContext.getApplicationServerType()) && md.getResultSetHoldability() != ResultSet.HOLD_CURSORS_OVER_COMMIT) { // For (some?) combinations of WebShere and DB2 this seems to be // the default and result in the following exception when (for // example?) a ResultSetIteratingPipe is calling next() on the // ResultSet after it's sender has called a pipeline which // contains a GenericMessageSendingPipe using // transactionAttribute="NotSupported": // com.ibm.websphere.ce.cm.ObjectClosedException: DSRA9110E: ResultSet is closed. ConfigurationWarnings configWarnings = ConfigurationWarnings.getInstance(); configWarnings.add(log, "The database's default holdability for ResultSet objects is " + md.getResultSetHoldability() + " instead of " + ResultSet.HOLD_CURSORS_OVER_COMMIT + " (ResultSet.HOLD_CURSORS_OVER_COMMIT)"); } dsinfo = "user [" + user + "] url [" + url + "] product [" + product + "] version [" + productVersion + "] driver [" + driver + "] version [" + driverVersion + "]"; } catch (SQLException e) { log.warn("Exception determining databaseinfo", e); } finally { if (conn != null) { try { conn.close(); } catch (SQLException e1) { log.warn("exception closing connection for metadata", e1); } } } return dsinfo; }
From source file:org.sakaiproject.nakamura.lite.storage.jdbc.JDBCStorageClientPool.java
protected JDBCStorageClient checkSchema(Object o) { JDBCStorageClient client = (JDBCStorageClient) o; synchronized (sqlConfigLock) { if (!schemaHasBeenChecked) { try { Connection connection = client.getConnection(); DatabaseMetaData metadata = connection.getMetaData(); LOGGER.info("Starting Sparse Map Content database "); LOGGER.info(" Database Vendor: {} {}", metadata.getDatabaseProductName(), metadata.getDatabaseProductVersion()); LOGGER.info(" Database Driver: {} ", properties.get(JDBC_DRIVER)); LOGGER.info(" Database URL : {} ", properties.get(CONNECTION_URL)); client.checkSchema(getClientConfigLocations(client.getConnection())); schemaHasBeenChecked = true; } catch (Throwable e) { LOGGER.warn("Failed to check Schema", e); }//from w w w .j ava 2 s . c o m } } return client; }
From source file:org.sakaiproject.nakamura.lite.storage.jdbc.BaseJDBCStorageClientPool.java
protected JDBCStorageClient checkSchema(Object o) { JDBCStorageClient client = (JDBCStorageClient) o; synchronized (sqlConfigLock) { if (!schemaHasBeenChecked) { try { Connection connection = client.getConnection(); DatabaseMetaData metadata = connection.getMetaData(); LOGGER.info("Starting Sparse Map Content database "); LOGGER.info(" Database Vendor: {} {}", metadata.getDatabaseProductName(), metadata.getDatabaseProductVersion()); LOGGER.info(" Database Driver: {} ", properties.get(JDBC_DRIVER)); LOGGER.info(" Database URL : {} ", properties.get(CONNECTION_URL)); client.checkSchema(getClientConfigLocations(client.getConnection())); schemaHasBeenChecked = true; indexColumnsMap = client.syncIndexColumns(); } catch (Throwable e) { LOGGER.warn("Failed to check Schema", e); }//from w ww. j a v a 2 s. c o m } } return client; }
From source file:org.wso2.carbon.server.admin.service.ServerAdmin.java
public ServerData getServerData() throws Exception { boolean isRestricted = true; MessageContext msgContext = MessageContext.getCurrentMessageContext(); if (msgContext != null) { HttpServletRequest request = (HttpServletRequest) msgContext .getProperty(HTTPConstants.MC_HTTP_SERVLETREQUEST); HttpSession httpSession = request.getSession(false); if (httpSession != null) { String userName = (String) httpSession.getAttribute(ServerConstants.USER_LOGGED_IN); isRestricted = !getUserRealm().getAuthorizationManager().isUserAuthorized(userName, "/permission/protected/server-admin/homepage", CarbonConstants.UI_PERMISSION_ACTION); }// www . j a v a 2 s.c o m } else { // non SOAP call isRestricted = false; } String location = null; if (!isRestricted) { location = getAxisConfig().getRepository().toString(); } ServerData data = new ServerData(ServerConstants.SERVER_NAME, location, (getTenantDomain() != null && !getTenantDomain().equals(MultitenantConstants.SUPER_TENANT_DOMAIN_NAME)), isRestricted); if (!isRestricted) { Parameter systemStartTime = getAxisConfig().getParameter(CarbonConstants.SERVER_START_TIME); long startTime = 0; if (systemStartTime != null) { startTime = Long.parseLong((String) systemStartTime.getValue()); } Date stTime = new Date(startTime); SimpleDateFormat dateFormatter = new SimpleDateFormat("yyyy-MM-dd' 'HH:mm:ss"); data.setServerStartTime(dateFormatter.format(stTime)); data.setServerUpTime(getTime((System.currentTimeMillis() - startTime) / 1000)); Parameter systemStartUpDuration = getAxisConfig().getParameter(CarbonConstants.START_UP_DURATION); if (systemStartUpDuration != null) { data.setServerStartUpDuration((String) systemStartUpDuration.getValue()); } ServerConfigurationService serverConfig = dataHolder.getServerConfig(); String registryType = serverConfig.getFirstProperty("Registry.Type"); if (registryType == null) { registryType = "embedded"; } data.setRegistryType(registryType); // Extract DB related data from RegistryContext if (registryType.equals("embedded")) { try { DataAccessManager dataAccessManager = RegistryContext.getBaseInstance().getDataAccessManager(); if (!(dataAccessManager instanceof JDBCDataAccessManager)) { String msg = "Failed to obtain DB connection. Invalid data access manager."; log.error(msg); throw new AxisFault(msg); } DataSource dataSource = ((JDBCDataAccessManager) dataAccessManager).getDataSource(); Connection dbConnection = dataSource.getConnection(); DatabaseMetaData metaData = dbConnection.getMetaData(); if (metaData != null) { data.setDbName(metaData.getDatabaseProductName()); data.setDbVersion(metaData.getDatabaseProductVersion()); data.setDbDriverName(metaData.getDriverName()); data.setDbDriverVersion(metaData.getDriverVersion()); data.setDbURL(metaData.getURL()); } dbConnection.close(); } catch (SQLException e) { String msg = "Cannot create DB connection"; log.error(msg, e); throw new AxisFault(msg, e); } } else if (registryType.equals("remote")) { data.setRemoteRegistryChroot(serverConfig.getFirstProperty("Registry.Chroot")); data.setRemoteRegistryURL(serverConfig.getFirstProperty("Registry.Url")); } } try { data.setServerIp(NetworkUtils.getLocalHostname()); } catch (SocketException e) { throw new AxisFault(e.getMessage(), e); } return data; }
From source file:org.talend.core.model.metadata.DBConnectionFillerImplTest.java
/** * // w w w . j av a 2 s . c o m * test TDQ-6569, it should be empty String even * dbMetadata.getDatabaseProductName()/dbMetadata.getDatabaseProductName() is null . * * @throws Exception */ @Test public void testfillUIConnParams_DB2ZOS() throws Exception { java.sql.Connection sqlConnection = mock(java.sql.Connection.class); IMetadataConnection metadataBean = mock(IMetadataConnection.class); DatabaseConnection connection = mock(DatabaseConnection.class); EList<TaggedValue> taggedValues = new BasicEList<TaggedValue>(); when(connection.getTaggedValue()).thenReturn(taggedValues); when(connection.getDatabaseType()).thenReturn("IBMDB2ZOS"); //$NON-NLS-1$ when(connection.getDriverClass()).thenReturn(EDatabase4DriverClassName.IBMDB2ZOS.getDriverClass()); when(connection.isContextMode()).thenReturn(Boolean.FALSE); TypedReturnCode<java.sql.Connection> rc = new TypedReturnCode<java.sql.Connection>(); rc.setOk(true); rc.setObject(sqlConnection); PowerMockito.mockStatic(MetadataConnectionUtils.class); when(MetadataConnectionUtils.checkConnection(metadataBean)).thenReturn(rc); when(MetadataConnectionUtils.createConnection(metadataBean)).thenReturn(rc); when(MetadataConnectionUtils.createConnection(metadataBean, true)).thenReturn(rc); when(MetadataConnectionUtils.createConnection(metadataBean, false)).thenReturn(rc); when(MetadataConnectionUtils.isDerbyRelatedDb(anyString(), anyString())).thenReturn(false); DatabaseMetaData dbMetadata = mock(DatabaseMetaData.class); when(dbMetadata.getDatabaseProductName()).thenReturn(null); when(dbMetadata.getDatabaseProductVersion()).thenReturn(null); PowerMockito.mockStatic(ExtractMetaDataUtils.class); ExtractMetaDataUtils extract = Mockito.mock(ExtractMetaDataUtils.class); Mockito.when(ExtractMetaDataUtils.getInstance()).thenReturn(extract); when(extract.getDatabaseMetaData(sqlConnection, connection, false)).thenReturn(dbMetadata); when(extract.getDatabaseMetaData(null, connection, false)).thenReturn(dbMetadata); PowerMockito.mockStatic(ConnectionUtils.class); ReturnCode ret = new ReturnCode(); ret.setOk(true); when(ConnectionUtils.closeConnection(sqlConnection)).thenReturn(ret); DBConnectionFillerImpl dBConnectionFillerImp_mock = PowerMockito.spy(dBConnectionFillerImpl); PowerMockito.doNothing().when(dBConnectionFillerImp_mock, "fillMetadataParams", metadataBean, connection); //$NON-NLS-1$ dBConnectionFillerImp_mock.fillUIConnParams(metadataBean, connection); String producetName = TaggedValueHelper.getValueString(TaggedValueHelper.DB_PRODUCT_NAME, connection); String version = TaggedValueHelper.getValueString(TaggedValueHelper.DB_PRODUCT_VERSION, connection); assertNotNull(producetName); assertNotNull(version); assertEquals(producetName, PluginConstant.EMPTY_STRING); assertEquals(version, PluginConstant.EMPTY_STRING); }
From source file:DatabaseInfo.java
public void doGet(HttpServletRequest inRequest, HttpServletResponse outResponse) throws ServletException, IOException { PrintWriter out = null;/*from w w w . jav a 2s.c o m*/ Connection connection = null; Statement statement; ResultSet rs; outResponse.setContentType("text/html"); out = outResponse.getWriter(); try { Context ctx = new InitialContext(); DataSource ds = (DataSource) ctx.lookup("java:comp/env/jdbc/AccountsDB"); connection = ds.getConnection(); DatabaseMetaData md = connection.getMetaData(); statement = connection.createStatement(); out.println("<HTML><HEAD><TITLE>Database Server Information</TITLE></HEAD>"); out.println("<BODY>"); out.println("<H1>General Source Information</H1>"); out.println("getURL() - " + md.getURL() + "<BR>"); out.println("getUserName() - " + md.getUserName() + "<BR>"); out.println("getDatabaseProductVersion - " + md.getDatabaseProductVersion() + "<BR>"); out.println("getDriverMajorVersion - " + md.getDriverMajorVersion() + "<BR>"); out.println("getDriverMinorVersion - " + md.getDriverMinorVersion() + "<BR>"); out.println("nullAreSortedHigh - " + md.nullsAreSortedHigh() + "<BR>"); out.println("<H1>Feature Support</H1>"); out.println("supportsAlterTableWithDropColumn - " + md.supportsAlterTableWithDropColumn() + "<BR>"); out.println("supportsBatchUpdates - " + md.supportsBatchUpdates() + "<BR>"); out.println("supportsTableCorrelationNames - " + md.supportsTableCorrelationNames() + "<BR>"); out.println("supportsPositionedDelete - " + md.supportsPositionedDelete() + "<BR>"); out.println("supportsFullOuterJoins - " + md.supportsFullOuterJoins() + "<BR>"); out.println("supportsStoredProcedures - " + md.supportsStoredProcedures() + "<BR>"); out.println("supportsMixedCaseQuotedIdentifiers - " + md.supportsMixedCaseQuotedIdentifiers() + "<BR>"); out.println("supportsANSI92EntryLevelSQL - " + md.supportsANSI92EntryLevelSQL() + "<BR>"); out.println("supportsCoreSQLGrammar - " + md.supportsCoreSQLGrammar() + "<BR>"); out.println("<H1>Data Source Limits</H1>"); out.println("getMaxRowSize - " + md.getMaxRowSize() + "<BR>"); out.println("getMaxStatementLength - " + md.getMaxStatementLength() + "<BR>"); out.println("getMaxTablesInSelect - " + md.getMaxTablesInSelect() + "<BR>"); out.println("getMaxConnections - " + md.getMaxConnections() + "<BR>"); out.println("getMaxCharLiteralLength - " + md.getMaxCharLiteralLength() + "<BR>"); out.println("<H1>SQL Object Available</H1>"); out.println("getTableTypes()<BR><UL>"); rs = md.getTableTypes(); while (rs.next()) { out.println("<LI>" + rs.getString(1)); } out.println("</UL>"); out.println("getTables()<BR><UL>"); rs = md.getTables("accounts", "", "%", new String[0]); while (rs.next()) { out.println("<LI>" + rs.getString("TABLE_NAME")); } out.println("</UL>"); out.println("<H1>Transaction Support</H1>"); out.println("getDefaultTransactionIsolation() - " + md.getDefaultTransactionIsolation() + "<BR>"); out.println( "dataDefinitionIgnoredInTransactions() - " + md.dataDefinitionIgnoredInTransactions() + "<BR>"); out.println("<H1>General Source Information</H1>"); out.println("getMaxTablesInSelect - " + md.getMaxTablesInSelect() + "<BR>"); out.println("getMaxColumnsInTable - " + md.getMaxColumnsInTable() + "<BR>"); out.println("getTimeDateFunctions - " + md.getTimeDateFunctions() + "<BR>"); out.println("supportsCoreSQLGrammar - " + md.supportsCoreSQLGrammar() + "<BR>"); out.println("getTypeInfo()<BR><UL>"); rs = md.getTypeInfo(); while (rs.next()) { out.println("<LI>" + rs.getString(1)); } out.println("</UL>"); out.println("</BODY></HTML>"); } catch (Exception e) { e.printStackTrace(); } }
From source file:nl.strohalm.cyclos.setup.DataBaseConfiguration.java
private void handleDatabase(final Properties properties) { // Retrieve the connection final String dataSource = StringUtils.trimToNull(properties.getProperty(Environment.DATASOURCE)); Connection connection;/* ww w.j a v a 2 s . c o m*/ String connectionLocation; if (dataSource != null) { // Use Hibernate's own DatasourceConnectionProvider when using a JNDI datasource final ConnectionProvider provider = new DatasourceConnectionProvider(); provider.configure(properties); try { connection = provider.getConnection(); } catch (final SQLException e) { final String msg = "Error connecting to datasource at " + dataSource; LOG.error(msg); throw new RuntimeException(msg, e); } connectionLocation = dataSource; } else { // Manually verify the connection final String driverClass = StringUtils.trimToNull(properties.getProperty(Environment.DRIVER)); validateDriver(driverClass); final String url = properties.getProperty(Environment.URL); final String username = properties.getProperty(Environment.USER); final String password = properties.getProperty(Environment.PASS); connection = validateConnection(url, username, password); connectionLocation = url; } final JDBCWrapper jdbc = new JDBCWrapper(connection); // Check whether we will create the database if necessary final boolean embedded = Boolean.valueOf(properties.getProperty("cyclos.embedded.enable", "false")); // Get the connection meta data boolean dataBaseExists = true; String dataBaseName; String dataBaseVersion; try { final DatabaseMetaData metaData = connection.getMetaData(); dataBaseName = metaData.getDatabaseProductName(); dataBaseVersion = metaData.getDatabaseProductVersion(); } catch (final SQLException e) { throw new RuntimeException("Error reading database metadata", e); } // Check if the database exists, by reading the current version final String currentVersion; try { currentVersion = readCurrentVersion(jdbc); if (currentVersion != null) { LOG.info(String.format("Cyclos database version %s found on %s version %s", currentVersion, dataBaseName, dataBaseVersion)); } dataBaseExists = currentVersion != null; // Check for new versions schema upgrade if (dataBaseExists) { final boolean autoUpgrade = Boolean .valueOf(properties.getProperty("cyclos.autoSchemaUpgrade.enable", "false")); if (autoUpgrade) { // Run the schema upgrade final String newVersion = upgradeSchema(currentVersion, jdbc); if (!currentVersion.equals(newVersion)) { // The version has changed. Add a custom property on the configuration properties for the cache // manager to clear the current cache, because new entities may be incompatible with cached versions properties.setProperty("cyclos.versionHasChanged", "true"); } } } else { // For MySQL connections, we should ensure that the database is set to utf8 if (embedded && dataBaseName.toLowerCase().equals("mysql")) { try { jdbc.commit(); jdbc.execute("alter database character set utf8"); } catch (final SQLException e) { e.printStackTrace(); // Ignore } } } } finally { // Close the connection try { connection.close(); } catch (final SQLException e) { } } // Run the setup if needed if (!dataBaseExists) { if (embedded) { final boolean smsEmbedded = Boolean .valueOf(properties.getProperty("cyclos.embedded.sms.enable", "false")); LOG.info("Database is empty. Running setup to populate it"); sessionFactory = configuration.buildSessionFactory(); final Locale locale = LocaleConverter.instance() .valueOf(properties.getProperty("cyclos.embedded.locale", "en_US")); final Setup setup = new Setup(configuration, sessionFactory); setup.setLocale(locale); setup.setCreateDataBase(true); setup.setCreateBasicData(true); setup.setCreateInitialData(true); setup.setCreateSmsData(smsEmbedded); setup.setForce(true); setup.execute(); } else { throw new RuntimeException("Cyclos database not found at " + connectionLocation); } } }
From source file:com.bluexml.side.Integration.alfresco.sql.synchronization.schemaManagement.SchemaCreation.java
private void checkMetaData() { logger.debug("Checking meta-data"); DatabaseMetaData dmd = null; Connection connection = DataSourceUtils.getConnection(dataSource); try {/*from www. ja v a 2 s . c o m*/ dmd = connection.getMetaData(); String dbname = dmd.getDatabaseProductName(); String dbversion = dmd.getDatabaseProductVersion(); if (logger.isDebugEnabled()) logger.debug("Running sql synchronization on " + dbname + " " + dbversion); } catch (SQLException e) { logger.error(e); } finally { DataSourceUtils.releaseConnection(connection, dataSource); } }