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:de.innovationgate.webgate.api.jdbc.WGDatabaseImpl.java

public void beginUpdate() throws WGAPIException {
    try {//from  www  .j  a  v  a 2  s . c om
        getSession().getTransaction().rollback();

        getSession().doWork(new Work() {
            public void execute(Connection connection) throws SQLException {
                if (connection.isReadOnly()) {
                    connection.setReadOnly(false);
                }
            }
        });

        String user = _db.getSessionContext().getUser();
        DBUpdate update = new DBUpdate(_db.getSessionContext());
        _dbUpdatesByUser.put(user, update);

        getSession().beginTransaction();
    } catch (HibernateException e) {
        throw new WGBackendException("unable to start transaction", e);
    }

}

From source file:de.innovationgate.webgate.api.jdbc.WGDatabaseImpl.java

/**
 * @throws WGUnavailableException /*w w  w  . ja v  a 2  s.c om*/
 * @throws WGAPIException 
 * @see de.innovationgate.webgate.api.WGDatabaseCore#openSession(String,
 *      String)
 */
public WGUserAccess openSession(AuthenticationSession authSession, Object pwd, boolean master)
        throws WGAPIException {

    try {

        // Hibernate login
        Session session = _sessionBuilder.openSession();
        // Connection conn = session.connection();
        // conn.setAutoCommit(true); //Problematic with DBCP?
        session.setFlushMode(FlushMode.COMMIT);
        if (_saveIsolationActive) {
            session.setDefaultReadOnly(true);
        }
        getSessionStatus().setSession(session);

        if (!session.isOpen()) {
            throw new WGUnavailableException(_db, "Unable to connect to hibernate session");
        }

        // special handling if loadbalancing is enabled
        if (hasFeature(WGDatabase.FEATURE_LOADBALANCE)) {

            // set all connections to readonly except master sessions and if
            // update is in progress
            final boolean readOnly = (master ? false : !isUpdateInProgress(authSession.getDistinguishedName()));

            try {
                session.doWork(new Work() {

                    public void execute(Connection connection) throws SQLException {
                        connection.setReadOnly(readOnly);
                    }
                });
            } catch (HibernateException e) {
                throw new WGBackendException("Unable to set readonly flag on connection.", e);
            }
        }

        if (getTransactionMode() != WGSessionContext.TRANSACTION_MODE_MANUAL) {
            session.beginTransaction();
        }

        if (master) {
            // Master login always has manager access
            return new WGUserAccess(WGDatabase.MASTER_USERNAME, WGDatabase.ACCESSLEVEL_MANAGER);
        }

        // Determine access
        WGUserDetails userDetails;
        try {
            userDetails = _db.defaultBuildUserDetails(authSession);
        } catch (WGBackendException e) {
            try {
                closeSession();
            } catch (WGBackendException e1) {
                WGFactory.getLogger().error(e1);
            }
            throw e;
        }
        if (userDetails.getAccessLevel() <= WGDatabase.ACCESSLEVEL_NOACCESS) {
            try {
                closeSession();
            } catch (WGBackendException e) {
                WGFactory.getLogger().error(e);
            }
        }

        return userDetails;

    } catch (HibernateException e) {
        try {
            closeSession();
        } catch (WGBackendException e1) {
            WGFactory.getLogger().error(e1);
        }
        throw new WGUnavailableException(_db, "Error opening hibernate session", e);
    }

}

From source file:de.innovationgate.webgate.api.jdbc.WGDatabaseImpl.java

public void commitHibernateTransaction() throws WGAPIException {
    if (getTransactionMode() != WGSessionContext.TRANSACTION_MODE_MANUAL) {
        Transaction trans = getSession().getTransaction();
        if (trans != null) {
            trans.commit();/*from  ww  w.  j  av  a 2 s  .c  o  m*/
        }

        // hibernate might release the underlying jdbc connection after commit
        // and get a new one
        // this connection will be readonly by default - therefore we should
        // check if we have to
        // make it read/write
        if (isUpdateInProgress()) {
            try {
                getSession().doWork(new Work() {
                    public void execute(Connection connection) throws SQLException {
                        if (connection.isReadOnly()) {
                            connection.setReadOnly(false);
                        }
                    }
                });
            } catch (HibernateException e) {
                throw new WGBackendException("unable to establish a read/write connection.", e);
            }
        }

        getSession().beginTransaction();
    } else {
        // perform at least a flush in this mode so JDBC driver will execute changes in current JDBC transaction
        getSession().flush();
    }
}

