Example usage for javax.persistence TypedQuery getSingleResult

List of usage examples for javax.persistence TypedQuery getSingleResult

Introduction

In this page you can find the example usage for javax.persistence TypedQuery getSingleResult.

Prototype

X getSingleResult();

Source Link

Document

Execute a SELECT query that returns a single result.

Usage

From source file:fr.univrouen.poste.provider.DatabaseAuthenticationProvider.java

@Override
@Transactional(noRollbackFor = BadCredentialsException.class)
protected UserDetails retrieveUser(String username, UsernamePasswordAuthenticationToken authentication)
        throws AuthenticationException {

    UserDetails userDetails = null;/*  ww w  .ja v  a2s  .c  om*/

    logger.debug("Inside retrieveUser");

    WebAuthenticationDetails wad = (WebAuthenticationDetails) authentication.getDetails();
    String userIPAddress = wad.getRemoteAddress();

    Boolean ipCanBeUsed4AuthAdminManager = this.isIpCanBeUsed4AuthAdminManager(userIPAddress);

    username = username.toLowerCase();

    String password = (String) authentication.getCredentials();
    if (!StringUtils.hasText(password) || !StringUtils.hasText(username)) {
        logService.logActionAuth(LogService.AUTH_FAILED, username, userIPAddress);
        throw new BadCredentialsException("Merci de saisir votre email et mot de passe");
    }
    String encryptedPassword = messageDigestPasswordEncoder.encodePassword(password, null);
    List<GrantedAuthority> authorities = new ArrayList<GrantedAuthority>();
    Boolean enabled;

    try {
        TypedQuery<User> query = User.findUsersByEmailAddress(username, null, null);

        User targetUser = (User) query.getSingleResult();

        if (targetUser.isLocked()) {
            throw new BadCredentialsException("Compte vrouill, merci de retenter d'ici quelques secondes.");
        }

        // authenticate the person
        String expectedPassword = targetUser.getPassword();
        if (!StringUtils.hasText(expectedPassword)) {
            logService.logActionAuth(LogService.AUTH_FAILED, username, userIPAddress);
            throw new BadCredentialsException("Aucun mot de passe pour " + username
                    + " n'est enregistr dans la base, merci d'activer votre compte via le lien d'activation envoy par email. Contactez un administrateur si problme.");
        }
        if (!encryptedPassword.equals(expectedPassword)) {
            logService.logActionAuth(LogService.AUTH_FAILED, username, userIPAddress);
            throw new BadCredentialsException("Email utilisateur ou mot de passe invalide.");
        }

        // restriction accs rseau
        if (!ipCanBeUsed4AuthAdminManager
                && (targetUser.getIsAdmin() || targetUser.getIsSuperManager() || targetUser.getIsManager())) {
            logService.logActionAuth(LogService.AUTH_FAILED, username, userIPAddress);
            logger.warn("User " + username
                    + " tried to access to his admin/manager/supermanager account from this IP "
                    + userIPAddress);
            throw new BadCredentialsException(
                    "Vous ne pouvez pas vous authentifier sur ce compte depuis cet accs rseau. Contactez un administrateur si problme.");
        }

        // restriction dates accs pour candidats et membres 
        boolean isCurrentTimeOk4ThisCandidat = dateClotureChecker.isCurrentTimeOk4ThisCandidat(targetUser);
        boolean isCurrentTimeOk4ThisMembre = dateClotureChecker.isCurrentTimeOk4ThisMembre(targetUser);
        if ((targetUser.getIsCandidat() || targetUser.getIsMembre()) && !isCurrentTimeOk4ThisCandidat
                && !isCurrentTimeOk4ThisMembre) {
            if (targetUser.getIsCandidat() && !isCurrentTimeOk4ThisCandidat) {
                logger.warn("User " + username
                        + " tried to access to his candidat account but the dateEndCandidat is < current time");
            }
            if (targetUser.getIsMembre() && !isCurrentTimeOk4ThisMembre) {
                logger.warn("User " + username
                        + " tried to access to his membre account but the dateEndMembre is < current time");
            }
            logService.logActionAuth(LogService.AUTH_FAILED, username, userIPAddress);
            throw new BadCredentialsException(
                    "La date de clture des dpts est dpasse, vous ne pouvez maintenant plus accder  l'application.");
        }

        userDetails = databaseUserDetailsService.loadUserByUser(targetUser);

    } catch (EmptyResultDataAccessException e) {
        logService.logActionAuth(LogService.AUTH_FAILED, username, userIPAddress);
        throw new BadCredentialsException("Compte utilisateur et/ou mot de passe invalide");
    } catch (EntityNotFoundException e) {
        logService.logActionAuth(LogService.AUTH_FAILED, username, userIPAddress);
        throw new BadCredentialsException("Compte utilisateur et/ou mot de passe invalide");
    } catch (NonUniqueResultException e) {
        logService.logActionAuth(LogService.AUTH_FAILED, username, userIPAddress);
        throw new BadCredentialsException("Utilisateur non unique, contactez l'administrateur.");
    }

    logService.logActionAuth(LogService.AUTH_SUCCESS, username, userIPAddress);

    return userDetails;
}

