com.algoTrader.entity.marketData.TickDaoBase.java Source code

Java tutorial

Introduction

Here is the source code for com.algoTrader.entity.marketData.TickDaoBase.java

Source

// license-header java merge-point
//
// Attention: Generated code! Do not modify by hand!
// Generated by: hibernate/SpringHibernateDaoBase.vsl in andromda-spring-cartridge.
//
package com.algoTrader.entity.marketData;

import com.algoTrader.PrincipalStore;
import com.algoTrader.PropertySearch;
import com.algoTrader.Search;
import com.algoTrader.entity.security.Security;
import com.algoTrader.entity.security.SecurityDao;
import com.algoTrader.vo.RawTickVO;
import java.math.BigDecimal;
import java.security.Principal;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Date;
import java.util.Iterator;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.Set;
import org.andromda.spring.PaginationResult;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.collections.Transformer;
import org.hibernate.Criteria;
import org.hibernate.HibernateException;
import org.hibernate.Query;
import org.hibernate.SQLQuery;
import org.hibernate.ScrollableResults;
import org.hibernate.Session;
import org.springframework.dao.InvalidDataAccessResourceUsageException;
import org.springframework.orm.hibernate3.HibernateCallback;
import org.springframework.orm.hibernate3.support.HibernateDaoSupport;

/**
 * <p>
 * Base Spring DAO Class: is able to create, update, remove, load, and find
 * objects of type <code>Tick</code>.
 * </p>
 *
 * @see Tick
 */
public abstract class TickDaoBase extends HibernateDaoSupport implements TickDao {
    private SecurityDao securityDao;

    /**
     * Sets the reference to <code>securityDao</code>.
     * @param securityDaoIn
     */
    public void setSecurityDao(SecurityDao securityDaoIn) {
        this.securityDao = securityDaoIn;
    }

    /**
     * Gets the reference to <code>securityDao</code>.
     * @return securityDao
     */
    protected SecurityDao getSecurityDao() {
        return this.securityDao;
    }

    /**
     * {@inheritDoc}
     */
    @Override
    public Object get(final int transform, final int id) {
        final Object entity = this.getHibernateTemplate().get(TickImpl.class, new Integer(id));
        return transformEntity(transform, (Tick) entity);
    }

    /**
     * {@inheritDoc}
     */
    @Override
    public Tick get(int id) {
        return (Tick) this.get(TRANSFORM_NONE, id);
    }

    /**
     * {@inheritDoc}
     */
    @Override
    public Object load(final int transform, final int id) {
        final Object entity = this.getHibernateTemplate().get(TickImpl.class, new Integer(id));
        return transformEntity(transform, (Tick) entity);
    }

    /**
     * {@inheritDoc}
     */
    @Override
    public Tick load(int id) {
        return (Tick) this.load(TRANSFORM_NONE, id);
    }

    /**
     * {@inheritDoc}
     */
    @Override
    @SuppressWarnings({ "unchecked" })
    public Collection<Tick> loadAll() {
        return (Collection<Tick>) this.loadAll(TickDao.TRANSFORM_NONE);
    }

    /**
     * {@inheritDoc}
     */
    @Override
    public Collection<?> loadAll(final int transform) {
        return this.loadAll(transform, -1, -1);
    }

    /**
     * {@inheritDoc}
     */
    @Override
    public Collection<?> loadAll(final int pageNumber, final int pageSize) {
        return this.loadAll(TickDao.TRANSFORM_NONE, pageNumber, pageSize);
    }

    /**
     * {@inheritDoc}
     */
    @Override
    public Collection<?> loadAll(final int transform, final int pageNumber, final int pageSize) {
        try {
            final Criteria criteria = this.getSession(false).createCriteria(TickImpl.class);
            if (pageNumber > 0 && pageSize > 0) {
                criteria.setFirstResult(this.calculateFirstResult(pageNumber, pageSize));
                criteria.setMaxResults(pageSize);
            }
            final Collection<?> results = criteria.list();
            this.transformEntities(transform, results);
            return results;
        } catch (HibernateException ex) {
            throw super.convertHibernateAccessException(ex);
        }
    }

    /**
     * firstResult = (pageNumber - 1) * pageSize
     * @param pageNumber
     * @param pageSize
     * @return firstResult
     */
    protected int calculateFirstResult(int pageNumber, int pageSize) {
        int firstResult = 0;
        if (pageNumber > 0) {
            firstResult = (pageNumber - 1) * pageSize;
        }
        return firstResult;
    }

