com.castis.xylophone.adsmadapter.convert.axistree.ConvertMgad.java Source code

Java tutorial

Introduction

Here is the source code for com.castis.xylophone.adsmadapter.convert.axistree.ConvertMgad.java

Source

package com.castis.xylophone.adsmadapter.convert.axistree;

import java.sql.SQLException;
import java.sql.Timestamp;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.Date;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.SortedSet;
import java.util.TreeSet;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.hibernate.HibernateException;
import org.hibernate.exception.DataException;
import org.springframework.transaction.annotation.Isolation;
import org.springframework.transaction.annotation.Transactional;

import com.castis.tambourine.bizobject.adcontract.ADCampaign;
import com.castis.tambourine.bizobject.adcontract.ADCampaignDailyExposure;
import com.castis.tambourine.bizobject.adcontract.ADCampaignDailyExposureKey;
import com.castis.tambourine.bizobject.common.Period;
import com.castis.tambourine.bizobject.inventory.GenericAxisItemID;
import com.castis.tambourine.bizobject.ktadsm.ADSMJobNameType;
import com.castis.tambourine.bizobject.ktadsm.ADSMSchedulerStatus;
import com.castis.tambourine.bizobject.ktadsm.AbstractInventoryPolicy;
import com.castis.tambourine.bizobject.ktadsm.ImportSyncVersion;
import com.castis.tambourine.bizobject.ktadsm.cuetone.CampaignTargetInfo;
import com.castis.tambourine.bizobject.user.NonTargetUserGroup;
import com.castis.tambourine.converter.Converter;
import com.castis.tambourine.define.Constants;
import com.castis.tambourine.dto.inventory.GenericAxisItemIDSet;
import com.castis.tambourine.dto.ktadsm.ADProductPriorityItemDTO;
import com.castis.tambourine.dto.ktadsm.ADProductPriorityPolicyDTO;
import com.castis.tambourine.dto.ktadsm.ADSMCampaignDTO;
import com.castis.tambourine.dto.ktadsm.ADSMSchedulerLogDTO;
import com.castis.tambourine.dto.ktadsm.CategoryDataDTO;
import com.castis.tambourine.dto.ktadsm.ContinuosExposurePolicyDTO;
import com.castis.tambourine.dto.ktadsm.DisableAttribute;
import com.castis.tambourine.dto.ktadsm.DisableItemDTO;
import com.castis.tambourine.dto.ktadsm.DisablePolicyDTO;
import com.castis.tambourine.dto.ktadsm.DisableSameFieldADItemDTO;
import com.castis.tambourine.dto.ktadsm.DisableSameFieldADPolicyDTO;
import com.castis.tambourine.dto.ktadsm.ExposurePolicyDTO;
import com.castis.tambourine.dto.ktadsm.FeSyncNoticeboardDTO;
import com.castis.tambourine.dto.ktadsm.GenericAxisItemIDDTO;
import com.castis.tambourine.dto.ktadsm.GroupRatePolicyDTO;
import com.castis.tambourine.dto.ktadsm.GroupRateType;
import com.castis.tambourine.dto.ktadsm.SlotNumberPolicyDTO;
import com.castis.tambourine.dto.ktadsm.SubInventoryDTO;
import com.castis.tambourine.dto.ktadsm.SubInventoryMemberDTO;
import com.castis.tambourine.dto.ktadsm.campaign.AdCategory;
import com.castis.tambourine.dto.ktadsm.campaign.AdProduct_priority;
import com.castis.tambourine.dto.ktadsm.campaign.Ad_list;
import com.castis.tambourine.dto.ktadsm.campaign.Ads;
import com.castis.tambourine.dto.ktadsm.campaign.AdsInfo;
import com.castis.tambourine.dto.ktadsm.campaign.Ads_disable;
import com.castis.tambourine.dto.ktadsm.campaign.Ads_disable_detail;
import com.castis.tambourine.dto.ktadsm.campaign.Category;
import com.castis.tambourine.dto.ktadsm.campaign.Category_monopolyRate;
import com.castis.tambourine.dto.ktadsm.campaign.Category_promoRate;
import com.castis.tambourine.dto.ktadsm.campaign.Channel;
import com.castis.tambourine.dto.ktadsm.campaign.Channel_monopolyRate;
import com.castis.tambourine.dto.ktadsm.campaign.Channel_promoRate;
import com.castis.tambourine.dto.ktadsm.campaign.Content;
import com.castis.tambourine.dto.ktadsm.campaign.ContentGroup;
import com.castis.tambourine.dto.ktadsm.campaign.Content_group_monopolyRate;
import com.castis.tambourine.dto.ktadsm.campaign.Content_group_promoRate;
import com.castis.tambourine.dto.ktadsm.campaign.Content_monopolyRate;
import com.castis.tambourine.dto.ktadsm.campaign.Content_promoRate;
import com.castis.tambourine.dto.ktadsm.campaign.DailyGoiLimit;
import com.castis.tambourine.dto.ktadsm.campaign.Exclusive_content_disable;
import com.castis.tambourine.dto.ktadsm.campaign.Exclusive_user_user_group_disable;
import com.castis.tambourine.dto.ktadsm.campaign.ExposurePolicy;
import com.castis.tambourine.dto.ktadsm.campaign.PlayInfo;
import com.castis.tambourine.dto.ktadsm.campaign.Slot_detail;
import com.castis.tambourine.dto.ktadsm.campaign.Target;
import com.castis.tambourine.dto.ktadsm.campaign.TargetList;
import com.castis.tambourine.dto.ktadsm.campaign.User;
import com.castis.tambourine.dto.ktadsm.campaign.UserGroup;
import com.castis.tambourine.dto.ktadsm.result.ResultAdsInfo;
import com.castis.tambourine.enumeration.ADCampaignClassType;
import com.castis.tambourine.enumeration.ADCampaignStatus;
import com.castis.tambourine.enumeration.AdvertiesmentType;
import com.castis.tambourine.enumeration.DataIntegrityExceptionType;
import com.castis.tambourine.enumeration.DeleteDataType;
import com.castis.tambourine.enumeration.ExecutionState;
import com.castis.tambourine.enumeration.FeSyncNoticeboardStatus;
import com.castis.tambourine.enumeration.InventoryBoxDayCode;
import com.castis.tambourine.enumeration.InventoryType;
import com.castis.tambourine.enumeration.OperationType;
import com.castis.tambourine.enumeration.PayTargetType;
import com.castis.tambourine.enumeration.PlacementOpportunityTypeEnum;
import com.castis.tambourine.enumeration.Platform;
import com.castis.tambourine.enumeration.PriceTypeEnum;
import com.castis.tambourine.enumeration.RelayTargetType;
import com.castis.tambourine.enumeration.ScheduleRoundType;
import com.castis.tambourine.enumeration.SubscriptionType;
import com.castis.tambourine.enumeration.SyncDataType;
import com.castis.tambourine.enumeration.SyncType;
import com.castis.tambourine.enumeration.TargetRate;
import com.castis.tambourine.enumeration.TargetType;
import com.castis.tambourine.enumeration.TreeType;
import com.castis.tambourine.exception.DataIntegrityException;
import com.castis.tambourine.exception.DuplicatedNameException;
import com.castis.tambourine.exception.NotFoundException;
import com.castis.tambourine.exception.WrappingException;
import com.castis.tambourine.exportModel.campaign.AccumulationGoiDay;
import com.castis.tambourine.inventorydomain.bizcomp.model.InventorySizeManager;
import com.castis.tambourine.inventorysysdomain.syscomp.export.IInventoryExportSysCompForAdapter;
import com.castis.tambourine.logger.TheLogger;
import com.castis.tambourine.util.DateUtil;
import com.castis.xylophone.adsmadapter.common.enumeration.InputDataType;
import com.castis.xylophone.adsmadapter.common.util.CiDateUtil;
import com.castis.xylophone.adsmadapter.common.util.CiStringUtil;
import com.castis.xylophone.adsmadapter.common.util.ResultFileUtil;
import com.castis.xylophone.adsmadapter.connectors.TambourineConnector;
import com.castis.xylophone.adsmadapter.setting.ADDSAdapterSetting;

/**
 * @author  Leftie
 */
public class ConvertMgad {
    //private static int DEFAULT_PRIORITY = 5; 
    IInventoryExportSysCompForAdapter inventoryExportSysCompForAdapter;
    TambourineConnector tambourineConnector;

    static final Log log = LogFactory.getLog(ConvertMgad.class);
    private static final int DEFAULT_MAX_CONT_PLAY = 1;
    private static final int DEFAULT_MAX_PLAY = 0;
    private static final int DEFAULT_MIN_INTERVAL = 1;

    private static final int NOT_EXIST_STATUS = -9;

    private static final String KT_MONDAY = "1";
    private static final String KT_SATURDAY = "6";

    private static final int DEFAULT_CONTENT_POLICY_PRIORITY = 3;
    private static final int DEFAULT_CONTINUOUS_POLICY_PRIORITY = 5;
    private static final int DEFAULT_CONTENT_GROUP_POLICY_PRIORITY = 10;
    private static final int DEFAULT_CHANNEL_POLICY_PRIORITY = 7;
    private static final int DEFAULT_CHANNEL_POLICY_ALL_SLOT_PRIORITY = 8;
    private static final int ROOT_CHANNEL_POLICY_PRIORITY = 9;
    private static final int ROOT_CHANNEL_POLICY_ALL_SLOT_PRIORITY = 10;

    private static final String CHANNEL_LAST_SLOT = "999";
    private static final String CHANNEL_MIDDLE_SLOT = "555";
    private static final String CHANNEL_ALL_SLOT = "0";

    static final int DEFAULT_PRIORITY = 999;
    private static final String NONE_VERSION = "NONE";

    private static final String MGAD_CHANNEL_ROOT = "root_channel";

    private ResultAdsInfo adsInfoResult = null;
    //private UpdateAdCampaignState resultUpdateAdCampaignState = null;
    private ResultFileUtil campaignResult;
    private ResultFileUtil exposurePolicyResult;
    private ResultFileUtil slotNumberPolicyResult;
    //private ResultFileUtil campaignStateResult;

    private String resultDirectory;
    private String subDirectory;
    private String unknownCategoryResultDirectory;
    private String fileName;
    private Map<String/*time */, Set<GenericAxisItemIDDTO>> timeGenericAxisItemMap = new HashMap<String, Set<GenericAxisItemIDDTO>>();
    private Map<String, List<String>> timeDefineMap = null;
    private Map<Integer, Integer> timeTreeNodeChildCount = null;
    private Set<String/*ad_id*/> setAdId = new HashSet<String>(); // ad_id?  set

    public String[] adProductArr = { "PPST", "PP+", "PPT", "CPST", "CPT" };

    private boolean limitHourlyExposure = false;
    private int dailyMinimumExposureGuaranteeRate;

    public void setSubDirectory(String subDirectory) {
        this.subDirectory = subDirectory;
    }

    public void setFileName(String fileName) {
        this.fileName = fileName;
    }

    public void setResultDirectory(String resultDirectory) {
        this.resultDirectory = resultDirectory;
    }

    public void setUnknownCategoryResultDirectory(String unknownCategoryResultDirectory) {
        this.unknownCategoryResultDirectory = unknownCategoryResultDirectory;
    }

    public void setInventoryExportSysCompForAdapter(
            IInventoryExportSysCompForAdapter inventoryExportSysCompForAdapter) {
        this.inventoryExportSysCompForAdapter = inventoryExportSysCompForAdapter;
    }

    public void setTambourineConnector(TambourineConnector tambourineConnector) {
        this.tambourineConnector = tambourineConnector;
    }

    public boolean isLimitHourlyExposure() {
        return limitHourlyExposure;
    }

    public void setLimitHourlyExposure(boolean limitHourlyExposure) {
        this.limitHourlyExposure = limitHourlyExposure;
    }

    public int getDailyMinimumExposureGuaranteeRate() {
        return dailyMinimumExposureGuaranteeRate;
    }

    public void setDailyMinimumExposureGuaranteeRate(int dailyMinimumExposureGuaranteeRate) {
        this.dailyMinimumExposureGuaranteeRate = dailyMinimumExposureGuaranteeRate;
    }

    @Transactional(rollbackFor = Exception.class, isolation = Isolation.READ_COMMITTED)
    public int convertAdsInfo(AdsInfo adsInfo, AdsInfo unknownCategoryAdsInfo, String unknownCategoryfileName,
            String fileName, ADSMSchedulerLogDTO schedulerLog, ADSMSchedulerLogDTO deleteSchedulerLog,
            InputDataType inputDataType, PlacementOpportunityTypeEnum oppType, PlayInfo playInfo,
            Platform platformType, InventoryType inventoryType, String subDirectory) throws Exception {
        int resultCount = 0;
        long start = System.currentTimeMillis();
        log.info("convertAdsInfo start (" + oppType.name() + ", " + inventoryType.name() + ", "
                + platformType.name() + ")");

        this.fileName = fileName;
        campaignResult = new ResultFileUtil(InputDataType.ADS_INFO);
        exposurePolicyResult = new ResultFileUtil(InputDataType.EXPOSURE_POLICY);
        slotNumberPolicyResult = new ResultFileUtil(InputDataType.SLOT_NUMBER_POLICY);

        try {
            if (adsInfo != null) {
                adsInfoResult = new ResultAdsInfo();
                adsInfoResult.setXml_ID(adsInfo.getXml_ID());
                adsInfoResult.setReg_DT(adsInfo.getReg_DT());

                try {
                    timeDefineMap = tambourineConnector.getTimeDefineMap();
                    if (timeDefineMap != null)
                        timeTreeNodeChildCount = tambourineConnector.getKTTimeTreeNodeChildCountMap(timeDefineMap);
                } catch (Exception e) {
                    String error = "Time Define  load   . error : " + e.getMessage();
                    log.error(error);
                    throw new Exception(error);
                }

                if (inputDataType == InputDataType.ADS_INFO) {
                    Date startTime = new Date(start);
                    generateDisablePolicyDTO(adsInfo, startTime, deleteSchedulerLog.getId(), oppType, playInfo,
                            platformType, inventoryType);
                    /*!*/ generateSlotNumberPolicyDTO(adsInfo, startTime, deleteSchedulerLog.getId(), inputDataType,
                            oppType, playInfo, platformType, inventoryType);
                    /*!*/ generateGroupRatePolicyDTO(adsInfo, startTime, deleteSchedulerLog.getId(), oppType,
                            playInfo, platformType, inventoryType);
                    generateContinuosExposurePolicyDTO(adsInfo, startTime, deleteSchedulerLog.getId(), oppType,
                            playInfo, platformType, inventoryType);
                    generateExposurePolicyDTO(adsInfo, startTime, deleteSchedulerLog.getId(), inputDataType,
                            oppType, playInfo, platformType, inventoryType);
                    generateADProductPriorityPolicyDTO(adsInfo, startTime, deleteSchedulerLog.getId(), oppType,
                            playInfo, platformType, inventoryType);
                    //AdCategory_dat
                    generateDisableSameFieldADPolicyDTO(adsInfo, startTime, deleteSchedulerLog.getId(), oppType,
                            playInfo, platformType, inventoryType);
                }

                if (inputDataType == InputDataType.UPDATE_AD_POLICY) {
                    Date startTime = new Date(start);
                    generateSlotNumberPolicyDTO(adsInfo, startTime, deleteSchedulerLog.getId(), inputDataType,
                            oppType, playInfo, platformType, inventoryType);
                    generateExposurePolicyDTO(adsInfo, startTime, deleteSchedulerLog.getId(), inputDataType,
                            oppType, playInfo, platformType, inventoryType);
                }

                if (inputDataType != InputDataType.UPDATE_AD_POLICY)
                    generateADCampaign(adsInfo, unknownCategoryAdsInfo, unknownCategoryfileName,
                            deleteSchedulerLog.getId(), inputDataType, schedulerLog, oppType, playInfo,
                            platformType, inventoryType);

                schedulerLog.setSchedulerStatus(ADSMSchedulerStatus.SUCCESS);
                deleteSchedulerLog.setSchedulerStatus(ADSMSchedulerStatus.SUCCESS);

                //Mgad   version  DB? ?.
                if (inputDataType == InputDataType.ADS_INFO) {
                    String version = adsInfo.getAdsVersion();
                    if (version == null || version.isEmpty())
                        version = NONE_VERSION;
                    ImportSyncVersion importSyncVersion = new ImportSyncVersion(version, SyncType.ADS_SYNC,
                            schedulerLog.getId());
                    tambourineConnector.mergeSyncVersion(importSyncVersion);
                }

                //update  ?  ??    ?, ? ?  ? ?? ? ?? .
                if (inputDataType != InputDataType.ADS_INFO) {
                    if (campaignResult.getErrorCount() > 0 || exposurePolicyResult.getErrorCount() > 0
                            || slotNumberPolicyResult.getErrorCount() > 0)
                        resultCount = -1;
                } else
                    resultCount = campaignResult.getErrorCount();

            } else {
                adsInfoResult = new ResultAdsInfo();
                adsInfoResult.setXml_ID("Parsing error");
                adsInfoResult.setReg_DT("Parsing error");
                log.error("mgad  ?(" + fileName
                        + ")  . Data ?  .");
                schedulerLog.setFailProcess("Parsing error");
                schedulerLog.setSchedulerStatus(ADSMSchedulerStatus.FAIL);
                deleteSchedulerLog.setFailProcess("Parsing error");
                deleteSchedulerLog.setSchedulerStatus(ADSMSchedulerStatus.FAIL);
                campaignResult.setErrorCount(-1); //Parsing error   
                exposurePolicyResult.setErrorCount(-1); //Parsing error   
                slotNumberPolicyResult.setErrorCount(-1); //Parsing error   
                resultCount = -1;
            }
        } catch (Exception e) {
            //log.error("",e);
            schedulerLog.setMessage(e.getMessage());
            schedulerLog.setSchedulerStatus(ADSMSchedulerStatus.FAIL);
            StackTraceElement[] stackTraces = e.getStackTrace();
            if (stackTraces.length > 0) {
                schedulerLog.setFailProcess(stackTraces[0].getClassName() + " - " + stackTraces[0].getMethodName()
                        + "(" + stackTraces[0].getLineNumber() + ")");
            }
            resultCount = -1;
            throw e;
        } finally {
            ResultFileUtil.writeAdsResultFile(inputDataType, adsInfoResult, exposurePolicyResult,
                    slotNumberPolicyResult, campaignResult, fileName, resultDirectory + subDirectory);
        }
        long end = System.currentTimeMillis();
        log.info("convertAdsInfo end - T(" + (end - start) + ") (" + oppType.name() + ")");

        return resultCount;
    }

    public OperationType caseBycaseUpdateADPolicy(String policyId, String operationType, int deleteSchedulerLogId,
            DeleteDataType deleteDataType, PlacementOpportunityTypeEnum oppType) throws Exception {

        OperationType policyType = OperationType.valueof(operationType);

        if (policyType == OperationType.INSERT) {
            if (policyId == null || policyId.isEmpty() == true)
                return OperationType.INSERT;
        } else {
            if (policyId == null || policyId.isEmpty() == true)
                throw new DataIntegrityException("policyId .", DataIntegrityExceptionType.UNKNOWN);
        }

        List<AbstractInventoryPolicy> policyList = inventoryExportSysCompForAdapter.findPoliciesByPolicyId(policyId,
                oppType);
        String stopDate = DateUtil.date2String(new Date(System.currentTimeMillis()));

        switch (OperationType.valueof(operationType)) {
        case INSERT:
            if (policyList != null && policyList.isEmpty() == false)
                throw new DataIntegrityException(
                        "[policyId = " + policyId
                                + ", Operation = INSERT] ??  policyId  ?  .",
                        DataIntegrityExceptionType.INSERT_INTERGRITY_EXCEPTION);
            break;
        case UPDATE:
            if (policyList == null || policyList.isEmpty() == true)
                throw new DataIntegrityException(
                        "[policyId = " + policyId
                                + ", Operation = UPDATE] ??  ?   .",
                        DataIntegrityExceptionType.UPDATE_INTERGRITY_EXCEPTION);
            else
                inventoryExportSysCompForAdapter.stopPolicyList(stopDate, policyList, deleteSchedulerLogId,
                        deleteDataType);
            break;
        case DELETE:
            if (policyList != null && policyList.isEmpty() == false)
                inventoryExportSysCompForAdapter.stopPolicyList(stopDate, policyList, deleteSchedulerLogId,
                        deleteDataType);
            else
                throw new DataIntegrityException(
                        "[policyId = " + policyId
                                + ", Operation = DELETE] ?? ?   .",
                        DataIntegrityExceptionType.DELETE_INTERGRITY_EXCEPTION);
            break;
        case INSERT_OR_UPDATE:
            if (policyList != null && policyList.isEmpty() == false) {
                inventoryExportSysCompForAdapter.stopPolicyList(stopDate, policyList, deleteSchedulerLogId,
                        deleteDataType);
                return OperationType.UPDATE;
            } else
                return OperationType.INSERT;
        case UNKNOWN:
            throw new Exception("[policyId = " + policyId + ", Operation = " + operationType
                    + "]   ? Operation .");
        default:
            throw new Exception("[policyId = " + policyId + ", Operation = " + operationType
                    + "]   ? Operation .");
        }

        return OperationType.valueof(operationType);
    }

