Search in sources :

Example 6 with DataAccessException

use of org.springframework.dao.DataAccessException in project jOOQ by jOOQ.

the class TransactionTest method testjOOQTransactionsNested.

@Test
public void testjOOQTransactionsNested() {
    AtomicBoolean rollback1 = new AtomicBoolean(false);
    AtomicBoolean rollback2 = new AtomicBoolean(false);
    try {
        // If using Spring transactions, we don't need the c1 reference
        dsl.transaction(c1 -> {
            dsl.insertInto(BOOK).set(BOOK.ID, 5).set(BOOK.AUTHOR_ID, 1).set(BOOK.TITLE, "Book 5").execute();
            assertEquals(5, dsl.fetchCount(BOOK));
            try {
                dsl.transaction(c2 -> {
                    for (int i = 0; i < 2; i++) dsl.insertInto(BOOK).set(BOOK.ID, 6).set(BOOK.AUTHOR_ID, 1).set(BOOK.TITLE, "Book 6").execute();
                    Assert.fail();
                });
            } catch (DataAccessException e) {
                rollback1.set(true);
            }
            assertEquals(5, dsl.fetchCount(BOOK));
            throw new org.jooq.exception.DataAccessException("Rollback");
        });
    }// Upon the constraint violation, the transaction must already have been rolled back
     catch (org.jooq.exception.DataAccessException e) {
        assertEquals("Rollback", e.getMessage());
        rollback2.set(true);
    }
    assertEquals(4, dsl.fetchCount(BOOK));
    assertTrue(rollback2.get());
    assertTrue(rollback2.get());
}
Also used : AtomicBoolean(java.util.concurrent.atomic.AtomicBoolean) DataAccessException(org.springframework.dao.DataAccessException) Test(org.junit.Test)

Example 7 with DataAccessException

use of org.springframework.dao.DataAccessException in project hudson-2.x by hudson.

the class LDAPSecurityRealm method loadGroupByGroupname.

/**
     * Lookup a group; given input must match the configured syntax for group names
     * in WEB-INF/security/LDAPBindSecurityRealm.groovy's authoritiesPopulator entry.
     * The defaults are a prefix of "ROLE_" and using all uppercase.  This method will
     * not return any data if the given name lacks the proper prefix and/or case. 
     */
@Override
public GroupDetails loadGroupByGroupname(String groupname) throws UsernameNotFoundException, DataAccessException {
    // Check proper syntax based on acegi configuration
    String prefix = "";
    boolean onlyUpperCase = false;
    try {
        AuthoritiesPopulatorImpl api = (AuthoritiesPopulatorImpl) ((LDAPUserDetailsService) getSecurityComponents().userDetails).authoritiesPopulator;
        prefix = api.rolePrefix;
        onlyUpperCase = api.convertToUpperCase;
    } catch (Exception ignore) {
    }
    if (onlyUpperCase && !groupname.equals(groupname.toUpperCase()))
        throw new UsernameNotFoundException(groupname + " should be all uppercase");
    if (!groupname.startsWith(prefix))
        throw new UsernameNotFoundException(groupname + " is missing prefix: " + prefix);
    groupname = groupname.substring(prefix.length());
    // TODO: obtain a DN instead so that we can obtain multiple attributes later
    String searchBase = groupSearchBase != null ? groupSearchBase : "";
    final Set<String> groups = (Set<String>) ldapTemplate.searchForSingleAttributeValues(searchBase, GROUP_SEARCH, new String[] { groupname }, "cn");
    if (groups.isEmpty())
        throw new UsernameNotFoundException(groupname);
    return new GroupDetails() {

        public String getName() {
            return groups.iterator().next();
        }
    };
}
Also used : UsernameNotFoundException(org.acegisecurity.userdetails.UsernameNotFoundException) Set(java.util.Set) NamingException(javax.naming.NamingException) AuthenticationException(org.acegisecurity.AuthenticationException) LdapDataAccessException(org.acegisecurity.ldap.LdapDataAccessException) UsernameNotFoundException(org.acegisecurity.userdetails.UsernameNotFoundException) DataAccessException(org.springframework.dao.DataAccessException) AcegiSecurityException(org.acegisecurity.AcegiSecurityException) IOException(java.io.IOException) UnknownHostException(java.net.UnknownHostException)

