Java tutorial
/** * Copyright(C) 2014 * NEC Corporation All rights reserved. * * No permission to use, copy, modify and distribute this software * and its documentation for any purpose is granted. * This software is provided under applicable license agreement only. */ package com.nec.harvest.service.impl; import java.io.IOException; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import org.apache.commons.collections.CollectionUtils; import org.apache.commons.lang.ArrayUtils; import org.apache.commons.lang.StringUtils; import org.hibernate.HibernateException; import org.hibernate.Query; import org.hibernate.Session; import org.hibernate.Transaction; import org.hibernate.exception.GenericJDBCException; import org.hibernate.exception.SQLGrammarException; import org.hibernate.transform.Transformers; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import com.nec.core.exception.ObjectNotFoundException; import com.nec.crud.hibernate.HibernateSessionManager; import com.nec.harvest.bean.mapping.ActualViewBean; import com.nec.harvest.bean.mapping.InventoryBean; import com.nec.harvest.bean.mapping.json.JSONActualViewBean; import com.nec.harvest.bean.mapping.json.JSONInventory; import com.nec.harvest.constant.Constants; import com.nec.harvest.constant.TblConstants; import com.nec.harvest.exception.ServiceException; import com.nec.harvest.helper.ProductHelper; import com.nec.harvest.model.User; import com.nec.harvest.model.internal.Version; import com.nec.harvest.repository.InventoryRepository; import com.nec.harvest.service.InventoryService; import com.nec.harvest.userdetails.AuthenticatedUserDetails; /** * {@link InventoryService} * * @author sondn * */ @SuppressWarnings("unchecked") public class InventoryServiceImpl implements InventoryService { private static final Logger logger = LoggerFactory.getLogger(InventoryServiceImpl.class); private InventoryRepository repository; public InventoryServiceImpl(InventoryRepository inventoryRepository) { this.repository = inventoryRepository; } /** {@inheritDoc} */ @Override public boolean updateByOrgCodeAndMonthlyAndCtgCode(Session session, String strCode, String monthly, JSONInventory jsonInventory) throws ServiceException { if (StringUtils.isEmpty(strCode)) { throw new IllegalArgumentException("Organization must not be null or empty"); } if (StringUtils.isEmpty(monthly)) { throw new IllegalArgumentException("Monthly must not be null or empty"); } if (jsonInventory == null) { throw new IllegalArgumentException("Inventory must not be null or empty"); } boolean isUpdated = Boolean.FALSE; try { StringBuilder sqlUpdate = new StringBuilder(); sqlUpdate.append(" UPDATE Inventory c"); sqlUpdate.append(" SET c.kingaku=:kingaku, "); sqlUpdate.append( " c.updNo = :newUpdNo, c.tanCode = :tanCode, c.APInf2 =:apInf2, c.stfCodeU = :stfCodeU, c.prdNoU = :prdNoU, c.timeU = NOW()"); sqlUpdate.append( " WHERE c.pk.organization.strCode = :strCode AND c.pk.getSudo = :getSudo AND c.pk.category.ctgCode = :ctgCode"); Query query = repository.getQuery(session, sqlUpdate.toString()); String version = null; try { Version productVersion = ProductHelper.getProductInfor(); if (productVersion != null) { version = productVersion.getProjectVersion(); } } catch (IOException ex) { logger.warn(ex.getMessage(), ex); } query.setDouble("kingaku", jsonInventory.getKingaku()); query.setInteger("newUpdNo", jsonInventory.getUpdNo() + 1); // User user = AuthenticatedUserDetails.getUserPrincipal(); query.setString("apInf2", user.getUsrCode()); query.setString("tanCode", user.getUsrCode()); query.setString("stfCodeU", user.getUsrCode()); query.setString("prdNoU", version); query.setString("strCode", strCode); query.setString("getSudo", monthly); query.setString("ctgCode", jsonInventory.getCtgCode()); int result = query.executeUpdate(); isUpdated = result > 0; } catch (HibernateException ex) { throw new ServiceException("An exception occured while update inventory data ", ex); } return isUpdated; } /** {@inheritDoc} */ @Override public int findUpdNoByOrgCodeAndMonthAndCtgCode(String strCode, String monthly, String ctgCode) throws ServiceException { if (StringUtils.isEmpty(strCode)) { throw new IllegalArgumentException("Organization's code must not be null or empty"); } if (StringUtils.isEmpty(monthly)) { throw new IllegalArgumentException("Monthly must not be null or empty"); } if (ctgCode == null) { throw new IllegalArgumentException("CtgCode must not be null"); } final Session session = HibernateSessionManager.getSession(); Transaction tx = null; int currentUpdNo = 0; try { tx = session.beginTransaction(); StringBuilder sql = new StringBuilder("select max(updNo) from Inventory c"); sql.append( " WHERE c.pk.organization.strCode = :strCode AND c.pk.getSudo = :getSudo AND c.pk.category.ctgCode = :ctgCode AND c.delKbn =2"); // create query Query query = repository.getQuery(session, sql.toString()); query.setParameter("strCode", strCode); query.setParameter("getSudo", monthly); query.setParameter("ctgCode", ctgCode); Object updNo = query.uniqueResult(); if (updNo != null) { currentUpdNo = Integer.parseInt(updNo.toString()); } tx.commit(); } catch (HibernateException ex) { if (tx != null) { tx.rollback(); } throw new ServiceException("An exception occured while get max updNo for the given organization " + strCode + " strCode and catagory code" + ctgCode, ex); } finally { HibernateSessionManager.closeSession(session); } return currentUpdNo; } /** {@inheritDoc} */ @Override public List<InventoryBean> findByOrgCodeAndMonth(String orgCode, String monthly) throws ServiceException { if (StringUtils.isEmpty(orgCode)) { throw new IllegalArgumentException("Organization's code must not be null or empty"); } if (StringUtils.isEmpty(monthly)) { throw new IllegalArgumentException("Monthly must not be null or empty"); } final Session session = HibernateSessionManager.getSession(); Transaction tx = null; List<InventoryBean> inventories = new ArrayList<>(); try { tx = session.beginTransaction(); StringBuffer sql = new StringBuffer( "SELECT a.CtgCode as ctgCode, a.Kingaku as kingaku, a.UpdNo as updNo, b.CtgNameR as ctgName FROM "); sql.append( " AT015 a, AT114 b WHERE a.Getsudo =:getSudo and a.StrCode =:strCode AND a.CtgCode = b.CtgCode "); sql.append(" AND a.DelKbn = 2 ORDER BY ctgCode ASC"); // Query query = repository.getSQLQuery(session, sql.toString()); query.setParameter("strCode", orgCode); query.setParameter("getSudo", monthly); query.setResultTransformer(Transformers.aliasToBean(InventoryBean.class)); inventories = query.list(); // Release transaction tx.commit(); if (CollectionUtils.isEmpty(inventories)) { throw new ObjectNotFoundException( "Could not find any object in monthly " + monthly + " for the organization " + orgCode); } } catch (SQLGrammarException | GenericJDBCException ex) { if (tx != null) { tx.rollback(); } throw new ServiceException("An exception occured while get inventory data ", ex); } finally { HibernateSessionManager.closeSession(session); } return inventories; } /** {@inheritDoc} */ @Override public List<InventoryBean> findByOrgCodeAndMonthAndBunruiKbn(String orgCode, String monthly, String bunruiKbn) throws ServiceException { if (StringUtils.isEmpty(orgCode)) { throw new IllegalArgumentException("Organization's code must not be null or empty"); } if (StringUtils.isEmpty(monthly)) { throw new IllegalArgumentException("Monthly must not be null or empty"); } if (StringUtils.isEmpty(bunruiKbn)) { throw new IllegalArgumentException("BunruiKbn must not be null or empty"); } final Session session = HibernateSessionManager.getSession(); Transaction tx = null; List<InventoryBean> inventories = new ArrayList<>(); try { tx = session.beginTransaction(); StringBuffer sql = new StringBuffer( "SELECT a.CtgCode as ctgCode, a.Kingaku as kingaku, a.UpdNo as updNo, b.CtgNameR as ctgName FROM "); sql.append( " AT015 a, AT114 b WHERE a.Getsudo =:getSudo and a.StrCode =:strCode AND a.CtgCode = b.CtgCode AND b.BunruiKbn = :bunruiKbn "); sql.append(" AND a.DelKbn = 2 AND b.DelKbn = 2 ORDER BY ctgCode ASC"); // Query query = repository.getSQLQuery(session, sql.toString()); query.setParameter("strCode", orgCode); query.setParameter("getSudo", monthly); query.setParameter("bunruiKbn", bunruiKbn); query.setResultTransformer(Transformers.aliasToBean(InventoryBean.class)); inventories = query.list(); // Release transaction tx.commit(); if (CollectionUtils.isEmpty(inventories)) { throw new ObjectNotFoundException( "Could not find any object in monthly " + monthly + " for the organization " + orgCode); } } catch (SQLGrammarException | GenericJDBCException ex) { if (tx != null) { tx.rollback(); } throw new ServiceException("An exception occured while get inventory data ", ex); } finally { HibernateSessionManager.closeSession(session); } return inventories; } /** {@inheritDoc} */ @Override public double calculateInventoryByOrgCodeAndMonthly(String orgCode, String monthly) throws ServiceException { if (StringUtils.isEmpty(orgCode)) { throw new IllegalArgumentException( "Calculation inventory amount cannot implement with organization code empty"); } if (StringUtils.isEmpty(monthly)) { throw new IllegalArgumentException( "Calculation inventory amount cannot implement with current monthly null"); } final Session session = HibernateSessionManager.getSession(); Transaction tx = null; double recordsNo = 0; StringBuffer sql = new StringBuffer(" SELECT SUM(Kingaku) "); sql.append(" FROM " + TblConstants.TBL_INVENTORY); sql.append(" WHERE StrCode=:orgCode AND GetSudo=:monthly AND DelKbn=2"); try { tx = session.beginTransaction(); Query query = repository.getSQLQuery(session, sql.toString()); query.setString("orgCode", orgCode); query.setString("monthly", monthly); Object amount = query.uniqueResult(); // Release transaction tx.commit(); if (amount == null) { throw new ObjectNotFoundException( "Could not find any object in monthly " + monthly + " for the organization " + orgCode); } recordsNo = Double.valueOf(amount.toString()); } catch (SQLGrammarException | GenericJDBCException ex) { if (tx != null) { tx.rollback(); } throw new ServiceException("An exception occured while getting for the given organization " + orgCode + " month " + monthly, ex); } finally { HibernateSessionManager.closeSession(session); } return recordsNo; } /** {@inheritDoc} */ @Override public Map<String, Double> findByOrgCodeAndPeriodMonthly(String strCode, String startMonth, String endMonth) throws ServiceException { if (StringUtils.isEmpty(strCode)) { throw new IllegalArgumentException("Organization's code must not be null or empty"); } if (StringUtils.isEmpty(startMonth)) { throw new IllegalArgumentException("Year must not be null or empty"); } if (StringUtils.isEmpty(endMonth)) { throw new IllegalArgumentException("Year must not be null or empty"); } final Session session = HibernateSessionManager.getSession(); Transaction tx = null; Map<String, Double> mapInventoryes = new HashMap<String, Double>(); try { tx = session.beginTransaction(); StringBuilder sql = new StringBuilder(" SELECT getSudo, SUM(c.Kingaku) as kingaku FROM AT015 c "); sql.append( " WHERE c.strCode = :strCode AND c.getSudo >= :startMonth AND c.getSudo <= :endtMonth AND c.delKbn =2 "); sql.append(" GROUP BY c.getSudo"); // create query Query query = repository.getSQLQuery(session, sql.toString()); query.setParameter("strCode", strCode); query.setParameter("startMonth", startMonth); query.setParameter("endtMonth", endMonth); query.setResultTransformer(Transformers.aliasToBean(InventoryBean.class)); List<InventoryBean> inventories = query.list(); // Release transaction tx.commit(); if (CollectionUtils.isEmpty(inventories)) { throw new ObjectNotFoundException("Could not found any inventory in the DB"); } for (InventoryBean inventoryBean : inventories) { mapInventoryes.put(inventoryBean.getGetSudo(), inventoryBean.getKingaku()); } } catch (SQLGrammarException | GenericJDBCException ex) { if (tx != null) { tx.rollback(); } throw new ServiceException("An exception occured while getting for the given organization " + strCode + " startMonth " + startMonth + " endMonth " + endMonth, ex); } finally { HibernateSessionManager.closeSession(session); } return mapInventoryes; } /** {@inheritDoc} */ @Override public double findTotalAmountByOrgCodeAndMonthly(String orgCode, String month) throws ServiceException { if (StringUtils.isEmpty(orgCode)) { throw new IllegalArgumentException("Organization's code must not be null or empty"); } if (StringUtils.isEmpty(month)) { throw new IllegalArgumentException("Month must not be null or empty"); } final Session session = HibernateSessionManager.getSession(); Transaction tx = null; double recordsNo = 0; try { tx = session.beginTransaction(); StringBuilder sql = new StringBuilder(" SELECT SUM(c.Kingaku) as kingaku FROM AT015 c "); sql.append(" WHERE c.strCode = :strCode AND c.Getsudo = :getSudo "); sql.append(" AND c.DelKbn = 2"); Query query = repository.getSQLQuery(session, sql.toString()); query.setParameter("strCode", orgCode); query.setParameter("getSudo", month); Object result = query.uniqueResult(); // Release transaction tx.commit(); if (result == null) { throw new ObjectNotFoundException("Could not found any inventory in the DB"); } recordsNo = Double.parseDouble(result.toString()); } catch (SQLGrammarException | GenericJDBCException ex) { if (tx != null) { tx.rollback(); } throw new ServiceException( "An exception occured while getting for the given organization " + orgCode + " month " + month, ex); } finally { HibernateSessionManager.closeSession(session); } return recordsNo; } /** {@inheritDoc} */ @Override public double calculateInventoryByOrgCodesAndMonth(String month, String... orgCodes) throws ServiceException { if (ArrayUtils.isEmpty(orgCodes)) { throw new IllegalArgumentException( "Calculation inventory price cannot implement with organization code null"); } if (StringUtils.isEmpty(month)) { throw new IllegalArgumentException( "Calculation inventory amount cannot implement with current month null"); } final Session session = HibernateSessionManager.getSession(); Transaction tx = null; double amountOfInventory = 0; try { tx = session.beginTransaction(); StringBuffer sql = new StringBuffer(" SELECT TRUNCATE(SUM(Kingaku)/1000, 0) "); sql.append(" FROM " + TblConstants.TBL_INVENTORY); sql.append(" WHERE StrCode IN (:orgCodes) AND GetSudo=:month AND DelKbn=2"); Query query = repository.getSQLQuery(session, sql.toString()); query.setParameterList("orgCodes", orgCodes); query.setString("month", month); Object amount = query.uniqueResult(); // Release transaction tx.commit(); if (amount == null) { throw new ObjectNotFoundException( "Could not find any object in monthly " + month + " for the organization " + orgCodes); } amountOfInventory = Double.valueOf(amount.toString()); } catch (SQLGrammarException | GenericJDBCException ex) { if (tx != null) { tx.rollback(); } throw new ServiceException( "Runtime exception occur when calculate inventory price for multi-organization in a month"); } finally { HibernateSessionManager.closeSession(session); } return amountOfInventory; } /** {@inheritDoc} */ @Override public Map<String, Double> findByPeriodMonthAndOrgCodes(String startMonth, String endMonth, List<String> strCodes) throws ServiceException { if (CollectionUtils.isEmpty(strCodes)) { throw new IllegalArgumentException("Organization's codes must not be null or empty"); } if (StringUtils.isEmpty(startMonth)) { throw new IllegalArgumentException("Year must not be null or empty"); } if (StringUtils.isEmpty(endMonth)) { throw new IllegalArgumentException("Year must not be null or empty"); } final Session session = HibernateSessionManager.getSession(); Transaction tx = null; Map<String, Double> mapInventoryes = new HashMap<String, Double>(); try { tx = session.beginTransaction(); StringBuilder sql = new StringBuilder(" SELECT getSudo, SUM(c.Kingaku) as kingaku FROM AT015 c "); sql.append( " WHERE c.strCode in (:strCode) AND c.getSudo >= :startMonth AND c.getSudo <= :endtMonth AND c.delKbn =2 "); sql.append(" GROUP BY c.getSudo"); // create query Query query = repository.getSQLQuery(session, sql.toString()); query.setParameterList("strCode", strCodes); query.setParameter("startMonth", startMonth); query.setParameter("endtMonth", endMonth); query.setResultTransformer(Transformers.aliasToBean(InventoryBean.class)); List<InventoryBean> inventories = query.list(); // Release transaction tx.commit(); if (CollectionUtils.isEmpty(inventories)) { throw new ObjectNotFoundException("Could not found any inventory in the DB"); } // put amount in map value and final tighten date is map key for (InventoryBean inventoryBean : inventories) { mapInventoryes.put(inventoryBean.getGetSudo(), inventoryBean.getKingaku()); } } catch (SQLGrammarException | GenericJDBCException ex) { if (tx != null) { tx.rollback(); } throw new ServiceException("An exception occured while getting for the given organization " + StringUtils.join(strCodes, ",") + " startMonth " + startMonth + " endMonth " + endMonth, ex); } finally { HibernateSessionManager.closeSession(session); } return mapInventoryes; } /** {@inheritDoc} */ @Override public List<ActualViewBean> findDataBeansByOrgCodeAndMonthly(String orgCode, String monthly) throws ServiceException { if (StringUtils.isEmpty(orgCode)) { throw new IllegalArgumentException("Orginazation's code must not be null or empty"); } if (StringUtils.isEmpty(monthly)) { throw new IllegalArgumentException("Month must not be null or empty"); } final Session session = HibernateSessionManager.getSession(); Transaction tx = null; List<ActualViewBean> jisekiBeans = new ArrayList<>(); try { tx = session.beginTransaction(); Query query = repository.getQuery(session, " SELECT " + " a.pk.category.ctgCode as ctgCode, a.pk.category.ctgNameR as ctgNameR, a.kingaku as kingaku, a.updNo as updNo " + " FROM Inventory a " + " WHERE a.delKbn = :delKbn AND a.pk.organization.strCode = :strCode AND a.pk.getSudo = :getSudo "); query.setParameter("strCode", orgCode); query.setParameter("getSudo", monthly); query.setParameter("delKbn", Constants.STATUS_ACTIVE); query.setResultTransformer(Transformers.aliasToBean(ActualViewBean.class)); // jisekiBeans = query.list(); tx.commit(); } catch (HibernateException ex) { if (tx != null) { tx.rollback(); } throw new ServiceException("An error occurred while finding the Inventory Data by organization " + orgCode + " and monthly " + monthly); } finally { HibernateSessionManager.closeSession(session); } return jisekiBeans; } /** {@inheritDoc} */ @Override public boolean updateInventoryData(Session session, String orgCode, String monthly, JSONActualViewBean[] beans) throws ServiceException { if (beans == null) { throw new IllegalArgumentException("Sales beans to update must not be null"); } User user = AuthenticatedUserDetails.getUserPrincipal(); if (user == null) { throw new IllegalArgumentException( "Sorry, you don't have a permission to use this. Please login with right permission"); } try { String sqlUpdate = " UPDATE at015 a SET a.`Kingaku` = :kingaku, a.`TanCode` = :tanCode , a.`UpdNo` = :updNo + 1, " + " a.`APInf2` = :aPInf2, a.`StfCodeU` = :stfCodeU, a.`PrdNoU` = :prdNoU, a.`TimeU` = NOW() " + " WHERE a.`Getsudo` = :getSudo AND a.`StrCode` = :strCode AND a.`CtgCode` = :ctgCode AND a.`UpdNo` = :updNo "; String usrCode = user.getUsrCode(); String version = StringUtils.EMPTY; try { version = ProductHelper.getProductInfor().getVersion(); } catch (IOException ex) { logger.warn(ex.getMessage()); } for (JSONActualViewBean bean : beans) { Query query = repository.getSQLQuery(session, sqlUpdate).setParameter("kingaku", bean.getKingaku()) .setParameter("tanCode", usrCode).setParameter("updNo", bean.getUpdNo()) .setParameter("aPInf2", usrCode).setParameter("stfCodeU", usrCode) .setParameter("prdNoU", version).setParameter("getSudo", monthly) .setParameter("strCode", orgCode).setParameter("ctgCode", bean.getCtgCode()); if (query.executeUpdate() <= 0) { logger.warn("can't update because updNo out of date at inventory record with: strCode = " + orgCode + " and getSudo = " + monthly); return false; } } return true; } catch (SQLGrammarException | GenericJDBCException ex) { throw new ServiceException("An error occurred while update inventory data", ex); } } }