Search in sources :

Example 46 with DataAccessException

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

the class MongoTemplate method executeCommand.

/*
	 * (non-Javadoc)
	 * @see org.springframework.data.mongodb.core.MongoOperations#executeCommand(org.bson.Document, com.mongodb.ReadPreference)
	 */
@Override
public Document executeCommand(Document command, @Nullable ReadPreference readPreference) {
    Assert.notNull(command, "Command must not be null!");
    Document result = execute(new DbCallback<Document>() {

        public Document doInDB(MongoDatabase db) throws MongoException, DataAccessException {
            return readPreference != null ? db.runCommand(command, readPreference, Document.class) : db.runCommand(command, Document.class);
        }
    });
    return result;
}
Also used : MongoException(com.mongodb.MongoException) Document(org.bson.Document) DataAccessException(org.springframework.dao.DataAccessException) MongoDatabase(com.mongodb.client.MongoDatabase)

Example 47 with DataAccessException

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

the class GeoJsonTests method shouldConvertPointRepresentationCorrectlyWhenSourceCoordinatesUsesInteger.

// DATAMONGO-1453
@Test
public void shouldConvertPointRepresentationCorrectlyWhenSourceCoordinatesUsesInteger() {
    this.template.execute(template.getCollectionName(DocumentWithPropertyUsingGeoJsonType.class), new CollectionCallback<Object>() {

        @Override
        public Object doInCollection(MongoCollection<org.bson.Document> collection) throws MongoException, DataAccessException {
            org.bson.Document pointRepresentation = new org.bson.Document();
            pointRepresentation.put("type", "Point");
            pointRepresentation.put("coordinates", new BasicDbListBuilder().add(0).add(0).get());
            org.bson.Document document = new org.bson.Document();
            document.append("_id", "datamongo-1453");
            document.append("geoJsonPoint", pointRepresentation);
            collection.insertOne(document);
            return document;
        }
    });
    assertThat(template.findOne(query(where("id").is("datamongo-1453")), DocumentWithPropertyUsingGeoJsonType.class).geoJsonPoint, is(equalTo(new GeoJsonPoint(0D, 0D))));
}
Also used : MongoException(com.mongodb.MongoException) BasicDbListBuilder(org.springframework.data.mongodb.test.util.BasicDbListBuilder) DataAccessException(org.springframework.dao.DataAccessException) Test(org.junit.Test)

Example 48 with DataAccessException

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

the class MongoTemplateUnitTests method sortShouldBeTakenAsIsWhenExecutingQueryWithoutSpecificTypeInformation.

// DATAMONGO-948
@Test
public void sortShouldBeTakenAsIsWhenExecutingQueryWithoutSpecificTypeInformation() {
    Query query = Query.query(Criteria.where("foo").is("bar")).with(Sort.by("foo"));
    template.executeQuery(query, "collection1", new DocumentCallbackHandler() {

        @Override
        public void processDocument(Document document) throws MongoException, DataAccessException {
        // nothing to do - just a test
        }
    });
    ArgumentCaptor<org.bson.Document> captor = ArgumentCaptor.forClass(org.bson.Document.class);
    verify(findIterable, times(1)).sort(captor.capture());
    assertThat(captor.getValue(), equalTo(new org.bson.Document("foo", 1)));
}
Also used : MongoException(com.mongodb.MongoException) BasicQuery(org.springframework.data.mongodb.core.query.BasicQuery) NearQuery(org.springframework.data.mongodb.core.query.NearQuery) Query(org.springframework.data.mongodb.core.query.Query) Document(org.bson.Document) DataAccessException(org.springframework.dao.DataAccessException) Test(org.junit.Test)

Example 49 with DataAccessException

use of org.springframework.dao.DataAccessException in project cas by apereo.

the class QueryDatabaseAuthenticationHandler method authenticateUsernamePasswordInternal.

