Example usage for org.springframework.dao.support DataAccessUtils uniqueResult

List of usage examples for org.springframework.dao.support DataAccessUtils uniqueResult

Introduction

In this page you can find the example usage for org.springframework.dao.support DataAccessUtils uniqueResult.

Prototype

@Nullable
public static <T> T uniqueResult(@Nullable Collection<T> results)
        throws IncorrectResultSizeDataAccessException 

Source Link

Document

Return a unique result object from the given Collection.

Usage

From source file:org.ambraproject.admin.service.impl.AdminServiceImpl.java

@Override
@Transactional/*from  w w w .ja va2s. co m*/
public void deleteIssue(final String issueUri) {
    log.debug("Deleting issue '{}'", issueUri);
    //using hibernateTemplate.execute() instead of hibernateTemplate.findByCriteria() here
    //because for some reason adding the issue restriction causes issues to be lazy-loaded,
    //even with fetchMode = JOIN
    hibernateTemplate.execute(new HibernateCallback<Void>() {
        @Override
        public Void doInHibernate(Session session) throws HibernateException, SQLException {
            Volume volume = (Volume) DataAccessUtils
                    .uniqueResult(session.createCriteria(Volume.class).setFetchMode("issues", FetchMode.JOIN)
                            .createAlias("issues", "i").add(Restrictions.eq("i.issueUri", issueUri))
                            .setResultTransformer(Criteria.DISTINCT_ROOT_ENTITY).list());
            if (volume != null) {
                Iterator<Issue> iterator = volume.getIssues().iterator();
                while (iterator.hasNext()) {
                    Issue issue = iterator.next();
                    if (issue.getIssueUri().equals(issueUri)) {
                        iterator.remove();
                        session.delete(issue);
                        break;
                    }
                }
                session.update(volume);
            }
            return null;
        }
    });
}

From source file:org.ambraproject.service.user.UserRegistrationServiceImpl.java

@Override
public void verifyUser(String email, String verificationToken)
        throws NoSuchUserException, UserAlreadyVerifiedException, VerificationTokenException {
    if (StringUtils.isEmpty(email)) {
        throw new IllegalArgumentException("Must supply an email");
    }// w ww.  ja  v  a2 s.  c o  m
    if (StringUtils.isEmpty(verificationToken)) {
        throw new IllegalArgumentException("Must supply a verification token");
    }
    UserProfile profile = (UserProfile) DataAccessUtils.uniqueResult(hibernateTemplate
            .findByCriteria(DetachedCriteria.forClass(UserProfile.class).add(Restrictions.eq("email", email))));
    if (profile == null) {
        throw new NoSuchUserException("No user with email: " + email);
    } else if (profile.getVerified()) {
        throw new UserAlreadyVerifiedException("User " + email + " was already verified");
    } else if (!verificationToken.equals(profile.getVerificationToken())) {
        throw new VerificationTokenException("An invalid verification token was given for this user");
    }
    log.debug("Verifying user {}", email);
    profile.setVerified(true);
    hibernateTemplate.update(profile);
}

From source file:org.ambraproject.service.user.UserRegistrationServiceImpl.java

/**
 * {@inheritDoc}//from  w w  w  .ja v a2s  .  co  m
 */
@Override
@Transactional
public String resendVerificationEmail(String email) throws NoSuchUserException, UserAlreadyVerifiedException {
    if (StringUtils.isEmpty(email)) {
        throw new IllegalArgumentException("Must supply an email");
    }

    UserProfile profile = (UserProfile) DataAccessUtils.uniqueResult(hibernateTemplate
            .findByCriteria(DetachedCriteria.forClass(UserProfile.class).add(Restrictions.eq("email", email))));
    if (profile == null) {
        throw new NoSuchUserException("No user with the email: " + email);
    }
    if (profile.getVerified()) {
        throw new UserAlreadyVerifiedException();
    }

    profile.setVerificationToken(TokenGenerator.getUniqueToken());
    hibernateTemplate.update(profile);

    log.debug("Resending verification email to {}", email);
    ambraMailer.sendVerificationEmail(email, profile.getVerificationToken());

    return profile.getVerificationToken();
}

From source file:org.ambraproject.service.user.UserRegistrationServiceImpl.java