    private List<ExposurePolicyDTO> getExposurePolicyDTOList(List<ExposurePolicy> exposurePolicyList,
            String startDate, Map<String, List<String>> timeDefineMap, InputDataType inputDataType,
            int deleteSchedulerLogId, PlacementOpportunityTypeEnum oppType, Platform platformType,
            InventoryType inventoryType) throws Exception {

        List<ExposurePolicyDTO> policyDTOList = new ArrayList<ExposurePolicyDTO>();
        if (exposurePolicyList == null || exposurePolicyList.isEmpty() == true)
            return policyDTOList;

        for (ExposurePolicy exposurePolicy : exposurePolicyList) {
            try {
                OperationType operationType = OperationType.UNKNOWN;
                //mgad kt : insert  ?, ?   id? 
                operationType = caseBycaseUpdateADPolicy(exposurePolicy.getPolicyId(),
                        exposurePolicy.getOperation(), deleteSchedulerLogId, DeleteDataType.EXPOSURE_POLICY,
                        oppType);

                if (operationType == OperationType.DELETE) {
                    ResultFileUtil.addPolicyResult(exposurePolicy.getPolicyId(), true, null, null,
                            exposurePolicy.getOpportunityType(), inputDataType, adsInfoResult,
                            exposurePolicyResult);
                    continue;
                }

                ExposurePolicyDTO policyDTO = new ExposurePolicyDTO();
                policyDTO.setPriority(exposurePolicy.getPriority());
                policyDTO.setExternalPolicyId(exposurePolicy.getPolicyId());
                policyDTO.setLicensingStart(DateUtil.string2Date(exposurePolicy.getStart_DT()));
                Date date = DateUtil.string2Date(exposurePolicy.getEnd_DT());
                date = DateUtil.getNextDate(date);
                policyDTO.setLicensingEnd(date);
                policyDTO.setPlatformType(platformType);
                policyDTO.setInventoryType(inventoryType);
                policyDTO.setOppType(oppType);

                if (exposurePolicy.getNoAdIfPaid().equalsIgnoreCase("Y"))
                    policyDTO.setNoAdIfPaid(PayTargetType.FREE);
                else if (exposurePolicy.getNoAdIfPaid().equalsIgnoreCase("N"))
                    policyDTO.setNoAdIfPaid(PayTargetType.ALL);
                else
                    throw new Exception("[policyId = " + exposurePolicy.getPolicyId() + ", NoAdIfPaid = "
                            + exposurePolicy.getNoAdIfPaid() + "]   Data .");

                if (exposurePolicy.getNoAdIfReplay().equalsIgnoreCase("Y"))
                    policyDTO.setNoAdIfReplay(true);
                else if (exposurePolicy.getNoAdIfReplay().equalsIgnoreCase("N"))
                    policyDTO.setNoAdIfReplay(false);
                else
                    throw new Exception("[policyId = " + exposurePolicy.getPolicyId() + ", NoAdIfReplay = "
                            + exposurePolicy.getNoAdIfReplay() + "]   Data .");

                policyDTO.setNoAdRuntimeLimit(exposurePolicy.getNoAdRuntimeLimit());

                SubInventoryDTO subInventoryDTO;
                if (exposurePolicy.getTargetList() != null
                        && exposurePolicy.getTargetList().isExistTarget() == true) {
                    Set<GenericAxisItemIDDTO> commonGenericAxisItems = new HashSet<GenericAxisItemIDDTO>();
                    //               commonGenericAxisItems.add(tambourineConnector.getPlacementTypeGenericAxisItemID(exposurePolicy.getOpportunityType()));
                    subInventoryDTO = generateMultiSubInventoryMember(exposurePolicy.getTargetList(), startDate,
                            "99991231", commonGenericAxisItems, null);
                } else {
                    subInventoryDTO = tambourineConnector.generateSubInventory(startDate, "99991231",
                            exposurePolicy.getTargetTM(), exposurePolicy.getTargetDayCD(),
                            exposurePolicy.getRegionInfo(), splitIds(exposurePolicy.getCategoryId(), true), null,
                            null, oppType, null, timeDefineMap, null, null, null, null);
                }

                policyDTO.setSubInventory(subInventoryDTO);
                if (inputDataType == InputDataType.UPDATE_AD_POLICY) {
                    inventoryExportSysCompForAdapter.registerExposurePolicy(policyDTO);
                    ResultFileUtil.addPolicyResult(exposurePolicy.getPolicyId(), true, null, null,
                            exposurePolicy.getOpportunityType(), inputDataType, adsInfoResult,
                            exposurePolicyResult);
                } else
                    policyDTOList.add(policyDTO);
            } catch (DataIntegrityException e) {
                ResultFileUtil.addPolicyResult(exposurePolicy.getPolicyId(), false,
                        e.getDataIntegrityExceptionType().toString(), e.getMessage(),
                        exposurePolicy.getOpportunityType(), inputDataType, adsInfoResult, exposurePolicyResult);
            } catch (Exception e) {
                ResultFileUtil.addPolicyResult(exposurePolicy.getPolicyId(), false, "100", e.getMessage(),
                        exposurePolicy.getOpportunityType(), inputDataType, adsInfoResult, exposurePolicyResult);
            }
        }
        return policyDTOList;
    }

    public boolean generateExposurePolicyDTO(AdsInfo adsInfo, Date startTime, int deleteSchedulerLogId,
            InputDataType inputDataType, PlacementOpportunityTypeEnum oppType, PlayInfo playInfo,
            Platform platformType, InventoryType inventoryType) {
        long start = System.currentTimeMillis(), end;
        log.info("@@@ generateExposurePolicyDTO - start");

        if (!setTimeDefineMap(inputDataType, exposurePolicyResult))
            return false;

        //?  ? 
        String startDate = DateUtil.date2String(startTime);

        if (inputDataType == InputDataType.ADS_INFO)
            inventoryExportSysCompForAdapter.stopAllExposurePolicy(startDate, false, deleteSchedulerLogId, oppType,
                    inventoryType);

        List<ExposurePolicyDTO> policyListDTO = new ArrayList<ExposurePolicyDTO>();

        boolean result = true;
        try {

            if (playInfo != null) {
                List<ExposurePolicy> exposurePolicyList = playInfo.getExposurePolicyList(oppType);
                if (exposurePolicyList != null && exposurePolicyList.isEmpty() == false)
                    playInfo.getExposurePolicyList().addAll(exposurePolicyList);
            }

            //ExposurePolicy ? ? OperationSequence? ? .
            playInfo.sortExposurePolicy();
            policyListDTO.addAll(getExposurePolicyDTOList(playInfo.getExposurePolicyList(), startDate,
                    timeDefineMap, inputDataType, deleteSchedulerLogId, oppType, platformType, inventoryType));

            if (policyListDTO.isEmpty() == false)
                result = inventoryExportSysCompForAdapter.registerExposurePolicies(policyListDTO);
        } catch (Exception e) {
            TheLogger.getWriter().error(adsInfo.getXml_ID() + "    ");
            throw new WrappingException(e.getMessage());
        }

        end = System.currentTimeMillis();
        log.info("@@@ generateExposurePolicyDTO - end(" + (end - start) + " ms)");
        return result;

    }

    //@Transactional(rollbackFor=Exception.class)
    public boolean generateDisablePolicyDTO(AdsInfo adsInfo, Date startTime, int deleteSchedulerLogId,
            PlacementOpportunityTypeEnum oppType, PlayInfo playInfo, Platform platformType,
            InventoryType inventoryType) {
        long start = System.currentTimeMillis(), end;
        log.info("@@@ generateDisablePolicyDTO - start");

        /*
         <ads_disable>               
           <content> //?             
        <content_id>M89E3JKYSGL080005200</content_id>
        <pps_slot_except_YN></pps_slot_except_YN>         
           </content>            
           <category>//             
        <category_id>0532</category_id>
        <pps_slot_except_YN></pps_slot_except_YN>         
           </category>            
           <category_content>//?_?
        <mapping>
           <category_id>10000000000000031567</category_id>         
           <content_id>M44E2Y5LSGL080000100</content_id>
           <pps_slot_except_YN></pps_slot_except_YN>
        </mapping>         
           </category_content>            
           <content>//?_?         
        <category_id>10000000000000061912</category_id>         
        <category_id>10000000000000059628</category_id>
        <pps_slot_except_YN></pps_slot_except_YN>         
           </content>
           <content_group>// ?  
        <content_group_id>CONTENTGR5</content_group_id>
        <pps_slot_except_YN></pps_slot_except_YN>
           </content_group>            
        </ads_disable>   
        */
        //?  ? 
        String startDate = DateUtil.date2String(startTime);

        inventoryExportSysCompForAdapter.stopAllDisablePolicy(startDate, false, deleteSchedulerLogId, oppType,
                inventoryType);
        List<DisablePolicyDTO> policyListDTO = new ArrayList<DisablePolicyDTO>();
        List<DisablePolicyDTO> contenCategoryDisablePolicyDTO = new ArrayList<DisablePolicyDTO>();
        Map<Boolean, Set<String>> disableCategoryContentMap = new HashMap<Boolean, Set<String>>();

        policyListDTO = getDisablePolicy(startDate, "99991231", oppType, policyListDTO,
                contenCategoryDisablePolicyDTO, playInfo, disableCategoryContentMap, platformType, inventoryType);

        inventoryExportSysCompForAdapter.deleteAllCategoryIdForDisableContent(oppType);
        if (disableCategoryContentMap.size() > 0 && contenCategoryDisablePolicyDTO.size() > 0) {
            for (DisablePolicyDTO disablePolicyDTO : contenCategoryDisablePolicyDTO) {
                boolean ppsSlotExceptYN = disablePolicyDTO.getPpsSlotExceptYN();
                saveDisableContentCategoryPolicy(disableCategoryContentMap.get(ppsSlotExceptYN), disablePolicyDTO,
                        oppType, adsInfo.getXml_ID(), ppsSlotExceptYN);
            }

        }

        //  --------------------------------------------------------
        boolean result;
        try {
            result = inventoryExportSysCompForAdapter.registerDisablePolicies(policyListDTO);
        } catch (Exception e) {
            TheLogger.getWriter().error(adsInfo.getXml_ID() + "    ");
            throw new WrappingException(e.getMessage());
        }

        end = System.currentTimeMillis();
        log.info("@@@ generateDisablePolicyDTO - end(" + (end - start) + " ms)");
        return result;

    }

    public boolean saveDisableContentCategoryPolicy(Set<String> disableCategoryContentList,
            DisablePolicyDTO disablePolicyDTO, PlacementOpportunityTypeEnum oppType, String jobId,
            boolean ppsSlotExceptYN) {

        try {
            return inventoryExportSysCompForAdapter.overwriteCategoryIdForDisableContent(disableCategoryContentList,
                    disablePolicyDTO, oppType, ppsSlotExceptYN);
        } catch (Exception e) {
            TheLogger.getWriter().error(jobId + "   Id  ");
            throw new WrappingException(e.getMessage());
        }
    }

    private void setDisableItemByPpsSoltExcept(DisablePolicyDTO policyDTO, String ppsSlotExceptYN) {
        if (ppsSlotExceptYN != null && ppsSlotExceptYN.equalsIgnoreCase("Y"))
            policyDTO.addDisableItem(new DisableItemDTO(DisableAttribute.PPS_SOLT_EXCEPT_YN, ppsSlotExceptYN));
    }

    private List<DisablePolicyDTO> getDisablePolicy(String startDate, String endDate,
            PlacementOpportunityTypeEnum oppType, List<DisablePolicyDTO> policyListDTO,
            List<DisablePolicyDTO> contenCategoryDisablePolicyListDTO, PlayInfo playInfo,
            Map<Boolean, Set<String>> disableCategoryContentMap, Platform platformType,
            InventoryType inventoryType) {
        if (playInfo == null || !inventoryType.equals(InventoryType.VOD))
            return policyListDTO;

        int categoryTreeID = tambourineConnector.getAxisTreeId(TreeType.CATEGORY_AXIS_TREE,
                Constants.tree.CATEGORY_TREE_NAME, ADDSAdapterSetting.defaultSiteName, platformType, false);
        if (categoryTreeID <= 0) {
            throw new WrappingException(
                    "DisablePolicy  ? . err :    load   ?.");
        }

        Ads_disable playDisable = playInfo.getAds_disable();
        //if(playDisable == null)   return policyListDTO;

        List<Ads_disable_detail> content_disable = null;
        List<Ads_disable_detail> category_disable = null;
        List<Ads_disable_detail> category_content_disable = new ArrayList<Ads_disable_detail>();
        List<Ads_disable_detail> content_group_disable = null;
        if (playDisable != null) {
            content_disable = playDisable.getContent_disable();
            category_disable = playDisable.getCategory_disable();
            content_group_disable = playDisable.getContent_group_disable();
            if (playDisable.getCategory_content_disable() != null)
                category_content_disable = playDisable.getCategory_content_disable().getMapping_disable();
        }

        Exclusive_content_disable exclusive_content_disable = playInfo.getExclusive_content_disable();
        // ?/? 
        Exclusive_user_user_group_disable exclusive_user_user_group_disable = playInfo
                .getExclusive_user_user_group_disable();

        if (content_disable != null) {
            for (Ads_disable_detail adsDisable : content_disable) {
                if (adsDisable.getContent_id().size() > 0) {
                    //? 
                    assert (adsDisable.getCateogry_id().size() == 0); //? ?    ?
                    try {
                        DisablePolicyDTO policyDTO = new DisablePolicyDTO();
                        setDisableItemByPpsSoltExcept(policyDTO, adsDisable.getPpsSlotExceptYN());

                        if (isValidDisableTarget(adsDisable.getContent_id(), null, null)) {
                            policyDTO.setSubInventory(tambourineConnector.generateSubInventory(startDate, endDate,
                                    null, null, null, null, adsDisable.getContent_id(), null, oppType, null, null,
                                    null, null, null, null));
                            policyDTO.setOppType(oppType);
                            policyDTO.setInventoryType(inventoryType);
                            policyDTO.setPlatformType(platformType);
                            policyListDTO.add(policyDTO);
                        }
                    } catch (WrappingException e) {
                        log.error("DisablePolicy  ? . err : " + e.getMessage());
                    } catch (Exception e) {
                        log.error("", e);
                    }
                } else {
                    //?_?
                    try {
                        if (isValidDisableTarget(null, adsDisable.getCateogry_id(), null)) {
                            for (String categoryId : adsDisable.getCateogry_id()) {
                                if (disableCategoryContentMap
                                        .get(CiStringUtil.isBoolean(adsDisable.getPpsSlotExceptYN())) == null) {
                                    Set<String> categoryIdSet = new HashSet<String>();
                                    categoryIdSet.add(categoryId);
                                    disableCategoryContentMap.put(
                                            CiStringUtil.isBoolean(adsDisable.getPpsSlotExceptYN()), categoryIdSet);
                                } else
                                    disableCategoryContentMap
                                            .get(CiStringUtil.isBoolean(adsDisable.getPpsSlotExceptYN()))
                                            .add(categoryId);
                            }
                        }
                    } catch (Exception e) {
                        log.error("", e);
                    }
                }
            }
        }

        if (disableCategoryContentMap.size() > 0) {
            for (boolean ppsSlotExceptYN : disableCategoryContentMap.keySet()) {
                DisablePolicyDTO policyDTO = generateCategoryContenDisablePolicyDTO(
                        disableCategoryContentMap.get(ppsSlotExceptYN), oppType, categoryTreeID, startDate, endDate,
                        ppsSlotExceptYN, platformType, inventoryType);
                if (policyDTO != null)
                    contenCategoryDisablePolicyListDTO.add(policyDTO);
            }
        }

        // 
        if (category_disable != null) {
            for (Ads_disable_detail adsDisable : category_disable) {
                assert (adsDisable.getContent_id().size() == 0); //?_?? ?   ?
                try {
                    DisablePolicyDTO policyDTO = new DisablePolicyDTO();
                    setDisableItemByPpsSoltExcept(policyDTO, adsDisable.getPpsSlotExceptYN());
                    if (isValidDisableTarget(null, adsDisable.getCateogry_id(), null)) {
                        policyDTO.setSubInventory(tambourineConnector.generateSubInventory(startDate, endDate, null,
                                null, null, adsDisable.getCateogry_id(), null, null, oppType, null, null, null,
                                null, null, null));
                        policyDTO.setOppType(oppType);
                        policyDTO.setInventoryType(inventoryType);
                        policyDTO.setPlatformType(platformType);
                        policyListDTO.add(policyDTO);
                    }
                } catch (WrappingException e) {
                    log.error("DisablePolicy  ? . err : " + e.getMessage());
                } catch (Exception e) {
                    log.error("", e);
                }
            }
        }

        //?_?
        if (category_content_disable != null) {
            for (Ads_disable_detail adsDisable : category_content_disable) {
                assert (adsDisable.getContent_id().size() == adsDisable.getCateogry_id().size()); //?_?? ?  ?.

                try {
                    DisablePolicyDTO policyDTO = new DisablePolicyDTO();
                    setDisableItemByPpsSoltExcept(policyDTO, adsDisable.getPpsSlotExceptYN());
                    if (isValidDisableTarget(adsDisable.getContent_id(), adsDisable.getCateogry_id(), null)) {
                        policyDTO.setSubInventory(tambourineConnector.generateSubInventory(startDate, endDate, null,
                                null, null, adsDisable.getCateogry_id(), adsDisable.getContent_id(), null, oppType,
                                null, null, null, null, null, null));
                        policyDTO.setOppType(oppType);
                        policyDTO.setInventoryType(inventoryType);
                        policyDTO.setPlatformType(platformType);
                        policyListDTO.add(policyDTO);
                    }
                } catch (WrappingException e) {
                    log.error("DisablePolicy  ? . err : " + e.getMessage());
                } catch (Exception e) {
                    log.error("", e);
                }
            }
        }

        // ?  
        if (content_group_disable != null) {
            for (Ads_disable_detail adsDisable : content_group_disable) {
                assert (adsDisable.getContent_grouop_id().size() != 0);
                try {
                    DisablePolicyDTO policyDTO = new DisablePolicyDTO();
                    setDisableItemByPpsSoltExcept(policyDTO, adsDisable.getPpsSlotExceptYN());
                    if (isValidDisableTarget(null, null, adsDisable.getContent_grouop_id())) {
                        policyDTO.setSubInventory(tambourineConnector.generateSubInventory(startDate, endDate, null,
                                null, null, null, null, null, oppType, null, null, null, null,
                                adsDisable.getContent_grouop_id(), null));

                        policyDTO.setOppType(oppType);
                        policyDTO.setInventoryType(inventoryType);
                        policyDTO.setPlatformType(platformType);
                        policyListDTO.add(policyDTO);
                    }

                } catch (WrappingException e) {
                    log.error("DisablePolicy  ? . err : " + e.getMessage());
                } catch (Exception e) {
                    log.error("", e);
                }
            }
        }

        if (exclusive_content_disable != null && exclusive_content_disable.getContentList() != null) {
            for (Content content : exclusive_content_disable.getContentList()) {
                if (content.getAdAsset_ID() != null) {
                    for (String adAssetId : content.getAdAsset_ID()) {
                        try {
                            List<String> content_id = content.getContent_id();
                            List<String> parent_cateogr_id = new ArrayList<String>();
                            parent_cateogr_id.add(content.getParent_category_id());
                            DisablePolicyDTO policyDTO = new DisablePolicyDTO();
                            DisableItemDTO disableItemDTO = new DisableItemDTO(
                                    DisableAttribute.AD_ASSET_ID_OF_CAMPAIGN, adAssetId);
                            policyDTO.addDisableItem(disableItemDTO);
                            policyDTO.setSubInventory(tambourineConnector.generateSubInventory(startDate, endDate,
                                    null, null, null, parent_cateogr_id, content_id, null, oppType, null, null,
                                    null, null, null, null));
                            policyDTO.setOppType(oppType);
                            policyDTO.setInventoryType(inventoryType);
                            policyDTO.setPlatformType(platformType);
                            policyListDTO.add(policyDTO);
                        } catch (WrappingException e) {
                            log.error("DisablePolicy  ? . err : " + e.getMessage());
                        } catch (Exception e) {
                            log.error("", e);
                        }
                    }
                } else {
                    log.warn("cannot register disable policy : adAsset_ID  is empty");
                }
            }
        }

        // ? ? Disable ?
        if (exclusive_user_user_group_disable != null && exclusive_user_user_group_disable.getUserList() != null) {
            for (User user : exclusive_user_user_group_disable.getUserList()) {
                try {
                    String user_id = user.getUser_id();
                    String adAssetId = user.getAdAsset_ID();

                    if ((user_id == null || user_id.isEmpty()) || (adAssetId == null || adAssetId.isEmpty()))
                        throw new WrappingException(
                                "cannot register disable policy : must have valid user_id and adAssetId");

                    List<String> userIds = new ArrayList<String>();
                    userIds.add(user_id);

                    DisablePolicyDTO policyDTO = new DisablePolicyDTO();
                    DisableItemDTO disableItemDTO = new DisableItemDTO(DisableAttribute.AD_ASSET_ID_OF_CAMPAIGN,
                            adAssetId);
                    policyDTO.addDisableItem(disableItemDTO);
                    policyDTO.setSubInventory(tambourineConnector.generateSubInventory(startDate, endDate, null,
                            null, null, null, null, null, oppType, null, null, userIds, null, null, null));
                    policyDTO.setOppType(oppType);
                    policyDTO.setInventoryType(inventoryType);
                    policyDTO.setPlatformType(platformType);
                    policyListDTO.add(policyDTO);
                } catch (WrappingException e) {
                    log.error("DisablePolicy  ? . err : " + e.getMessage());
                } catch (Exception e) {
                    log.error("", e);
                }
            }
        }

        // ?? ? Disable ?
        if (exclusive_user_user_group_disable != null
                && exclusive_user_user_group_disable.getUserGroupList() != null) {
            for (UserGroup userGroup : exclusive_user_user_group_disable.getUserGroupList()) {
                try {
                    String userGroupId = userGroup.getUser_group_id();
                    String adAssetId = userGroup.getAdAsset_ID();

                    if ((userGroupId == null || userGroupId.isEmpty())
                            || (adAssetId == null || adAssetId.isEmpty()))
                        throw new WrappingException(
                                "cannot register disable policy : must have valid user_group_id and adAssetId");

                    List<String> userGroupIds = splitIds(userGroupId, true);

                    DisablePolicyDTO policyDTO = new DisablePolicyDTO();
                    DisableItemDTO disableItemDTO = new DisableItemDTO(DisableAttribute.AD_ASSET_ID_OF_CAMPAIGN,
                            adAssetId);
                    policyDTO.addDisableItem(disableItemDTO);
                    policyDTO.setSubInventory(tambourineConnector.generateSubInventory(startDate, endDate, null,
                            null, null, null, null, null, oppType, null, null, null, userGroupIds, null, null));
                    policyDTO.setOppType(oppType);
                    policyDTO.setInventoryType(inventoryType);
                    policyDTO.setPlatformType(platformType);
                    policyListDTO.add(policyDTO);
                } catch (WrappingException e) {
                    log.error("DisablePolicy  ? . err : " + e.getMessage());
                } catch (Exception e) {
                    log.error("", e);
                }
            }
        }

        return policyListDTO;
    }