@Override
protected AuthenticationHandlerExecutionResult authenticateUsernamePasswordInternal(final UsernamePasswordCredential credential, final String originalPassword) throws GeneralSecurityException, PreventedException {
    if (StringUtils.isBlank(this.sql) || getJdbcTemplate() == null) {
        throw new GeneralSecurityException("Authentication handler is not configured correctly. " + "No SQL statement or JDBC template is found.");
    }
    final Map<String, Object> attributes = new LinkedHashMap<>(this.principalAttributeMap.size());
    final String username = credential.getUsername();
    final String password = credential.getPassword();
    try {
        final Map<String, Object> dbFields = getJdbcTemplate().queryForMap(this.sql, username);
        final String dbPassword = (String) dbFields.get(this.fieldPassword);
        if ((StringUtils.isNotBlank(originalPassword) && !matches(originalPassword, dbPassword)) || (StringUtils.isBlank(originalPassword) && !StringUtils.equals(password, dbPassword))) {
            throw new FailedLoginException("Password does not match value on record.");
        }
        if (StringUtils.isNotBlank(this.fieldDisabled)) {
            final Object dbDisabled = dbFields.get(this.fieldDisabled);
            if (dbDisabled != null && (Boolean.TRUE.equals(BooleanUtils.toBoolean(dbDisabled.toString())) || dbDisabled.equals(Integer.valueOf(1)))) {
                throw new AccountDisabledException("Account has been disabled");
            }
        }
        if (StringUtils.isNotBlank(this.fieldExpired)) {
            final Object dbExpired = dbFields.get(this.fieldExpired);
            if (dbExpired != null && (Boolean.TRUE.equals(BooleanUtils.toBoolean(dbExpired.toString())) || dbExpired.equals(1))) {
                throw new AccountPasswordMustChangeException("Password has expired");
            }
        }
        this.principalAttributeMap.forEach((key, names) -> {
            final Object attribute = dbFields.get(key);
            if (attribute != null) {
                LOGGER.debug("Found attribute [{}] from the query results", key);
                final Collection<String> attributeNames = (Collection<String>) names;
                attributeNames.forEach(s -> {
                    LOGGER.debug("Principal attribute [{}] is virtually remapped/renamed to [{}]", key, s);
                    attributes.put(s, CollectionUtils.wrap(attribute.toString()));
                });
            } else {
                LOGGER.warn("Requested attribute [{}] could not be found in the query results", key);
            }
        });
    } catch (final IncorrectResultSizeDataAccessException e) {
        if (e.getActualSize() == 0) {
            throw new AccountNotFoundException(username + " not found with SQL query");
        }
        throw new FailedLoginException("Multiple records found for " + username);
    } catch (final DataAccessException e) {
        throw new PreventedException("SQL exception while executing query for " + username, e);
    }
    return createHandlerResult(credential, this.principalFactory.createPrincipal(username, attributes), new ArrayList<>(0));
}
Also used : GeneralSecurityException(java.security.GeneralSecurityException) LinkedHashMap(java.util.LinkedHashMap) FailedLoginException(javax.security.auth.login.FailedLoginException) IncorrectResultSizeDataAccessException(org.springframework.dao.IncorrectResultSizeDataAccessException) Collection(java.util.Collection) PreventedException(org.apereo.cas.authentication.PreventedException) AccountPasswordMustChangeException(org.apereo.cas.authentication.exceptions.AccountPasswordMustChangeException) AccountNotFoundException(javax.security.auth.login.AccountNotFoundException) AccountDisabledException(org.apereo.cas.authentication.exceptions.AccountDisabledException) DataAccessException(org.springframework.dao.DataAccessException) IncorrectResultSizeDataAccessException(org.springframework.dao.IncorrectResultSizeDataAccessException)

Example 50 with DataAccessException

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

the class PipelineRepositoryTest method stubPipelineInstancesInDb.

private void stubPipelineInstancesInDb(Object[]... rows) {
    pipelineRepository.setHibernateTemplate(new HibernateTemplate() {

        @Override
        public <T> T execute(HibernateCallback<T> action) throws DataAccessException {
            try {
                return action.doInHibernate(session);
            } catch (SQLException e) {
                throw new RuntimeException();
            }
        }
    });
    when(session.createSQLQuery(anyString())).thenReturn(sqlQuery);
    when(sqlQuery.list()).thenReturn(Arrays.asList(rows));
}
Also used : SQLException(java.sql.SQLException) HibernateTemplate(org.springframework.orm.hibernate3.HibernateTemplate) DataAccessException(org.springframework.dao.DataAccessException)

Aggregations

DataAccessException (org.springframework.dao.DataAccessException)89 SQLException (java.sql.SQLException)40 Test (org.junit.Test)26 Connection (java.sql.Connection)17 ResultSet (java.sql.ResultSet)16 PreparedStatement (java.sql.PreparedStatement)14 MongoException (com.mongodb.MongoException)13 Document (org.bson.Document)8 TransactionStatus (org.springframework.transaction.TransactionStatus)7 HashMap (java.util.HashMap)6 DataIntegrityViolationException (org.springframework.dao.DataIntegrityViolationException)5 DeadlockLoserDataAccessException (org.springframework.dao.DeadlockLoserDataAccessException)5 IOException (java.io.IOException)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