@Override
 protected DetachedCriteria getNaturalKeyCriteria(RecipientFavourite entity) {
   DetachedCriteria det =
       DetachedCriteria.forClass(RecipientFavourite.class)
           .add(Restrictions.eq("owner", entity.getOwner()))
           .add(Restrictions.eq("recipient", entity.getRecipient()));
   return det;
 }
 private List<String> transformRecipientFavouriteToRecipient(List<RecipientFavourite> recipients) {
   ArrayList<String> listElements = new ArrayList<String>();
   if (null != recipients) {
     for (RecipientFavourite recipientFavourite : recipients) {
       listElements.add(recipientFavourite.getRecipient());
     }
   }
   return listElements;
 }
  public List<String> findMatchElementsOrderByWeight(String matchStartWith, User owner) {
    DetachedCriteria det = DetachedCriteria.forClass(RecipientFavourite.class);
    det.add(Restrictions.eq("owner", owner));
    det.add(Restrictions.ilike("recipient", matchStartWith, MatchMode.ANYWHERE));
    det.addOrder(Order.desc("weight"));
    List<RecipientFavourite> recipients = findByCriteria(det);

    ArrayList<String> mails = new ArrayList<String>();

    for (RecipientFavourite recipientFavour : recipients) {
      mails.add(recipientFavour.getRecipient());
    }
    return mails;
  }
 private void createFavourite(List<String> elements, List<RecipientFavourite> recipients, User u)
     throws BusinessException {
   for (String recipient : elements) {
     boolean contain = false;
     for (RecipientFavourite recipientFavour : recipients) {
       if (recipientFavour.getRecipient().equals(recipient)) {
         contain = true;
         break;
       }
     }
     if (!contain) {
       super.create(new RecipientFavourite(u, recipient));
     }
   }
 }
  private List<String> reorderElement(List<String> elements, List<RecipientFavourite> recipients) {

    ArrayList<String> orderedElements = new ArrayList<String>();

    // 1) first put favorite at the top of the list
    for (RecipientFavourite recipientFavour : recipients) {
      orderedElements.add(recipientFavour.getRecipient());
    }

    // 2) second put remaining entries in the list (exclude them if they are present in favorite)
    for (String element : elements) {
      if (!orderedElements.contains(element)) {
        orderedElements.add(element);
      }
    }
    return orderedElements;
  }