FFMInfo.java 20.1 KB
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551
package com.tianbo.analysis.model;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.Serializable;
import java.io.StringReader;
import java.text.ParseException;
import java.util.*;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import com.tianbo.analysis.exception.FFMResolveException;
import com.tianbo.util.Date.DateUtil;
import lombok.Data;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;

import javax.validation.constraints.NotNull;

/**
 * FFM_INFO
 * @author
 */
@Data
@Slf4j
public class FFMInfo implements Serializable {
    private String autoid;

    private Date createdate;

    private String flightno;

    private Date flightdate;

    private String waybillnomaster;

    private String originatingstation;

    private String destinationstation;

    private String manifesttotalpiece;

    private String manifesttotalweight;

    private String productname;

    private String specialgoodscode;

    private String customscode;

    private String customsstatus;

    private String isbatch;

    private String pallet;

    /**
     * 报文序号
     */
    private String reportorder;

    private String islast;

    private String originatingstationBill;

    private String destinationstationBill;

    private String totalpiece;

    private String dealstatus;

    //报文内容
    public String text;
    public List<String> lineList;
    public String order;
    public String planeNo;
    public int wayBillParseStartLine =0;
    private static final String TEXT_SIGN_LAST = "LAST";
    private static final String TEXT_SIGN_CONT= "CONT";
    private static final String KEY_WORD_3 = "FFM,ULD,OSI,COR,OCI,DEG,DIM";
    private static final String KEY_WORD_4 = "CONT,LAST";
    private static final long serialVersionUID = 1L;

    public FFMInfo(){

    }

    public FFMInfo(String autoid, Date createdate, String flightno, Date flightdate, String waybillnomaster, String originatingstation, String destinationstation, String manifesttotalpiece, String manifesttotalweight, String productname, String specialgoodscode, String customscode, String customsstatus, String isbatch, String pallet, String reportorder, String islast, String originatingstationBill, String destinationstationBill, String totalpiece, String dealstatus) {
        this.autoid = autoid;
        this.createdate = createdate;
        this.flightno = flightno;
        this.flightdate = flightdate;
        this.waybillnomaster = waybillnomaster;
        this.originatingstation = originatingstation;
        this.destinationstation = destinationstation;
        this.manifesttotalpiece = manifesttotalpiece;
        this.manifesttotalweight = manifesttotalweight;
        this.productname = productname;
        this.specialgoodscode = specialgoodscode;
        this.customscode = customscode;
        this.customsstatus = customsstatus;
        this.isbatch = isbatch;
        this.pallet = pallet;
        this.reportorder = reportorder;
        this.islast = islast;
        this.originatingstationBill = originatingstationBill;
        this.destinationstationBill = destinationstationBill;
        this.totalpiece = totalpiece;
        this.dealstatus = dealstatus;
    }


    @Override
    public String toString() {
        StringBuilder sb = new StringBuilder();
        sb.append(getClass().getSimpleName());
        sb.append(" [");
        sb.append("Hash = ").append(hashCode());
        sb.append(", autoid=").append(autoid);
        sb.append(", createdate=").append(createdate);
        sb.append(", flightno=").append(flightno);
        sb.append(", flightdate=").append(flightdate);
        sb.append(", waybillnomaster=").append(waybillnomaster);
        sb.append(", originatingstation=").append(originatingstation);
        sb.append(", destinationstation=").append(destinationstation);
        sb.append(", manifesttotalpiece=").append(manifesttotalpiece);
        sb.append(", manifesttotalweight=").append(manifesttotalweight);
        sb.append(", productname=").append(productname);
        sb.append(", specialgoodscode=").append(specialgoodscode);
        sb.append(", customscode=").append(customscode);
        sb.append(", customsstatus=").append(customsstatus);
        sb.append(", isbatch=").append(isbatch);
        sb.append(", pallet=").append(pallet);
        sb.append(", reportorder=").append(reportorder);
        sb.append(", islast=").append(islast);
        sb.append(", originatingstationBill=").append(originatingstationBill);
        sb.append(", destinationstationBill=").append(destinationstationBill);
        sb.append(", totalpiece=").append(totalpiece);
        sb.append(", dealstatus=").append(dealstatus);
        sb.append(", serialVersionUID=").append(serialVersionUID);
        sb.append("]");
        return sb.toString();
    }