    /**
     * {@inheritDoc}
     */
    @Override
    public Tick create(Tick tick) {
        return (Tick) this.create(TickDao.TRANSFORM_NONE, tick);
    }

    /**
     * {@inheritDoc}
     */
    @Override
    public Object create(final int transform, final Tick tick) {
        if (tick == null) {
            throw new IllegalArgumentException("Tick.create - 'tick' can not be null");
        }
        this.getHibernateTemplate().save(tick);
        return this.transformEntity(transform, tick);
    }

    /**
     * {@inheritDoc}
     */
    @Override
    @SuppressWarnings({ "unchecked" })
    public Collection<Tick> create(final Collection<Tick> entities) {
        return (Collection<Tick>) create(TickDao.TRANSFORM_NONE, entities);
    }

    /**
     * {@inheritDoc}
     */
    @Override
    public Collection<?> create(final int transform, final Collection<Tick> entities) {
        if (entities == null) {
            throw new IllegalArgumentException("Tick.create - 'entities' can not be null");
        }
        this.getHibernateTemplate().executeWithNativeSession(new HibernateCallback() {
            public Object doInHibernate(Session session) throws HibernateException {
                for (Tick entity : entities) {
                    create(transform, entity);
                }
                return null;
            }
        });
        return entities;
    }

    /**
     * {@inheritDoc}
     */
    @Override
    public Tick create(BigDecimal last, Date lastDateTime, int vol, int volBid, int volAsk, BigDecimal bid,
            BigDecimal ask, int openIntrest, BigDecimal settlement, Date dateTime) {
        return (Tick) this.create(TickDao.TRANSFORM_NONE, last, lastDateTime, vol, volBid, volAsk, bid, ask,
                openIntrest, settlement, dateTime);
    }

    /**
     * {@inheritDoc}
     */
    @Override
    public Object create(final int transform, BigDecimal last, Date lastDateTime, int vol, int volBid, int volAsk,
            BigDecimal bid, BigDecimal ask, int openIntrest, BigDecimal settlement, Date dateTime) {
        Tick entity = new TickImpl();
        entity.setLast(last);
        entity.setLastDateTime(lastDateTime);
        entity.setVol(vol);
        entity.setVolBid(volBid);
        entity.setVolAsk(volAsk);
        entity.setBid(bid);
        entity.setAsk(ask);
        entity.setOpenIntrest(openIntrest);
        entity.setSettlement(settlement);
        entity.setDateTime(dateTime);
        return this.create(transform, entity);
    }

    /**
     * {@inheritDoc}
     */
    @Override
    public Tick create(BigDecimal ask, BigDecimal bid, Date dateTime, int openIntrest, Security security, int vol,
            int volAsk, int volBid) {
        return (Tick) this.create(TickDao.TRANSFORM_NONE, ask, bid, dateTime, openIntrest, security, vol, volAsk,
                volBid);
    }

    /**
     * {@inheritDoc}
     */
    @Override
    public Object create(final int transform, BigDecimal ask, BigDecimal bid, Date dateTime, int openIntrest,
            Security security, int vol, int volAsk, int volBid) {
        Tick entity = new TickImpl();
        entity.setAsk(ask);
        entity.setBid(bid);
        entity.setDateTime(dateTime);
        entity.setOpenIntrest(openIntrest);
        entity.setSecurity(security);
        entity.setVol(vol);
        entity.setVolAsk(volAsk);
        entity.setVolBid(volBid);
        return this.create(transform, entity);
    }

    /**
     * {@inheritDoc}
     */
    @Override
    public void update(Tick tick) {
        if (tick == null) {
            throw new IllegalArgumentException("Tick.update - 'tick' can not be null");
        }
        this.getHibernateTemplate().update(tick);
    }

    /**
     * {@inheritDoc}
     */
    @Override
    public void update(final Collection<Tick> entities) {
        if (entities == null) {
            throw new IllegalArgumentException("Tick.update - 'entities' can not be null");
        }
        this.getHibernateTemplate().executeWithNativeSession(new HibernateCallback() {
            public Object doInHibernate(Session session) throws HibernateException {
                for (Tick entity : entities) {
                    update(entity);
                }
                return null;
            }
        });
    }

    /**
     * {@inheritDoc}
     */
    @Override
    public void remove(Tick tick) {
        if (tick == null) {
            throw new IllegalArgumentException("Tick.remove - 'tick' can not be null");
        }
        this.getHibernateTemplate().delete(tick);
    }

