mitm.common.sms.hibernate.SMSGatewayDAO.java Source code

Java tutorial

Introduction

Here is the source code for mitm.common.sms.hibernate.SMSGatewayDAO.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.common.sms.hibernate;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import mitm.common.hibernate.GenericHibernateDAO;
import mitm.common.hibernate.SessionAdapter;
import mitm.common.hibernate.SortDirection;
import mitm.common.sms.SMS;
import mitm.common.sms.SortColumn;

import org.apache.commons.lang.SerializationUtils;
import org.hibernate.Criteria;
import org.hibernate.criterion.DetachedCriteria;
import org.hibernate.criterion.Order;
import org.hibernate.criterion.Projections;
import org.hibernate.criterion.Property;
import org.hibernate.criterion.Restrictions;

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

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

    protected SMSGatewayEntity addSMS(SMS sms, Date dateCreated) {
        byte[] serializedData = sms.getData() != null ? SerializationUtils.serialize(sms.getData()) : null;

        SMSGatewayEntity entity = new SMSGatewayEntity(sms.getPhoneNumber(), sms.getMessage(), serializedData,
                dateCreated);

        entity = makePersistent(entity);

        return entity;
    }

    public SMSGatewayEntity addSMS(SMS sms) {
        Date now = new Date();

        return addSMS(sms, now);
    }

    /**
     * Converts the entity to an SMS instance.
     */
    public static SMS entityToSMS(SMSGatewayEntity entity) {
        SMS sms = null;

        if (entity != null) {
            Serializable data = null;

            if (entity.getData() != null) {
                data = (Serializable) SerializationUtils.deserialize(entity.getData());
            }

            sms = new SMSImpl(entity.getID(), entity.getPhoneNumber(), entity.getMessage(), data,
                    entity.getDateCreated(), entity.getDateLastTry(), entity.getLastError());
        }

        return sms;
    }

    public List<SMS> getAll(Integer firstResult, Integer maxResults, SortColumn sortColumn,
            SortDirection sortDirection) {
        Criteria criteria = createCriteria(entityName);

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

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

        if (sortColumn != null) {
            String sortColumnName;

            switch (sortColumn) {
            case PHONENUMBER:
                sortColumnName = SMSGatewayEntity.PHONENUMBER_COLUMN_NAME;
                break;
            case CREATED:
                sortColumnName = SMSGatewayEntity.DATE_CREATED_COLUMN_NAME;
                break;
            case LAST_TRY:
                sortColumnName = SMSGatewayEntity.DATE_LAST_TRY_COLUMN_NAME;
                break;
            default:
                throw new IllegalArgumentException("Unknown sortColumn");
            }

            criteria.addOrder(
                    sortDirection == SortDirection.DESC ? Order.desc(sortColumnName) : Order.asc(sortColumnName));
        }

        List<?> allEntities = criteria.list();

        List<SMS> smss = new ArrayList<SMS>(allEntities.size());

        for (Object entity : allEntities) {
            if (!(entity instanceof SMSGatewayEntity)) {
                throw new IllegalArgumentException("entity is not-a SMSGatewayEntity");
            }

            smss.add(entityToSMS((SMSGatewayEntity) entity));
        }

        return smss;
    }

    public int getAvailableCount(Date notAfter) {
        Criteria criteria = createCriteria(entityName);

        if (notAfter != null) {
            /*
             * We only want entries that are older than notAfter or have no dateLastTry yet
             */
            criteria.add(
                    Restrictions.or(Restrictions.le(SMSGatewayEntity.Columns.DATE_LAST_TRY.getColumn(), notAfter),
                            Restrictions.isNull(SMSGatewayEntity.Columns.DATE_LAST_TRY.getColumn())));
        }

        criteria.setProjection(Projections.rowCount());

        return (Integer) criteria.uniqueResult();
    }

    /**
     * Returns the entry that has the oldest try date and not after notAfter. If there is no such entry null
     * is returned.
     */
    @SuppressWarnings("unchecked")
    public SMSGatewayEntity getNextAvailable(Date notAfter) {
        DetachedCriteria minDateCriteria = createDetachedCriteria(entityName);

        /*
         * Create a criteria to get the oldest dateLastTry
         */
        minDateCriteria.setProjection(Projections.min(SMSGatewayEntity.Columns.DATE_LAST_TRY.getColumn()));

        Criteria criteria = createCriteria(entityName);

        criteria.add(Restrictions.or(
                Property.forName(SMSGatewayEntity.Columns.DATE_LAST_TRY.getColumn()).eq(minDateCriteria),
                Restrictions.isNull(SMSGatewayEntity.Columns.DATE_LAST_TRY.getColumn())));

        /*
         * We only want entries that are older than notAfter or have no dateLastTry yet. The reason for notAfter is
         * that we do not want to try too fast in succession. By setting notAfter in the past we can make sure that
         * we only get entries that are not recently been updated.
         */
        criteria.add(Restrictions.or(Restrictions.le(SMSGatewayEntity.Columns.DATE_LAST_TRY.getColumn(), notAfter),
                Restrictions.isNull(SMSGatewayEntity.Columns.DATE_LAST_TRY.getColumn())));

        SMSGatewayEntity next = null;

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

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

        return next;
    }

    public void deleteAll() {
        List<SMSGatewayEntity> allEntities = findAll();

        for (SMSGatewayEntity entity : allEntities) {
            delete(entity);
        }
    }

    /**
     * Returns all entries that have a created date older than the given date.
     */
    @SuppressWarnings("unchecked")
    public List<SMSGatewayEntity> getExpired(Date olderThan) {
        Criteria criteria = createCriteria(entityName);

        criteria.add(Restrictions.le(SMSGatewayEntity.Columns.DATE_CREATED.getColumn(), olderThan));

        return criteria.list();
    }
}