标签:ted timestamp 目录 bat import contains 文件名 tabs constant
package com.cfets.ts.u.shchgateway.util; import imix.Message; import java.io.BufferedOutputStream; import java.io.BufferedReader; import java.io.File; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStreamReader; import java.io.OutputStream; import java.io.PrintWriter; import java.math.BigDecimal; import java.nio.charset.Charset; import java.util.ArrayList; import java.util.Date; import java.util.List; import java.util.Properties; import java.util.zip.ZipEntry; import java.util.zip.ZipOutputStream; import org.apache.commons.collections.CollectionUtils; import org.apache.commons.compress.utils.IOUtils; import org.apache.commons.lang3.StringUtils; import com.cfets.cwap.s.spi.SpiConfig; import com.cfets.cwap.s.util.DateUtil; import com.cfets.ts.s.dealcommon.api.bean.CfclDeal; import com.cfets.ts.s.dealcommon.api.bean.CfclDeal.CfclBondInfo; import com.cfets.ts.s.log.TsLogger; import com.cfets.ts.u.shchgateway.constant.Constants; import com.cfets.ts.u.shchgateway.handler.CfclBondDataConverter; import com.jcraft.jsch.Channel; import com.jcraft.jsch.ChannelSftp; import com.jcraft.jsch.JSch; import com.jcraft.jsch.Session; import com.jcraft.jsch.SftpATTRS; import com.jcraft.jsch.SftpException; public class SftpUtils { private static final TsLogger logger = TsLogger.getLogger(SftpUtils.class); private String TAG = "SFTPUtils"; private String host = null; private String username = null; private String password = null; private int port = 22; private ChannelSftp sftp = null; private String localPath = ""; private String remotePath = ""; private String tempPath = ""; private String fileNameTemp = null; // 文件名 private String remote = ""; private String masterRemote = ""; private String masterhost = null; private String masterUsername = null; private String masterPassword = null; private int masterPort = 22; public static final String LINE_SEPARATOR = "line.separator"; public static final String ENCODING_UTF8 = "UTF-8"; // 存放生成的Imix文件,上传结束自动删除 public SftpUtils() { this.remote = SpiConfig.getPropValue("ts.shchgateway.remote"); this.host = SpiConfig.getPropValue("ts.shchgateway.host"); this.username = SpiConfig.getPropValue("ts.shchgateway.username"); this.password = SpiConfig.getPropValue("ts.shchgateway.password"); this.port = Integer.parseInt(SpiConfig.getPropValue("ts.shchgateway.port")); this.remotePath = SpiConfig.getPropValue("ts.shchgateway.remotePath"); // shch this.masterhost = SpiConfig.getPropValue("ts.shchgatewaymaster.host"); this.masterUsername = SpiConfig.getPropValue("ts.shchgatewaymaster.username"); this.masterPassword = SpiConfig.getPropValue("ts.shchgatewaymaster.password"); this.masterPort = Integer.parseInt(SpiConfig.getPropValue("ts.shchgatewaymaster.port")); this.masterRemote = SpiConfig.getPropValue("ts.shchgatewaymaster.remote"); } public SftpUtils(String host, int port, String username, String password, String remote, String tempPath) { this.host = host; this.username = username; this.password = password; this.remote = remote; this.tempPath = tempPath; this.port = port; } /** * connect server via sftp */ public void connectServer() { try { if (sftp != null) { System.out.println("sftp is not null"); } JSch jsch = new JSch(); jsch.getSession(masterUsername, masterhost, port); Session sshSession = jsch.getSession(masterUsername, masterhost, masterPort); logger.info("Session created."); sshSession.setPassword(masterPassword); Properties sshConfig = new Properties(); sshConfig.put("StrictHostKeyChecking", "no"); sshSession.setConfig(sshConfig); sshSession.connect(); logger.info("Session connected."); logger.info("Opening Channel."); Channel channel = sshSession.openChannel("sftp"); channel.connect(); sftp = (ChannelSftp) channel; logger.info("Connected to " + masterhost + "."); } catch (Exception e) { logger.error(e); } } public boolean createDir(String createpath) { try { if (isDirExist(createpath)) { this.sftp.cd(createpath); logger.debug(TAG, createpath); return true; } String pathArry[] = createpath.split("/"); StringBuffer filePath = new StringBuffer("/"); for (String path : pathArry) { if (path.equals("")) { continue; } filePath.append(path + "/"); createpath = filePath.toString(); if (isDirExist(createpath)) { sftp.cd(createpath); } else { sftp.mkdir(createpath); sftp.cd(createpath); } } this.sftp.cd(createpath); return true; } catch (SftpException e) { e.printStackTrace(); } return false; } /** * 判断目录是否存在 * * @param directory * @return */ public boolean isDirExist(String directory) { boolean isDirExistFlag = false; try { SftpATTRS sftpATTRS = sftp.lstat(directory); isDirExistFlag = true; return sftpATTRS.isDir(); } catch (Exception e) { if (e.getMessage().toLowerCase().equals("no such file")) { isDirExistFlag = false; } } return isDirExistFlag; } public void deleteSFTP(String directory, String deleteFile) { try { sftp.cd(directory); sftp.rm(deleteFile); } catch (Exception e) { e.printStackTrace(); } } /** * 创建目录 * * @param path */ public void mkdirs(String path) { File f = new File(path); String fs = f.getParent(); f = new File(fs); if (!f.exists()) { f.mkdirs(); } } /* * public SFTPUtil(){ this.host = "172.17.192.28"; this.username = "ts"; * this.password = "ts"; this.port = 22; this.remotePath = * "/opt/shchrepo/ts-u-shchgateway/ihub/"; } */ /** * connect server via sftp */ public void connect() { try { if (sftp != null) { System.out.println("sftp is not null"); } JSch jsch = new JSch(); jsch.getSession(username, host, port); Session sshSession = jsch.getSession(username, host, port); System.out.println("Session created."); sshSession.setPassword(password); Properties sshConfig = new Properties(); sshConfig.put("StrictHostKeyChecking", "no"); sshSession.setConfig(sshConfig); sshSession.connect(); System.out.println("Session connected."); System.out.println("Opening Channel."); Channel channel = sshSession.openChannel("sftp"); channel.connect(); sftp = (ChannelSftp) channel; System.out.println("Connected to " + host + "."); } catch (Exception e) { // e.printStackTrace(); logger.error(e); } } /** * Disconnect with server */ public void disconnect() { if (this.sftp != null) { this.sftp.disconnect(); /* * if(this.sftp.isConnected()){ }else if(this.sftp.isClosed()){ * System.out.println("sftp is closed already"); } */ } } public void download() { // TODO Auto-generated method stub } private void download(String directory, String downloadFile, String saveFile, ChannelSftp sftp) { try { sftp.cd(directory); File file = new File(saveFile); sftp.get(downloadFile, new FileOutputStream(file)); } catch (Exception e) { // e.printStackTrace(); logger.error(e); } } /** * create Directory * * @param filepath * @param sftp */ private void createDir(String filepath, ChannelSftp sftp) { boolean bcreated = false; boolean bparent = false; File file = new File(filepath); String ppath = file.getParent(); try { this.sftp.cd(ppath); bparent = true; } catch (SftpException e1) { bparent = false; } try { if (bparent) { try { this.sftp.cd(filepath); bcreated = true; } catch (Exception e) { bcreated = false; } if (!bcreated) { this.sftp.mkdir(filepath); bcreated = true; } return; } else { createDir(ppath, sftp); this.sftp.cd(ppath); this.sftp.mkdir(filepath); } } catch (SftpException e) { System.out.println("mkdir failed :" + filepath); e.printStackTrace(); } try { this.sftp.cd(filepath); } catch (SftpException e) { e.printStackTrace(); System.out.println("can not cd into :" + filepath); } } /** * * @Title: generateTxtFile * @Description: 本地服务器生成临时Imix文件 * @param @param deal * @return void * @throws */ public static void generateTxtFile(CfclDeal deal) { try { SftpUtils sftp = new SftpUtils(); String fileName = SftpUtils.getFileName(deal.getCltrlMthd(), deal.getDlCd(), new Date()); new SftpUtils().creatTxtFile(fileName); String context = CfclBondDataConverter.convertObjectToImix(deal).toString(); sftp.writeTxtFile(context); } catch (IOException e) { logger.error("sftp 上传上清所服务器失败", e); } } /** * * @Title: uploadFile * @Description: 单个文件上传 * @param @param remotePath * @param @param remoteFileName * @param @return * @return boolean * @throws */ public boolean uploadFile(String remotePath, CfclDeal cfcl) { long startTime = new Date().getTime(); logger.info("FXREPO-BOND 远程服务器路径:{}, 单文件上传开始:{}", remotePath, cfcl.getDlCd()); SftpUtils sftpUtils = null; ChannelSftp sftp = null; BufferedOutputStream bos = null; try { sftpUtils = new SftpUtils(); sftpUtils.connectShchServer(); sftp = sftpUtils.getSftp(); if (sftp == null) { logger.warn("SHCH SFTP连接对象未获取到, {} 不上传", cfcl.getDlCd()); return false; } Message message = CfclBondDataConverter.convertObjectToImix(cfcl); String fileName = SftpUtils.getFileName(cfcl.getCltrlMthd(), cfcl.getDlCd(), new Date()); if (StringUtils.isEmpty(fileName)) { logger.warn("{} 上传的文件名为空, 不上传", cfcl.getDlCd()); return false; } OutputStream os = sftp.put(masterRemote + fileName); bos = new BufferedOutputStream(os); byte[] bt = (message.toString() + System.getProperty(SftpUtils.LINE_SEPARATOR)).getBytes(Charset .forName(SftpUtils.ENCODING_UTF8)); os.write(bt); bos.flush(); long endTime = new Date().getTime(); logger.info("上传 {} 文件 耗时{}ms", cfcl.getDlCd(), endTime - startTime); logger.info("FXREPO-BOND 远程服务器路径:{}, 单文件上传结束:{}", remotePath, cfcl.getDlCd()); return true; } catch (Exception e) { logger.error("FXREPO-BOND 单文件上传报错:{}", e, cfcl.getDlCd()); return false; } finally { IOUtils.closeQuietly(bos); sftpUtils.disconnect(); } } /** * * @Title: batchUploadFile * @Description: 批量上传 * @param @param remotePath * @param @param list * @param @return * @throws */ public boolean batchUploadFile(String remotePath, List<CfclDeal> list) { long startTime = new Date().getTime(); logger.info("FXREPO-BOND 远程服务器路径:{}, 批量文件上传开始", remotePath); SftpUtils sftpUtils = null; ChannelSftp sftp = null; BufferedOutputStream bos = null; ZipOutputStream zos = null; try { sftpUtils = new SftpUtils(); sftpUtils.connectShchServer(); sftp = sftpUtils.getSftp(); if (sftp == null) { logger.warn("SHCH SFTP连接对象未获取到, 不上传"); return false; } if (CollectionUtils.isEmpty(list)) { logger.warn("没有待打包上传的交易,不上传"); return false; } String zipFileName = ZipUtils.getZipFileName(); if (StringUtils.isEmpty(zipFileName)) { logger.warn("{} 上传的压缩文件名为空, 不上传"); return false; } List<String> nameList = new ArrayList<String>(); OutputStream os = sftp.put(masterRemote + zipFileName); bos = new BufferedOutputStream(os); zos = new ZipOutputStream(bos, Charset.forName(SftpUtils.ENCODING_UTF8)); for (CfclDeal cfclDeal : list) { Date currentDate = DateUtil.getCurrentDate(); String imixFileName = SftpUtils.getFileName(cfclDeal.getCltrlMthd(), cfclDeal.getDlCd(), currentDate); if (nameList.contains(imixFileName)) { // TXT文件名重复则+1秒重新生成 Date incrementTime = DateUtils.addSecond(currentDate, 1); imixFileName = SftpUtils.getFileName(cfclDeal.getCltrlMthd(), cfclDeal.getDlCd(), incrementTime); nameList.add(imixFileName); } else { // 添加文件名 nameList.add(imixFileName); } Message message = CfclBondDataConverter.convertObjectToImix(cfclDeal); byte[] bt = (message.toString() + System.getProperty(SftpUtils.LINE_SEPARATOR)).getBytes(Charset .forName(SftpUtils.ENCODING_UTF8)); ZipEntry zipEntry = new ZipEntry(imixFileName); zos.putNextEntry(zipEntry); zos.write(bt); zos.closeEntry(); } zos.flush(); long endTime = new Date().getTime(); logger.info("上传压缩文件耗时{}ms", endTime - startTime); logger.info("FXREPO-BOND 远程服务器路径:{}, 批量文件上传结束", remotePath); return true; } catch (Exception e) { logger.error("FXREPO-BOND 上传压缩文件报错:", e); return false; } finally { IOUtils.closeQuietly(zos); IOUtils.closeQuietly(bos); sftpUtils.disconnect(); } } /** * * @Title: getFileName * @Description: 获取txt文件名称 * @param @param collateralMethod * @param @param dealCode * @param @param current * @param @return * @return String * @throws */ public static String getFileName(String collateralMethod, String dealCode, Date current) { String time1 = DateUtils.formatDate(current, "yyyy-MM-dd HH:mm:ss").replaceAll("-", "").replaceAll(" ", "") .replaceAll(":", ""); // 买断式 if (Constants.FXREPO_PLEDGED.equals(collateralMethod)) { return "FXREPO_Outright_SCH_" + time1 + "_" + dealCode + ".txt"; } else if (Constants.FXREPO_OUTRIGHT.equals(collateralMethod)) { // 质押式 return "FXREPO_Pledged_SCH_" + time1 + "_" + dealCode + ".txt"; } else { // do nothing return ""; } } public boolean creatTxtFile(String name) { boolean flag = false; fileNameTemp = tempPath + name + ".txt"; File fileName = new File(fileNameTemp); if (!fileName.exists()) { try { fileName.createNewFile(); logger.info("创建imix文件成功"); } catch (IOException e) { logger.error("创建TXT文件失败", e); } flag = true; } return flag; } public boolean writeTxtFile(String context) throws IOException { boolean flag = false; String fileIn = context + "\r\n"; String temp = ""; FileInputStream input = null; InputStreamReader isr = null; BufferedReader br = null; FileOutputStream outPut = null; PrintWriter pw = null; try { File file = new File(fileNameTemp); input = new FileInputStream(file); isr = new InputStreamReader(input); br = new BufferedReader(isr); StringBuffer sb = new StringBuffer(); // 保存该文件原有的内容 for (int i = 1; (temp = br.readLine()) != null; i++) { sb = sb.append(temp); sb = sb.append(System.getProperty("line.separator")); } sb.append(fileIn); outPut = new FileOutputStream(file); pw = new PrintWriter(outPut); pw.write(sb.toString().toCharArray()); pw.flush(); flag = true; logger.info("imix 文件写入成功"); } catch (IOException e) { logger.error("imix 文件写入失败", e); } finally { if (pw != null) { pw.close(); } if (outPut != null) { outPut.close(); } if (br != null) { br.close(); } if (isr != null) { isr.close(); } if (input != null) { input.close(); } } return flag; } /** * 删除文件 * * @param filePath * @return */ public boolean deleteFile(String filePath) { File file = new File(filePath); if (!file.exists()) { return false; } if (!file.isFile()) { return false; } return file.delete(); } /** * @return the host */ public String getHost() { return host; } /** * @param host * the host to set */ public void setHost(String host) { this.host = host; } /** * @return the username */ public String getUsername() { return username; } public String getRemote() { return remote; } public void setRemote(String remote) { this.remote = remote; } /** * @param username * the username to set */ public void setUsername(String username) { this.username = username; } /** * @return the password */ public String getPassword() { return password; } /** * @param password * the password to set */ public void setPassword(String password) { this.password = password; } /** * @return the port */ public int getPort() { return port; } /** * @param port * the port to set */ public void setPort(int port) { this.port = port; } /** * @return the sftp */ public ChannelSftp getSftp() { return sftp; } public String getMasterRemote() { return masterRemote; } public void setMasterRemote(String masterRemote) { this.masterRemote = masterRemote; } /** * @param sftp * the sftp to set */ public void setSftp(ChannelSftp sftp) { this.sftp = sftp; } /** * @return the localPath */ public String getLocalPath() { return localPath; } public String getMasterhost() { return masterhost; } public void setMasterhost(String masterhost) { this.masterhost = masterhost; } public String getMasterUsername() { return masterUsername; } public void setMasterUsername(String masterUsername) { this.masterUsername = masterUsername; } public String getMasterPassword() { return masterPassword; } public void setMasterPassword(String masterPassword) { this.masterPassword = masterPassword; } public int getMasterPort() { return masterPort; } public void setMasterPort(int masterPort) { this.masterPort = masterPort; } /** * @param localPath * the localPath to set */ public void setLocalPath(String localPath) { this.localPath = localPath; } /** * @return the remotePath */ public String getRemotePath() { return remotePath; } /** * @param remotePath * the remotePath to set */ public void setRemotePath(String remotePath) { this.remotePath = remotePath; } public String getTempPath() { return tempPath; } public void setTempPath(String tempPath) { this.tempPath = tempPath; } public String getFileNameTemp() { return fileNameTemp; } public void setFileNameTemp(String fileNameTemp) { this.fileNameTemp = fileNameTemp; } /** * @return the fileListPath */ public void uploadFile(String localFileStr, String remoteFileName) throws Exception { try { this.connectShchServer(); File file = new File(localFileStr); if (file.isFile()) { System.out.println("localFile : " + file.getAbsolutePath()); String remoteFile = this.remotePath + remoteFileName; System.out.println("remotePath:" + remoteFile); System.out.println(file.getName()); this.sftp.put(new FileInputStream(file), remoteFile); System.out.println("=========upload down for " + localFileStr); } } catch (SftpException e) { logger.error("SFTP上传文件异常SftpException", e); } catch (FileNotFoundException e) { logger.error("SFTP上传文件异常FileNotFoundException", e); } } public void uploadFile(String localFileStr) throws Exception { try { this.connectShchServer(); File file = new File(localFileStr); if (file.isFile()) { System.out.println("localFile : " + file.getAbsolutePath()); String remoteFile = this.remotePath + file.getName(); System.out.println("remotePath:" + remoteFile); this.sftp.put(new FileInputStream(file), remoteFile); System.out.println("=========upload down for " + localFileStr); } } catch (SftpException e) { logger.error("SFTP上传文件异常SftpException", e); } catch (FileNotFoundException e) { logger.error("SFTP上传文件异常FileNotFoundException", e); } } public static void main(String[] args) throws Exception { CfclDeal cfcl = new CfclDeal(); cfcl.setDlCd("6.8.0020202"); cfcl.setDlSt("0"); cfcl.setTxnDt(new Date()); cfcl.setMkrBondDpstAcntNo("PPPPPP"); cfcl.setCnShrtNm("美国"); cfcl.setDlTm(new java.sql.Timestamp(new Date().getTime())); cfcl.setLndngCcy("USD"); cfcl.setOfrdRate(new BigDecimal(7.9)); cfcl.setMrtyAmnt(new BigDecimal(5000)); cfcl.setVlDt(new Date()); cfcl.setLndngAmnt(new BigDecimal(10000)); cfcl.setMrtyDt(new Date()); List<CfclBondInfo> list = new ArrayList<CfclBondInfo>(); CfclBondInfo info = new CfclBondInfo(); info.setBondCd("010011"); info.setPldgdBndsNmnlVol(new BigDecimal(25000000)); CfclBondInfo info2 = new CfclBondInfo(); info2.setBondCd("010011"); info2.setPldgdBndsNmnlVol(new BigDecimal(256000000)); CfclBondInfo info3 = new CfclBondInfo(); info3.setBondCd("1010011"); info3.setPldgdBndsNmnlVol(new BigDecimal(27000000)); list.add(info); list.add(info2); list.add(info3); cfcl.setInfo(list); // 发起方为正回购 cfcl.setDir("S"); cfcl.setTkrInstnCnShrtNm("工商银行2"); cfcl.setTkrDcOpngBnkNm("CICBC-USD-zq001"); cfcl.setTkrDcOpngBnkBicCd("ICBC-USD-zq001"); cfcl.setTkrDcOpngBnkAcntNo("ICBC0USD005"); cfcl.setTkrDcBnfcryBnkNm("ICBC-USD-zq003"); cfcl.setTkrDcBnfcryBnkBicCd("ICBC0USD00522"); cfcl.setTkrDcBnfcryBnkAcntNo("ICBC0CNY005"); cfcl.setMkrDcOpngBnkNm("ICBC-USD-zq004"); cfcl.setMkrDcOpngBnkBicCd("YYYYY"); cfcl.setMkrDcOpngBnkAcntNo("USD-zq001"); cfcl.setMkrDcBnfcryBnkNm("zhongguoyinghang"); cfcl.setMkrDcBnfcryBnkBicCd("dddd"); cfcl.setMkrDcBnfcryBnkAcntNo("855"); cfcl.setTkrBondDpstAcntNo("111"); cfcl.setMkrBondDpstAcntNo("555"); cfcl.setFrstStlmntWay("4"); cfcl.setStlmntMthdToMrty("0"); cfcl.setCltrlMthd("1"); // SftpUtils.creatTxtFile(getFileName("2", "6.2832145")); // writeTxtFile(CfclDataTransfer.convertObjectToImix(cfcl).toString()); // SftpUtils sftp = new SftpUtils("199.31.224.13", 22, "support", // "splinux"); // sftp.connect(); // String fileName = getFileName(cfcl.getCltrlMthd(), cfcl.getDlCd()); // new SftpUtils().creatTxtFile(fileName); // String context = // CfclBondDataTransfer.convertObjectToImix(cfcl).toString(); // new SftpUtils().writeTxtFile(context); // sftp.uploadFile("/home/support/a", "imix.txt", "C:\\", "imix.txt"); // sftp.bacthUploadFile("/home/support/a", "C:\\imix\\", false); // sftp.disconnect(); new SftpUtils().createDir("C:/aa/bb"); } }
标签:ted timestamp 目录 bat import contains 文件名 tabs constant
原文地址:https://www.cnblogs.com/lhl-shubiao/p/11870174.html