org.libreplan.business.documents.daos.DocumentDAO.java Source code

Java tutorial

Introduction

Here is the source code for org.libreplan.business.documents.daos.DocumentDAO.java

Source

/*
 * This file is part of LibrePlan
 *
 * Copyright (C) 2009-2010 Fundacin para o Fomento da Calidade Industrial e
 * Desenvolvemento Tecnolxico de Galicia
 *
 * This program is free software: you can redistribute it and/or modify it under
 * the terms of the GNU Affero General Public License as published by the Free
 * Software Foundation, either version 3 of the License, or (at your option) any
 * later version.
 *
 * This program is distributed in the hope that it will be useful, but WITHOUT
 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
 * FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more
 * details.
 *
 * You should have received a copy of the GNU Affero General Public License
 * along with this program. If not, see <http://www.gnu.org/licenses/>.
 */

/**
 * Dao for {@link Document}
 *
 * @author Dergen Lee
 */

package org.libreplan.business.documents.daos;

import java.math.BigInteger;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import org.hibernate.Criteria;
import org.hibernate.Query;
import org.hibernate.criterion.Criterion;
import org.hibernate.criterion.MatchMode;
import org.hibernate.criterion.Restrictions;
import org.libreplan.business.common.daos.GenericDAOHibernate;
import org.libreplan.business.common.exceptions.InstanceNotFoundException;
import org.libreplan.business.departments.entities.Department;
import org.libreplan.business.documents.entities.Document;
import org.libreplan.business.documents.entities.DocumentTypeEnum;
import org.libreplan.business.orders.entities.Order;
import org.libreplan.business.orders.entities.OrderElement;
import org.libreplan.business.users.entities.User;
import org.libreplan.business.works.entities.Work;
import org.springframework.stereotype.Repository;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

@Repository
public class DocumentDAO extends GenericDAOHibernate<Document, Long> implements IDocumentDAO {

    @Override
    public Document getUserRoot(User user) {
        Criteria c = getSession().createCriteria(Document.class);
        c.add(Restrictions.eq("docType", DocumentTypeEnum.PERSONAL));
        c.add(Restrictions.eq("user", user));
        c.add(Restrictions.eq("docTitle", "PersonalRoot-" + user.getId()));
        c.add(Restrictions.isNull("parent"));
        Document doc = (Document) c.uniqueResult();
        if (doc == null) {
            doc = Document.create("PersonalRoot-" + user.getId());
            doc.setDocType(DocumentTypeEnum.PERSONAL);
            doc.setFolder(true);
            doc.setUser(user);
            save(doc);
            flush();
            doc.dontPoseAsTransientObjectAnymore();
        }
        return doc;
    }

    @Override
    public Document getDepartmentRoot(Department dept) {
        Criteria c = getSession().createCriteria(Document.class);
        c.add(Restrictions.eq("docType", DocumentTypeEnum.DEPARTMENT));
        c.add(Restrictions.eq("dept", dept));
        c.add(Restrictions.eq("docTitle", "DepartmentRoot-" + dept.getId()));
        c.add(Restrictions.isNull("parent"));
        Document doc = (Document) c.uniqueResult();
        if (doc == null) {
            doc = Document.create("DepartmentRoot-" + dept.getId());
            doc.setDocType(DocumentTypeEnum.DEPARTMENT);
            doc.setFolder(true);
            doc.setDept(dept);
            save(doc);
            flush();
            doc.dontPoseAsTransientObjectAnymore();
        }
        return doc;
    }

    @Override
    public Document getTaskRoot(OrderElement task) {
        Criteria c = getSession().createCriteria(Document.class);
        c.add(Restrictions.eq("docType", DocumentTypeEnum.TASK));
        c.add(Restrictions.eq("task", task));
        c.add(Restrictions.eq("docTitle", "TaskRoot-" + task.getId()));
        c.add(Restrictions.isNull("parent"));
        Document doc = (Document) c.uniqueResult();
        if (doc == null) {
            doc = Document.create("TaskRoot-" + task.getId());
            doc.setDocType(DocumentTypeEnum.TASK);
            doc.setFolder(true);
            doc.setTask(task);
            save(doc);
            flush();
            doc.dontPoseAsTransientObjectAnymore();
        }
        return doc;
    }