Example 8 with DataAccessException

use of org.springframework.dao.DataAccessException in project hudson-2.x by hudson.

the class PAMSecurityRealm method createSecurityComponents.

public SecurityComponents createSecurityComponents() {
    Binding binding = new Binding();
    binding.setVariable("instance", this);
    BeanBuilder builder = new BeanBuilder();
    builder.parse(Hudson.getInstance().servletContext.getResourceAsStream("/WEB-INF/security/PAMSecurityRealm.groovy"), binding);
    WebApplicationContext context = builder.createApplicationContext();
    return new SecurityComponents(findBean(AuthenticationManager.class, context), new UserDetailsService() {

        public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException, DataAccessException {
            if (!UnixUser.exists(username))
                throw new UsernameNotFoundException("No such Unix user: " + username);
            // return some dummy instance
            return new User(username, "", true, true, true, true, new GrantedAuthority[] { AUTHENTICATED_AUTHORITY });
        }
    });
}
Also used : Binding(groovy.lang.Binding) BeanBuilder(hudson.util.spring.BeanBuilder) AuthenticationManager(org.acegisecurity.AuthenticationManager) UsernameNotFoundException(org.acegisecurity.userdetails.UsernameNotFoundException) UserDetails(org.acegisecurity.userdetails.UserDetails) UnixUser(org.jvnet.libpam.UnixUser) User(org.acegisecurity.userdetails.User) GrantedAuthority(org.acegisecurity.GrantedAuthority) UserDetailsService(org.acegisecurity.userdetails.UserDetailsService) DataAccessException(org.springframework.dao.DataAccessException) WebApplicationContext(org.springframework.web.context.WebApplicationContext)

Example 9 with DataAccessException

use of org.springframework.dao.DataAccessException in project spring-framework by spring-projects.

the class AbstractFallbackSQLExceptionTranslator method translate.

/**
	 * Pre-checks the arguments, calls {@link #doTranslate}, and invokes the
	 * {@link #getFallbackTranslator() fallback translator} if necessary.
	 */
@Override
public DataAccessException translate(String task, String sql, SQLException ex) {
    Assert.notNull(ex, "Cannot translate a null SQLException");
    if (task == null) {
        task = "";
    }
    if (sql == null) {
        sql = "";
    }
    DataAccessException dex = doTranslate(task, sql, ex);
    if (dex != null) {
        // Specific exception match found.
        return dex;
    }
    // Looking for a fallback...
    SQLExceptionTranslator fallback = getFallbackTranslator();
    if (fallback != null) {
        return fallback.translate(task, sql, ex);
    }
    // We couldn't identify it more precisely.
    return new UncategorizedSQLException(task, sql, ex);
}
Also used : UncategorizedSQLException(org.springframework.jdbc.UncategorizedSQLException) DataAccessException(org.springframework.dao.DataAccessException)

Example 10 with DataAccessException

use of org.springframework.dao.DataAccessException in project spring-framework by spring-projects.

the class SQLErrorCodeSQLExceptionTranslator method doTranslate.