    //?_?
    public DisablePolicyDTO generateCategoryContenDisablePolicyDTO(Set<String> disableCateIdList,
            PlacementOpportunityTypeEnum oppType, int categoryTreeID, String startDate, String endDate,
            boolean ppsSlotExceptYN, Platform platformType, InventoryType inventoryType) {
        try {
            List<PlacementOpportunityTypeEnum> opportunityTypeList = new ArrayList<PlacementOpportunityTypeEnum>();
            if (oppType != null)
                opportunityTypeList.add(oppType);

            Set<String> disableCategoryIdSet = new HashSet<String>();

            for (String parentId : disableCateIdList) {
                List<String> familyCategoryIdList = tambourineConnector.getFamilyExternalIdList(parentId,
                        categoryTreeID);

                if (familyCategoryIdList != null && familyCategoryIdList.isEmpty() == false) {
                    disableCategoryIdSet.addAll(familyCategoryIdList);
                } else {
                    log.warn("DisablePolicy  ? . category : " + parentId
                            + "  ?  .");
                    disableCategoryIdSet.add(parentId);
                }
            }

            if (disableCategoryIdSet != null && disableCategoryIdSet.size() > 0) {

                DisablePolicyDTO policyDTO = new DisablePolicyDTO();
                policyDTO.setDisableList(null);
                if (ppsSlotExceptYN)
                    setDisableItemByPpsSoltExcept(policyDTO, "Y");

                policyDTO.setSubInventory(tambourineConnector.generateSubInventory(startDate, endDate, null, null,
                        null, null, true, new ArrayList<String>(disableCategoryIdSet), //??? ? externalId  .
                        null, opportunityTypeList, null, null, null, null, true, null, null));
                policyDTO.setOppType(oppType);
                policyDTO.setInventoryType(inventoryType);
                policyDTO.setPlatformType(platformType);
                return policyDTO;
            }

        } catch (WrappingException e) {
            log.error("DisablePolicy  ? . err : " + e.getMessage());
        } catch (Exception e) {
            log.error("", e);
        }

        return null;
    }

    private boolean isValidDisableTarget(List<String> contentIdList, List<String> categoryIdList,
            List<String> contentGroupIdList) {
        if ((contentIdList == null || contentIdList.isEmpty())
                && (categoryIdList == null || categoryIdList.isEmpty())
                && (contentGroupIdList == null || contentGroupIdList.isEmpty())) {
            log.warn("cannot register disable policy : must have valid contentId or cateogryId or contentGroupId");
            return false;
        }
        if (contentIdList != null) {
            for (String contentId : contentIdList) {
                if (contentId != null && contentId.isEmpty()) {
                    log.warn("cannot register disable policy : contentId is empty");
                    return false;
                }
            }
        }
        if (categoryIdList != null) {
            for (String categoryId : categoryIdList) {
                if (categoryId != null && categoryId.isEmpty()) {
                    log.warn("cannot register disable policy : categoryId is empty");
                    return false;
                }
            }
        }
        if (contentGroupIdList != null) {
            for (String contentGroupId : contentGroupIdList) {
                if (contentGroupId != null && contentGroupId.isEmpty()) {
                    log.warn("cannot register disable policy : contentGroupId is empty");
                    return false;
                }
            }
        }
        return true;
    }

    //@Transactional(rollbackFor=Exception.class)
    public boolean generateGroupRatePolicyDTO(AdsInfo mgad, Date startTime, int deleteSchedulerLogId,
            PlacementOpportunityTypeEnum oppType, PlayInfo playInfo, Platform platformType,
            InventoryType inventoryType) {
        log.info("@@@ generatePromotionRatePolicyDTO - start");
        long start = System.currentTimeMillis(), end;
        //?    ? 
        String startDate = DateUtil.date2String(startTime);
        inventoryExportSysCompForAdapter.stopAllGroupRatePolicy(startDate, false, deleteSchedulerLogId, oppType,
                inventoryType);

        List<GroupRatePolicyDTO> policyDTOList = new ArrayList<GroupRatePolicyDTO>();

        //   
        List<GroupRatePolicyDTO> policyDTOListByOppType = generatePromotionRatePolicyDTO(playInfo, startDate,
                oppType, platformType, inventoryType);
        policyDTOList.addAll(policyDTOListByOppType);
        //??  
        policyDTOListByOppType = generateMonopolyRatePolicyDTO(playInfo, startDate, oppType, platformType,
                inventoryType);
        policyDTOList.addAll(policyDTOListByOppType);
        //   
        policyDTOListByOppType = generatePromoBonusRatePolicyDTO(playInfo, startDate, oppType, platformType,
                inventoryType);
        policyDTOList.addAll(policyDTOListByOppType);

        boolean result;
        try {
            result = inventoryExportSysCompForAdapter.registerGroupRatePolicies(policyDTOList);
        } catch (Exception e) {
            TheLogger.getWriter().error(mgad.getXml_ID() + " Promotion   ");
            throw new WrappingException(e.getMessage());
        }

        end = System.currentTimeMillis();
        log.info("@@@ generatePromotionRatePolicyDTO - end(" + (end - start) + " ms)");
        return result;

    }

    private List<GroupRatePolicyDTO> generatePromotionRatePolicyDTO(PlayInfo playInfo, String startDate,
            PlacementOpportunityTypeEnum oppType, Platform platformType, InventoryType inventoryType) {
        List<GroupRatePolicyDTO> policyDTOList = new ArrayList<GroupRatePolicyDTO>();
        if (playInfo == null)
            return policyDTOList;

        List<Category> playInfoCategoryList = null;
        List<Content> playInfoContentList = null;
        List<ContentGroup> playInfoContentGroupList = null;
        List<Channel> playInfoChannelList = null;

        Category_promoRate catePromoRate = playInfo.getCategory_promoRate();
        if (catePromoRate != null)
            playInfoCategoryList = catePromoRate.getCategoryList();

        Content_promoRate contPromoRate = playInfo.getContent_promoRate();
        if (contPromoRate != null)
            playInfoContentList = contPromoRate.getContentList();

        Content_group_promoRate contGroupPromoRate = playInfo.getContent_group_promoRate();
        if (contGroupPromoRate != null)
            playInfoContentGroupList = contGroupPromoRate.getContentGroupList();

        Channel_promoRate channelPromoRate = playInfo.getChannel_promoRate();
        if (channelPromoRate != null)
            playInfoChannelList = channelPromoRate.getChannelList();

        if (playInfoCategoryList != null)
            policyDTOList = getCategoryGroupRatePolicyList(startDate, "99991231", oppType, policyDTOList,
                    playInfoCategoryList, GroupRateType.PROMO_RATE, platformType, inventoryType);
        if (playInfoContentList != null)
            policyDTOList = getContentGroupRatePolicyList(startDate, "99991231", oppType, policyDTOList,
                    playInfoContentList, GroupRateType.PROMO_RATE, platformType, inventoryType);
        if (playInfoContentGroupList != null)
            policyDTOList = getContentGroupIdGroupRatePolicyList(startDate, "99991231", oppType, policyDTOList,
                    playInfoContentGroupList, GroupRateType.PROMO_RATE, platformType, inventoryType);
        if (playInfoChannelList != null)
            policyDTOList = getChannelIdRatePolicyList(startDate, "99991231", oppType, policyDTOList,
                    playInfoChannelList, GroupRateType.PROMO_RATE, inventoryType, platformType);

        return policyDTOList;
    }

    private List<GroupRatePolicyDTO> generateMonopolyRatePolicyDTO(PlayInfo playInfo, String startDate,
            PlacementOpportunityTypeEnum oppType, Platform platformType, InventoryType inventoryType) {
        List<GroupRatePolicyDTO> policyDTOList = new ArrayList<GroupRatePolicyDTO>();
        if (playInfo == null)
            return policyDTOList;

        List<Category> playInfoCategoryList = null;
        List<Content> playInfoContentList = null;
        List<ContentGroup> playInfoContentGroupList = null;
        List<Channel> playInfoChannelList = null;

        Category_monopolyRate cateMonopolyRate = playInfo.getCategory_monopolyRate();
        if (cateMonopolyRate != null)
            playInfoCategoryList = cateMonopolyRate.getCategoryList();

        Content_monopolyRate contMonopolyRate = playInfo.getContent_monopolyRate();
        if (contMonopolyRate != null)
            playInfoContentList = contMonopolyRate.getContentList();

        Content_group_monopolyRate contGroupMonopolyRate = playInfo.getContent_group_monopolyRate();
        if (contGroupMonopolyRate != null)
            playInfoContentGroupList = contGroupMonopolyRate.getContentGroupList();

        Channel_monopolyRate channelMonopolyRate = playInfo.getChannel_monopolyRate();
        if (channelMonopolyRate != null)
            playInfoChannelList = channelMonopolyRate.getChannelList();

        if (playInfoCategoryList != null)
            policyDTOList = getCategoryGroupRatePolicyList(startDate, "99991231", oppType, policyDTOList,
                    playInfoCategoryList, GroupRateType.COMERCIAL_MONOPOLY_RATE, platformType, inventoryType);
        if (playInfoContentList != null)
            policyDTOList = getContentGroupRatePolicyList(startDate, "99991231", oppType, policyDTOList,
                    playInfoContentList, GroupRateType.COMERCIAL_MONOPOLY_RATE, platformType, inventoryType);
        if (playInfoContentGroupList != null)
            policyDTOList = getContentGroupIdGroupRatePolicyList(startDate, "99991231", oppType, policyDTOList,
                    playInfoContentGroupList, GroupRateType.COMERCIAL_MONOPOLY_RATE, platformType, inventoryType);

        if (playInfoChannelList != null)
            policyDTOList = getChannelIdRatePolicyList(startDate, "99991231", oppType, policyDTOList,
                    playInfoChannelList, GroupRateType.COMERCIAL_MONOPOLY_RATE, inventoryType, platformType);

        return policyDTOList;
    }

    private List<GroupRatePolicyDTO> generatePromoBonusRatePolicyDTO(PlayInfo playInfo, String startDate,
            PlacementOpportunityTypeEnum oppType, Platform platformType, InventoryType inventoryType) {
        List<GroupRatePolicyDTO> policyDTOList = new ArrayList<GroupRatePolicyDTO>();
        if (playInfo == null)
            return policyDTOList;

        List<Category> playInfoCategoryList = null;
        List<Content> playInfoContentList = null;
        List<ContentGroup> playInfoContentGroupList = null;
        List<Channel> playInfoChannelList = null;

        Category_promoRate catePromoRate = playInfo.getCategory_promoRate();
        if (catePromoRate != null)
            playInfoCategoryList = catePromoRate.getCategoryList();

        Content_promoRate contPromoRate = playInfo.getContent_promoRate();
        if (contPromoRate != null)
            playInfoContentList = contPromoRate.getContentList();

        Content_group_promoRate contGroupPromoRate = playInfo.getContent_group_promoRate();
        if (contGroupPromoRate != null)
            playInfoContentGroupList = contGroupPromoRate.getContentGroupList();

        Channel_promoRate channelPromoRate = playInfo.getChannel_promoRate();
        if (channelPromoRate != null)
            playInfoChannelList = channelPromoRate.getChannelList();

        if (playInfoCategoryList != null)
            policyDTOList = getCategoryGroupRatePolicyList(startDate, "99991231", oppType, policyDTOList,
                    playInfoCategoryList, GroupRateType.PROMO_RATE_FOR_BONUS, platformType, inventoryType);
        if (playInfoContentList != null)
            policyDTOList = getContentGroupRatePolicyList(startDate, "99991231", oppType, policyDTOList,
                    playInfoContentList, GroupRateType.PROMO_RATE_FOR_BONUS, platformType, inventoryType);
        if (playInfoContentGroupList != null)
            policyDTOList = getContentGroupIdGroupRatePolicyList(startDate, "99991231", oppType, policyDTOList,
                    playInfoContentGroupList, GroupRateType.PROMO_RATE_FOR_BONUS, platformType, inventoryType);

        if (playInfoChannelList != null)
            policyDTOList = getChannelIdRatePolicyList(startDate, "99991231", oppType, policyDTOList,
                    playInfoChannelList, GroupRateType.PROMO_RATE_FOR_BONUS, inventoryType, platformType);

        return policyDTOList;
    }

    private int convertGroupRate(Slot_detail slotDetail, GroupRateType groupRateType) {
        try {
            switch (groupRateType) {
            case PROMO_RATE:
                if (slotDetail.getPromo_Rate() == null || slotDetail.getPromo_Rate().equals("")) //      promoRate ?   ?  ?.
                    return NOT_EXIST_STATUS;
                return Integer.parseInt(slotDetail.getPromo_Rate());
            case COMERCIAL_MONOPOLY_RATE:
                return Integer.parseInt(slotDetail.getMaximum_monopoly_Rate());
            case PROMO_RATE_FOR_BONUS:
                if (slotDetail.getBonus() == null || slotDetail.getBonus().getPromo_Rate() == null
                        || slotDetail.getBonus().getPromo_Rate().equals("")) //      promoRate ?   ?  ?.
                    return NOT_EXIST_STATUS;
                int promoBonusRate = Integer.parseInt(slotDetail.getBonus().getPromo_Rate());
                if (promoBonusRate < 0)
                    promoBonusRate = 0;
                if (promoBonusRate > 100)
                    promoBonusRate = 100;
                return promoBonusRate;
            default: // ?? !
                return 0;
            }
        } catch (NumberFormatException e) {
            log.error("groupRateType-" + groupRateType + ", " + slotDetail, e);
            return -1;
        }
    }

    private List<GroupRatePolicyDTO> getChannelIdRatePolicyList(String startDate, String endDate,
            PlacementOpportunityTypeEnum oppType, List<GroupRatePolicyDTO> policyDTOList,
            List<Channel> playInfoChannelList, GroupRateType groupRateType, InventoryType inventoryType,
            Platform platformType) {
        for (Channel channel : playInfoChannelList) {

            for (Slot_detail channel_slot : channel.getChannel_slotList()) {
                try {
                    GroupRatePolicyDTO policyDTO = new GroupRatePolicyDTO();
                    policyDTO.setGroupRateType(groupRateType);
                    int groupRate = convertGroupRate(channel_slot, groupRateType);
                    if (groupRate < 0) {
                        if (groupRate != NOT_EXIST_STATUS)
                            log.error("wrong groupRatePolicy(channel_id-" + channel.getChannel_id() + ", Slot_ORD-"
                                    + channel_slot.getSlot_ORD() + ")");
                        continue;
                    }

                    policyDTO.setTargetSlotOrder(convertSlotOrder(channel_slot.getSlot_ORD()));
                    policyDTO.setGroupRate(groupRate);

                    if (channel.getChannel_id().equals("root_channel")) {
                        if (channel_slot.getSlot_ORD().equalsIgnoreCase("ALL")) {
                            policyDTO.setPriority(ROOT_CHANNEL_POLICY_ALL_SLOT_PRIORITY);
                        } else {
                            policyDTO.setPriority(ROOT_CHANNEL_POLICY_PRIORITY);
                        }
                    } else {
                        if (channel_slot.getSlot_ORD().equalsIgnoreCase("ALL")) {
                            policyDTO.setPriority(DEFAULT_CHANNEL_POLICY_ALL_SLOT_PRIORITY);
                        } else {
                            policyDTO.setPriority(DEFAULT_CHANNEL_POLICY_PRIORITY);
                        }
                    }

                    policyDTO.setSubInventory(tambourineConnector.generateSubInventory(startDate, endDate, null,
                            null, null, null, null, channel_slot.getSlotOrdList(), oppType, null, null, null, null,
                            null, channel.getChannel_id()));
                    policyDTO.setOppType(oppType);
                    policyDTO.setInventoryType(inventoryType);
                    policyDTO.setPlatformType(platformType);

                    policyDTOList.add(policyDTO);
                } catch (WrappingException e) {
                    log.error("ChannelIdGroupRatePolicy ? .  err : " + e.getMessage());
                } catch (Exception e) {
                    log.error("", e);
                }
            }
        }
        return policyDTOList;
    }