From source file:de.innovationgate.webgate.api.jdbc.WGDatabaseImpl.java

protected void rollbackHibernateTransaction(boolean noThrows) throws WGAPIException {

    if (getTransactionMode() != WGSessionContext.TRANSACTION_MODE_MANUAL) {

        try {//from  ww  w  . j av a 2  s. c o m
            Transaction trans = getSession().getTransaction();
            if (trans != null && trans.isActive()) {
                trans.rollback();
            }

            // hibernate might release the underlying jdbc connection after commit
            // and get a new one
            // this connection will be readonly by default - therefore we should
            // check if we have to
            // make it read/write
            if (isUpdateInProgress()) {
                try {
                    getSession().doWork(new Work() {
                        public void execute(Connection connection) throws SQLException {
                            if (connection.isReadOnly()) {
                                connection.setReadOnly(false);
                            }
                        }
                    });

                } catch (HibernateException e) {
                    throw new WGBackendException("unable to establish a read/write connection.", e);
                }
            }

            getSession().beginTransaction();
        } catch (Throwable e) {
            if (noThrows) {
                WGFactory.getLogger().error(
                        "Exception rolling back transaction. Cause for rollback may be logged after this exception.",
                        e);
            } else if (e instanceof WGBackendException) {
                throw (WGBackendException) e;
            } else if (e instanceof RuntimeException) {
                throw (RuntimeException) e;
            } else {
                throw new WGBackendException("Exception rolling back transaction", e);
            }
        }

    }

}

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

/**
 * Returns the photo of the contact identified by the given id or null if
 * not found./*from   ww  w. j ava  2  s . c om*/
 * @param id the contact id
 * @return the photo
 * @throws com.funambol.foundation.exception.DAOException if an error occurs
 */
public Photo getPhoto(Long id) throws DAOException {
    Connection conn = null;
    try {
        conn = getUserDataSource().getRoutedConnection(userId);
        conn.setReadOnly(true);

        return getPhoto(conn, id);
    } catch (Exception ex) {
        throw new DAOException("Error retrieving photo with id: " + id, ex);
    } finally {
        DBTools.close(conn, null, null);
    }
}

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

/**
 * Gets the contact with given UID, provided it has the same userId as this
 * DAO. The contact photo will be provide if <code>withPhoto</code> is true,
 * otherwise the contact is retrived without photo
 *
 * @param uid corresponds to the id field in the fnbl_pim_contact table
 * @param withPhoto should the contact contain its photo ?
 * @throws DAOException/*w  w  w  .j av  a2 s . c om*/
 * @return the contact as a ContactWrapper object.
 */
public ContactWrapper getItem(String uid, boolean withPhoto) throws DAOException {

    if (log.isTraceEnabled()) {
        log.trace("Retrieving contact '" + uid + "'");
    }

    Connection con = null;
    PreparedStatement ps = null;
    ResultSet rs = null;
    ContactWrapper c;

    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_CONTACT_BY_ID_USER);
        ps.setLong(1, id);
        ps.setString(2, userId);

        rs = ps.executeQuery();

        c = createContact(uid, rs);

        DBTools.close(null, ps, rs);

        ps = con.prepareStatement(SQL_GET_FNBL_PIM_CONTACT_ITEM_BY_ID);
        ps.setLong(1, id);

        rs = ps.executeQuery();

        try {
            addPIMContactItems(c, rs);
        } catch (SQLException sqle) {
            throw new SQLException(
                    "Error while adding extra PIM contact " + "information. " + sqle.getMessage(),
                    sqle.getSQLState());
        }

        DBTools.close(null, ps, rs);

        ps = con.prepareStatement(SQL_GET_FNBL_PIM_ADDRESS_BY_ID);
        ps.setLong(1, id);

        rs = ps.executeQuery();

        try {
            addPIMAddresses(c, rs);
        } catch (SQLException sqle) {
            throw new SQLException("Error while adding PIM address " + "information. " + sqle,
                    sqle.getSQLState());
        }

        if (withPhoto) {
            //if the photo type is null, there is nothing to do
            if (c.getPhotoType() != null) {
                if (ContactWrapper.PHOTO_IMAGE.equals(c.getPhotoType())
                        || ContactWrapper.PHOTO_URL.equals(c.getPhotoType())) {
                    Photo photo = getPhoto(con, id);
                    c.getContact().getPersonalDetail().setPhotoObject(photo);
                } else if (ContactWrapper.EMPTY_PHOTO.equals(c.getPhotoType())) {
                    c.getContact().getPersonalDetail().setPhotoObject(new Photo(null, null, null));
                }
            }
        }

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

    return c;
}

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

