TransactionHibernateImpl.java :  » GWT » mufly » net » mufly » server » dao » hibernate » Java Open Source

Java Open Source » GWT » mufly 
mufly » net » mufly » server » dao » hibernate » TransactionHibernateImpl.java
package net.mufly.server.dao.hibernate;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Date;
import java.util.Iterator;
import java.util.List;

import net.mufly.client.ui.summary.account.AccountDTO;
import net.mufly.client.ui.summary.month.MonthDTO;
import net.mufly.domain.Account;
import net.mufly.domain.Tag;
import net.mufly.domain.Transaction;
import net.mufly.server.dao.TransactionDao;

import org.hibernate.HibernateException;
import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.springframework.orm.hibernate3.HibernateTemplate;

import com.extjs.gxt.ui.client.data.BasePagingLoadResult;
import com.extjs.gxt.ui.client.data.PagingLoadConfig;
import com.extjs.gxt.ui.client.data.PagingLoadResult;


public class TransactionHibernateImpl implements TransactionDao {

  private SessionFactory sessionFactory;
  @SuppressWarnings("unused")
  private HibernateTemplate hibernateTemplate;

  //private List<Transaction> transactionList;

  public SessionFactory getSessionFactory() {
    return sessionFactory;
  }

  public void setSessionFactory(SessionFactory sessionFactory) {
    this.sessionFactory = sessionFactory;

    // This is only to use detached criteria to do the finds.
    this.hibernateTemplate = new HibernateTemplate(sessionFactory);
  }

  @SuppressWarnings("unchecked")
  public List<Transaction> lookupTransactionsByAccountTagDate(Account account, Tag tag, Date startDate, Date endDate) {
    Session session = sessionFactory.openSession();

    String myQuery = " from Transaction TR fetch all properties" +
    " where parent is null" + 
    " and TR.account.isHidden = false";

    if (account != null) myQuery += " and account = :accParam ";
    if (tag != null) myQuery += " and :tagParam in elements (TR.tags)";
    if (startDate != null) myQuery += " and :startDateParam <= TR.transactionDate ";
    if (endDate != null) myQuery += " and TR.transactionDate <= :endDateParam";
    myQuery += " order by TR.transactionDate, TR.id";

    Query q = session.createQuery(myQuery);

    if (account != null) q.setParameter("accParam", account);
    if (tag != null) q.setParameter("tagParam", tag);
    if (startDate != null) q.setParameter("startDateParam", startDate);
    if (endDate != null) q.setParameter("endDateParam", endDate);


    List<Transaction> list = q.list();
    // Fetch all the tags from the transactions
    for (Transaction tran : list) {
      System.out.println(tran.getTags());
    }

    session.close();
    return list;

  }

  @SuppressWarnings("unchecked")
  public List<Transaction> lookupTransactionsByParent(Transaction parentTransaction) {
    Session session = sessionFactory.openSession();

    String myQuery = " from Transaction TR fetch all properties" + 
    " where parent = :parentParam" + 
    " order by TR.transactionDate, TR.id";

    Query q = session.createQuery(myQuery);
    q.setParameter("parentParam", parentTransaction);

    List<Transaction> list = q.list();
    // Fetch all the tags from the transactions
    for (Transaction tran : list) {
      System.out.println(tran.getTags());
    }

    session.close();
    return list;
  }

  public void addTransaction(Transaction transaction) {
    System.out.println("Adding transaction (DAO)...");

    // Round the transaction amount
    transaction.setTransactionAmount(round(transaction.getTransactionAmount()));

    Session session = sessionFactory.openSession();
    org.hibernate.Transaction tx = session.beginTransaction();
    try {
      session.save(transaction);
      tx.commit();
      session.flush();
    } catch (HibernateException e) {
      tx.rollback();
    } finally {
      session.close();
    }
  }

  public void updateTransaction(Transaction transaction) {
    System.out.println("Updating transaction (DAO)...");

    // Round the transaction amount
    transaction.setTransactionAmount(round(transaction.getTransactionAmount()));

    Session session = sessionFactory.openSession();
    org.hibernate.Transaction tx = session.beginTransaction();
    try {
      session.update(transaction);
      tx.commit();
      session.flush();
    } catch (HibernateException e) {
      tx.rollback();
    } finally {
      session.close();
    }
  }

