com.roncoo.pay.app.reconciliation.parser.WEIXINParser.java Source code

Java tutorial

Introduction

Here is the source code for com.roncoo.pay.app.reconciliation.parser.WEIXINParser.java

Source

/*
 * Copyright 2015-2102 RonCoo(http://www.roncoo.com) Group.
 *  
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *  
 *      http://www.apache.org/licenses/LICENSE-2.0
 *  
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package com.roncoo.pay.app.reconciliation.parser;

import java.io.File;
import java.io.IOException;
import java.math.BigDecimal;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import org.apache.commons.io.FileUtils;
import org.apache.commons.lang.StringUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.jdom2.JDOMException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import com.roncoo.pay.reconciliation.entity.RpAccountCheckBatch;
import com.roncoo.pay.reconciliation.enums.BatchStatusEnum;
import com.roncoo.pay.reconciliation.service.RpAccountCheckBatchService;
import com.roncoo.pay.reconciliation.utils.XmlUtils;
import com.roncoo.pay.reconciliation.vo.ReconciliationEntityVo;

/**
 * ?? .
 *
 * www.roncoo.com
 * 
 * @authorshenjialong
 */
@Component("WEIXINParser")
public class WEIXINParser implements ParserInterface {

    private static final Log LOG = LogFactory.getLog(WEIXINParser.class);

    private static final String DATE_FORMAT_STYLE = "yyyy-MM-dd HH:mm:ss";

    @Autowired
    private RpAccountCheckBatchService rpAccountCheckBatchService;

    /**
     * ????
     * 
     * @param file
     *            ??
     * @param billDate
     *            ?
     * @param batch
     *            
     * @return
     */
    public List<ReconciliationEntityVo> parser(File file, Date billDate, RpAccountCheckBatch batch) {
        SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd");
        String billDateStr = sdf.format(billDate);

        // file?
        this.isError(file, batch);
        if (batch.getStatus() != null) {
            if (batch.getStatus().equals(BatchStatusEnum.ERROR.name())
                    || batch.getStatus().equals(BatchStatusEnum.NOBILL.name())) {
                if (LOG.isDebugEnabled()) {
                    LOG.debug(", : " + billDateStr + ", batchStatus: "
                            + BatchStatusEnum.ERROR + ", bankMsg: [" + batch.getBankErrMsg() + "], checkFailMsg: ["
                            + batch.getCheckFailMsg() + "]");
                }
                return null;
            }
        }
        // file??
        try {
            List<String> list = FileUtils.readLines(file, "UTF-8");
            // 
            for (Iterator<String> it = list.iterator(); it.hasNext();) {
                if (StringUtils.isBlank(it.next())) {
                    it.remove();
                }
            }

            List<ReconciliationEntityVo> sheetList = null;
            sheetList = parseSuccess(list, billDateStr, batch);
            return sheetList;
        } catch (IOException e) {
            LOG.error("??", e);
            return null;
        }

    }