    @Override
    public Document getProjectRoot(Order project) {
        Criteria c = getSession().createCriteria(Document.class);
        c.add(Restrictions.eq("docType", DocumentTypeEnum.PROJECT));
        c.add(Restrictions.eq("project", project));
        c.add(Restrictions.eq("docTitle", "ProjectRoot-" + project.getId()));
        c.add(Restrictions.isNull("parent"));
        Document doc = (Document) c.uniqueResult();
        if (doc == null) {
            doc = Document.create("ProjectRoot-" + project.getId());
            doc.setDocType(DocumentTypeEnum.PROJECT);
            doc.setFolder(true);
            doc.setProject(project);
            save(doc);
            flush();
            doc.dontPoseAsTransientObjectAnymore();
        }
        return doc;
    }

    @Override
    public Document getWorkRoot(Work work) {
        Criteria c = getSession().createCriteria(Document.class);
        c.add(Restrictions.eq("docType", DocumentTypeEnum.WORK));
        c.add(Restrictions.eq("work", work));
        c.add(Restrictions.eq("docTitle", "WorkRoot-" + work.getId()));
        c.add(Restrictions.isNull("parent"));
        Document doc = (Document) c.uniqueResult();
        if (doc == null) {
            doc = Document.create("WorkRoot-" + work.getId());
            doc.setDocType(DocumentTypeEnum.WORK);
            doc.setFolder(true);
            doc.setWork(work);
            save(doc);
            flush();
            doc.dontPoseAsTransientObjectAnymore();
        }
        return doc;
    }

    @Override
    public List<Document> getSubDocuments(Document doc, boolean folder) {
        Criteria c = getSession().createCriteria(Document.class);
        c.add(Restrictions.eq("parent", doc));
        c.add(Restrictions.eq("isFolder", folder));

        c.addOrder(org.hibernate.criterion.Order.asc("sequence"));

        return c.list();
    }

    @Override
    public List<Document> getSubDocuments(Document doc) {
        Criteria c = getSession().createCriteria(Document.class);
        c.add(Restrictions.eq("parent", doc));

        c.addOrder(org.hibernate.criterion.Order.asc("sequence"));

        return c.list();
    }

    @Override
    public List<Document> getDocumentsUploadedBy(User user) {
        Criteria c = getSession().createCriteria(Document.class);
        c.add(Restrictions.eq("uploadedBy", user));
        c.addOrder(org.hibernate.criterion.Order.desc("uploadTime"));
        c.addOrder(org.hibernate.criterion.Order.asc("docType"));

        return c.list();
    }

    @Override
    public void remove(Document document) throws InstanceNotFoundException {
        List<Document> children = this.getSubDocuments(document);
        for (Document child : children)
            remove(child);
        Query query = getSession().createSQLQuery("delete from document_content where id=" + document.getId());
        query.executeUpdate();
        remove(document.getId());
    }

    @Override
    @Transactional(readOnly = true, propagation = Propagation.REQUIRES_NEW)
    public long getDocumentSize(Document document) {
        Long result = 0L;
        if (!document.isFolder()) {
            Query query = getSession()
                    .createSQLQuery("select length(content) from document_content where id=" + document.getId());
            Integer I = (Integer) query.uniqueResult();
            result = (long) ((I == null) ? 0 : I);
        } else {
            Query query = getSession()
                    .createSQLQuery("select sum(length(content)) from document_content where id in"
                            + " (select id from document where parent=" + document.getId() + " and not is_folder)");
            BigInteger bi = ((BigInteger) query.uniqueResult());
            result = (bi == null ? 0 : bi.longValue());
            List<Document> subFolders = this.getSubDocuments(document, true);
            for (Document folder : subFolders) {
                result += getDocumentSize(folder);
            }
        }

        return result;
    }

    @Override
    @Transactional(readOnly = true, propagation = Propagation.REQUIRES_NEW)
    public long getFileCount(Document document) {
        long result = 0L;
        Query query = getSession().createSQLQuery(
                "select count(*) from document where parent=" + document.getId() + " and not is_folder");
        BigInteger bi = ((BigInteger) query.uniqueResult());
        result = (bi == null ? 0L : bi.longValue());
        List<Document> subFolders = this.getSubDocuments(document);
        for (Document folder : subFolders) {
            result += getFileCount(folder);
        }
        return result;
    }