    public String convertSlotOrder(String slot_ORD) {
        String slot = slot_ORD;
        String[] slotArr = slot.split(",");

        for (int i = 0; i < slotArr.length; i++) {
            if (slotArr[i].equalsIgnoreCase("MIDDLE")) {
                slot = CHANNEL_MIDDLE_SLOT;
            } else if (slotArr[i].equalsIgnoreCase("LAST")) {
                slot = CHANNEL_LAST_SLOT;
            } else if (slotArr[i].equalsIgnoreCase("ALL")) {
                slot = CHANNEL_ALL_SLOT;
            } else {
                slot = slotArr[i];
            }
            slotArr[i] = slot;
        }
        return Arrays.toString(slotArr).substring(1, Arrays.toString(slotArr).length() - 1).replaceAll("\\p{Space}",
                "");
    }

    private List<GroupRatePolicyDTO> getContentGroupIdGroupRatePolicyList(String startDate, String endDate,
            PlacementOpportunityTypeEnum oppType, List<GroupRatePolicyDTO> policyListDTO,
            List<ContentGroup> contentGroupList, GroupRateType groupRateType, Platform platformType,
            InventoryType inventoryType) {
        for (ContentGroup contentGroup : contentGroupList) {

            PriceTypeEnum paidType = getPriceTypeOfKT(contentGroup.getContent_price_type());

            int priceTypeValue = getPriorityValue(paidType);

            for (Slot_detail content_group_slot : contentGroup.getContent_group_slotList()) {
                try {
                    GroupRatePolicyDTO policyDTO = new GroupRatePolicyDTO();
                    policyDTO.setGroupRateType(groupRateType);
                    int groupRate = convertGroupRate(content_group_slot, groupRateType);
                    if (groupRate < 0) {
                        if (groupRate != NOT_EXIST_STATUS)
                            log.error("wrong groupRatePolicy(Content_group_id-" + contentGroup.getContent_group_id()
                                    + ", Slot_ORD-" + content_group_slot.getSlot_ORD() + ")");
                        continue;
                    }

                    if (priceTypeValue == 1)
                        policyDTO.setPriority(DEFAULT_CONTENT_GROUP_POLICY_PRIORITY);
                    else
                        policyDTO.setPriority(11);

                    policyDTO.setTargetSlotOrder(content_group_slot.getSlot_ORD());
                    policyDTO.setGroupRate(groupRate);

                    //relay  
                    RelayTargetType relayType = RelayTargetType.ALL;
                    if (contentGroup.getRelay_YN() != null) {
                        if (contentGroup.getRelay_YN().equalsIgnoreCase("1"))
                            relayType = RelayTargetType.RELAY_Y;
                        else if (contentGroup.getRelay_YN().equalsIgnoreCase("2"))
                            relayType = RelayTargetType.RELAY_N;
                    }

                    policyDTO.setRelay_YN(relayType);

                    policyDTO.setSubInventory(tambourineConnector.generateSubInventory(startDate, endDate, null,
                            null, null, null, null, content_group_slot.getSlotOrdList(), oppType, paidType, null,
                            null, null, contentGroup.getContent_group_id(), null));
                    policyDTO.setInventoryType(inventoryType);
                    policyDTO.setPlatformType(platformType);
                    policyDTO.setOppType(oppType);
                    policyListDTO.add(policyDTO);
                } catch (WrappingException e) {
                    log.error("ContentGroupIdGroupRatePolicy ? .  err : " + e.getMessage());
                } catch (Exception e) {
                    log.error("", e);
                }
            }
        }
        return policyListDTO;
    }

    private List<GroupRatePolicyDTO> getContentGroupRatePolicyList(String startDate, String endDate,
            PlacementOpportunityTypeEnum oppType, List<GroupRatePolicyDTO> policyListDTO, List<Content> contentList,
            GroupRateType groupRateType, Platform platformType, InventoryType inventoryType) {
        for (Content content : contentList) {

            PriceTypeEnum paidType = getPriceTypeOfKT(content.getContent_price_type());

            int priceTypeValue = getPriorityValue(paidType);

            for (Slot_detail content_slot : content.getContent_slotList()) {
                try {
                    GroupRatePolicyDTO policyDTO = new GroupRatePolicyDTO();
                    policyDTO.setGroupRateType(groupRateType);
                    int groupRate = convertGroupRate(content_slot, groupRateType);
                    if (groupRate < 0) {
                        if (groupRate != NOT_EXIST_STATUS)
                            log.error("wrong groupRatePolicy(Content_id-" + content.getContent_id() + ", Slot_ORD-"
                                    + content_slot.getSlot_ORD() + ")");
                        continue;
                    }

                    if (priceTypeValue == 1)
                        policyDTO.setPriority(DEFAULT_CONTENT_POLICY_PRIORITY);
                    else
                        policyDTO.setPriority(4);

                    policyDTO.setTargetSlotOrder(content_slot.getSlot_ORD());
                    policyDTO.setGroupRate(groupRate);

                    //relay  
                    RelayTargetType relayType = RelayTargetType.ALL;
                    if (content.getRelay_YN() != null) {
                        if (content.getRelay_YN().equalsIgnoreCase("1"))
                            relayType = RelayTargetType.RELAY_Y;
                        else if (content.getRelay_YN().equalsIgnoreCase("2"))
                            relayType = RelayTargetType.RELAY_N;
                    }

                    policyDTO.setRelay_YN(relayType);

                    policyDTO.setSubInventory(tambourineConnector.generateSubInventory(startDate, endDate, null,
                            null, null, null, content.getContent_id(), content_slot.getSlotOrdList(), oppType,
                            paidType, null, null, null, null, null));
                    policyDTO.setInventoryType(inventoryType);
                    policyDTO.setPlatformType(platformType);
                    policyDTO.setOppType(oppType);
                    policyListDTO.add(policyDTO);
                } catch (WrappingException e) {
                    log.error("ContentGroupRatePolicy ? .  err : " + e.getMessage());
                } catch (Exception e) {
                    log.error("", e);
                }
            }
        }
        return policyListDTO;
    }

    private List<GroupRatePolicyDTO> getCategoryGroupRatePolicyList(String startDate, String endDate,
            PlacementOpportunityTypeEnum oppType, List<GroupRatePolicyDTO> policyListDTO,
            List<Category> categoryList, GroupRateType groupRateType, Platform platformType,
            InventoryType inventoryType) {
        for (Category category : categoryList) {

            //   
            PriceTypeEnum paidType = getPriceTypeOfKT(category.getContent_price_type());

            int priceTypeValue = getPriorityValue(paidType);

            for (Slot_detail category_slot : category.getCategory_slotList()) {
                try {
                    GroupRatePolicyDTO policyDTO = new GroupRatePolicyDTO();

                    policyDTO.setGroupRateType(groupRateType);
                    int groupRate = convertGroupRate(category_slot, groupRateType);
                    if (groupRate < 0) {
                        if (groupRate != NOT_EXIST_STATUS)
                            log.error("wrong groupRatePolicy(Category_id-" + category.getCategory_id()
                                    + ", Slot_ORD-" + category_slot.getSlot_ORD() + ")");
                        continue;
                    }
                    policyDTO.setGroupRate(groupRate);
                    policyDTO.setTargetSlotOrder(category_slot.getSlot_ORD());

                    int level = inventoryExportSysCompForAdapter.getNodeLevelByTreeTypeAndExternalId(
                            TreeType.CATEGORY_AXIS_TREE, category.getCategory_id());
                    if (level >= 0)
                        policyDTO.setPriority(1000 - level * 10 - priceTypeValue);//??  ?.
                    else
                        policyDTO.setPriority(999);
                    List<String> categoryIdList = new ArrayList<String>();
                    categoryIdList.add(category.getCategory_id());

                    //relay  
                    RelayTargetType relayType = RelayTargetType.ALL;
                    if (category.getRelay_YN() != null) {
                        if (category.getRelay_YN().equalsIgnoreCase("1"))
                            relayType = RelayTargetType.RELAY_Y;
                        else if (category.getRelay_YN().equalsIgnoreCase("2"))
                            relayType = RelayTargetType.RELAY_N;
                    }

                    policyDTO.setRelay_YN(relayType);

                    policyDTO.setSubInventory(tambourineConnector.generateSubInventory(startDate, endDate, null,
                            null, null, categoryIdList, null, category_slot.getSlotOrdList(), oppType, paidType,
                            null, null, null, null, null));
                    policyDTO.setInventoryType(inventoryType);
                    policyDTO.setPlatformType(platformType);
                    policyDTO.setOppType(oppType);
                    policyListDTO.add(policyDTO);
                } catch (WrappingException e) {
                    log.error("CategoryGroupRatePolicy  ? . err : " + e.getMessage());
                } catch (Exception e) {
                    log.error("", e);
                }
            }
        }
        return policyListDTO;
    }

    private int getPriorityValue(PriceTypeEnum paidType) {
        int val = 0;

        if (paidType == null) {
            val = 0;
        } else {
            val = 1;
        }
        return val;
    }

    PriceTypeEnum getPriceTypeOfKT(String priceStr) {

        PriceTypeEnum paidType = null;

        //price   ? ?.
        if (priceStr == null)
            return paidType;

        if (priceStr.equals("1"))
            paidType = PriceTypeEnum.PAID;
        else if (priceStr.equals("2"))
            paidType = PriceTypeEnum.FREE;

        return paidType;
    }

    //@Transactional(rollbackFor=Exception.class)
    public boolean generateSlotNumberPolicyDTO(AdsInfo mgad, Date startTime, int deleteSchedulerLogId,
            InputDataType inputDataType, PlacementOpportunityTypeEnum oppType, PlayInfo playInfo,
            Platform platformType, InventoryType inventoryType) {
        long start = System.currentTimeMillis(), end;
        log.info("@@@ generateSlotNumberPolicyDTO - start");

        if (!setTimeDefineMap(inputDataType, slotNumberPolicyResult))
            return false;

        //?  ? 
        String startDate = DateUtil.date2String(startTime);

        if (inputDataType == InputDataType.ADS_INFO)
            inventoryExportSysCompForAdapter.stopAllSlotNumberPolicy(startDate, false, deleteSchedulerLogId,
                    oppType, inventoryType);

        List<SlotNumberPolicyDTO> policyDTOList = new ArrayList<SlotNumberPolicyDTO>();

        boolean result = true;
        try {
            Category_promoRate catePromoRate = new Category_promoRate();

            if (playInfo != null && playInfo.getCategory_promoRate() != null)
                catePromoRate.getCategoryList().addAll(playInfo.getCategory_promoRate().getCategoryList(oppType));

            //Category_promoRate ? ? OperationSequence? ? .
            catePromoRate.sortCategory();

            if (catePromoRate.getCategoryList() != null && catePromoRate.getCategoryList().isEmpty() == false)
                policyDTOList = generateCategorySlotNumberPolicy(startDate, policyDTOList,
                        catePromoRate.getCategoryList(), deleteSchedulerLogId, inputDataType, oppType, platformType,
                        inventoryType);

            if (playInfo != null) {
                Content_promoRate contPromoRate = playInfo.getContent_promoRate();
                if (contPromoRate != null && contPromoRate.getContentList() != null)
                    policyDTOList = generateContentSlotNumberPolicy(startDate, policyDTOList,
                            contPromoRate.getContentList(), oppType, platformType, inventoryType);

                Content_group_promoRate contGroupPromoRate = playInfo.getContent_group_promoRate();
                if (contGroupPromoRate != null && contGroupPromoRate.getContentGroupList() != null)
                    policyDTOList = generateContentGroupSlotNumberPolicy(startDate, policyDTOList,
                            contGroupPromoRate.getContentGroupList(), oppType, platformType, inventoryType);

                Channel_promoRate channelPromoRate = playInfo.getChannel_promoRate();
                if (channelPromoRate != null && channelPromoRate.getChannelList() != null)
                    policyDTOList = generateChannelPromoRateSlotNumberPolicy(startDate, policyDTOList,
                            channelPromoRate.getChannelList(), oppType, platformType, inventoryType);
            }

            if (policyDTOList.isEmpty() == false)
                result = inventoryExportSysCompForAdapter.registerSlotNumberPolicies(policyDTOList);
        } catch (Exception e) {
            TheLogger.getWriter().error(mgad.getXml_ID() + " SlotNumber   ");
            throw new WrappingException(e.getMessage());
        }

        end = System.currentTimeMillis();
        log.info("@@@ generateSlotNumberPolicyDTO - end(" + (end - start) + " ms)");
        return result;
    }

    private List<SlotNumberPolicyDTO> generateChannelPromoRateSlotNumberPolicy(String startDate,
            List<SlotNumberPolicyDTO> policyDTOList, List<Channel> channelList,
            PlacementOpportunityTypeEnum oppType, Platform platformType, InventoryType inventoryType) {
        for (Channel channel : channelList) {
            try {

                SlotNumberPolicyDTO policyDTO = new SlotNumberPolicyDTO();

                if (channel.getSlot_CNT() == null && channel.getMax_duration() == null) {
                    throw new Exception("slot_CNT, max_duration? ? .");
                }

                if (channel.getSlot_CNT() != null)
                    policyDTO.setSlotNumber(Integer.parseInt(channel.getSlot_CNT()));

                if (channel.getMax_duration() != null)
                    policyDTO.setMaxDuration(CiStringUtil.getMaxDuration(channel.getMax_duration()));

                if (channel.getChannel_id().equals("root_channel"))
                    policyDTO.setPriority(ROOT_CHANNEL_POLICY_PRIORITY);
                else
                    policyDTO.setPriority(DEFAULT_CHANNEL_POLICY_PRIORITY);

                policyDTO.setSubInventory(
                        tambourineConnector.generateSubInventory(startDate, "99991231", null, null, null, null,
                                null, null, oppType, null, null, null, null, null, channel.getChannel_id()));
                policyDTO.setOppType(oppType);
                policyDTO.setInventoryType(inventoryType);
                policyDTO.setPlatformType(platformType);
                policyDTOList.add(policyDTO);

            } catch (WrappingException e) {
                log.error("ContentSlotNumberPolicy  ? . err : " + e.getMessage());
            } catch (Exception e) {
                log.error("", e);
            }

        }

        return policyDTOList;
    }

    private List<SlotNumberPolicyDTO> generateContentGroupSlotNumberPolicy(String startDate,
            List<SlotNumberPolicyDTO> policyListDTO, List<ContentGroup> contentGroupList,
            PlacementOpportunityTypeEnum oppType, Platform platformType, InventoryType inventoryType) {

        for (ContentGroup contentGroup : contentGroupList) {
            try {

                PriceTypeEnum paidType = getPriceTypeOfKT(contentGroup.getContent_price_type());
                int priceTypeValue = getPriorityValue(paidType);

                SlotNumberPolicyDTO policyDTO = new SlotNumberPolicyDTO();

                if (priceTypeValue == 1)
                    policyDTO.setPriority(DEFAULT_CONTENT_GROUP_POLICY_PRIORITY);
                else
                    policyDTO.setPriority(11);

                policyDTO.setSlotNumber(Integer.parseInt(contentGroup.getSlot_CNT()));
                policyDTO.setMaxDuration(CiStringUtil.getMaxDuration(contentGroup.getMax_duration()));

                //relay  
                RelayTargetType relayType = RelayTargetType.ALL;
                if (contentGroup.getRelay_YN() != null) {
                    if (contentGroup.getRelay_YN().equalsIgnoreCase("1"))
                        relayType = RelayTargetType.RELAY_Y;
                    else if (contentGroup.getRelay_YN().equalsIgnoreCase("2"))
                        relayType = RelayTargetType.RELAY_N;
                }
                policyDTO.setRelay_YN(relayType);

                //pps_YN
                SortedSet<Slot_detail> SlotInfoSet = new TreeSet<Slot_detail>();
                for (Slot_detail slotInfo : contentGroup.getContent_group_slotList()) {
                    if (slotInfo.getPps_YN() != null) {
                        SlotInfoSet.add(slotInfo);
                    }
                }
                policyDTO.setPpsSlotNumber(checkPpsSlotNumber(SlotInfoSet));

                policyDTO.setSubInventory(tambourineConnector.generateSubInventory(startDate, "99991231", null,
                        null, null, null, contentGroup.getContent_group_id(), null, oppType, paidType, null, null,
                        null, null, null));
                policyDTO.setOppType(oppType);
                policyDTO.setInventoryType(inventoryType);
                policyDTO.setPlatformType(platformType);
                policyListDTO.add(policyDTO);

            } catch (WrappingException e) {
                log.error("ContentSlotNumberPolicy  ? . err : " + e.getMessage());
            } catch (Exception e) {
                log.error("", e);
            }

        }

        return policyListDTO;
    }

    private List<SlotNumberPolicyDTO> generateContentSlotNumberPolicy(String startDate,
            List<SlotNumberPolicyDTO> policyListDTO, List<Content> contentList,
            PlacementOpportunityTypeEnum oppType, Platform platformType, InventoryType inventoryType) {
        for (Content content : contentList) {

            try {

                PriceTypeEnum paidType = getPriceTypeOfKT(content.getContent_price_type());
                int priceTypeValue = getPriorityValue(paidType);

                SlotNumberPolicyDTO policyDTO = new SlotNumberPolicyDTO();

                if (priceTypeValue == 1)
                    policyDTO.setPriority(DEFAULT_CONTENT_POLICY_PRIORITY);
                else
                    policyDTO.setPriority(4);

                policyDTO.setSlotNumber(Integer.parseInt(content.getSlot_CNT()));
                policyDTO.setMaxDuration(CiStringUtil.getMaxDuration(content.getMax_duration()));

                //relay  
                RelayTargetType relayType = RelayTargetType.ALL;
                if (content.getRelay_YN() != null) {
                    if (content.getRelay_YN().equalsIgnoreCase("1"))
                        relayType = RelayTargetType.RELAY_Y;
                    else if (content.getRelay_YN().equalsIgnoreCase("2"))
                        relayType = RelayTargetType.RELAY_N;
                }
                policyDTO.setRelay_YN(relayType);

                //pps_YN
                SortedSet<Slot_detail> SlotInfoSet = new TreeSet<Slot_detail>();
                for (Slot_detail slotInfo : content.getContent_slotList()) {
                    if (slotInfo.getPps_YN() != null) {
                        SlotInfoSet.add(slotInfo);
                    }
                }
                policyDTO.setPpsSlotNumber(checkPpsSlotNumber(SlotInfoSet));

                policyDTO.setSubInventory(
                        tambourineConnector.generateSubInventory(startDate, "99991231", null, null, null, null,
                                content.getContent_id(), null, oppType, paidType, null, null, null, null, null));
                policyDTO.setOppType(oppType);
                policyDTO.setInventoryType(inventoryType);
                policyDTO.setPlatformType(platformType);
                policyListDTO.add(policyDTO);
            } catch (WrappingException e) {
                log.error("ContentSlotNumberPolicy  ? . err : " + e.getMessage());
            } catch (Exception e) {
                log.error("", e);
            }
        }
        return policyListDTO;
    }

    private List<SlotNumberPolicyDTO> generateCategorySlotNumberPolicy(String startDate,
            List<SlotNumberPolicyDTO> policyListDTO, List<Category> categoryList, int deleteSchedulerLogId,
            InputDataType inputDataType, PlacementOpportunityTypeEnum oppType, Platform platformType,
            InventoryType inventoryType) throws Exception {
        for (Category category : categoryList) {
            try {
                List<SlotNumberPolicyDTO> slotNumberPolicyListDTO = new ArrayList<SlotNumberPolicyDTO>();
                OperationType operationType = OperationType.UNKNOWN;
                //mgad kt : insert  ?, ?   id? 
                operationType = caseBycaseUpdateADPolicy(category.getPolicy_id(), category.getOperation(),
                        deleteSchedulerLogId, DeleteDataType.SLOT_NUMBER_POLICY, oppType);

                if (operationType == OperationType.DELETE) {
                    ResultFileUtil.addPolicyResult(category.getPolicy_id(), true, null, null,
                            category.getOpportunityType(), inputDataType, adsInfoResult, slotNumberPolicyResult);
                    continue;
                }

                slotNumberPolicyListDTO.add(makeSlotNumberPolicyWithContentPrice(startDate, category,
                        category.getOpportunityType(), platformType, inventoryType));

                if (slotNumberPolicyListDTO.isEmpty() == false) {
                    if (inputDataType == InputDataType.UPDATE_AD_POLICY) {
                        inventoryExportSysCompForAdapter.registerSlotNumberPolicies(slotNumberPolicyListDTO);
                        ResultFileUtil.addPolicyResult(category.getPolicy_id(), true, null, null,
                                category.getOpportunityType(), inputDataType, adsInfoResult,
                                slotNumberPolicyResult);
                    } else
                        policyListDTO.addAll(slotNumberPolicyListDTO);

                }
            } catch (DataIntegrityException e) {
                ResultFileUtil.addPolicyResult(category.getPolicy_id(), false,
                        e.getDataIntegrityExceptionType().toString(), e.getMessage(), category.getOpportunityType(),
                        inputDataType, adsInfoResult, slotNumberPolicyResult);
            } catch (Exception e) {
                ResultFileUtil.addPolicyResult(category.getPolicy_id(), false, "100", e.getMessage(),
                        category.getOpportunityType(), inputDataType, adsInfoResult, slotNumberPolicyResult);
            }
        }
        return policyListDTO;
    }

