List of usage examples for java.sql DatabaseMetaData getURL
String getURL() throws SQLException;
From source file:com.ah.be.communication.BusinessUtil.java
private static String[] getDBSettings() throws SQLException { String[] dbSettings = new String[5]; Connection con = null;//from w w w . j a va 2 s. c o m try { con = QueryUtil.getConnection(); DatabaseMetaData mData = con.getMetaData(); String[] urls = DBOperationUtil.parseJDBCUrl(mData.getURL()); if (urls != null && urls.length == 3) { dbSettings[0] = urls[0]; dbSettings[1] = urls[1]; dbSettings[2] = urls[2]; dbSettings[3] = System.getProperty("hm.connection.username"); dbSettings[4] = System.getProperty("hm.connection.password"); } return dbSettings; } finally { if (con != null && !con.isClosed()) { try { con.close(); } catch (SQLException e) { log.error("Connection close error.", e); } } } }
From source file:org.metis.push.PusherBean.java
/** * Called by Spring after all of this bean's properties have been set. *///w w w . j a va 2 s . co m public void afterPropertiesSet() throws Exception { // create the session registry setWdsSessions(new Hashtable<String, WdsSocketSession>(getInitCapacity())); // log info for the jdbc driver being used // this will also attempt to open connection // with jdbc driver try { Connection con = getDataSource().getConnection(); if (con != null) { DatabaseMetaData dbmd = con.getMetaData(); setDbConnectionAcquired(true); if (dbmd != null) { setDriverName(dbmd.getDriverName().trim().toLowerCase()); // record the URL to the DB setDbUrl(dbmd.getURL().trim()); isOracle = (getDriverName() != null && getDriverName().indexOf(ORACLE_STR) >= 0) ? true : false; LOG.info(getBeanName() + ":Is Oracle JDBC Driver = " + isOracle); LOG.info(getBeanName() + ":JDBC Driver name = " + getDriverName()); LOG.info(getBeanName() + ":JDBC Driver version = " + dbmd.getDriverVersion().trim()); LOG.info(getBeanName() + ":JDBC Driver product name = " + dbmd.getDatabaseProductName().trim()); LOG.info(getBeanName() + ":JDBC URL = " + getDbUrl()); LOG.info(getBeanName() + ":JDBC Driver database product version = " + dbmd.getDatabaseProductVersion().trim()); con.close(); } else { LOG.info(getBeanName() + ": Unable to get JDBC driver meta data"); } } else { LOG.info(getBeanName() + ": Unable to get JDBC connection"); } } catch (SQLException exc) { LOG.error(getBeanName() + ": got this exception when trying to " + "get driver meta data: " + exc.toString()); LOG.error(getBeanName() + ": exception stack trace follows:"); dumpStackTrace(exc.getStackTrace()); LOG.error(getBeanName() + ": Caused by " + exc.getCause().toString()); LOG.error(getBeanName() + ": causing exception stack trace follows:"); dumpStackTrace(exc.getCause().getStackTrace()); } // bean must be assigned a JDBC DataSource if (getDataSource() == null) { throw new Exception( getBeanName() + ".afterPropertiesSet: this bean has not been " + "assigned a JDBC DataSource"); } // do some validation if (getSqls4Get() == null) { throw new Exception("The PusherBean must be assigned at least one SQL statement"); } // create and validate the injected SQL statements sqlStmnts4Get = new ArrayList<SqlStmnt>(); for (String sql : getSqls4Get()) { // get the frequency settings Map<String, Long> map = Utils.parseTimeInterval(sql); sql = Utils.stripTimeInterval(sql); sql = Utils.stripCall(sql); SqlStmnt stmt = getSQLStmnt(this, sql, getJdbcTemplate()); if (stmt.isEqual(sqlStmnts4Get)) { throw new Exception("Injected SQL statements for GET are not distinct"); } // set the frequency stmt.setIntervalTime(map.get(TIME_INTERVAL)); if (map.get(TIME_INTERVAL_MAX) != null) { stmt.setIntervalMax(map.get(TIME_INTERVAL_MAX)); } if (map.get(TIME_INTERVAL_STEP) != null) { stmt.setIntervalStep(map.get(TIME_INTERVAL_STEP)); } sqlStmnts4Get.add(stmt); } if (LOG.isDebugEnabled()) { for (SqlStmnt sqlstmnt : sqlStmnts4Get) { LOG.debug(getBeanName() + ": SQL for GET = " + sqlstmnt.getOriginal()); LOG.debug(getBeanName() + ": Parameterized SQL for GET = " + sqlstmnt.getPrepared()); } } if (getHazelcastInstance() != null) { LOG.debug(getBeanName() + ": My Hazelcast Instance Name = " + getHazelcastInstance().getName()); ; } }
From source file:com.nextep.designer.dbgm.services.impl.DataService.java
private void safeClose(ResultSet rset, Statement stmt, Connection conn, boolean displayDisconnectMsg) { if (rset != null) { try {// www.j a va 2 s. co m rset.close(); } catch (SQLException e) { LOGGER.error(DBGMMessages.getString("service.data.closeResultSetFailed"), e); //$NON-NLS-1$ } } if (stmt != null) { try { stmt.close(); } catch (SQLException e) { LOGGER.error(DBGMMessages.getString("service.data.closeStatementFailed"), e); //$NON-NLS-1$ } } if (conn != null) { try { if (displayDisconnectMsg) { final DatabaseMetaData md = conn.getMetaData(); LOGGER.info("Disconnecting from " + md.getURL()); } conn.close(); } catch (SQLException e) { LOGGER.error(DBGMMessages.getString("service.data.closeConnectionFailed"), e); //$NON-NLS-1$ } } }
From source file:com.atlassian.jira.startup.JiraSystemInfo.java
/** * Obtains database configuration information. This should be called after the database has been checked for sanity * and hence we can safely do some entityengine.xml and database connection test. But this is before the database is * auto-created and hence the support team can get valuable configuration information before a real DB cockup is * encountered./*from w w w.j ava 2 s . c o m*/ */ public void obtainDatabaseConfigurationInfo() { logMsg.outputHeader("Database Configuration"); final URL entityEngineURL = ClassLoaderUtils.getResource("entityengine.xml", getClass()); logMsg.outputProperty("Loading entityengine.xml from", entityEngineURL.toString()); final DatasourceInfo datasourceInfo = connectionFactory.getDatasourceInfo(); if (datasourceInfo != null) { logMsg.outputProperty("Entity model field type name", datasourceInfo.getFieldTypeName()); logMsg.outputProperty("Entity model schema name", datasourceInfo.getSchemaName()); } Connection connection = null; try { connection = connectionFactory.getConnection(); final DatabaseMetaData metaData = connection.getMetaData(); final SystemInfoUtils jiraSysInfo = new SystemInfoUtilsImpl(); logMsg.outputProperty("Database Version", metaData.getDatabaseProductName() + " - " + metaData.getDatabaseProductVersion()); logMsg.outputProperty("Database Driver", metaData.getDriverName() + " - " + metaData.getDriverVersion()); logMsg.outputProperty("Database URL", maskURL(metaData.getURL())); logMsg.outputProperty(jiraSysInfo.getDbDescriptorLabel(), jiraSysInfo.getDbDescriptorValue()); } catch (final SQLException e) { // dont worry about this exception here. Code later one will barf on the same problem and do more appropriate actions. // We are just trying to get startup information for support purposes for now. log.debug(e); } finally { silentlyClose(connection); } }
From source file:net.sf.jasperreports.engine.query.JRJdbcQueryExecuter.java
/** * /*w ww . ja v a2 s. c om*/ */ public JRJdbcQueryExecuter(JasperReportsContext jasperReportsContext, JRDataset dataset, Map<String, ? extends JRValueParameter> parameters) { super(jasperReportsContext, dataset, parameters); connection = (Connection) getParameterValue(JRParameter.REPORT_CONNECTION); if (connection == null) { if (log.isWarnEnabled()) { log.warn("The supplied java.sql.Connection object is null."); } } else if (log.isDebugEnabled()) { try { DatabaseMetaData metaData = connection.getMetaData(); log.debug("DB is " + metaData.getDatabaseProductName() + " version " + metaData.getDatabaseProductVersion() + " (" + metaData.getDatabaseMajorVersion() + "/" + metaData.getDatabaseMinorVersion() + ")"); log.debug("driver is " + metaData.getDriverName() + " version " + metaData.getDriverVersion() + " (" + metaData.getDriverMajorVersion() + "/" + metaData.getDriverMinorVersion() + ")"); log.debug("jdbc " + metaData.getJDBCMajorVersion() + "/" + metaData.getJDBCMinorVersion()); log.debug("connection URL is " + metaData.getURL()); } catch (SQLException e) { log.debug("failed to read connection metadata", e); } } isCachedRowSet = getBooleanParameterOrProperty(JRJdbcQueryExecuterFactory.PROPERTY_CACHED_ROWSET, false); setTimeZone(); registerFunctions(); parseQuery(); }
From source file:nl.b3p.gis.writers.B3pOgcSqlWriter.java
private void createTable(DatabaseMetaData dbmd, String tablename, FeatureSchema fs, String geomColumn, boolean attributeNamesToLowerCase, String srid, Geometry aGeom, boolean sameGeomType, int dimension) throws SQLException, Exception { //check if the product is supported if (SUPPORTED_DIALECTS.contains(dbmd.getDatabaseProductName())) { StringBuffer sb = new StringBuffer(); sb.append("CREATE TABLE \""); sb.append(tablename);//w ww .java2 s . co m sb.append("\"("); boolean firstColumn = true; boolean geomColumnFound = false; //create a create table script without the geometry column. for (int i = 0; i < fs.getAttributeCount(); i++) { AttributeType at = fs.getAttributeType(i); if (at.equals(AttributeType.GEOMETRY)) { geomColumnFound = true; if (geomColumn == null) { if (attributeNamesToLowerCase) { geomColumn = fs.getAttributeName(i).toLowerCase(); } else { geomColumn = fs.getAttributeName(i); } } } else { if (!firstColumn) { sb.append(", "); } firstColumn = false; sb.append("\""); if (attributeNamesToLowerCase) { sb.append(fs.getAttributeName(i).toLowerCase()); } else { sb.append(fs.getAttributeName(i)); } sb.append("\" "); if (at.equals(AttributeType.DATE)) { sb.append("date"); } else if (at.equals(AttributeType.DOUBLE)) { sb.append("double precision"); } else if (at.equals(AttributeType.INTEGER)) { sb.append("bigint"); } else { sb.append("varchar(255)"); } } } sb.append(")WITH OIDS"); StringBuffer sbg = null; //if there is a geomColum needed create the create script. if (geomColumnFound) { //if it is a postgres/postgis db if (dbmd.getDatabaseProductName().equalsIgnoreCase(SqlMetaDataUtils.PRODUCT_POSTGRES)) { // get the database name. String s = dbmd.getURL(); String url = dbmd.getURL(); String db = url.split("/")[url.split("/").length - 1]; //create the script for the addGeometryColumn function sbg = new StringBuffer(); sbg.append("select addGeometryColumn(\'"); sbg.append("public"); sbg.append("\', \'"); sbg.append(tablename); sbg.append("\', \'"); sbg.append(geomColumn); sbg.append("\', "); //if the srid is given as param use it. Otherwise try to get the srid out of the geometry or use -1 as srid if (srid != null) { sbg.append(srid); } else if (aGeom != null) { if (aGeom.getSRID() >= 0) { sbg.append(aGeom.getSRID()); } } else { sbg.append(-1); } sbg.append(", \'"); //if not all geometries are of the same type create a global geometry column if (!sameGeomType || aGeom == null) { sbg.append(POSTGRES_GLOBALGEOMETRY); } else { sbg.append(aGeom.getGeometryType().toUpperCase()); } sbg.append("\', "); //if the dimension is given use it, otherwise try to get it out of the Geometry of use 2 if (dimension > 0) { sbg.append(dimension); } else { if (aGeom.getDimension() > 1) { sbg.append(aGeom.getDimension()); } else { sbg.append("2"); } } sbg.append(")"); } } //execute the create table script. PreparedStatement statement = null; if (sbg.toString() != null) { sb.append(";"); sb.append(sbg.toString()); } statement = connection.prepareStatement(sb.toString()); statement.execute(); statement.close(); } else { log.error("CREATE TABLE not supported for " + dbmd.getDatabaseProductName()); throw new Exception("CREATE TABLE not supported for " + dbmd.getDatabaseProductName()); } }
From source file:nl.nn.adapterframework.extensions.esb.EsbUtils.java
public static PoolingDataSource getPoolingDataSource(JdbcTransactionalStorage errorStorage) { String dsUrl = null;/*from w ww.ja va 2 s . com*/ String dsUserName = null; String dsPassword = null; java.sql.Connection errorStorageConnection = null; try { errorStorageConnection = errorStorage.getConnection(); } catch (JdbcException e) { log.warn("error occured during getting errorStorage connection: " + e.getMessage()); } if (errorStorageConnection == null) { log.warn("could not get errorStorage connection"); } else { DatabaseMetaData md; try { md = errorStorageConnection.getMetaData(); dsUrl = md.getURL(); // dsUserName = md.getUserName(); // dsPassword = md.getPassword(); } catch (SQLException e) { log.warn("error occured during getting errorStorage metadata: " + e.getMessage()); } if (dsUrl == null) { log.warn("could not get errorStorage url"); } else { // onderstaande is nodig omdat het niet mogelijk is het // password op te vragen uit het DatabaseMetaData object of // uit het Connection object String confResString = null; try { confResString = Misc.getConfigurationResources(); if (confResString != null) { confResString = XmlUtils.removeNamespaces(confResString); } } catch (IOException e) { log.warn("error getting configuration resources: " + e.getMessage()); } String authDataAlias = null; if (confResString != null) { String dsName = null; try { dsName = errorStorage.getDataSourceNameToUse(); } catch (JdbcException e) { log.warn("error getting datasource name to use: " + e.getMessage()); } if (dsName != null) { String xpathExpression = "XMI/JDBCProvider/factories[@jndiName='" + dsName + "']/@authDataAlias"; try { Transformer t = XmlUtils.createXPathEvaluator(xpathExpression); authDataAlias = XmlUtils.transformXml(t, confResString); } catch (Exception e) { log.warn("error getting datasource authDataAlias: " + e.getMessage()); } } } if (StringUtils.isEmpty(authDataAlias)) { log.warn("could not get errorStorage authDataAlias"); } else { CredentialFactory cf = new CredentialFactory(authDataAlias, null, null); dsUserName = cf.getUsername(); dsPassword = cf.getPassword(); return setupJdbcDataSource(dsUrl, dsUserName, dsPassword); } } } return null; }
From source file:nl.nn.adapterframework.jdbc.JdbcFacade.java
public String getDatasourceInfo() throws JdbcException { String dsinfo = null;//from w ww. j a v a 2 s .co 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:nl.nn.adapterframework.jdbc.JdbcFacade.java
/** * Returns the name and location of the database that this objects operates on. * //from w w w . j ava 2 s.c o m * @see nl.nn.adapterframework.core.HasPhysicalDestination#getPhysicalDestinationName() */ public String getPhysicalDestinationName() { String result = "unknown"; try { Connection connection = getConnection(); DatabaseMetaData metadata = connection.getMetaData(); result = metadata.getURL(); String catalog = null; catalog = connection.getCatalog(); result += catalog != null ? ("/" + catalog) : ""; connection.close(); } catch (Exception e) { log.warn(getLogPrefix() + "exception retrieving PhysicalDestinationName", e); } return result; }
From source file:org.ambraproject.action.debug.DebugInfoAction.java
@Override public String execute() throws Exception { if (!checkAccess()) { return ERROR; }/*from w ww . j a va2 s. co m*/ timestamp = new Date(System.currentTimeMillis()); Runtime rt = Runtime.getRuntime(); jvmFreeMemory = (double) rt.freeMemory() / (1024.0 * 1024.0); jvmTotalMemory = (double) rt.totalMemory() / (1024.0 * 1024.0); jvmMaxMemory = (double) rt.maxMemory() / (1024.0 * 1024.0); HttpServletRequest req = ServletActionContext.getRequest(); tomcatVersion = ServletActionContext.getServletContext().getServerInfo(); sessionCount = SessionCounter.getSessionCount(); host = req.getLocalName(); hostIp = req.getLocalAddr(); buildInfo = generateBuildInfo(); // The easiest way I found to get the URL and username for the DB. // It's not that easy and involves opening a connection... Context initialContext = new InitialContext(); Context context = (Context) initialContext.lookup("java:comp/env"); DataSource ds = (DataSource) context.lookup("jdbc/AmbraDS"); Connection conn = null; try { conn = ds.getConnection(); DatabaseMetaData metadata = conn.getMetaData(); dbUrl = metadata.getURL(); dbUser = metadata.getUserName(); } finally { conn.close(); } Configuration config = ConfigurationStore.getInstance().getConfiguration(); FileStoreService filestoreService = (FileStoreService) context.lookup("ambra/FileStore"); filestore = filestoreService.toString(); solrUrl = (String) config.getProperty("ambra.services.search.server.url"); configuration = dumpConfig(config); cmdLine = IOUtils.toString(new FileInputStream("/proc/self/cmdline")); return SUCCESS; }