  public void deleteTransaction(Transaction transaction) {
    System.out.println("Deleting transaction (DAO)...");

    Session session = sessionFactory.openSession();
    org.hibernate.Transaction tx = session.beginTransaction();
    try {
      session.delete(transaction);
      tx.commit();
      session.flush();
    } catch (HibernateException e) {
      tx.rollback();
    } finally {
      session.close();
    }
  }

  public void addTransactions(List<Transaction> transactions) {
    System.out.println("Adding transactions (DAO)...");

    Session session = sessionFactory.openSession();
    org.hibernate.Transaction tx = session.beginTransaction();
    try {
      for (Transaction transaction : transactions) {
        // Round the transaction amount
        transaction.setTransactionAmount(round(transaction.getTransactionAmount()));

        session.save(transaction);
      }
      tx.commit();
      session.flush();
    } catch (HibernateException e) {
      //e.getMessage();
      tx.rollback();

    } finally {
      session.close();
    }
  }

  public void updateParentAndChildTransactions(Transaction parentTransaction) {
    System.out.println("Updating parent and child transactions (DAO)...");

    // First we get the childs of the transaction
    List<Transaction> childTrans = lookupTransactionsByParent(parentTransaction);

    Session session = sessionFactory.openSession();
    org.hibernate.Transaction tx = session.beginTransaction();
    try {
      // Update the parent
      parentTransaction.setTransactionAmount(round(parentTransaction.getTransactionAmount()));
      session.update(parentTransaction);

      for (Transaction childTransaction : childTrans) {
        // Update the date and the account in every child
        childTransaction.setAccount(parentTransaction.getAccount());
        childTransaction.setTransactionDate(parentTransaction.getTransactionDate());

        session.update(childTransaction);
      }
      tx.commit();
      session.flush();
    } catch (HibernateException e) {
      //e.getMessage();
      tx.rollback();
    } finally {
      session.close();
    }
  }

  @SuppressWarnings("unchecked")
  public List<String> lookupAllTransactionDescriptions() {
    System.out.println("Getting all transactions' descriptions (DAO)...");

    Session session = sessionFactory.openSession();

    String myQuery = "select distinct transactionDesc from Transaction TR";
    myQuery += " order by TR.transactionDesc, TR.id";

    Query q = session.createQuery(myQuery);

    // Get all the transactions' descriptions
    List<String> transDescList = q.list();

    session.close();

    return transDescList;
  }

  public List<MonthDTO> getTotalByMonth(int year) {
    Session session = sessionFactory.openSession();

    String myQuery = "select sum(TR.transactionAmount), month(TR.transactionDate)" +
    " from Transaction TR " + 
    " where year(TR.transactionDate) = :year" +
    " and TR.parent is null" +
    // It should not be necessary. If an account is hidden it's because it has been closed,
    // so all the money has been moved to another account.
    " and TR.account.isHidden = false" +
    " group by month(TR.transactionDate)";

    Query q = session.createQuery(myQuery);
    q.setParameter("year", year);

    List<MonthDTO> monthTotal =  new ArrayList<MonthDTO>();

    Iterator iter = q.iterate();
    while (iter.hasNext()) {
      Object[] row = (Object[]) iter.next();

      MonthDTO tmpMonth = new MonthDTO(round(((Double)row[0]).doubleValue()), ((Integer)row[1]).intValue());
      monthTotal.add(tmpMonth);
    }
    session.close();

    return monthTotal;
  }

  @SuppressWarnings("unchecked")
  public List<Integer> getYears() {
    Session session = sessionFactory.openSession();

    String myQuery = "select distinct year(transactionDate) from Transaction" +
    " order by 1 desc";

    Query q = session.createQuery(myQuery);

    // Get the years of the transactions
    List<Integer> years = q.list();

    session.close();

    return years;
  }

  public List<AccountDTO> getTotalByAccount() {
    Session session = sessionFactory.openSession();

    String myQuery = "select sum(transactionAmount), TR.account" +
    " from Transaction TR" +
    " where TR.parent is null" +
    " group by TR.account" + 
    " order by TR.account.accountName";

    Query q = session.createQuery(myQuery);

    List<AccountDTO> accountTotal =  new ArrayList<AccountDTO>();

    Iterator iter = q.iterate();
    while (iter.hasNext()) {
      Object[] row = (Object[]) iter.next();

      AccountDTO tmpData = new AccountDTO(round(((Double)row[0]).doubleValue()), ((Account)row[1]));
      accountTotal.add(tmpData);
    }
    session.close();

    return accountTotal;
  }

