You cannot select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

517 lines
18 KiB
Java

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Properties;
import org.apache.log4j.Logger;
import org.apache.log4j.PropertyConfigurator;
import org.json.simple.JSONObject;
import com.jcraft.jsch.JSchException;
import com.jcraft.jsch.SftpException;
public class SendThread extends Thread {
private String[] g_strFTP = new String[6];
private String g_strTenel = "";
private final Logger logger = Logger.getLogger(SendThread.class);
@Override
public void run() {
runCarNoImageSend();
this.logger.debug(String.format("=======================================================", new Object[0]));
}
public SendThread(String str) {
PropertyConfigurator.configure("./log4j.properties");
try {
String propFile = "./config.properties";
Properties props = new Properties();
FileInputStream fis = new FileInputStream(propFile);
props.load(new BufferedInputStream(fis));
this.g_strFTP[0] = props.getProperty("path_org");
this.g_strFTP[1] = props.getProperty("ftp_ip");
this.g_strFTP[2] = props.getProperty("ftp_id");
this.g_strFTP[3] = props.getProperty("ftp_pw");
this.g_strFTP[4] = props.getProperty("api_url");
this.g_strFTP[5] = props.getProperty("path_desc");
this.g_strTenel = props.getProperty("tennel_no");
Calendar cal = Calendar.getInstance();
int date = cal.get(5);
this.g_strFTP[0] = String.format("%s/%02d/%s/", new Object[] { this.g_strFTP[0], Integer.valueOf(date), str });
this.logger.info("=== g_strFTP[0] : " + this.g_strFTP[0]);
props.clear();
props = null;
} catch (Exception e) {
this.logger.info("Exception : " + e);
}
}
public void findFileList(String source, List<String> list) {
File dir = new File(source);
File[] fileList = dir.listFiles();
if (fileList == null) {
this.logger.debug("======== 12.5 :::" + source);
return;
}
int cnt = 10;
if (fileList.length < cnt)
cnt = fileList.length;
for (int i = 0; i < cnt; i++) {
File file = fileList[i];
if (file.isFile()) {
String tempFileName = file.getName();
if (tempFileName.toLowerCase().endsWith(".jpg")) {
list.add(tempFileName);
this.logger.info("=== = " + file.getName());
}
} else if (file.isDirectory()) {
this.logger.debug("디렉토리 이름 = " + file.getName());
}
}
}
private String transFileName(String strOrgFile, JSONObject jsonParam, Map<String, String> mapDefault) {
Map<String, String> cctvID = new HashMap<>();
cctvID.put("101", "A10401001");
cctvID.put("102", "A10301002");
cctvID.put("103", "A10201003");
cctvID.put("104", "A10101004");
cctvID.put("105", "A10111005");
cctvID.put("106", "A10211006");
cctvID.put("107", "A10311007");
cctvID.put("108", "A10411008");
cctvID.put("301", "A10503001");
cctvID.put("302", "A10403002");
cctvID.put("303", "A10303003");
cctvID.put("304", "A10203004");
cctvID.put("305", "폐쇄차로");
cctvID.put("306", "폐쇄차로");
cctvID.put("307", "A10213005");
cctvID.put("308", "A10313006");
cctvID.put("309", "A10413007");
cctvID.put("310", "A10513008");
String[] strarr = strOrgFile.split("_");
String tennel = strarr[3].substring(0, 1); //터널
String line = strarr[3].substring(1, 3); //차로
String dirc = strarr[3].substring(3); //진행방향
dirc = cctvID.get(String.valueOf(tennel) + line); //덧씌움
this.logger.debug("=============================X : " + dirc);
dirc = dirc.substring(dirc.length() - 1);
this.logger.debug("============================= Y : " + dirc);
Map<String, String> mapDic = new HashMap<>(); //1~8
mapDic.put("1", "0");
mapDic.put("2", "0");
mapDic.put("3", "0");
mapDic.put("4", "0");
mapDic.put("5", "1");
mapDic.put("6", "1");
mapDic.put("7", "1");
mapDic.put("8", "1");
this.logger.debug("============================= Z : " + mapDic.get(dirc));
mapDefault.put(
"image_path_desc_center",
String.format(
" /images/ANPRImage/cfs/%s/0%s/%s/",
new Object[] { strarr[0].substring(0, 4), tennel, strarr[0] }
)
);
mapDefault.put("work_times", strarr[1]);
mapDefault.put("seqno", strarr[2]);
int n = Integer.parseInt(strarr[2].substring(6, 8));
if (n >= 40 && n < 50) { //미납관련?
mapDefault.put("collect_id", "40");
} else if (n >= 60 && n < 70) { //사전등록관련?
mapDefault.put("collect_id", "40");
} else {
mapDefault.put("collect_id", String.format("%02d", new Object[] { Integer.valueOf(n) }));
}
String strRate = "95";
String strCarNo = MakeCarNoHex2CarNo.makeCarNoHex2CarNo(strarr[4].trim());
if (strCarNo.contains("????") || strCarNo.contains("XXXX")) {
strRate = "0";
this.logger.debug("=== strCarNo : " + strCarNo + ", " + strarr[4].trim());
}
jsonParam.put("camId" , cctvID.get(String.valueOf(tennel) + line));
jsonParam.put("pasageTime" , String.valueOf(strarr[0]) + strarr[1].substring(0, 6));
jsonParam.put("vhcleNum" , strCarNo);
jsonParam.put("vhcleKnd" , strarr[5].substring(0, 1)); //차종
jsonParam.put("vhcleColor" , "0"); //차량색상정보 그냥 0
jsonParam.put("allImagePath" , "./car_img/");
jsonParam.put("vhcleImagePath" , "");
jsonParam.put("nopltImagePath" , "");
jsonParam.put("inputKnd" , "");
jsonParam.put("vhcleDrc" , mapDic.get(dirc));
jsonParam.put("recogCnfdncRate", strRate); //인식신뢰도
jsonParam.put("tfclneInfo" , line);
jsonParam.put("recogReqreTime" , "000000");
jsonParam.put("regltTrgetSe" , "20");
jsonParam.put("boothId" , line);
jsonParam.put("fareId" , "0" + tennel);
StringBuilder pathOrg = new StringBuilder();
pathOrg.append(this.g_strFTP[0]);
StringBuilder path = new StringBuilder();
path.append(this.g_strFTP[5]);path.append("/");
path.append(strarr[0].substring(0, 4));
path.append("/");
path.append(strarr[0].substring(4, 6));
path.append("/");
path.append(strarr[0].substring(6, 8));
path.append("/");
path.append(cctvID.get(String.valueOf(tennel) + line));
path.append("/");
path.append(strarr[1].substring(0, 2));
path.append("/");
StringBuilder strbuf = new StringBuilder();
strbuf.append("2");
if (tennel.equals("1")) {
strbuf.append("NO");
} else if (tennel.equals("3")) {
strbuf.append("NT");
} else {
return null;
}
strbuf.append("TT");
strbuf.append("C");
strbuf.append("_");
strbuf.append(cctvID.get(String.valueOf(tennel) + line));
strbuf.append("_");
strbuf.append(strarr[0]);
strbuf.append("_");
strbuf.append(strarr[1]);
strbuf.append("_");
strbuf.append(strarr[2]);
strbuf.append(".jpg");
mapDefault.put("image_file_new2",
String.format(
"0%s%s%s%sS.JPG",
new Object[] { tennel, line, strarr[0], strarr[1].substring(0, 6) }
)
);
mapDefault.put("image_path", pathOrg.toString());
mapDefault.put("image_file", strOrgFile);
this.logger.debug("=== pathOrg.toString() : " + pathOrg.toString());
this.logger.debug("=== path.toString() : " + path.toString());
this.logger.debug("=== strbuf.toString() : " + strbuf.toString());
jsonParam.put("allImagePath",
String.format(
"%s%s",
new Object[] {
path.toString().replace(String.valueOf(this.g_strFTP[5]) + "/", ""), strbuf.toString()
}
)
);
this.logger.debug("=== : " + jsonParam.toJSONString());
return String.valueOf(pathOrg.toString())
+ "#" + path.toString() + "#" + strbuf.toString()
+ "#" + line;
}
//연계api호출
private int callAnprCarnoSend(String strJson) {
int nResult = 0;
HttpURLConnection connection = null;
InputStream is = null;
InputStreamReader isr = null;
BufferedReader br = null;
try {
URL url = new URL(this.g_strFTP[4]);
this.logger.info("==== 대외연계서버 주소 + 녹색과태료 API URL : " + this.g_strFTP[4]);
connection = (HttpURLConnection)url.openConnection();
connection.setDoInput(true);
connection.setDoOutput(true);
connection.setUseCaches(false);
connection.setRequestMethod("POST");
connection.setConnectTimeout(30000);
connection.setReadTimeout(30000);
connection.setRequestProperty("Accept", "application/json");
connection.setRequestProperty("Content-Type", "application/json");
BufferedOutputStream bos = new BufferedOutputStream(connection.getOutputStream());
bos.write(strJson.getBytes("UTF-8"));
bos.flush();
bos.close();
int resCode = connection.getResponseCode();
StringBuffer sb = new StringBuffer();
String inputLine = null;
this.logger.info("==== : " + resCode);
if (resCode == 200) {
is = connection.getInputStream();
isr = new InputStreamReader(is, "UTF-8");
br = new BufferedReader(isr);
while ((inputLine = br.readLine()) != null)
sb.append(inputLine);
this.logger.info("==== " + sb.toString());
} else if (connection.getErrorStream() != null) {
br = new BufferedReader(new InputStreamReader(connection.getErrorStream(), "UTF-8"));
while ((inputLine = br.readLine()) != null)
sb.append(inputLine);
this.logger.info("==== Http Error Resopnse : " + sb.toString());
nResult = -1;
} else {
this.logger.info("==== Http Error Resopnse : " + sb.toString());
nResult = -1;
}
} catch (Exception e) {
this.logger.info("Exception : " + e);
this.logger.info("==== Http Error Resopnse : ");
nResult = -1;
} finally {
try {
if (is != null) {
is.close();
}
if (isr != null) {
isr.close();
}
if (br != null) {
br.close();
}
} catch (Exception exception) {
}
}
return nResult;
}
//차로갯수만큼 반복문 내에서 실행
//FTP업로드 후 연계API(차량번호 인식 정보 송신(차량번호,차종,차량색상,인식신뢰도 등))호출
public void runCarNoImageSend() {
List<String> list = new ArrayList<>();
String pathOrg = this.g_strFTP[0];
findFileList(pathOrg, list);
if (list.size() == 0) {
this.logger.debug("======== 21");
this.logger.debug("신규 이미지 없음");
return;
}
Map<String, String> mapNewTerminal = new HashMap<>();
mapNewTerminal.put("101", "new");
mapNewTerminal.put("102", "new");
mapNewTerminal.put("103", "new");
mapNewTerminal.put("104", "new");
mapNewTerminal.put("105", "new");
mapNewTerminal.put("106", "new");
mapNewTerminal.put("107", "new");
mapNewTerminal.put("108", "new");
mapNewTerminal.put("301", "new");
mapNewTerminal.put("302", "new");
mapNewTerminal.put("303", "new");
mapNewTerminal.put("304", "new");
mapNewTerminal.put("307", "new");
mapNewTerminal.put("308", "new");
mapNewTerminal.put("309", "new");
mapNewTerminal.put("310", "new");
Map<String, String> mapDefaultCar = new HashMap<>();
boolean isOk = false;
String strNewFile = "";
String[] strTargPath = null;
JSONObject jsonParam = new JSONObject();
FTPUtil sftp = new FTPUtil();
boolean sftpInitSuccess = sftp.init(this.g_strFTP[1], this.g_strFTP[2], this.g_strFTP[3]);
if(!sftpInitSuccess) {
return;
}
for (int i = 0; i < list.size(); i++) { //디렉토리 경로상에 현재 존재하는 JPG파일
mapDefaultCar.clear();
this.logger.debug("=== i : " + i + ", : " + list.get(i));
//
strNewFile = transFileName(list.get(i), jsonParam, mapDefaultCar);
if (strNewFile == null || strNewFile.equals("") || jsonParam.size() == 0) {
this.logger.debug("=== continue 1");
} else {
strTargPath = strNewFile.split("#");
this.logger.debug("===" + strTargPath[0]);
this.logger.debug("===" + strTargPath[1]);
this.logger.debug("===" + strTargPath[2]);
this.logger.debug("===" + strTargPath[3]);
File Folder = new File(String.valueOf(strTargPath[0]) + "send/");
if (!Folder.exists()) {
try {
Folder.mkdir();
this.logger.debug("폴더가 생성되었습니다.");
} catch (Exception e) {
e.getStackTrace();
}
} else {
this.logger.debug("이미 폴더가 생성되어 있습니다.");
}
File FolderErr = new File(String.valueOf(strTargPath[0]) + "error/");
if (!FolderErr.exists()) {
try {
FolderErr.mkdir();
this.logger.debug("폴더가 생성되었습니다.(error)");
} catch (Exception e) {
e.getStackTrace();
}
} else {
this.logger.debug("이미 폴더가 생성되어 있습니다.");
}
File file = new File(String.valueOf(strTargPath[0]) + list.get(i));
File fileNew = new File(String.valueOf(strTargPath[0]) + "send/" + list.get(i));
File fileErr = new File(String.valueOf(strTargPath[0]) + "error/" + list.get(i));
if (fileNew.exists()) {
fileNew.delete();
}
if (fileErr.exists()) {
fileErr.delete();
}
if(!sftpInitSuccess) {
file.renameTo(fileErr);
continue;
}
this.logger.debug("=== 3 : " + strTargPath[0]);
this.logger.debug("=== 4 : " + strTargPath[1]);
isOk = false;
try {
//SFTP 1-1
sftp.mkdir2(strTargPath[1].substring(1));
this.logger.debug("폴더가 생성되었습니다.");
} catch (Exception e) {
e.getStackTrace();
}
this.logger.debug(String.format("============= : 업로드 전 ", new Object[0]));
try {
//SFTP 1-2
sftp.upload(strTargPath[1], file, list.get(i), strTargPath[2]);
this.logger.debug(String.format("============= : 업로드 성공 ", new Object[0]));
isOk = true;
} catch (SftpException e) {
this.logger.info("=== Exception 1 : " + e);
} catch (IOException e) {
this.logger.info("=== Exception 2 : " + e);
} catch (JSchException e) {
this.logger.info("=== Exception 3 : " + e);
}
this.logger.debug(String.format("============= : 업로드 후 ", new Object[0]));
if (isOk) {
//연계api호출
int nResult = callAnprCarnoSend(jsonParam.toJSONString());
jsonParam.clear();
this.logger.debug(String.format("============= : 미납체크 전", new Object[0]));
String strTemp = String.valueOf(this.g_strTenel) + strTargPath[3];
if (mapNewTerminal.get(strTemp).equals("new")) {
this.logger.debug("============= : 미납여부 확인 후 : " + mapDefaultCar.get("collect_id"));
if (mapDefaultCar.get("collect_id").equals("40")) {
this.logger.debug(String.format("=== update param : %s, %s, %s", new Object[] { strTargPath[1], file, list.get(i), strTargPath[2] }));
this.logger.debug("==== 미납 수행 시작");
try {
//2번째FTP처리
DefaultCarCenter(strTargPath[3], file, mapDefaultCar);
} catch (SQLException e) {
this.logger.info("Exception : " + e);
}
this.logger.debug("==== 미납 수행 완료");
}
}
this.logger.debug(String.format("============= : 미납체크 후", new Object[0]));
if (file.exists()) {
if (nResult < 0) { //curl의 결과
file.renameTo(fileErr);
} else {
file.renameTo(fileNew);
}
}
if (file.exists()) {
file.renameTo(fileNew);
}
}
}
}
sftp.disconnect();
}
private void DefaultCarCenter(String strBoothId, File file, Map<String, String> map) throws SQLException {
FTPUtil sftp = new FTPUtil();
boolean initSuccess = sftp.init(this.g_strFTP[1], this.g_strFTP[2], this.g_strFTP[3]);
if(!initSuccess) {
return;
}
this.logger.debug("============ Center ftp connect");
try {
try {
sftp.mkdir2(map.get("image_path_desc_center").substring(1));
this.logger.debug("폴더가 생성되었습니다.");
} catch (Exception e) {
e.getStackTrace();
}
this.logger.debug("=== " + map.get("image_path_desc_center"));
this.logger.debug("=== image_file_new2 : " + map.get("image_file_new2"));
this.logger.info(String.format("============= : DefaultCarCenter 파일전송 전 ", new Object[0]));
this.logger.debug(String.format("=== update2 param : %s, %s, %s",
new Object[] { map.get("image_path_desc_center"), map.get("image_file"), map.get("image_file_new2") }));
sftp.upload2(map.get("image_path_desc_center").toString().trim(), file, map.get("image_file"), map.get("image_file_new2"));
this.logger.info(String.format("============= : DefaultCarCenter 파일전송 후 ", new Object[0]));
} catch (IOException e) {
e.printStackTrace();
this.logger.info("Exception : " + e);
} catch (SftpException e) {
e.printStackTrace();
this.logger.info("Exception : " + e);
} catch (JSchException e) {
e.printStackTrace();
} finally {
sftp.disconnect();
}
}
}