List of usage examples for java.sql DatabaseMetaData getDatabaseProductName
String getDatabaseProductName() throws SQLException;
From source file:nl.nn.adapterframework.jdbc.JdbcFacade.java
public String getDatasourceInfo() throws JdbcException { String dsinfo = null;/*from ww w. j av a 2 s.c o m*/ 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 ww .j a v a2 s . c o m } } return client; }
From source file:org.openbizview.util.Bvt001A.java
/** * Leer registros en la tabla/* w w w. j a va 2 s . c om*/ * @throws NamingException * @throws IOException **/ public void counter(Object filterValue) throws SQLException, NamingException { try { Context initContext = new InitialContext(); DataSource ds = (DataSource) initContext.lookup(JNDI); con = ds.getConnection(); //Reconoce la base de datos de coneccin para ejecutar el query correspondiente a cada uno DatabaseMetaData databaseMetaData = con.getMetaData(); productName = databaseMetaData.getDatabaseProductName();//Identifica la base de datos de coneccin String query = ""; switch (productName) { case "Oracle": query = "SELECT count_bvt001a('" + ((String) filterValue).toUpperCase() + "','" + instancia + "') from dual"; break; case "PostgreSQL": query = "SELECT count_bvt001a('" + ((String) filterValue).toUpperCase() + "','" + instancia + "')"; break; case "Microsoft SQL Server": query = "SELECT DBO.count_bvt001a('" + ((String) filterValue).toUpperCase() + "','" + instancia + "')"; break; } pstmt = con.prepareStatement(query); //System.out.println(query); r = pstmt.executeQuery(); while (r.next()) { rows = r.getInt(1); } } catch (SQLException e) { e.printStackTrace(); } //Cierra las conecciones pstmt.close(); con.close(); r.close(); }
From source file:org.openbizview.util.Bvt006.java
/** * Leer Datos de auditoria/*from ww w .j a v a 2 s . c o m*/ * @throws NamingException * @throws IOException **/ public void select(int first, int pageSize, String sortField, Object filterValue) throws SQLException, ClassNotFoundException, NamingException { Context initContext = new InitialContext(); DataSource ds = (DataSource) initContext.lookup(JNDI); con = ds.getConnection(); //Reconoce la base de datos de coneccin para ejecutar el query correspondiente a cada uno DatabaseMetaData databaseMetaData = con.getMetaData(); productName = databaseMetaData.getDatabaseProductName();//Identifica la base de datos de coneccin String query = ""; if (bcoduser == null) { bcoduser = " - "; } if (bcoduser == "") { bcoduser = " - "; } String[] vlcoduser = bcoduser.split("\\ - ", -1); switch (productName) { case "Oracle": query += " select * from "; query += " ( select query.*, rownum as rn from"; query += " (SELECT trim(B_CODREP), trim(B_DESREP), trim(B_CODUSER), to_char(FECACC, 'dd/mm/yyyy hh:mi:ss')"; query += " FROM bvt006"; query += " WHERE B_CODUSER LIKE '" + vlcoduser[0] + "%'"; query += " and b_codrep||b_desrep like '%" + ((String) filterValue).toUpperCase() + "%'"; query += " AND instancia = '" + instancia + "'"; query += " order by B_CODUSER, FECACC desc) query"; query += " ) where rownum <= " + pageSize; query += " and rn > (" + first + ")"; break; case "PostgreSQL": query += " SELECT trim(B_CODREP), trim(B_DESREP), trim(B_CODUSER), to_char(FECACC, 'dd/mm/yyyy hh:mi:ss') "; query += " FROM BVT006"; query += " WHERE B_CODUSER LIKE '" + vlcoduser[0] + "%'"; query += " and b_codrep||b_desrep like '%" + ((String) filterValue).toUpperCase() + "%'"; query += " AND instancia = '" + instancia + "'"; query += " order by B_CODUSER, FECACC desc"; query += " LIMIT " + pageSize; query += " OFFSET " + first; break; case "Microsoft SQL Server": query += " SELECT * "; query += " FROM (SELECT "; query += " ROW_NUMBER() OVER (ORDER BY B_CODREP ASC) AS ROW_NUM, "; query += " B_CODREP, "; query += " B_DESREP, "; query += " B_CODUSER, "; query += " CONVERT(VARCHAR(10), FECACC, 103) + ' ' + CONVERT(VARCHAR(8), FECACC, 14) FECACC "; query += " FROM BVT006) TOT "; query += " WHERE "; query += " TOT.B_CODUSER LIKE '" + vlcoduser[0] + "%'"; query += " AND TOT.B_CODREP + TOT.B_DESREP LIKE '%" + ((String) filterValue).toUpperCase() + "%'"; query += " AND tot.instancia = '" + instancia + "'"; query += " AND TOT.ROW_NUM <= " + pageSize; query += " AND TOT.ROW_NUM > " + first; query += " ORDER BY "; query += " TOT.B_CODUSER, "; query += " TOT.FECACC DESC "; break; } pstmt = con.prepareStatement(query); ////System.out.println(query); r = pstmt.executeQuery(); while (r.next()) { Bvt006 select = new Bvt006(); select.setBcodrep(r.getString(1)); select.setBdesrep(r.getString(2)); select.setBcoduser(r.getString(3)); select.setFecacc(r.getString(4)); //Agrega la lista list.add(select); } //Cierra las conecciones pstmt.close(); con.close(); }
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); }/*from w w w . j a va 2s .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.openbizview.util.Tubder09.java
/** * Leer Datos de paises/*w w w .ja v a 2 s .com*/ * @throws NamingException * @throws IOException **/ public void select(int first, int pageSize, String sortField, Object filterValue) throws SQLException, ClassNotFoundException, NamingException { //System.out.println("entre al metodo SELECT"); Context initContext = new InitialContext(); DataSource ds = (DataSource) initContext.lookup(JNDI); con = ds.getConnection(); //Reconoce la base de datos de coneccin para ejecutar el query correspondiente a cada uno DatabaseMetaData databaseMetaData = con.getMetaData(); productName = databaseMetaData.getDatabaseProductName();//Identifica la base de datos de coneccin //Consulta paginada String query = "SELECT * FROM"; query += "(select query.*, rownum as rn from"; query += "(SELECT A.CODIGO, A.DESCR"; query += " FROM TUBDER09 A"; query += " GROUP BY A.CODIGO, A.DESCR"; query += ")query ) "; query += " WHERE ROWNUM <=" + pageSize; query += " AND rn > (" + first + ")"; query += " ORDER BY " + sortField.replace("z", ""); pstmt = con.prepareStatement(query); //System.out.println(query); r = pstmt.executeQuery(); while (r.next()) { Tubder09 select = new Tubder09(); select.setZcodigo(r.getString(1)); select.setZdesc(r.getString(2)); //Agrega la lista list.add(select); } //Cierra las conecciones pstmt.close(); con.close(); }
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); }/* w w w . j ava2 s. c o m*/ } } return client; }
From source file:org.openbizview.util.Bvtcat1.java
/** * Leer registros en la tabla// ww w. ja v a 2 s. c o m * @throws NamingException * @throws IOException **/ public void counter(Object filterValue) throws SQLException, NamingException { try { Context initContext = new InitialContext(); DataSource ds = (DataSource) initContext.lookup(JNDI); con = ds.getConnection(); //Reconoce la base de datos de coneccin para ejecutar el query correspondiente a cada uno DatabaseMetaData databaseMetaData = con.getMetaData(); productName = databaseMetaData.getDatabaseProductName();//Identifica la base de datos de coneccin String query = ""; switch (productName) { case "Oracle": query = "SELECT count_bvtcat1('" + ((String) filterValue).toUpperCase() + "','" + instancia + "') from dual"; break; case "PostgreSQL": query = "SELECT count_bvtcat1('" + ((String) filterValue).toUpperCase() + "','" + instancia + "')"; break; case "Microsoft SQL Server": query = "SELECT DBO.count_bvtcat1('" + ((String) filterValue).toUpperCase() + "','" + instancia + "')"; break; } pstmt = con.prepareStatement(query); //System.out.println(query); r = pstmt.executeQuery(); while (r.next()) { rows = r.getInt(1); } } catch (SQLException e) { e.printStackTrace(); } //Cierra las conecciones pstmt.close(); con.close(); r.close(); }
From source file:org.openbizview.util.Bvt003.java
/** * Leer registros en la tabla/* w w w .j ava 2s. c o m*/ * @throws NamingException * @throws IOException **/ public void counter(Object filterValue) throws SQLException, NamingException { try { Context initContext = new InitialContext(); DataSource ds = (DataSource) initContext.lookup(JNDI); con = ds.getConnection(); //Reconoce la base de datos de coneccin para ejecutar el query correspondiente a cada uno DatabaseMetaData databaseMetaData = con.getMetaData(); productName = databaseMetaData.getDatabaseProductName();//Identifica la base de datos de coneccin String query = ""; switch (productName) { case "Oracle": query = "SELECT count_bvt003('" + ((String) filterValue).toUpperCase() + "','" + instancia + "') from dual"; break; case "PostgreSQL": query = "SELECT count_bvt003('" + ((String) filterValue).toUpperCase() + "','" + instancia + "')"; break; case "Microsoft SQL Server": query = "SELECT DBO.count_bvt003('" + ((String) filterValue).toUpperCase() + "','" + instancia + "')"; break; } pstmt = con.prepareStatement(query); //System.out.println(query); r = pstmt.executeQuery(); while (r.next()) { rows = r.getInt(1); } } catch (SQLException e) { e.printStackTrace(); } //Cierra las conecciones pstmt.close(); con.close(); r.close(); }
From source file:org.talend.core.model.metadata.DBConnectionFillerImplTest.java
/** * /*from w w w . j av a 2s .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); }