    /**
     * {@inheritDoc}
     */
    @Override
    public void remove(int id) {
        Tick entity = this.get(id);
        if (entity != null) {
            this.remove(entity);
        }
    }

    /**
     * {@inheritDoc}
     */
    @Override
    public void remove(Collection<Tick> entities) {
        if (entities == null) {
            throw new IllegalArgumentException("Tick.remove - 'entities' can not be null");
        }
        this.getHibernateTemplate().deleteAll(entities);
    }

    /**
     * {@inheritDoc}
     */
    @Override
    @SuppressWarnings({ "unchecked" })
    public Tick findLastTickForSecurityAndMaxDate(int securityId, Date maxDate) {
        return (Tick) this.findLastTickForSecurityAndMaxDate(TickDao.TRANSFORM_NONE, securityId, maxDate);
    }

    /**
     * {@inheritDoc}
     */
    @Override
    public Object findLastTickForSecurityAndMaxDate(final int transform, final int securityId, final Date maxDate) {
        return this.findLastTickForSecurityAndMaxDate(transform,
                "select * from tick where security_fk = :securityId and date_time <= :maxDate order by date_time desc limit 1 ",
                securityId, maxDate);
    }

    /**
     * {@inheritDoc}
     */
    @Override
    public Tick findLastTickForSecurityAndMaxDate(final String queryString, final int securityId,
            final Date maxDate) {
        return (Tick) this.findLastTickForSecurityAndMaxDate(TickDao.TRANSFORM_NONE, queryString, securityId,
                maxDate);
    }

    /**
     * {@inheritDoc}
     */
    @Override
    @SuppressWarnings("unchecked")
    public Object findLastTickForSecurityAndMaxDate(final int transform, final String queryString,
            final int securityId, final Date maxDate) {
        try {
            SQLQuery queryObject = super.getSession(false).createSQLQuery(queryString);
            queryObject.addEntity(TickImpl.class);
            queryObject.setParameter("securityId", new Integer(securityId));
            queryObject.setParameter("maxDate", maxDate);
            Set results = new LinkedHashSet(queryObject.list());
            Object result = null;
            if (results.size() > 1) {
                throw new InvalidDataAccessResourceUsageException(
                        "More than one instance of 'com.algoTrader.entity.marketData.Tick"
                                + "' was found when executing query --> '" + queryString + "'");
            } else if (results.size() == 1) {
                result = results.iterator().next();
            }
            if (transform != TRANSFORM_NONE) {
                result = transformEntity(transform, (Tick) result);
            }
            return result;
        } catch (HibernateException ex) {
            throw super.convertHibernateAccessException(ex);
        }
    }

    /**
     * Allows transformation of entities into value objects
     * (or something else for that matter), when the <code>transform</code>
     * flag is set to one of the constants defined in <code>TickDao</code>, please note
     * that the {@link #TRANSFORM_NONE} constant denotes no transformation, so the entity itself
     * will be returned.
     * <p>
     * This method will return instances of these types:
     * <ul>
     *   <li>{@link Tick} - {@link #TRANSFORM_NONE}</li>
     *   <li>{@link RawTickVO} - {@link #TRANSFORM_RAWTICKVO}</li>
     * </ul>
     *
     * If the integer argument value is unknown {@link #TRANSFORM_NONE} is assumed.
     *
     * @param transform one of the constants declared in {@link TickDao}
     * @param entity an entity that was found
     * @return the transformed entity (i.e. new value object, etc)
     * @see TickDao#transformEntity(int, Tick)
     */
    public Object transformEntity(final int transform, final Tick entity) {
        Object target = null;
        if (entity != null) {
            switch (transform) {
            case TRANSFORM_RAWTICKVO:
                target = toRawTickVO(entity);
                break;
            case TickDao.TRANSFORM_NONE: // fall-through
            default:
                target = entity;
            }
        }
        return target;
    }

    /**
     * {@inheritDoc}
     */
    @Override
    public void transformEntities(final int transform, final Collection<?> entities) {
        switch (transform) {
        case TRANSFORM_RAWTICKVO:
            toRawTickVOCollection(entities);
            break;
        case TickDao.TRANSFORM_NONE: // fall-through
        default:
            // do nothing;
        }
    }

