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:gridool.mapred.db.task.DBMapShuffleTaskBase.java

private static void configureConnection(final Connection conn) {
    try {//  ww  w  .  j a v  a 2 s  .c o m
        conn.setReadOnly(true); // should *not* call setReadOnly in a transaction (for MonetDB)
        conn.setAutoCommit(false);
    } catch (SQLException e) {
        LOG.warn("failed to configure a connection", e);
    }
}

From source file:com.example.querybuilder.server.Jdbc.java

public static void setReadOnly(Connection connection, boolean isReadOnly) {
    try {/* ww w  . j a  v  a  2 s  .com*/
        connection.setReadOnly(isReadOnly);
    } catch (SQLException e) {
        throw new SqlRuntimeException(e);
    }
}

From source file:org.cfr.capsicum.datasource.DataSourceUtils.java

/**
 * Prepare the given Connection with the given transaction semantics.
 * @param con the Connection to prepare/*from  ww w.j a  v a2s . co m*/
 * @param definition the transaction definition to apply
 * @return the previous isolation level, if any
 * @throws SQLException if thrown by JDBC methods
 * @see #resetConnectionAfterTransaction
 */
public static Integer prepareConnectionForTransaction(Connection con, 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 (Throwable ex) {
            // SQLException or UnsupportedOperationException
            // -> 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());
        }
        previousIsolationLevel = new Integer(con.getTransactionIsolation());
        con.setTransactionIsolation(definition.getIsolationLevel());
    }

    return previousIsolationLevel;
}

From source file:io.seldon.db.jdbc.JDBCConnectionFactory.java

public Connection getConnection(String client, boolean readonly) throws SQLException {
    DataSource ds = dataSources.get(client);
    Connection c = null;
    if (ds != null) {
        c = ds.getConnection();// w  w w  .ja v a 2 s  .c  o m
        if (readonly)
            c.setReadOnly(true);
        else
            c.setReadOnly(false);
        c.setCatalog(clientToCatalog.get(client));
    } else {
        //         logger.error("Can't get connection for client "+client);
        final String message = "Can't get connection for client " + client;
        logger.error(message, new Exception(message));
    }
    return c;
}

From source file:de.doering.dwca.arkive.ChecklistBuilder.java

private void parseData() throws IOException {
    int count = 0;
    log.info("Query for nub species");

    try {//  w  w  w . ja va  2  s  .  c  om
        Connection con = getConnection();
        con.setReadOnly(true);
        Statement sta = con.createStatement();
        // get all nub names which are species or below
        ResultSet res = sta.executeQuery(
                "SELECT distinct cn.scientific_name FROM name_usage u join name_string n on u.name_fk=n.id join name_string cn on n.canonical_name_fk=cn.id where checklist_fk=1 and rank_fk>=600");

        log.info("Iterate over nub species");
        while (res.next()) {
            String name = res.getString(1);
            if (count % LOG_INTERVALL == 0) {
                log.debug("{} names found with {} images out of {} searched nub names",
                        new Object[] { usageCounter, imageCounter, count });
            }
            findSpecies(name);
            count++;
        }
        res.close();
        sta.close();
        con.close();

    } catch (SQLException e) {
        // TODO: Handle exception
    }

    log.info("Finished with {} names found with {} images out of {} searched nub names",
            new Object[] { usageCounter, imageCounter, count });
}

From source file:org.cfr.capsicum.datasource.DataSourceUtils.java

/**
 * Reset the given Connection after a transaction,
 * regarding read-only flag and isolation level.
 * @param con the Connection to reset/*  w ww.  j a v a  2 s . c  o m*/
 * @param previousIsolationLevel the isolation level to restore, if any
 * @see #prepareConnectionForTransaction
 */
public static void resetConnectionAfterTransaction(Connection con, 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.intValue());
        }

        // 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);
    }
}

From source file:io.apiman.gateway.engine.policies.auth.JDBCIdentityValidator.java

/**
 * @see io.apiman.gateway.engine.policies.auth.IIdentityValidator#validate(java.lang.String, java.lang.String, io.apiman.gateway.engine.beans.ServiceRequest, io.apiman.gateway.engine.policy.IPolicyContext, java.lang.Object, io.apiman.gateway.engine.async.IAsyncHandler)
 *///w  w w. java  2  s.c o  m
@Override
public void validate(String username, String password, ServiceRequest request, IPolicyContext context,
        JDBCIdentitySource config, IAsyncResultHandler<Boolean> handler) {
    DataSource ds = lookupDatasource(config);
    String sqlPwd = password;
    switch (config.getHashAlgorithm()) {
    case MD5:
        sqlPwd = DigestUtils.md5Hex(password);
        break;
    case SHA1:
        sqlPwd = DigestUtils.shaHex(password);
        break;
    case SHA256:
        sqlPwd = DigestUtils.sha256Hex(password);
        break;
    case SHA384:
        sqlPwd = DigestUtils.sha384Hex(password);
        break;
    case SHA512:
        sqlPwd = DigestUtils.sha512Hex(password);
        break;
    case None:
    default:
        break;
    }
    String query = config.getQuery();
    Connection conn = null;
    boolean validated = false;
    try {
        conn = ds.getConnection();
        conn.setReadOnly(true);
        PreparedStatement statement = conn.prepareStatement(query);
        statement.setString(1, username);
        statement.setString(2, sqlPwd);
        ResultSet resultSet = statement.executeQuery();
        if (resultSet.next()) {
            validated = true;
        }
        resultSet.close();
    } catch (Exception e) {
        throw new RuntimeException(e);
    } finally {
        if (conn != null) {
            try {
                conn.close();
            } catch (SQLException e) {
            }
        }
    }

    handler.handle(AsyncResultImpl.create(validated));
}