    /**
     * 
     * @param user
     *            :if not null,search only documents belong to user
     * @param onlyTitle
     *            :only search doctitle,otherwise search description also
     * @param keyWords
     *            :keyword to be search
     * @return search result
     */
    @Override
    public List<Document> search(User user, boolean onlyTitle, String... keyWords) {
        if (keyWords.length == 0) {
            return new ArrayList<Document>();
        }
        Criteria c = getSession().createCriteria(Document.class);
        if (user != null) {
            c.add(Restrictions.eq("user", user));
        }
        List<Criterion> keys = new ArrayList<Criterion>();
        for (String keyWord : keyWords) {
            if (keyWord.isEmpty())
                continue;
            keys.add(Restrictions.like("docTitle", keyWord, MatchMode.ANYWHERE));
            if (!onlyTitle)
                keys.add(Restrictions.like("description", keyWord, MatchMode.ANYWHERE));
        }
        Criterion[] crs = keys.toArray(new Criterion[0]);

        c.add(Restrictions.or(crs));
        c.addOrder(org.hibernate.criterion.Order.desc("uploadTime"));
        c.addOrder(org.hibernate.criterion.Order.asc("docType"));
        return c.list();
    }

    @Override
    @Transactional(readOnly = true)
    public List<Document> findWorkDocumentBetween(Date from, Date to) {
        Criteria c = getSession().createCriteria(Document.class);
        c.add(Restrictions.eq("docType", DocumentTypeEnum.WORK))
                .add(Restrictions.not(Restrictions.like("docTitle", "WorkRoot-", MatchMode.START)))
                .createCriteria("work").add(Restrictions.ge("fromTime", from)).add(Restrictions.lt("toTime", to));

        return c.list();
    }

    @Override
    @Transactional(readOnly = true)
    public List<Document> findWorkDocumentBetween(Date from, Date to, boolean folder) {
        Criteria c = getSession().createCriteria(Document.class);
        c.add(Restrictions.eq("docType", DocumentTypeEnum.WORK)).add(Restrictions.eq("isFolder", folder))
                .add(Restrictions.not(Restrictions.like("docTitle", "WorkRoot-", MatchMode.START)))
                .createCriteria("work").add(Restrictions.ge("fromTime", from)).add(Restrictions.lt("toTime", to));

        return c.list();
    }

    @Override
    @Transactional(readOnly = true, propagation = Propagation.REQUIRES_NEW)
    public byte[] getContent(Document doc) {
        if (doc == null)
            return new byte[0];
        Query query = getSession().createSQLQuery("select content from document_content where id=" + doc.getId());
        byte[] result = (byte[]) query.uniqueResult();
        if (result == null)
            return new byte[0];
        else
            return result;
    }

    @Override
    // @Transactional(propagation = Propagation.REQUIRES_NEW)
    public int updateContent(Document doc, byte[] content) {
        if (doc == null)
            return -1;
        if (content == null) {
            return getSession().createSQLQuery("delete from document_content where id=" + doc.getId())
                    .executeUpdate();
        }
        Query query = getSession().createSQLQuery("select id from document_content where id=" + doc.getId());

        String iuSql = "";
        if (query.uniqueResult() == null) {
            iuSql = "insert into document_content (content,id) values (?,?) ";
            query = getSession().createSQLQuery(iuSql);
        } else {
            iuSql = "update document_content set content=? where id=?";
            query = getSession().createSQLQuery(iuSql);
        }
        query.setBinary(0, content);
        query.setLong(1, doc.getId());
        return query.executeUpdate();
    }

    @Override
    @Transactional(readOnly = true, propagation = Propagation.REQUIRES_NEW)
    public int getMaxSequenceOf(Document parent) {
        String sql = "";
        if (parent == null) {
            sql = "select max(sequence) from document where parent is null";
        } else {
            sql = "select max(sequence) from document where parent=" + parent.getId();
        }
        Query query = getSession().createSQLQuery(sql);

        Integer result = (Integer) query.uniqueResult();
        return result == null ? 0 : result;
    }
}