com.algoTrader.entity.PositionDaoBase.java Source code

Java tutorial

Introduction

Here is the source code for com.algoTrader.entity.PositionDaoBase.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;

import com.algoTrader.PrincipalStore;
import com.algoTrader.PropertySearch;
import com.algoTrader.Search;
import com.algoTrader.entity.security.Security;
import java.math.BigDecimal;
import java.security.Principal;
import java.util.Collection;
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.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>Position</code>.
 * </p>
 *
 * @see Position
 */
public abstract class PositionDaoBase extends HibernateDaoSupport implements PositionDao {
    /**
     * {@inheritDoc}
     */
    @Override
    public Object get(final int transform, final int id) {
        final Object entity = this.getHibernateTemplate().get(PositionImpl.class, new Integer(id));
        return transformEntity(transform, (Position) entity);
    }

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

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

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

    /**
     * {@inheritDoc}
     */
    @Override
    @SuppressWarnings({ "unchecked" })
    public Collection<Position> loadAll() {
        return (Collection<Position>) this.loadAll(PositionDao.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(PositionDao.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(PositionImpl.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 Position create(Position position) {
        return (Position) this.create(PositionDao.TRANSFORM_NONE, position);
    }

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

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

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

    /**
     * {@inheritDoc}
     */
    @Override
    public Position create(long quantity, Double exitValue, BigDecimal maintenanceMargin) {
        return (Position) this.create(PositionDao.TRANSFORM_NONE, quantity, exitValue, maintenanceMargin);
    }

    /**
     * {@inheritDoc}
     */
    @Override
    public Object create(final int transform, long quantity, Double exitValue, BigDecimal maintenanceMargin) {
        Position entity = new PositionImpl();
        entity.setQuantity(quantity);
        entity.setExitValue(exitValue);
        entity.setMaintenanceMargin(maintenanceMargin);
        return this.create(transform, entity);
    }

    /**
     * {@inheritDoc}
     */
    @Override
    public Position create(long quantity, Security security, Strategy strategy) {
        return (Position) this.create(PositionDao.TRANSFORM_NONE, quantity, security, strategy);
    }

    /**
     * {@inheritDoc}
     */
    @Override
    public Object create(final int transform, long quantity, Security security, Strategy strategy) {
        Position entity = new PositionImpl();
        entity.setQuantity(quantity);
        entity.setSecurity(security);
        entity.setStrategy(strategy);
        return this.create(transform, entity);
    }

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

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

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

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

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

    /**
     * {@inheritDoc}
     */
    @Override
    @SuppressWarnings({ "unchecked" })
    public List<Position> findOpenPositions() {
        return (List<Position>) this.findOpenPositions(PositionDao.TRANSFORM_NONE);
    }

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

    /**
     * {@inheritDoc}
     */
    @Override
    @SuppressWarnings({ "unchecked" })
    public List<Position> findOpenPositions(final String queryString) {
        return (List<Position>) this.findOpenPositions(PositionDao.TRANSFORM_NONE, queryString);
    }

    /**
     * {@inheritDoc}
     */
    @Override
    @SuppressWarnings({ "unchecked" })
    public List<Position> findOpenPositions(final int pageNumber, final int pageSize) {
        return (List<Position>) this.findOpenPositions(PositionDao.TRANSFORM_NONE, pageNumber, pageSize);
    }

    /**
     * {@inheritDoc}
     */
    @Override
    @SuppressWarnings({ "unchecked" })
    public List<Position> findOpenPositions(final String queryString, final int pageNumber, final int pageSize) {
        return (List<Position>) this.findOpenPositions(PositionDao.TRANSFORM_NONE, queryString, pageNumber,
                pageSize);
    }

    /**
     * {@inheritDoc}
     */
    @Override
    public List<?> findOpenPositions(final int transform, final String queryString) {
        return this.findOpenPositions(transform, queryString, -1, -1);
    }

    /**
     * {@inheritDoc}
     */
    @Override
    public List<?> findOpenPositions(final int transform, final int pageNumber, final int pageSize) {
        return this.findOpenPositions(transform,
                "select p from PositionImpl as p join fetch p.security as s join fetch s.securityFamily as f where p.quantity != 0 order by p.id",
                pageNumber, pageSize);
    }

    /**
     * {@inheritDoc}
     */
    @Override
    @SuppressWarnings("unchecked")
    public List<?> findOpenPositions(final int transform, final String queryString, int pageNumber, int pageSize) {
        try {
            Query queryObject = super.getSession(false).createQuery(queryString);
            queryObject.setCacheable(true);
            if (pageNumber > 0 && pageSize > 0) {
                queryObject.setFirstResult(this.calculateFirstResult(pageNumber, pageSize));
                queryObject.setMaxResults(pageSize);
            }
            List results = queryObject.list();
            transformEntities(transform, results);
            return results;
        } catch (HibernateException ex) {
            throw super.convertHibernateAccessException(ex);
        }
    }

    /**
     * {@inheritDoc}
     */
    @Override
    @SuppressWarnings({ "unchecked" })
    public List<Position> findOpenPositionsByStrategy(String strategyName) {
        return (List<Position>) this.findOpenPositionsByStrategy(PositionDao.TRANSFORM_NONE, strategyName);
    }

    /**
     * {@inheritDoc}
     */
    @Override
    public List<?> findOpenPositionsByStrategy(final int transform, final String strategyName) {
        return this.findOpenPositionsByStrategy(transform, -1, -1, strategyName);
    }

    /**
     * {@inheritDoc}
     */
    @Override
    @SuppressWarnings({ "unchecked" })
    public List<Position> findOpenPositionsByStrategy(final String queryString, final String strategyName) {
        return (List<Position>) this.findOpenPositionsByStrategy(PositionDao.TRANSFORM_NONE, queryString,
                strategyName);
    }

    /**
     * {@inheritDoc}
     */
    @Override
    @SuppressWarnings({ "unchecked" })
    public List<Position> findOpenPositionsByStrategy(final int pageNumber, final int pageSize,
            final String strategyName) {
        return (List<Position>) this.findOpenPositionsByStrategy(PositionDao.TRANSFORM_NONE, pageNumber, pageSize,
                strategyName);
    }

    /**
     * {@inheritDoc}
     */
    @Override
    @SuppressWarnings({ "unchecked" })
    public List<Position> findOpenPositionsByStrategy(final String queryString, final int pageNumber,
            final int pageSize, final String strategyName) {
        return (List<Position>) this.findOpenPositionsByStrategy(PositionDao.TRANSFORM_NONE, queryString,
                pageNumber, pageSize, strategyName);
    }

    /**
     * {@inheritDoc}
     */
    @Override
    public List<?> findOpenPositionsByStrategy(final int transform, final String queryString,
            final String strategyName) {
        return this.findOpenPositionsByStrategy(transform, queryString, -1, -1, strategyName);
    }

    /**
     * {@inheritDoc}
     */
    @Override
    public List<?> findOpenPositionsByStrategy(final int transform, final int pageNumber, final int pageSize,
            final String strategyName) {
        return this.findOpenPositionsByStrategy(transform,
                "from PositionImpl as p join fetch p.security as s join fetch s.securityFamily as f where p.strategy.name = :strategyName and p.quantity != 0 order by p.id ",
                pageNumber, pageSize, strategyName);
    }

    /**
     * {@inheritDoc}
     */
    @Override
    @SuppressWarnings("unchecked")
    public List<?> findOpenPositionsByStrategy(final int transform, final String queryString, int pageNumber,
            int pageSize, final String strategyName) {
        try {
            Query queryObject = super.getSession(false).createQuery(queryString);
            queryObject.setCacheable(true);
            queryObject.setParameter("strategyName", strategyName);
            if (pageNumber > 0 && pageSize > 0) {
                queryObject.setFirstResult(this.calculateFirstResult(pageNumber, pageSize));
                queryObject.setMaxResults(pageSize);
            }
            List results = queryObject.list();
            transformEntities(transform, results);
            return results;
        } catch (HibernateException ex) {
            throw super.convertHibernateAccessException(ex);
        }
    }

    /**
     * {@inheritDoc}
     */
    @Override
    @SuppressWarnings({ "unchecked" })
    public Position findByIdFetched(int id) {
        return (Position) this.findByIdFetched(PositionDao.TRANSFORM_NONE, id);
    }

    /**
     * {@inheritDoc}
     */
    @Override
    public Object findByIdFetched(final int transform, final int id) {
        return this.findByIdFetched(transform,
                "select p from PositionImpl as p join fetch p.security as s join fetch s.securityFamily as f left join fetch s.underlaying as ul where p.id = :id",
                id);
    }

    /**
     * {@inheritDoc}
     */
    @Override
    public Position findByIdFetched(final String queryString, final int id) {
        return (Position) this.findByIdFetched(PositionDao.TRANSFORM_NONE, queryString, id);
    }

    /**
     * {@inheritDoc}
     */
    @Override
    @SuppressWarnings("unchecked")
    public Object findByIdFetched(final int transform, final String queryString, final int id) {
        try {
            Query queryObject = super.getSession(false).createQuery(queryString);
            queryObject.setCacheable(true);
            queryObject.setParameter("id", new Integer(id));
            Set results = new LinkedHashSet(queryObject.list());
            Object result = null;
            if (results.size() > 1) {
                throw new InvalidDataAccessResourceUsageException(
                        "More than one instance of 'com.algoTrader.entity.Position"
                                + "' was found when executing query --> '" + queryString + "'");
            } else if (results.size() == 1) {
                result = results.iterator().next();
            }
            if (transform != TRANSFORM_NONE) {
                result = transformEntity(transform, (Position) result);
            }
            return result;
        } catch (HibernateException ex) {
            throw super.convertHibernateAccessException(ex);
        }
    }

    /**
     * {@inheritDoc}
     */
    @Override
    @SuppressWarnings({ "unchecked" })
    public Position findBySecurityAndStrategy(int securityId, String strategyName) {
        return (Position) this.findBySecurityAndStrategy(PositionDao.TRANSFORM_NONE, securityId, strategyName);
    }

    /**
     * {@inheritDoc}
     */
    @Override
    public Object findBySecurityAndStrategy(final int transform, final int securityId, final String strategyName) {
        return this.findBySecurityAndStrategy(transform,
                "from PositionImpl as p join fetch p.security as s join fetch s.securityFamily as f where p.security.id = :securityId and p.strategy.name = :strategyName",
                securityId, strategyName);
    }

    /**
     * {@inheritDoc}
     */
    @Override
    public Position findBySecurityAndStrategy(final String queryString, final int securityId,
            final String strategyName) {
        return (Position) this.findBySecurityAndStrategy(PositionDao.TRANSFORM_NONE, queryString, securityId,
                strategyName);
    }

    /**
     * {@inheritDoc}
     */
    @Override
    @SuppressWarnings("unchecked")
    public Object findBySecurityAndStrategy(final int transform, final String queryString, final int securityId,
            final String strategyName) {
        try {
            Query queryObject = super.getSession(false).createQuery(queryString);
            queryObject.setCacheable(true);
            queryObject.setParameter("securityId", new Integer(securityId));
            queryObject.setParameter("strategyName", strategyName);
            Set results = new LinkedHashSet(queryObject.list());
            Object result = null;
            if (results.size() > 1) {
                throw new InvalidDataAccessResourceUsageException(
                        "More than one instance of 'com.algoTrader.entity.Position"
                                + "' was found when executing query --> '" + queryString + "'");
            } else if (results.size() == 1) {
                result = results.iterator().next();
            }
            if (transform != TRANSFORM_NONE) {
                result = transformEntity(transform, (Position) 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>PositionDao</code>, please note
     * that the {@link #TRANSFORM_NONE} constant denotes no transformation, so the entity itself
     * will be returned.
     *
     * If the integer argument value is unknown {@link #TRANSFORM_NONE} is assumed.
     *
     * @param transform one of the constants declared in {@link PositionDao}
     * @param entity an entity that was found
     * @return the transformed entity (i.e. new value object, etc)
     * @see PositionDao#transformEntity(int, Position)
     */
    public Object transformEntity(final int transform, final Position entity) {
        Object target = null;
        if (entity != null) {
            switch (transform) {
            case PositionDao.TRANSFORM_NONE: // fall-through
            default:
                target = entity;
            }
        }
        return target;
    }

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

    /**
     * @see PositionDao#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 Position}
     * 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 Position) {
                result = input;
            }
            return result;
        }
    };

    /**
     * @param row
     * @return Position
     */
    protected Position toEntity(Object[] row) {
        Position 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 Position) {
                    target = (Position) object;
                    break;
                }
            }
        }
        return target;
    }

    /**
     * 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), PositionImpl.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(PositionDao.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), PositionImpl.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<Position> search(final Search search) {
        return (Set<Position>) this.search(PositionDao.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
}