    /**
     * ?
     * 
     * @param list
     * @param billDate
     *            ?
     * @param batch
     *            
     * @return
     */
    private List<ReconciliationEntityVo> parseSuccess(List<String> list, String billDate,
            RpAccountCheckBatch batch) {
        // ,?ID,?,??,?,??,??,,,?,,??,?,??,???,?,,
        // `2016-02-16
        // 20:30:28,`wx3798432a27e0c92a,`1263453701,`1308363301,`,`1000010956201602163321502558,`PAY2016021610017753,`ozSK7wgGhLpgZ09x_OjkKgz0Zeis,`MICROPAY,`SUCCESS,`CFT,`CNY,`32.50,`0.00,`erp
        // product,`,`0.20000,`0.60%
        // `2016-02-16
        // 18:42:38,`wx3798432a27e0c92a,`1263453701,`1308363301,`,`1000020956201602163316153533,`PAY2016021610017685,`ozSK7wswIt3nBfUxsJDp5hWZSm_8,`MICROPAY,`SUCCESS,`CFT,`CNY,`95.00,`0.00,`erp
        // product,`,`0.57000,`0.60%

        // ?,?,?,??,?
        // `383,`32903.45,`0.00,`0.00,`197.45000

        String title = ",?ID,?,??,?,??,??,,,?,,??,?,??,???,?,,";
        String totalTitle = "?,?,?,??,?";

        Pattern titlePattern = Pattern.compile(
                "(.*?),(.*?),(.*?),(.*?),(.*?),(.*?),(.*?),(.*?),(.*?),(.*?),(.*?),(.*?),(.*?),(.*?),(.*?),(.*?),(.*?),(.*?)$");
        Pattern pattern = Pattern.compile(
                "^`(.*?),`(.*?),`(.*?),`(.*?),`(.*?),`(.*?),`(.*?),`(.*?),`(.*?),`(.*?),`(.*?),`(.*?),`(.*?),`(.*?),`(.*?),`(.*?),`(.*?),`(.*?)$");

        Pattern totalTitlePattern = Pattern.compile("(.*?),(.*?),(.*?),(.*?),(.*?)$");
        Pattern totalPattern = Pattern.compile("^`(.*?),`(.*?),`(.*?),`(.*?),`(.*?)$");

        // 
        String titleRawData = list.remove(0);
        if (!titlePattern.matcher(titleRawData).find()) {
            batch.setStatus(BatchStatusEnum.FAIL.name());
            batch.setCheckFailMsg(
                    "?, rawdata[" + titleRawData + "], [" + title + "]");
            return null;
        }

        // ??
        String totalRawData = list.remove(list.size() - 1); // ???
        String totalTitleRawData = list.remove(list.size() - 1);
        if (!totalTitlePattern.matcher(totalTitleRawData).find()) {
            batch.setStatus(BatchStatusEnum.FAIL.name());
            batch.setCheckFailMsg("?, rawdata[" + totalTitleRawData + "], ["
                    + totalTitle + "]");
            return new ArrayList<ReconciliationEntityVo>();
        }
        Matcher totalMatcher = totalPattern.matcher(totalRawData);
        if (totalMatcher.find()) {
            // ?
            String totalCount = totalMatcher.group(1);
            // ?
            String totalAmountStr = totalMatcher.group(2);
            // ?
            String refundAmountStr = totalMatcher.group(3);
            // ?
            String feeAmountStr = totalMatcher.group(5);

            try {
                batch.setBankTradeCount(Integer.parseInt(totalCount));
                // ????
                batch.setBankTradeAmount(new BigDecimal(totalAmountStr));
                batch.setBankRefundAmount(new BigDecimal(refundAmountStr));
                batch.setBankFee(new BigDecimal(feeAmountStr));
            } catch (NumberFormatException e) {
                LOG.warn("?, billDate[" + billDate + "], billType[SUCCESS], rawdata["
                        + totalRawData + "]", e);
                batch.setStatus(BatchStatusEnum.FAIL.name());
                batch.setCheckFailMsg("?, rawdata[" + totalRawData + "]");
                // ??
                batch.setBankTradeCount(null);
                batch.setBankTradeAmount(null);
                batch.setBankRefundAmount(null);
                batch.setBankFee(null);
                return null;
            }
        } else {
            batch.setStatus(BatchStatusEnum.FAIL.name());
            batch.setCheckFailMsg("?, rawdata[" + totalRawData + "]");
            return new ArrayList<ReconciliationEntityVo>();
        }

        // ????list
        List<ReconciliationEntityVo> entityVoList = new ArrayList<ReconciliationEntityVo>();
        for (String rawData : list) {
            ReconciliationEntityVo entityVo = new ReconciliationEntityVo();
            entityVoList.add(entityVo);

            Matcher matcher = pattern.matcher(rawData);
            if (matcher.find()) {

                // 
                String tradeTimeStr = matcher.group(1);
                // ??(??)
                String bankTrxNo = matcher.group(6);
                // ??(???)
                String bankOrderNo = matcher.group(7);
                // ?
                String bankTradeStatus = matcher.group(10);
                // ?
                String orderAmount = matcher.group(13);
                // ??
                // String discountAmount = matcher.group(14);
                // 
                String bankFee = matcher.group(17);

                try {
                    // 
                    SimpleDateFormat sdf = new SimpleDateFormat(DATE_FORMAT_STYLE);
                    entityVo.setOrderTime(sdf.parse(tradeTimeStr));
                } catch (ParseException e) {
                    LOG.warn("?, billDate[" + billDate + "], billType[SUCCESS], tradeTime["
                            + tradeTimeStr + "], rawdata[" + rawData + "]", e);
                    batch.setStatus(BatchStatusEnum.FAIL.name());
                    batch.setCheckFailMsg(
                            "?, tradeTime[" + tradeTimeStr + "], rawdata[" + rawData + "]");
                    return null;
                }
                // ??
                entityVo.setBankTrxNo(bankTrxNo);
                // ???
                entityVo.setBankOrderNo(bankOrderNo);
                // ??success
                entityVo.setBankTradeStatus(bankTradeStatus);
                // ??:(??)
                entityVo.setBankAmount(new BigDecimal(orderAmount));
                // 
                entityVo.setBankFee(new BigDecimal(bankFee));
            } else {
                batch.setStatus(BatchStatusEnum.FAIL.name());
                batch.setCheckFailMsg("??, rawdata[" + rawData + "]");
                return null;
            }
        }

        return entityVoList;
    }

    /**
     * ?fail
     * 
     * @param file
     *            
     * @param batch
     *            
     */
    public void isError(File file, RpAccountCheckBatch batch) {
        // <xml><return_code><![CDATA[FAIL]]></return_code>
        // <return_msg><![CDATA[No Bill Exist]]></return_msg>
        // </xml>
        try {
            String content = FileUtils.readFileToString(file, "UTF-8");
            if (content.contains("<return_code>")) {

                Map<String, Object> map = XmlUtils.xmlToMap(content);
                String returnMsg = map.get("return_msg") != null ? map.get("return_msg").toString() : "";
                batch.setBankErrMsg(returnMsg);
                // ?
                // ????????batch
                if (returnMsg.contains("No Bill Exist")) {
                    batch.setStatus(BatchStatusEnum.NOBILL.name());
                } else {
                    batch.setStatus(BatchStatusEnum.ERROR.name());
                    rpAccountCheckBatchService.saveData(batch);
                }
            }
        } catch (JDOMException e) {
            LOG.error("??(?)", e);
        } catch (IOException e) {
            LOG.error("??(?)", e);
        }
    }

}