Commit 56def104 zshaohui

1.复试功能提交

2.增加接口异常交互功能
1 个父辈 1e2c16a0
正在显示 27 个修改的文件 包含 774 行增加384 行删除
package com.neotel.smfcore.core.apiInteraction.bean.query;
import com.neotel.smfcore.core.apiInteraction.enums.ApiInteraction_Status;
import lombok.Data;
import java.util.Date;
@Data
public class ApiInteractionQuery {
private Date requestDate;
//private String url;
//private String param;
//private String result;
private String status = ApiInteraction_Status.OK;
}
package com.neotel.smfcore.core.apiInteraction.controller;
import com.neotel.smfcore.common.bean.PageData;
import com.neotel.smfcore.common.utils.QueryHelp;
import com.neotel.smfcore.core.apiInteraction.bean.query.ApiInteractionQuery;
import com.neotel.smfcore.core.apiInteraction.service.manager.IApiInteractionManager;
import com.neotel.smfcore.security.annotation.AnonymousAccess;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Pageable;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
@Slf4j
@RequestMapping("/apiInteraction")
@RestController
public class ApiInteractionController {
@Autowired
private IApiInteractionManager apiInteractionManager;
@ApiOperation("接口情况记录查询")
@RequestMapping("/list")
@AnonymousAccess
public PageData list(ApiInteractionQuery query, Pageable pageable){
Query q = QueryHelp.getQuery(query);
return apiInteractionManager.findByPage(q,pageable);
}
}
package com.neotel.smfcore.core.apiInteraction.enums;
public class ApiInteraction_Status {
public static String OK = "ok";
public static String ERROE = "error";
}
package com.neotel.smfcore.core.apiInteraction.service.dao;
import com.neotel.smfcore.common.base.IBaseDao;
public interface IApiInteractionDao extends IBaseDao {
}
package com.neotel.smfcore.core.apiInteraction.service.dao.impl;
import com.neotel.smfcore.common.base.AbstractBaseDao;
import com.neotel.smfcore.core.apiInteraction.service.dao.IApiInteractionDao;
import com.neotel.smfcore.core.apiInteraction.service.po.ApiInteraction;
import org.springframework.stereotype.Service;
@Service
public class ApiInteractionDaoImpl extends AbstractBaseDao implements IApiInteractionDao {
@Override
public Class getEntityClass() {
return ApiInteraction.class;
}
}
package com.neotel.smfcore.core.apiInteraction.service.manager;
import com.neotel.smfcore.common.base.IBaseManager;
import com.neotel.smfcore.core.apiInteraction.service.po.ApiInteraction;
public interface IApiInteractionManager extends IBaseManager<ApiInteraction> {
}
package com.neotel.smfcore.core.apiInteraction.service.manager.impl;
import com.neotel.smfcore.common.base.AbstractBaseDao;
import com.neotel.smfcore.common.bean.PageData;
import com.neotel.smfcore.common.exception.ValidateException;
import com.neotel.smfcore.core.apiInteraction.service.dao.IApiInteractionDao;
import com.neotel.smfcore.core.apiInteraction.service.manager.IApiInteractionManager;
import com.neotel.smfcore.core.apiInteraction.service.po.ApiInteraction;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Pageable;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.stereotype.Service;
import java.util.List;
@Service
public class ApiInteractionManagerImpl extends AbstractBaseDao implements IApiInteractionManager {
@Autowired
private IApiInteractionDao apiInteractionDao;
@Override
public Class getEntityClass() {
return ApiInteraction.class;
}
@Override
public ApiInteraction get(String id) {
return apiInteractionDao.findOneById(id);
}
@Override
public ApiInteraction save(ApiInteraction object) throws ValidateException {
return apiInteractionDao.save(object);
}
@Override
public void delete(ApiInteraction object) throws ValidateException {
apiInteractionDao.removeOne(object);
}
@Override
public PageData<ApiInteraction> findByPage(Query query, Pageable pageable) {
int totalCount = apiInteractionDao.countByQuery(query);
List<ApiInteraction> list = apiInteractionDao.findByQuery(query, pageable);
return new PageData<>(list, totalCount);
}
}
package com.neotel.smfcore.core.apiInteraction.service.po;
import com.neotel.smfcore.common.base.BasePo;
import com.neotel.smfcore.core.apiInteraction.enums.ApiInteraction_Status;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
import java.io.Serializable;
import java.util.Date;
@Data
@AllArgsConstructor
@NoArgsConstructor
public class ApiInteraction extends BasePo implements Serializable {
private Date requestDate;
private String url;
private String param;
private String result;
private String status = ApiInteraction_Status.OK;
}
......@@ -9,15 +9,22 @@ import com.neotel.smfcore.common.utils.HttpHelper;
import com.neotel.smfcore.common.utils.StringUtils;
import com.neotel.smfcore.core.api.bean.CodeValidateParam;
import com.neotel.smfcore.core.api.listener.BaseSmfApiListener;
import com.neotel.smfcore.core.apiInteraction.enums.ApiInteraction_Status;
import com.neotel.smfcore.core.apiInteraction.service.manager.IApiInteractionManager;
import com.neotel.smfcore.core.apiInteraction.service.po.ApiInteraction;
import com.neotel.smfcore.core.barcode.service.po.Barcode;
import com.neotel.smfcore.core.device.util.DataCache;
import com.neotel.smfcore.core.system.service.po.DataLog;
import com.neotel.smfcore.custom.fuji.config.FileDirectoryConfig;
import com.neotel.smfcore.custom.fuji.bean.FujiConfig;
import com.neotel.smfcore.custom.fuji.config.FujiCacheConfig;
import com.neotel.smfcore.custom.fuji.config.FujiUrlConfig;
import com.neotel.smfcore.custom.fuji.util.NotifyUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.util.Arrays;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
......@@ -26,6 +33,12 @@ import java.util.Map;
@Slf4j
public class FujiApi extends BaseSmfApiListener {
@Autowired
private DataCache dataCache;
@Autowired
private IApiInteractionManager apiInteractionManager;
@Override
public boolean isForThisApi(String apiName) {
return apiName != null && apiName.equalsIgnoreCase("fuji");
......@@ -54,7 +67,7 @@ public class FujiApi extends BaseSmfApiListener {
@Override
public void inTaskStatusChange(String inNotifyUrl, DataLog task) {
if (task.isFinished()) {
NotifyUtil.createLoadEtn(task.getBarcode(),task.getPosName(),task.getNum(),"",task.getW(),task.getH(),task.getPartNumber(),task.getStorageName(),FileDirectoryConfig.NOTIFY);
NotifyUtil.createLoadEtn(task.getBarcode(),task.getPosName(),task.getNum(),"",task.getW(),task.getH(),task.getPartNumber(),task.getStorageName(),getNotifyEtn());
}
}
......@@ -62,7 +75,7 @@ public class FujiApi extends BaseSmfApiListener {
public void outTaskStatusChange(String outNotifyUrl, DataLog task) {
if (task.isFinished()) {
//NotifyUtil.createLoadEtn(task.getBarcode(),task.getPosName(),task.getNum(),"",task.getW(),task.getH(),task.getPartNumber(),task.getStorageName(),FileDirectoryConfig.NOTIFY);
NotifyUtil.createProvideEtn(task.getBarcode(),task.getPosName(),task.getNum(),"",task.getW(),task.getH(),task.getPartNumber(),task.getSourceName(),task.getLine(),task.getStorageName(),FileDirectoryConfig.NOTIFY);
NotifyUtil.createProvideEtn(task.getBarcode(),task.getPosName(),task.getNum(),"",task.getW(),task.getH(),task.getPartNumber(),task.getSourceName(),task.getLine(),task.getStorageName(),getNotifyEtn());
//NotifyUtil.createDeleteEtn(task.getBarcode(),task.getW(),task.getH(),task.getPartNumber(),FileDirectoryConfig.NOTIFY);
}
}
......@@ -74,11 +87,11 @@ public class FujiApi extends BaseSmfApiListener {
Map<String, Object> params = new HashMap<>();
params.put("did",barcode.getBarcode());
params.put("partBarcode",barcode.getBarcode());
params.put("partBarcode",barcode.getPartNumber());
params.put("quantity",barcode.getAmount());
params.put("packageType","paper"); //默认是paper,
params.put("partsoutWarning",0);
params.put("splicingWarning",0);
params.put("partsoutWarning",barcode.getAmount());
params.put("splicingWarning",barcode.getAmount());
params.put("partNumber",barcode.getPartNumber());
params.put("vendorName",barcode.getProvider());
params.put("lotName",barcode.getBatch());
......@@ -96,25 +109,27 @@ public class FujiApi extends BaseSmfApiListener {
params.put("trayPickupPositionY",1);
params.put("traySizeX",0);
params.put("traySizeY",0);
log.info("注册Fuji的did参数为:"+JSON.toJSONString(params));
String paramStr = JSON.toJSONString(params);
log.info("注册Fuji的did参数为:"+paramStr);
String result = "";
try {
String result = HttpHelper.postJsonWithAuth(FujiUrlConfig.inventoryDids(), Arrays.asList(params), "", headerMap);
result = HttpHelper.postJsonWithAuth(inventoryDids(), Arrays.asList(params), "", headerMap);
log.info("注册Fuji的did结果为:"+result);
JSONObject resultObj = JSONObject.parseObject(result);
Integer addedCount = resultObj.getInteger("addedCount");
if (addedCount != null && addedCount > 0){
apiInteractionManager.save(new ApiInteraction(new Date(),getAuthLogin(),paramStr,result,ApiInteraction_Status.OK));
return true;
} else {
String details = resultObj.getString("details");
apiInteractionManager.save(new ApiInteraction(new Date(),getAuthLogin(),paramStr,result,ApiInteraction_Status.ERROE));
throw new ValidateException("smfcore.registerdid.false",barcode.getBarcode()+"注册失败:"+details);
}
} catch (ApiException e) {
log.info("注册Fuji的did失败:",e);
}
apiInteractionManager.save(new ApiInteraction(new Date(),getAuthLogin(),paramStr,result,ApiInteraction_Status.ERROE));
return false;
}
......@@ -134,8 +149,10 @@ public class FujiApi extends BaseSmfApiListener {
paramMap.put("search", search);
paramMap.put("orderBy", orderBy);
String paramStr = JSON.toJSONString(paramMap);
String result = "";
try {
String result = HttpHelper.getParam(FujiUrlConfig.inventoryDids(), headerMap, paramMap);
result = HttpHelper.getParam(getInventoryDids(), headerMap, paramMap);
log.info(barcode + "获取Fuji的inventory/dids结果为:" + result);
JSONObject resultObj = JSONObject.parseObject(result);
JSONArray dataArray = resultObj.getJSONArray("datas");
......@@ -143,6 +160,7 @@ public class FujiApi extends BaseSmfApiListener {
for (int i = 0; i < dataArray.size(); i++) {
JSONObject data = dataArray.getJSONObject(i);
if (barcode.equals(data.getString("did"))){
apiInteractionManager.save(new ApiInteraction(new Date(),getAuthLogin(),paramStr,result,ApiInteraction_Status.OK));
return true;
}
}
......@@ -150,6 +168,7 @@ public class FujiApi extends BaseSmfApiListener {
} catch (ApiException e) {
log.info(barcode + "获取Fuji的inventory/dids失败:", e.getMessage());
}
apiInteractionManager.save(new ApiInteraction(new Date(),getAuthLogin(),paramStr,result,ApiInteraction_Status.ERROE));
return false;
}
......@@ -158,14 +177,16 @@ public class FujiApi extends BaseSmfApiListener {
* 获取登录的token
* @return
*/
private String getAccessToken() {
public String getAccessToken() {
Map<String, Object> paramMap = new HashMap<>();
paramMap.put("userName", FujiUrlConfig.userName);
paramMap.put("password", FujiUrlConfig.password);
log.info("获取Fuji的token参数为:" + JSON.toJSONString(paramMap));
String paramStr = JSON.toJSONString(paramMap);
log.info("获取Fuji的token参数为:" + paramStr);
String accessToken = "";
String result = "";
try {
String result = HttpHelper.postJson(FujiUrlConfig.getAuthLogin(), paramMap);
result = HttpHelper.postJson(getAuthLogin(), paramMap);
log.info("获取Fuji的token结果为:" + result);
JSONObject resultObj = JSONObject.parseObject(result);
accessToken = resultObj.getString("accessToken");
......@@ -173,11 +194,49 @@ public class FujiApi extends BaseSmfApiListener {
log.info("获取Fuji的token异常:", e);
accessToken = "";
}
String status = "";
if (StringUtils.isEmpty(accessToken)){
status = ApiInteraction_Status.ERROE;
}
apiInteractionManager.save(new ApiInteraction(new Date(),getAuthLogin(),paramStr,result,status));
if (StringUtils.isEmpty(accessToken)) {
throw new ValidateException("smfcore.accessToken.ng", "获取AccessToken失败");
}
return accessToken;
}
private String getAuthLogin(){
FujiConfig config = dataCache.getCache(FujiCacheConfig.FujiConfig_Cache_Name);
if (config == null) {
config = new FujiConfig();
}
return config.getAuthUrl();
}
private String getInventoryDids(){
FujiConfig config = dataCache.getCache(FujiCacheConfig.FujiConfig_Cache_Name);
if (config == null) {
config = new FujiConfig();
}
return config.getGetDidInfoUrl();
}
private String inventoryDids(){
FujiConfig config = dataCache.getCache(FujiCacheConfig.FujiConfig_Cache_Name);
if (config == null) {
config = new FujiConfig();
}
return config.getRegisterDidInfoUrl();
}
private String getNotifyEtn(){
FujiConfig config = dataCache.getCache(FujiCacheConfig.FujiConfig_Cache_Name);
if (config == null) {
config = new FujiConfig();
}
return config.getOutputEtn();
}
}
package com.neotel.smfcore.custom.fuji.bean;
import lombok.Data;
import java.util.Date;
@Data
public class FujiConfig {
private String authUrl = "";
private String getDidInfoUrl = "";
private String registerDidInfoUrl = "";
private String result = "";
private String lastUpdateTime = "";
private String inputEto = "";
private String outputEtn = "";
private int time = 10;
}
package com.neotel.smfcore.custom.fuji.bean;
import lombok.Data;
import java.io.Serializable;
@Data
public class Notify implements Serializable {
/**
* action NEW = Object (item or carrier) creation
* DELETE = Object (item or carrier) deletion
* LOAD = Carrier check in
* PROVIDE = Carrier check out
*/
private String action;
/**
* object ARTICLE or CARRIER
*/
private String object;
/**
* objectname Item or carrier name(DID)
*/
private String name;
/**
* Date of Action、yyyymmdd format
*/
private String date;
/**
* Action Time
*/
private String time;
/**
* Job name
*/
private String jobName;
/**
* storage location (Only if object=CARRIER)
*/
private String depot;
/**
* Item designation (Only if object=CARRIER)
*/
private String demand;
/**
* Current carrier's parts inventory or total inventory of the item
*/
private int stock;
}
\ No newline at end of file
package com.neotel.smfcore.custom.fuji.bean;
import lombok.Data;
@Data
public class OrderReq {
private String action;
private String object;
private String name;
private String date;
private String time;
private String depot;
private String stock;
private String expiry;
private String mSL;
private String mSLWATCH;
private String stockMin;
private String stockMax;
private String reelsMin;
private String reelsMax;
private String height;
private String diameter;
private String supply;
private String stockNew;
private String article;
private String units;
private String target;
private String forceTower;
private String demand;
private String los;
}
package com.neotel.smfcore.custom.fuji.bean;
import lombok.Data;
import java.util.ArrayList;
import java.util.List;
@Data
public class OrderResp extends OrderReq {
private String answer = "TRUE";
private int error;
private String carrier;
private String values;
private List<String> carrierNameList;
public void setCarrierNameList(String carrierName) {
if (carrierNameList == null || carrierNameList.isEmpty()){
carrierNameList = new ArrayList<>();
}
this.carrierNameList.add(carrierName);
}
}
package com.neotel.smfcore.custom.fuji.config;
public class FileDirectoryConfig {
public static final String NOTIFY = "D:\\Remoteorder\\notify\\";
public class FujiCacheConfig {
public static final String FujiConfig_Cache_Name = "FujiConfig_Cache_Name";
}
......@@ -5,23 +5,14 @@ import lombok.Data;
@Data
public class FujiUrlConfig {
private static final String baseUrl = "http://175.41.238.212/fujiopenwebapi/api/v1";
//private static final String baseUrl = "http://175.41.238.212/fujiopenwebapi/api/v1";
public static final String userName = "Neotel";
public static final String password = "Neotel";
private static final String authLogin = "/auth/login";
//private static final String authLogin = "/auth/login";
private static final String inventoryDids = "/inventory/dids";
public static String getAuthLogin() {
return baseUrl + authLogin;
}
public static String inventoryDids() {
return baseUrl + inventoryDids;
}
//private static final String inventoryDids = "/inventory/dids";
}
package com.neotel.smfcore.custom.fuji.controller;
import com.alibaba.fastjson.JSON;
import com.neotel.smfcore.common.bean.ResultBean;
import com.neotel.smfcore.common.utils.StringUtils;
import com.neotel.smfcore.core.barcode.service.po.Barcode;
import com.neotel.smfcore.core.barcode.utils.CodeResolve;
import com.neotel.smfcore.core.device.util.DataCache;
import com.neotel.smfcore.custom.fuji.FujiApi;
import com.neotel.smfcore.custom.fuji.bean.FujiConfig;
import com.neotel.smfcore.custom.fuji.config.FujiCacheConfig;
import com.neotel.smfcore.security.annotation.AnonymousAccess;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import java.util.Map;
@Slf4j
@RestController
@RequestMapping("/fuji")
public class FujiController {
@Autowired
private DataCache dataCache;
@Autowired
private CodeResolve codeResolve;
@Autowired
private FujiApi fujiApi;
@ApiOperation("修改配置")
@RequestMapping("/updateFujiConfig")
@AnonymousAccess
public ResultBean updateFujiConfig(@RequestBody FujiConfig newConfig) {
log.info("修改配置信息为:" + JSON.toJSONString(newConfig));
FujiConfig config = dataCache.getCache(FujiCacheConfig.FujiConfig_Cache_Name);
if (config == null) {
config = new FujiConfig();
}
config.setAuthUrl(newConfig.getAuthUrl());
config.setGetDidInfoUrl(newConfig.getGetDidInfoUrl());
config.setRegisterDidInfoUrl(newConfig.getRegisterDidInfoUrl());
config.setInputEto(newConfig.getInputEto());
config.setOutputEtn(newConfig.getOutputEtn());
config.setTime(newConfig.getTime());
dataCache.updateCache(FujiCacheConfig.FujiConfig_Cache_Name, config);
return ResultBean.newOkResult("");
}
@ApiOperation("获取配置")
@RequestMapping("/getFujiConfig")
@AnonymousAccess
public ResultBean getFujiConfig() {
FujiConfig config = dataCache.getCache(FujiCacheConfig.FujiConfig_Cache_Name);
if (config == null) {
config = new FujiConfig();
}
return ResultBean.newOkResult(config);
}
@ApiOperation("did注册")
@RequestMapping("/didRegister")
@AnonymousAccess
public ResultBean didRegister(@RequestBody Map<String, String> paramMap) {
String code = paramMap.get("code");
if (StringUtils.isEmpty(code)) {
return ResultBean.newErrorResult(-1, "smfcore.valueCanotNull", "{0}不能为空", new String[]{"code"});
}
Barcode barcode = codeResolve.resolveCode(code);
if (barcode == null) {
return ResultBean.newErrorResult(-1, "smfcore.error.barcode.invalid", "{0}不是有效的条码", new String[]{code});
}
String accessToken = fujiApi.getAccessToken();
boolean hasDid = fujiApi.inventoryHasDid(barcode.getBarcode(), accessToken);
if (!hasDid){
fujiApi.registerNewDid(barcode, accessToken);
}
return ResultBean.newOkResult("");
}
}
package com.neotel.smfcore.custom.fuji.enums;
/**
* Action 类型
*/
public enum Action {
/**
* Object (item or carrier) creation
*/
NEW,
/**
* Object (item or carrier) deletion
*/
DELETE,
/**
* Carrier check in
*/
LOAD,
/**
* Carrier check out
*/
PROVIDE,
/**
* 修改
*/
UPDATE,
/**
* 读取
*/
READ
}
package com.neotel.smfcore.custom.fuji.enums;
public class ErrorCode {
public static final int ok = 0;
public static final int lockingError = 1;
public static final int unknownAction = 9;
}
package com.neotel.smfcore.custom.fuji.enums;
public enum NexObject {
/**
* 料号
*/
ARTICLE,
/**
* 唯一码
*/
CARRIER,
/**
* 工单
*/
JOBLIST
}
package com.neotel.smfcore.custom.fuji.enums;
public class OrderType {
public static final String order = "[Order]";
public static final String result = "[Result]";
public static final String data = "[Data]";
}
package com.neotel.smfcore.custom.fuji.order;
import cn.hutool.core.io.FileUtil;
import com.alibaba.fastjson.JSON;
import com.neotel.smfcore.common.utils.DateUtil;
import com.neotel.smfcore.common.utils.StringUtils;
import com.neotel.smfcore.core.api.SmfApi;
import com.neotel.smfcore.core.device.util.DataCache;
import com.neotel.smfcore.core.order.LiteOrderCache;
import com.neotel.smfcore.core.order.service.manager.ILiteOrderManager;
import com.neotel.smfcore.core.order.service.po.LiteOrder;
import com.neotel.smfcore.core.order.service.po.LiteOrderItem;
import com.neotel.smfcore.core.system.service.po.DataLog;
import com.neotel.smfcore.core.system.util.TaskService;
import com.neotel.smfcore.custom.fuji.bean.FujiConfig;
import com.neotel.smfcore.custom.fuji.config.FujiCacheConfig;
import com.neotel.smfcore.custom.fuji.order.bean.Job;
import com.neotel.smfcore.custom.fuji.order.bean.JobItem;
import com.neotel.smfcore.custom.fuji.order.service.JobService;
import com.neotel.smfcore.custom.fuji.util.NotifyUtil;
import com.neotel.smfcore.custom.fuji.util.OrderUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import javax.annotation.PostConstruct;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.nio.file.StandardCopyOption;
import java.util.*;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;
@Slf4j
@Component
public class JobHandler {
@Autowired
private SmfApi smfApi;
@Autowired
private JobService jobService;
@Autowired
private TaskService taskService;
@Autowired
private DataCache dataCache;
ScheduledExecutorService scheduledThreadPool = Executors.newScheduledThreadPool(1);
private static long lastHandleTime = 0l;
@PostConstruct
public void init() {
if ("fuji".equals(smfApi.getApiName())) {
scheduledThreadPool.scheduleAtFixedRate(() -> {
FujiConfig config = dataCache.getCache(FujiCacheConfig.FujiConfig_Cache_Name);
if (config == null) {
config = new FujiConfig();
}
if (System.currentTimeMillis()-lastHandleTime >= 1000 * config.getTime()){
log.info(DateUtil.toDateString(System.currentTimeMillis(),"yyyy-MM-dd HH:mm:ss"));
try {
handler();
} catch (Exception e) {
log.info("执行fuji工单失败:", e);
}
lastHandleTime = System.currentTimeMillis();
}
}, 10, 1, TimeUnit.SECONDS);
}
}
public static void main(String[] args) throws IOException {
new JobHandler().handler();
}
public void handler() throws IOException {
FujiConfig config = dataCache.getCache(FujiCacheConfig.FujiConfig_Cache_Name);
if (config == null) {
config = new FujiConfig();
}
String path = config.getInputEto();
if (StringUtils.isEmpty(path)){
return;
}
log.info("开始执行工单,路径为:" + path);
File file = new File(path);
if (file.exists() && file.isDirectory()) {
//获取到最近的一个文件
File[] files = file.listFiles();
if (files == null || files.length == 0){
return;
}
List<File> fileList = Arrays.stream(files).sorted(Comparator.comparing(File::lastModified).reversed()).collect(Collectors.toList());
File currentFile = fileList.get(0);
String name = currentFile.getName();
if (!name.endsWith("ETO")) {
return;
}
//解析出来每行数据
List<String> lineList = OrderUtil.getLines(currentFile.getAbsolutePath(), StandardCharsets.US_ASCII);
log.info("获取到line为:" + JSON.toJSONString(lineList));
//开始处理每行数据
Job job = getJob(lineList);
//判断是否已经存在job
/* boolean existJob = jobService.isExistJob(job.getName());
if (existJob){
return;
}*/
job = jobService.getJobResultInfo(job);
//旧的文件,移除到其他文件夹,写入ANS文件
String newFilePath = "nexim/eto/"+currentFile.getName();
FileUtil.move(currentFile,new File(newFilePath),true);
//新写入文件到当前文件夹
List<JobItem> data = job.getData();
int error = 0;
for (JobItem item : data) {
if (error == 1){
continue;
} else {
if (item.getErrorCode() == 1902 || item.getErrorCode() == 1928){
error = 2;
} else if (item.getErrorCode() == 1876 || item.getErrorCode() == 1877 || item.getErrorCode() == 1878 || item.getErrorCode() == 1886 || item.getErrorCode() == 1901){
error = 1;
}
}
}
lineList.add("[Result]");
lineList.add("Error="+error);
for (JobItem item : data) {
if (item.getErrorCode() != 0){
lineList.add(item.getItem()+"="+item.getErrorCode()+":"+item.getErrorText());
}
}
//写入文件到当前文件夹
String ansName = currentFile.getName();
int pos = ansName.lastIndexOf(".");
ansName = pos > 0 ? ansName.substring(0,pos) :ansName;
String ansFilePath = path+"\\"+ansName+".ANS";
try (BufferedWriter writer = new BufferedWriter(new FileWriter(ansFilePath))) {
for (String line : lineList) {
// 逐行写入 List 中的内容
writer.write(line);
writer.newLine(); // 写入换行符以分隔每一行
}
} catch (IOException e) {
// 处理可能发生的 IO 异常
log.info("写入文件时发生错误: ",e);
}
//生成出库任务
List<DataLog> dataLogList = job.getDataLogList();
if (dataLogList != null && !dataLogList.isEmpty()){
for (DataLog dataLog : dataLogList) {
taskService.updateQueueTask(dataLog);
}
}
}
}
private Job getJob(List<String> lineList) {
Job job = new Job();
for (String line : lineList) {
String[] lineSpl = line.split("=");
if (line.startsWith("Action")) {
job.setAction(lineSpl[1]);
} else if (line.startsWith("Object")) {
job.setObject(lineSpl[1]);
} else if (line.startsWith("Name")) {
job.setName(lineSpl[1]);
} else if (line.startsWith("Los")) {
job.setLos(lineSpl[1]);
} else if (line.startsWith("JobState")) {
job.setJobState(lineSpl[1]);
} else if (line.startsWith("ProdSite")) {
job.setProdSite(lineSpl[1]);
} else if (line.startsWith("Answer")) {
job.setAnswer(lineSpl[1]);
}
}
List<JobItem> itemList = new ArrayList<>();
for (String line : lineList) {
if (line.startsWith("Item")) {
String[] lineSpl = line.split("=");
JobItem item = new JobItem();
item.setItem(lineSpl[0]);
String[] split = lineSpl[1].split("\\|");
item.setPart(split[0]);
item.setCarrier(split[1]);
if (StringUtils.isNotEmpty(split[2])) {
item.setNeedNum(Integer.valueOf(split[2]));
}
if (StringUtils.isNotEmpty(split[3])) {
item.setNeedReelCount(Integer.valueOf(split[3]));
}
itemList.add(item);
}
}
job.setData(itemList);
return job;
}
}
package com.neotel.smfcore.custom.fuji.order;
import com.alibaba.fastjson.JSON;
import com.neotel.smfcore.core.api.SmfApi;
import com.neotel.smfcore.core.device.util.DataCache;
import com.neotel.smfcore.core.order.LiteOrderCache;
import com.neotel.smfcore.core.order.service.manager.ILiteOrderManager;
import com.neotel.smfcore.core.order.service.po.LiteOrder;
import com.neotel.smfcore.core.order.service.po.LiteOrderItem;
import com.neotel.smfcore.custom.fuji.util.NotifyUtil;
import com.neotel.smfcore.custom.fuji.util.OrderUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import javax.annotation.PostConstruct;
import java.io.File;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.util.*;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;
@Slf4j
@Component
public class OrderHandler {
private static DataCache dataCache;
@Autowired
public void setDataCache(DataCache cache) {
dataCache = cache;
}
private static ILiteOrderManager liteOrderManager;
@Autowired
public void setLiteOrderManager(ILiteOrderManager manager) {
liteOrderManager = manager;
}
private static LiteOrderCache liteOrderCache;
@Autowired
public void setLiteOrderCache(LiteOrderCache cache) {
liteOrderCache = cache;
}
public static SmfApi smfApi;
@Autowired
public void setSmfApi(SmfApi api) {
smfApi = api;
}
ScheduledExecutorService scheduledThreadPool = Executors.newScheduledThreadPool(1);
@PostConstruct
public void init() {
if ("fuji".equals(smfApi.getApiName())){
scheduledThreadPool.scheduleAtFixedRate(() -> {
try {
handler();
} catch (Exception e) {
log.info("执行fuji工单失败:",e);
}
},10, 10, TimeUnit.SECONDS);
}
}
public static void handler() throws IOException {
String path = dataCache.getOrderSetting().getOrderDir();
log.info("开始执行工单,路径为:" + path);
File file = new File(path);
if (file.exists() && file.isDirectory()) {
String resultStr = "";
File[] files = file.listFiles();
List<File> fileList = Arrays.stream(files).sorted(Comparator.comparing(File::lastModified).reversed()).collect(Collectors.toList());
File currentFile = fileList.get(0);
List<String> lineList = OrderUtil.getLines(currentFile.getAbsolutePath(), StandardCharsets.US_ASCII);
log.info("获取到line为:" + JSON.toJSONString(lineList));
String orderName = "";
String orderLine = "";
List<LiteOrderItem> orderItemList = new ArrayList<>();
for (String line : lineList) {
resultStr = resultStr + line;
if (line.split("=").length < 2) {
continue;
}
String value = line.split("=")[1];
if (line.startsWith("Name")) {
orderName = value;
}
if (line.startsWith("ProdSite")){
orderLine = value;
}
if (line.startsWith("Item")) {
String[] itemStr = value.split("\\|", -1);
LiteOrderItem item = new LiteOrderItem();
item.setPn(itemStr[0]);
item.setRi(itemStr[1]);
int needNum = 1;
try {
needNum = Integer.valueOf(itemStr[2]);
} catch (NumberFormatException e) {
e.printStackTrace();
}
item.setNeedNum(needNum);
int needReelCount = 1;
try {
needReelCount = Integer.valueOf(itemStr[3]);
} catch (NumberFormatException e) {
e.printStackTrace();
}
item.setNeedReelCount(needReelCount);
orderItemList.add(item);
}
}
int error = 0;
LiteOrder liteOrder = liteOrderManager.findByOrderNo(orderName);
if (liteOrder == null) {
LiteOrder order = new LiteOrder();
order.setOrderItems(orderItemList);
order.setOrderNo(orderName);
order.setLine(orderLine);
liteOrderManager.createWithItems(order);
liteOrderCache.addOrderToMap(order);
} else {
return;
}
resultStr = resultStr + "\n";
resultStr = resultStr +"[Result]";
resultStr = resultStr + "\n";
resultStr = resultStr + "Error="+error;
NotifyUtil.createOrderAns(file.getName(),resultStr);
}
}
}
package com.neotel.smfcore.custom.fuji.order.bean;
import com.neotel.smfcore.core.system.service.po.DataLog;
import lombok.Data;
import java.util.List;
@Data
public class Job {
private String Action;
private String Object;
private String Name;
private String Los;
private String JobState;
private String ProdSite;
private String Answer;
private int Error = 0;
private List<JobItem> Data;
private List<DataLog> dataLogList;
}
package com.neotel.smfcore.custom.fuji.order.bean;
import lombok.Data;
@Data
public class JobItem {
private String item;
private String part;
private String carrier;
private int needNum;
private int needReelCount;
private int errorCode;
private String errorText;
}
package com.neotel.smfcore.custom.fuji.order.service;
import com.neotel.smfcore.common.utils.StringUtils;
import com.neotel.smfcore.core.barcode.service.po.Barcode;
import com.neotel.smfcore.core.device.enums.OP;
import com.neotel.smfcore.core.device.util.DataCache;
import com.neotel.smfcore.core.order.LiteOrderCache;
import com.neotel.smfcore.core.order.service.manager.ILiteOrderManager;
import com.neotel.smfcore.core.order.service.po.LiteOrder;
import com.neotel.smfcore.core.order.service.po.LiteOrderItem;
import com.neotel.smfcore.core.storage.enums.CHECKOUT_TYPE;
import com.neotel.smfcore.core.storage.service.manager.IStoragePosManager;
import com.neotel.smfcore.core.storage.service.po.Storage;
import com.neotel.smfcore.core.storage.service.po.StoragePos;
import com.neotel.smfcore.core.system.service.po.DataLog;
import com.neotel.smfcore.core.system.util.TaskService;
import com.neotel.smfcore.custom.fuji.order.bean.Job;
import com.neotel.smfcore.custom.fuji.order.bean.JobItem;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
@Slf4j
@Service
public class JobService {
@Autowired
private LiteOrderCache liteOrderCache;
@Autowired
private ILiteOrderManager liteOrderManager;
@Autowired
private IStoragePosManager storagePosManager;
@Autowired
private TaskService taskService;
@Autowired
private DataCache dataCache;
public boolean isExistJob(String jobName) {
LiteOrder liteOrder = liteOrderCache.getLiteOrder(jobName);
if (liteOrder != null){
return true;
}
return false;
}
public Job getJobResultInfo(Job job) {
String name = job.getName();
String prodSite = job.getProdSite();
List<JobItem> jobItemList = job.getData();
List<DataLog> dataLogList = new ArrayList<>();
for (JobItem jobItem : jobItemList) {
String carrier = jobItem.getCarrier();
String part = jobItem.getPart();
int needNum = jobItem.getNeedNum();
int needReelCount = jobItem.getNeedReelCount();
if (StringUtils.isNotEmpty(carrier)) {
StoragePos pos = storagePosManager.getByBarcode(carrier);
if (pos != null) {
Barcode barcode = pos.getBarcode();
DataLog dataLog = null;
List<DataLog> allTasks = taskService.getAllTasks();
for (DataLog task : allTasks) {
if (task.getBarcode().equals(barcode.getBarcode())) {
if (!task.isCancel() && !task.isFinished()) {
dataLog = task;
break;
}
}
}
if (dataLog == null) {
Storage storage = dataCache.getStorageById(pos.getStorageId());
DataLog task = new DataLog(storage, barcode, pos);
//task.setSubSourceId(item.getId());
task.setSourceName(name);
//task.setSourceId(order.getId());
task.setType(OP.CHECKOUT);
dataLogList.add(task);
} else {
jobItem.setErrorCode(1886);
jobItem.setErrorText("The carrier is locked");
}
} else {
jobItem.setErrorCode(1878);
jobItem.setErrorText("Insufficient stock quantity");
}
} else if (StringUtils.isNotEmpty(part)) {
int totalOutReelCount = 0;
//int totalOutNum = 0;
List<String> availableStorageIds = new ArrayList<>();
for (Storage storage : dataCache.getAllStorage().values()) {
availableStorageIds.add(storage.getId());
}
CHECKOUT_TYPE checkoutType = dataCache.getCheckOutType();
while (totalOutReelCount < needReelCount /*|| needNum < totalOutNum*/){
Collection<String> excludePosIds = liteOrderCache.excludeOutPosIds();
if (dataLogList != null && !dataLogList.isEmpty()){
for (DataLog dataLog : dataLogList) {
excludePosIds.add(dataLog.getPosId());
}
}
StoragePos pos = storagePosManager.findPartNumberInStorages(availableStorageIds, "", part, excludePosIds, checkoutType);
if (pos == null){
break;
}
Storage storage = dataCache.getStorageById(pos.getStorageId());
Barcode barcode = pos.getBarcode();
DataLog task = new DataLog(storage, barcode, pos);
task.setSourceName(name);
//task.setSourceId(order.getId());
task.setType(OP.CHECKOUT);
dataLogList.add(task);
totalOutReelCount = totalOutReelCount + 1;
//totalOutNum = totalOutNum + barcode.getAmount();
}
if (totalOutReelCount == 0){
jobItem.setErrorCode(1878);
jobItem.setErrorText("Insufficient stock quantity");
} else {
/*if (totalOutNum > needNum){
jobItem.setErrorCode(1928);
jobItem.setErrorText("A different reel quantity from that of the demand requests multiple reels");
}*/
/*if (totalOutReelCount > needReelCount){
jobItem.setErrorCode(1902);
jobItem.setErrorText("One reel is requested but the demand requests multiple reels");
}*/
if (/*totalOutNum < needNum || */totalOutReelCount < needReelCount){
jobItem.setErrorCode(1878);
jobItem.setErrorText("Insufficient stock quantity");
}
}
}
}
job.setDataLogList(dataLogList);
return job;
}
}
package com.neotel.smfcore.custom.fuji.util;
import com.neotel.smfcore.common.utils.StringUtils;
import lombok.extern.slf4j.Slf4j;
import java.io.File;
......@@ -46,7 +47,8 @@ public class NotifyUtil {
"Name=" + barcode + "\n" +
"Date=" + new SimpleDateFormat("yyyyMMdd").format(new Date()) + "\n" +
"Time=" + new SimpleDateFormat("HH:mm:ss").format(new Date()) + "\n" +
"Depot=" + posName + "\n" +
"JOBNAME=\n" +
"Depot=" + storageName + "\n" +
"Stock=" + num + "\n" +
"Station=" + station + "\n" +
"EXPIRY=\n" +
......@@ -56,8 +58,8 @@ public class NotifyUtil {
"SUPPLY=\n" +
"STOCKNEW=0\n" +
"ARTICLE=" + partNumber + "\n" +
"DEPOTLONG="+storageName+" " + posName + "\n" +
"DEPOTOLD=Unknown\n" +
"DEPOTLONG=\n" +
"DEPOTOLD=\n" +
"custom1=\n" +
"custom2=\n" +
"custom3=\n" +
......@@ -95,7 +97,7 @@ public class NotifyUtil {
try {
//CARRIER_1608R-00002_LOAD_20240524_15_00_02.ETN
//localFilePath = path + "CARRIER_" + barcode + "_PROVIDE_" + new SimpleDateFormat("yyyyMMdd_HH_mm_ss").format(new Date()) + ".ETN";
localFilePath = path +barcode+"_PROVIDE"+".ETN";
localFilePath = path +"\\"+barcode+"_PROVIDE"+".ETN";
log.info("本地文件路径为:" + localFilePath);
//log.info("内容为:" + JSON.toJSONString(notify));
......@@ -105,6 +107,10 @@ public class NotifyUtil {
file.createNewFile();
}
if (StringUtils.isEmpty(sourceName)){
sourceName = "";
}
out = new OutputStreamWriter(new FileOutputStream(file), CHARSET_NAME); //打开文件输出流
out.write("[Notify]\n" +
"Action=PROVIDE\n" +
......@@ -113,7 +119,7 @@ public class NotifyUtil {
"Date=" + new SimpleDateFormat("yyyyMMdd").format(new Date()) + "\n" +
"Time=" + new SimpleDateFormat("HH:mm:ss").format(new Date()) + "\n" +
"JOBNAME=" + sourceName + "\n" +
"Depot=" + line + "\n" +
"Depot=" + storageName + "\n" +
"Stock=" + num + "\n" +
"Station=" + station + "\n" +
"EXPIRY=\n" +
......@@ -123,8 +129,8 @@ public class NotifyUtil {
"SUPPLY=\n" +
"STOCKNEW=0\n" +
"ARTICLE=" + partNumber + "\n" +
"DEPOTOLD=" + posName + "\n" +
"DEPOTLONG="+storageName+" " + posName + "\n" +
"DEPOTOLD=\n" +
"DEPOTLONG=\n" +
"custom1=\n" +
"custom2=\n" +
"custom3=\n" +
......
......@@ -2,7 +2,6 @@ package com.neotel.smfcore.custom.fuji.util;
import com.neotel.smfcore.common.utils.SmbUtil;
import com.neotel.smfcore.common.utils.StringUtils;
import com.neotel.smfcore.custom.fuji.bean.OrderResp;
import jcifs.smb.SmbFile;
import lombok.extern.slf4j.Slf4j;
......@@ -85,18 +84,4 @@ public class OrderUtil {
}
return localFilePath;
}
public static void uploadRemoteFilePath(List<String> lineList, String localRespFilePath, String writeRemoteFilePath, OrderResp resp) {
if (lineList != null && !lineList.isEmpty()) {
//开始写入本地文件
String localFilePath = OrderUtil.getLocalFilePathByOrder(localRespFilePath, resp.getName() + ".ANS", lineList, StandardCharsets.US_ASCII);
//同步到远程
if (StringUtils.isNotBlank(localFilePath)) {
SmbUtil.smbPut(writeRemoteFilePath, localFilePath);
//TODO 暂时不删除本地文件
//FileUtil.del(new File(localFilePath));
}
}
}
}
支持 Markdown 格式
你添加了 0 到此讨论。请谨慎行事。
Finish editing this message first!