com.nec.harvest.service.impl.FixedSystemCostServiceImpl.java Source code

Java tutorial

Introduction

Here is the source code for com.nec.harvest.service.impl.FixedSystemCostServiceImpl.java

Source

/**
 * 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.List;

import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang.StringUtils;
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.FixedSystemCostBean;
import com.nec.harvest.bean.mapping.json.JSONBean;
import com.nec.harvest.bean.mapping.json.JSONFixedSystemCost;
import com.nec.harvest.constant.Constants;
import com.nec.harvest.constant.MsgConstants;
import com.nec.harvest.exception.ServiceException;
import com.nec.harvest.helper.MessageHelper;
import com.nec.harvest.helper.ProductHelper;
import com.nec.harvest.model.User;
import com.nec.harvest.repository.FixedSystemCostRepository;
import com.nec.harvest.service.FixedSystemCostService;
import com.nec.harvest.service.SerialNumberService;
import com.nec.harvest.userdetails.AuthenticatedUserDetails;

/**
 *
 * @author vuta
 *
 */
public class FixedSystemCostServiceImpl implements FixedSystemCostService {

    private static final Logger logger = LoggerFactory.getLogger(InventoryServiceImpl.class);

    private static final int STATE_DELETE = 1;
    private static final int STATE_UPDATE = 2;
    private static final int STATE_INSERT = 3;
    private static final int STATE_COPY = 4;

    private final FixedSystemCostRepository fixedSystemCostRepository;

    private final SerialNumberService serialNumberService;

    public FixedSystemCostServiceImpl(FixedSystemCostRepository fixedSystemCostRepository,
            SerialNumberService serialNumberService) {
        this.fixedSystemCostRepository = fixedSystemCostRepository;
        this.serialNumberService = serialNumberService;
    }

