List of usage examples for java.sql Connection setReadOnly
void setReadOnly(boolean readOnly) throws SQLException;
From source file:org.apache.druid.metadata.SQLMetadataConnector.java
protected final <T> T inReadOnlyTransaction(final TransactionCallback<T> callback) { return getDBI().withHandle(new HandleCallback<T>() { @Override//from www. j a v a 2 s. com public T withHandle(Handle handle) throws Exception { final Connection connection = handle.getConnection(); final boolean readOnly = connection.isReadOnly(); connection.setReadOnly(true); try { return handle.inTransaction(callback); } finally { try { connection.setReadOnly(readOnly); } catch (SQLException e) { // at least try to log it so we don't swallow exceptions log.error(e, "Unable to reset connection read-only state"); } } } }); }
From source file:org.apache.jackrabbit.oak.plugins.document.rdb.RDBExport.java
private static void dumpJDBC(String url, String user, String pw, String table, String query, Format format, PrintStream out, List<String> fieldNames, RDBDocumentSerializer ser) throws SQLException { String driver = RDBJDBCTools.driverForDBType(RDBJDBCTools.jdbctype(url)); try {/* www .ja v a 2 s . c o m*/ Class.forName(driver); } catch (ClassNotFoundException ex) { System.err.println( RDBExport.class.getName() + ":attempt to load class " + driver + " failed:" + ex.getMessage()); } Connection c = DriverManager.getConnection(url, user, pw); c.setReadOnly(true); Statement stmt = c.createStatement(); String sql = "select ID, MODIFIED, MODCOUNT, CMODCOUNT, HASBINARY, DELETEDONCE, DATA, BDATA from " + table; if (query != null) { sql += " where " + query; } sql += " order by id"; ResultSet rs = stmt.executeQuery(sql); if (format == Format.JSONARRAY) { out.println("["); } else if (format == Format.CSV) { out.println(dumpFieldNames(fieldNames)); } boolean needComma = format == Format.JSONARRAY; ResultSetMetaData rsm = null; boolean idIsAscii = true; while (rs.next()) { if (rsm == null) { rsm = rs.getMetaData(); idIsAscii = !isBinaryType(rsm.getColumnType(1)); } String id = idIsAscii ? rs.getString("ID") : new String(rs.getBytes("ID"), UTF8); long modified = rs.getLong("MODIFIED"); long modcount = rs.getLong("MODCOUNT"); long cmodcount = rs.getLong("CMODCOUNT"); long hasBinary = rs.getLong("HASBINARY"); long deletedOnce = rs.getLong("DELETEDONCE"); String data = rs.getString("DATA"); byte[] bdata = rs.getBytes("BDATA"); RDBRow row = new RDBRow(id, hasBinary == 1, deletedOnce == 1, modified, modcount, cmodcount, data, bdata); StringBuilder fulljson = dumpRow(ser, id, row); if (format == Format.CSV) { out.println(asCSV(fieldNames, fulljson)); } else { fulljson = asJSON(fieldNames, fulljson); if (format == Format.JSONARRAY && needComma && !rs.isLast()) { fulljson.append(","); } out.println(fulljson); needComma = true; } } if (format == Format.JSONARRAY) { out.println("]"); } out.close(); rs.close(); stmt.close(); c.close(); }
From source file:org.apache.olio.workload.driver.common.DBConnectionFactory.java
public static Connection getWriteConnection() throws SQLException { if (bds == null) { ensureConnection();/*from w ww . ja v a2s . com*/ } Connection conn = bds.getConnection(); conn.setAutoCommit(false); conn.setReadOnly(false); return conn; }
From source file:org.apache.olio.workload.driver.common.DBConnectionFactory.java
public static Connection getReadConnection() throws SQLException { if (bds == null) { ensureConnection();//from ww w . ja v a 2 s . c om } Connection conn = bds.getConnection(); conn.setAutoCommit(true); conn.setReadOnly(true); return conn; }
From source file:org.apache.openjpa.jdbc.sql.MySQLDictionary.java
@Override public Connection decorate(Connection conn) throws SQLException { conn = super.decorate(conn); String driver = conf.getConnectionDriverName(); if ("com.mysql.jdbc.ReplicationDriver".equals(driver)) conn.setReadOnly(true); return conn;/*from w ww.ja v a 2s . c o m*/ }
From source file:org.fcrepo.server.storage.ConnectionPool.java
private void setConnectionReadOnly(Connection connection, boolean readOnly) { if (supportsReadOnly) { try {//from w ww . ja v a 2s . c om connection.setReadOnly(readOnly); } catch (Throwable th) { logger.info("Read-only connections not supported (" + th.getMessage() + ")"); supportsReadOnly = false; } } }
From source file:org.kuali.test.utils.Utils.java
/** * /*w w w . ja v a 2 s . c om*/ * @param password * @param dbconn * @return * @throws ClassNotFoundException * @throws SQLException * @throws UnsupportedEncodingException */ public static Connection getDatabaseConnection(String password, DatabaseConnection dbconn) throws ClassNotFoundException, SQLException, UnsupportedEncodingException { Class.forName(dbconn.getJdbcDriver()); Connection retval = DriverManager.getConnection(dbconn.getJdbcUrl(), dbconn.getUsername(), Utils.decrypt(password, dbconn.getPassword())); retval.setReadOnly(true); return retval; }
From source file:org.sakaiproject.webservices.SakaiReport.java
protected String getQueryAsString(String query, Object[] args, int rowCount, String type) { Connection conn = null; PreparedStatement ps = null;//from w w w. j ava 2 s .c o m ResultSet rs = null; try { conn = sqlService.borrowConnection(); conn.setReadOnly(true); ps = conn.prepareStatement(query, ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_READ_ONLY); if (rowCount > 0) { ps.setMaxRows(rowCount); } for (int i = 0; i < args.length; i++) { if (args[i] instanceof String) { ps.setString(i + 1, (String) args[i]); } else if (args[i] instanceof java.util.Date) { // select * from sakai_event where event_date between to_date('2001-12-12 12:12','YYYY-MM-DD HH24:MI') and to_date('2017-12-12 12:12','YYYY-MM-DD HH24:MI') if (sqlService.getVendor().equals("oracle")) { ps.setString(i + 1, df.format(args[i])); // select * from sakai_event where event_date between '2001-12-12 12:12' and '2017-12-12 12:12'; } else { ps.setString(i + 1, df.format(args[i])); } } } LOG.info("preparing query: " + ps.toString()); rs = ps.executeQuery(); //return toJsonString(rs); if (type == TYPE_CSV) { return stripInvalidXmlCharacters(toCsvString(rs)); } if (type == TYPE_CSV_WITH_HEADER_ROW) { return stripInvalidXmlCharacters(toCsvString(rs, true)); } if (type == TYPE_JSON) { return stripInvalidXmlCharacters(toJsonString(rs)); } return Xml.writeDocumentToString(toDocument(rs)); } catch (Exception e) { LOG.error(e.getMessage(), e); throw new RuntimeException(e.getMessage(), e); } finally { if (rs != null) { try { rs.close(); } catch (SQLException e) { } } if (ps != null) { try { ps.close(); } catch (SQLException e) { } } if (conn != null) { try { conn.close(); } catch (SQLException e) { } } } }
From source file:org.springframework.jdbc.datasource.DataSourceUtils.java
/** * Prepare the given Connection with the given transaction semantics. * @param con the Connection to prepare//from w w w.j a v a 2s . c om * @param definition the transaction definition to apply * @return the previous isolation level, if any * @throws SQLException if thrown by JDBC methods * @see #resetConnectionAfterTransaction */ @Nullable public static Integer prepareConnectionForTransaction(Connection con, @Nullable TransactionDefinition definition) throws SQLException { Assert.notNull(con, "No Connection specified"); // Set read-only flag. if (definition != null && definition.isReadOnly()) { try { if (logger.isDebugEnabled()) { logger.debug("Setting JDBC Connection [" + con + "] read-only"); } con.setReadOnly(true); } catch (SQLException | RuntimeException ex) { Throwable exToCheck = ex; while (exToCheck != null) { if (exToCheck.getClass().getSimpleName().contains("Timeout")) { // Assume it's a connection timeout that would otherwise get lost: e.g. from JDBC 4.0 throw ex; } exToCheck = exToCheck.getCause(); } // "read-only not supported" SQLException -> ignore, it's just a hint anyway logger.debug("Could not set JDBC Connection read-only", ex); } } // Apply specific isolation level, if any. Integer previousIsolationLevel = null; if (definition != null && definition.getIsolationLevel() != TransactionDefinition.ISOLATION_DEFAULT) { if (logger.isDebugEnabled()) { logger.debug("Changing isolation level of JDBC Connection [" + con + "] to " + definition.getIsolationLevel()); } int currentIsolation = con.getTransactionIsolation(); if (currentIsolation != definition.getIsolationLevel()) { previousIsolationLevel = currentIsolation; con.setTransactionIsolation(definition.getIsolationLevel()); } } return previousIsolationLevel; }
From source file:org.springframework.jdbc.datasource.DataSourceUtils.java
/** * Reset the given Connection after a transaction, * regarding read-only flag and isolation level. * @param con the Connection to reset//w w w . jav a2 s . c o m * @param previousIsolationLevel the isolation level to restore, if any * @see #prepareConnectionForTransaction */ public static void resetConnectionAfterTransaction(Connection con, @Nullable Integer previousIsolationLevel) { Assert.notNull(con, "No Connection specified"); try { // Reset transaction isolation to previous value, if changed for the transaction. if (previousIsolationLevel != null) { if (logger.isDebugEnabled()) { logger.debug("Resetting isolation level of JDBC Connection [" + con + "] to " + previousIsolationLevel); } con.setTransactionIsolation(previousIsolationLevel); } // Reset read-only flag. if (con.isReadOnly()) { if (logger.isDebugEnabled()) { logger.debug("Resetting read-only flag of JDBC Connection [" + con + "]"); } con.setReadOnly(false); } } catch (Throwable ex) { logger.debug("Could not reset JDBC Connection after transaction", ex); } }