mitm.application.djigzo.impl.hibernate.UserPreferencesDAO.java Source code

Java tutorial

Introduction

Here is the source code for mitm.application.djigzo.impl.hibernate.UserPreferencesDAO.java

Source

/*
 * Copyright (c) 2008-2011, Martijn Brinkers, Djigzo.
 * 
 * This file is part of Djigzo email encryption.
 *
 * Djigzo is free software: you can redistribute it and/or modify
 * it under the terms of the GNU Affero General Public License 
 * version 3, 19 November 2007 as published by the Free Software 
 * Foundation.
 *
 * Djigzo 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 Djigzo. If not, see <http://www.gnu.org/licenses/>
 *
 * Additional permission under GNU AGPL version 3 section 7
 * 
 * If you modify this Program, or any covered work, by linking or 
 * combining it with aspectjrt.jar, aspectjweaver.jar, tyrex-1.0.3.jar, 
 * freemarker.jar, dom4j.jar, mx4j-jmx.jar, mx4j-tools.jar, 
 * spice-classman-1.0.jar, spice-loggerstore-0.5.jar, spice-salt-0.8.jar, 
 * spice-xmlpolicy-1.0.jar, saaj-api-1.3.jar, saaj-impl-1.3.jar, 
 * wsdl4j-1.6.1.jar (or modified versions of these libraries), 
 * containing parts covered by the terms of Eclipse Public License, 
 * tyrex license, freemarker license, dom4j license, mx4j license,
 * Spice Software License, Common Development and Distribution License
 * (CDDL), Common Public License (CPL) the licensors of this Program grant 
 * you additional permission to convey the resulting work.
 */
package mitm.application.djigzo.impl.hibernate;

import java.util.List;

import mitm.common.hibernate.AbstractScrollableResultsIterator;
import mitm.common.hibernate.GenericHibernateDAO;
import mitm.common.hibernate.SessionAdapter;
import mitm.common.hibernate.SortDirection;
import mitm.common.properties.hibernate.NamedBlobEntity;
import mitm.common.security.certstore.hibernate.X509CertStoreEntryHibernate;
import mitm.common.util.CloseableIterator;

import org.hibernate.Criteria;
import org.hibernate.Query;
import org.hibernate.ScrollMode;
import org.hibernate.ScrollableResults;
import org.hibernate.criterion.Projections;
import org.hibernate.criterion.Restrictions;

public class UserPreferencesDAO extends GenericHibernateDAO<UserPreferencesEntity, Long> {
    private String entityName = UserPreferencesEntity.ENTITY_NAME;

    public UserPreferencesDAO(SessionAdapter session) {
        super(session);
    }

    public UserPreferencesEntity getPreferences(String category, String name) {
        Criteria criteria = createCriteria(entityName);
        criteria.add(Restrictions.eq("category", category));
        criteria.add(Restrictions.eq("name", name));

        return (UserPreferencesEntity) criteria.uniqueResult();
    }

    public CloseableIterator<String> getPreferencesIterator(String category) {
        /*
         * We will use HQL because I do not (yet?) know how to return just a field instead of 
         * an object when using the Criteria API.
         */
        final String hql = "select p.name from " + entityName + " p where p.category = :category";

        Query query = createQuery(hql);

        query.setString("category", category);

        ScrollableResults scrollableResults = query.scroll(ScrollMode.FORWARD_ONLY);

        return new StringIterator(scrollableResults);
    }

    public CloseableIterator<String> getPreferencesIterator(String category, Integer firstResult,
            Integer maxResults, SortDirection sortDirection) {
        if (sortDirection == null) {
            sortDirection = SortDirection.ASC;
        }

        /*
         * We will use HQL because I do not (yet?) know how to return just a field instead of 
         * an object when using the Criteria API.
         */
        final String hql = "select p.name from " + entityName + " p where p.category = :category order by p.name "
                + sortDirection;

        Query query = createQuery(hql);

        query.setString("category", category);

        if (firstResult != null) {
            query.setFirstResult(firstResult);
        }

        if (maxResults != null) {
            query.setMaxResults(maxResults);
        }

        ScrollableResults scrollableResults = query.scroll(ScrollMode.FORWARD_ONLY);

        return new StringIterator(scrollableResults);
    }

    public CloseableIterator<String> getCategoryIterator() {
        /*
         * We will use HQL because I do not (yet?) know how to return just a field instead of 
         * an object when using the Criteria API.
         */
        final String hql = "select distinct p.category from " + entityName + " p";

        Query query = createQuery(hql);

        ScrollableResults scrollableResults = query.scroll(ScrollMode.FORWARD_ONLY);

        return new StringIterator(scrollableResults);
    }