    int getSlotCount(String slotCount) {
        if (slotCount == null || slotCount.isEmpty())
            return -1;

        return Integer.valueOf(slotCount);
    }

    //?? ? ?   ?
    private SlotNumberPolicyDTO makeSlotNumberPolicyWithContentPrice(String startDate, Category category,
            PlacementOpportunityTypeEnum oppType, Platform platformType, InventoryType inventoryType)
            throws Exception {
        SlotNumberPolicyDTO policyDTO = new SlotNumberPolicyDTO();
        PriceTypeEnum paidType = getPriceTypeOfKT(category.getContent_price_type());
        int priceTypeValue = getPriorityValue(paidType);
        if (category.getPriority() == null || category.getPriority().isEmpty()) {
            int level = inventoryExportSysCompForAdapter
                    .getNodeLevelByTreeTypeAndExternalId(TreeType.CATEGORY_AXIS_TREE, category.getCategory_id());
            if (level >= 0)
                policyDTO.setPriority(1000 - level * 10 - priceTypeValue);//??  ?.
            else
                policyDTO.setPriority(DEFAULT_PRIORITY);
        } else
            policyDTO.setPriority(Integer.parseInt(category.getPriority()));

        //? slot count . (-1: ? ? ?)
        //for HC
        int freeSlotCnt = getSlotCount(category.getFree_content_slot_CNT());
        int paidSlotCnt = getSlotCount(category.getPaid_content_slot_CNT());

        //for KT
        if (category.getContent_price_type() != null) {
            if (category.getContent_price_type().equals("1"))
                paidSlotCnt = getSlotCount(category.getSlot_CNT());
            else if (category.getContent_price_type().equals("2"))
                freeSlotCnt = getSlotCount(category.getSlot_CNT());
        }

        //pps_YN
        SortedSet<Slot_detail> SlotInfoSet = new TreeSet<Slot_detail>();
        for (Slot_detail slotInfo : category.getCategory_slotList()) {
            if (slotInfo.getPps_YN() != null) {
                SlotInfoSet.add(slotInfo);
            }
        }

        policyDTO.setPpsSlotNumber(checkPpsSlotNumber(SlotInfoSet));

        policyDTO.setSlotNumber(Integer.parseInt(category.getSlot_CNT()));

        policyDTO.setMaxDuration(CiStringUtil.getMaxDuration(category.getMax_duration()));
        policyDTO.setExternalPolicyId(category.getPolicy_id());
        policyDTO.setLicensingStart(DateUtil.string2Date(category.getStart_DT()));
        policyDTO.setLicensingEnd(DateUtil.getNextDate(DateUtil.string2Date(category.getEnd_DT())));

        //relay  
        RelayTargetType relayType = RelayTargetType.ALL;
        if (category.getRelay_YN() != null) {
            if (category.getRelay_YN().equalsIgnoreCase("1"))
                relayType = RelayTargetType.RELAY_Y;
            else if (category.getRelay_YN().equalsIgnoreCase("2"))
                relayType = RelayTargetType.RELAY_N;
        }
        policyDTO.setRelay_YN(relayType);

        SubInventoryDTO subInventoryDTO;
        if (category.getTargetList() != null && category.getTargetList().isExistTarget() == true) {
            Set<GenericAxisItemIDDTO> commonGenericAxisItems = new HashSet<GenericAxisItemIDDTO>();
            //         commonGenericAxisItems.add(tambourineConnector.getPlacementTypeGenericAxisItemID(oppType));
            subInventoryDTO = generateMultiSubInventoryMember(category.getTargetList(), startDate, "99991231",
                    commonGenericAxisItems, paidType);
        } else {
            subInventoryDTO = tambourineConnector.generateSubInventory(startDate, "99991231",
                    category.getTarget_TM(), category.getTargetDay_CD(), category.getRegion_Info(),
                    splitIds(category.getCategory_id(), true), null, null, oppType, paidType, timeDefineMap, null,
                    null, null, null);
        }
        policyDTO.setOppType(oppType);
        policyDTO.setInventoryType(inventoryType);
        policyDTO.setPlatformType(platformType);
        policyDTO.setSubInventory(subInventoryDTO);
        return policyDTO;
    }

    private String checkPpsSlotNumber(SortedSet<Slot_detail> SlotInfoSet) {
        List<Slot_detail> slotDetailList = new ArrayList<Slot_detail>(SlotInfoSet);

        for (int i = 0; i < slotDetailList.size(); i++) {
            int idx = slotDetailList.size() - 1 - i;
            if (!slotDetailList.get(idx).getPps_YN().equalsIgnoreCase("Y")) {
                for (int j = 0; j < idx; j++) {
                    slotDetailList.get(j).setPps_YN("N");
                }
                break;
            }
        }

        SortedSet<Integer> ppsSlotNumber = new TreeSet<Integer>();
        for (Slot_detail slot : slotDetailList) {
            if (slot.getPps_YN().equalsIgnoreCase("Y")) {
                ppsSlotNumber.add(Integer.parseInt(slot.getSlot_ORD()));
            }
        }

        return toPpsString(ppsSlotNumber);
    }

    private List<String> splitIds(String notSplitedText, boolean isSlash) {
        if (notSplitedText == null || notSplitedText.isEmpty())
            return null;

        String[] splited = null;

        if (isSlash == true) {
            splited = notSplitedText.split("/");
        } else {
            splited = notSplitedText.split("\\|");
        }

        List<String> splitedList = Arrays.asList(splited);
        return splitedList;
    }

    public Set<GenericAxisItemIDDTO> getTimeAxisItemDTOs(String time_id, String week_id) throws Exception {
        String timeAxisItemKey = time_id + "_" + week_id;
        Set<GenericAxisItemIDDTO> timeAxisItemIDList = null;
        timeAxisItemIDList = timeGenericAxisItemMap.get(timeAxisItemKey);

        if (timeAxisItemIDList == null) {
            timeAxisItemIDList = new HashSet<GenericAxisItemIDDTO>(
                    tambourineConnector.getKTTimeGenericAxisItemIDList(time_id, week_id, timeDefineMap));

            timeGenericAxisItemMap.put(timeAxisItemKey, timeAxisItemIDList);
        }

        return timeAxisItemIDList;
    }

    public Set<GenericAxisItemID> getTimeAxisItems(String time_id, String week_id) throws Exception {
        Set<GenericAxisItemIDDTO> timeAxisItemIDDTOList = getTimeAxisItemDTOs(time_id, week_id);

        Set<GenericAxisItemID> timeAxisItemIDList = new HashSet<GenericAxisItemID>();

        for (GenericAxisItemIDDTO genericAxisItemIDDTO : timeAxisItemIDDTOList) {
            timeAxisItemIDList
                    .add((GenericAxisItemID) Converter.map(genericAxisItemIDDTO, GenericAxisItemID.class));
        }
        return timeAxisItemIDList;
    }

    public OperationType caseBycaseUpdateADCampaign(String externalCampId, String operationType,
            int deleteSchedulerLogId, int syncId) throws Exception {

        if (externalCampId == null || externalCampId.isEmpty() == true)
            throw new Exception("[ad_ID = " + externalCampId + "] ad_ID ?   .");

        ADCampaignStatus[] adCampaignStatusList = { ADCampaignStatus.READY, ADCampaignStatus.RUNNING,
                ADCampaignStatus.SUSPENDING };
        List<ADCampaign> adCampaignList = inventoryExportSysCompForAdapter
                .getADCampaignListByExternalCampIdAndStatus(externalCampId, adCampaignStatusList);

        switch (OperationType.valueof(operationType)) {
        case INSERT:
            if (adCampaignList != null && adCampaignList.isEmpty() == false)
                throw new DataIntegrityException(
                        "[ad_ID = " + externalCampId
                                + ", Operation = INSERT] ??  ad_ID ??  .",
                        DataIntegrityExceptionType.INSERT_INTERGRITY_EXCEPTION);
            break;
        case UPDATE:
            if (adCampaignList == null || adCampaignList.isEmpty() == true)
                throw new DataIntegrityException(
                        "[ad_ID = " + externalCampId
                                + ", Operation = UPDATE] ??  ??   .",
                        DataIntegrityExceptionType.UPDATE_INTERGRITY_EXCEPTION);
            else
                inventoryExportSysCompForAdapter.stopCampaign(adCampaignList, deleteSchedulerLogId, syncId);
            break;
        case DELETE:
            if (adCampaignList != null && adCampaignList.isEmpty() == false)
                inventoryExportSysCompForAdapter.stopCampaign(adCampaignList, deleteSchedulerLogId, syncId);
            else
                throw new DataIntegrityException(
                        "[ad_ID = " + externalCampId
                                + ", Operation = DELETE] ?? ??   .",
                        DataIntegrityExceptionType.DELETE_INTERGRITY_EXCEPTION);
            break;
        case INSERT_OR_UPDATE:
            if (adCampaignList != null && adCampaignList.isEmpty() == false) {
                inventoryExportSysCompForAdapter.stopCampaign(adCampaignList, deleteSchedulerLogId, syncId);
                return OperationType.UPDATE;
            } else
                return OperationType.INSERT;
        case UNKNOWN:
            throw new Exception("[ad_ID = " + externalCampId + ", Operation = " + operationType
                    + "]   ? Operation .");
        default:
            throw new Exception("[ad_ID = " + externalCampId + ", Operation = " + operationType
                    + "]   ? Operation .");
        }

        return OperationType.valueof(operationType);
    }

    public boolean generateADCampaign(AdsInfo mgad, AdsInfo unknownCategoryAdsInfo, String unknownCategoryfileName,
            int deleteSchedulerLogId, InputDataType inputDataType, ADSMSchedulerLogDTO schedulerLog,
            PlacementOpportunityTypeEnum oppType, PlayInfo playInfo, Platform platformType,
            InventoryType inventoryType) throws Exception {
        log.info("@@@ generateADCampaign - start");

        String param = "oppType:" + oppType.toString() + "/inventoryType:" + inventoryType.toString()
                + "/plaformType:" + platformType.toString() + "/fileName:" + fileName;
        FeSyncNoticeboardDTO feSyncNoticeboardDTO = tambourineConnector.generateFeSyncNoticeboardData(
                SyncDataType.CAMPAIGN, null, param, null, FeSyncNoticeboardStatus.UNKNOWN, platformType,
                inventoryType, oppType);
        //      feSyncNoticeboardDTO.setOpportunityType(oppType);
        //      feSyncNoticeboardDTO.setInventoryType(inventoryType);
        //      feSyncNoticeboardDTO.setPlatform(platformType);
        feSyncNoticeboardDTO = tambourineConnector.insertSyncNoticeboard(feSyncNoticeboardDTO);

        if (inputDataType == InputDataType.ADS_INFO) {
            inventoryExportSysCompForAdapter.stopAllCampaign(deleteSchedulerLogId, feSyncNoticeboardDTO.getId(),
                    oppType, inventoryType);
            log.info("stop All Campaign");
        }

        timeGenericAxisItemMap.clear();
        setAdId.clear(); // ad_id set 

        //join load
        inventoryExportSysCompForAdapter.initializeBeforeInsertCampaign(oppType, Constants.tree.REGION_TREE_NAME);
        log.info("@@@ initializeBeforeInsertCampaign ?  .");

        long start = System.currentTimeMillis(), end;
        Ad_list allAdList = new Ad_list();

        addAllAdList(playInfo, allAdList, oppType);

        // ?  ?? operationSequence? ? .
        allAdList.sortAds();

        //Data  ID 
        ADSMSchedulerLogDTO categoryDataSchedulerLog = tambourineConnector
                .getLatestADSMSchedulerLog(ADSMJobNameType.CATEGORY_DATA.name());

        insertAdCampaigns(allAdList, deleteSchedulerLogId, inputDataType, feSyncNoticeboardDTO.getId(),
                categoryDataSchedulerLog, adsInfoResult, oppType, platformType, inventoryType);

        //unknown Category   ?
        if (unknownCategoryAdsInfo != null) {
            log.info("Unknown Category  ?  .");
            allAdList.clear();
            addAllAdList(customizeUnknownCategoryAds(playInfo), allAdList, oppType);
            ResultAdsInfo unknownCategoryResult = new ResultAdsInfo();
            insertAdCampaigns(allAdList, deleteSchedulerLogId, inputDataType, feSyncNoticeboardDTO.getId(),
                    categoryDataSchedulerLog, unknownCategoryResult, oppType, platformType, inventoryType);
            ResultFileUtil.simpleWriteAdsResultFile(unknownCategoryResult, unknownCategoryfileName,
                    unknownCategoryResultDirectory);
        }

        setAdId.clear(); //ad_id set? ??  
        timeGenericAxisItemMap.clear();
        inventoryExportSysCompForAdapter.terminateAfterInsertCampaign();

        if (ADDSAdapterSetting.getIntegrityKT() == true && campaignResult.getTotalCount() == 0) {
            log.error(" ?? ?  ??   .");
            TheLogger.getWriter()
                    .error(mgad.getXml_ID() + " ?  (??   ?)");
            throw new Exception("campaign Count is 0.");
        }

        if (campaignResult.getTotalCount() > 0 && campaignResult.getSuccessCount() == 0) {
            log.error("Successful campaign Count is 0(errorCount:" + campaignResult.getErrorCount() + ").");
            throw new Exception(
                    "Successful campaign Count is 0(errorCount:" + campaignResult.getErrorCount() + ").");
        }

        if (inputDataType == InputDataType.UPDATE_AD_CAMPAIGN) {
            inventoryExportSysCompForAdapter.insertDeleteData(feSyncNoticeboardDTO.getId(), deleteSchedulerLogId,
                    DeleteDataType.AD_CAMPAIGN.name(), "UPDATE_AD_CAMPAIGN : Delete Campaign");
        }
        feSyncNoticeboardDTO.setStatus(FeSyncNoticeboardStatus.NEWDATA);
        Timestamp timestamp = new Timestamp(new Date().getTime());
        feSyncNoticeboardDTO.setSyncStartTime(timestamp);
        tambourineConnector.updateSyncNoticeboard(feSyncNoticeboardDTO);

        String message = "(Success:" + campaignResult.getSuccessCount() + ", Error:"
                + campaignResult.getErrorCount() + ", Total:" + campaignResult.getTotalCount() + ")";
        schedulerLog.setMessage(message);
        log.info("@@@@@@@@@@@@@@@@@@@@@@ campaignCount" + message);
        TheLogger.getWriter().info(mgad.getXml_ID() + " ?  " + message);

        end = System.currentTimeMillis();
        log.info("@@@ generateADCampaign - end(" + (end - start) + " ms)");
        return true;
    }

    private Map<String, List<Ads>> distributeADS(Ad_list allAdList) {

        Map<String, List<Ads>> campaignMap = new HashMap<String, List<Ads>>();

        for (Ads ads : allAdList.getAdsList()) {
            List<Ads> adsList = campaignMap.get(ads.getExternalCampaignId());

            if (adsList == null) {
                adsList = new ArrayList<Ads>();
                adsList.add(ads);
                campaignMap.put(ads.getExternalCampaignId(), adsList);
            } else
                adsList.add(ads);
        }

        return campaignMap;
    }

    @SuppressWarnings("null")
    private void insertAdCampaigns(Ad_list allAdList, int deleteSchedulerLogId, InputDataType inputDataType,
            int feSyncNoticeboardId, ADSMSchedulerLogDTO categoryDataSchedulerLog, ResultAdsInfo result,
            PlacementOpportunityTypeEnum oppType, Platform platformType, InventoryType inventoryType) {

        int insertCampaignCount = 0;
        int totalCampaignCount = allAdList.getAdsList().size();

        uniqueIdCheckInCampaign(allAdList, result, oppType, inventoryType);

        Map<String, List<Ads>> campaignMap = distributeADS(allAdList);
        Map<String, AccumulationGoiDay> adIdMap = new HashMap<String, AccumulationGoiDay>();
        Map<Date, Integer> dateExposureMap = new HashMap<Date, Integer>();
        Map<Date, Integer> dateMinimumExposureMap = new HashMap<Date, Integer>();
        List<ADCampaignDailyExposure> adCampaignDailyExposureList = null;
        List<NonTargetUserGroup> nontargetUserList = new ArrayList<NonTargetUserGroup>();
        List<CampaignTargetInfo> targetInfoList = new ArrayList<CampaignTargetInfo>();
        Map<String, List<String>> targetInfoSet = new HashMap<String, List<String>>();
        List<String> targetInfoStrList = new ArrayList<String>();
        Integer adCampaignID = null;
        Date updateDate = new Date(System.currentTimeMillis());

        for (Map.Entry<String, List<Ads>> entry : campaignMap.entrySet()) {
            String externalId = entry.getKey();
            List<Ads> value = entry.getValue();
            try {
                //1. externalId ? ??   .
                for (Ads ads : value) {
                    Integer reservePercent = CiStringUtil.parseInteger(ads.getReservePercent());
                    if (reservePercent == null)
                        reservePercent = 0;

                    if (ads.getStart_DT() != null && ads.getEnd_DT() != null && ads.getStart_DT().isEmpty() == false
                            && ads.getEnd_DT().isEmpty() == false) {
                        Date startDate = DateUtil.string2Date(ads.getStart_DT()); //yyyy-mm-dd
                        Date endDate = DateUtil.string2Date(ads.getEnd_DT()); //yyyy-mm-dd
                        AccumulationGoiDay accumulationGoiDay = new AccumulationGoiDay(ads.getGoi_CNT(),
                                ads.getGoi_DAY(),
                                CiDateUtil.countDayInLicense(ads.getStart_DT(), ads.getEnd_DT(), null),
                                reservePercent, dailyMinimumExposureGuaranteeRate);

                        if (ads.getAd_ID() != null && ads.getAd_ID().isEmpty() == false) {
                            if (ads.getGoi_DAY() != null && ads.getGoi_DAY().isEmpty() == false) {
                                Date nextDate = startDate;
                                int dayCnt = 0;
                                while (nextDate.compareTo(endDate) <= 0) {
                                    Integer dailyExposure = dateExposureMap.get(nextDate);
                                    if (dailyExposure == null)
                                        dailyExposure = 0;
                                    dateExposureMap.put(nextDate,
                                            dailyExposure += accumulationGoiDay.getAccumulationCounts()[dayCnt]);

                                    Integer dailyMinimumExposure = dateMinimumExposureMap.get(nextDate);
                                    if (dailyMinimumExposure == null)
                                        dailyMinimumExposure = 0;
                                    dateMinimumExposureMap.put(nextDate, dailyMinimumExposure += accumulationGoiDay
                                            .getDailyMinimumExposureCount()[dayCnt]);

                                    nextDate = DateUtil.getNextDate(nextDate);
                                    dayCnt++;
                                }
                            }
                        }
                        adIdMap.put(ads.getAd_ID(), accumulationGoiDay);
                    }
                }

                //2. ??  Data ?
                adCampaignDailyExposureList = new ArrayList<ADCampaignDailyExposure>();
                for (Map.Entry<Date, Integer> dateEntry : dateExposureMap.entrySet()) {
                    Date date = dateEntry.getKey();
                    Integer exposure = dateEntry.getValue();

                    ADCampaignDailyExposure adCampaignDailyExposure = new ADCampaignDailyExposure(
                            new ADCampaignDailyExposureKey(externalId, date, oppType, inventoryType), exposure,
                            updateDate);
                    adCampaignDailyExposureList.add(adCampaignDailyExposure);
                }
            } catch (Exception e) {
                log.error("ADSchedulerId (" + externalId
                        + ") ?  .  ?  : " + value.size() + ", err : "
                        + e.getMessage());
                insertCampaignCount += value.size();
                for (Ads ads : value) {
                    ResultFileUtil.addAdsInfoResult(ads, false, "100", e.getMessage(), inventoryType, oppType,
                            result);
                    campaignResult.increaseErrorCount();
                }
                //??   ?  ??   ?.
                continue;
            }

            //3. ??  
            try {
                inventoryExportSysCompForAdapter.insertADCampaignDailyExposureList(adCampaignDailyExposureList);
            } catch (Exception e) {
                log.error("ADSchedulerId (" + externalId
                        + ") ?  .  ?  : " + value.size() + ", err : "
                        + e.getMessage());
                insertCampaignCount += value.size();
                for (Ads ads : value) {
                    ResultFileUtil.addAdsInfoResult(ads, false, "30", e.getMessage(), inventoryType, oppType,
                            result);
                    campaignResult.increaseErrorCount();
                }
                //??   ?  ??   ?.
                continue;
            }

            //4.  ? .
            for (Ads ads : value) {
                AccumulationGoiDay accumulationGoiDay = adIdMap.get(ads.getAd_ID());
                if (ads.getAd_ID() != null && ads.getAd_ID().isEmpty() == false) {
                    if (ads.getGoi_DAY() != null && ads.getGoi_DAY().isEmpty() == false) {
                        if (ads.getStart_DT() != null && ads.getEnd_DT() != null
                                && ads.getStart_DT().isEmpty() == false && ads.getEnd_DT().isEmpty() == false) {
                            Date startDate = DateUtil.string2Date(ads.getStart_DT()); //yyyy-mm-dd
                            Date endDate = DateUtil.string2Date(ads.getEnd_DT()); //yyyy-mm-dd
                            accumulationGoiDay.replaceAccumulationGoi(dateExposureMap, dateMinimumExposureMap,
                                    startDate, endDate);
                        }
                    }
                }
                adCampaignID = generateADCampaign(ads, deleteSchedulerLogId, inputDataType, feSyncNoticeboardId,
                        categoryDataSchedulerLog, result, oppType, accumulationGoiDay, inventoryType, platformType);
                insertCampaignCount++;

                //? mgad   non_target_user_group ?? ,  (, ?) 
                if (inventoryType == InventoryType.CUETONE && adCampaignID != null) {
                    nontargetUserList.addAll(updateNonTargetUserGroup(adCampaignID, ads));
                    targetInfoList.addAll(updateTargetInfo(ads, targetInfoSet, targetInfoStrList));
                }

                if ((insertCampaignCount % 1000) == 0)
                    log.info(totalCampaignCount + " ?  " + insertCampaignCount
                            + " ??  .");

            }

            //5. Map .
            dateExposureMap.clear();
            dateMinimumExposureMap.clear();
            adIdMap.clear();
        }

        //?mgad : non_target_user_group,    ? 
        if (inventoryType == InventoryType.CUETONE) {
            inventoryExportSysCompForAdapter.deleteChannelTargetInfo();
            inventoryExportSysCompForAdapter.saveChannelTargetInfo(targetInfoList);

            inventoryExportSysCompForAdapter.deleteNonTargetUserGroup();
            inventoryExportSysCompForAdapter.insertNonTargetUserGroup(nontargetUserList);
        }

    }