    /**
     * 校验报文结尾标识
     * 将报文字符窜转换成行数组
     * @return
     * @throws IOException
     * @throws FFMResolveException
     */
    public boolean textToStringList() throws IOException,FFMResolveException {
            if (StringUtils.isNotBlank(text)) {
                /**
                 * 检查报文是否包含尾部标识
                 */
                lineList = new ArrayList<>();
                if (text.contains(TEXT_SIGN_CONT) || text.contains(TEXT_SIGN_LAST)) {
                    BufferedReader reader = new BufferedReader(new StringReader(text));
                    log.info(this.toString());
                    for (String lineStr = reader.readLine();
                         lineStr != null;
                         lineStr = reader.readLine()) {
                        //log.info("已读取行{}-{}",i,lineStr);
                        lineList.add(lineStr);
                    }
                    return true;
                } else {
                    throw new FFMResolveException("报文尾部缺少文件结束标识LAST或者CONT");
                }
            }

        return false;
    }

    /**
     * 寻找FFM/* 开头
     * 根据开头行号 并向下处理 航班信息行
     * 再向下处理航班目的站信息
     * @return
     * @throws FFMResolveException
     */
    public boolean resolveFFMPart() throws FFMResolveException, ParseException{
        int currentLine = 0;
        if (!lineList.isEmpty()){
            int keyword_i = 0;
            for (int i = 0; i < lineList.size(); i++) {
                //根据行关键字走相应的解析逻辑
                String line = lineList.get(i);
                log.debug("[TEXT] 开始处理行[{}]-[{}]",i,line);
                String keyword = keyword(line);
                if (!"NOT_KEYWORD".equals(keyword)){
                    log.debug("[TEXT] 行[{}]包含关键字,开始处理",i);
                    if ("FFM".equals(keyword)){
                        log.debug("[TEXT] 找到FFM开头节点");
                        currentLine = i;
                        //ffm版本
                        String ver = line.split("/")[1];
                        log.info("[TEXT] 报文版本{}",ver.trim());

                        //处理航班信息
                        log.debug("[TEXT] 向下行确定航班信息");
                        currentLine++;
                        flight(lineList.get(currentLine).trim());

                        /**
                         * 取第一目的站
                         * 这里注意,有的错误报文的航班节点后面没带或者忘了带目的站节点,
                         * 所以这里需要加个校验
                         */
                        currentLine++;
                        destination(lineList.get(currentLine).trim());
                        currentLine++;
                        wayBillParseStartLine = currentLine;
                    }else if ("CONT".equals(keyword) || "LAST".equals(keyword) ){
                        keyword_i++;
                    }

                }
            }
            if (keyword_i==0){
                throw new FFMResolveException("[TEXT] 报文尾部缺少文件结束标识LAST或者CONT");
            }
        }
        return false;
    }

    /**
     * 解析航班信息部分
     * @throws FFMResolveException
     * @throws ParseException
     */
    public void flight(String text) throws FFMResolveException, ParseException {
        log.debug("[FLIGHT] 开始处理航班信息");
        String[] flight = text.split("/");
        if (flight.length>3){
            order = flight[0];
            log.info("[FLIGHT] 报文序号为{}",order);
            flightno = flight[1];
            log.info("[FLIGHT] 航班号为[{}]",flightno);


            //航班日期取出来的格式为10SEP或者10SEP1022,带时间的注意
            String flightDateStr = flight[2];
            log.info("[FLIGHT] 航班日期信息为[{}]",flightDateStr);

            String flightDateDay = flightDateStr.substring(0,2);
            String flightDateMonth = flightDateStr.substring(2,5);


            /**
             * FFM跨年问题
             * FFM报文中的月份为12月,当前服务器时间月份为1月,视为跨年.
             * 跨年问题需要设置FFM报文的航班年份为当前年份-1
             */
            Calendar cal = Calendar.getInstance();
            //当前年份
            int yearNow = cal.get(Calendar.YEAR);
            int monthNow = cal.get(Calendar.MONTH);

            if (monthNow == 1 && "DEC".equals(flightDateMonth)){
                log.info("[FLIGHT] 航班日期跨年");
                yearNow = yearNow-1;
            }

            flightDateStr = flightDateStr+yearNow;
            flightdate = DateUtil.dateFormatFlight(flightDateStr);

            originatingstation = flight[3];
            log.info("[FLIGHT] 航班起始站为[{}]",originatingstation);
            if (flight.length>4){
                planeNo = flight[4];
                log.info("[FLIGHT] 航班飞机号为[{}]",planeNo);
            }
        }else {
            log.error("[FLIGHT] 航班信息节点不正确");
            throw new FFMResolveException("[FLIGHT] 航班信息节点不正确");
        }
    }
    /**
     * 解析航班第一目的站
     *
     */
    public void destination(String text) throws FFMResolveException{
        log.info("4.开始校验处理航班目的站节点信息 -> {}",text);
        if (text.length()>=3){
            //校验是否空货机
            String pattern_nil = "[A-Z]{3}/NIL";
            Pattern r_nil = Pattern.compile(pattern_nil);
            // 现在创建 matcher 对象
            Matcher m_nil = r_nil.matcher(text);
            if (m_nil.find()){
                log.info("4.1 航班目的站货物为空");
                throw new FFMResolveException("航班第一目的站货物为空,解析结束");
            }

            //校验是否是目的站节点
            //校验正则1,取前三位验证是否是机场代码
            String pattern = "^[A-Z]{3}$|^[A-Z]{3}/\\d{2}[A-Z]{3}\\d{4}";
            // 创建 Pattern 对象
            Pattern r = Pattern.compile(pattern);
            // 现在创建 matcher 对象
            Matcher m = r.matcher(text);
            if (m.find()){
                log.info("4.1 航班目的站节点校验通过");

                destinationstation = text.substring(0,3);
                log.info("4.2 航班目的站一为[{}]",destinationstation);
            }else {
                log.error("4.1[ERROR] !!航班目的站节点校验不通过!!");
                throw new FFMResolveException("航班目的站节点校验不通过.缺少航班目的站节点");
            }
        }else {
            throw new FFMResolveException("航班目的站节点长度不对.");
        }


    }