  private double round(double value) {
    BigDecimal bd = new BigDecimal(value);
    bd = bd.setScale(2, BigDecimal.ROUND_HALF_UP);

    return bd.doubleValue();
  }

  public PagingLoadResult<Transaction> getTransactions(PagingLoadConfig config) {


    //if (transactionList == null) {
      //transactionList = lookupTransactionsByAccountTagDate(null, null, null, null);
      
    List<Transaction> transactionList = lookupTransactions(null, false, null, null, null, null, null, null, null);
    //}

//    ArrayList<Transaction> sublist = new ArrayList<Transaction>();
//    int start = config.getOffset();
//    int limit = transactionList.size();
//    if (config.getLimit() > 0) {
//      limit = Math.min(start + config.getLimit(), limit);
//    }
//    for (int i = config.getOffset(); i < limit; i++) {
//      sublist.add(transactionList.get(i));
//    }
//    return new BasePagingLoadResult<Transaction>(sublist, config.getOffset(), transactionList.size());
    return new BasePagingLoadResult<Transaction>(transactionList, 0, transactionList.size());
    //return null;
  }

  public List<Transaction> lookupTransactions(String desc,
      boolean subTrans, Date startDate, Date endDate,
      List<Account> accounts, List<Tag> tags, Double amountGT,
      Double amountLT, PagingLoadConfig config) {

    Session session = sessionFactory.openSession();

    String myQuery = " from Transaction TR fetch all properties" +
    " where TR.account.isHidden = false";


    // Find in description
    if (desc != null) myQuery += " and TR.transactionDesc like :tranDescParam";
    
    // Include childTransactions?
    if (!subTrans) myQuery += " and TR.parent is null";
    
    // startDate <= transactionDate <= endDate
    if (startDate != null) myQuery += " and :startDateParam <= TR.transactionDate";
    if (endDate != null) myQuery += " and TR.transactionDate <= :endDateParam";

    // Accounts: we use an 'OR'
    if (accounts != null) {
      for (int i=0; i<accounts.size(); i++) {
        if (i == 0)  myQuery += " and (:accountParam" + i + " = TR.account";
        else myQuery += " or :accountParam" + i + " = TR.account";

        // Close the parenthesis in the last account
        if (i == accounts.size()-1) myQuery += ") ";    
      }
    }

    // Tags: we use an 'AND'
    if (tags != null) {
      for (int i=0; i<tags.size(); i++) {
        myQuery += " and :tagParam" + i + " in elements (TR.tags)";
      }
    }

    // amountGT <= transactionAmount <= amountLT
    if (amountGT != null) myQuery += " and :amountGTParam <= TR.transactionAmount";
    if (amountLT != null) myQuery += " and TR.transactionAmount <= :amountLTParam";
    
    myQuery += " order by TR.transactionDate, TR.id";

    Query q = session.createQuery(myQuery);

    // Set the parameters
    if (desc != null) q.setParameter("tranDescParam", "%" + desc + "%");
    if (startDate != null) q.setParameter("startDateParam", startDate);
    if (endDate != null) q.setParameter("endDateParam", endDate);
    if (accounts != null) for (int i=0; i<accounts.size(); i++) q.setParameter("accountParam" + i, (Account)accounts.get(i));
    if (tags != null) for (int i=0; i<tags.size(); i++) q.setParameter("tagParam" + i, (Tag)tags.get(i));
    if (amountGT != null) q.setParameter("amountGTParam", amountGT);
    if (amountLT != null) q.setParameter("amountLTParam", amountLT);
    

    List<Transaction> list = q.list();
    // Fetch all the tags from the transactions
    System.out.println("Num trans: " + list.size());
    for (Transaction tran : list) {
      System.out.println(tran.getTags());
    }

    session.close();    
//    ArrayList<Transaction> sublist = new ArrayList<Transaction>();
//    int start = config.getOffset();
//    int limit = list.size();
//    if (config.getLimit() > 0) {
//      limit = Math.min(start + config.getLimit(), limit);
//    }
//    for (int i = config.getOffset(); i < limit; i++) {
//      sublist.add(list.get(i));
//    }
//    return new BasePagingLoadResult<Transaction>(sublist, config.getOffset(), list.size());
    
    //return new BasePagingLoadResult<Transaction>(list, 0, list.size());
    
    return list;
  }
}

java2s.com  | Contact Us | Privacy Policy
Copyright 2009 - 12 Demo Source and Support. All rights reserved.
All other trademarks are property of their respective owners.