    public List<CampaignTargetInfo> updateTargetInfo(Ads ads, Map<String, List<String>> targetInfoSet,
            List<String> targetInfoStrList) {

        List<CampaignTargetInfo> tempTargetInfoList = new ArrayList<CampaignTargetInfo>();
        String channelId = ads.getChannel_ID();

        if (targetInfoSet.get(channelId) == null) {
            targetInfoStrList = new ArrayList<String>();
            targetInfoSet.put(channelId, targetInfoStrList);
        }

        if (ads.getRegion_Info() != null && !ads.getRegion_Info().isEmpty()) {
            List<String> regionList = splitIds(ads.getRegion_Info(), true);
            for (String regionStr : regionList) {
                CampaignTargetInfo targetInfo = new CampaignTargetInfo();
                targetInfo.setChannelId(channelId);
                targetInfo.setTargetType(TargetType.REGION.name());
                targetInfo.setTargetValue(regionStr);

                if (!targetInfoSet.get(channelId).contains(regionStr)) {
                    targetInfoSet.get(channelId).add(regionStr);
                    tempTargetInfoList.add(targetInfo);
                }
            }
        }

        if (ads.getTarget_user_group() != null && !ads.getTarget_user_group().isEmpty()) {
            List<String> userGroupList = splitIds(ads.getTarget_user_group(), true);
            for (String userGroupStr : userGroupList) {
                CampaignTargetInfo targetInfo = new CampaignTargetInfo();
                targetInfo.setChannelId(channelId);
                targetInfo.setTargetType(TargetType.USER_GROUP.name());
                targetInfo.setTargetValue(userGroupStr);

                if (!targetInfoSet.get(channelId).contains(userGroupStr)) {
                    targetInfoSet.get(channelId).add(userGroupStr);
                    tempTargetInfoList.add(targetInfo);
                }

            }
        }

        return tempTargetInfoList;
    }

    private List<NonTargetUserGroup> updateNonTargetUserGroup(Integer adCampaignID, Ads ads) {
        List<NonTargetUserGroup> nonTargetUserGroupList = new ArrayList<NonTargetUserGroup>();
        if (ads.getNon_target_user_group() != null && ads.getNon_target_user_group().length() != 0) {
            List<String> nonTargetUserGroupStrList = splitIds(ads.getNon_target_user_group(), true);
            nonTargetUserGroupList.addAll(collectNonTargetUserGroup(adCampaignID, nonTargetUserGroupStrList));
        }

        return nonTargetUserGroupList;
    }

    public List<NonTargetUserGroup> collectNonTargetUserGroup(Integer adCampaignID, List<String> nonTargetList) {
        List<NonTargetUserGroup> nonTargetUserGroupList = new ArrayList<NonTargetUserGroup>();
        for (String nonTargetUser : nonTargetList) {
            NonTargetUserGroup nonUser = new NonTargetUserGroup(adCampaignID, nonTargetUser);
            nonTargetUserGroupList.add(nonUser);
        }

        return nonTargetUserGroupList;
    }

    private void integrityAds(Ads ads, boolean useTargetListInfo, boolean useGoiDayInfo,
            AdvertiesmentType advertiesmentType, InventoryType inventoryType) throws Exception {

        //start, end date  ?
        Date startDate = null, endDate = null;
        if (ads.getStart_DT() != null && !ads.getStart_DT().isEmpty())
            startDate = DateUtil.string2Date(ads.getStart_DT()); //yyyy-mm-dd
        else
            throw new Exception("<start_DT></start_DT> tag is empty. start_DT tag is required.");

        if (ads.getEnd_DT() != null && !ads.getEnd_DT().isEmpty())
            endDate = DateUtil.string2Date(ads.getEnd_DT()); //yyyy-mm-dd
        else
            throw new Exception("<end_DT></end_DT> tag is empty. end_DT tag is required.");

        isBeforeDate(startDate, endDate);

        if (advertiesmentType == AdvertiesmentType.COMMERCIAL_AD
                || advertiesmentType == AdvertiesmentType.PROMO_AD) {
            if (ads.getExecution_ratio() == null || ads.getExecution_ratio().isEmpty()) {
                /*??? , ?  ?? ?? */
                if (getADContentType(ads.getAdPromo_YN()) == SubscriptionType.COMMERCIAL_VIDEO
                        && (ads.getGoi_CNT() == null || ads.getGoi_CNT().isEmpty()))
                    throw new DataIntegrityException("[COMMERCIAL] goi_CNT ? .",
                            DataIntegrityExceptionType.ADS_INTERGRITY_EXCEPTION);

                if (getADContentType(ads.getAdPromo_YN()) == SubscriptionType.OAP)
                    if (ads.getAdPriority() == null || ads.getAdPriority().isEmpty())
                        throw new DataIntegrityException("[Promo] adPriority ? .",
                                DataIntegrityExceptionType.ADS_INTERGRITY_EXCEPTION);
            }
        }
        if (advertiesmentType == AdvertiesmentType.COMMERCIAL_AD) { //?
            if (ads.getMonopoly_Rate() == null || ads.getMonopoly_Rate().isEmpty()) //???  
                if (ads.getGoi_DAY() == null || ads.getGoi_DAY().isEmpty())
                    throw new DataIntegrityException("[COMMERCIAL] getGoi_DAY ? .",
                            DataIntegrityExceptionType.ADS_INTERGRITY_EXCEPTION);

        }
        String targetUser = ads.getTarget_user();
        String targetUserGroup = ads.getTarget_user_group();

        if (ads.getAd_ID() == null || ads.getAd_ID().isEmpty())
            throw new DataIntegrityException("ad_ID   .",
                    DataIntegrityExceptionType.ADS_INTERGRITY_EXCEPTION);

        if (ads.getAdAsset_ID() == null || ads.getAdAsset_ID().isEmpty())
            throw new DataIntegrityException("adAsset_ID   .",
                    DataIntegrityExceptionType.ADS_INTERGRITY_EXCEPTION);

        if (inventoryType.equals(InventoryType.CUETONE)
                && (ads.getChannel_ID() == null || ads.getChannel_ID().isEmpty()))
            throw new DataIntegrityException("channel_ID   .",
                    DataIntegrityExceptionType.ADS_INTERGRITY_EXCEPTION);

        if (!AdvertiesmentType.DUMMY_AD.equals(advertiesmentType)
                && !AdvertiesmentType.DEFAULT_AD.equals(advertiesmentType))
            if (ads.getTarget_TM() == null || ads.getTarget_TM().isEmpty())
                throw new DataIntegrityException("target_TM   .",
                        DataIntegrityExceptionType.ADS_INTERGRITY_EXCEPTION);

        if (!AdvertiesmentType.DUMMY_AD.equals(advertiesmentType)
                && !AdvertiesmentType.DEFAULT_AD.equals(advertiesmentType))
            if (ads.getTargetDay_CD() == null || ads.getTargetDay_CD().isEmpty())
                throw new DataIntegrityException("targetDay_CD   .",
                        DataIntegrityExceptionType.ADS_INTERGRITY_EXCEPTION);

        //target_user target_user_group?    error .
        if (!inventoryType.equals(InventoryType.CUETONE))
            if (targetUser != null && targetUserGroup != null && targetUser.isEmpty() == false
                    && targetUserGroup.isEmpty() == false)
                throw new DataIntegrityException(
                        "target_user  target_user_group  ??    .",
                        DataIntegrityExceptionType.ADS_INTERGRITY_EXCEPTION);

        if (useTargetListInfo && useGoiDayInfo)
            throw new DataIntegrityException(
                    "Goi_DAY  TargetList  ??    .",
                    DataIntegrityExceptionType.ADS_INTERGRITY_EXCEPTION);

        if (useTargetListInfo) {
            if (ads.getExecution_ratio() == null || ads.getExecution_ratio().isEmpty())
                throw new DataIntegrityException(
                        "TargetList      execution_ratio ?  .",
                        DataIntegrityExceptionType.ADS_INTERGRITY_EXCEPTION);
        }
    }

    private GenericAxisItemIDSet getCommonGenericAxisItems(Ads ads, AdvertiesmentType advertiesmentType)
            throws Exception {

        List<String> categoryIdList = new ArrayList<String>();
        List<String> contentIdList = new ArrayList<String>();
        List<String> contentGroupIdList = new ArrayList<String>();
        List<String> userIdList = new ArrayList<String>();
        List<String> userGroupIdList = new ArrayList<String>();
        String channelId = null;
        //          
        String regionInfos = null;

        if (ads.getMenu_ID() != null && ads.getMenu_ID().length() > 0)
            categoryIdList.addAll(splitIds(ads.getMenu_ID(), false));
        if (ads.getContent_ID() != null && ads.getContent_ID().length() > 0)
            contentIdList.addAll(splitIds(ads.getContent_ID(), true));
        if (ads.getContent_group_ID() != null && ads.getContent_group_ID().length() > 0)
            contentGroupIdList.addAll(splitIds(ads.getContent_group_ID(), true));
        if (ads.getChannel_ID() != null)
            channelId = ads.getChannel_ID();

        if (channelId == null && (categoryIdList == null || categoryIdList.size() == 0)
                && (contentIdList == null || contentIdList.size() == 0)
                && (contentGroupIdList == null || contentGroupIdList.size() == 0)) {
            String errorMsg = "Need to add Category Or Content Or Content Group Or ChannelId data to Campaign ["
                    + ads.getAd_ID() + "]";
            throw new WrappingException(errorMsg);
        }

        //?   ,  ?,   
        if (advertiesmentType != AdvertiesmentType.DEFAULT_AD || advertiesmentType != AdvertiesmentType.DUMMY_AD) {
            regionInfos = ads.getRegion_Info();
            if (ads.getTarget_user() != null && ads.getTarget_user().length() > 0)
                userIdList.add(ads.getTarget_user()); //user 1?  .
            if (ads.getTarget_user_group() != null && ads.getTarget_user_group().length() > 0)
                userGroupIdList.addAll(splitIds(ads.getTarget_user_group(), true));
        }

        return tambourineConnector.generateGenericAxisItemIDDTO(null, null, categoryIdList, false, contentIdList,
                contentGroupIdList, userIdList, userGroupIdList, regionInfos, channelId);
    }

    private Integer generateADCampaign(Ads ads, int deleteSchedulerLogId, InputDataType inputDataType, int syncId,
            ADSMSchedulerLogDTO categoryDataSchedulerLog, ResultAdsInfo result,
            PlacementOpportunityTypeEnum oppType, AccumulationGoiDay accumulationGoiDay,
            InventoryType inventoryType, Platform platformType) {

        boolean isSuccess = false;
        boolean useTargetListInfo = false;
        boolean useGoiDayInfo = false;
        AdvertiesmentType advertiesmentType = AdvertiesmentType.UNKNOWN_AD;

        String errorCode = "";
        String errorMessage = "";
        Date startDate = null, endDate = null;
        Integer campaignId = null;
        try {

            //1. UPDATE_AD_CAMPAIGN? OperationType ? ?   ?? .
            if (inputDataType == InputDataType.UPDATE_AD_CAMPAIGN) {
                boolean isDone = workByOperationType(ads, deleteSchedulerLogId, syncId);
                if (isDone) {
                    isSuccess = true;
                    campaignResult.increaseSuccessCount();
                    ResultFileUtil.addAdsInfoResult(ads, isSuccess, errorCode, errorMessage, inventoryType, oppType,
                            adsInfoResult);
                    return null;
                }
            }

            //2. Data   ?
            if (ads.getTargetList() != null && ads.getTargetList().isExistTarget() == true)
                useTargetListInfo = true; //  
            if (ads.getGoi_DAY() != null && ads.getGoi_DAY().isEmpty() == false)
                useGoiDayInfo = true; //??   (KT)

            advertiesmentType = AdvertiesmentType.valueof(ads);

            //3.  ?
            integrityAds(ads, useTargetListInfo, useGoiDayInfo, advertiesmentType, inventoryType);

            //4.  
            Integer reservePercent = CiStringUtil.parseInteger(ads.getReservePercent());
            if (reservePercent == null)
                reservePercent = 0;

            int accumulationGoiCnt = 0;
            startDate = DateUtil.string2Date(ads.getStart_DT()); //yyyy-mm-dd
            endDate = DateUtil.string2Date(ads.getEnd_DT()); //yyyy-mm-dd

            if (useGoiDayInfo == true && (advertiesmentType == AdvertiesmentType.COMMERCIAL_AD
                    || advertiesmentType == AdvertiesmentType.PREPLAY_PLUS_AD
                    || advertiesmentType == AdvertiesmentType.PUBLIC_AD
                    || advertiesmentType == AdvertiesmentType.PPT_AD
                    || advertiesmentType == AdvertiesmentType.COMMERCIAL_PPS_AD
                    || advertiesmentType == AdvertiesmentType.PPST_AD
                    || advertiesmentType == AdvertiesmentType.CPT_AD
                    || advertiesmentType == AdvertiesmentType.CPST_AD)) {
                accumulationGoiCnt = tambourineConnector.getSumADCampaignDailyExposure(ads.getAdSchedule_ID(),
                        startDate);
                accumulationGoiDay.addAccumulationGoiCnt(accumulationGoiCnt);
            }

            //cc_series_ID?   ? ? ?   Id?  menu_id? ?
            setMenuIdWithCcSeriesId(ads, categoryDataSchedulerLog);

            //-,,,?,,opp,slot,price
            //5. getTargetList     GenericAxisItems? .
            //  ? ?   , ?, , slot, ? GenericAxisItems? .
            //?   ,  ?,  
            GenericAxisItemIDSet genericAxisItemIDSet = null;
            if (useTargetListInfo == false) {
                genericAxisItemIDSet = getCommonGenericAxisItems(ads, advertiesmentType);
                genericAxisItemIDSet.addGenericAxisItemID(
                        getTimeAxisItemDTOs(ads.getTarget_TM(), ads.getTargetDay_CD()), TreeType.TIME_AXIS_TREE);
            } else
                genericAxisItemIDSet = new GenericAxisItemIDSet();

            Period period = new Period(startDate, DateUtil.getNextDate(endDate));
            ADSMCampaignDTO adCampaignDTO = convertADSMCampaignDTO(ads, accumulationGoiDay, period,
                    ads.getOpportunityType(), advertiesmentType, useGoiDayInfo, useTargetListInfo, inventoryType,
                    platformType);
            adCampaignDTO.setAccumulationGoiCnt(accumulationGoiCnt);

            campaignId = registerCampaign(ads, adCampaignDTO, genericAxisItemIDSet, syncId, advertiesmentType);
            isSuccess = true;
        } catch (DataIntegrityException e) {
            isSuccess = false;
            errorCode = e.getDataIntegrityExceptionType().toString();
            errorMessage = e.getMessage();
            campaignResult.increaseErrorCount();
        } catch (DuplicatedNameException de) {
            isSuccess = false;
            errorCode = "10";
            errorMessage = de.getMessage();
            campaignResult.increaseErrorCount();
        } catch (NotFoundException e) {
            isSuccess = false;
            errorCode = "20";
            errorMessage = e.getMessage();
            campaignResult.increaseErrorCount();
        } catch (DataException e) {
            isSuccess = false;
            errorCode = "30";
            errorMessage = e.getMessage();
            campaignResult.increaseErrorCount();
        } catch (HibernateException e) {
            isSuccess = false;
            errorCode = "30";
            errorMessage = e.getMessage();
            campaignResult.increaseErrorCount();
        } catch (SQLException e) {
            isSuccess = false;
            errorCode = "30";
            errorMessage = e.getMessage();
            campaignResult.increaseErrorCount();
        } catch (Exception e) {
            isSuccess = false;
            errorCode = "100";
            errorMessage = e.getMessage();
            if (errorMessage == null || errorMessage.isEmpty())
                errorMessage = e.toString();
            campaignResult.increaseErrorCount();
        } finally {
            ResultFileUtil.addAdsInfoResult(ads, isSuccess, errorCode, errorMessage, inventoryType, oppType,
                    result);
            errorCode = "";
            errorMessage = "";
            isSuccess = false;
        }
        return campaignId;
    }

    public SubInventoryDTO generateMultiSubInventoryMember(TargetList targetList, String startDate, String endDate,
            Set<GenericAxisItemIDDTO> commonGenericAxisItems, PriceTypeEnum priceType) throws Exception {

        SubInventoryDTO subInventoryDTO = new SubInventoryDTO();

        if (targetList != null && targetList.getTarget() != null && targetList.getTarget().isEmpty() == false) {
            subInventoryDTO.setStartDate(startDate);
            subInventoryDTO.setEndDate(endDate);

            //  ?.
            for (Target target : targetList.getTarget()) {
                SubInventoryMemberDTO member = null;
                member = tambourineConnector.generateSubInventoryMember(null, null, target.getRegion_Info(),
                        splitIds(target.getCategory_id(), true), splitIds(target.getContent_ID(), true),
                        target.getSlotOrdList(), null, priceType, timeDefineMap);
                //?  ?   load  Data ? .
                member.addAllAxisItemIDCopy(getTimeAxisItemDTOs(target.getTarget_TM(), target.getTargetDay_CD()));
                if (commonGenericAxisItems != null)
                    member.addAllAxisItemIDCopy(commonGenericAxisItems);
                subInventoryDTO.addMember(member);
            }
        }
        return subInventoryDTO;
    }