@Override
protected DataAccessException doTranslate(String task, String sql, SQLException ex) {
    SQLException sqlEx = ex;
    if (sqlEx instanceof BatchUpdateException && sqlEx.getNextException() != null) {
        SQLException nestedSqlEx = sqlEx.getNextException();
        if (nestedSqlEx.getErrorCode() > 0 || nestedSqlEx.getSQLState() != null) {
            logger.debug("Using nested SQLException from the BatchUpdateException");
            sqlEx = nestedSqlEx;
        }
    }
    // First, try custom translation from overridden method.
    DataAccessException dex = customTranslate(task, sql, sqlEx);
    if (dex != null) {
        return dex;
    }
    // Next, try the custom SQLException translator, if available.
    if (this.sqlErrorCodes != null) {
        SQLExceptionTranslator customTranslator = this.sqlErrorCodes.getCustomSqlExceptionTranslator();
        if (customTranslator != null) {
            DataAccessException customDex = customTranslator.translate(task, sql, sqlEx);
            if (customDex != null) {
                return customDex;
            }
        }
    }
    // Check SQLErrorCodes with corresponding error code, if available.
    if (this.sqlErrorCodes != null) {
        String errorCode;
        if (this.sqlErrorCodes.isUseSqlStateForTranslation()) {
            errorCode = sqlEx.getSQLState();
        } else {
            // Try to find SQLException with actual error code, looping through the causes.
            // E.g. applicable to java.sql.DataTruncation as of JDK 1.6.
            SQLException current = sqlEx;
            while (current.getErrorCode() == 0 && current.getCause() instanceof SQLException) {
                current = (SQLException) current.getCause();
            }
            errorCode = Integer.toString(current.getErrorCode());
        }
        if (errorCode != null) {
            // Look for defined custom translations first.
            CustomSQLErrorCodesTranslation[] customTranslations = this.sqlErrorCodes.getCustomTranslations();
            if (customTranslations != null) {
                for (CustomSQLErrorCodesTranslation customTranslation : customTranslations) {
                    if (Arrays.binarySearch(customTranslation.getErrorCodes(), errorCode) >= 0) {
                        if (customTranslation.getExceptionClass() != null) {
                            DataAccessException customException = createCustomException(task, sql, sqlEx, customTranslation.getExceptionClass());
                            if (customException != null) {
                                logTranslation(task, sql, sqlEx, true);
                                return customException;
                            }
                        }
                    }
                }
            }
            // Next, look for grouped error codes.
            if (Arrays.binarySearch(this.sqlErrorCodes.getBadSqlGrammarCodes(), errorCode) >= 0) {
                logTranslation(task, sql, sqlEx, false);
                return new BadSqlGrammarException(task, sql, sqlEx);
            } else if (Arrays.binarySearch(this.sqlErrorCodes.getInvalidResultSetAccessCodes(), errorCode) >= 0) {
                logTranslation(task, sql, sqlEx, false);
                return new InvalidResultSetAccessException(task, sql, sqlEx);
            } else if (Arrays.binarySearch(this.sqlErrorCodes.getDuplicateKeyCodes(), errorCode) >= 0) {
                logTranslation(task, sql, sqlEx, false);
                return new DuplicateKeyException(buildMessage(task, sql, sqlEx), sqlEx);
            } else if (Arrays.binarySearch(this.sqlErrorCodes.getDataIntegrityViolationCodes(), errorCode) >= 0) {
                logTranslation(task, sql, sqlEx, false);
                return new DataIntegrityViolationException(buildMessage(task, sql, sqlEx), sqlEx);
            } else if (Arrays.binarySearch(this.sqlErrorCodes.getPermissionDeniedCodes(), errorCode) >= 0) {
                logTranslation(task, sql, sqlEx, false);
                return new PermissionDeniedDataAccessException(buildMessage(task, sql, sqlEx), sqlEx);
            } else if (Arrays.binarySearch(this.sqlErrorCodes.getDataAccessResourceFailureCodes(), errorCode) >= 0) {
                logTranslation(task, sql, sqlEx, false);
                return new DataAccessResourceFailureException(buildMessage(task, sql, sqlEx), sqlEx);
            } else if (Arrays.binarySearch(this.sqlErrorCodes.getTransientDataAccessResourceCodes(), errorCode) >= 0) {
                logTranslation(task, sql, sqlEx, false);
                return new TransientDataAccessResourceException(buildMessage(task, sql, sqlEx), sqlEx);
            } else if (Arrays.binarySearch(this.sqlErrorCodes.getCannotAcquireLockCodes(), errorCode) >= 0) {
                logTranslation(task, sql, sqlEx, false);
                return new CannotAcquireLockException(buildMessage(task, sql, sqlEx), sqlEx);
            } else if (Arrays.binarySearch(this.sqlErrorCodes.getDeadlockLoserCodes(), errorCode) >= 0) {
                logTranslation(task, sql, sqlEx, false);
                return new DeadlockLoserDataAccessException(buildMessage(task, sql, sqlEx), sqlEx);
            } else if (Arrays.binarySearch(this.sqlErrorCodes.getCannotSerializeTransactionCodes(), errorCode) >= 0) {
                logTranslation(task, sql, sqlEx, false);
                return new CannotSerializeTransactionException(buildMessage(task, sql, sqlEx), sqlEx);
            }
        }
    }
    // We couldn't identify it more precisely - let's hand it over to the SQLState fallback translator.
    if (logger.isDebugEnabled()) {
        String codes;
        if (this.sqlErrorCodes != null && this.sqlErrorCodes.isUseSqlStateForTranslation()) {
            codes = "SQL state '" + sqlEx.getSQLState() + "', error code '" + sqlEx.getErrorCode();
        } else {
            codes = "Error code '" + sqlEx.getErrorCode() + "'";
        }
        logger.debug("Unable to translate SQLException with " + codes + ", will now try the fallback translator");
    }
    return null;
}
Also used : BadSqlGrammarException(org.springframework.jdbc.BadSqlGrammarException) TransientDataAccessResourceException(org.springframework.dao.TransientDataAccessResourceException) CannotAcquireLockException(org.springframework.dao.CannotAcquireLockException) SQLException(java.sql.SQLException) DataAccessResourceFailureException(org.springframework.dao.DataAccessResourceFailureException) PermissionDeniedDataAccessException(org.springframework.dao.PermissionDeniedDataAccessException) InvalidResultSetAccessException(org.springframework.jdbc.InvalidResultSetAccessException) DuplicateKeyException(org.springframework.dao.DuplicateKeyException) DataIntegrityViolationException(org.springframework.dao.DataIntegrityViolationException) CannotSerializeTransactionException(org.springframework.dao.CannotSerializeTransactionException) DeadlockLoserDataAccessException(org.springframework.dao.DeadlockLoserDataAccessException) DataAccessException(org.springframework.dao.DataAccessException) DeadlockLoserDataAccessException(org.springframework.dao.DeadlockLoserDataAccessException) PermissionDeniedDataAccessException(org.springframework.dao.PermissionDeniedDataAccessException) BatchUpdateException(java.sql.BatchUpdateException)

Aggregations

DataAccessException (org.springframework.dao.DataAccessException)73 SQLException (java.sql.SQLException)40 Test (org.junit.Test)20 Connection (java.sql.Connection)17 ResultSet (java.sql.ResultSet)16 PreparedStatement (java.sql.PreparedStatement)14 TransactionStatus (org.springframework.transaction.TransactionStatus)7 HashMap (java.util.HashMap)6 DeadlockLoserDataAccessException (org.springframework.dao.DeadlockLoserDataAccessException)5 IncorrectResultSizeDataAccessException (org.springframework.dao.IncorrectResultSizeDataAccessException)5 IOException (java.io.IOException)4 EmptyResultDataAccessException (org.springframework.dao.EmptyResultDataAccessException)4 ConnectionCallback (org.springframework.jdbc.core.ConnectionCallback)4 SpringSqlParams (com.opengamma.elsql.SpringSqlParams)3 DatabaseMetaData (java.sql.DatabaseMetaData)3 Statement (java.sql.Statement)3 ArrayList (java.util.ArrayList)3 List (java.util.List)3 IJoinQueryString (org.apereo.portal.jdbc.IJoinQueryString)3 DataIntegrityViolationException (org.springframework.dao.DataIntegrityViolationException)3