List of usage examples for java.sql Connection getClass
@HotSpotIntrinsicCandidate public final native Class<?> getClass();
From source file:com.paladin.sys.db.DBManager.java
public static final Connection getConnection() { Connection conn = conns.get(); try {// ww w . j ava 2s . c o m if (conn == null || conn.isClosed()) { conn = dataSource.getConnection(); conns.set(conn); } } catch (Exception e) { e.printStackTrace(); } return (show_sql && !Proxy.isProxyClass(conn.getClass())) ? new DebugConnection(conn).getConnection() : conn; }
From source file:co.nubetech.apache.hadoop.OracleDBRecordReader.java
/** * Set session time zone//from ww w . java2 s .c o m * * @param conf * The current configuration. We read the * 'oracle.sessionTimeZone' property from here. * @param conn * The connection to alter the timezone properties of. */ public static void setSessionTimeZone(Configuration conf, Connection conn) throws SQLException { // need to use reflection to call the method setSessionTimeZone on // the OracleConnection class because oracle specific java libraries are // not accessible in this context. Method method; try { method = conn.getClass().getMethod("setSessionTimeZone", new Class[] { String.class }); } catch (Exception ex) { LOG.error("Could not find method setSessionTimeZone in " + conn.getClass().getName(), ex); // rethrow SQLException throw new SQLException(ex); } // Need to set the time zone in order for Java // to correctly access the column "TIMESTAMP WITH LOCAL TIME ZONE". // We can't easily get the correct Oracle-specific timezone string // from Java; just let the user set the timezone in a property. String clientTimeZone = conf.get(SESSION_TIMEZONE_KEY, "GMT"); try { method.setAccessible(true); method.invoke(conn, clientTimeZone); LOG.info("Time zone has been set to " + clientTimeZone); } catch (Exception ex) { LOG.warn("Time zone " + clientTimeZone + " could not be set on Oracle database."); LOG.warn("Setting default time zone: GMT"); try { // "GMT" timezone is guaranteed to exist. method.invoke(conn, "GMT"); } catch (Exception ex2) { LOG.error("Could not set time zone for oracle connection", ex2); // rethrow SQLException throw new SQLException(ex); } } }
From source file:com.jolbox.bonecp.spring.BoneCPNativeJdbcExtractor.java
/** * @see org.springframework.jdbc.support.nativejdbc.NativeJdbcExtractorAdapter#doGetNativeConnection(java.sql.Connection) *//*from w w w. j a va2s.c om*/ @Override protected Connection doGetNativeConnection(Connection conn) throws SQLException { if (this.connectionHandleClass.isAssignableFrom(conn.getClass())) { return (Connection) ReflectionUtils.invokeJdbcMethod(this.getInternalConnectionMethod, conn); } return conn; }
From source file:com.p6spy.engine.spy.MultipleDataSourceTest.java
private void validateNotSpyEnabled(DataSource ds) throws SQLException { assertNotNull("JNDI data source not found", ds); // get the connection Connection con = ds.getConnection(); if (ProxyFactory.isProxy(con.getClass())) { assertTrue("p6spy proxy is enabled!", !(Proxy.getInvocationHandler(con) instanceof P6LogConnectionInvocationHandler)); }/* w w w . j a v a 2 s . c o m*/ if (con.getMetaData().getDatabaseProductName().contains("HSQL")) { con.createStatement().execute("set database sql syntax ora true"); } con.createStatement().execute("select current_date from dual"); assertNull(((P6TestLogger) P6LogQuery.getLogger()).getLastEntry()); }
From source file:com.yoncabt.ebr.jdbcbridge.pool.DataSource.java
private void fillHint(Connection connection, String client, String module, String action) { if (connection.getClass().getName().startsWith("oracle")) { //dier veritabanlar iin bakmak lazm try {/*ww w. j av a 2s. co m*/ CallableStatement call; call = connection.prepareCall("call dbms_application_info.set_client_info(?)"); call.setString(1, client); call.execute(); call = connection .prepareCall("call dbms_application_info.set_module(module_name => ?, action_name => ?)"); call.setString(1, module); call.setString(2, action); call.execute(); } catch (SQLException ex) { logManager.error(ex); } } }
From source file:com.p6spy.engine.spy.MultipleDataSourceTest.java
private void validateSpyEnabled(DataSource ds) throws SQLException { assertNotNull("JNDI data source not found", ds); // get the connection Connection con = ds.getConnection(); // verify that the connection class is a proxy assertTrue("Connection is not a proxy", ProxyFactory.isProxy(con.getClass())); if (con.getMetaData().getDatabaseProductName().contains("HSQL")) { con.createStatement().execute("set database sql syntax ora true"); }/*from w w w . ja va 2 s . c om*/ con.createStatement().execute("select current_date from dual"); assertTrue(((P6TestLogger) P6LogQuery.getLogger()).getLastEntry().indexOf("select current_date") != -1); }
From source file:com.espertech.esper.epl.db.DatabasePollingViewableFactory.java
/** * Creates the viewable for polling via database SQL query. * @param streamNumber is the stream number of the view * @param databaseStreamSpec provides the SQL statement, database name and additional info * @param databaseConfigService for getting database connection and settings * @param eventAdapterService for generating event beans from database information * @param epStatementAgentInstanceHandle is the statements-own handle for use in registering callbacks with services * @param columnTypeConversionHook hook for statement-specific column conversion * @param outputRowConversionHook hook for statement-specific row conversion * @param enableJDBCLogging indicator to enable JDBC logging * @return viewable providing poll functionality * @throws ExprValidationException if the validation failed */// ww w. ja v a2 s.c om public static HistoricalEventViewable createDBStatementView(String statementId, int streamNumber, DBStatementStreamSpec databaseStreamSpec, DatabaseConfigService databaseConfigService, EventAdapterService eventAdapterService, EPStatementAgentInstanceHandle epStatementAgentInstanceHandle, SQLColumnTypeConversion columnTypeConversionHook, SQLOutputRowConversion outputRowConversionHook, boolean enableJDBCLogging) throws ExprValidationException { // Parse the SQL for placeholders and text fragments List<PlaceholderParser.Fragment> sqlFragments; try { sqlFragments = PlaceholderParser.parsePlaceholder(databaseStreamSpec.getSqlWithSubsParams()); } catch (PlaceholderParseException ex) { String text = "Error parsing SQL"; throw new ExprValidationException(text + ", reason: " + ex.getMessage()); } // Assemble a PreparedStatement and parameter list String preparedStatementText = createPreparedStatement(sqlFragments); SQLParameterDesc parameterDesc = getParameters(sqlFragments); if (log.isDebugEnabled()) { log.debug(".createDBEventStream preparedStatementText=" + preparedStatementText + " parameterDesc=" + parameterDesc); } // Get a database connection String databaseName = databaseStreamSpec.getDatabaseName(); DatabaseConnectionFactory databaseConnectionFactory; ColumnSettings metadataSetting; try { databaseConnectionFactory = databaseConfigService.getConnectionFactory(databaseName); metadataSetting = databaseConfigService.getQuerySetting(databaseName); } catch (DatabaseConfigException ex) { String text = "Error connecting to database '" + databaseName + '\''; log.error(text, ex); throw new ExprValidationException(text + ", reason: " + ex.getMessage()); } Connection connection; try { connection = databaseConnectionFactory.getConnection(); } catch (DatabaseConfigException ex) { String text = "Error connecting to database '" + databaseName + '\''; log.error(text, ex); throw new ExprValidationException(text + ", reason: " + ex.getMessage()); } // On default setting, if we detect Oracle in the connection then don't query metadata from prepared statement ConfigurationDBRef.MetadataOriginEnum metaOriginPolicy = metadataSetting.getMetadataRetrievalEnum(); if (metaOriginPolicy == ConfigurationDBRef.MetadataOriginEnum.DEFAULT) { String connectionClass = connection.getClass().getName(); if ((connectionClass.toLowerCase().contains("oracle") || (connectionClass.toLowerCase().contains("timesten")))) { // switch to sample statement if we are dealing with an oracle connection metaOriginPolicy = ConfigurationDBRef.MetadataOriginEnum.SAMPLE; } } QueryMetaData queryMetaData; try { if ((metaOriginPolicy == ConfigurationDBRef.MetadataOriginEnum.METADATA) || (metaOriginPolicy == ConfigurationDBRef.MetadataOriginEnum.DEFAULT)) { queryMetaData = getPreparedStmtMetadata(connection, parameterDesc.getParameters(), preparedStatementText, metadataSetting); } else { String sampleSQL; boolean isGivenMetadataSQL = true; if (databaseStreamSpec.getMetadataSQL() != null) { sampleSQL = databaseStreamSpec.getMetadataSQL(); isGivenMetadataSQL = true; if (log.isInfoEnabled()) { log.info(".createDBStatementView Using provided sample SQL '" + sampleSQL + "'"); } } else { // Create the sample SQL by replacing placeholders with null and // SAMPLE_WHERECLAUSE_PLACEHOLDER with a "where 1=0" clause sampleSQL = createSamplePlaceholderStatement(sqlFragments); if (log.isInfoEnabled()) { log.info(".createDBStatementView Using un-lexed sample SQL '" + sampleSQL + "'"); } // If there is no SAMPLE_WHERECLAUSE_PLACEHOLDER, lexical analyse the SQL // adding a "where 1=0" clause. if (parameterDesc.getBuiltinIdentifiers().length != 1) { sampleSQL = lexSampleSQL(sampleSQL); if (log.isInfoEnabled()) { log.info(".createDBStatementView Using lexed sample SQL '" + sampleSQL + "'"); } } } // finally get the metadata by firing the sample SQL queryMetaData = getExampleQueryMetaData(connection, parameterDesc.getParameters(), sampleSQL, metadataSetting, isGivenMetadataSQL); } } catch (ExprValidationException ex) { try { connection.close(); } catch (SQLException e) { // don't handle } throw ex; } // Close connection try { connection.close(); } catch (SQLException e) { String text = "Error closing connection"; log.error(text, e); throw new ExprValidationException(text + ", reason: " + e.getMessage()); } // Create event type // Construct an event type from SQL query result metadata Map<String, Object> eventTypeFields = new HashMap<String, Object>(); int columnNum = 1; for (Map.Entry<String, DBOutputTypeDesc> entry : queryMetaData.getOutputParameters().entrySet()) { String name = entry.getKey(); DBOutputTypeDesc dbOutputDesc = entry.getValue(); Class clazz; if (dbOutputDesc.getOptionalBinding() != null) { clazz = dbOutputDesc.getOptionalBinding().getType(); } else { clazz = SQLTypeMapUtil.sqlTypeToClass(dbOutputDesc.getSqlType(), dbOutputDesc.getClassName()); } if (columnTypeConversionHook != null) { Class newValue = columnTypeConversionHook.getColumnType(new SQLColumnTypeContext( databaseStreamSpec.getDatabaseName(), databaseStreamSpec.getSqlWithSubsParams(), name, clazz, dbOutputDesc.getSqlType(), columnNum)); if (newValue != null) { clazz = newValue; } } eventTypeFields.put(name, clazz); columnNum++; } EventType eventType; if (outputRowConversionHook == null) { String outputEventType = statementId + "_dbpoll_" + streamNumber; eventType = eventAdapterService.createAnonymousMapType(outputEventType, eventTypeFields); } else { Class carrierClass = outputRowConversionHook .getOutputRowType(new SQLOutputRowTypeContext(databaseStreamSpec.getDatabaseName(), databaseStreamSpec.getSqlWithSubsParams(), eventTypeFields)); if (carrierClass == null) { throw new ExprValidationException("Output row conversion hook returned no type"); } eventType = eventAdapterService.addBeanType(carrierClass.getName(), carrierClass, false, false, false); } // Get a proper connection and data cache ConnectionCache connectionCache; DataCache dataCache; try { connectionCache = databaseConfigService.getConnectionCache(databaseName, preparedStatementText); dataCache = databaseConfigService.getDataCache(databaseName, epStatementAgentInstanceHandle); } catch (DatabaseConfigException e) { String text = "Error obtaining cache configuration"; log.error(text, e); throw new ExprValidationException(text + ", reason: " + e.getMessage()); } PollExecStrategyDBQuery dbPollStrategy = new PollExecStrategyDBQuery(eventAdapterService, eventType, connectionCache, preparedStatementText, queryMetaData.getOutputParameters(), columnTypeConversionHook, outputRowConversionHook, enableJDBCLogging); return new DatabasePollingViewable(streamNumber, queryMetaData.getInputParameters(), dbPollStrategy, dataCache, eventType); }
From source file:com.teradata.benchto.driver.macro.query.QueryMacroExecutionDriver.java
private void setSessionForPresto(Connection connection, String sqlStatement) { PrestoConnection prestoConnection;/*from ww w.jav a2 s . c om*/ try { prestoConnection = connection.unwrap(PrestoConnection.class); } catch (SQLException e) { LOGGER.error(e.getMessage()); throw new UnsupportedOperationException( format("SET SESSION for non PrestoConnection [%s] is not supported", connection.getClass())); } String[] keyValue = extractKeyValue(sqlStatement); prestoConnection.setSessionProperty(keyValue[0].trim(), keyValue[1].trim()); }
From source file:com.jaspersoft.jasperserver.api.engine.jasperreports.service.impl.TibcoDriverManagerImpl.java
private boolean unlockInnerConnection(Connection originalConnection) throws SQLException { if (originalConnection == null) return false; printLog("ORIGINAL CONNECTION CLASS - " + originalConnection.getClass().toString()); // printAvailableMethods(originalConnection); try {//from w ww . j av a2 s.c o m if (originalConnection instanceof DelegatingConnection) { printLog("Get innermost connection..."); Connection innerConn = ((DelegatingConnection) originalConnection).getInnermostDelegate(); if (innerConn != null) return unlockInnerConnection(innerConn); } else if ((Boolean) isTibcoConnection().invoke(null, originalConnection)) { printLog("TibcoDriverManagerImpl Tibco connection..." + originalConnection.getClass().toString()); boolean isSuccessful = unlockTibcoConnection(originalConnection); printLog("UNLOCK successful? " + isSuccessful); return isSuccessful; } else { Connection innerConn = (Connection) getInnerConnectionFromAppServerClass().invoke(null, originalConnection, JndiJdbcReportDataSourceServiceFactory.getJndiAppServerConnectionFunctionMap()); if (innerConn != null) return unlockInnerConnection(innerConn); printLog("Fail to find Tibco Connection"); } } catch (SQLFeatureNotSupportedException sqlFeatureNotSupportedEx) { // non-tibco drivers } catch (SQLException ex) { printLog("Fail to unlock data source. Connection class = " + originalConnection.getClass().toString(), ex); } catch (Throwable throwable) { printLog("Fail to unlock data source.", throwable); } return false; }
From source file:net.big_oh.common.jdbc.JdbcDriverProxy.java
public Connection connect(String url, Properties connectionProperties) throws SQLException { Driver delegateDriver = lookupDelegateDriver(url); if (delegateDriver == null) { // return null per the API guidelines return null; }//from w ww .j av a 2 s. c o m url = stripJdbcObserverPrefixFromUrl(url); ConnectionInstantiationEvent connectionInstantiationEvent = new ConnectionInstantiationEvent(this, delegateDriver, url, connectionProperties); for (JDBCEventListener listener : listeners) { try { listener.connectionRequested(connectionInstantiationEvent); } catch (RuntimeException rte) { logger.error(rte); } } Connection newConnection = delegateDriver.connect(url, connectionProperties); if (newConnection == null) { throw new SQLException("Failed to connect to url '" + url + "' using delegate driver " + delegateDriver.getClass().getName()); } // Create a proxy for the returned connection boolean newConnectionInterfacesContainsConnection = Arrays.asList(newConnection.getClass().getInterfaces()) .contains(Connection.class); Class<?>[] interfaces = new Class<?>[(newConnection.getClass().getInterfaces().length + ((newConnectionInterfacesContainsConnection) ? 0 : 1))]; System.arraycopy(newConnection.getClass().getInterfaces(), 0, interfaces, 0, newConnection.getClass().getInterfaces().length); if (!newConnectionInterfacesContainsConnection) { interfaces[newConnection.getClass().getInterfaces().length] = Connection.class; } Connection connectionProxy = (Connection) Proxy.newProxyInstance(this.getClass().getClassLoader(), interfaces, new JdbcObserverProxyConnectionInvocationHandler(newConnection, listeners)); for (JDBCEventListener listener : listeners) { try { listener.connectionInstantiated(connectionInstantiationEvent, connectionProxy); } catch (RuntimeException rte) { logger.error(rte); } } return connectionProxy; }