/**
 * {@inheritDoc}//from   www .  ja  va 2  s .c o  m
 */
@Override
@Transactional
public String sendForgotPasswordMessage(String email) throws NoSuchUserException {
    if (StringUtils.isEmpty(email)) {
        throw new IllegalArgumentException("Must supply an email");
    }
    UserProfile profile = (UserProfile) DataAccessUtils
            .uniqueResult(hibernateTemplate.findByCriteria(DetachedCriteria.forClass(UserProfile.class)
                    .add(Restrictions.eq("email", email)).add(Restrictions.eq("verified", true))));
    if (profile == null) {
        throw new NoSuchUserException("No user with the email: " + email);
    }
    log.debug("Sending forgotten newPassword message to {}", email);
    String passwordResetToken = TokenGenerator.getUniqueToken();
    profile.setVerificationToken(passwordResetToken);
    hibernateTemplate.update(profile);
    ambraMailer.sendForgotPasswordEmail(email, passwordResetToken);

    return passwordResetToken;
}

From source file:org.ambraproject.service.user.UserRegistrationServiceImpl.java

/**
 * {@inheritDoc}//from   w w  w  .j a  va  2s. com
 */
@Override
@Transactional
public void removeVerificationToken(String email) {
    UserProfile profile = (UserProfile) DataAccessUtils.uniqueResult(hibernateTemplate
            .findByCriteria(DetachedCriteria.forClass(UserProfile.class).add(Restrictions.eq("email", email))));
    if (profile == null) {
        throw new IllegalArgumentException("Incorrect email: " + email);
    }

    log.debug("Resetting token for {}", email);

    profile.setVerificationToken(null);

    hibernateTemplate.update(profile);
}

From source file:org.ambraproject.service.user.UserRegistrationServiceImpl.java

/**
 * {@inheritDoc}//  ww  w.j a v a  2  s . co  m
 */
@Override
@Transactional
public void resetPassword(final String email, final String newPassword) {
    for (Map.Entry<String, String> argument : new HashMap<String, String>() {
        {
            put("email", email);
            put("new password", newPassword);
        }
    }.entrySet()) {
        if (StringUtils.isEmpty(argument.getValue())) {
            throw new IllegalArgumentException("Must supply a(n) " + argument.getKey());
        }
    }

    UserProfile profile = (UserProfile) DataAccessUtils.uniqueResult(hibernateTemplate
            .findByCriteria(DetachedCriteria.forClass(UserProfile.class).add(Restrictions.eq("email", email))));
    if (profile == null) {
        throw new IllegalArgumentException("Incorrect email: " + email);
    }

    log.debug("Setting new password for {}", email);
    profile.setPassword(passwordDigestService.generateDigest(newPassword));
    hibernateTemplate.update(profile);
}

From source file:org.ambraproject.service.user.UserRegistrationServiceImpl.java

/**
 * {@inheritDoc}/*from  w  w  w .j av a  2 s  .c o m*/
 */
@Override
@Transactional
public String sendEmailChangeMessage(final String oldEmail, final String newEmail, final String password)
        throws NoSuchUserException, DuplicateUserException {
    for (Map.Entry<String, String> argument : new HashMap<String, String>() {
        {
            put("old email", oldEmail);
            put("new email", newEmail);
            put("password", password);
        }
    }.entrySet()) {
        if (StringUtils.isEmpty(argument.getValue())) {
            throw new IllegalArgumentException("Must supply a(n) " + argument.getKey());
        }
    }

    UserProfile profile = (UserProfile) DataAccessUtils.uniqueResult(hibernateTemplate.findByCriteria(
            DetachedCriteria.forClass(UserProfile.class).add(Restrictions.eq("email", oldEmail))));

    if (profile == null) {
        throw new NoSuchUserException("No user with the email: " + oldEmail);
    }

    boolean validPassword = passwordDigestService.verifyPassword(password, profile.getPassword());
    if (!validPassword) {
        throw new SecurityException("Invalid password");
    }

    int existingUserCount = DataAccessUtils.intResult(hibernateTemplate.findByCriteria(
            DetachedCriteria.forClass(UserProfile.class).add(Restrictions.eq("email", newEmail).ignoreCase())
                    .setProjection(Projections.count("email"))));
    if (existingUserCount > 0) {
        throw new DuplicateUserException(DuplicateUserException.Field.EMAIL);
    }

    log.debug("sending email change verification to {}", newEmail);
    profile.setVerificationToken(TokenGenerator.getUniqueToken());
    hibernateTemplate.update(profile);
    ambraMailer.sendChangeEmailNotice(oldEmail, newEmail, profile.getVerificationToken());

    return profile.getVerificationToken();
}

