Example usage for java.sql Connection setReadOnly

List of usage examples for java.sql Connection setReadOnly

Introduction

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

Prototype

void setReadOnly(boolean readOnly) throws SQLException;

Source Link

Document

Puts this connection in read-only mode as a hint to the driver to enable database optimizations.

Usage

From source file:com.insprise.common.db.DefaultConnectionPool.java

/**
* Gets a connection./*from w  w  w.j a  v a  2 s .  c  o m*/
* A shortcut for: getDataSource().getConnection(). After using the connection, always remember to close it.
* <p>
* <code><pre>
* Connection conn = null;
* try {
*   conn = pool.getConnection();
*   ...
* }catch(Exception e) {
*   ...
* }finally{
*   &lt;b&gt;conn.close();&lt;/b&gt; // return the connection to the pool.
* }
* </pre></code>
* @param readOnly Whether the connection should be read only or not.
* @return getDataSource().getConnection().
* @throws SQLException
*/
public Connection getConnection(boolean readOnly) throws SQLException {
    if (sourceType == SourceType.DRIVER_MANAGER) {
        if (!initialized) {
            synchronized (this) {
                if (!initialized) {
                    try {
                        setupPool();
                    } catch (ClassNotFoundException e) {
                        throw new SQLException(e.getMessage(), e);
                    }
                }
                initialized = true;
            }
        }
    }

    Connection conn = dataSource.getConnection();
    conn.setReadOnly(readOnly);
    if (readOnly) {
        conn.setAutoCommit(true); // auto commit read only.
    }

    return conn;
}

From source file:com.jaxio.celerio.configuration.database.support.MetadataExtractor.java

private Connection getDatabaseConnection(JdbcConnectivity configuration)
        throws ClassNotFoundException, SQLException {

    if (log.isInfoEnabled()) {
        log.info("Connecting to Database jdbcUrl=" + configuration.getUrl());
    }//from   w ww .  jav  a 2  s . c  om

    Properties info = new Properties();
    info.put("user", configuration.getUser());
    info.put("password", configuration.getPassword());

    if (isOracle && configuration.isOracleRetrieveSynonyms()) {
        info.put("includeSynonyms", "true");
        if (log.isInfoEnabled()) {
            log.info("    Requesting oracle synonyms");
        }
    }

    if (isOracle && configuration.isOracleRetrieveRemarks()) {
        // it is important to pass the property only on oracle connection
        // For example passing it on postgresql trigger a NPE!
        info.put("remarksReporting", "true");

        if (log.isInfoEnabled()) {
            log.info("    Requesting oracle remarks/comments");
        }
    }

    Connection dbConnection = DriverManager.getConnection(configuration.getUrl(), info);
    dbConnection.setReadOnly(true);

    if (log.isInfoEnabled()) {
        log.info("Connected OK");
    }
    return dbConnection;
}

From source file:edu.education.ucsb.muster.MusterServlet.java

private String testConnectivity(DatabaseDefinition db) {

    // load driver
    try {//w ww  . j a  va  2  s .co  m
        DriverManager.getDriver(db.url);
    } catch (SQLException e) {
        try {
            DriverManager.registerDriver(
                    (Driver) Class.forName(db.driver).getConstructor().newInstance((Object[]) null));
        } catch (Exception e1) {
            addException(e1, "A driver couldn't be loaded. Check the config file and try again. driver: `"
                    + db.driver + "`, confPath: `" + confPath + "`");
            return "FAIL";
        }
    }

    // connect and test setReadOnly

    // Add the connection to our list and try setting readOnly to test
    Connection connection = null;
    try {
        connection = DriverManager.getConnection(db.url, db.username, db.password);
        connection.setReadOnly(true);
        connection.close();
    } catch (Exception e) {
        addException(e, "Setting readonly failed on " + db.url);
        return e.toString();
    }

    return "OK";
}

From source file:de.mendelson.comm.as2.database.DBDriverManager.java

/**Returns a connection to the database
 * @param hostName Name of the database server to connect to. Use "localhost"
 * to connect to your local host/*w w w. j ava  2s.c  o  m*/
 * @param DB_TYPE of the database that should be created, as defined in this class
 */
public static synchronized Connection getConnectionWithoutErrorHandling(final int DB_TYPE, String host)
        throws SQLException {
    Connection connection = null;
    if (DB_TYPE == DB_RUNTIME) {
        //no pooling
        if (dataSourceRuntime == null) {
            connection = DriverManager.getConnection(getConnectionURI(host, DB_TYPE), DB_USER_NAME,
                    DB_PASSWORD);
        } else {
            int maxConnections = dataSourceRuntime.getMaxActive();
            if (maxConnections < dataSourceRuntime.getNumActive() + 1) {
                dataSourceRuntime.setMaxActive(maxConnections + 1);
            }
            connection = dataSourceRuntime.getConnection();
        }
    } else if (DB_TYPE == DB_CONFIG) {
        //no pooling
        if (dataSourceConfig == null) {
            connection = DriverManager.getConnection(getConnectionURI(host, DB_TYPE), DB_USER_NAME,
                    DB_PASSWORD);
        } else {
            int maxConnections = dataSourceConfig.getMaxActive();
            if (maxConnections < dataSourceConfig.getNumActive() + 1) {
                dataSourceConfig.setMaxActive(maxConnections + 1);
            }
            connection = dataSourceConfig.getConnection();
        }
    } else if (DB_TYPE == DB_DEPRICATED) {
        //deprecated connection: no pooling
        connection = DriverManager.getConnection(getConnectionURI(host, DB_TYPE), DB_USER_NAME, DB_PASSWORD);
    } else {
        throw new RuntimeException("Requested invalid db type in getConnectionWithoutErrorHandling");
    }
    connection.setReadOnly(false);
    connection.setAutoCommit(true);
    return (connection);
}