From source file:edu.arizona.rice.kew.docsearch.dao.impl.IndexTableSearchHandler.java

@Override
public void run() {
    Connection conn = null;
    ResultSet res = null;/*from w  w w  .j av a2s. c  o  m*/
    Statement stmt = null;
    try {
        long start = System.currentTimeMillis();
        conn = dataSource.getConnection();
        conn.setReadOnly(true);

        char dataTypeCode = DocumentSearchConstants.TYPE_CODE_BY_ATTRIBUTE_TABLE_MAP.get(indexTableName);
        stmt = conn.createStatement();
        stmt.setFetchSize(fetchSize);

        for (List<String> inlist : DocumentSearchUtils.getInLists(docids)) {
            res = stmt.executeQuery(getSqlSelect(inlist));

            while (res.next()) {
                String docid = res.getString(1);
                String keyCd = res.getString(2);
                String val = res.getString(3);

                if (StringUtils.isNotBlank(val)) {
                    List<DocumentAttribute> attlist = attributeMap.get(docid);

                    if (attlist == null) {
                        attributeMap.put(docid, attlist = new ArrayList<DocumentAttribute>());
                    }

                    attlist.add(buildDocumentAttribute(dataTypeCode, keyCd, res));
                }
            }
        }

        if (LOG.isDebugEnabled()) {
            LOG.debug("index table query [" + indexTableName + "] elapsed time(sec): "
                    + (System.currentTimeMillis() - start) / 1000);
        }
    }

    catch (Exception ex) {
        exception = ex;
    }

    finally {
        done = true;
        DocumentSearchUtils.closeDbObjects(conn, stmt, res);
    }
}

From source file:net.fender.sql.DriverConnectionFactory.java

public Connection getConnection() throws SQLException {
    // don't log properties as it contains plain text user name and password
    log.debug("creating connection to " + driver + " " + url);
    Connection connection = driver.connect(url, properties);
    if (autoCommit != null) {
        connection.setAutoCommit(autoCommit);
    }/* ww  w. j  av  a2s.c  o  m*/
    if (holdability != null) {
        connection.setHoldability(holdability.getHoldability());
    }
    if (readOnly != null) {
        connection.setReadOnly(readOnly);
    }
    if (transactionIsolation != null) {
        connection.setTransactionIsolation(transactionIsolation.getLevel());
    }
    if (catalog != null) {
        connection.setCatalog(catalog);
    }
    return connection;
}

From source file:org.onebusaway.nyc.webapp.actions.admin.ReportingAction.java

public String submit() throws Exception {
    Session session = null;// ww  w .  j  av  a 2s .co  m
    Connection connection = null;
    Statement statement = null;
    ResultSet rs = null;
    try {
        session = sessionFactory.openSession();
        connection = getConnectionFromSession(session);
        connection.setReadOnly(true);

        statement = connection.createStatement();
        rs = statement.executeQuery(query);

    } catch (Exception e) {
        // make sure everything is closed if an exception was thrown
        try {
            rs.close();
        } catch (Exception ex) {
        }
        try {
            statement.close();
        } catch (Exception ex) {
        }
        try {
            connection.close();
        } catch (Exception ex) {
        }
        try {
            session.close();
        } catch (Exception ex) {
        }

        reportError = e.getMessage();
        // not really "success", but we'll use the same template with the error displayed
        return SUCCESS;
    }

    // final so the output generator thread can close it
    final Session finalSession = session;
    final Connection finalConnection = connection;
    final Statement finalStatement = statement;
    final ResultSet finalRS = rs;

    final PipedInputStream pipedInputStream = new PipedInputStream();
    final PipedOutputStream pipedOutputStream = new PipedOutputStream(pipedInputStream);

    executorService.execute(new Runnable() {

        @Override
        public void run() {
            try {
                // column labels
                ResultSetMetaData metaData = finalRS.getMetaData();
                int columnCount = metaData.getColumnCount();

                for (int i = 0; i < columnCount; i++) {
                    String columnName = metaData.getColumnName(i + 1);
                    byte[] bytes = columnName.getBytes();

                    if (i > 0)
                        pipedOutputStream.write(columnDelimiter);

                    pipedOutputStream.write(bytes);
                }

                pipedOutputStream.write(newline);

                // column values
                while (finalRS.next()) {
                    for (int i = 0; i < columnCount; i++) {
                        String value = finalRS.getString(i + 1);

                        if (value == null)
                            value = "null";
                        else {
                            // remove returns
                            value = value.replaceAll("\n|\r", "");
                        }

                        byte[] valueBytes = value.getBytes();

                        if (i > 0)
                            pipedOutputStream.write(columnDelimiter);

                        pipedOutputStream.write(valueBytes);
                    }

                    pipedOutputStream.write(newline);
                }
            } catch (Exception e) {
            } finally {
                try {
                    pipedOutputStream.close();
                } catch (IOException e) {
                }
                try {
                    finalRS.close();
                } catch (SQLException e) {
                }
                try {
                    finalStatement.close();
                } catch (SQLException e) {
                }
                try {
                    finalConnection.close();
                } catch (SQLException e) {
                }
                try {
                    finalSession.close();
                } catch (Exception e) {
                }
            }
        }
    });

    // the input stream will get populated by the piped output stream
    inputStream = pipedInputStream;
    return "download";
}