    public Integer registerCampaign(Ads ads, ADSMCampaignDTO adCampaignDTO,
            GenericAxisItemIDSet genericAxisItemIDSet, int syncId, AdvertiesmentType advertiesmentType)
            throws Exception {

        SubInventoryDTO subInventoryDTO = null;
        TargetList targetList = ads.getTargetList();
        InventorySizeManager inventorySizeManager = null;

        // ?  goiDay? goiCnt    execution_ratio   .
        if (targetList != null && targetList.getTarget() != null && targetList.getTarget().isEmpty() == false
                && advertiesmentType != AdvertiesmentType.DEFAULT_AD) {
            subInventoryDTO = generateMultiSubInventoryMember(targetList, ads.getStart_DT(), ads.getEnd_DT(),
                    genericAxisItemIDSet.getEntireGenericAxisItemIDs(), null);
        } else {
            subInventoryDTO = tambourineConnector.generateSubInventory(ads.getStart_DT(), ads.getEnd_DT(),
                    genericAxisItemIDSet.getEntireGenericAxisItemIDs());

            inventorySizeManager = new InventorySizeManager(timeTreeNodeChildCount,
                    adCampaignDTO.getExecutionPeriod(), ads.getTargetDay_CD());
            if (inventorySizeManager.getWeekDayCnt() > 0)
                inventorySizeManager.addDayCodeAxisItemID(InventoryBoxDayCode.WEEKDAY,
                        getTimeAxisItems(ads.getTarget_TM(), KT_MONDAY));
            if (inventorySizeManager.getWeekendDayCnt() > 0)
                inventorySizeManager.addDayCodeAxisItemID(InventoryBoxDayCode.WEEKEND,
                        getTimeAxisItems(ads.getTarget_TM(), KT_SATURDAY));
        }

        adCampaignDTO.setSubInventory(subInventoryDTO);

        Integer campaignId = inventoryExportSysCompForAdapter.registerCampaign(adCampaignDTO, inventorySizeManager,
                syncId, genericAxisItemIDSet);
        campaignResult.increaseSuccessCount(); // ?  . ? 0? ?   (fxpark)
        return campaignId;
    }

    public ADSMCampaignDTO convertADSMCampaignDTO(Ads ads, AccumulationGoiDay accumulationGoiDay, Period period,
            PlacementOpportunityTypeEnum opportunityType, AdvertiesmentType advertiesmentType,
            boolean useGoiDayInfo, boolean useTargetListInfo, InventoryType inventoryType, Platform platformType)
            throws Exception {

        ADSMCampaignDTO adCampaignDTO = new ADSMCampaignDTO();
        adCampaignDTO.setAdAssetID(ads.getAdAsset_ID());
        adCampaignDTO.setExternalCampaignId(ads.getExternalCampaignId());

        adCampaignDTO.setInventoryType(inventoryType);
        adCampaignDTO.setPlatformType(platformType);

        int priority = getIntegerValue(ads.getAdPriority());
        adCampaignDTO.setAdPriority(priority < 0 ? 0 : priority);
        adCampaignDTO.setAdPromotionType(getADContentType(ads.getAdPromo_YN()));
        adCampaignDTO.setAdTargetRate(TargetRate.valueof(ads.getPrInfo_CD()));
        adCampaignDTO.setAdAssetName(ads.getAdAsset_NM());
        adCampaignDTO.setCampaignName(ads.getAd_ID());
        adCampaignDTO.setContractNumber(ads.getAds_ID());
        adCampaignDTO.setTargetTM(ads.getTarget_TM());
        adCampaignDTO.setNoAdIfPaid(getPayTargetType(ads.getContentFree_YN()));

        float executionRatioWeight = getFloatValue(ads.getExecution_ratio_weight(), -1.0F);
        if (executionRatioWeight < 0)
            executionRatioWeight = 1.0F;
        adCampaignDTO.setExecutionRatioWeight(executionRatioWeight);
        ADCampaignClassType adCampaignClassType = getADCampaignClassType(ads.getAd_class());
        adCampaignDTO.setAdClass(adCampaignClassType);

        if (ads.getTarget_slot() == null) {
            String slotORD = (ads.getTarget_slot_ORD() == null) ? "0"
                    : (ads.getTarget_slot_ORD().isEmpty()) ? "0" : ads.getTarget_slot_ORD();
            slotORD = convertSlotOrder(slotORD);
            if (ads.getContentFree_YN() == null || ads.getContentFree_YN().equals("0")
                    || ads.getContentFree_YN().isEmpty()) {
                adCampaignDTO.setFreeTargetSlotOrder(slotORD);
                adCampaignDTO.setPaidTargetSlotOrder(slotORD);
                adCampaignDTO.setFreeResumeTargetSlotOrder(slotORD);
                adCampaignDTO.setPaidResumeTargetSlotOrder(slotORD);
            } else if (ads.getContentFree_YN().equals("1")) {
                adCampaignDTO.setPaidTargetSlotOrder(slotORD);
                adCampaignDTO.setPaidResumeTargetSlotOrder(slotORD);
            } else if (ads.getContentFree_YN().equals("2")) {
                adCampaignDTO.setFreeTargetSlotOrder(slotORD);
                adCampaignDTO.setFreeResumeTargetSlotOrder(slotORD);
            }
        } else {
            adCampaignDTO.setFreeTargetSlotOrder(ads.getTarget_slot().getFree_target_slot_ORD());
            adCampaignDTO.setPaidTargetSlotOrder(ads.getTarget_slot().getPaid_target_slot_ORD());
            adCampaignDTO.setFreeResumeTargetSlotOrder(ads.getTarget_slot().getFree_resume_target_slot_ORD());
            adCampaignDTO.setPaidResumeTargetSlotOrder(ads.getTarget_slot().getPaid_resume_target_slot_ORD());
        }
        //      adCampaignDTO.setPlayAdIfRelay(getRelayTargetType(ads.getRelay_YN())); // Relay_YN
        //adCampaignDTO.setNoAdIfReplay((ads.getRelay_YN().equalsIgnoreCase("Y")) ? false : true);

        int runtimeLimit = getIntegerValue(ads.getRunTimeLimit());
        adCampaignDTO.setNoAdRuntimeLimit(runtimeLimit < 0 ? 0 : runtimeLimit);
        adCampaignDTO.setVodTargetRate(ads.getTargeting_Rate());
        adCampaignDTO.setExecutionPeriod(period);
        adCampaignDTO.setOpportunityType(opportunityType);

        ExecutionState executionState = ExecutionState.valueof(ads.getExecution_state());
        com.castis.tambourine.dto.adsm.enumeration.ADCampaignStatus adCampaignStatus = com.castis.tambourine.dto.adsm.enumeration.ADCampaignStatus
                .valueOf(executionState.name());
        adCampaignDTO.setCampaignStatus(adCampaignStatus);

        if (ads.getConfirm_date() != null) {
            Date confirmDate = DateUtil.string2Date(ads.getConfirm_date(), "yyyy-MM-dd HH:mm:ss");
            adCampaignDTO.setConfirmDate(confirmDate);
        }

        int executionQueueNumber = getIntegerValue(ads.getExecution_queue_number());
        adCampaignDTO.setExecutionQueueNumber(executionQueueNumber);

        int bonusMonopolyRate = getIntegerValue(ads.getBonus_monopoly_rate());
        adCampaignDTO.setBonusMonopolyRate(bonusMonopolyRate);

        float bonusExecutionRatio = getFloatValue(ads.getBonus_execution_ratio(), -1.0F);
        adCampaignDTO.setBonusExecutionRatio(bonusExecutionRatio);

        float bonusExecutionRatioWeight = getFloatValue(ads.getBonus_execution_ratio_weight(), -1.0F);
        if (bonusExecutionRatioWeight < 0)
            bonusExecutionRatioWeight = 1.0F;
        adCampaignDTO.setBonusExecutionRatioWeight(bonusExecutionRatioWeight);

        int bonusExecutionQueueNumber = getIntegerValue(ads.getBonus_execution_queue_number());
        adCampaignDTO.setBonusExecutionQueueNumber(bonusExecutionQueueNumber);

        int bonusGoiCNT = getIntegerValue(ads.getBonus_goi_CNT());
        adCampaignDTO.setBonusGoiCNT(bonusGoiCNT);

        int monopolyRate = getIntegerValue(ads.getMonopoly_Rate());
        int monopolyRateByView = getIntegerValue(ads.getMonopoly_Rate_by_view());

        /*??   */
        if (ads.getDailyGoiLimit() != null) {
            DailyGoiLimit dailyGoiLimit = ads.getDailyGoiLimit();

            Period dailyBonusGoiLimitPeriod = new Period(
                    DateUtil.string2Date(dailyGoiLimit.getDaily_bonus_goi_limit_start_date(),
                            "yyyy-MM-dd HH:mm:ss"),
                    DateUtil.string2Date(dailyGoiLimit.getDaily_bonus_goi_limit_end_date(), "yyyy-MM-dd HH:mm:ss"));
            Period dailyGoiLimitPeriod = new Period(
                    DateUtil.string2Date(dailyGoiLimit.getDaily_goi_limit_start_date(), "yyyy-MM-dd HH:mm:ss"),
                    DateUtil.string2Date(dailyGoiLimit.getDaily_goi_limit_end_date(), "yyyy-MM-dd HH:mm:ss"));

            adCampaignDTO.setDailyBonusGoiLimitPeriod(dailyBonusGoiLimitPeriod);
            adCampaignDTO.setDailyGoiLimitPeriod(dailyGoiLimitPeriod);

            int dailyGoiLimitCNT = getIntegerValue(dailyGoiLimit.getDaily_goi_limit_CNT());
            int dailyBonusGoiLimitCNT = getIntegerValue(dailyGoiLimit.getDaily_bonus_goi_limit_CNT());

            adCampaignDTO.setDailyGoiLimitCNT(dailyGoiLimitCNT);
            adCampaignDTO.setDailyBonusGoiLimitCNT(dailyBonusGoiLimitCNT);

            adCampaignDTO.setDailyExposureLimit(getParseBoolean(dailyGoiLimit.getIs_daily_exposure_limit()));
            adCampaignDTO
                    .setDailyBonusExposureLimit(getParseBoolean(dailyGoiLimit.getIs_daily_bonus_exposure_limit()));

            //XML ? DailyGoiLimit  isDailyExposureLimit, isDailyBonusExposureLimit ? ?   ? .
            if (limitHourlyExposure == true)
                adCampaignDTO.setHourlyGoiLimit(
                        adCampaignDTO.isDailyExposureLimit() || adCampaignDTO.isDailyBonusExposureLimit());

        } else if (limitHourlyExposure == true && useGoiDayInfo == true && useTargetListInfo == false) {
            //goi_day ? ?  ??  ?   ? .
            if (advertiesmentType == AdvertiesmentType.COMMERCIAL_AD
                    || advertiesmentType == AdvertiesmentType.PREPLAY_PLUS_AD
                    || advertiesmentType == AdvertiesmentType.PUBLIC_AD
                    || advertiesmentType == AdvertiesmentType.PPT_AD
                    || advertiesmentType == AdvertiesmentType.COMMERCIAL_PPS_AD
                    || advertiesmentType == AdvertiesmentType.PPST_AD
                    || advertiesmentType == AdvertiesmentType.CPT_AD
                    || advertiesmentType == AdvertiesmentType.CPST_AD) {
                adCampaignDTO.setDailyGoiLimitPeriod(period);
                adCampaignDTO.setDailyGoiLimitCNT(-1);
                adCampaignDTO.setDailyAccumulationLimit(accumulationGoiDay.toFormalString());
                adCampaignDTO.setDailyMinimumExposureCount(accumulationGoiDay.getDailyMinExCnt());
                adCampaignDTO.setDailyExposureLimit(true);
                adCampaignDTO.setHourlyGoiLimit(true);
            }
        }

        adCampaignDTO.setScheduleRoundType(ScheduleRoundType.UNKNOWN_ROUND);

        if (advertiesmentType == AdvertiesmentType.DEFAULT_AD || advertiesmentType == AdvertiesmentType.DUMMY_AD) {

            float executionRatio = 1.0F;
            if (ads.getAdDefault_excution_ratio() != null && ads.getAdDefault_excution_ratio().isEmpty() == false)
                executionRatio = getFloatValue(ads.getAdDefault_excution_ratio(), 1.0F);
            if (executionRatio <= 0)
                executionRatio = 1.0F;

            adCampaignDTO.setExecutionRatio(executionRatio);
            adCampaignDTO.setUseServiceCount(false);
            adCampaignDTO.setMonopolyRate(-1);
            adCampaignDTO.setMonopolyRateByView(-1);
            adCampaignDTO.setServiceCount(0);
            adCampaignDTO.setAdDefaultYN(true);
            adCampaignDTO.setAdPromotionType(SubscriptionType.UNKNOWN_AD);
        } else {

            float executionRatio = getFloatValue(ads.getExecution_ratio(), -1.0F);
            adCampaignDTO.setExecutionRatio(executionRatio);
            adCampaignDTO.setMonopolyRate(monopolyRate);
            adCampaignDTO.setMonopolyRateByView(monopolyRateByView);

            //limitOverGoal? true? KT  ? ?.
            if (ADDSAdapterSetting.isLimitOverGoal() == true) {
                //ad_for_bonus_service_YN? Y? bonus_service_execution_ratio? bonusExecutionRatio? 
                //service Count  bonus goi count ? 0 .
                // useServiceCount? true .
                //passDefaultRound? false .
                if (advertiesmentType == AdvertiesmentType.BONUS_SERVICE_AD
                        || advertiesmentType == AdvertiesmentType.BONUS_PPS_AD) {
                    float bonusServiceExecutionRatio = 1.0F;

                    if (ads.getBonusServiceExecutionRatio() != null
                            && ads.getBonusServiceExecutionRatio().isEmpty() == false)
                        bonusServiceExecutionRatio = getFloatValue(ads.getBonusServiceExecutionRatio(), 1.0F);
                    if (bonusServiceExecutionRatio <= 0)
                        bonusServiceExecutionRatio = 1.0F;

                    //   ADDITIONAL_SERVICE_ROUND 
                    if (advertiesmentType == AdvertiesmentType.BONUS_PPS_AD)
                        adCampaignDTO.setScheduleRoundType(ScheduleRoundType.BONUS_PPS_ROUND);
                    else
                        adCampaignDTO.setScheduleRoundType(ScheduleRoundType.ADDITIONAL_SERVICE_ROUND);
                    adCampaignDTO.setExecutionRatio(bonusServiceExecutionRatio);
                    adCampaignDTO.setServiceCount(0);
                    adCampaignDTO.setBonusGoiCNT(0);
                    adCampaignDTO.setUseServiceCount(false);
                    adCampaignDTO.setMonopolyRate(-1);
                    adCampaignDTO.setMonopolyRateByView(-1);
                    adCampaignDTO.setAdPromotionType(SubscriptionType.UNKNOWN_AD);
                } else {
                    //ad_for_bonus_service_YN? N?  ?? useServiceCount? false . 
                    if (advertiesmentType == AdvertiesmentType.PROMO_AD
                            || advertiesmentType == AdvertiesmentType.MONOPOLY_AD
                            || advertiesmentType == AdvertiesmentType.MONOPOLY_BY_VIEW_AD
                            || advertiesmentType == AdvertiesmentType.MONOPOLY_PPS_AD) {
                        adCampaignDTO.setUseServiceCount(false);
                    }
                    //ad_for_bonus_service_YN? N? ? ?
                    else {
                        // useServiceCount? ?? ? ? ? 
                        if (ads.getUse_service_count() != null && !ads.getUse_service_count().isEmpty()) {
                            adCampaignDTO.setUseServiceCount(getParseBoolean(ads.getUse_service_count()));
                        } else {
                            //useServiceCount? ? ?       useServiceCount? true .                     
                            if (accumulationGoiDay.getTotalGoi() > 0)
                                adCampaignDTO.setUseServiceCount(true);
                            else
                                adCampaignDTO.setUseServiceCount(false);
                        }

                    }
                    adCampaignDTO.setServiceCount(accumulationGoiDay.getTotalGoi());
                    adCampaignDTO.setServiceCountAppliedReserve(accumulationGoiDay.getLastAccumulationCounts());
                }
            } else {
                adCampaignDTO.setUseServiceCount(getParseBoolean(ads.getUse_service_count()));
                adCampaignDTO.setServiceCount(accumulationGoiDay.getTotalGoi());
            }
        } ////////////////

        String targetContentAudioType = ads.getTargetContentAudioType();
        if (targetContentAudioType == null || targetContentAudioType.isEmpty())
            if (inventoryType != InventoryType.CUETONE)
                targetContentAudioType = "aac";

        adCampaignDTO.setTargetContentAudioType(targetContentAudioType);
        adCampaignDTO.setUsePolicyInTheCampaign(getUsePolicyInTheCampaign(ads));
        adCampaignDTO.setReservePercent(getIntegerValue(ads.getReservePercent())); //reserve percent

        //PP+ ?  (adProductType? PP+? useServiceCount true )
        if (advertiesmentType == AdvertiesmentType.PREPLAY_PLUS_AD) {
            adCampaignDTO.setUseServiceCount(true);
            adCampaignDTO.setMonopolyRate(-1);
            adCampaignDTO.setScheduleRoundType(ScheduleRoundType.PLUS_ROUND);
        }

        //PPT
        if (advertiesmentType == AdvertiesmentType.PPT_AD) {
            adCampaignDTO.setUseServiceCount(true);
            adCampaignDTO.setMonopolyRate(-1);
            adCampaignDTO.setScheduleRoundType(ScheduleRoundType.PROGRAM_ROUND);
        }

        //PPTS
        if (advertiesmentType == AdvertiesmentType.PPST_AD) {
            adCampaignDTO.setUseServiceCount(true);
            adCampaignDTO.setMonopolyRate(-1);
            adCampaignDTO.setScheduleRoundType(ScheduleRoundType.PPST_ROUND);
        }

        //CPT
        if (advertiesmentType == AdvertiesmentType.CPT_AD) {
            adCampaignDTO.setUseServiceCount(true);
            adCampaignDTO.setMonopolyRate(-1);
            adCampaignDTO.setScheduleRoundType(ScheduleRoundType.CPT_ROUND);
        }

        //CPTS
        if (advertiesmentType == AdvertiesmentType.CPST_AD) {
            adCampaignDTO.setUseServiceCount(true);
            adCampaignDTO.setMonopolyRate(-1);
            adCampaignDTO.setScheduleRoundType(ScheduleRoundType.CPST_ROUND);
        }

        if (advertiesmentType == AdvertiesmentType.PUBLIC_AD) {
            adCampaignDTO.setUseServiceCount(true);
            adCampaignDTO.setAdPromotionType(SubscriptionType.COMMERCIAL_VIDEO); //? or   , ?? ? 
            adCampaignDTO.setScheduleRoundType(ScheduleRoundType.PUBLIC_ROUND);
        }

        if (advertiesmentType == AdvertiesmentType.MONOPOLY_AD)
            adCampaignDTO.setScheduleRoundType(ScheduleRoundType.MONOPOLY_ROUND);

        if (advertiesmentType == AdvertiesmentType.COMMERCIAL_PPS_AD)
            adCampaignDTO.setScheduleRoundType(ScheduleRoundType.COMMERCIAL_PPS_ROUND);

        if (advertiesmentType == AdvertiesmentType.MONOPOLY_PPS_AD)
            adCampaignDTO.setScheduleRoundType(ScheduleRoundType.MONOPOLY_PPS_ROUND);

        if (advertiesmentType == AdvertiesmentType.DUMMY_AD)
            adCampaignDTO.setScheduleRoundType(ScheduleRoundType.DUMMY_ROUND);

        return adCampaignDTO;
    }

    private boolean getUsePolicyInTheCampaign(Ads ads) {
        if (ads.getRunTimeLimit() != null && ads.getRunTimeLimit().isEmpty() == false)
            return true;
        if (ads.getContentFree_YN() != null && ads.getContentFree_YN().isEmpty() == false)
            return true;
        return false;
    }