    /**
     * @see TickDao#toEntities(Collection)
     */
    public void toEntities(final Collection<?> results) {
        if (results != null) {
            CollectionUtils.transform(results, this.ENTITYTRANSFORMER);
        }
    }

    /**
     * This anonymous transformer is designed to transform report query results
     * (which result in an array of entities) to {@link Tick}
     * using the Jakarta Commons-Collections Transformation API.
     */
    private Transformer ENTITYTRANSFORMER = new Transformer() {
        public Object transform(Object input) {
            Object result = null;
            if (input instanceof Object[]) {
                result = toEntity((Object[]) input);
            } else if (input instanceof Tick) {
                result = input;
            }
            return result;
        }
    };

    /**
     * @param row
     * @return Tick
     */
    protected Tick toEntity(Object[] row) {
        Tick target = null;
        if (row != null) {
            final int numberOfObjects = row.length;
            for (int ctr = 0; ctr < numberOfObjects; ctr++) {
                final Object object = row[ctr];
                if (object instanceof Tick) {
                    target = (Tick) object;
                    break;
                }
            }
        }
        return target;
    }

    /**
     * {@inheritDoc}
     */
    @Override
    public final Collection toRawTickVOCollection(Collection<?> entities) {
        Collection result = new ArrayList<RawTickVO>();
        if (entities != null) {
            CollectionUtils.transform(entities, this.RAWTICKVO_TRANSFORMER);
            result.addAll((Collection) entities);
        }
        return result;
    }

    /**
     * {@inheritDoc}
     */
    @Override
    @SuppressWarnings({ "unchecked" })
    public final RawTickVO[] toRawTickVOArray(Collection<?> entities) {
        RawTickVO[] result = null;
        if (entities != null) {
            // Unchecked transformation: reuses entities Collection
            final Collection collection = new ArrayList(entities);
            this.toRawTickVOCollection(collection);
            result = (RawTickVO[]) collection.toArray(new RawTickVO[collection.size()]);
        }
        return result;
    }

    /**
     * Default implementation for transforming the results of a report query into a value object. This
     * implementation exists for convenience reasons only. It needs only be overridden in the
     * {@link TickDaoImpl} class if you intend to use reporting queries.
     * @param row
     * @return toRawTickVO(this.toEntity(row))
     * @see TickDao#toRawTickVO(Tick)
     */
    protected RawTickVO toRawTickVO(Object[] row) {
        return this.toRawTickVO(this.toEntity(row));
    }

    /**
     * This anonymous transformer is designed to transform entities or report query results
     * (which result in an array of objects) to {@link RawTickVO}
     * using the Jakarta Commons-Collections Transformation API.
     */
    private Transformer RAWTICKVO_TRANSFORMER = new Transformer() {
        public Object transform(Object input) {
            Object result = null;
            if (input instanceof Tick) {
                result = toRawTickVO((Tick) input);
            } else if (input instanceof Object[]) {
                result = toRawTickVO((Object[]) input);
            }
            return result;
        }
    };

    /**
     * {@inheritDoc}
     */
    @Override
    public final void rawTickVOToEntityCollection(Collection<?> instances) {
        if (instances != null) {
            for (final Iterator<?> iterator = instances.iterator(); iterator.hasNext();) {
                // - remove an objects that are null or not of the correct instance
                if (!(iterator.next() instanceof RawTickVO)) {
                    iterator.remove();
                }
            }
            CollectionUtils.transform(instances, this.RawTickVOToEntityTransformer);
        }
    }

    private final Transformer RawTickVOToEntityTransformer = new Transformer() {
        public Object transform(Object input) {
            return rawTickVOToEntity((RawTickVO) input);
        }
    };

    /**
     * {@inheritDoc}
     */
    @Override
    public void toRawTickVO(Tick source, RawTickVO target) {
        target.setDateTime(source.getDateTime());
        target.setLast(source.getLast());
        target.setLastDateTime(source.getLastDateTime());
        target.setVol(source.getVol());
        target.setVolBid(source.getVolBid());
        target.setVolAsk(source.getVolAsk());
        target.setBid(source.getBid());
        target.setAsk(source.getAsk());
        target.setOpenIntrest(source.getOpenIntrest());
        target.setSettlement(source.getSettlement());
    }

    /**
     * {@inheritDoc}
     */
    @Override
    public RawTickVO toRawTickVO(final Tick entity) {
        RawTickVO target = null;
        if (entity != null) {
            target = new RawTickVO();
            this.toRawTickVO(entity, target);
        }
        return target;
    }