    /**
     * 判断是否有散舱
     * 有BUP散舱先处理散舱,没有则进入ULD及ULD货物解析阶段
     * 假设默认航班有散舱,将散舱的ULD号默认为 "BUP"
     * 设置当前的ULD 为 散舱ULD "BUP"
     * 那么散舱下的运单直到解析到真正的板箱号后,uld变成真正的货物板箱
     *
     */
    public List<FFMInfo> resolve_ULD_Waybill() throws FFMResolveException{
        log.info("[BILL] 开始解析舱单列表");
        String uld = "BUP";
        List<FFMInfo> ffmInfoList = new ArrayList<>();
        //默认非国际转运
        if (this.wayBillParseStartLine ==0){
            return ffmInfoList;
        }

        for (int i = this.wayBillParseStartLine; i < lineList.size(); i++) {
            wayBillParseStartLine++;
            String line = lineList.get(i);
            log.debug("[BILL] 开始解析行[{}]-[{}]",i,line);
            String customStatus = "-1";
            //行尾部结束标识检查
            String keyword = keyword(line);
            if ("CONT".equals(keyword) || "LAST".equals(keyword)){
                log.info("[END] 已解析到文件结束标识[{}],解析完毕",keyword);
                islast = keyword;
                break;
            }

            multiDestinationParse(line);

            if ("ULD".equals(keyword)){
                uld = ULDParse(line);
            }
            FFMInfo ffmInfoParsed = WayBillParse(line,uld);
            if (ffmInfoParsed!=null){
                ffmInfoList.add(ffmInfoParsed);
            }

            //todo:判断下一行是否/开头,是/头则为上面运单的特货操作代码
            //todo:判断下行是否为特殊字符"DIM,OSI,COR,OCI",是则作为上面运单的附加信息继续解析.
        }
        return ffmInfoList;

    }
    /**
     * 多航班目的站解析
     */
    private void multiDestinationParse(String line) throws FFMResolveException {

        //校验正则1,取前三位验证是否是机场代码
        String pattern_f = "^[A-Z]{3}$|^[A-Z]{3}/\\d{2}[A-Z]{3}\\d{4}";
        // 创建 Pattern 对象
        Pattern r_f = Pattern.compile(pattern_f);
        // 现在创建 matcher 对象
        Matcher mF = r_f.matcher(line);
        if (mF.find()){
            log.debug("5-[FLIGHT] 适配到航班其他目的站");
            String flightDes = line.substring(0,3);
            if (!KEY_WORD_3.contains(flightDes)){
                destinationstation = flightDes;
                log.info("5-[FLIGHT] 新航班目的站为[{}]",destinationstation);
            }
        }
        if (StringUtils.isEmpty(destinationstation)){
            throw new FFMResolveException("航班目的站节点校验不通过.");
        }
    }

    /**
     * 解析ULD板箱号部分
     * @param line
     * @return 解析成功返回板箱号
     */
    private String ULDParse(String line) throws FFMResolveException {

        log.debug("[ULD] 此行为ULD信息行");
        //板箱格式适配
        String patternULD = "^ULD/([A-Z]{3}\\S{4,5}\\S{2})";
        Pattern rULD = Pattern.compile(patternULD);
        // 现在创建 matcher 对象
        Matcher mULD = rULD.matcher(line);
        if (mULD.find()){
            log.debug("[ULD] ULD查到分组,数量{}",mULD.groupCount());
//                    for (int j1 = 1; j1 < mULD.groupCount()+1; j1++) {
//                        log.info("5-[ULD] 分组{}内容为:{}",j1,mULD.group(j1));
//                    }
            String uld= mULD.group(1);
            log.debug("[ULD] 当前ULD已变更为{}",uld);
            return uld;
        }else {
            throw new FFMResolveException(line+"的ULD节点格式错误,无法适配正则(^ULD/([A-Z]{3})(\\S{5})(\\S{2})");
        }


    }