    public UserPreferencesEntity addPreferences(String category, String name) {
        UserPreferencesEntity userPreferencesEntity = new UserPreferencesEntity(category, name);

        return makePersistent(userPreferencesEntity);
    }

    public boolean deletePreferences(String category, String name) {
        boolean deleted = false;

        UserPreferencesEntity userPreferencesEntity = getPreferences(category, name);

        if (userPreferencesEntity != null) {
            delete(userPreferencesEntity);

            deleted = true;
        }

        return deleted;
    }

    public void deletePreferences(UserPreferencesEntity userPreferencesEntity) {
        delete(userPreferencesEntity);
    }

    /** 
     * Checks if the given userPreferencesEntity is inherited by another UserPreferencesEntity.
     */
    public boolean isInherited(UserPreferencesEntity userPreferencesEntity) {
        /*
         * Note: The following pure hibernate code is replaced with raw SQL because raw SQL 
         * is orders faster.
         */

        /*
        String hql = "select count(*) from " + entityName + 
          " u where :otherid in (select ip.inheritedPreferences from u.inheritedPreferences ip)";
            
        Query query = createQuery(hql);
            
        query.setParameter("otherid", userPreferencesEntity.getId());
            
        return ((Long) query.uniqueResult()) > 0;
        /*/

        String sql = "select count(*) from userpreferences_inheritedpreferences where inherited_preferences_id = :otherid";

        Query query = createSQLQuery(sql);

        query.setParameter("otherid", userPreferencesEntity.getId());

        return toLong(query.uniqueResult()) > 0;
    }

    /**
     * Checks if the given X509CertStoreEntryHibernate is in the certificate collection of a 
     * UserPreferences instance.
     */
    public long referencingFromCertificatesCount(X509CertStoreEntryHibernate certStoreEntry) {
        /*
         * Note: The following pure hibernate code is replaced with raw SQL because raw SQL 
         * is orders faster.
         */

        /*
        String hql = "select count(*) from " + entityName + 
            " u where :otherid in (select c.id from u.certificates c)";
            
        Query query = createQuery(hql);
            
        query.setParameter("otherid", certStoreEntry.getID());
            
        return (Long) query.uniqueResult();
        */

        /*
         * Note: the names used in the query can change if the generated SQL changes because the entities involve
         * changes
         */
        String sql = "select count(*) from userpreferences_certificates where certificates_id = :otherid";

        Query query = createSQLQuery(sql);

        query.setParameter("otherid", certStoreEntry.getID());

        return toLong(query.uniqueResult());
    }

    /**
     * Returns a list of UserPreferencesEntity's that references the certificate entry from the certificates collection.
     */
    @SuppressWarnings("unchecked")
    public List<UserPreferencesEntity> getReferencingFromCertificates(X509CertStoreEntryHibernate certStoreEntry,
            Integer firstResult, Integer maxResults) {
        String hql = "select u from " + entityName + " u where :otherid in (select c.id from u.certificates c)";

        Query query = createQuery(hql);

        query.setParameter("otherid", certStoreEntry.getID());

        if (firstResult != null) {
            query.setFirstResult(firstResult);
        }

        if (maxResults != null) {
            query.setMaxResults(maxResults);
        }

        return query.list();
    }

    /**
     * Checks if the given X509CertStoreEntryHibernate is in the named certificate collection of a 
     * UserPreferences instance.
     */
    public long referencingFromNamedCertificatesCount(X509CertStoreEntryHibernate certStoreEntry) {
        /*
         * Note: The following pure hibernate code is replaced with raw SQL because raw SQL 
         * is orders faster.
         */

        /*
        String hql = "select count(*) from " + entityName + 
        " u where :otherid in (select c.certificateEntry from u.namedCertificates c)";
            
        Query query = createQuery(hql);
            
        query.setParameter("otherid", certStoreEntry.getID());
            
        return (Long) query.uniqueResult();
        */

        /*
         * Note: the names used in the query can change if the generated SQL changes because the entities involve
         * changes
         */
        String sql = "select count(*) from userpreferences_named_certificates where certificateentry_id = :otherid";

        Query query = createSQLQuery(sql);

        query.setParameter("otherid", certStoreEntry.getID());

        return toLong(query.uniqueResult());
    }