From source file:gridool.db.sql.ParallelSQLExecJob.java

private static String invokeStringOutputReduce(final Connection conn, final String reduceQuery,
        final ReadWriteLock rwlock) throws GridException {
    final ResultSetHandler rsh = new ResultSetHandler() {
        public String handle(ResultSet rs) throws SQLException {
            if (rs.next()) {
                String firstResult = rs.getString(1);
                return firstResult;
            }/* ww w.  j  a  v  a2 s.c  om*/
            return null;
        }
    };

    if (LOG.isInfoEnabled()) {
        LOG.info("Executing a Reduce SQL query: \n" + reduceQuery);
    }
    final String result;
    final Lock rlock = rwlock.readLock();
    try {
        rlock.lock();
        conn.setReadOnly(true);
        result = (String) JDBCUtils.query(conn, reduceQuery, rsh);
    } catch (SQLException e) {
        String errmsg = "failed running a reduce query: " + reduceQuery;
        LOG.error(errmsg, e);
        try {
            conn.rollback();
        } catch (SQLException rbe) {
            LOG.warn("Rollback failed", rbe);
        }
        throw new GridException(errmsg, e);
    } finally {
        rlock.unlock();
    }
    return result;
}

From source file:com.adaptris.jdbc.connection.FailoverDatasourceTest.java

@Test
public void testInfo() throws Exception {
    Connection conn = new MyProxy();

    try {// ww  w  . j  a va  2s .com
        try {
            conn.getMetaData();
        } catch (SQLException e) {

        }
        try {
            conn.setCatalog(conn.getCatalog());
        } catch (SQLException e) {

        }
        try {
            conn.setReadOnly(conn.isReadOnly());
        } catch (SQLException e) {

        }
        try {
            conn.setTransactionIsolation(conn.getTransactionIsolation());
        } catch (SQLException e) {

        }
        try {
            conn.setTransactionIsolation(conn.getTransactionIsolation());
        } catch (SQLException e) {

        }
        try {
            conn.getWarnings();
        } catch (SQLException e) {

        }
        try {
            conn.clearWarnings();
        } catch (SQLException e) {

        }
        try {
            conn.setHoldability(conn.getHoldability());
        } catch (SQLException e) {

        }

        try {
            conn.setSchema(conn.getSchema());
        } catch (SQLException e) {

        }

    } finally {
        JdbcUtil.closeQuietly(conn);
    }

}

From source file:com.funambol.foundation.items.dao.PIMNoteDAO.java

public NoteWrapper getItem(String uid) throws DAOException {
    if (log.isTraceEnabled()) {
        log.trace("PIMNoteDAO start getItem " + uid);
    }/*  ww w. ja  va  2 s .c om*/

    Connection con = null;
    PreparedStatement ps = null;
    ResultSet rs = null;
    NoteWrapper nw;

    Long id = Long.parseLong(uid);

    try {
        // Looks up the data source when the first connection is created
        con = getUserDataSource().getRoutedConnection(userId);
        con.setReadOnly(true);

        ps = con.prepareStatement(SQL_GET_FNBL_PIM_NOTE_BY_ID_USER);
        ps.setLong(1, id);
        ps.setString(2, userId);

        rs = ps.executeQuery();

        nw = createNoteWrapper(uid, rs);

        DBTools.close(null, ps, rs);

    } catch (Exception e) {
        throw new DAOException("Error seeking note.", e);
    } finally {
        DBTools.close(con, ps, rs);
    }

    return nw;
}

From source file:com.funambol.foundation.items.dao.PIMNoteDAO.java

