Commit d8819168 LN

Merge remote-tracking branch 'origin/master'

2 个父辈 9cf3156a aae33481
正在显示 19 个修改的文件 包含 823 行增加955 行删除
...@@ -39,287 +39,353 @@ import java.util.Map.Entry; ...@@ -39,287 +39,353 @@ import java.util.Map.Entry;
*/ */
@Slf4j @Slf4j
public class HttpHelper { public class HttpHelper {
// 编码方式 // 编码方式
private static final String CONTENT_CHARSET = "UTF-8"; private static final String CONTENT_CHARSET = "UTF-8";
// 连接超时时间 // 连接超时时间
private static final int CONNECTION_TIMEOUT = 10000; private static final int CONNECTION_TIMEOUT = 10000;
// 读数据超时时间 // 读数据超时时间
private static final int READ_DATA_TIMEOUT = 10000; private static final int READ_DATA_TIMEOUT = 10000;
/** /**
* 兼容smdBox接口 * 兼容smdBox接口
* @param url *
* @param paramMap * @param url
* @param user * @param paramMap
* @param pwd * @param user
* @return * @param pwd
* @throws ApiException * @return
*/ * @throws ApiException
@Deprecated */
public static String postParamWithAuth(String url, Map<String, Object> paramMap, String user, String pwd) throws ApiException { @Deprecated
PrintWriter out = null; public static String postParamWithAuth(String url, Map<String, Object> paramMap, String user, String pwd) throws ApiException {
BufferedReader in = null; PrintWriter out = null;
String result = ""; BufferedReader in = null;
try { String result = "";
URL realUrl = new URL(url); try {
// 打开和URL之间的连接 URL realUrl = new URL(url);
URLConnection conn = realUrl.openConnection(); // 打开和URL之间的连接
// 设置通用的请求属性 URLConnection conn = realUrl.openConnection();
conn.setRequestProperty("accept", "*/*"); // 设置通用的请求属性
conn.setRequestProperty("connection", "Keep-Alive"); conn.setRequestProperty("accept", "*/*");
conn.setRequestProperty("user-agent", "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1;SV1)"); conn.setRequestProperty("connection", "Keep-Alive");
conn.setRequestProperty("user-agent", "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1;SV1)");
//设置用户名和密码
//设置用户名和密码
if (Strings.isNotBlank(user)) {
String auth = user + ":" + pwd; if (Strings.isNotBlank(user)) {
//对其进行加密 String auth = user + ":" + pwd;
byte[] rel = Base64.getEncoder().encode(auth.getBytes()); //对其进行加密
String res = new String(rel); byte[] rel = Base64.getEncoder().encode(auth.getBytes());
//设置认证属性 String res = new String(rel);
conn.setRequestProperty("Authorization", "Basic " + res); //设置认证属性
} conn.setRequestProperty("Authorization", "Basic " + res);
}
// conn.setRequestProperty("Charset", "UTF-8");
// 发送POST请求必须设置如下两行 // conn.setRequestProperty("Charset", "UTF-8");
conn.setDoOutput(true); // 发送POST请求必须设置如下两行
conn.setDoInput(true); conn.setDoOutput(true);
// 获取URLConnection对象对应的输出流 conn.setDoInput(true);
out = new PrintWriter(conn.getOutputStream()); // 获取URLConnection对象对应的输出流
out = new PrintWriter(conn.getOutputStream());
// 设置请求属性
String param = ""; // 设置请求属性
if (paramMap != null && paramMap.size() > 0) { String param = "";
Iterator<String> ite = paramMap.keySet().iterator(); if (paramMap != null && paramMap.size() > 0) {
while (ite.hasNext()) { Iterator<String> ite = paramMap.keySet().iterator();
String key = ite.next();// key while (ite.hasNext()) {
Object valueObj = paramMap.get(key); String key = ite.next();// key
String value = ""; Object valueObj = paramMap.get(key);
if (valueObj != null) { String value = "";
if (valueObj instanceof Date) { if (valueObj != null) {
DateUtil.toDateString((Date) valueObj, "yyyyMMdd"); if (valueObj instanceof Date) {
} else { DateUtil.toDateString((Date) valueObj, "yyyyMMdd");
value = valueObj.toString(); } else {
} value = valueObj.toString();
} }
param += key + "=" + value + "&"; }
} param += key + "=" + value + "&";
param = param.substring(0, param.length() - 1); }
} param = param.substring(0, param.length() - 1);
}
// 发送请求参数
out.print(param); // 发送请求参数
// flush输出流的缓冲 out.print(param);
out.flush(); // flush输出流的缓冲
// 定义BufferedReader输入流来读取URL的响应 out.flush();
in = new BufferedReader( // 定义BufferedReader输入流来读取URL的响应
new InputStreamReader(conn.getInputStream())); in = new BufferedReader(
String line; new InputStreamReader(conn.getInputStream()));
while ((line = in.readLine()) != null) { String line;
result += line; while ((line = in.readLine()) != null) {
} result += line;
} catch (Exception e) { }
throw new ApiException("Request [" + url + "] failed:" + e.getMessage()); } catch (Exception e) {
} throw new ApiException("Request [" + url + "] failed:" + e.getMessage());
// 使用finally块来关闭输出流、输入流 }
finally { // 使用finally块来关闭输出流、输入流
try { finally {
if (out != null) { try {
out.close(); if (out != null) {
} out.close();
if (in != null) { }
in.close(); if (in != null) {
} in.close();
} catch (IOException ex) { }
throw new ApiException("Request [" + url + "] close instream failed:" + ex.getMessage()); } catch (IOException ex) {
} throw new ApiException("Request [" + url + "] close instream failed:" + ex.getMessage());
} }
return result; }
} return result;
}
public static String postJson(String url, Map<String, Object> params) throws ApiException {
// 设置请求参数 public static String postJson(String url, Map<String, Object> params) throws ApiException {
if (params == null || params.isEmpty()) { // 设置请求参数
params = null; if (params == null || params.isEmpty()) {
} params = null;
return postJsonWithAuth(url, params, null); }
} return postJsonWithAuth(url, params, null);
}
public static String postJsonWithAuth(String url, Object params, String auth) throws ApiException { public static String postJsonWithAuth(String url, Object params, String auth) throws ApiException {
String requestBody = ""; String requestBody = "";
// 设置请求参数 // 设置请求参数
if (params != null) { if (params != null) {
try { try {
ObjectMapper mapper = new ObjectMapper(); ObjectMapper mapper = new ObjectMapper();
requestBody = mapper.writeValueAsString(params); requestBody = mapper.writeValueAsString(params);
} catch (JsonProcessingException e) { } catch (JsonProcessingException e) {
throw new ApiException("Request params to [" + url + "] Json failed:" + e.getMessage()); throw new ApiException("Request params to [" + url + "] Json failed:" + e.getMessage());
} catch (Exception e) { } catch (Exception e) {
throw new ApiException("Request params to [" + url + "] json exception:" + e.getMessage()); throw new ApiException("Request params to [" + url + "] json exception:" + e.getMessage());
} }
} }
HttpPost httpPost = null; HttpPost httpPost = null;
CloseableHttpClient httpClient = null; CloseableHttpClient httpClient = null;
CloseableHttpResponse response = null; CloseableHttpResponse response = null;
try { try {
httpPost = new HttpPost(url); httpPost = new HttpPost(url);
httpPost.addHeader("Content-Type", "application/json;charset=utf-8"); httpPost.addHeader("Content-Type", "application/json;charset=utf-8");
if (auth != null && !auth.isEmpty()) { if (auth != null && !auth.isEmpty()) {
httpPost.addHeader("Authorization", auth); httpPost.addHeader("Authorization", auth);
} }
httpPost.setEntity(new StringEntity(requestBody, CONTENT_CHARSET)); httpPost.setEntity(new StringEntity(requestBody, CONTENT_CHARSET));
httpClient = HttpClients.createDefault(); httpClient = HttpClients.createDefault();
response = httpClient.execute(httpPost); response = httpClient.execute(httpPost);
HttpEntity entity = response.getEntity(); HttpEntity entity = response.getEntity();
String responseContent = EntityUtils.toString(entity, CONTENT_CHARSET); String responseContent = EntityUtils.toString(entity, CONTENT_CHARSET);
//response.close(); //response.close();
//httpClient.close(); //httpClient.close();
return responseContent; return responseContent;
} catch (Exception e) { } catch (Exception e) {
throw new ApiException("Request to [" + url + "]["+requestBody+"] failed:" + e.getMessage()); throw new ApiException("Request to [" + url + "][" + requestBody + "] failed:" + e.getMessage());
} finally { } finally {
try { try {
if (response != null) { if (response != null) {
response.close(); response.close();
} }
if (httpClient != null) { if (httpClient != null) {
httpClient.close(); httpClient.close();
} }
} catch (IOException e) { } catch (IOException e) {
e.printStackTrace(); e.printStackTrace();
} }
if (httpPost != null) { if (httpPost != null) {
httpPost.releaseConnection(); httpPost.releaseConnection();
} }
} }
} }
/** public static String postJson(String url, Map<String, Object> params, Map<String, String> headerMap) throws ApiException {
* 向指定URL发送POST请求 // 设置请求参数
* @param url if (params == null || params.isEmpty()) {
* @param paramMap params = null;
* @return 响应结果 }
*/ return postJsonWithAuth(url, params, null, headerMap);
public static String postParam(String url, Map<String, Object> paramMap) throws ApiException { }
String contentType = "application/json;charset=utf-8";
return postParam(url, paramMap, contentType); public static String postJsonWithAuth(String url, Object params, String auth, Map<String, String> headerMap) throws ApiException {
}
String requestBody = "";
public static String postFormParam(String url, Map<String, Object> paramMap) throws ApiException { // 设置请求参数
String contentType = "application/x-www-form-urlencoded"; if (params != null) {
return postParam(url, paramMap, contentType); try {
} ObjectMapper mapper = new ObjectMapper();
requestBody = mapper.writeValueAsString(params);
public static String postParam(String url, Map<String, Object> paramMap, String contentType) throws ApiException { } catch (JsonProcessingException e) {
// 设置请求参数 throw new ApiException("Request params to [" + url + "] Json failed:" + e.getMessage());
CloseableHttpClient httpClient = null; } catch (Exception e) {
CloseableHttpResponse response = null; throw new ApiException("Request params to [" + url + "] json exception:" + e.getMessage());
HttpPost httpPost = null; }
try { }
List<NameValuePair> params = toNameValuePair(paramMap);
URI uri = new URIBuilder(url).setParameters(params).build(); HttpPost httpPost = null;
log.info("执行请求:" + uri.toString()); CloseableHttpClient httpClient = null;
httpPost = new HttpPost(uri); CloseableHttpResponse response = null;
httpPost.addHeader("Content-Type", contentType); try {
httpPost = new HttpPost(url);
httpPost.addHeader("Content-Type", "application/json;charset=utf-8");
if (headerMap != null && !headerMap.isEmpty()) {
for (Entry<String, String> entry : headerMap.entrySet()) {
httpPost.addHeader(entry.getKey(), entry.getValue());
}
}
if (auth != null && !auth.isEmpty()) {
httpPost.addHeader("Authorization", auth);
}
httpPost.setEntity(new StringEntity(requestBody, CONTENT_CHARSET));
httpClient = HttpClients.createDefault();
response = httpClient.execute(httpPost);
HttpEntity entity = response.getEntity();
String responseContent = EntityUtils.toString(entity, CONTENT_CHARSET);
//response.close();
//httpClient.close();
return responseContent;
} catch (Exception e) {
throw new ApiException("Request to [" + url + "][" + requestBody + "] failed:" + e.getMessage());
} finally {
try {
if (response != null) {
response.close();
}
if (httpClient != null) {
httpClient.close();
}
} catch (IOException e) {
e.printStackTrace();
}
if (httpPost != null) {
httpPost.releaseConnection();
}
}
}
/**
* 向指定URL发送POST请求
*
* @param url
* @param paramMap
* @return 响应结果
*/
public static String postParam(String url, Map<String, Object> paramMap) throws ApiException {
String contentType = "application/json;charset=utf-8";
return postParam(url, paramMap, contentType);
}
public static String postFormParam(String url, Map<String, Object> paramMap) throws ApiException {
String contentType = "application/x-www-form-urlencoded";
return postParam(url, paramMap, contentType);
}
public static String postParam(String url, Map<String, Object> paramMap, String contentType) throws ApiException {
// 设置请求参数
CloseableHttpClient httpClient = null;
CloseableHttpResponse response = null;
HttpPost httpPost = null;
try {
List<NameValuePair> params = toNameValuePair(paramMap);
URI uri = new URIBuilder(url).setParameters(params).build();
log.info("执行请求:" + uri.toString());
httpPost = new HttpPost(uri);
httpPost.addHeader("Content-Type", contentType);
// httpPost.setEntity(new UrlEncodedFormEntity(params, CONTENT_CHARSET)); // httpPost.setEntity(new UrlEncodedFormEntity(params, CONTENT_CHARSET));
httpClient = HttpClients.createDefault(); httpClient = HttpClients.createDefault();
response = httpClient.execute(httpPost); response = httpClient.execute(httpPost);
HttpEntity entity = response.getEntity(); HttpEntity entity = response.getEntity();
String responseContent = EntityUtils.toString(entity, CONTENT_CHARSET); String responseContent = EntityUtils.toString(entity, CONTENT_CHARSET);
//response.close(); //response.close();
//httpClient.close(); //httpClient.close();
return responseContent; return responseContent;
} catch (Exception e) { } catch (Exception e) {
throw new ApiException("Request params to [" + url + "] failed:" + e.getMessage()); throw new ApiException("Request params to [" + url + "] failed:" + e.getMessage());
}finally { } finally {
try { try {
if (response != null) { if (response != null) {
response.close(); response.close();
} }
if (httpClient != null) { if (httpClient != null) {
httpClient.close(); httpClient.close();
} }
} catch (IOException e) { } catch (IOException e) {
e.printStackTrace(); e.printStackTrace();
} }
if (httpPost != null){ if (httpPost != null) {
httpPost.releaseConnection(); httpPost.releaseConnection();
} }
} }
} }
private static List<NameValuePair> toNameValuePair(Map<String, Object> paramMap) { private static List<NameValuePair> toNameValuePair(Map<String, Object> paramMap) {
List<NameValuePair> params = new ArrayList<NameValuePair>(); List<NameValuePair> params = new ArrayList<NameValuePair>();
if (paramMap != null && !paramMap.isEmpty()) { if (paramMap != null && !paramMap.isEmpty()) {
//建立一个NameValuePair数组,用于存储欲传送的参数 //建立一个NameValuePair数组,用于存储欲传送的参数
for (Entry<String, Object> entry : paramMap.entrySet()) { for (Entry<String, Object> entry : paramMap.entrySet()) {
String value = ""; String value = "";
Object valueObj = entry.getValue(); Object valueObj = entry.getValue();
if (valueObj != null) { if (valueObj != null) {
if (valueObj instanceof Date) { if (valueObj instanceof Date) {
value = DateUtil.toDateString((Date) valueObj, "yyyyMMdd"); value = DateUtil.toDateString((Date) valueObj, "yyyyMMdd");
} else { } else {
value = valueObj.toString(); value = valueObj.toString();
} }
} }
params.add(new BasicNameValuePair(entry.getKey(), value)); params.add(new BasicNameValuePair(entry.getKey(), value));
} }
} }
return params; return params;
} }
public static String posJsonParams(String url, Object params) throws ApiException { public static String posJsonParams(String url, Object params) throws ApiException {
HttpPost httpPost = new HttpPost(url); HttpPost httpPost = new HttpPost(url);
httpPost.addHeader("Content-Type", "application/json;charset=utf-8"); httpPost.addHeader("Content-Type", "application/json;charset=utf-8");
// 设置请求参数 // 设置请求参数
if (params != null) { if (params != null) {
ObjectMapper mapper = new ObjectMapper(); ObjectMapper mapper = new ObjectMapper();
try { try {
String requestBody = mapper.writeValueAsString(params); String requestBody = mapper.writeValueAsString(params);
httpPost.setEntity(new StringEntity(requestBody, CONTENT_CHARSET)); httpPost.setEntity(new StringEntity(requestBody, CONTENT_CHARSET));
} catch (JsonProcessingException e) { } catch (JsonProcessingException e) {
throw new ApiException("Request params to [" + url + "] Json failed:" + e.getMessage()); throw new ApiException("Request params to [" + url + "] Json failed:" + e.getMessage());
} catch (Exception e) { } catch (Exception e) {
throw new ApiException("Request params to [" + url + "] json exception:" + e.getMessage()); throw new ApiException("Request params to [" + url + "] json exception:" + e.getMessage());
} }
} }
CloseableHttpClient httpClient = null; CloseableHttpClient httpClient = null;
CloseableHttpResponse response = null; CloseableHttpResponse response = null;
try { try {
httpClient = HttpClients.createDefault(); httpClient = HttpClients.createDefault();
response = httpClient.execute(httpPost); response = httpClient.execute(httpPost);
HttpEntity entity = response.getEntity(); HttpEntity entity = response.getEntity();
String responseContent = EntityUtils.toString(entity, CONTENT_CHARSET); String responseContent = EntityUtils.toString(entity, CONTENT_CHARSET);
//response.close(); //response.close();
//httpClient.close(); //httpClient.close();
return responseContent; return responseContent;
} catch (Exception e) { } catch (Exception e) {
throw new ApiException("Request to [" + url + "] failed:" + e.getMessage()); throw new ApiException("Request to [" + url + "] failed:" + e.getMessage());
}finally { } finally {
try { try {
if (response != null) { if (response != null) {
response.close(); response.close();
} }
if (httpClient != null) { if (httpClient != null) {
httpClient.close(); httpClient.close();
} }
} catch (IOException e) { } catch (IOException e) {
e.printStackTrace(); e.printStackTrace();
} }
} }
} }
public static MicronResult getMicronJson(String url) throws ApiException { public static MicronResult getMicronJson(String url) throws ApiException {
if (ObjectUtil.isEmpty(url)) { if (ObjectUtil.isEmpty(url)) {
return new MicronResult(); return new MicronResult();
} }
HttpGet httpGet = new HttpGet(url); HttpGet httpGet = new HttpGet(url);
httpGet.addHeader("Content-Type", "application/json;charset=utf-8"); httpGet.addHeader("Content-Type", "application/json;charset=utf-8");
// // 设置请求参数 // // 设置请求参数
// if (params != null && !params.isEmpty()) { // if (params != null && !params.isEmpty()) {
// ObjectMapper mapper = new ObjectMapper(); // ObjectMapper mapper = new ObjectMapper();
...@@ -332,205 +398,244 @@ public class HttpHelper { ...@@ -332,205 +398,244 @@ public class HttpHelper {
// throw new ApiException("Request params to [" + url + "] failed:" + e.getMessage()); // throw new ApiException("Request params to [" + url + "] failed:" + e.getMessage());
// } // }
// } // }
CloseableHttpClient httpClient = null; CloseableHttpClient httpClient = null;
CloseableHttpResponse response = null; CloseableHttpResponse response = null;
try { try {
httpClient = HttpClients.createDefault(); httpClient = HttpClients.createDefault();
response = httpClient.execute(httpGet); response = httpClient.execute(httpGet);
int code = response.getStatusLine().getStatusCode(); int code = response.getStatusLine().getStatusCode();
//System.out.println(response.getStatusLine().getStatusCode() + "\n"); //System.out.println(response.getStatusLine().getStatusCode() + "\n");
HttpEntity entity = response.getEntity(); HttpEntity entity = response.getEntity();
String responseContent = EntityUtils.toString(entity, CONTENT_CHARSET); String responseContent = EntityUtils.toString(entity, CONTENT_CHARSET);
MicronResult result = JsonUtil.toObj(responseContent, MicronResult.class); MicronResult result = JsonUtil.toObj(responseContent, MicronResult.class);
if (result == null) { if (result == null) {
result = new MicronResult(); result = new MicronResult();
} }
result.setHttpCode(code); result.setHttpCode(code);
result.setResponseData(responseContent); result.setResponseData(responseContent);
//response.close(); //response.close();
//httpClient.close(); //httpClient.close();
return result; return result;
} catch (Exception e) { } catch (Exception e) {
throw new ApiException("Request to [" + url + "] failed:" + e.getMessage()); throw new ApiException("Request to [" + url + "] failed:" + e.getMessage());
}finally { } finally {
try { try {
if (response != null) { if (response != null) {
response.close(); response.close();
} }
if (httpClient != null) { if (httpClient != null) {
httpClient.close(); httpClient.close();
} }
} catch (IOException e) { } catch (IOException e) {
e.printStackTrace(); e.printStackTrace();
} }
} }
} }
public static MicronResult postMicronJson(String url, Map<String, Object> params) throws ApiException { public static MicronResult postMicronJson(String url, Map<String, Object> params) throws ApiException {
try { try {
if (ObjectUtil.isEmpty(url)) { if (ObjectUtil.isEmpty(url)) {
return new MicronResult(); return new MicronResult();
} }
String responseContent = postJson(url, params); String responseContent = postJson(url, params);
MicronResult result = JsonUtil.toObj(responseContent, MicronResult.class); MicronResult result = JsonUtil.toObj(responseContent, MicronResult.class);
if (result == null) { if (result == null) {
result = new MicronResult(); result = new MicronResult();
} }
result.setResponseData(responseContent); result.setResponseData(responseContent);
return result; return result;
} catch (Exception e) { } catch (Exception e) {
throw new ApiException("Request to [" + url + "] failed:" + e.getMessage()); throw new ApiException("Request to [" + url + "] failed:" + e.getMessage());
} }
} }
public static String getJson(String url, Object params) throws ApiException { public static String getJson(String url, Object params) throws ApiException {
// 设置请求参数 // 设置请求参数
if (params != null) { if (params != null) {
try { try {
ObjectMapper mapper = new ObjectMapper(); ObjectMapper mapper = new ObjectMapper();
String requestBody = mapper.writeValueAsString(params); String requestBody = mapper.writeValueAsString(params);
List<NameValuePair> nameValuePairs = new LinkedList<>(); List<NameValuePair> nameValuePairs = new LinkedList<>();
nameValuePairs.add(new BasicNameValuePair("JSON", requestBody)); nameValuePairs.add(new BasicNameValuePair("JSON", requestBody));
String paramStr = EntityUtils.toString(new UrlEncodedFormEntity(nameValuePairs)); String paramStr = EntityUtils.toString(new UrlEncodedFormEntity(nameValuePairs));
url = appendString(url, paramStr); url = appendString(url, paramStr);
// url=url+"?JSON="+requestBody; // url=url+"?JSON="+requestBody;
} catch (Exception e) { } catch (Exception e) {
throw new ApiException("getJson append params to [" + url + "] exception:" + e.getMessage()); throw new ApiException("getJson append params to [" + url + "] exception:" + e.getMessage());
} }
} }
CloseableHttpClient httpClient = null; CloseableHttpClient httpClient = null;
CloseableHttpResponse response = null; CloseableHttpResponse response = null;
try { try {
HttpGet httpGet = new HttpGet(url); HttpGet httpGet = new HttpGet(url);
RequestConfig requestConfig = RequestConfig.custom().setConnectTimeout(CONNECTION_TIMEOUT).build(); RequestConfig requestConfig = RequestConfig.custom().setConnectTimeout(CONNECTION_TIMEOUT).build();
httpGet.setConfig(requestConfig); httpGet.setConfig(requestConfig);
httpGet.addHeader("Content-Type", "application/json;charset=utf-8"); httpGet.addHeader("Content-Type", "application/json;charset=utf-8");
httpClient = HttpClients.createDefault(); httpClient = HttpClients.createDefault();
response = httpClient.execute(httpGet); response = httpClient.execute(httpGet);
int code = response.getStatusLine().getStatusCode(); int code = response.getStatusLine().getStatusCode();
HttpEntity entity = response.getEntity(); HttpEntity entity = response.getEntity();
String responseContent = EntityUtils.toString(entity, CONTENT_CHARSET); String responseContent = EntityUtils.toString(entity, CONTENT_CHARSET);
//response.close(); //response.close();
//httpClient.close(); //httpClient.close();
return responseContent; return responseContent;
} catch (Exception e) { } catch (Exception e) {
throw new ApiException("Request to [" + url + "] failed:" + e.getMessage()); throw new ApiException("Request to [" + url + "] failed:" + e.getMessage());
}finally { } finally {
try { try {
if (response != null) { if (response != null) {
response.close(); response.close();
} }
if (httpClient != null) { if (httpClient != null) {
httpClient.close(); httpClient.close();
} }
} catch (IOException e) { } catch (IOException e) {
e.printStackTrace(); e.printStackTrace();
} }
} }
} }
public static String getJson(String url,Map<String,String> headerMap ,Object params) throws ApiException { public static String getJson(String url, Map<String, String> headerMap, Object params) throws ApiException {
// 设置请求参数 // 设置请求参数
if (params != null) { if (params != null) {
try { try {
ObjectMapper mapper = new ObjectMapper(); ObjectMapper mapper = new ObjectMapper();
String requestBody = mapper.writeValueAsString(params); String requestBody = mapper.writeValueAsString(params);
List<NameValuePair> nameValuePairs = new LinkedList<>(); List<NameValuePair> nameValuePairs = new LinkedList<>();
nameValuePairs.add(new BasicNameValuePair("JSON", requestBody)); nameValuePairs.add(new BasicNameValuePair("JSON", requestBody));
String paramStr = EntityUtils.toString(new UrlEncodedFormEntity(nameValuePairs)); String paramStr = EntityUtils.toString(new UrlEncodedFormEntity(nameValuePairs));
url = appendString(url, paramStr); url = appendString(url, paramStr);
// url=url+"?JSON="+requestBody; // url=url+"?JSON="+requestBody;
} catch (Exception e) { } catch (Exception e) {
throw new ApiException("getJson append params to [" + url + "] exception:" + e.getMessage()); throw new ApiException("getJson append params to [" + url + "] exception:" + e.getMessage());
} }
} }
CloseableHttpClient httpClient = null; CloseableHttpClient httpClient = null;
CloseableHttpResponse response = null; CloseableHttpResponse response = null;
try { try {
HttpGet httpGet = new HttpGet(url); HttpGet httpGet = new HttpGet(url);
RequestConfig requestConfig = RequestConfig.custom().setConnectTimeout(CONNECTION_TIMEOUT).build(); RequestConfig requestConfig = RequestConfig.custom().setConnectTimeout(CONNECTION_TIMEOUT).build();
httpGet.setConfig(requestConfig); httpGet.setConfig(requestConfig);
if (headerMap != null && !headerMap.isEmpty()) { if (headerMap != null && !headerMap.isEmpty()) {
for (Entry<String, String> entry : headerMap.entrySet()) { for (Entry<String, String> entry : headerMap.entrySet()) {
httpGet.addHeader(entry.getKey(), entry.getValue()); httpGet.addHeader(entry.getKey(), entry.getValue());
} }
} }
httpClient = HttpClients.createDefault(); httpClient = HttpClients.createDefault();
response = httpClient.execute(httpGet); response = httpClient.execute(httpGet);
int code = response.getStatusLine().getStatusCode(); int code = response.getStatusLine().getStatusCode();
HttpEntity entity = response.getEntity(); HttpEntity entity = response.getEntity();
String responseContent = EntityUtils.toString(entity, CONTENT_CHARSET); String responseContent = EntityUtils.toString(entity, CONTENT_CHARSET);
//response.close(); //response.close();
//httpClient.close(); //httpClient.close();
return responseContent; return responseContent;
} catch (Exception e) { } catch (Exception e) {
throw new ApiException("Request to [" + url + "] failed:" + e.getMessage()); throw new ApiException("Request to [" + url + "] failed:" + e.getMessage());
}finally { } finally {
try { try {
if (response != null) { if (response != null) {
response.close(); response.close();
} }
if (httpClient != null) { if (httpClient != null) {
httpClient.close(); httpClient.close();
} }
} catch (IOException e) { } catch (IOException e) {
e.printStackTrace(); e.printStackTrace();
} }
} }
} }
public static String postParam(String url, Map<String, Object> paramMap, Map<String,String> headerMap) throws ApiException { public static String postParam(String url, Map<String, Object> paramMap, Map<String, String> headerMap) throws ApiException {
// 设置请求参数 // 设置请求参数
CloseableHttpClient httpClient = null; CloseableHttpClient httpClient = null;
CloseableHttpResponse response = null; CloseableHttpResponse response = null;
try { try {
List<NameValuePair> params = toNameValuePair(paramMap); List<NameValuePair> params = toNameValuePair(paramMap);
URI uri = new URIBuilder(url).setParameters(params).build(); URI uri = new URIBuilder(url).setParameters(params).build();
log.info("执行请求:" + uri.toString()); log.info("执行请求:" + uri.toString());
HttpPost httpPost = new HttpPost(uri); HttpPost httpPost = new HttpPost(uri);
for (Entry<String, String> entry : headerMap.entrySet()) { for (Entry<String, String> entry : headerMap.entrySet()) {
httpPost.addHeader(entry.getKey(), entry.getValue()); httpPost.addHeader(entry.getKey(), entry.getValue());
} }
// httpPost.setEntity(new UrlEncodedFormEntity(params, CONTENT_CHARSET)); // httpPost.setEntity(new UrlEncodedFormEntity(params, CONTENT_CHARSET));
httpClient = HttpClients.createDefault(); httpClient = HttpClients.createDefault();
response = httpClient.execute(httpPost); response = httpClient.execute(httpPost);
HttpEntity entity = response.getEntity(); HttpEntity entity = response.getEntity();
String responseContent = EntityUtils.toString(entity, CONTENT_CHARSET); String responseContent = EntityUtils.toString(entity, CONTENT_CHARSET);
//response.close(); //response.close();
//httpClient.close(); //httpClient.close();
return responseContent; return responseContent;
} catch (Exception e) { } catch (Exception e) {
throw new ApiException("Request params to [" + url + "] failed:" + e.getMessage()); throw new ApiException("Request params to [" + url + "] failed:" + e.getMessage());
}finally { } finally {
try { try {
if (response != null) { if (response != null) {
response.close(); response.close();
} }
if (httpClient != null) { if (httpClient != null) {
httpClient.close(); httpClient.close();
} }
} catch (IOException e) { } catch (IOException e) {
e.printStackTrace(); e.printStackTrace();
} }
} }
} }
private static String appendString(String url, String paramStr) {
StringBuffer stringBuffer = new StringBuffer(); public static String getParam(String url, Map<String, String> headerMap, Map<String,Object> paramMap) throws ApiException {
stringBuffer.append(url); CloseableHttpClient httpClient = null;
stringBuffer.append("?"); CloseableHttpResponse response = null;
stringBuffer.append(paramStr); try {
return stringBuffer.toString();
} List<NameValuePair> params = toNameValuePair(paramMap);
URI uri = new URIBuilder(url).setParameters(params).build();
log.info("getParam请求,地址为:"+uri);
HttpGet httpGet = new HttpGet(uri);
RequestConfig requestConfig = RequestConfig.custom().setConnectTimeout(CONNECTION_TIMEOUT).build();
httpGet.setConfig(requestConfig);
if (headerMap != null && !headerMap.isEmpty()) {
for (Entry<String, String> entry : headerMap.entrySet()) {
httpGet.addHeader(entry.getKey(), entry.getValue());
}
}
httpClient = HttpClients.createDefault();
response = httpClient.execute(httpGet);
HttpEntity entity = response.getEntity();
String responseContent = EntityUtils.toString(entity, CONTENT_CHARSET);
return responseContent;
} catch (Exception e) {
throw new ApiException("Request to [" + url + "] failed:" + e.getMessage());
} finally {
try {
if (response != null) {
response.close();
}
if (httpClient != null) {
httpClient.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
private static String appendString(String url, String paramStr) {
StringBuffer stringBuffer = new StringBuffer();
stringBuffer.append(url);
stringBuffer.append("?");
stringBuffer.append(paramStr);
return stringBuffer.toString();
}
} }
package com.neotel.smfcore.custom.fuji;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.neotel.smfcore.common.exception.ApiException;
import com.neotel.smfcore.common.exception.ValidateException;
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.barcode.service.po.Barcode;
import com.neotel.smfcore.core.system.service.po.DataLog;
import com.neotel.smfcore.custom.fuji.config.FileDirectoryConfig;
import com.neotel.smfcore.custom.fuji.config.FujiUrlConfig;
import com.neotel.smfcore.custom.fuji.util.NotifyUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import java.util.Arrays;
import java.util.HashMap;
import java.util.Map;
@Service
@Slf4j
public class FujiApi extends BaseSmfApiListener {
@Override
public boolean isForThisApi(String apiName) {
return apiName != null && apiName.equalsIgnoreCase("fuji");
}
@Override
public Barcode canPutInAfterResolve(String inCheckUrl, CodeValidateParam params, Barcode barcode) throws ValidateException {
String accessToken = getAccessToken();
//log.info(barcode.getBarcode()+"获取token的结果为:"+accessToken);
boolean hasDid = inventoryHasDid(barcode.getBarcode(),accessToken);
if (hasDid){
log.info(barcode.getBarcode()+"在Fuji中已经存在,直接返回");
return barcode;
} else {
boolean register = registerNewDid(barcode, accessToken);
if (register){
log.info(barcode.getBarcode()+"在Fuji中注册成功,直接返回");
return barcode;
} else {
throw new ValidateException("smfcore.registerdid.false",barcode.getBarcode()+"注册失败");
}
}
}
@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);
}
}
@Override
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.createDeleteEtn(task.getBarcode(),task.getW(),task.getH(),task.getPartNumber(),FileDirectoryConfig.NOTIFY);
}
}
public boolean registerNewDid(Barcode barcode,String accessToken) {
Map<String, String> headerMap = new HashMap<>();
headerMap.put("fujiAccessToken", accessToken);
Map<String, Object> params = new HashMap<>();
params.put("did",barcode.getBarcode());
params.put("partBarcode",barcode.getFullCode());
params.put("quantity",barcode.getAmount());
params.put("packageType","paper"); //默认是paper,
params.put("partsoutWarning",0);
params.put("splicingWarning",0);
params.put("partNumber",barcode.getPartNumber());
params.put("vendorName",barcode.getProvider());
params.put("lotName",barcode.getBatch());
params.put("dateCode",barcode.getProduceDate());
params.put("location","");
params.put("memo","");
params.put("note1","");
params.put("note2","");
params.put("note3","");
params.put("note4","");
params.put("useSplicing",true);
params.put("useTrayPackage",true);
params.put("trayStackCount",1);
params.put("trayPickupPositionX",1);
params.put("trayPickupPositionY",1);
params.put("traySizeX",0);
params.put("traySizeY",0);
log.info("注册Fuji的did参数为:"+JSON.toJSONString(params));
try {
String result = HttpHelper.postJsonWithAuth(FujiUrlConfig.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){
return true;
} else {
String details = resultObj.getString("details");
throw new ValidateException("smfcore.registerdid.false",barcode.getBarcode()+"注册失败:"+details);
}
} catch (ApiException e) {
log.info("注册Fuji的did失败:",e);
}
return false;
}
public boolean inventoryHasDid(String barcode,String accessToken) {
Map<String, String> headerMap = new HashMap<>();
headerMap.put("fujiAccessToken", accessToken);
String search = "did == \""+barcode+"\"";
String orderBy = "did asc";
int pageToken = 0;
int pageSize = 200;
Map<String, Object> paramMap = new HashMap<>();
paramMap.put("pageToken", pageToken);
paramMap.put("pageSize", pageSize);
paramMap.put("search", search);
paramMap.put("orderBy", orderBy);
try {
String result = HttpHelper.getParam(FujiUrlConfig.inventoryDids(), headerMap, paramMap);
log.info(barcode + "获取Fuji的inventory/dids结果为:" + result);
JSONObject resultObj = JSONObject.parseObject(result);
JSONArray dataArray = resultObj.getJSONArray("datas");
if (dataArray != null && !dataArray.isEmpty()){
for (int i = 0; i < dataArray.size(); i++) {
JSONObject data = dataArray.getJSONObject(i);
if (barcode.equals(data.getString("did"))){
return true;
}
}
}
} catch (ApiException e) {
log.info(barcode + "获取Fuji的inventory/dids失败:", e.getMessage());
}
return false;
}
/**
* 获取登录的token
* @return
*/
private 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 accessToken = "";
try {
String result = HttpHelper.postJson(FujiUrlConfig.getAuthLogin(), paramMap);
log.info("获取Fuji的token结果为:" + result);
JSONObject resultObj = JSONObject.parseObject(result);
accessToken = resultObj.getString("accessToken");
} catch (ApiException e) {
log.info("获取Fuji的token异常:", e);
accessToken = "";
}
if (StringUtils.isEmpty(accessToken)) {
throw new ValidateException("smfcore.accessToken.ng", "获取AccessToken失败");
}
return accessToken;
}
}
package com.neotel.smfcore.custom.nexim.bean; package com.neotel.smfcore.custom.fuji.bean;
import lombok.Data; import lombok.Data;
......
package com.neotel.smfcore.custom.nexim.bean; package com.neotel.smfcore.custom.fuji.bean;
import lombok.Data; import lombok.Data;
......
package com.neotel.smfcore.custom.nexim.bean; package com.neotel.smfcore.custom.fuji.bean;
import lombok.Data; import lombok.Data;
......
package com.neotel.smfcore.custom.fuji.config;
public class FileDirectoryConfig {
public static final String NOTIFY = "\\\\175.41.238.212\\remoteorder\\notify\\";
}
package com.neotel.smfcore.custom.fuji.config;
import lombok.Data;
@Data
public class FujiUrlConfig {
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 inventoryDids = "/inventory/dids";
public static String getAuthLogin() {
return baseUrl + authLogin;
}
public static String inventoryDids() {
return baseUrl + inventoryDids;
}
}
package com.neotel.smfcore.custom.nexim.enums; package com.neotel.smfcore.custom.fuji.enums;
/** /**
* Action 类型 * Action 类型
......
package com.neotel.smfcore.custom.nexim.enums; package com.neotel.smfcore.custom.fuji.enums;
public class ErrorCode { public class ErrorCode {
public static final int ok = 0; public static final int ok = 0;
......
package com.neotel.smfcore.custom.nexim.enums; package com.neotel.smfcore.custom.fuji.enums;
public enum NexObject { public enum NexObject {
......
package com.neotel.smfcore.custom.nexim.enums; package com.neotel.smfcore.custom.fuji.enums;
public class OrderType { public class OrderType {
public static final String order = "[Order]"; public static final String order = "[Order]";
......
package com.neotel.smfcore.custom.nexim.order; package com.neotel.smfcore.custom.fuji.order;
import cn.hutool.core.date.DateUtil;
import com.alibaba.fastjson.JSON; import com.alibaba.fastjson.JSON;
import com.neotel.smfcore.common.utils.*;
import com.neotel.smfcore.core.api.SmfApi; import com.neotel.smfcore.core.api.SmfApi;
import com.neotel.smfcore.core.barcode.service.manager.IBarcodeManager;
import com.neotel.smfcore.core.barcode.service.po.Barcode;
import com.neotel.smfcore.core.device.enums.OP;
import com.neotel.smfcore.core.device.enums.OP_STATUS;
import com.neotel.smfcore.core.device.util.DataCache; import com.neotel.smfcore.core.device.util.DataCache;
import com.neotel.smfcore.core.order.LiteOrderCache; import com.neotel.smfcore.core.order.LiteOrderCache;
import com.neotel.smfcore.core.order.service.manager.ILiteOrderManager; 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.LiteOrder;
import com.neotel.smfcore.core.order.service.po.LiteOrderItem; import com.neotel.smfcore.core.order.service.po.LiteOrderItem;
import com.neotel.smfcore.core.storage.enums.CHECKOUT_TYPE; import com.neotel.smfcore.custom.fuji.util.NotifyUtil;
import com.neotel.smfcore.core.storage.service.manager.IStoragePosManager; import com.neotel.smfcore.custom.fuji.util.OrderUtil;
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.nexim.NeximApi;
import com.neotel.smfcore.custom.nexim.bean.OrderReq;
import com.neotel.smfcore.custom.nexim.bean.OrderResp;
import com.neotel.smfcore.custom.nexim.enums.Action;
import com.neotel.smfcore.custom.nexim.enums.ErrorCode;
import com.neotel.smfcore.custom.nexim.enums.NexObject;
import com.neotel.smfcore.custom.nexim.enums.OrderType;
import com.neotel.smfcore.custom.nexim.util.NotifyUtil;
import com.neotel.smfcore.custom.nexim.util.OrderUtil;
import com.neotel.smfcore.security.annotation.AnonymousAccess;
import jcifs.smb.SmbFile;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j; import lombok.extern.slf4j.Slf4j;
import org.apache.logging.log4j.util.Strings;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.stereotype.Component; import org.springframework.stereotype.Component;
import org.springframework.web.bind.annotation.RequestMapping;
import javax.annotation.PostConstruct; import javax.annotation.PostConstruct;
import java.io.File; import java.io.File;
import java.io.FileInputStream;
import java.io.IOException; import java.io.IOException;
import java.io.InputStreamReader;
import java.nio.charset.Charset;
import java.nio.charset.StandardCharsets; import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.*; import java.util.*;
import java.util.concurrent.Executors; import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService; import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit; import java.util.concurrent.TimeUnit;
import java.util.regex.Pattern;
import java.util.stream.Collectors; import java.util.stream.Collectors;
@Slf4j @Slf4j
@Component @Component
public class OrderHandler { public class OrderHandler {
private static IStoragePosManager storagePosManager;
@Autowired
public void setStoragePosManager(IStoragePosManager manager) {
storagePosManager = manager;
}
private static IBarcodeManager barcodeManager;
@Autowired
public void setBarcodeManager(IBarcodeManager manager) {
barcodeManager = manager;
}
private static DataCache dataCache; private static DataCache dataCache;
@Autowired @Autowired
...@@ -82,13 +34,6 @@ public class OrderHandler { ...@@ -82,13 +34,6 @@ public class OrderHandler {
dataCache = cache; dataCache = cache;
} }
private static TaskService taskService;
@Autowired
public void setTaskService(TaskService service) {
taskService = service;
}
private static ILiteOrderManager liteOrderManager; private static ILiteOrderManager liteOrderManager;
@Autowired @Autowired
...@@ -103,12 +48,6 @@ public class OrderHandler { ...@@ -103,12 +48,6 @@ public class OrderHandler {
liteOrderCache = cache; liteOrderCache = cache;
} }
private static OrderCheckOutService checkOutService;
@Autowired
public void setOrderCheckOutService(OrderCheckOutService service) {
checkOutService = service;
}
public static SmfApi smfApi; public static SmfApi smfApi;
...@@ -122,16 +61,15 @@ public class OrderHandler { ...@@ -122,16 +61,15 @@ public class OrderHandler {
@PostConstruct @PostConstruct
public void init() { public void init() {
scheduledThreadPool.scheduleAtFixedRate(() -> { if ("nexim".equals(smfApi.getApiName())){
try { scheduledThreadPool.scheduleAtFixedRate(() -> {
if ("nexim".equals(smfApi.getApiName())) { try {
handler(); handler();
} catch (Exception e) {
log.info("执行fuji工单失败:",e);
} }
} catch (IOException e) { },60, 10, TimeUnit.SECONDS);
e.printStackTrace(); }
log.error(e.getMessage());
}
}, 60, 10, TimeUnit.SECONDS);
} }
public static void handler() throws IOException { public static void handler() throws IOException {
......
package com.neotel.smfcore.custom.nexim.util; package com.neotel.smfcore.custom.fuji.util;
import cn.hutool.core.date.DateUtil;
import com.alibaba.fastjson.JSON;
import com.neotel.smfcore.core.system.service.po.DataLog;
import com.neotel.smfcore.custom.nexim.bean.Notify;
import lombok.extern.slf4j.Slf4j; import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import java.io.File; import java.io.File;
import java.io.FileOutputStream; import java.io.FileOutputStream;
......
package com.neotel.smfcore.custom.nexim.util; package com.neotel.smfcore.custom.fuji.util;
import com.alibaba.fastjson.JSON;
import com.neotel.smfcore.common.utils.FileUtil;
import com.neotel.smfcore.common.utils.SmbUtil; import com.neotel.smfcore.common.utils.SmbUtil;
import com.neotel.smfcore.common.utils.StringUtils; import com.neotel.smfcore.common.utils.StringUtils;
import com.neotel.smfcore.custom.nexim.bean.Notify; import com.neotel.smfcore.custom.fuji.bean.OrderResp;
import com.neotel.smfcore.custom.nexim.bean.OrderReq;
import com.neotel.smfcore.custom.nexim.bean.OrderResp;
import com.neotel.smfcore.custom.nexim.enums.OrderType;
import jcifs.smb.SmbFile; import jcifs.smb.SmbFile;
import lombok.extern.slf4j.Slf4j; import lombok.extern.slf4j.Slf4j;
...@@ -20,7 +15,6 @@ import java.nio.charset.StandardCharsets; ...@@ -20,7 +15,6 @@ import java.nio.charset.StandardCharsets;
import java.nio.file.Files; import java.nio.file.Files;
import java.nio.file.Path; import java.nio.file.Path;
import java.nio.file.Paths; import java.nio.file.Paths;
import java.util.ArrayList;
import java.util.Comparator; import java.util.Comparator;
import java.util.List; import java.util.List;
import java.util.stream.Collectors; import java.util.stream.Collectors;
......
...@@ -295,7 +295,7 @@ public class NeotelApi extends BaseSmfApiListener { ...@@ -295,7 +295,7 @@ public class NeotelApi extends BaseSmfApiListener {
barcode = barcodeManager.save(barcode); barcode = barcodeManager.save(barcode);
return barcode; return barcode;
} else { } else {
return null; throw new ValidateException("smfcore.mesApi.inCheck.error", "MES验证出错:" + apiResult.getMsg());
} }
} catch (Exception e) { } catch (Exception e) {
log.error("入库验证接口出错:" + e.getMessage()); log.error("入库验证接口出错:" + e.getMessage());
......
package com.neotel.smfcore.custom.nexim;
import com.neotel.smfcore.common.utils.FileUtil;
import com.neotel.smfcore.common.utils.SmbUtil;
import com.neotel.smfcore.core.api.listener.BaseSmfApiListener;
import com.neotel.smfcore.core.system.service.po.DataLog;
import com.neotel.smfcore.custom.nexim.bean.Notify;
import com.neotel.smfcore.custom.nexim.config.FileDirectoryConfig;
import com.neotel.smfcore.custom.nexim.enums.Action;
import com.neotel.smfcore.custom.nexim.enums.NexObject;
import com.neotel.smfcore.custom.nexim.util.NotifyUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import java.io.File;
@Service
@Slf4j
public class NeximApi extends BaseSmfApiListener {
@Override
public boolean isForThisApi(String apiName) {
return apiName != null && apiName.equalsIgnoreCase("nexim");
}
@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);
}
}
@Override
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.createDeleteEtn(task.getBarcode(),task.getW(),task.getH(),task.getPartNumber(),FileDirectoryConfig.NOTIFY);
}
}
}
package com.neotel.smfcore.custom.nexim.config;
public class FileDirectoryConfig {
//public static final String NOTIFY = "Remoteorder\\notify\\";
public static final String NOTIFY = "F:\\FUJI\\remoteorder\\notify\\";
//public static final String INPUT = "Remoteorder\\input\\";
public static final String INPUT = "F:\\FUJI\\remoteorder\\line\\";
public static final String OUTPUT = "Remoteorder\\output\\";
}
package com.neotel.smfcore.custom.nexim.order;
import com.google.common.base.Strings;
import com.neotel.smfcore.common.bean.ResultBean;
import com.neotel.smfcore.common.exception.ValidateException;
import com.neotel.smfcore.common.utils.SecurityUtils;
import com.neotel.smfcore.core.api.SmfApi;
import com.neotel.smfcore.core.barcode.service.po.Barcode;
import com.neotel.smfcore.core.device.enums.OP;
import com.neotel.smfcore.core.device.enums.OP_STATUS;
import com.neotel.smfcore.core.device.util.DataCache;
import com.neotel.smfcore.core.order.LiteOrderCache;
import com.neotel.smfcore.core.order.enums.LITEORDER_STATUS;
import com.neotel.smfcore.core.order.enums.ORDER_COLOR;
import com.neotel.smfcore.core.order.service.manager.ILiteOrderItemManager;
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 lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.stereotype.Service;
import java.util.Collection;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
@Slf4j
@Service
public class OrderCheckOutService {
@Autowired
private LiteOrderCache liteOrderCache;
@Autowired
private ILiteOrderManager liteOrderManager;
@Autowired
private TaskService taskService;
@Autowired
private IStoragePosManager storagePosManager;
@Autowired
private SmfApi smfApi;
@Autowired
private DataCache dataCache;
@Autowired
private ILiteOrderItemManager liteOrderItemManager;
/**
* 执行工单出库
*/
public synchronized String checkOutLiteOrder(String orderNo, boolean outBom,boolean singleOut) {
LiteOrder cacheOrder = liteOrderCache.getLiteOrder(orderNo);;
if (cacheOrder == null) {
cacheOrder = liteOrderManager.findByOrderNo(orderNo);
}
if (cacheOrder == null) {
return "smfcore.order.out.notFound";
}
if ( !cacheOrder.isTaskFinished() && !cacheOrder.isNew()) {
log.info("工单[" + orderNo + "]正在执行");
return "smfcore.order.out.executing";
}
if(cacheOrder.isClosed()) {
log.info("工单[" + orderNo + "]已关闭,无法出库");
return "smfcore.order.hasClose";
}
ORDER_COLOR nextColor = getNextColor();
if (nextColor == null) {
log.info("执行工单[" + orderNo + "] outBom=" + outBom + "时,已达最大可执行工单数");
return "smfcore.order.out.maxOrder";
}
//先查找是否已经锁定过库位,如果已经锁定过,出锁定的库位
List<StoragePos> lockPosList = storagePosManager.findLockPos(cacheOrder.getOrderNo());
if(lockPosList!=null&& lockPosList.size()>0){
return checkOutOrder(cacheOrder).getMsgKey();
}
log.info("开始执行工单[" + orderNo + "] outBom=" + outBom);
cacheOrder.setTaskReelCount(0);
cacheOrder.setTaskFinishedTime(-1);
cacheOrder.setFinishedReelCount(0);
if (outBom) {
cacheOrder.setStatus(LITEORDER_STATUS.BOM);
} else {
cacheOrder.setStatus(LITEORDER_STATUS.TAILS);
}
//liteOrderMap.put(cacheOrder.getOrderNo(), cacheOrder);
int taskReelCount = 0;
CHECKOUT_TYPE checkoutType = dataCache.getCheckOutType();
List<String> availableStorageIds = dataCache.getAvailableStorageIds();
//其他出库模式一次性全部生成任务
for (LiteOrderItem orderItem : cacheOrder.getOrderItems()) {
orderItem.setOutNum(0);
orderItem.setOutReelCount(0);
liteOrderItemManager.save(orderItem);
//剩余未出数量
Float totalNum = orderItem.getNeedNum() * cacheOrder.getOrderTimes();
int remainNum = totalNum.intValue() - orderItem.getTotalOutNum();
//剩余未出盘数
int remainReelCount = orderItem.getNeedReelCount() - orderItem.getTotalOutReelCount();
//此PN未完成
if (remainNum > 0) {
if (outBom) {
//套料出库,设置剩余数量为1,这样就只会出一盘
remainNum = 1;
remainReelCount = 0;
}
int assignNum = 0;
int assignReelCount = 0;
while (assignNum < remainNum || assignReelCount < remainReelCount) {
Collection<String> excludePosIds = excludeOutPosIds();
String partNumber = orderItem.getPn();
String reelId = orderItem.getRi();
String mpn = orderItem.getMpn();
StoragePos pos = null;
if(!Strings.isNullOrEmpty(reelId)){
//RI
pos=storagePosManager.getByBarcode(reelId);
if(pos != null){
if(excludePosIds.contains(pos.getId())) {
log.info("工单[" + orderNo + "]RI出库,任务数[" + taskReelCount + "]出库位置仓位【" + pos.getPosName() + "】RI=[" + pos.getBarcode().getBarcode() + "]已在操作队列中,跳过不处理");
break;
}
}else{
log.info("工单[" + orderNo + "]RI出库时,库存中未找到料盘["+reelId+"]");
}
}else if (Strings.isNullOrEmpty(reelId) && !Strings.isNullOrEmpty(partNumber)){
//PN
pos=storagePosManager.findPartNumberInStorages(availableStorageIds,"", partNumber, excludePosIds, checkoutType,orderItem.getAppendData());
} else if (Strings.isNullOrEmpty(reelId) && Strings.isNullOrEmpty(partNumber) && !Strings.isNullOrEmpty(mpn)){
pos=storagePosManager.findMpnInStorages(availableStorageIds, mpn, excludePosIds, checkoutType,orderItem.getAppendData());
}
//如果库位没有料,随便找一盘进行出库
if (pos == null){
log.info("没有找到要出库的物料,随便出库一个物料");
Criteria c = Criteria.where("id").nin(excludePosIds).and("enabled").is(true)
.and("barcode.lockId").is(null)
.and("barcode").exists(true);
if (availableStorageIds != null && !availableStorageIds.isEmpty()){
c = c.and("storageId").in(availableStorageIds);
}
Query q = new Query(c);
pos=storagePosManager.findOne(q);
}
if (pos == null) {
// log.error("未找到可以出库的物料[" + partNumber + "]");
break;
} else {
assignNum = assignNum + pos.getBarcode().getAmount();
assignReelCount = assignReelCount + 1;
taskReelCount = taskReelCount + 1;
log.info("工单[" + orderNo + "],任务数[" + taskReelCount + "]出库位置仓位【" + pos.getPosName() + "】RI=[" + pos.getBarcode().getBarcode() + "] PN=[" + partNumber + "] num:" + pos.getBarcode().getAmount());
DataLog task = newTask(pos) ;
task.setSourceId(cacheOrder.getId());
task.setSourceName(cacheOrder.getOrderNo());
task.setSubSourceId(orderItem.getId());
task.setSubSourceInfo(orderItem.getFeederInfo());
task.setType(OP.CHECKOUT);
task.setLightColor(nextColor.getRgb());
task.setStatus(OP_STATUS.WAIT.name());
task.setSingleOut(singleOut);
// task = dataLogDao.save(task);
taskService.addTaskToExecute(task);
}
//如果是RI出库,只有一盘,出完就结束
if(!Strings.isNullOrEmpty(reelId)){
break;
}
}
}
}
cacheOrder.setTaskReelCount(taskReelCount);
cacheOrder.setTotalTaskReelCount(cacheOrder.getTotalTaskReelCount()+taskReelCount);
log.info("工单[" + orderNo + "]任务分配结束,任务数[" + taskReelCount + "]");
smfApi.onOrderStatusChange(cacheOrder);
//有需要出库的
if (taskReelCount <= 0) {
finishedOrderTasks(cacheOrder);
}
liteOrderManager.save(cacheOrder);
liteOrderCache.addOrderToMap(cacheOrder);
if (taskReelCount <= 0) {
//return "工单无可执行的任务";
return "smfcore.order.out.noTask";
}
return "";
}
public ResultBean checkOutOrder(LiteOrder liteOrder) throws ValidateException {
ORDER_COLOR nextColor = getNextColor();
if (nextColor == null) {
log.info("执行工单[" + liteOrder.getOrderNo() + "] 时,已达最大可执行工单数");
throw new ValidateException("order.out.maxOrder","已达最大可执行工单数");
}
//其他出库模式一次性全部生成任务
List<StoragePos> lockPosList = storagePosManager.findLockPos(liteOrder.getOrderNo());
if(lockPosList==null){
throw new ValidateException("smfcore.notFindPos","未找到锁定库位");
}
int taskReelCount = 0;
for (StoragePos lockPos : lockPosList) {
Storage storage = dataCache.getStorageById(lockPos.getStorageId());
Barcode barcode = lockPos.getBarcode();
DataLog task = new DataLog(storage,barcode,lockPos);
task.setSourceId(liteOrder.getId());
task.setSourceName(liteOrder.getOrderNo());
task.setSubSourceId(barcode.getLockName());
task.setSubSourceInfo(barcode.getLockName());
task.setType(OP.CHECKOUT);
task.setPutInDate(barcode.getPutInDate());
task.setLightColor(nextColor.getRgb());
task.setStatus(OP_STATUS.WAIT.name());
taskService.addTaskToExecute(task);
taskReelCount = taskReelCount + 1;
log.info("工单[" + liteOrder.getOrderNo() + "]出库位置仓位【" + task.getPosName() + "】RI=[" + task.getBarcode() + "] PN=[" + task.getPartNumber() + "] ");
}
liteOrder.setTaskReelCount(taskReelCount);
liteOrder.setTotalTaskReelCount(liteOrder.getTotalTaskReelCount()+taskReelCount);
liteOrder.setStatus(LITEORDER_STATUS.TAILS);
log.info("工单[" + liteOrder.getOrderNo() + "]任务分配结束,任务数[" + taskReelCount + "]");
smfApi.onOrderStatusChange(liteOrder);
if (taskReelCount <= 0) {
//没有任务,直接结束
finishedOrderTasks(liteOrder);
}else{
//有需要出库的 ,更新状态
liteOrder.setStatus(LITEORDER_STATUS.TAILS);
}
liteOrder = liteOrderManager.save(liteOrder);
liteOrderCache.addOrderToMap(liteOrder);
if (taskReelCount <= 0) {
return ResultBean.newErrorResult(-1,"smfcore.notask","No task in this order");
}
return ResultBean.newOkResult("smfcore.taskCount", "total task is :{0}",new String[]{ taskReelCount+""},"");
}
public ORDER_COLOR getNextColor() {
//设置颜色
Set<String> currentColors = new HashSet<>();
for (DataLog dataLog :taskService. getQueueTasks()) {
currentColors.add(dataLog.getLightColor());
}
ORDER_COLOR nextColor = ORDER_COLOR.nextColor(currentColors);
return nextColor;
}
/**
* 防止仓位任务重复,需要排除掉已经分配掉的出库仓位
*/
public Collection<String> excludeOutPosIds() {
//排除掉正在执行的仓位
List<DataLog> allTasks = taskService.getAllTasks();
Collection<String> operatingPosIds = new HashSet<>();
for (DataLog task : allTasks) {
if(task.isCheckOutTask()){
String posId = task.getPosId();
if (!Strings.isNullOrEmpty(posId)) {
operatingPosIds.add(task.getPosId());
}
}
}
return operatingPosIds;
}
/**
* 结束当前的任务
*/
public void finishedOrderTasks(LiteOrder liteOrder){
if(liteOrder.isOutOne()){
// setStatus(LITEORDER_STATUS.ONE_FINISHED);
liteOrder.setClosed(true);
}else if(liteOrder.isOutBom()){
liteOrder.setStatus(LITEORDER_STATUS.BOM_FINISHED);
}else if(liteOrder.isOutTails()){
// setStatus(LITEORDER_STATUS.TAILS_FINISHED);
liteOrder.setClosed(true);
}
liteOrder.setTaskFinishedTime(System.currentTimeMillis());
smfApi.onOrderStatusChange(liteOrder);
}
private DataLog newTask(StoragePos pos) {
Storage storage = dataCache.getStorageById(pos.getStorageId());
DataLog task = new DataLog(storage,pos.getBarcode(),pos);
String operator = SecurityUtils.getLoginUsername();
task.setOperator(operator);
return task;
}
}
...@@ -2,11 +2,13 @@ server: ...@@ -2,11 +2,13 @@ server:
port: 8800 port: 8800
api: api:
name: SO21476 name:
inCheckUrl: D:\remain\ inCheckUrl:
outNotifyUrl: outNotifyUrl:
inNotifyUrl: inNotifyUrl:
hella: hella:
#host: 127.0.0.1 #host: 127.0.0.1
#port: 3333 #port: 3333
...@@ -50,5 +52,6 @@ menu: ...@@ -50,5 +52,6 @@ menu:
smd: smd:
filePath: filePath:
userName:
password:
\ No newline at end of file \ No newline at end of file
userName :
password :
url:
\ No newline at end of file \ No newline at end of file
支持 Markdown 格式
你添加了 0 到此讨论。请谨慎行事。
Finish editing this message first!