    /**
     * Returns a list of UserPreferencesEntity's that references the certificate entry from the named certificates 
     * collection.
     */
    @SuppressWarnings("unchecked")
    public List<UserPreferencesEntity> getReferencingFromNamedCertificates(
            X509CertStoreEntryHibernate certStoreEntry, Integer firstResult, Integer maxResults) {
        String hql = "select u from " + entityName
                + " u where :otherid in (select c.certificateEntry from u.namedCertificates c)";

        Query query = createQuery(hql);

        query.setParameter("otherid", certStoreEntry.getID());

        if (firstResult != null) {
            query.setFirstResult(firstResult);
        }

        if (maxResults != null) {
            query.setMaxResults(maxResults);
        }

        return query.list();
    }

    /**
     * Checks if the given X509CertStoreEntryHibernate is used as a signing key
     */
    public long referencingFromKeyAndCertificateCount(X509CertStoreEntryHibernate certStoreEntry) {
        /*
         * Note: The following pure hibernate code is replaced with raw SQL because raw SQL 
         * is orders faster.
         */

        /*
        String hql = "select count(*) from " + entityName + 
        " u where :otherid in (select c.id from u.keyAndCertificateEntry c)";
            
        Query query = createQuery(hql);
            
        query.setParameter("otherid", certStoreEntry.getID());
            
        return (Long) query.uniqueResult();
        */

        /*
         * Note: the names used in the query can change if the generated SQL changes because the entities involve
         * changes
         */
        String sql = "select count(*) from userpreferences where keyandcertificateentry_id = :otherid";

        Query query = createSQLQuery(sql);

        query.setParameter("otherid", certStoreEntry.getID());

        return toLong(query.uniqueResult());
    }

    /**
     * Returns a list of UserPreferencesEntity's that references the certificate from the key and certificate.
     */
    @SuppressWarnings("unchecked")
    public List<UserPreferencesEntity> getReferencingFromKeyAndCertificate(
            X509CertStoreEntryHibernate certStoreEntry, Integer firstResult, Integer maxResults) {
        String hql = "select u from " + entityName
                + " u where :otherid in (select c.id from u.keyAndCertificateEntry c)";

        Query query = createQuery(hql);

        query.setParameter("otherid", certStoreEntry.getID());

        if (firstResult != null) {
            query.setFirstResult(firstResult);
        }

        if (maxResults != null) {
            query.setMaxResults(maxResults);
        }

        return query.list();
    }

    /** 
     * Checks if the given X509CertStoreEntryHibernate is referenced by a UserPreferences instance.
     */
    public boolean isReferencing(X509CertStoreEntryHibernate certStoreEntry) {
        boolean referencing = referencingFromCertificatesCount(certStoreEntry) > 0;

        if (!referencing) {
            referencing = referencingFromKeyAndCertificateCount(certStoreEntry) > 0;
        }

        if (!referencing) {
            referencing = referencingFromNamedCertificatesCount(certStoreEntry) > 0;
        }

        return referencing;
    }

    public int getUserPreferencesCount(String category) {
        Criteria criteria = createCriteria(entityName);
        criteria.add(Restrictions.eq("category", category));

        criteria.setProjection(Projections.rowCount());

        return (Integer) criteria.uniqueResult();
    }

    /**
     * Returns the number of UserPreferences that references the NamedBlob 
     */
    public long referencingFromNamedBlobsCount(NamedBlobEntity namedBlob) {
        /*
         * Note: the names used in the query can change if the generated SQL changes because the entities involve
         * changes
         */
        String sql = "select count(*) from userpreferences_named_blob where namedblobs_id = :otherid";

        Query query = createSQLQuery(sql);

        query.setParameter("otherid", namedBlob.getId());

        return toLong(query.uniqueResult());
    }

    /**
     * Returns the UserPreferences that references the NamedBlob 
     */
    @SuppressWarnings("unchecked")
    public List<UserPreferencesEntity> getReferencingFromNamedBlobs(NamedBlobEntity namedBlob, Integer firstResult,
            Integer maxResults) {
        String hql = "select u from " + entityName + " u where :otherid in (select c.id from u.namedBlobs c)";

        Query query = createQuery(hql);

        query.setParameter("otherid", namedBlob.getId());

        if (firstResult != null) {
            query.setFirstResult(firstResult);
        }

        if (maxResults != null) {
            query.setMaxResults(maxResults);
        }

        return query.list();
    }

    private static class StringIterator extends AbstractScrollableResultsIterator<String> {
        public StringIterator(ScrollableResults results) {
            super(results);
        }

        @Override
        protected boolean hasMatch(String element) {
            return element != null;
        }
    }
}