fr.mael.microrss.dao.impl.GenericDaoImpl.java Source code

Java tutorial

Introduction

Here is the source code for fr.mael.microrss.dao.impl.GenericDaoImpl.java

Source

/*
   Copyright  2013 Mael Le Guvel
   This work is free. You can redistribute it and/or modify it under the
   terms of the Do What The Fuck You Want To Public License, Version 2,
   as published by Sam Hocevar. See the COPYING file for more details.
*/
package fr.mael.microrss.dao.impl;

import java.io.File;
import java.io.IOException;
import java.lang.reflect.ParameterizedType;
import java.util.List;

import org.apache.lucene.index.IndexReader;
import org.apache.lucene.index.IndexWriterConfig;
import org.apache.lucene.search.spell.Dictionary;
import org.apache.lucene.search.spell.LevensteinDistance;
import org.apache.lucene.search.spell.LuceneDictionary;
import org.apache.lucene.search.spell.SpellChecker;
import org.apache.lucene.store.Directory;
import org.apache.lucene.store.FSDirectory;
import org.apache.lucene.util.Version;
import org.hibernate.Criteria;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.criterion.Criterion;
import org.hibernate.criterion.Projections;
import org.hibernate.criterion.Restrictions;
import org.hibernate.search.FullTextSession;
import org.hibernate.search.Search;
import org.hibernate.search.SearchFactory;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;

import fr.mael.microrss.dao.GenericDao;
import fr.mael.microrss.domain.BaseDomain;
import fr.mael.microrss.util.Configuration;

/**
 * 
 * Generic Dao implementation
 * @author mael
 *
 * @param <T>
 */
public abstract class GenericDaoImpl<T extends BaseDomain> implements GenericDao<T> {

    private static Logger log = LoggerFactory.getLogger(GenericDaoImpl.class);

    private Class<T> persistentClass;

    @Autowired
    private SessionFactory sessionFactory;

    @Autowired
    private Configuration configuration;

    /**
     * Constructor
     */
    public GenericDaoImpl() {
        this.persistentClass = (Class<T>) ((ParameterizedType) getClass().getGenericSuperclass())
                .getActualTypeArguments()[0];
    }

    /**
     * @param sf the hibernate session factory
     */
    public void setSessionFactory(SessionFactory sf) {
        this.sessionFactory = sf;
    }

    /**
     * @return the hibernate session factory
     */
    public SessionFactory getSessionFactory() {
        return this.sessionFactory;
    }

    /**
     * @see fr.mael.jmusic.dao.GenericDao#getSession()
     */
    public Session getSession() {
        return getSessionFactory().getCurrentSession();
    }

    /**
     * Gets the persistent class ( {@link DBOObject})
     * @return the persistent class
     */
    public Class<T> getPersistentClass() {
        return persistentClass;
    }

    /**
     * @see fr.mael.jmusic.dao.GenericDao#get(java.lang.Integer)
     */
    public T get(Integer id) {
        return (T) getSession().get(getPersistentClass(), id);
    }

    /**
     * @see fr.mael.jmusic.dao.GenericDao#list()
     */
    public List<T> list() {
        return findByCriteria();
    }

    /**
     * @see fr.mael.jmusic.dao.GenericDao#save(fr.mael.jmusic.dbo.DBOObject)
     */
    public T save(T entity) {
        BaseDomain object = (BaseDomain) entity;
        // it is an update
        if (object.getId() != null) {
            return (T) getSession().merge(object);
        }
        // you are saving a new one
        else {
            getSession().saveOrUpdate(object);
        }
        return entity;
    }

    /** 
     * @see fr.mael.jmusic.dao.GenericDao#delete(fr.mael.jmusic.dbo.DBOObject)
     */
    public void delete(T entity) {
        getSession().delete(getSession().merge(entity));
    }

    /**
     * Flushes the current session
     */
    public void flush() {
        getSession().flush();
    }

    /**
     * Clear the current session
     */
    public void clear() {
        getSession().clear();
    }

    /**
     * @see fr.mael.jmusic.dao.GenericDao#findByCriteria(org.hibernate.criterion.Criterion[])
     */
    public List<T> findByCriteria(Criterion... criterion) {
        Criteria crit = getSession().createCriteria(getPersistentClass());
        for (Criterion c : criterion) {
            crit.add(c);
        }
        return crit.list();
    }

    /**
     * @see fr.mael.jmusic.dao.GenericDao#selectRandom(int)
     */
    @Override
    public List<T> selectRandom(int nb) {
        Criteria criteria = sessionFactory.getCurrentSession().createCriteria(getPersistentClass());
        criteria.add(Restrictions.sqlRestriction("1=1 order by rand() limit " + nb));
        return (List<T>) criteria.list();
    }

    /**
     * @see fr.mael.jmusic.dao.GenericDao#buildSpellIndex()
     */
    @Override
    public void buildSpellIndex() throws IOException {
        FullTextSession searchSession = Search.getFullTextSession(sessionFactory.getCurrentSession());
        SearchFactory searchFactory = searchSession.getSearchFactory();
        IndexReader reader = searchFactory.getIndexReaderAccessor().open(getPersistentClass());
        try {
            FSDirectory spellDir = FSDirectory
                    .open(new File(configuration.getIndexDir() + "/spell_" + getPersistentClass().getName()));
            SpellChecker spellChecker = new SpellChecker(spellDir);
            Dictionary dictionary = new LuceneDictionary(reader, "name");
            IndexWriterConfig config = new IndexWriterConfig(Version.LUCENE_35,
                    searchFactory.getAnalyzer(getPersistentClass()));
            spellChecker.indexDictionary(dictionary, config, true);
        } catch (Exception e) {
            log.error("Error building spell index", e);
        } finally {
            searchFactory.getIndexReaderAccessor().close(reader);
        }

    }

    /**
     * @see fr.mael.jmusic.dao.GenericDao#getSuggestions(java.lang.String)
     */
    @Override
    public String[] getSuggestions(String query) throws IOException {
        Directory directory = FSDirectory
                .open(new File(configuration.getIndexDir() + "/spell_" + getPersistentClass().getName()));
        SpellChecker spell = new SpellChecker(directory);
        spell.setStringDistance(new LevensteinDistance());
        spell.setAccuracy(configuration.getSuggestionAccuracy());
        return spell.suggestSimilar(query, configuration.getSuggestionNumber());
    }

    @Override
    public Long count() {
        Criteria criteria = sessionFactory.getCurrentSession().createCriteria(getPersistentClass());
        criteria.setProjection(Projections.rowCount());
        return (Long) criteria.uniqueResult();
    }

    /**
     * @return the global configuration object
     */
    public Configuration getConfiguration() {
        return configuration;
    }

    /**
     * @param configuration the global configuration object
     */
    public void setConfiguration(Configuration configuration) {
        this.configuration = configuration;
    }

}