From source file:eu.domibus.ebms3.common.dao.PModeDao.java

@Override
public boolean isMpcExistant(final String mpc) {
    final TypedQuery<Integer> query = this.entityManager.createNamedQuery("Mpc.countForQualifiedName",
            Integer.class);
    return query.getSingleResult() > 0;
}

From source file:com.qpark.eip.core.spring.lockedoperation.dao.LockedOperationDaoImpl.java

/**
 * @see com.qpark.eip.core.spring.lockedoperation.dao.LockableOperationDao#isLockedByThisServer(com.qpark.eip.core.spring.lockedoperation.LockableOperation)
 *///w w  w  .  java2 s . c om
@Override
@Transactional(value = EipLockedoperationConfig.TRANSACTION_MANAGER_NAME, propagation = Propagation.REQUIRED)
public synchronized boolean isLockedByThisServer(final LockableOperation operation) {
    boolean lockedByThisServer = false;
    OperationLockControllType value = null;
    String logString = getOperationLockString(operation);
    CriteriaBuilder cb = this.em.getCriteriaBuilder();
    CriteriaQuery<OperationLockControllType> q = cb.createQuery(OperationLockControllType.class);
    Root<OperationLockControllType> c = q.from(OperationLockControllType.class);
    q.where(cb.equal(c.<String>get("operationName"), logString));
    TypedQuery<OperationLockControllType> typedQuery = this.em.createQuery(q);
    try {
        value = typedQuery.getSingleResult();
        if (value != null) {
            if (value.getServerIpAddress().equals(this.hostAddress)) {
                lockedByThisServer = true;
            }
            this.logger.debug(" isLockedByThisServer# {} opeation {} {} locked by: {} {}",
                    new Object[] { lockedByThisServer, operation.getUUID(), operation.getName(),
                            value.getServerName(), value.getLockDate() });
        }
    } catch (NoResultException e) {
        lockedByThisServer = false;
    } catch (NonUniqueResultException e) {
        lockedByThisServer = false;
    }
    return lockedByThisServer;
}

From source file:fr.univrouen.poste.web.ForgotPasswordController.java

@RequestMapping(value = "/forgotpassword/update", method = RequestMethod.POST)
public String update(@ModelAttribute("forgotpasswordForm") @Valid ForgotPasswordForm form, BindingResult result,
        HttpServletRequest request) {/*from ww w . j  a  v a 2s  .  com*/
    if (result.hasErrors()) {
        return "forgotpassword/index";
    } else {
        TypedQuery<User> userQuery = User
                .findUsersByEmailAddressAndActivationDateIsNotNull(form.getEmailAddress(), null, null);
        if (null != userQuery && !userQuery.getResultList().isEmpty()) {
            User user = userQuery.getSingleResult();

            String activationKey = generateActivationKey();
            user.setActivationKey(activationKey);
            user.merge();

            String mailTo = form.getEmailAddress();
            String mailFrom = AppliConfig.getCacheMailFrom();
            String mailSubject = AppliConfig.getCacheMailSubject();

            String mailMessage = AppliConfig.getCacheTexteMailPasswordOublie();
            mailMessage = mailMessage.replaceAll("@@activationKey@@", activationKey);

            logService.logActionAuth(LogService.AUTH_PASSWORD_FORGOT_SENT, user.getEmailAddress(),
                    request.getRemoteAddr());

            emailService.sendMessage(mailFrom, mailTo, mailSubject, mailMessage);
        } else {
            logService.logActionAuth(LogService.AUTH_PASSWORD_FORGOT_FAILED, form.getEmailAddress(),
                    request.getRemoteAddr());
        }

        return "forgotpassword/thanks";
    }
}

From source file:com.epam.ipodromproject.repository.jpa.JPAUserRepository.java

private double getTotalMoneyByResult(User user, BetResult betResult) {
    TypedQuery<Double> query = entityManager.createNamedQuery("User.findTotalMoneyByUsernameAndResult",
            Double.class);
    query.setParameter("user", user);
    query.setParameter("betResult", betResult);
    double moneyWon = 0;
    try {/*from   w  w  w  .  j  av  a2  s .c om*/
        moneyWon = query.getSingleResult();
    } catch (Exception e) {
    }
    return moneyWon;
}

From source file:com.mycompany.login.filter.AutenticacaoFilter.java

/**
 * Metodos de acesso ao BD/*from   ww  w . java  2s  .  c  om*/
 *
 * @param login
 * @param senha
 * @return   
 */