    private PayTargetType getPayTargetType(String contentFree_YN) throws Exception {
        if (contentFree_YN == null || contentFree_YN.isEmpty())
            return PayTargetType.ALL;
        return PayTargetType.values()[Integer.parseInt(contentFree_YN)];
    }

    /*  */
    //   private RelayTargetType getRelayTargetType(String relay_YN) throws Exception {
    //      if (relay_YN == null || relay_YN.isEmpty()) return RelayTargetType.ALL;
    //      return RelayTargetType.values()[Integer.parseInt(relay_YN)];
    //   }

    private boolean getParseBoolean(String dataYN) {
        if (dataYN == null || dataYN.isEmpty())
            return false;
        else if (dataYN.equalsIgnoreCase("1") == true)
            return true;
        else if (dataYN.equals("y") == true)
            return true;
        else
            return false;
    }

    private SubscriptionType getADContentType(String adPromo_YN) throws Exception {
        //enum type?  ? ??   ?? null?    100 ? .
        if (adPromo_YN == null || adPromo_YN.isEmpty())
            return SubscriptionType.UNKNOWN_AD;
        //throw new Exception("adPromo_YN field is null.");
        if (adPromo_YN.equalsIgnoreCase("1") == true)
            return SubscriptionType.OAP;
        else if (adPromo_YN.equalsIgnoreCase("0") == true)
            return SubscriptionType.COMMERCIAL_VIDEO;
        else
            return SubscriptionType.UNKNOWN_AD;
    }

    private ADCampaignClassType getADCampaignClassType(String adCampaignClass) throws Exception {
        if (adCampaignClass == null || adCampaignClass.isEmpty())
            return ADCampaignClassType.NEUTRAL;
        return ADCampaignClassType.valueof(adCampaignClass);
    }

    public boolean generateDisableSameFieldADPolicyDTO(AdsInfo adsInfo, Date startTime, int deleteSchedulerLogId,
            PlacementOpportunityTypeEnum oppType, PlayInfo playInfo, Platform platformType,
            InventoryType inventoryType) {

        boolean result = false;
        log.info("@@@ generateDisableSameFieldADPolicyDTO - start");
        long start = System.currentTimeMillis(), end;

        try {
            String startDate = DateUtil.date2String(startTime);
            inventoryExportSysCompForAdapter.stopAllDisableSameFieldADPolicy(startDate, false, deleteSchedulerLogId,
                    oppType, inventoryType);
            if (playInfo != null && playInfo.getAdCategory_dat() != null
                    && playInfo.getAdCategory_dat().getAdCategoryList() != null
                    && playInfo.getAdCategory_dat().getAdCategoryList().size() != 0) {

                DisableSameFieldADPolicyDTO policyDTO = new DisableSameFieldADPolicyDTO();
                List<AdCategory> adCategoryList = playInfo.getAdCategory_dat().getAdCategoryList();
                Set<String> uniqueADCategoryName = new HashSet<String>();
                for (AdCategory adCategory : adCategoryList) {
                    if (adCategory.getAdCategry_id() != null && !adCategory.getAdCategry_id().equals("")
                            && adCategory.getAdAsset_list() != null
                            && adCategory.getAdAsset_list().getAdAsset_id() != null
                            && adCategory.getAdAsset_list().getAdAsset_id().size() > 1) {
                        if (!uniqueADCategoryName.contains(adCategory.getAdCategry_id())) {
                            List<String> adAssetIdList = adCategory.getAdAsset_list().getAdAsset_id();
                            Set<String> adAssetIdSet = new HashSet<String>();
                            for (String adAssetId : adAssetIdList) {
                                if (!adAssetId.equals("")) {
                                    if (!adAssetIdSet.contains(adAssetId)) {
                                        adAssetIdSet.add(adAssetId);
                                    } else {
                                        log.warn("adAsset_list ? ?  adAsset_id : " + adAssetId
                                                + "   ?  . adCategory_id : "
                                                + adCategory.getAdCategry_id());
                                    }
                                }
                            }
                            if (adAssetIdSet.size() > 1) {
                                DisableSameFieldADItemDTO itemDTO = new DisableSameFieldADItemDTO(
                                        adCategory.getAdCategry_id(), new ArrayList<String>(adAssetIdSet));
                                policyDTO.addDisableSameFieldADItem(itemDTO);
                                uniqueADCategoryName.add(adCategory.getAdCategry_id());
                            } else {
                                log.warn(
                                        "adAsset_list ?  adAsset_id  1 ?   . adCategory_id : "
                                                + adCategory.getAdCategry_id());
                            }
                        } else {
                            log.warn("?  adCategory_id : " + adCategory.getAdCategry_id()
                                    + "  ?  . adCategory_id : "
                                    + adCategory.getAdCategry_id());
                        }
                    } else if (adCategory.getAdCategry_id() == null || adCategory.getAdCategry_id().equals("")) {
                        log.warn("adCategory_id  ?  .");
                    } else if (adCategory.getAdAsset_list() == null
                            || adCategory.getAdAsset_list().getAdAsset_id() == null
                            || adCategory.getAdAsset_list().getAdAsset_id().size() <= 1) {
                        log.warn(
                                "adAsset_list ?  adAsset_id  1 ?   . adCategory_id : "
                                        + adCategory.getAdCategry_id());
                    }
                }
                if (policyDTO.getDisableSameFeildAdItemList() != null) {
                    policyDTO.setOppType(oppType);
                    policyDTO.setInventoryType(inventoryType);
                    policyDTO.setPlatformType(platformType);
                    policyDTO.setSubInventory(tambourineConnector.generateSubInventory(startDate, "99991231", null,
                            null, null, null, null, null, oppType, null, null, null, null, null, null));

                    try {
                        result = inventoryExportSysCompForAdapter.registerDisableSameFieldADPolicy(policyDTO);
                    } catch (Exception e) {
                        TheLogger.getWriter()
                                .error(adsInfo.getXml_ID() + " DisableSameFieldADPolicy   ");
                        throw new WrappingException(e.getMessage());
                    }

                }
            }

        } catch (WrappingException e) {
            log.error("DisableSameFieldADPolicy  ? . err : " + e.getMessage());
        } catch (Exception e) {
            log.error("", e);
        }
        end = System.currentTimeMillis();
        log.info("@@@ generateDisableSameFieldADPolicyDTO - end(" + (end - start) + " ms)");
        return result;

    }

    public boolean generateADProductPriorityPolicyDTO(AdsInfo adsInfo, Date startTime, int deleteSchedulerLogId,
            PlacementOpportunityTypeEnum oppType, PlayInfo playInfo, Platform platformType,
            InventoryType inventoryType) {

        boolean result = false;
        log.info("@@@ generateADProductPriorityPolicyDTO - start");
        long start = System.currentTimeMillis(), end;

        try {
            if (playInfo != null && playInfo.getAdProduct_priority_policy() != null
                    && playInfo.getAdProduct_priority_policy().getAdProductPriorityList() != null
                    && playInfo.getAdProduct_priority_policy().getAdProductPriorityList().size() != 0) {

                String startDate = DateUtil.date2String(startTime);
                inventoryExportSysCompForAdapter.stopAllADProductPriorityPolicy(startDate, false,
                        deleteSchedulerLogId, oppType, inventoryType);
                ADProductPriorityPolicyDTO policyDTO = new ADProductPriorityPolicyDTO();

                List<AdProduct_priority> adProductPriorityList = playInfo.getAdProduct_priority_policy()
                        .getAdProductPriorityList();

                for (AdProduct_priority adPrior : adProductPriorityList) {
                    if (!Arrays.asList(adProductArr).contains(adPrior.getAdProduct_Type())) {
                        throw new WrappingException(
                                " ?  ? ? ? ?. <adProduct_Type>"
                                        + adPrior.getAdProduct_Type() + "</adProduct_Type>");
                    }

                    ADProductPriorityItemDTO itemDTO = new ADProductPriorityItemDTO(adPrior.getAdProduct_Type(),
                            adPrior.getRound_priority());
                    policyDTO.addADProductPriorityItem(itemDTO);
                }
                policyDTO.setOppType(oppType);
                policyDTO.setInventoryType(inventoryType);
                policyDTO.setPlatformType(platformType);
                policyDTO.setSubInventory(tambourineConnector.generateSubInventory(startDate, "99991231", null,
                        null, null, null, null, null, oppType, null, null, null, null, null, null));

                try {
                    result = inventoryExportSysCompForAdapter.registerADProductPriorityPolicy(policyDTO);
                } catch (Exception e) {
                    TheLogger.getWriter().error(adsInfo.getXml_ID() + " ADProductPriority   ");
                    throw new WrappingException(e.getMessage());
                }
            } else {
                log.error(" ?  ?  .");
            }

        } catch (WrappingException e) {
            log.error("ADProductPriorityPolicy  ? . err : " + e.getMessage());
        } catch (Exception e) {
            log.error("", e);
        }
        end = System.currentTimeMillis();
        log.info("@@@ generateADProductPriorityPolicyDTO - end(" + (end - start) + " ms)");

        return result;

    }

    //@Transactional(rollbackFor=Exception.class)
    public boolean generateContinuosExposurePolicyDTO(AdsInfo adsInfo, Date startTime, int deleteSchedulerLogId,
            PlacementOpportunityTypeEnum oppType, PlayInfo playInfo, Platform platformType,
            InventoryType inventoryType) {
        long start = System.currentTimeMillis(), end;
        log.info("@@@ generateContinuosExposurePolicyDTO - start");

        //?  ? 
        String startDate = DateUtil.date2String(startTime);
        inventoryExportSysCompForAdapter.stopAllContinuosExposurePolicy(startDate, false, deleteSchedulerLogId,
                oppType, inventoryType);

        List<ContinuosExposurePolicyDTO> policyListDTO = new ArrayList<ContinuosExposurePolicyDTO>();
        try {
            if (playInfo != null && playInfo.getAd_play_cnt_cfg() != null) {
                ContinuosExposurePolicyDTO playPolicyDTO = new ContinuosExposurePolicyDTO();
                Integer maxContPlay = playInfo.getAd_play_cnt_cfg().getMax_cont_play();
                playPolicyDTO
                        .setMaxCountinuosExposureCount(maxContPlay == null ? DEFAULT_MAX_CONT_PLAY : maxContPlay);
                Integer maxPlay = playInfo.getAd_play_cnt_cfg().getMax_play();
                playPolicyDTO.setMaxExposureCount(maxPlay == null ? DEFAULT_MAX_PLAY : maxPlay);
                Integer minInterval = playInfo.getAd_play_cnt_cfg().getMin_interval();
                playPolicyDTO
                        .setMinBreakCountToNextExposure(minInterval == null ? DEFAULT_MIN_INTERVAL : minInterval);
                playPolicyDTO.setPriority(DEFAULT_CONTINUOUS_POLICY_PRIORITY);
                playPolicyDTO.setSubInventory(tambourineConnector.generateSubInventory(startDate, "99991231", null,
                        null, null, null, null, null, oppType, null, null, null, null, null, null));
                playPolicyDTO.setOppType(oppType);
                playPolicyDTO.setInventoryType(inventoryType);
                playPolicyDTO.setPlatformType(platformType);

                policyListDTO.add(playPolicyDTO);
            }

        } catch (WrappingException e) {
            log.error("ContinuosExposurePolicy  ? . err : " + e.getMessage());
        } catch (Exception e) {
            log.error("", e);
        }

        boolean result;
        try {
            result = inventoryExportSysCompForAdapter.registerContinuosExposurePolicies(policyListDTO);
        } catch (Exception e) {
            TheLogger.getWriter().error(adsInfo.getXml_ID() + " ContinuosExposure   ");
            throw new WrappingException(e.getMessage());
        }

        end = System.currentTimeMillis();
        log.info("@@@ generateContinuosExposurePolicyDTO - end(" + (end - start) + " ms)");
        return result;

    }

    private Integer getIntegerValue(String string) {
        if (string == null || string.isEmpty())
            return -1;
        try {
            return Integer.parseInt(string);
        } catch (NumberFormatException e) {
            log.warn(string + " is wrong int-number");
            return -1;
        }
    }

    private float getFloatValue(String string, float defaultFloat) {
        if (string == null || string.isEmpty())
            return defaultFloat;
        try {
            return Float.parseFloat(string);
        } catch (NumberFormatException e) {
            log.warn(string + " is wrong float-number");
            return defaultFloat;
        }
    }

    private void uniqueIdCheckInCampaign(Ad_list allAdList, ResultAdsInfo result,
            PlacementOpportunityTypeEnum oppType, InventoryType inventoryType) {
        List<ADCampaign> ADCampaignList = new ArrayList<ADCampaign>();
        Set<String> adIDSet = new HashSet<String>();
        Set<String> adScheduleIDSet = new HashSet<String>();
        ADCampaignList = inventoryExportSysCompForAdapter.getADCampaignListByStatus();

        boolean isSuccess = false;
        String errorCode = "";
        String errorMessage = "";

        for (int i = 0; i < ADCampaignList.size(); i++) {
            String adID = ADCampaignList.get(i).getCampaignAdId();
            adIDSet.add(adID);
            String adScheduleId = ADCampaignList.get(i).getExternalCampaignId();
            adScheduleIDSet.add(adScheduleId);
        }
        Iterator<Ads> it = allAdList.getAdsList().iterator();

        Ads ads = null;
        while (it.hasNext()) {
            ads = it.next();
            try {
                if (ads.getAd_ID() != null && (ads.getAd_ID().isEmpty() == false)
                        && adIDSet.contains(ads.getAd_ID())) {
                    throw new DuplicatedNameException(
                            "duplicate Campaign in DB Table adId Value. adId = " + ads.getAd_ID());
                }
                if (ads.getExternalCampaignId() != null && (ads.getExternalCampaignId().isEmpty() == false)
                        && adScheduleIDSet.contains(ads.getExternalCampaignId())) {
                    throw new DuplicatedNameException(
                            "duplicate Campaign in DB Table adScheduleId Value. adScheduleId = "
                                    + ads.getExternalCampaignId());
                }
                // adId? exception? ?. duplicateNameException
                if (ads.getAd_ID() != null && (ads.getAd_ID().isEmpty() == false)
                        && setAdId.contains(ads.getAd_ID())) {
                    throw new DuplicatedNameException("duplicate Campaign adId Value. adId = " + ads.getAd_ID());
                }

                if (ads.getAd_ID() != null && (ads.getAd_ID().isEmpty() == false))
                    setAdId.add(ads.getAd_ID());

                isSuccess = true;
            } catch (DuplicatedNameException de) {
                it.remove();
                isSuccess = false;
                errorCode = "10";
                errorMessage = de.getMessage();
                campaignResult.increaseErrorCount();
            }

            if (isSuccess == false) {
                ResultFileUtil.addAdsInfoResult(ads, isSuccess, errorCode, errorMessage, inventoryType, oppType,
                        result);
                errorCode = "";
                errorMessage = "";
                isSuccess = false;
            }
        }
    }

    private boolean workByOperationType(Ads ads, int deleteSchedulerLogId, int syncId) throws Exception {
        OperationType adsOperationType = caseBycaseUpdateADCampaign(ads.getAd_ID(), ads.getOperation(),
                deleteSchedulerLogId, syncId);

        switch (adsOperationType) {
        case INSERT:
            log.info("  ?  INSERT . (adsID:" + ads.getAds_ID() + ", adID:"
                    + ads.getAd_ID() + ")");
            break;
        case UPDATE:
            log.info("? ? ?  UPDATE . (adsID:" + ads.getAds_ID()
                    + ", adID:" + ads.getAd_ID() + ")");
            break;
        case DELETE:
            log.info("? ? ?  DELETE . (adsID:" + ads.getAds_ID()
                    + ", adID:" + ads.getAd_ID() + ")");
            break;
        }

        if (adsOperationType == OperationType.DELETE)
            return true;

        return false;
    }

    //cc_series_ID  ,  ID? ?  ID?  menu_ID? .(? menu_ID )
    private void setMenuIdWithCcSeriesId(Ads ads, ADSMSchedulerLogDTO categoryDataSchedulerLog) {
        // cc_series_ID?   ?
        if (ads.getCcSeriesId() == null || ads.getCcSeriesId().equals(""))
            return;

        //,  ??    ?
        if (categoryDataSchedulerLog == null)
            return;

        String ccSeriesId = ads.getCcSeriesId();

        List<CategoryDataDTO> categoryDataList = tambourineConnector
                .getCategoryDataByCcSeriesId(categoryDataSchedulerLog.getId(), ccSeriesId);

        //cc_series_Id?  menu_id?  ??  ?
        // cc_series_Id? ?   ,   . ? ? .
        if (categoryDataList.size() == 0) {
            String errorMsg = "cc_series_ID(" + ccSeriesId
                    + ")?    ?  .";
            throw new WrappingException(errorMsg);
        }

        StringBuffer sb = new StringBuffer();

        for (CategoryDataDTO data : categoryDataList) {
            sb.append(data.getCatId());
            sb.append("|");
        }

        ads.setMenu_ID(sb.substring(0, sb.length() - 1));
    }

    //  ?,  ??? Exception? ? ?   ?
    private void isBeforeDate(Date startDate, Date endDate) throws Exception {
        Date nowDate = DateUtil.getCurDate();

        //startDate endDate ??  ? Exception ?
        if (startDate.after(endDate))
            throw new Exception("this campaign is not valid. startDate(" + startDate + ") is later than endDate("
                    + endDate + ").");

        //endDate  Date ???  ?? Exception ?
        if (endDate.before(nowDate))
            throw new Exception("this campaign is not valid. endDate is (" + endDate + ").");

    }

    private boolean setTimeDefineMap(InputDataType inputDataType, ResultFileUtil resultFileUtil) {
        try {
            timeDefineMap = tambourineConnector.getTimeDefineMap();
            if (timeDefineMap == null) {
                String errMsg = "Time Define   . " + inputDataType.toString()
                        + " ? ?   .";
                ResultFileUtil.addPolicyResult(null, false, "100", errMsg, PlacementOpportunityTypeEnum.PREROLL,
                        inputDataType, adsInfoResult, resultFileUtil);
                return false;
            }
        } catch (Exception e) {
            String errMsg = "Time Define  load   . error : " + e.getMessage();
            ResultFileUtil.addPolicyResult(null, false, "100", errMsg, PlacementOpportunityTypeEnum.PREROLL,
                    inputDataType, adsInfoResult, resultFileUtil);
            return false;
        }

        return true;
    }

    void addAllAdList(PlayInfo playInfo, Ad_list output, PlacementOpportunityTypeEnum oppType) {
        if (playInfo == null)
            return;

        Ad_list adList = playInfo.getAd_list();
        if (adList != null && adList.getAdsList() != null) {
            //         GenericAxisItemIDDTO genericAxisItemIDDTO = tambourineConnector.getPlacementTypeGenericAxisItemID(oppType);
            output.getAdsList().addAll(adList.getAdsList(/*genericAxisItemIDDTO,*/ oppType));
        }
    }

    //unknown cateogry ?  ?
    PlayInfo customizeUnknownCategoryAds(PlayInfo playInfo) {
        if (playInfo == null)
            return null;

        convertUnknownCategoryAds(playInfo);

        return playInfo;
    }

    void convertUnknownCategoryAds(PlayInfo playInfo) {
        if (playInfo != null && playInfo.getAd_list() != null) {
            Iterator<Ads> itr_Ads = playInfo.getAd_list().getUnknownCategoryAdsList().iterator();
            while (itr_Ads.hasNext()) {
                Ads ads = itr_Ads.next();

                if (ads.getAdPromo_YN() == null || ads.getAdPromo_YN().equalsIgnoreCase("1")) //promo (? )
                {
                    itr_Ads.remove();
                    continue;
                }

                ads.setMenu_ID("?"); //unknown   
                ads.setUse_service_count("0"); //0? false =>   
                ads.setAdProductType(null); //PP+ 
                ads.setMonopoly_Rate(null); //monopoly 
                ads.setMonopoly_Rate_by_view(null); //monopoly_by_view 
            }
        }
    }

    private String toPpsString(SortedSet<Integer> ppsSlotNumber) {
        return ppsSlotNumber.toString().substring(1, ppsSlotNumber.toString().length() - 1).replaceAll("\\p{Space}",
                "");
    }

}