/** * Return the DirContextOperations containing the user's information * * @param dn full DN of the user to search for. * * @return An DirContextOperations object containing the details of the located user's * directory entry * * @throws UsernameNotFoundException if no matching entry is found. */ @Override public DirContextOperations searchForUser(String dn) { log.debug("Searching for dn '{}'.", dn); SpringSecurityLdapTemplate template = new SpringSecurityLdapTemplate(getContextSource()); template.setSearchControls(getSearchControls()); try { return template.retrieveEntry(dn, null); } catch (IncorrectResultSizeDataAccessException ex) { if (ex.getActualSize() == 0) { throw new UsernameNotFoundException("User " + dn + " not found in directory."); } // Search should never return multiple results if properly configured, so just rethrow throw ex; } }
@Test public void testOptional() { Optional<SimpleEntity> optional = repository.findByNumberBetweenOrderByHero(9, 11); Assert.assertTrue(optional.isPresent()); Assert.assertEquals(new Long(4), optional.get().getId()); optional = repository.findByNumberBetweenOrderByHero(1234, 2000); Assert.assertFalse(optional.isPresent()); try { repository.findByNumberBetweenOrderByHero(-5, 15); Assert.fail(); } catch (Exception e) { Assert.assertEquals(IncorrectResultSizeDataAccessException.class, e.getClass()); } }
@Override public TermResult getTerm(String fullTermPath) { List<TermResult> trs = executeListQuery(queryGetTerm, Collections.singletonMap("term", fullTermPath)); if( Check.isEmpty(trs) ) { return null; } else if( trs.size() == 1 ) { return trs.get(0); } else { // Sanity check - ensure only a single result throw new IncorrectResultSizeDataAccessException(1); } }
private Object executeSingleResultQuery(String query, Map<?, ?> params) { return jdbcTemplate.query(query, params, new ResultSetExtractor() { @Override public Object extractData(ResultSet rs) throws SQLException, DataAccessException { Object data = null; if( rs.next() ) { data = rs.getObject(1); // Sanity check - ensure only a single result if( rs.next() ) { throw new IncorrectResultSizeDataAccessException(1); } } return data; } }); }
@Test public void withEquivalentIntegerInstanceTwice() { Collection<Integer> col = new ArrayList<Integer>(2); col.add(new Integer(5)); col.add(new Integer(5)); try { DataAccessUtils.uniqueResult(col); fail("Should have thrown IncorrectResultSizeDataAccessException"); } catch (IncorrectResultSizeDataAccessException ex) { // expected assertEquals(1, ex.getExpectedSize()); assertEquals(2, ex.getActualSize()); } }
private DirContextOperations searchForUser(DirContext context, String username) throws NamingException { SearchControls searchControls = new SearchControls(); searchControls.setSearchScope(SearchControls.SUBTREE_SCOPE); String bindPrincipal = createBindPrincipalDomainAlias(username); String searchRoot = rootDn != null ? rootDn : searchRootFromPrincipal(bindPrincipal); try { return SpringSecurityLdapTemplate.searchForSingleEntryInternal(context, searchControls, searchRoot, searchFilter, new Object[] { bindPrincipal }); } catch (IncorrectResultSizeDataAccessException incorrectResults) { // Search should never return multiple results if properly configured - just // rethrow if (incorrectResults.getActualSize() != 0) { throw incorrectResults; } // If we found no results, then the username/password did not match UsernameNotFoundException userNameNotFoundException = new UsernameNotFoundException( "User " + username + " not found in directory.", incorrectResults); throw badCredentials(userNameNotFoundException); } }
@Test(expected = IncorrectResultSizeDataAccessException.class) @SuppressWarnings("serial") public void testGetAnnotationCollectionByIdTwo() { W3CAnnotationCollection w3cAnnotationCollection = generateRandomW3CAnnotationCollection(); String collectionId = w3cAnnotationCollection.getCollectionId(); Object[] params = {collectionId, false}; int[] sqlTypes = {Types.VARCHAR, Types.BOOLEAN}; when(jdbcTemplate.query(anyString(), aryEq(params), aryEq(sqlTypes), (W3CAnnotationCollectionRowMapper) any())).thenReturn(new ArrayList<W3CAnnotationCollection>() { { add(w3cAnnotationCollection); add(w3cAnnotationCollection); } }); annotationCollectionStoreRepository.getAnnotationCollectionById(collectionId); }
@SuppressWarnings("serial") @Test(expected = IncorrectResultSizeDataAccessException.class) public void testGetAnnotationByCollectionIdAndAnnotationIdTwo() { W3CAnnotation w3cAnnotation = generateRandomW3CAnnotation(); String collectionId = generateRandomId(); String annotationId = generateRandomId(); Object[] params = {collectionId, annotationId, false}; int[] sqlTypes = {Types.VARCHAR, Types.VARCHAR, Types.BOOLEAN}; when(jdbcTemplate.query(anyString(), aryEq(params), aryEq(sqlTypes), (W3CAnnotationRowMapper) any())).thenReturn(new ArrayList<W3CAnnotation>() { { add(w3cAnnotation); add(w3cAnnotation); } }); annotationStoreRepository.getAnnotationByCollectionIdAndAnnotationId(collectionId, annotationId); }
@Override public <T> T findObjectBySearch(Class<T> type, Map<String, String> formProps) { // This is the strictly Lookup-compatible way of constructing the criteria // from a map of properties, which performs some minor logic such as only including // non-blank and "writable" properties, as well as minor type coercions of string values QueryByCriteria.Builder queryByCriteria = lookupCriteriaGenerator.createObjectCriteriaFromMap(type, formProps); List<T> results = dataObjectService.findMatching(type, queryByCriteria.build()).getResults(); if (results.isEmpty()) { return null; } if (results.size() != 1) { // this behavior is different from the legacy OJB behavior in that it throws an exception if more than // one result from such a single object query throw new IncorrectResultSizeDataAccessException("Incorrect number of results returned when finding object", 1, results.size()); } return results.get(0); }
@Test(expected = IncorrectResultSizeDataAccessException.class) public void testFindUnique_TooManyResults() { QueryByCriteria criteria = QueryByCriteria.Builder.create().build(); // create results that contains multiple objects Object result1 = new Object(); Object result2 = new Object(); GenericQueryResults.Builder<Object> resultsBuilder = GenericQueryResults.Builder.<Object>create(); resultsBuilder.setResults(Lists.newArrayList(result1, result2)); QueryResults<Object> results = resultsBuilder.build(); when(mockProvider.findMatching(Object.class, criteria)).thenReturn(results); // now when we invoke this, we should get the data access exception // (see the "expected" exception on the @Test annotation) service.findUnique(Object.class, criteria); }
/** * * @param username Set the username * @param newPassword Set the new password */ @Transactional(readOnly = false) public final void changePasswordForUser(final String username, final String newPassword) { Assert.hasText(username); Assert.hasText(newPassword); try { User user = dao.find(username); if (user == null) { throw new UsernameNotFoundException(username); } Object salt = this.saltSource.getSalt(user); String password = passwordEncoder.encodePassword(newPassword, salt); ((User) user).setPassword(password); dao.update((User) user); userCache.removeUserFromCache(user.getUsername()); } catch (NonUniqueResultException nure) { throw new IncorrectResultSizeDataAccessException( "More than one user found with name '" + username + "'", 1); } }
/** * DO NOT CALL THIS METHOD IN LONG RUNNING SESSIONS OR CONVERSATIONS A * THROWN UsernameNotFoundException WILL RENDER THE CONVERSATION UNUSABLE. * * @param username * Set the username * @return the userdetails of the user */ @Transactional(readOnly = true) public final UserDetails loadUserByUsername(final String username) { try { Assert.hasText(username); } catch (IllegalArgumentException iae) { throw new UsernameNotFoundException(username, iae); } try { User user = dao.load(username); userCache.putUserInCache(user); return user; } catch (ObjectRetrievalFailureException orfe) { throw new UsernameNotFoundException(username, orfe); } catch (NonUniqueResultException nure) { throw new IncorrectResultSizeDataAccessException( "More than one user found with name '" + username + "'", 1); } }
@Override public Pair<Long, Long> getCurrentTimeMillis() { return (Pair<Long, Long>) getJdbcTemplate().execute(new StatementCallback() { @Override public Object doInStatement(Statement stmt) throws SQLException, DataAccessException { ResultSet rs = null; try { long time1 = System.currentTimeMillis(); rs = stmt.executeQuery("show @@status.time"); long time2 = System.currentTimeMillis(); if (rs.next()) { return new Pair<Long, Long>(time1 + (time2 - time1) / 2, rs.getLong(1)); } else { throw new IncorrectResultSizeDataAccessException(1, 0); } } finally { if (rs != null) { rs.close(); } } } }); }
/** * Return a unique result object from the given Collection. * Throws an exception if 0 or more than 1 result objects found, * of if the unique result object is not convertable to the * specified required type. * @param results the result Collection (can be {@code null}) * @return the unique result object * @throws IncorrectResultSizeDataAccessException if more than one * result object has been found in the given Collection * @throws EmptyResultDataAccessException if no result object * at all has been found in the given Collection * @throws TypeMismatchDataAccessException if the unique object does * not match the specified required type */ @SuppressWarnings("unchecked") public static <T> T objectResult(Collection<?> results, Class<T> requiredType) throws IncorrectResultSizeDataAccessException, TypeMismatchDataAccessException { Object result = requiredUniqueResult(results); if (requiredType != null && !requiredType.isInstance(result)) { if (String.class.equals(requiredType)) { result = result.toString(); } else if (Number.class.isAssignableFrom(requiredType) && Number.class.isInstance(result)) { try { result = NumberUtils.convertNumberToTargetClass(((Number) result), (Class<? extends Number>) requiredType); } catch (IllegalArgumentException ex) { throw new TypeMismatchDataAccessException(ex.getMessage()); } } else { throw new TypeMismatchDataAccessException( "Result object is of type [" + result.getClass().getName() + "] and could not be converted to required type [" + requiredType.getName() + "]"); } } return (T) result; }
@Override public PersistentRememberMeToken getTokenForSeries(String seriesId) { try { return getJdbcTemplate().queryForObject(sqlSelect, new RowMapper<PersistentRememberMeToken>() { public PersistentRememberMeToken mapRow(ResultSet rs, int rowNum) throws SQLException { //String username, String series, String tokenValue, Date date return new PersistentRememberMeToken(rs.getString(3), rs.getString(1), rs.getString(2), rs.getTimestamp(4)); } }, seriesId); } catch (EmptyResultDataAccessException zeroResults) { if (logger.isInfoEnabled()) { logger.info("Querying token for series '" + seriesId + "' returned no results.", zeroResults); } } catch (IncorrectResultSizeDataAccessException moreThanOne) { logger.error("Querying token for series '" + seriesId + "' returned more than one value. Series" + " should be unique"); } catch (DataAccessException e) { logger.error("Failed to load token for series " + seriesId, e); } return null; }
/** * This implementation tries to resolve placeholders first by using a SQL statement, * then in the passed-in properties. */ @Override protected String resolvePlaceholder(String placeholder, Properties props) { String value = null; if ( this.jdbcTemplate != null ) { try { value = this.jdbcTemplate.queryForObject( this.selectStatement, new Object[]{placeholder}, String.class); } catch (IncorrectResultSizeDataAccessException e ) { // Ignored } } if (value == null) { value = props.getProperty(placeholder); } return value; }
@SuppressWarnings("rawtypes") @Override public User getUser(String realm, String uid) { AndFilter filter = new AndFilter(); filter.and(new EqualsFilter(OBJECTCLASS, userObjectClass)).and(new EqualsFilter(userSearchAttribute, uid)); DistinguishedName dn = new DistinguishedName("ou=" + realm); User user; try { List userList = ldapTemplate.search(dn, filter.toString(), SearchControls.SUBTREE_SCOPE, new String[] { "*", CREATE_TIMESTAMP, MODIFY_TIMESTAMP }, new UserContextMapper()); if (userList == null || userList.size() == 0) { throw new EmptyResultDataAccessException(1); } else if (userList.size() > 1) { throw new IncorrectResultSizeDataAccessException("User must be unique", 1); } user = (User) userList.get(0); user.setUid(uid); user.setGroups(getGroupNames(getUserGroups(realm, uid))); } catch (EmptyResultDataAccessException e) { return null; } return user; }
@SuppressWarnings("unchecked") @Test @Category(NoAdTest.class) public void verifyAuthenticate() { EqualsFilter filter = new EqualsFilter("cn", "Some Person2"); List<String> results = ldapTemplate.search("", filter.toString(), new DnContextMapper()); if (results.size() != 1) { throw new IncorrectResultSizeDataAccessException(1, results.size()); } DirContext ctx = null; try { ctx = tested.getContext(results.get(0), "password"); assertThat(true).isTrue(); } catch (Exception e) { fail("Authentication failed"); } finally { LdapUtils.closeContext(ctx); } }
@Test public void verifyThatFindOneThrowsIncorrectResultSizeDataAccessExceptionWhenMoreResults() throws Exception { Class<Object> expectedClass = Object.class; when(contextSourceMock.getReadOnlyContext()).thenReturn(dirContextMock); when(odmMock.filterFor(expectedClass, new EqualsFilter("ou", "somevalue"))).thenReturn(new EqualsFilter("ou", "somevalue")); DirContextAdapter expectedObject = new DirContextAdapter(); SearchResult searchResult = new SearchResult("", expectedObject, new BasicAttributes()); setupSearchResults(searchControlsRecursive(), new SearchResult[]{searchResult, searchResult}); Object expectedResult = expectedObject; when(odmMock.mapFromLdapDataEntry(expectedObject, expectedClass)).thenReturn(expectedResult, expectedResult); try { tested.findOne(query().where("ou").is("somevalue"), expectedClass); fail("EmptyResultDataAccessException expected"); } catch (IncorrectResultSizeDataAccessException expected) { assertThat(true).isTrue(); } verify(namingEnumerationMock).close(); verify(dirContextMock).close(); }
@Test public void testAuthenticateWithTwoUsersFoundShouldThrowException() throws Exception { when(contextSourceMock.getReadOnlyContext()).thenReturn(dirContextMock); Object expectedObject = new DirContextAdapter(new BasicAttributes(), LdapUtils.newLdapName("cn=john doe"), LdapUtils.newLdapName("dc=jayway, dc=se")); SearchResult searchResult1 = new SearchResult("", expectedObject, new BasicAttributes()); SearchResult searchResult2 = new SearchResult("", expectedObject, new BasicAttributes()); setupSearchResults(searchControlsRecursive(), new SearchResult[] { searchResult1, searchResult2 }); try { tested.authenticate(nameMock, "(ou=somevalue)", "password", entryContextCallbackMock); fail("IncorrectResultSizeDataAccessException expected"); } catch (IncorrectResultSizeDataAccessException expected) { // expected } verify(dirContextMock).close(); }
private static ImpactDataset assignImpactDataset(String idurn) { int level = Integer.parseInt(idurn.substring(0, idurn.indexOf("****"))); String urn = idurn.substring(idurn.indexOf("****") + 4); ImpactDataset impD = new ImpactDataset(); Map<String, Object> row = null; MapSqlParameterSource parameters = new MapSqlParameterSource(); parameters.addValue("urn", urn); NamedParameterJdbcTemplate namedParameterJdbcTemplate = new NamedParameterJdbcTemplate(getJdbcTemplate().getDataSource()); try { row = namedParameterJdbcTemplate.queryForMap(GET_DATA_ATTR, parameters); } catch (IncorrectResultSizeDataAccessException irsdae) { Logger.error("Incorrect result size ", irsdae); } catch (DataAccessException dae) { Logger.error("SQL query failed ", dae); } impD.urn = urn; impD.level = level; impD.name = (String) row.get("name"); impD.id = (Long) row.get("id"); impD.datasetUrl = "#/datasets/" + impD.id; JsonNode prop = Json.parse((String) row.get("properties")); if (prop.has("valid") && (prop.get("valid").asText()) == "true") { impD.isValidDataset = true; } else { impD.isValidDataset = false; } return impD; }
/** * Return the DirContextOperations containing the user's information * * @param username the kerberos username to search for. * * @return An DirContextOperations object containing the details of the located user's * directory entry * * @throws UsernameNotFoundException if no matching entry is found. */ public DirContextOperations searchForUser(String username) { String[] data = username.split("@"); eq(data.length, 2, () -> new UsernameNotFoundException("Wrong username format for " + username)); String accountName = data[0]; String domainName = data[1]; String[] domainData = domainName.split("\\."); String searchBase = Stream.of(domainData) .map(part -> "dc=" + part) .collect(Collectors.joining(",")); log.debug("Searching for user '{}' in '{}', with user search {}.", accountName, searchBase, this); SpringSecurityLdapTemplate template = new SpringSecurityLdapTemplate(getContextSource()); template.setSearchControls(getSearchControls()); try { return template.searchForSingleEntry(searchBase, getSearchFilter(), new String[] { accountName }); } catch (IncorrectResultSizeDataAccessException ex) { if (ex.getActualSize() == 0) { throw new UsernameNotFoundException("User " + username + " not found in directory."); } // Search should never return multiple results if properly configured, so just rethrow throw ex; } }
protected T single() { List<T> list = list(); switch (list.size()) { case 0: return null; case 1: return list.get(0); default: throw new IncorrectResultSizeDataAccessException(String.format("Found %s results, expected 1.", list.size()), 1); } }
protected T single() { try { //noinspection unchecked return (T) fullTextQuery.uniqueResult(); } catch (NonUniqueResultException ex) { throw new IncorrectResultSizeDataAccessException(ex.getMessage(), 1); } finally { close(); } }
public void testDuplicateUser() { this.jdbcTemplate.update("INSERT INTO UP_PERSON_DIR VALUES ('foobar', 'pass1')"); this.jdbcTemplate.update("INSERT INTO UP_PERSON_DIR VALUES ('foobar', 'pass2')"); try { this.userPasswordDao.getPasswordHash("foobar"); fail("should have thrown IncorrectResultSizeDataAccessException"); } catch (IncorrectResultSizeDataAccessException e) { //expected } }
@Override public TermResult getTermByUuid(String termUuid) { List<TermResult> trs = executeListQuery(queryGetTerm, Collections.singletonMap("uuid", termUuid)); if( Check.isEmpty(trs) ) { return null; } else if( trs.size() == 1 ) { return trs.get(0); } else { // Sanity check - ensure only a single result throw new IncorrectResultSizeDataAccessException(1); } }
/** * Return a single result object from the given Collection. * <p>Returns {@code null} if 0 result objects found; * throws an exception if more than 1 element found. * @param results the result Collection (can be {@code null}) * @return the single result object, or {@code null} if none * @throws IncorrectResultSizeDataAccessException if more than one * element has been found in the given Collection */ public static <T> T singleResult(Collection<T> results) throws IncorrectResultSizeDataAccessException { int size = (results != null ? results.size() : 0); if (size == 0) { return null; } if (results.size() > 1) { throw new IncorrectResultSizeDataAccessException(1, size); } return results.iterator().next(); }
/** * Return a single result object from the given Collection. * <p>Throws an exception if 0 or more than 1 element found. * @param results the result Collection (can be {@code null}) * @return the single result object * @throws IncorrectResultSizeDataAccessException if more than one * element has been found in the given Collection * @throws EmptyResultDataAccessException if no element at all * has been found in the given Collection */ public static <T> T requiredSingleResult(Collection<T> results) throws IncorrectResultSizeDataAccessException { int size = (results != null ? results.size() : 0); if (size == 0) { throw new EmptyResultDataAccessException(1); } if (results.size() > 1) { throw new IncorrectResultSizeDataAccessException(1, size); } return results.iterator().next(); }
/** * Return a unique result object from the given Collection. * <p>Returns {@code null} if 0 result objects found; * throws an exception if more than 1 instance found. * @param results the result Collection (can be {@code null}) * @return the unique result object, or {@code null} if none * @throws IncorrectResultSizeDataAccessException if more than one * result object has been found in the given Collection * @see org.springframework.util.CollectionUtils#hasUniqueObject */ public static <T> T uniqueResult(Collection<T> results) throws IncorrectResultSizeDataAccessException { int size = (results != null ? results.size() : 0); if (size == 0) { return null; } if (!CollectionUtils.hasUniqueObject(results)) { throw new IncorrectResultSizeDataAccessException(1, size); } return results.iterator().next(); }
@Test @SuppressWarnings("serial") public void testConvertJpaPersistenceException() { EntityNotFoundException entityNotFound = new EntityNotFoundException(); assertSame(JpaObjectRetrievalFailureException.class, EntityManagerFactoryUtils.convertJpaAccessExceptionIfPossible(entityNotFound).getClass()); NoResultException noResult = new NoResultException(); assertSame(EmptyResultDataAccessException.class, EntityManagerFactoryUtils.convertJpaAccessExceptionIfPossible(noResult).getClass()); NonUniqueResultException nonUniqueResult = new NonUniqueResultException(); assertSame(IncorrectResultSizeDataAccessException.class, EntityManagerFactoryUtils.convertJpaAccessExceptionIfPossible(nonUniqueResult).getClass()); OptimisticLockException optimisticLock = new OptimisticLockException(); assertSame(JpaOptimisticLockingFailureException.class, EntityManagerFactoryUtils.convertJpaAccessExceptionIfPossible(optimisticLock).getClass()); EntityExistsException entityExists = new EntityExistsException("foo"); assertSame(DataIntegrityViolationException.class, EntityManagerFactoryUtils.convertJpaAccessExceptionIfPossible(entityExists).getClass()); TransactionRequiredException transactionRequired = new TransactionRequiredException("foo"); assertSame(InvalidDataAccessApiUsageException.class, EntityManagerFactoryUtils.convertJpaAccessExceptionIfPossible(transactionRequired).getClass()); PersistenceException unknown = new PersistenceException() { }; assertSame(JpaSystemException.class, EntityManagerFactoryUtils.convertJpaAccessExceptionIfPossible(unknown).getClass()); }
/** * Return a unique result object from the given Collection. * Throws an exception if 0 or more than 1 result objects found, * of if the unique result object is not convertable to the * specified required type. * @param results the result Collection (can be {@code null}) * @return the unique result object * @throws IncorrectResultSizeDataAccessException if more than one * result object has been found in the given Collection * @throws EmptyResultDataAccessException if no result object * at all has been found in the given Collection * @throws TypeMismatchDataAccessException if the unique object does * not match the specified required type */ @SuppressWarnings("unchecked") public static <T> T objectResult(Collection<?> results, Class<T> requiredType) throws IncorrectResultSizeDataAccessException, TypeMismatchDataAccessException { Object result = requiredUniqueResult(results); if (requiredType != null && !requiredType.isInstance(result)) { if (String.class == requiredType) { result = result.toString(); } else if (Number.class.isAssignableFrom(requiredType) && Number.class.isInstance(result)) { try { result = NumberUtils.convertNumberToTargetClass(((Number) result), (Class<? extends Number>) requiredType); } catch (IllegalArgumentException ex) { throw new TypeMismatchDataAccessException(ex.getMessage()); } } else { throw new TypeMismatchDataAccessException( "Result object is of type [" + result.getClass().getName() + "] and could not be converted to required type [" + requiredType.getName() + "]"); } } return (T) result; }
@Test public void testFindTooManyCustomers() throws SQLException { given(resultSet.next()).willReturn(true, true, false); given(resultSet.getInt("id")).willReturn(1, 2); given(resultSet.getString("forename")).willReturn("rod", "rod"); class CustomerQuery extends MappingSqlQuery<Customer> { public CustomerQuery(DataSource ds) { super(ds, SELECT_ID_FORENAME_WHERE); declareParameter(new SqlParameter(Types.VARCHAR)); compile(); } @Override protected Customer mapRow(ResultSet rs, int rownum) throws SQLException { Customer cust = new Customer(); cust.setId(rs.getInt(COLUMN_NAMES[0])); cust.setForename(rs.getString(COLUMN_NAMES[1])); return cust; } public Customer findCustomer(String id) { return findObject(id); } } CustomerQuery query = new CustomerQuery(dataSource); thrown.expect(IncorrectResultSizeDataAccessException.class); try { query.findCustomer("rod"); } finally { verify(preparedStatement).setString(1, "rod"); verify(connection).prepareStatement(SELECT_ID_FORENAME_WHERE); verify(resultSet).close(); verify(preparedStatement).close(); verify(connection).close(); } }
@Test public void testQueryForObjectThrowsIncorrectResultSizeForMoreThanOneRow() throws Exception { String sql = "select pass from t_account where first_name='Alef'"; given(this.resultSet.next()).willReturn(true, true, false); given(this.resultSet.getString(1)).willReturn("pass"); this.thrown.expect(IncorrectResultSizeDataAccessException.class); try { this.template.queryForObject(sql, String.class); } finally { verify(this.resultSet).close(); verify(this.statement).close(); } }