From source file:org.ambraproject.service.user.UserRegistrationServiceImpl.java

@Override
@Transactional/*from   w  w  w  .j a  v  a2 s  . com*/
public void updateEmailAddress(final String oldEmail, final String newEmail, final String verificationToken)
        throws NoSuchUserException, VerificationTokenException, DuplicateUserException {
    for (Map.Entry<String, String> argument : new HashMap<String, String>() {
        {
            put("old email", oldEmail);
            put("new email", newEmail);
            put("verification token", verificationToken);
        }
    }.entrySet()) {
        if (StringUtils.isEmpty(argument.getValue())) {
            throw new IllegalArgumentException("Must supply a(n) " + argument.getKey());
        }
    }

    UserProfile profile = (UserProfile) DataAccessUtils.uniqueResult(hibernateTemplate.findByCriteria(
            DetachedCriteria.forClass(UserProfile.class).add(Restrictions.eq("email", oldEmail))));

    if (profile == null) {
        throw new NoSuchUserException("No user with the email: " + oldEmail);
    } else if (!verificationToken.equals(profile.getVerificationToken())) {
        throw new VerificationTokenException("An invalid verification token was given for this user");
    }

    int existingUserCount = DataAccessUtils.intResult(hibernateTemplate.findByCriteria(
            DetachedCriteria.forClass(UserProfile.class).add(Restrictions.eq("email", newEmail).ignoreCase())
                    .setProjection(Projections.count("email"))));
    if (existingUserCount > 0) {
        throw new DuplicateUserException(DuplicateUserException.Field.EMAIL);
    }

    log.debug("Changing email for {} to {}", oldEmail, newEmail);
    profile.setEmail(newEmail);
    hibernateTemplate.update(profile);
}

From source file:org.ambraproject.service.user.UserServiceImpl.java

/**
 * {@inheritDoc}/*from w ww  . jav  a  2s  .  c  o  m*/
 */
@Transactional(rollbackFor = { Throwable.class })
public List<SavedSearchView> getSavedSearches(Long userProfileId) {
    UserProfile userProfile = (UserProfile) DataAccessUtils
            .uniqueResult(hibernateTemplate.findByCriteria(DetachedCriteria.forClass(UserProfile.class)
                    .add(Restrictions.eq("ID", userProfileId)).setFetchMode("savedSearches", FetchMode.JOIN)
                    .setResultTransformer(Criteria.DISTINCT_ROOT_ENTITY)));

    List<SavedSearch> searches = userProfile.getSavedSearches();
    List<SavedSearchView> searchViews = new ArrayList<SavedSearchView>(searches.size());

    for (SavedSearch savedSearch : searches) {
        searchViews.add(new SavedSearchView(savedSearch));
    }

    return searchViews;
}

From source file:org.ambraproject.service.user.UserServiceImpl.java

/**
 * {@inheritDoc}/*w w w.j a  v a  2  s. co  m*/
 */
@Transactional(rollbackFor = { Throwable.class })
public void deleteSavedSearch(Long userProfileId, Long savedSearchId) {

    UserProfile userProfile = (UserProfile) DataAccessUtils
            .uniqueResult(hibernateTemplate.findByCriteria(DetachedCriteria.forClass(UserProfile.class)
                    .add(Restrictions.eq("ID", userProfileId)).setFetchMode("savedSearches", FetchMode.JOIN)
                    .setResultTransformer(Criteria.DISTINCT_ROOT_ENTITY)));
    List<SavedSearch> savedSearches = userProfile.getSavedSearches();
    for (Iterator<SavedSearch> it = savedSearches.iterator(); it.hasNext();) {
        SavedSearch savedSearch = it.next();
        if (savedSearch.getID().equals(savedSearchId)) {
            it.remove();
        }
    }
    hibernateTemplate.update(userProfile);
}