AccountServiceDefault.java 2.58 KB
package org.legrog.web.account;

import org.legrog.entities.*;

import javax.ejb.Stateless;
import javax.inject.Inject;
import javax.validation.constraints.NotNull;
import java.util.ArrayList;
import java.util.List;

@Stateless
public class AccountServiceDefault implements AccountService {
    AccountRepository accountRepository;
    AccountSearchRepository accountSearchRepository;

    /**
     * Le service s'appuie concrètement sur un ensemble de dépôts et sur le service auxiliaire SharedService.
     *
     * @param accountRepository
     * @param accountSearchRepository
     */
    @Inject
    public AccountServiceDefault(AccountRepository accountRepository,
                                   AccountSearchRepository accountSearchRepository) {
        this.accountRepository = accountRepository;
        this.accountSearchRepository = accountSearchRepository;
    }

    AccountServiceDefault() {
        //no args constructor to make it proxyable
    }

    public void addUser(Account account) {
        accountRepository.save(account);
    }

    public List<Account> getAllUsers() {
        return accountRepository.findAll();
    }

    public Account findUserById(int id) {
        return accountRepository.findOne(new Integer(id));
    }

    public void updateUser(Account account) {
        accountRepository.save(account);
    }

    @Override
    public List<Account> search(@NotNull String string) throws SearchingException {
        return convertIndexedAccountsIntoAccounts(accountSearchRepository.search(string));
    }

    @Override
    public List<Account> convertIndexedAccountsIntoAccounts(List<IndexedAccount> indexedAccounts) {
        List<Integer> integers = new ArrayList<>(indexedAccounts.size());
        indexedAccounts.forEach(indexedAccount -> integers.add(indexedAccount.getUserId()));

        if (!integers.isEmpty()) {
            return accountRepository.findByUserIdIn(integers);
        }

        return new ArrayList<>();
    }

    protected List<IndexedAccount> convertAccountsIntoIndexedAccounts(List<Account> accounts) {
        List<IndexedAccount> indexedAccounts = new ArrayList<>(accounts.size());

        accounts.forEach(account -> indexedAccounts.add(new IndexedAccount(account)));

        return indexedAccounts;
    }

    @Override
    public int reindexAllAccounts() throws IndexingException {
        List<Account> accounts = accountRepository.findByPresentationIsNotNull();
        List<IndexedAccount> indexedAccounts = convertAccountsIntoIndexedAccounts(accounts);
        accountSearchRepository.reindex(indexedAccounts);
        return indexedAccounts.size();
    }


}