/**
 * Retrieves the UID list of the contacts considered to be "twins" of a
 * given contact.//from  w w  w. j  ava 2 s. co m
 *
 * @param c the Contact object representing the contact whose twins
 *          need to be found.
 * @return a List of UIDs (as String objects) that may be empty but not null
 * @throws DAOException if an error occurs
 */
public List<String> getTwinItems(Contact c) throws DAOException {
    if (log.isTraceEnabled()) {
        log.trace("Retrieving twin items for the given contact...");
    }

    List<String> twins = new ArrayList<String>();
    Map<Long, Map<Integer, String>> twinsFound = new HashMap<Long, Map<Integer, String>>();

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

    if (!isTwinSearchAppliableOn(c)) {
        if (log.isTraceEnabled()) {
            log.trace("Item with no email addresses, company name, first, "
                    + "last and display names: twin search skipped.");
        }
        return twins;
    }

    try {

        String firstName = c.getName().getFirstName().getPropertyValueAsString();
        String lastName = c.getName().getLastName().getPropertyValueAsString();
        String displayName = c.getName().getDisplayName().getPropertyValueAsString();
        String companyName = null;
        if (c.getBusinessDetail().getCompany() != null) {
            companyName = c.getBusinessDetail().getCompany().getPropertyValueAsString();
        }

        firstName = StringUtils.left(firstName, SQL_FIRSTNAME_DIM);
        lastName = StringUtils.left(lastName, SQL_LASTNAME_DIM);
        displayName = StringUtils.left(displayName, SQL_DISPLAYNAME_DIM);
        companyName = StringUtils.left(companyName, SQL_COMPANY_DIM);
        firstName = normalizeField(firstName);
        lastName = normalizeField(lastName);
        displayName = normalizeField(displayName);
        companyName = normalizeField(companyName);

        StringBuilder query = new StringBuilder(SQL_GET_POTENTIAL_TWINS);
        List<String> params = new ArrayList<String>();

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

        //
        // If Funambol is not in the debug mode is not possible to print the
        // contact because it contains sensitive data.
        //
        if (Configuration.getConfiguration().isDebugMode()) {
            if (log.isTraceEnabled()) {
                StringBuilder sb = new StringBuilder(100);
                sb.append("Looking for items having: ").append("\n> first name   : '")
                        .append(toPrintableString(firstName)).append('\'').append("\n> last  name   : '")
                        .append(toPrintableString(lastName)).append('\'').append("\n> display name : '")
                        .append(toPrintableString(displayName)).append('\'').append("\n> company name : '")
                        .append(toPrintableString(companyName)).append('\'');

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

        boolean isUnnamedContact = StringUtils.isEmpty(firstName) && StringUtils.isEmpty(lastName)
                && StringUtils.isEmpty(displayName) && StringUtils.isEmpty(companyName);

        if (isUnnamedContact) {

            if (unnamedContacts == null) {

                query.append(SQL_UNNAMED_WHERE_CLAUSES);
                query.append(SQL_STATUS_NOT_D);
                query.append(SQL_ORDER_BY_ID);

                params.add(userId);
                params.add(firstName);
                params.add(lastName);
                params.add(companyName);
                params.add(displayName);

                ps = con.prepareStatement(query.toString());

                int cont = 1;
                for (String param : params) {
                    ps.setString(cont++, param);
                }

                rs = ps.executeQuery();

                //slipts query result in a better organized data structure
                //-contact id
                //  -item type, item value
                //  -item type, item value
                //  -...
                //-contact id
                //  -...
                unnamedContacts = getTwinsItemsFromRecordset(rs);

                if (log.isTraceEnabled()) {
                    log.trace(
                            "Found '" + unnamedContacts.size() + "' potential twin unnamed contacts with ids '"
                                    + unnamedContacts.keySet().toString() + "'");
                }
                DBTools.close(null, null, rs);
            }

            // returns only the twin items
            twinsFound = retrievePotentialTwinsComparingEmailsAndPhoneNumbers(c, unnamedContacts,
                    isUnnamedContact);

        } else {

            params.add(userId);

            query.append(" AND (");
            if ("".equals(firstName)) {
                query.append(" (c.first_name is null) OR ");
            }
            query.append(" (lower(c.first_name) = ?) ");
            params.add(firstName.toLowerCase());
            query.append(" )");

            query.append(" AND (");
            if ("".equals(lastName)) {
                query.append(" (c.last_name is null) OR ");
            }
            query.append(" (lower(c.last_name) = ?) ");
            params.add(lastName.toLowerCase());
            query.append(" )");
            //
            // Only if the first name and last name are empty,
            // the company is used in the research of twin items.
            //                
            if ("".equals(firstName) && "".equals(lastName)) {

                query.append(" AND (");

                if ("".equals(companyName)) {
                    query.append(" (c.company is null) OR ");
                }
                query.append(" (lower(c.company) = ?) ");
                params.add(companyName.toLowerCase());
                query.append(" )");

                //
                // Only if the first name, last name and company are empty,
                // the display name is used in the research of twin items.
                //
                if ("".equals(companyName)) {

                    query.append(" AND (");
                    if ("".equals(displayName)) {
                        query.append(" (c.display_name is null) OR ");
                    }
                    query.append(" (lower(c.display_name) = ?) ");
                    params.add(displayName.toLowerCase());
                    query.append(" ) ");
                }
            }

            query.append(SQL_STATUS_NOT_D);
            query.append(SQL_ORDER_BY_ID);

            ps = con.prepareStatement(query.toString());

            int cont = 1;
            for (String param : params) {
                ps.setString(cont++, param);
            }

            rs = ps.executeQuery();

            //slipts query result in a better organized data structure
            //-contact id
            //  -item type, item value
            //  -item type, item value
            //  -...
            //-contact id
            //  -...
            Map<Long, Map<Integer, String>> twinsInfo = getTwinsItemsFromRecordset(rs);

            if (log.isTraceEnabled()) {
                log.trace("Found '" + twinsInfo.size() + "' potential twin contacts with ids '"
                        + twinsInfo.keySet().toString() + "'");
            }
            DBTools.close(null, null, rs);

            //returns only the twin items
            twinsFound = retrievePotentialTwinsComparingEmailsAndPhoneNumbers(c, twinsInfo, isUnnamedContact);
        }

        for (Long twinId : twinsFound.keySet()) {
            if (log.isTraceEnabled()) {
                log.trace("Found twin '" + twinId + "'");
            }
            twins.add(Long.toString(twinId));
        }

    } catch (Exception e) {
        throw new DAOException("Error retrieving contact twin items", e);
    } finally {
        DBTools.close(con, ps, rs);
    }

    return twins;
}

From source file:net.xy.jcms.controller.configurations.parser.TranslationDBConnector.java

/**
 * constructor needs db connection to retrieve translation rules
 * /*from   w w  w.  j  a va 2  s.c  o  m*/
 * @param connection
 *            will be set to readonly
 * @param parentLoader
 * @throws SQLException
 */
public TranslationDBConnector(final Connection connection, final ClassLoader parentLoader) throws SQLException {
    this.connection = connection;
    this.parentLoader = parentLoader;
    connection.setReadOnly(true);
}

From source file:net.xy.jcms.controller.configurations.parser.UsecaseDBConnector.java

/**
 * constructor needs db connection to retrieve usescases
 * /*from   w w  w  .jav  a  2 s .co  m*/
 * @param connection
 *            will be set to readonly
 * @param parentLoader
 *            to load common classes to all usecases
 * @throws SQLException
 */
public UsecaseDBConnector(final Connection connection, final ClassLoader parentLoader) throws SQLException {
    this.connection = connection;
    this.parentLoader = parentLoader;
    connection.setReadOnly(true);
}

From source file:org.apache.calcite.avatica.jdbc.JdbcMeta.java

protected void apply(Connection conn, ConnectionProperties connProps) throws SQLException {
    if (connProps.isAutoCommit() != null) {
        conn.setAutoCommit(connProps.isAutoCommit());
    }/*from  w  w w.  j av  a 2  s.c  o  m*/
    if (connProps.isReadOnly() != null) {
        conn.setReadOnly(connProps.isReadOnly());
    }
    if (connProps.getTransactionIsolation() != null) {
        conn.setTransactionIsolation(connProps.getTransactionIsolation());
    }
    if (connProps.getCatalog() != null) {
        conn.setCatalog(connProps.getCatalog());
    }
    if (connProps.getSchema() != null) {
        conn.setSchema(connProps.getSchema());
    }
}