    /** {@inheritDoc} */
    @Override
    @SuppressWarnings("unchecked")
    public List<FixedSystemCostBean> findByOrgCodeAndMonth(String orgCode, String monthly, boolean isCopying)
            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<FixedSystemCostBean> fixedSystemCosts = new ArrayList<>();
        try {
            StringBuffer sql;
            if (!isCopying) {
                sql = new StringBuffer("SELECT a.RecID as recID, a.KmkCode as kmkCode, a.ShoriKbn as shoriKbn,");
                sql.append(
                        " a.Tekiyo as tekiyo, a.HSKbn as hsKbn, a.kingaku as kingaku, a.UpdNo as updNo, ( SELECT d.kmkNameR FROM AT106 d WHERE d.DelKbn = :delKbn AND d.KmkCode = a.kmkCode) as kmkNameR");
                sql.append(" FROM AT017 a WHERE a.Getsudo =:getSudo and a.StrCode =:strCode AND a.DelKbn = 2");
                sql.append(" ORDER BY HSKbn ASC, KmkCode ASC");

            } else {
                sql = new StringBuffer("SELECT a.RecID as recID, a.KmkCode as kmkCode, a.ShoriKbn as shoriKbn,");
                sql.append(
                        " a.Tekiyo as tekiyo, a.HSKbn as hsKbn, a.kingaku as kingaku, a.UpdNo as updNo, ( SELECT d.kmkNameR FROM AT106 d WHERE d.DelKbn = :delKbn AND d.KmkCode = a.kmkCode) as kmkNameR");
                sql.append(
                        " FROM AT017 a WHERE a.Getsudo =:getSudo and a.StrCode =:strCode AND a.DelKbn = 2 AND HSKbn = 1");
                sql.append(" ORDER BY HSKbn ASC, KmkCode ASC");
            }

            tx = session.beginTransaction();
            // 
            Query query = fixedSystemCostRepository.getSQLQuery(session, sql.toString());
            query.setParameter("delKbn", Constants.DEFAULT_DEL_KBN);
            query.setParameter("strCode", orgCode);
            query.setParameter("getSudo", monthly);
            query.setResultTransformer(Transformers.aliasToBean(FixedSystemCostBean.class));

            //
            fixedSystemCosts = query.list();
            // Release transaction
            tx.commit();
            if (CollectionUtils.isEmpty(fixedSystemCosts)) {
                throw new ObjectNotFoundException(
                        "Could not find any object in monthly " + monthly + " for the organization " + orgCode);
            }
        } catch (SQLGrammarException | GenericJDBCException ex) {
            if (tx != null) {
                tx.commit();
            }
            throw new ServiceException("An exception occured while get data ", ex);
        } finally {
            HibernateSessionManager.closeSession(session);
        }
        return fixedSystemCosts;
    }

    /** {@inheritDoc} */
    @Override
    public synchronized boolean insertFixedSystemCost(String monthly, JSONFixedSystemCost jsonFixedSystemCost)
            throws ServiceException {
        if (StringUtils.isEmpty(monthly)) {
            throw new IllegalArgumentException("Monthly must not be null or empty");
        }
        if (jsonFixedSystemCost == null) {
            throw new IllegalArgumentException("Inventory must not be null or empty");
        }
        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");
        }

        final Session session = HibernateSessionManager.getSession();
        Transaction tx = null;

        boolean isInserted = Boolean.FALSE;
        try {
            StringBuilder sql = new StringBuilder();
            sql.append(" INSERT INTO AT017 ");

            //sql.append(" (RecID, StrCode, GetSudo, KmkCode, ShoriKbn, Tekiyo , Kingaku, HSKbn,TanCode, UpdNo, DelKbn) ");
            sql.append(
                    " (RecID, StrCode, GetSudo, KmkCode, ShoriKbn, Tekiyo , Kingaku, HSKbn, TanCode, UpdNo, DelKbn, ");
            sql.append(" APInf1, APInf2, RecCkbn, StfCodeC, StfCodeU, PrdNoC, TimeC, PrdNoU, TimeU) ");
            sql.append(
                    " VALUES(:recID, :strCode, :getSudo, :kmkCode, :shoriKbn, :tekiyo, :kingaku, :hsKbn, :tanCode, :updNo, :delKbn, ");
            sql.append(" :aPInf1, :aPInf2, :recCkbn, :stfCodeC, :stfCodeU, :prdNoC, now(), :prdNoU, now())");

            tx = session.beginTransaction();
            Query query = fixedSystemCostRepository.getSQLQuery(session, sql.toString())
                    .setParameter("recID", jsonFixedSystemCost.getRecID())
                    .setParameter("strCode", user.getOrganization().getStrCode()).setParameter("getSudo", monthly)
                    .setParameter("kmkCode", jsonFixedSystemCost.getKmkCode())
                    .setParameter("shoriKbn", jsonFixedSystemCost.getShoriKbn())
                    .setParameter("tekiyo", jsonFixedSystemCost.getTekiyo())
                    .setParameter("kingaku", jsonFixedSystemCost.getKingaku())
                    .setParameter("hsKbn", jsonFixedSystemCost.getHsKbn())
                    .setParameter("tanCode", user.getUsrCode()).setParameter("updNo", Constants.DEFAULT_INT_ONE)
                    .setParameter("delKbn", Constants.STATUS_ACTIVE)

                    .setParameter("aPInf1", user.getUsrCode()).setParameter("aPInf2", user.getUsrCode())
                    .setParameter("recCkbn", Constants.DEFAULT_KBN).setParameter("stfCodeC", user.getUsrCode())
                    .setParameter("stfCodeU", user.getUsrCode());

            try {
                String version = ProductHelper.getProductInfor().getVersion();
                query.setParameter("prdNoC", version);
                query.setParameter("prdNoU", version);
            } catch (IOException ex) {
                logger.warn(ex.getMessage());
            }

            // 
            int result = query.executeUpdate();
            isInserted = result > 0;
            tx.commit();
        } catch (SQLGrammarException | GenericJDBCException ex) {
            if (tx != null) {
                tx.rollback();
            }
            throw new ServiceException("An exception occured while inserting data ", ex);
        } finally {
            HibernateSessionManager.closeSession(session);
        }
        return isInserted;
    }

    /** {@inheritDoc} */
    @Override
    public boolean updateFixedSystemCost(JSONFixedSystemCost jsonFixedSystemCost) throws ServiceException {
        if (jsonFixedSystemCost == null) {
            throw new IllegalArgumentException("Inventory must not be null or empty");
        }

        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");
        }

        final Session session = HibernateSessionManager.getSession();
        Transaction tx = null;

        boolean isUpdated = Boolean.FALSE;
        try {

            StringBuilder sqlUpdate = new StringBuilder();
            sqlUpdate.append(" UPDATE AT017 c");
            sqlUpdate.append(" SET c.KmKCode=:kmkCode, ");
            sqlUpdate.append(
                    " c.ShoriKbn = :shoriKbn, c.tanCode = :tanCode, c.APInf2 =:apInf2, c.StfCodeU = :stfCodeU, c.prdNoU = :prdNoU, c.TimeU = NOW(),");
            sqlUpdate.append(
                    " c.Tekiyo = :tekiYo, c.HSKbn = :hsKbn, c.Kingaku = :kingaku, c.UpdNo = (:updNo + 1), c.RecCkbn = :recCkbn, c.DelKbn = :delKbn ");
            sqlUpdate.append(" WHERE c.RecID = :recID AND c.UpdNo = :updNo");

            tx = session.beginTransaction();
            //
            Query query = fixedSystemCostRepository.getSQLQuery(session, sqlUpdate.toString());
            query.setParameter("kmkCode", jsonFixedSystemCost.getKmkCode());
            query.setParameter("shoriKbn", jsonFixedSystemCost.getShoriKbn());
            query.setParameter("tanCode", user.getUsrCode());
            query.setParameter("apInf2", user.getUsrCode());
            query.setParameter("stfCodeU", user.getUsrCode());
            query.setParameter("tekiYo", jsonFixedSystemCost.getTekiyo());
            query.setParameter("hsKbn", jsonFixedSystemCost.getHsKbn());
            query.setParameter("kingaku", jsonFixedSystemCost.getKingaku());
            query.setParameter("updNo", jsonFixedSystemCost.getUpdNo());
            query.setParameter("recID", jsonFixedSystemCost.getRecID());
            query.setParameter("delKbn", Constants.STATUS_ACTIVE);
            query.setParameter("recCkbn", Constants.DEFAULT_KBN);

            try {
                query.setParameter("prdNoU", ProductHelper.getProductInfor().getVersion());
            } catch (IOException e) {
                logger.warn("Can not get product informations when update help record");
            }

            // 
            int result = query.executeUpdate();
            isUpdated = result > 0;
            tx.commit();
        } catch (SQLGrammarException | GenericJDBCException ex) {
            if (tx != null) {
                tx.rollback();
            }
            throw new ServiceException("An exception occured while updating  data ", ex);
        } finally {
            HibernateSessionManager.closeSession(session);
        }
        return isUpdated;
    }

    /** {@inheritDoc} */
    @Override
    public boolean deleteByRecordId(String recId) throws ServiceException {
        if (StringUtils.isEmpty(recId)) {
            throw new IllegalArgumentException("Array FixedSystemCost must not be null or empty");
        }

        final Session session = HibernateSessionManager.getSession();
        Transaction tx = null;

        boolean isDeleted = Boolean.FALSE;
        try {
            tx = session.beginTransaction();
            String sql = " DELETE FROM  FixedSystemCost a WHERE  a.recID = :recID";
            Query query = fixedSystemCostRepository.getQuery(session, sql).setParameter("recID", recId);

            // 
            isDeleted = query.executeUpdate() > 0;
            // Release transaction
            tx.commit();
        } catch (SQLGrammarException | GenericJDBCException ex) {
            if (tx != null) {
                tx.rollback();
            }
            throw new ServiceException("An error occurred while delete FixedSystemCost list");
        } finally {
            HibernateSessionManager.closeSession(session);
        }
        return isDeleted;
    }

    /** {@inheritDoc} */
    @Override
    public JSONBean handleData(String monthly, JSONFixedSystemCost[] fixedSystemCosts) throws ServiceException {
        if (StringUtils.isEmpty(monthly)) {
            throw new IllegalArgumentException("Monthly must not be null or empty");
        }

        User user = AuthenticatedUserDetails.getUserPrincipal();
        if (user == null) {
            logger.warn("Sorry, you don't have a permission to use this. Please login with right permission");
            // 
            throw new IllegalArgumentException(
                    "Sorry, you don't have a permission to use this. Please login with right permission");
        }

        // if have any object have state = copy then delete data of month 
        if (fixedSystemCosts.length <= 0 || fixedSystemCosts[0].getState() == STATE_COPY) {
            final Session session = HibernateSessionManager.getSession();
            Transaction tx = null;

            try {
                String sqlDelete = "DELETE from AT017  WHERE AT017.StrCode = :strCode AND AT017.Getsudo = :getSudo AND AT017.DelKbn = 2 AND AT017.HSKbn <> 0";

                tx = session.beginTransaction();
                Query deleteQuery = fixedSystemCostRepository.getSQLQuery(session, sqlDelete);
                deleteQuery.setParameter("strCode", user.getOrganization().getStrCode());
                deleteQuery.setParameter("getSudo", monthly);
                deleteQuery.executeUpdate();

                // 
                tx.commit();
            } catch (SQLGrammarException | GenericJDBCException ex) {
                if (tx != null) {
                    tx.rollback();
                }
                return new JSONBean(Boolean.FALSE, -1, MessageHelper.getSystemError());
            } finally {
                HibernateSessionManager.closeSession(session);
            }
        }

        for (JSONFixedSystemCost fixedSystemCost : fixedSystemCosts) {
            int state = fixedSystemCost.getState();
            switch (state) {
            case STATE_DELETE: {
                //delete data from table
                boolean deleteState = deleteByRecordId(fixedSystemCost.getRecID());
                if (!deleteState) {
                    logger.warn("Could not delete the record with entity's code " + fixedSystemCost.getRecID()
                            + " and updNo = " + fixedSystemCost.getUpdNo());

                    // Update not successful
                    return new JSONBean(Boolean.FALSE, 2, MessageHelper.get(MsgConstants.CM_UPD_M03));
                }
                break;
            }
            case STATE_UPDATE: {
                boolean updateState = updateFixedSystemCost(fixedSystemCost);
                if (!updateState) {
                    logger.warn("Could not update the record with entity's code " + fixedSystemCost.getRecID()
                            + " and updNo = " + fixedSystemCost.getUpdNo());

                    // Update not successful
                    return new JSONBean(Boolean.FALSE, 2, MessageHelper.get(MsgConstants.CM_UPD_M01));
                }
                break;
            }
            case STATE_COPY:
            case STATE_INSERT: {
                String maximumSeqNo = null;

                try {
                    final String REC_CODE = "AT017.RecID";
                    maximumSeqNo = serialNumberService.generateUUIDByRecID(REC_CODE);
                } catch (ServiceException ex) {
                    logger.error(ex.getMessage(), ex);

                    // 
                    return new JSONBean(Boolean.FALSE, -1, MessageHelper.getSystemError());
                }

                if (StringUtils.isEmpty(maximumSeqNo)) {
                    logger.warn("Could not generate a sequence number at this time");

                    //
                    return new JSONBean(Boolean.FALSE, 2, MessageHelper.get(MsgConstants.CM_UPD_M03));
                }

                logger.info("Old serial number is {} and maximum serial number is {}", fixedSystemCost.getRecID(),
                        maximumSeqNo);

                // Creating a new one move transfer for the given sequence number
                fixedSystemCost.setRecID(maximumSeqNo);

                // Insert data into table
                boolean insertResult = insertFixedSystemCost(monthly, fixedSystemCost);

                if (!insertResult) {
                    logger.warn("Could not delete the record with entity's code " + fixedSystemCost.getRecID()
                            + " and updNo = " + fixedSystemCost.getUpdNo());

                    // Update not successful
                    return new JSONBean(Boolean.FALSE, 2, MessageHelper.get(MsgConstants.CM_UPD_M03));
                }

                logger.info("Successfully created a new one move transfer");
                break;
            }
            default: {
                break;
            }
            }
        }

        logger.info("Handle submission data from client successfuly");
        return new JSONBean(Boolean.TRUE, 1, MessageHelper.get(MsgConstants.CM_UPD_M02));
    }

}