mitm.common.security.ca.hibernate.CertificateRequestDAO.java Source code

Java tutorial

Introduction

Here is the source code for mitm.common.security.ca.hibernate.CertificateRequestDAO.java

Source

/*
 * Copyright (c) 2010-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.common.security.ca.hibernate;

import java.util.Date;
import java.util.List;

import mitm.common.hibernate.GenericHibernateDAO;
import mitm.common.hibernate.SessionAdapter;
import mitm.common.mail.EmailAddressUtils;
import mitm.common.security.ca.CertificateRequest;
import mitm.common.security.ca.Match;

import org.hibernate.Criteria;
import org.hibernate.criterion.Criterion;
import org.hibernate.criterion.DetachedCriteria;
import org.hibernate.criterion.MatchMode;
import org.hibernate.criterion.Order;
import org.hibernate.criterion.Projections;
import org.hibernate.criterion.Property;
import org.hibernate.criterion.Restrictions;

public class CertificateRequestDAO extends GenericHibernateDAO<CertificateRequestEntity, Long> {
    public CertificateRequestDAO(SessionAdapter session) {
        super(session);
    }

    /*
     * Note: We assume that this DAO will only work with CertificateRequest's that are instances of 
     * CertificateRequestEntity's. This ties the implementation to a specific implementation of CertificateRequest.
     * If the DAO should be made more general all relevant data should be copied from the CertificateRequest. This 
     * however requires some minor changes to the CertificateRequest interface to allow access to the raw encoded 
     * public and private key. 
     */
    private CertificateRequestEntity toEntity(CertificateRequest request) {
        if (!(request instanceof CertificateRequestEntity)) {
            throw new IllegalArgumentException("request is-not-a CertificateRequestEntity.");
        }

        return (CertificateRequestEntity) request;
    }

    void addSortOnCreationDate(Criteria criteria) {
        /* 
         * sort on creation date
         */
        criteria.addOrder(Order.asc(CertificateRequestEntity.CREATED_COLUMN_NAME));
    }

    public CertificateRequestEntity addRequest(CertificateRequest request) {
        CertificateRequestEntity entity = toEntity(request);

        makePersistent(entity);

        return entity;
    }

    public void deleteRequest(Long id) {
        CertificateRequestEntity entity = findById(id);

        if (entity != null) {
            delete(entity);
        }
    }

    @SuppressWarnings("unchecked")
    public CertificateRequestEntity getNextRequest(Date notAfter) {
        DetachedCriteria minDateCriteria = createDetachedCriteria(CertificateRequestEntity.ENTITY_NAME);

        /*
         * Create a criteria to get the oldest nextUpdate
         */
        minDateCriteria.setProjection(Projections.min(CertificateRequestEntity.NEXT_UPDATE_COLUMN_NAME));

        Criteria criteria = createCriteria(CertificateRequestEntity.ENTITY_NAME);

        criteria.add(Restrictions.or(
                Property.forName(CertificateRequestEntity.NEXT_UPDATE_COLUMN_NAME).eq(minDateCriteria),
                Restrictions.isNull(CertificateRequestEntity.NEXT_UPDATE_COLUMN_NAME)));

        /*
         * We only want entries that are older than notAfter or have no nextUpdate yet. The reason for notAfter is
         * that we do not want to try too fast in succession. By setting notAfter to the current date we will only 
         * get entries for which the update is long overdue.
         */
        criteria.add(Restrictions.or(Restrictions.le(CertificateRequestEntity.NEXT_UPDATE_COLUMN_NAME, notAfter),
                Restrictions.isNull(CertificateRequestEntity.NEXT_UPDATE_COLUMN_NAME)));

        addSortOnCreationDate(criteria);

        CertificateRequestEntity next = null;

        List<CertificateRequestEntity> found = criteria.list();

        if (found != null && found.size() > 0) {
            next = found.get(0);
        }

        return next;
    }

    public int getSize() {
        Criteria criteria = createCriteria(CertificateRequestEntity.ENTITY_NAME);

        criteria.setProjection(Projections.rowCount());

        return (Integer) criteria.uniqueResult();
    }

    private Criterion createEmailCriterion(String email, Match match) {
        email = EmailAddressUtils.canonicalize(email);

        Criterion criterion;

        if (match == null) {
            match = Match.EXACT;
        }

        switch (match) {
        case EXACT:
            criterion = Restrictions.eq(CertificateRequestEntity.EMAIL_COLUMN_NAME, email);
            break;
        case LIKE:
            criterion = Restrictions.ilike(CertificateRequestEntity.EMAIL_COLUMN_NAME, email, MatchMode.ANYWHERE);
            break;
        default:
            throw new IllegalArgumentException("Unknown Match. " + match);
        }

        return criterion;
    }

    public int getSizeByEmail(String email, Match match) {
        Criteria criteria = createCriteria(CertificateRequestEntity.ENTITY_NAME);

        criteria.setProjection(Projections.rowCount());

        criteria.add(createEmailCriterion(email, match));

        return (Integer) criteria.uniqueResult();
    }

    @SuppressWarnings("unchecked")
    public List<CertificateRequestEntity> getAllRequests(Integer firstResult, Integer maxResults) {
        Criteria criteria = createCriteria(CertificateRequestEntity.ENTITY_NAME);

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

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

        addSortOnCreationDate(criteria);

        return (List<CertificateRequestEntity>) criteria.list();
    }

    @SuppressWarnings("unchecked")
    public List<CertificateRequestEntity> getRequestsByEmail(String email, Match match, Integer firstResult,
            Integer maxResults) {
        Criteria criteria = createCriteria(CertificateRequestEntity.ENTITY_NAME);

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

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

        criteria.add(createEmailCriterion(email, match));

        addSortOnCreationDate(criteria);

        return (List<CertificateRequestEntity>) criteria.list();
    }
}