Example usage for java.sql Connection getClass

List of usage examples for java.sql Connection getClass

Introduction

In this page you can find the example usage for java.sql Connection getClass.

Prototype

@HotSpotIntrinsicCandidate
public final native Class<?> getClass();

Source Link

Document

Returns the runtime class of this Object .

Usage

From source file:com.cloudera.sqoop.manager.OracleManager.java

/**
 * Set session time zone.//ww  w . j  a  v a2  s  .c  o  m
 * @param conn      Connection object
 * @throws          SQLException instance
 */
private void setSessionTimeZone(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".  The user may have set this in
    // the configuration as 'oracle.sessionTimeZone'.
    String clientTimeZoneStr = options.getConf().get(ORACLE_TIMEZONE_KEY, "GMT");
    try {
        method.setAccessible(true);
        method.invoke(conn, clientTimeZoneStr);
        LOG.info("Time zone has been set to " + clientTimeZoneStr);
    } catch (Exception ex) {
        LOG.warn("Time zone " + clientTimeZoneStr + " could not be set on Oracle database.");
        LOG.info("Setting default time zone: GMT");
        try {
            // Per the documentation at:
            // http://download-west.oracle.com/docs/cd/B19306_01
            //     /server.102/b14225/applocaledata.htm#i637736
            // The "GMT" timezone is guaranteed to exist in the available timezone
            // regions, whereas others (e.g., "UTC") are not.
            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.nextep.datadesigner.vcs.services.VCSFiles.java

/**
 * Write the specified file to the given repository file with Oracle-specific Blob support.
 * /* www.  ja v a  2s .co  m*/
 * @param conn Oracle connection
 * @param file repository file which must have been created
 * @param localFile local file to dump into the repository file
 * @throws SQLException when any database connection problems occurs
 */
private void writeOracleBlob(Connection conn, IRepositoryFile file, File localFile) throws SQLException {
    PreparedStatement stmt = null;
    long size = 0;

    try {
        /*
         * Columns names in the SET clause cannot be qualified with an alias name because it
         * would fail in Postgres.
         */
        stmt = conn.prepareStatement("UPDATE rep_files rf " //$NON-NLS-1$
                + "  SET file_content = ? " //$NON-NLS-1$
                + "    , filesize = ? " //$NON-NLS-1$
                + "WHERE rf.file_id = ? "); //$NON-NLS-1$

        OutputStream os = null;
        FileInputStream is = null;
        BLOB tempBlob = null;

        try {
            // Get the oracle connection class for checking
            Class<?> oracleConnectionClass = Class.forName("oracle.jdbc.OracleConnection"); //$NON-NLS-1$

            // Make sure connection object is right type
            if (!oracleConnectionClass.isAssignableFrom(conn.getClass())) {
                throw new HibernateException(VCSMessages.getString("files.invalidOracleConnection") //$NON-NLS-1$
                        + VCSMessages.getString("files.invalidOracleConnection.2") //$NON-NLS-1$
                        + conn.getClass().getName());
            }

            // Create our temp BLOB
            tempBlob = BLOB.createTemporary(conn, true, BLOB.DURATION_SESSION);
            tempBlob.open(BLOB.MODE_READWRITE);
            os = tempBlob.getBinaryOutputStream();
            is = new FileInputStream(localFile);

            // Large 10K buffer for efficient read
            byte[] buffer = new byte[10240];
            int bytesRead = 0;

            while ((bytesRead = is.read(buffer)) >= 0) {
                os.write(buffer, 0, bytesRead);
                size += bytesRead;
            }
        } catch (ClassNotFoundException cnfe) {
            // could not find the class with reflection
            throw new ErrorException(VCSMessages.getString("files.classUnresolved") //$NON-NLS-1$
                    + cnfe.getMessage());
        } catch (FileNotFoundException fnfe) {
            throw new ErrorException(VCSMessages.getString("files.fileUnresolved")); //$NON-NLS-1$
        } catch (IOException ioe) {
            throw new ErrorException(VCSMessages.getString("files.readProblem"), ioe); //$NON-NLS-1$
        } finally {
            safeClose(os);
            safeClose(is);
            if (tempBlob != null) {
                tempBlob.close();
            }
        }
        stmt.setBlob(1, tempBlob);
        stmt.setLong(2, size);
        stmt.setLong(3, file.getUID().rawId());
        stmt.execute();
    } finally {
        if (stmt != null) {
            stmt.close();
        }
        file.setFileSizeKB(size / 1024);
    }
}

From source file:org.apache.jackrabbit.core.util.db.ConnectionFactory.java

/**
 * Needed for pre-10R2 Oracle blob support....:(
 *
 * This method actually assumes that we are using commons DBCP 1.2.2.
 *
 * @param con the commons-DBCP {@code DelegatingConnection} to unwrap
 * @return the unwrapped connection/* w  ww. java 2 s .  c om*/
 */
public static Connection unwrap(Connection con) throws SQLException {
    if (con instanceof DelegatingConnection) {
        return ((DelegatingConnection) con).getInnermostDelegate();
    } else {
        throw new SQLException("failed to unwrap connection of class " + con.getClass().getName()
                + ", expected it to be a " + DelegatingConnection.class.getName());
    }
}

From source file:org.apache.jackrabbit.core.util.db.Oracle10R1ConnectionHelper.java

/**
 * Retrieve the <code>oracle.sql.BLOB</code> class via reflection, and initialize the values for the
 * <code>DURATION_SESSION</code> and <code>MODE_READWRITE</code> constants defined there.
 * /*from  ww w .jav a2  s.  co m*/
 * @see oracle.sql.BLOB#DURATION_SESSION
 * @see oracle.sql.BLOB#MODE_READWRITE
 */
@Override
public void init() throws Exception {
    super.init();
    // initialize oracle.sql.BLOB class & constants

    // use the Connection object for using the exact same
    // class loader that the Oracle driver was loaded with
    Connection con = null;
    try {
        con = dataSource.getConnection();
        blobClass = con.getClass().getClassLoader().loadClass("oracle.sql.BLOB");
        durationSessionConstant = new Integer(blobClass.getField("DURATION_SESSION").getInt(null));
        modeReadWriteConstant = new Integer(blobClass.getField("MODE_READWRITE").getInt(null));
    } finally {
        if (con != null) {
            DbUtility.close(con, null, null);
        }
    }
}

From source file:org.apache.openjpa.jdbc.sql.PostgresDictionary.java

/**
 * Get the native PostgreSQL connection from the given connection.
 * Various attempts of unwrapping are being performed.
 *//*from www. ja  va  2  s. c  om*/
protected PGConnection getPGConnection(DelegatingConnection conn) {
    Connection innerConn = conn.getInnermostDelegate();
    if (innerConn instanceof PGConnection) {
        return (PGConnection) innerConn;
    }
    if (innerConn.getClass().getName().startsWith("org.apache.commons.dbcp")) {
        return (PGConnection) getDbcpDelegate(innerConn);
    }
    return (PGConnection) unwrapConnection(conn, PGConnection.class);
}

From source file:org.apache.openjpa.jdbc.sql.PostgresDictionary.java

/**
 * Get the delegated connection from the given DBCP connection.
 * //from  ww w.  j  a va2s .c  om
 * @param conn must be a DBCP connection
 * @return connection the DBCP connection delegates to
 */
protected Connection getDbcpDelegate(Connection conn) {
    Connection delegate = null;
    try {
        if (dbcpGetDelegate == null) {
            Class<?> dbcpConnectionClass = Class.forName("org.apache.commons.dbcp.DelegatingConnection", true,
                    AccessController.doPrivileged(J2DoPrivHelper.getContextClassLoaderAction()));
            Class<?> poolingDataSource = Class.forName("org.apache.commons.dbcp.PoolingDataSource", true,
                    AccessController.doPrivileged(J2DoPrivHelper.getContextClassLoaderAction()));
            Method setAccessToUnderlyingConnectionAllowed = poolingDataSource
                    .getMethod("setAccessToUnderlyingConnectionAllowed", boolean.class);

            Field this$0 = conn.getClass().getDeclaredField("this$0");
            this$0.setAccessible(true);
            Object poolingDataSourceObj = this$0.get(conn);
            setAccessToUnderlyingConnectionAllowed.invoke(poolingDataSourceObj, true);

            dbcpGetDelegate = dbcpConnectionClass.getMethod("getInnermostDelegate");
        }
        delegate = (Connection) dbcpGetDelegate.invoke(conn);
    } catch (Exception e) {
        throw new InternalException(_loc.get("dbcp-unwrap-failed"), e);
    }
    if (delegate == null) {
        throw new InternalException(_loc.get("dbcp-unwrap-failed"));
    }
    return delegate;
}

From source file:org.glowroot.agent.plugin.jdbc.Connections.java

private static Connection initConnection(DataSource ds) throws Exception {
    Connection connection = ds.getConnection();
    insertRecords(connection);/*from   w w w  .j  av  a  2  s  . com*/
    if (connection.getClass().getName().startsWith("com.sun.gjc.spi.")) {
        hackGlassfishConnection(connection);
    }
    return connection;
}

From source file:org.hyperic.util.jdbc.DBUtil.java

/**
 * Given a Connection object, this method returns a constant indicating what
 * type of database the Connection is connected to.
 * //from   w w  w .  ja  v  a  2 s  . co  m
 * @param conn The connection whose database type the caller wished to
 *        ascertain.
 * @return One of the DATABASE_XXX constants defined in this class.
 */
public static int getDBType(Connection conn) throws SQLException {

    Class connClass = conn.getClass();
    Integer dbTypeInteger = (Integer) _dbTypes.get(connClass);
    int dbType = DATABASE_UNKNOWN;

    if (dbTypeInteger == null) {

        DatabaseMetaData dbMetaData = conn.getMetaData();
        String dbName = dbMetaData.getDatabaseProductName().toLowerCase();
        String dbVersion = dbMetaData.getDatabaseProductVersion().toLowerCase();
        log.debug("getDBType: dbName='" + dbName + "', version='" + dbVersion + "'");

        if (dbName.indexOf("postgresql") != -1) {
            if (dbVersion.startsWith("7.")) {
                dbType = DATABASE_POSTGRESQL_7;
            } else if (dbVersion.startsWith("8.")) {
                dbType = DATABASE_POSTGRESQL_8;
            } else if (dbVersion.startsWith("9.")) {
                dbType = DATABASE_POSTGRESQL_9;
            }
        } else if (dbName.indexOf("oracle") != -1) {
            if (dbVersion.startsWith("oracle8")) {
                dbType = DATABASE_ORACLE_8;
            } else if (dbVersion.startsWith("oracle9")) {
                dbType = DATABASE_ORACLE_9;
            } else if (dbVersion.startsWith("oracle database 10g")) {
                dbType = DATABASE_ORACLE_10;
            } else if (dbVersion.startsWith("oracle database 11g")) {
                dbType = DATABASE_ORACLE_11;
            }
        } else if (dbName.indexOf("mysql") != -1) {
            dbType = DATABASE_MYSQL5;
        }

        _dbTypes.put(connClass, new Integer(dbType));

    } else {
        dbType = dbTypeInteger.intValue();
    }

    return dbType;
}

From source file:org.jaffa.persistence.engines.jdbcengine.datasource.DataSourceFactory.java

/**
 * When using the dbcp DataSource, a wrapper connection is created. Extract the actual connection from the wrapper.
 *
 * @param connection The dbcp connection.
 * @return the original connection if using dbcp.
 * @throws Exception if any error occurs.
 *//*from   w  w w  . j  a  va2 s  .  c  o m*/
private static Connection checkDbcpWrapper(Connection connection) throws Exception {
    // When using the dbcp DataSource, a wrapper connection is created. Extract the actual connection from the wrapper.
    Class<?> dbcpDelegatingConnectionClass = null;
    try {
        dbcpDelegatingConnectionClass = Class.forName("org.apache.commons.dbcp.DelegatingConnection");
    } catch (Throwable e) {
        // Commons dbcp is not being used. Just return
        return connection;
    }
    if (dbcpDelegatingConnectionClass.isInstance(connection)) {
        log.debug("Obtain the underlying connection from the dbcp DelegatingConnection");
        Method m = connection.getClass().getMethod("getInnermostDelegate", (Class[]) null);
        connection = (Connection) m.invoke(connection, (Object[]) null);
    }
    return connection;
}

From source file:org.jaffa.persistence.engines.jdbcengine.datasource.DataSourceFactory.java

/**
 * When using JBoss, a wrapper connection is created. Extract the actual connection from the wrapper.
 *
 * @param connection The dbcp connection.
 * @return the original connection if using JBoss.
 * @throws Exception if any error occurs.
 *///from   w w w . ja va  2s .c om
private static Connection checkJbossWrapper(Connection connection) throws Exception {
    // When using JBoss, a wrapper connection is created. Extract the actual oracle connection from the wrapper.
    if (connection.getClass().getName().equals("org.jboss.resource.adapter.jdbc.WrappedConnection")) {
        log.debug("Obtain the underlying connection from the jboss WrappedConnection");
        Method m = connection.getClass().getMethod("getUnderlyingConnection", (Class[]) null);
        connection = (Connection) m.invoke(connection, (Object[]) null);
    }
    return connection;
}