com.algoTrader.entity.StrategyDaoBase.java Source code

Java tutorial

Introduction

Here is the source code for com.algoTrader.entity.StrategyDaoBase.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.SearchParameter;
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.NonUniqueResultException;
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>Strategy</code>.
 * </p>
 *
 * @see Strategy
 */
public abstract class StrategyDaoBase extends HibernateDaoSupport implements StrategyDao {
    private TransactionDao transactionDao;

    /**
     * Sets the reference to <code>transactionDao</code>.
     * @param transactionDaoIn
     */
    public void setTransactionDao(TransactionDao transactionDaoIn) {
        this.transactionDao = transactionDaoIn;
    }

    /**
     * Gets the reference to <code>transactionDao</code>.
     * @return transactionDao
     */
    protected TransactionDao getTransactionDao() {
        return this.transactionDao;
    }

    private PositionDao positionDao;

    /**
     * Sets the reference to <code>positionDao</code>.
     * @param positionDaoIn
     */
    public void setPositionDao(PositionDao positionDaoIn) {
        this.positionDao = positionDaoIn;
    }

    /**
     * Gets the reference to <code>positionDao</code>.
     * @return positionDao
     */
    protected PositionDao getPositionDao() {
        return this.positionDao;
    }

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

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

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

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

    /**
     * {@inheritDoc}
     */
    @Override
    @SuppressWarnings({ "unchecked" })
    public Collection<Strategy> loadAll() {
        return (Collection<Strategy>) this.loadAll(StrategyDao.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(StrategyDao.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(StrategyImpl.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 Strategy create(Strategy strategy) {
        return (Strategy) this.create(StrategyDao.TRANSFORM_NONE, strategy);
    }

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

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

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

    /**
     * {@inheritDoc}
     */
    @Override
    public Strategy create(String name, boolean autoActivate, double allocation, String modules) {
        return (Strategy) this.create(StrategyDao.TRANSFORM_NONE, name, autoActivate, allocation, modules);
    }

    /**
     * {@inheritDoc}
     */
    @Override
    public Object create(final int transform, String name, boolean autoActivate, double allocation,
            String modules) {
        Strategy entity = new StrategyImpl();
        entity.setName(name);
        entity.setAutoActivate(autoActivate);
        entity.setAllocation(allocation);
        entity.setModules(modules);
        return this.create(transform, entity);
    }

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

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

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

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

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

    /**
     * {@inheritDoc}
     */
    @Override
    @SuppressWarnings({ "unchecked" })
    public Strategy findByName(String name) {
        return (Strategy) this.findByName(StrategyDao.TRANSFORM_NONE, name);
    }

    /**
     * {@inheritDoc}
     */
    @Override
    public Object findByName(final int transform, final String name) {
        return this.findByName(transform, "from StrategyImpl where name = :name ", name);
    }

    /**
     * {@inheritDoc}
     */
    @Override
    public Strategy findByName(final String queryString, final String name) {
        return (Strategy) this.findByName(StrategyDao.TRANSFORM_NONE, queryString, name);
    }

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

    /**
     * {@inheritDoc}
     */
    @Override
    @SuppressWarnings({ "unchecked" })
    public Strategy findByNameFetched(String name) {
        return (Strategy) this.findByNameFetched(StrategyDao.TRANSFORM_NONE, name);
    }

    /**
     * {@inheritDoc}
     */
    @Override
    public Object findByNameFetched(final int transform, final String name) {
        return this.findByNameFetched(transform, "from StrategyImpl as st where st.name = :name ", name);
    }

    /**
     * {@inheritDoc}
     */
    @Override
    public Strategy findByNameFetched(final String queryString, final String name) {
        return (Strategy) this.findByNameFetched(StrategyDao.TRANSFORM_NONE, queryString, name);
    }

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

    /**
     * {@inheritDoc}
     */
    @Override
    @SuppressWarnings({ "unchecked" })
    public List<Strategy> findAutoActivateStrategies() {
        return (List<Strategy>) this.findAutoActivateStrategies(StrategyDao.TRANSFORM_NONE);
    }

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

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

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

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

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

    /**
     * {@inheritDoc}
     */
    @Override
    public List<?> findAutoActivateStrategies(final int transform, final int pageNumber, final int pageSize) {
        return this.findAutoActivateStrategies(transform,
                "select s from StrategyImpl as s where s.autoActivate = true order by s.id", pageNumber, pageSize);
    }

    /**
     * {@inheritDoc}
     */
    @Override
    @SuppressWarnings("unchecked")
    public List<?> findAutoActivateStrategies(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
    public double getPortfolioCashBalanceDouble() {
        try {
            return this.handleGetPortfolioCashBalanceDouble();
        } catch (Throwable th) {
            throw new RuntimeException("Error performing 'StrategyDao.getPortfolioCashBalanceDouble()' --> " + th,
                    th);
        }
    }

    /**
     * Performs the core logic for {@link #getPortfolioCashBalanceDouble()}
     * @return double
     * @throws Exception
     */
    protected abstract double handleGetPortfolioCashBalanceDouble() throws Exception;

    /**
     * {@inheritDoc}
     */
    @Override
    public double getPortfolioSecuritiesCurrentValueDouble() {
        try {
            return this.handleGetPortfolioSecuritiesCurrentValueDouble();
        } catch (Throwable th) {
            throw new RuntimeException(
                    "Error performing 'StrategyDao.getPortfolioSecuritiesCurrentValueDouble()' --> " + th, th);
        }
    }

    /**
     * Performs the core logic for {@link #getPortfolioSecuritiesCurrentValueDouble()}
     * @return double
     * @throws Exception
     */
    protected abstract double handleGetPortfolioSecuritiesCurrentValueDouble() throws Exception;

    /**
     * {@inheritDoc}
     */
    @Override
    public double getPortfolioMaintenanceMarginDouble() {
        try {
            return this.handleGetPortfolioMaintenanceMarginDouble();
        } catch (Throwable th) {
            throw new RuntimeException(
                    "Error performing 'StrategyDao.getPortfolioMaintenanceMarginDouble()' --> " + th, th);
        }
    }

    /**
     * Performs the core logic for {@link #getPortfolioMaintenanceMarginDouble()}
     * @return double
     * @throws Exception
     */
    protected abstract double handleGetPortfolioMaintenanceMarginDouble() throws Exception;

    /**
     * {@inheritDoc}
     */
    @Override
    public double getPortfolioInitialMarginDouble() {
        try {
            return this.handleGetPortfolioInitialMarginDouble();
        } catch (Throwable th) {
            throw new RuntimeException("Error performing 'StrategyDao.getPortfolioInitialMarginDouble()' --> " + th,
                    th);
        }
    }

    /**
     * Performs the core logic for {@link #getPortfolioInitialMarginDouble()}
     * @return double
     * @throws Exception
     */
    protected abstract double handleGetPortfolioInitialMarginDouble() throws Exception;

    /**
     * {@inheritDoc}
     */
    @Override
    public double getPortfolioNetLiqValueDouble() {
        try {
            return this.handleGetPortfolioNetLiqValueDouble();
        } catch (Throwable th) {
            throw new RuntimeException("Error performing 'StrategyDao.getPortfolioNetLiqValueDouble()' --> " + th,
                    th);
        }
    }

    /**
     * Performs the core logic for {@link #getPortfolioNetLiqValueDouble()}
     * @return double
     * @throws Exception
     */
    protected abstract double handleGetPortfolioNetLiqValueDouble() throws Exception;

    /**
     * {@inheritDoc}
     */
    @Override
    public double getPortfolioAvailableFundsDouble() {
        try {
            return this.handleGetPortfolioAvailableFundsDouble();
        } catch (Throwable th) {
            throw new RuntimeException(
                    "Error performing 'StrategyDao.getPortfolioAvailableFundsDouble()' --> " + th, th);
        }
    }

    /**
     * Performs the core logic for {@link #getPortfolioAvailableFundsDouble()}
     * @return double
     * @throws Exception
     */
    protected abstract double handleGetPortfolioAvailableFundsDouble() throws Exception;

    /**
     * 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>StrategyDao</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 StrategyDao}
     * @param entity an entity that was found
     * @return the transformed entity (i.e. new value object, etc)
     * @see StrategyDao#transformEntity(int, Strategy)
     */
    public Object transformEntity(final int transform, final Strategy entity) {
        Object target = null;
        if (entity != null) {
            switch (transform) {
            case StrategyDao.TRANSFORM_NONE: // fall-through
            default:
                target = entity;
            }
        }
        return target;
    }

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

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

    /**
     * @param row
     * @return Strategy
     */
    protected Strategy toEntity(Object[] row) {
        Strategy 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 Strategy) {
                    target = (Strategy) 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), StrategyImpl.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(StrategyDao.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), StrategyImpl.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<Strategy> search(final Search search) {
        return (Set<Strategy>) this.search(StrategyDao.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);
        }
    }

    /**
     * {@inheritDoc}
     */
    @Override
    public Strategy searchUniqueName(final String name) {
        final Search search = new Search(
                new SearchParameter[] { new SearchParameter("name", name, SearchParameter.EQUAL_COMPARATOR) });

        final Set<Strategy> searchResult = this.search(search);
        switch (searchResult.size()) {
        case 0:
            return null;
        case 1:
            return searchResult.iterator().next();
        default:
            throw new NonUniqueResultException(searchResult.size());
        }
    }

    /**
     * {@inheritDoc}
     */
    @Override
    public Object searchUniqueName(final int transform, final String name) {
        final Strategy entity = this.searchUniqueName(name);
        if (entity == null) {
            return null;
        }
        return transformEntity(transform, entity);
    }

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