    /**
     * {@inheritDoc}
     */
    @Override
    public void rawTickVOToEntity(RawTickVO source, Tick target, boolean copyIfNull) {
        if (copyIfNull || source.getLast() != null) {
            target.setLast(source.getLast());
        }
        if (copyIfNull || source.getLastDateTime() != null) {
            target.setLastDateTime(source.getLastDateTime());
        }
        if (copyIfNull || source.getVol() != 0) {
            target.setVol(source.getVol());
        }
        if (copyIfNull || source.getVolBid() != 0) {
            target.setVolBid(source.getVolBid());
        }
        if (copyIfNull || source.getVolAsk() != 0) {
            target.setVolAsk(source.getVolAsk());
        }
        if (copyIfNull || source.getBid() != null) {
            target.setBid(source.getBid());
        }
        if (copyIfNull || source.getAsk() != null) {
            target.setAsk(source.getAsk());
        }
        if (copyIfNull || source.getOpenIntrest() != 0) {
            target.setOpenIntrest(source.getOpenIntrest());
        }
        if (copyIfNull || source.getSettlement() != null) {
            target.setSettlement(source.getSettlement());
        }
        if (copyIfNull || source.getDateTime() != null) {
            target.setDateTime(source.getDateTime());
        }
    }

    /**
     * Gets the current <code>principal</code> if one has been set,
     * otherwise returns <code>null</code>.
     *
     * @return the current principal
     */
    protected Principal getPrincipal() {
        return PrincipalStore.get();
    }

    /**
     * {@inheritDoc}
     */
    @Override
    @SuppressWarnings({ "unchecked" })
    public PaginationResult search(final int transform, final int pageNumber, final int pageSize,
            final Search search) {
        try {
            search.setPageNumber(pageNumber);
            search.setPageSize(pageSize);
            final PropertySearch propertySearch = new PropertySearch(this.getSession(false), TickImpl.class,
                    search);
            final List results = propertySearch.executeAsList();
            this.transformEntities(transform, results);
            return new PaginationResult(results.toArray(new Object[results.size()]),
                    propertySearch.getTotalCount());
        } catch (HibernateException ex) {
            throw super.convertHibernateAccessException(ex);
        }
    }

    /**
     * {@inheritDoc}
     */
    @Override
    public PaginationResult search(final int pageNumber, final int pageSize, final Search search) {
        return this.search(TickDao.TRANSFORM_NONE, pageNumber, pageSize, search);
    }

    /**
     * {@inheritDoc}
     */
    @Override
    public Set<?> search(final int transform, final Search search) {
        try {
            final PropertySearch propertySearch = new PropertySearch(this.getSession(false), TickImpl.class,
                    search);
            final Set<?> results = propertySearch.executeAsSet();
            this.transformEntities(transform, results);
            return results;
        } catch (HibernateException ex) {
            throw super.convertHibernateAccessException(ex);
        }
    }

    /**
     * {@inheritDoc}
     */
    @Override
    @SuppressWarnings("unchecked")
    public Set<Tick> search(final Search search) {
        return (Set<Tick>) this.search(TickDao.TRANSFORM_NONE, search);
    }

    /**
     * Executes and returns the given Hibernate queryObject as a {@link PaginationResult} instance.
     * @param queryObject
     * @param transform
     * @param pageNumber
     * @param pageSize
     * @return PaginationResult
     */
    @SuppressWarnings({ "unchecked" })
    protected PaginationResult getPaginationResult(final Query queryObject, final int transform, int pageNumber,
            int pageSize) {
        try {
            final ScrollableResults scrollableResults = queryObject.scroll();
            scrollableResults.last();
            int totalCount = scrollableResults.getRowNumber();
            totalCount = totalCount >= 0 ? totalCount + 1 : 0;
            if (pageNumber > 0 && pageSize > 0) {
                queryObject.setFirstResult(this.calculateFirstResult(pageNumber, pageSize));
                queryObject.setMaxResults(pageSize);
            }
            // Unchecked transformation because Set object is reused, cannot be strongly typed.
            Set results = new LinkedHashSet(queryObject.list());
            transformEntities(transform, results);
            return new PaginationResult(results.toArray(new Object[results.size()]), totalCount);
        } catch (HibernateException ex) {
            throw super.convertHibernateAccessException(ex);
        }
    }

    // spring-hibernate-dao-base merge-point
}