public Usuario buscarUsuario(String login, String senha) throws IOException {
    em = factory.createEntityManager();
    com.mycompany.login.bean.Usuario usuario = null;
    try {
        TypedQuery<Usuario> query = em.createQuery(
                "SELECT u FROM Usuario u WHERE u.login = :login AND u.senha = :senha", Usuario.class);
        query.setParameter("login", login);
        query.setParameter("senha", senha);

        usuario = (Usuario) query.getSingleResult();

    } catch (NoResultException e) {
        System.out.println("DAO: No foi encontrado resultado!");

    } catch (Exception e) {
        e.printStackTrace();
    } finally {
        em.close();
    }

    return usuario;
}

From source file:org.openmeetings.app.data.basic.ErrorManagement.java

public ErrorValues getErrorValuesById(Long errorvalues_id) {
    try {//from  www  . j  ava2  s .  c  o m
        String hql = "select c from ErrorValues as c " + " where c.errorvalues_id = :errorvalues_id "
                + " AND c.deleted <> :deleted";
        TypedQuery<ErrorValues> query = em.createQuery(hql, ErrorValues.class);
        query.setParameter("errorvalues_id", errorvalues_id);
        query.setParameter("deleted", "true");
        ErrorValues e = null;
        try {
            e = query.getSingleResult();
        } catch (NoResultException ex) {
        }
        return e;
    } catch (Exception ex2) {
        log.error("[getErrorValuesById]", ex2);
    }
    return null;
}

From source file:com.epam.training.taranovski.web.project.repository.implementation.UserRepositoryImplementation.java

/**
 *
 * @param name/*from  ww w.jav a 2  s . c  om*/
 * @param password
 * @return
 */
@Override
public User getByNameAndPassword(String name, String password) {
    EntityManager em = entityManagerFactory.createEntityManager();
    User user = null;
    boolean exists = false;

    try {
        em.getTransaction().begin();

        TypedQuery<User> query = em.createNamedQuery("User.findByUserLoginAndPassword", User.class);
        query.setParameter("login", name);
        query.setParameter("password", encryptionService.encrypt(password));

        user = query.getSingleResult();

        em.getTransaction().commit();
        exists = true;
    } catch (NoResultException ex) {
        Logger.getLogger(OfferBidRepositoryImplementation.class.getName()).info(ex);
        exists = false;
    } finally {
        if (em.getTransaction().isActive()) {
            em.getTransaction().rollback();
        }
        em.close();
    }

    if (exists) {
        return user;
    } else {
        return null;
    }

}

From source file:com.qpark.eip.core.spring.lockedoperation.dao.LockedOperationDaoImpl.java

/**
 * @see com.qpark.eip.core.spring.lockedoperation.dao.LockableOperationDao#isLockedOperation(com.qpark.eip.core.spring.lockedoperation.LockableOperation)
 *//*from w w  w .  java 2 s. co  m*/
@Override
@Transactional(value = EipLockedoperationConfig.TRANSACTION_MANAGER_NAME, propagation = Propagation.REQUIRED)
public synchronized boolean isLockedOperation(final LockableOperation operation) {
    this.logger.debug("+isLocked# {} {} {}",
            new Object[] { this.hostName, operation.getUUID(), operation.getName() });
    if (this.firstRun) {
        this.unlockOperationOnServerStart();
        this.firstRun = false;
    }
    boolean locked = false;
    String logString = getOperationLockString(operation);
    OperationLockControllType value = null;
    CriteriaBuilder cb = this.em.getCriteriaBuilder();
    CriteriaQuery<OperationLockControllType> q = cb.createQuery(OperationLockControllType.class);
    Root<OperationLockControllType> c = q.from(OperationLockControllType.class);
    q.where(cb.equal(c.<String>get("operationName"), logString));
    TypedQuery<OperationLockControllType> typedQuery = this.em.createQuery(q);
    try {
        value = typedQuery.getSingleResult();
        if (value != null) {
            this.logger.debug(" isLocked# opeation {} {} locked by: {} {}", new Object[] { operation.getUUID(),
                    operation.getName(), value.getServerName(), value.getLockDate() });
            locked = true;
        }
    } catch (NoResultException e) {
        locked = false;
    } catch (NonUniqueResultException e) {
        locked = true;
    }
    this.logger.debug("-isLocked# {} {} {} {}", new Object[] { this.hostName, locked ? "locked" : "not locked",
            operation.getUUID(), operation.getName() });
    return locked;
}

From source file:com.ushahidi.swiftriver.core.api.dao.impl.JpaAccountDao.java

public Account findByUsernameOrEmail(String username) {
    String qlString = "SELECT a FROM Account a JOIN a.owner o "
            + "WHERE o.username = :username OR o.email = :email";

    Account account = null;/*from w  w w.ja v  a 2  s.com*/
    try {
        TypedQuery<Account> query = em.createQuery(qlString, Account.class);
        query.setParameter("username", username);
        query.setParameter("email", username);
        account = query.getSingleResult();
    } catch (NoResultException e) {
        logger.info("Account associated with {} not found", username);
    }
    return account;
}