    private FFMInfo WayBillParse(String line,String uld) throws FFMResolveException {
        //运单格式适配,这里注意空格字符 与连字符"-"
        String pattern = "^(\\d{3}-\\d{8})([A-Z]{3})([A-Z]{3})/(T|P|S|M)(\\d+)(K)([0-9\\.]+)(MC)?([0-9\\.]+)?(DG)?([0-9\\.]+)?(T)?([0-9]+)?/";
        // 创建 Pattern 对象
        Pattern r = Pattern.compile(pattern);
        // 现在创建 matcher 对象
        Matcher m = r.matcher(line);
        if(m.find()){
            log.debug("[AWB] 行[{}]属于运单行,开始解析,当前板箱号为:{}",line,uld);
            log.debug("[AWB] 查到分组,数量{}",m.groupCount());
            String waybillNo = m.group(1);
            String waybillOrigin =  m.group(2);
            String waybillDes =  m.group(3);
            String waybillSplit = m.group(4);
            String waybillPiece = m.group(5);
            String waybillWeight = m.group(7);
            String waybillVolume = m.group(9);
            String waybillDensity = m.group(11);
            String waybillTotalPiece = m.group(13);


            /**
             * 考虑到货物描述带空格及其他字符 用split获取
             */
            String waybillGoodsDes = line.split("/")[2];



//                for (int j = 1; j < m.groupCount()+1; j++) {
//                    log.info("5-[AWB] 分组{}内容为:{}",j,m.group(j));
//                }

            if(model7Check(waybillNo)){
                log.debug("[AWB] 运单-({})模七校验通过",waybillNo);
            }else {
                log.error("{}运单模七校验不通过",waybillNo);
                throw new FFMResolveException(waybillNo+"运单模七校验不通过");
            }
            log.debug("运单的下一行为{}",lineList.get(wayBillParseStartLine));

            log.info("[AWB-INFO] 运单信息:报文序号:{} 所属航班:{}/{} 航班起始站/目的站:{}/{} 所属板箱:{} 运单号:{} 起始站/目的站:{}/{} 分批标识:{} 分批件重:{}/{} 体积:{} 密度:{} 总件数:{} 货物描述:{}",
                    order,
                    flightno,
                    flightdate,
                    originatingstation,
                    destinationstation,
                    uld,
                    waybillNo,
                    waybillOrigin,
                    waybillDes,
                    waybillSplit,
                    waybillPiece,
                    waybillWeight,
                    waybillVolume,
                    waybillDensity,
                    waybillTotalPiece,
                    waybillGoodsDes);

            return new FFMInfo(
                    UUID.randomUUID().toString(),
                    new Date(),
                    flightno,
                    flightdate,
                    waybillNo,
                    originatingstation,
                    destinationstation,
                    waybillPiece,
                    waybillWeight,
                    waybillGoodsDes,
                    "",
                    "4604",
                    "-1",
                    waybillSplit,
                    uld,
                    order,
                    islast,
                    waybillOrigin,
                    waybillDes,
                    waybillTotalPiece,
                    "0");
        }
        return null;
    }
    /**
     * 关键字识别
     * @param text 每行的内容
     * @return 识别为关键字的返回关键字,未被识别为关键字的返回NOT_KEYWORD;
     * 返回的关键字 三字码关键字 机场代码关键字 文件结尾关键字 CONT,LAST
     */
    public String keyword(@NotNull String text){
        //取每行前三位
        if (StringUtils.isNotBlank(text) && text.length()>3){
            String s_3 =  text.substring(0,3);
            String s_4 =  text.substring(0,4);
            if(KEY_WORD_3.contains(s_3)){
                return s_3;
            }
            if(KEY_WORD_4.contains(s_4)){
                return s_4;
            }
        }else if(text.length()==3){
            log.info("[KEYWORD] {}很大可能是机场目的站",text);
        }

        return "NOT_KEYWORD";
    }
    /**
     * 模七校验
     * @param waybillNo
     * @return
     */
    public boolean model7Check(String waybillNo){
        String pattern = "\\d{3}-\\d{8}";
        // 创建 Pattern 对象
        Pattern r = Pattern.compile(pattern);
        // 现在创建 matcher 对象
        Matcher m = r.matcher(waybillNo);
        if (m.find()){
            String num = waybillNo.split("-")[1];
            String num_7 = num.substring(0,7);
            String num_end = num.substring(7,8);
            if (Integer.parseInt(num_7)% 7 == Integer.parseInt(num_end)){
                return true;
            }else {
                log.error("{}模七不通过",waybillNo);
            }

        }else {
            log.error("{}运单格式不正确",waybillNo);
        }

        return false;
    }
}