public List getTwinItems(Note note) throws DAOException {
    if (log.isTraceEnabled()) {
        log.trace("PIMNoteDAO getTwinItems begin");
    }/*from w  w w.  j  av a  2 s .  c o  m*/

    List twins = new ArrayList();
    Connection con = null;
    PreparedStatement ps = null;
    ResultSet rs = null;

    if (!isTwinSearchAppliableOn(note)) {
        return twins;
    }

    try {

        // Looks up the data source when the first connection is created
        con = getUserDataSource().getRoutedConnection(userId);
        con.setReadOnly(true);

        // calculate crc
        String textDescription = note.getTextDescription().getPropertyValueAsString();
        if (textDescription != null) {
            textDescription = textDescription.replace('\0', ' ');
        }
        String truncatedTextDescription = StringUtils.left(textDescription, SQL_TEXTDESCRIPTION_DIM);
        Long crc = calculateCrc(truncatedTextDescription);

        //
        // If funambol is not in the debug mode is not possible to print the
        // note because it contains sensitive data.
        //
        if (Configuration.getConfiguration().isDebugMode()) {
            if (log.isTraceEnabled()) {

                String tdSearch = (crc == null ? "<N/A>" : crc.toString());

                StringBuilder sb = new StringBuilder();
                sb.append("Looking for items having: ").append("\n> crc: '").append(tdSearch).append('\'');

                log.trace(sb.toString());
            }
        }

        if (crc == null) {
            ps = con.prepareStatement(SQL_GET_NOTE_TWIN_ID_LIST_CRC_NULL + SQL_ORDER_BY_ID);
        } else {
            ps = con.prepareStatement(SQL_GET_NOTE_TWIN_ID_LIST + SQL_ORDER_BY_ID);
            ps.setLong(2, crc);
        }
        ps.setString(1, userId);

        rs = ps.executeQuery();

        long twinId;
        while (rs.next()) {
            twinId = rs.getLong(1); // The id is the first
                                    // and only column
            if (log.isTraceEnabled()) {
                log.trace("Twin found: " + twinId);
            }
            twins.add(Long.toString(twinId));
        }

    } catch (Exception e) {
        throw new DAOException("Error retrieving twin.", e);
    } finally {
        DBTools.close(con, ps, rs);
    }
    if (log.isTraceEnabled()) {
        log.trace("PIMNoteDAO getTwinItems end");
    }

    return twins;
}

From source file:gridool.db.sql.ParallelSQLExecJob.java

private static String invokeCsvOutputReduce(final Connection conn, final String reduceQuery,
        final String outputTableName, final ReadWriteLock rwlock, final Timings timings) throws GridException {
    File colDir = GridUtils.getWorkDir(true);
    final File outFile = new File(colDir, outputTableName + ".csv");
    final CsvWriter writer = new CsvWriter(outFile);
    final MutableBoolean first = new MutableBoolean(true);
    final MutableLong ansGenStart = new MutableLong(-1L);
    final ResultSetHandler rsh = new ResultSetHandler() {
        public Object handle(ResultSet rs) throws SQLException {
            if (first.getBoolean()) {
                ansGenStart.setValue(System.currentTimeMillis());
                first.setBoolean(false);
            }/*from  w w  w . j ava2s  .  c  o  m*/
            int numRows = writer.writeAll(rs, MONETDB_NULL_STRING, false);
            if (LOG.isInfoEnabled()) {
                LOG.info("Result row count: " + numRows);
            }
            return null;
        }
    };

    if (LOG.isInfoEnabled()) {
        LOG.info("Executing a Reduce SQL query: \n" + reduceQuery);
    }
    final Lock rlock = rwlock.readLock();
    try {
        rlock.lock();
        conn.setReadOnly(true);
        JDBCUtils.query(conn, reduceQuery, rsh);
    } catch (SQLException e) {
        String errmsg = "failed running a reduce query: " + reduceQuery;
        LOG.error(errmsg, e);
        try {
            conn.rollback();
        } catch (SQLException rbe) {
            LOG.warn("Rollback failed", rbe);
        }
        throw new GridException(errmsg, e);
    } finally {
        rlock.unlock();
        writer.close();
    }

    long answerGenStart = ansGenStart.getValue();
    long answerGenTime = (answerGenStart == -1L) ? 0L : System.currentTimeMillis() - answerGenStart;
    timings.setAnswerGenerationTime(answerGenTime);

    if (!outFile.exists()) {
        throw new IllegalStateException("Output file does not exist:" + outFile.getAbsolutePath());
    }
    return outFile.getAbsolutePath();
}

From source file:com.funambol.foundation.items.dao.DataBaseFileDataObjectMetadataDAO.java

/**
 * Removes all the properties associated to the expired incomplete items.
 * Items are incomplete if they don't have a corresponding file on
 * the file system.//from ww w .j  a  v a2  s.  com
 * Incomplete items are considered expired if older than 24h.
 *
 * @param lastUpdate the last update time
 * @throws DAOException if an error occurs during deletion
 */
public void removeAllPropertiesOfExpiredIncompleteItems(long lastUpdate) throws DAOException {

    Connection con = null;
    PreparedStatement ps = null;

    try {
        // Looks up the data source when the first connection is created
        con = getUserDataSource().getRoutedConnection(userId);
        con.setReadOnly(false);

        ps = con.prepareStatement(SQL_DELETE_ALL_PROPERTY_OF_EXPIRED_INCOMPLETE_FDOS);
        ps.setLong(1, getCutOffTime());
        ps.setString(2, userId);
        ps.setString(3, sourceURI);

        ps.execute();

    } catch (Exception e) {
        throw new DAOException("Error deleting all properties for expired incomplete items.", e);
    } finally {
        DBTools.close(con, ps, null);
    }
}