diff --git a/src/main/java/ebu7common/youhong/ai/csv/ReadCsvUtil.java b/src/main/java/ebu7common/youhong/ai/csv/ReadCsvUtil.java new file mode 100644 index 0000000..5567d6f --- /dev/null +++ b/src/main/java/ebu7common/youhong/ai/csv/ReadCsvUtil.java @@ -0,0 +1,70 @@ +package ebu7common.youhong.ai.csv; + +import aiyh.utils.excention.CustomerException; + +import java.io.*; +import java.util.ArrayList; +import java.util.List; +import java.util.regex.Matcher; +import java.util.regex.Pattern; + +/** + *

读取csv文件

+ * + *

create: 2022-11-23 17:19

+ * + * @author youHong.ai + */ + +public class ReadCsvUtil { + + + /** + *

读取csv文件数据

+ * + * @param path csv文件路径 + * @return csv文件shave + */ + public static List> readCsvFromPath(String path) { + try { + return readScvFromInputStream(new FileInputStream(path)); + } catch (FileNotFoundException e) { + throw new CustomerException("[读取CSV文件,插入数据时,读取文件异常]"); + } + } + + + /** + *

读取csv文件

+ * + * @param inputStream 文件流 + * @return csv文件 + */ + public static List> readScvFromInputStream(InputStream inputStream) { + List> tableInfo = new ArrayList<>(); + BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream)); + String[] fieldsArr = null; + String line = null; + try { + while ((line = reader.readLine()) != null) { + String str; + line += ","; + Pattern pCells = Pattern + .compile("(\"[^\"]*(\"{2})*[^\"]*\")*[^,]*,"); + Matcher mCells = pCells.matcher(line); + List cells = new ArrayList<>(); + while (mCells.find()) { + str = mCells.group(); + str = str.replaceAll( + "(?sm)\"?([^\"]*(\"{2})*[^\"]*)\"?.*,", "$1"); + str = str.replaceAll("(?sm)(\"(\"))", "$2"); + cells.add(str); + } + tableInfo.add(cells); + } + } catch (IOException e) { + throw new CustomerException("无法读取文件数据!", e); + } + return tableInfo; + } +} diff --git a/src/main/java/ebu7common/youhong/ai/csv/entity/CsvTable.java b/src/main/java/ebu7common/youhong/ai/csv/entity/CsvTable.java new file mode 100644 index 0000000..8e760f5 --- /dev/null +++ b/src/main/java/ebu7common/youhong/ai/csv/entity/CsvTable.java @@ -0,0 +1,128 @@ +package ebu7common.youhong.ai.csv.entity; + + +import lombok.Getter; +import lombok.Setter; +import lombok.ToString; + +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; +import java.util.Map; + +/** + *

csv表信息

+ * + *

create: 2022-11-23 17:19

+ * + * @author youHong.ai + */ + +@Setter +@Getter +@ToString +public class CsvTable { + + private List csvRows = new ArrayList<>(); + + private CsvTableHeard csvTableHeard; + + private int rowSize = 0; + + + public void setCsvTableHeard(CsvTableHeard csvTableHeard) { + this.csvTableHeard = csvTableHeard; + this.rowSize++; + + } + + public void addRow(CsvRow csvRow) { + csvRows.add(csvRow); + rowSize++; + } + + + /** + *

csv列数据

+ * + *

create: 2022-11-23 17:21

+ * + * @author youHong.ai + */ + + @Setter + @Getter + @ToString + static class CsvColumn { + + + } + + + /** + *

csv表行数据

+ * + *

create: 2022-11-23 17:21

+ * + * @author youHong.ai + */ + + @Setter + @Getter + @ToString + static class CsvRow { + private List csvColumns = new ArrayList<>(); + private int rowSize = 0; + + public void add(CsvColumn csvColumn) { + csvColumns.add(csvColumn); + rowSize++; + } + + + } + + + /** + *

csv表头数据

+ * + *

create: 2022-11-23 17:21

+ * + * @author youHong.ai + */ + @ToString + static class CsvTableHeard { + private List heard; + + private Map mapping; + + private int heardSize = 0; + + public void addHeard(String value) { + if (heard == null) { + this.heard = new ArrayList<>(); + this.mapping = new HashMap<>(); + } + mapping.put(value, heardSize++); + heard.add(value); + } + + public int getHeardRow(String value) { + if (mapping != null) { + return mapping.get(value); + } + return -1; + } + + public String getHeard(int columnIndex) { + if (heard != null) { + return this.heard.get(columnIndex); + } + return null; + } + + } + + +} + diff --git a/src/main/java/ebu7common/youhong/ai/sftp/SftpConnectUtil.java b/src/main/java/ebu7common/youhong/ai/sftp/SftpConnectUtil.java index 3395123..4422314 100644 --- a/src/main/java/ebu7common/youhong/ai/sftp/SftpConnectUtil.java +++ b/src/main/java/ebu7common/youhong/ai/sftp/SftpConnectUtil.java @@ -1,15 +1,18 @@ package ebu7common.youhong.ai.sftp; +import aiyh.utils.Util; import aiyh.utils.excention.CustomerException; import com.jcraft.jsch.*; import lombok.Getter; import lombok.NoArgsConstructor; +import weaver.general.GCONST; -import java.io.IOException; -import java.io.InputStream; -import java.io.OutputStream; +import java.io.*; +import java.nio.file.Files; +import java.nio.file.Paths; import java.util.Hashtable; import java.util.Properties; +import java.util.UUID; import java.util.Vector; /** @@ -68,8 +71,16 @@ public class SftpConnectUtil extends ChannelSftp { private Integer sftpTimeOut; - public SftpConnectUtil(String userName, String prvKeyFilePath,String password, String sftpIp, - Integer port, Integer sftpTimeOut) { + /** + * @param userName 用户姓名 + * @param prvKeyFilePath 密钥文件地址 + * @param password 密码 (密钥文件随便传递一个) + * @param sftpIp 链接ip地址 + * @param port 端口 + * @param sftpTimeOut 超时时间 + * @author youHong.ai + */ + public SftpConnectUtil(String userName, String prvKeyFilePath, String password, String sftpIp, Integer port, Integer sftpTimeOut) { this.userName = userName; this.prvKeyFilePath = prvKeyFilePath; this.sftpIp = sftpIp; @@ -86,8 +97,7 @@ public class SftpConnectUtil extends ChannelSftp { * @author youHong.ai */ - private void login() { - + private void login() { JSch jSch = new JSch(); try { if (prvKeyFilePath != null && !"".equals(prvKeyFilePath)) { @@ -97,7 +107,7 @@ public class SftpConnectUtil extends ChannelSftp { jSch.addIdentity(prvKeyFilePath); } } else { - throw new RuntimeException("从sftp下载需要的ppk文件未找到"); + throw new RuntimeException("从sftp下载需要的ppk/pem文件未找到"); } if (port != null && port > 0) { this.session = jSch.getSession(userName, sftpIp, port); @@ -114,10 +124,153 @@ public class SftpConnectUtil extends ChannelSftp { this.sftp = (ChannelSftp) channel; this.success = true; } catch (JSchException e) { + this.close(); throw new CustomerException("SFTP链接失败!", e); } } + + /** + *

下载文件

+ * + * @param remoteFile 远程文件名(路径) + * @param localeFile 本地文件名 + * @return 本地文件路径 + * @throws IOException io异常 + * @author youHong.ai + */ + public String downFile(String remoteFile, String localeFile) throws IOException { + if (!isExist(remoteFile)) { + throw new FileNotFoundException("远程文件未找到!no search remote file"); + } + try { + File file = new File(localeFile); + if (!file.exists()) { + boolean mkdirs = file.getParentFile().mkdirs(); + if (!mkdirs) { + throw new CustomerException("无法创建目录(can not create dirs):[" + localeFile + "]"); + } + } else { + String parent = file.getParent(); + String name = file.getName(); + if (null == parent) { + parent = GCONST.getSysFilePath(); + } + if (!parent.endsWith(String.valueOf(File.separatorChar))) { + parent = parent + File.separatorChar; + } + localeFile = parent + System.currentTimeMillis() + UUID.randomUUID() + "_" + name; + } + this.get(remoteFile, Files.newOutputStream(Paths.get(localeFile))); + return localeFile; + } catch (SftpException e) { + throw new CustomerException("下载文件出错,down file error!"); + } + } + + /** + *

下载文件到系统文件目录中

+ * + * @param remoteFile 远程文件全路径 + * @param localeFileName 下载后的文件名称,只需要名称 + * @return 下载后的文件路径 + * @throws IOException IO异常 + */ + public String downFileToSystemFilePath(String remoteFile, String localeFileName) throws IOException { + return this.downFile(remoteFile, GCONST.getSysFilePath() + localeFileName); + } + + + /** + *

下载文件到系统中,并生成docId

+ * + * @param remoteFile 远程文件路径 + * @param catalogue doc目录id + * @param userId 文件创建者id + * @return docId + * @throws Exception 异常信息 + */ + public int downFileToDoc(String remoteFile, int catalogue, int userId) throws Exception { + if (!this.isExist(remoteFile)) { + throw new FileNotFoundException("远程文件未找到!no search remote file"); + } + Vector ls = null; + try { + ls = this.ls(remoteFile); + } catch (SftpException e) { + throw new CustomerException("无法查询当前文件信息!can not find file info~", e); + } + if (ls.size() == 0) { + throw new CustomerException("无法查询当前文件信息,ls 大小为0!can not find file info~ls size is 0"); + } + String fileName = null; +// 查看远程文件文件名 + for (int i = 0; i < ls.size(); i++) { + Object obj = ls.elementAt(i); + if (obj instanceof com.jcraft.jsch.ChannelSftp.LsEntry) { + LsEntry entry = (LsEntry) obj; + if (!entry.getAttrs().isDir()) { + fileName = entry.getFilename(); + } + if (entry.getAttrs().isDir()) { + if (!entry.getFilename().equals(".") && !entry.getFilename().equals("..")) { + fileName = entry.getFilename(); + } + } + } + } + if (null == fileName) { + throw new CustomerException("无法自动获取文件名!"); + } + InputStream inputStream; + try { + inputStream = this.get(remoteFile); + } catch (SftpException e) { + throw new CustomerException("下载文件是出错!down file error", e); + } + this.get(remoteFile); + int docId = Util.createDoc(fileName, catalogue, inputStream, userId); + return docId; + } + + /** + *

下载文件流

+ * + * @param remoteFile 远程文件路径 + * @return 文件流 + * @throws FileNotFoundException 文件未找到 + */ + public InputStream down(String remoteFile) throws FileNotFoundException { + if (!this.isExist(remoteFile)) { + throw new FileNotFoundException("远程文件未找到!no search remote file"); + } + try { + return this.get(remoteFile); + } catch (SftpException e) { + throw new CustomerException("下载文件是出错!down file error", e); + } + } + + /** + *

判断文件是否存在

+ * + * @param remotePath 远程文件路径 + * @return 是否存在 + */ + public boolean isExist(String remotePath) { + try { + this.ls(remotePath); + return true; + } catch (SftpException ignore) { + } + try { + this.lstat(remotePath); + return true; + } catch (SftpException e) { + return false; + } + } + /** * 关闭连接 server * @@ -139,7 +292,7 @@ public class SftpConnectUtil extends ChannelSftp { /** *

关闭链接释放资源

*/ - public void close(){ + public void close() { this.login(); } @@ -149,13 +302,13 @@ public class SftpConnectUtil extends ChannelSftp { } @Override - public void setBulkRequests(int bulk_requests) throws JSchException { - this.sftp.setBulkRequests(bulk_requests); + public int getBulkRequests() { + return this.sftp.getBulkRequests(); } @Override - public int getBulkRequests() { - return this.sftp.getBulkRequests(); + public void setBulkRequests(int bulk_requests) throws JSchException { + this.sftp.setBulkRequests(bulk_requests); } @Override @@ -168,21 +321,11 @@ public class SftpConnectUtil extends ChannelSftp { return this.sftp.isEOF(); } - @Override - public void setInputStream(InputStream in) { - this.sftp.setInputStream(in); - } - @Override public void setInputStream(InputStream in, boolean dontclose) { this.sftp.setInputStream(in, dontclose); } - @Override - public void setOutputStream(OutputStream out) { - this.sftp.setOutputStream(out); - } - @Override public void setOutputStream(OutputStream out, boolean dontclose) { this.sftp.setOutputStream(out, dontclose); @@ -203,6 +346,11 @@ public class SftpConnectUtil extends ChannelSftp { return this.sftp.getInputStream(); } + @Override + public void setInputStream(InputStream in) { + this.sftp.setInputStream(in); + } + @Override public InputStream getExtInputStream() throws IOException { return this.sftp.getExtInputStream(); @@ -213,6 +361,11 @@ public class SftpConnectUtil extends ChannelSftp { return this.sftp.getOutputStream(); } + @Override + public void setOutputStream(OutputStream out) { + this.sftp.setOutputStream(out); + } + @Override public void quit() { this.sftp.quit(); diff --git a/src/main/java/weaver/youhong/ai/pcn/hrorganization/service/OranizationAsyncService.java b/src/main/java/weaver/youhong/ai/pcn/hrorganization/service/OrganizationAsyncService.java similarity index 81% rename from src/main/java/weaver/youhong/ai/pcn/hrorganization/service/OranizationAsyncService.java rename to src/main/java/weaver/youhong/ai/pcn/hrorganization/service/OrganizationAsyncService.java index c7313df..2776e48 100644 --- a/src/main/java/weaver/youhong/ai/pcn/hrorganization/service/OranizationAsyncService.java +++ b/src/main/java/weaver/youhong/ai/pcn/hrorganization/service/OrganizationAsyncService.java @@ -8,7 +8,7 @@ package weaver.youhong.ai.pcn.hrorganization.service; * @author youHong.ai */ -public class OranizationAsyncService { +public class OrganizationAsyncService { } diff --git a/src/main/java/weaver/youhong/ai/pcn/hrorganization/sftp/FetchDataUtil.java b/src/main/java/weaver/youhong/ai/pcn/hrorganization/sftp/FetchDataUtil.java deleted file mode 100644 index 713f78e..0000000 --- a/src/main/java/weaver/youhong/ai/pcn/hrorganization/sftp/FetchDataUtil.java +++ /dev/null @@ -1,57 +0,0 @@ -package weaver.youhong.ai.pcn.hrorganization.sftp; - -import ebu7common.youhong.ai.sftp.SftpConnectUtil; -import com.jcraft.jsch.ChannelSftp; -import com.jcraft.jsch.SftpException; - -import java.io.*; - -/** - *

获取数据工具

- * - *

create: 2022-11-22 14:48

- * - *

HRIS_PositionExport20221119 职位文件名称

- *

HRIS_EmployeeExport20210825 人员文件名称

- *

HRIS_DepartmentExport20200503 部门文件名称

- * - * @author youHong.ai - */ - -public class FetchDataUtil { - - - - - public FetchDataUtil(){ - - } - - - - public void downloadFile(SftpConnectUtil sftpConnectUtil, - String fileName, String targetFile){ - try { - // sftpConnectUtil.lcd("."); - // Vector ls = sftpConnectUtil.ls("."); - // for (Object l : ls) { - // System.out.println(l); - // } - // - File file = new File(targetFile); - if (!file.exists()) { - file.getParentFile().mkdirs(); - } - sftpConnectUtil.get(fileName,new FileOutputStream(targetFile)); - - - } catch (SftpException e) { - sftpConnectUtil.close(); - e.printStackTrace(); - // throw new CustomerException("下载文件出错,down file error!"); - } catch (FileNotFoundException e) { - throw new RuntimeException(e); - } - } - -} \ No newline at end of file diff --git a/src/main/java/weaver/youhong/ai/pcn/hrorganization/wesmat/SyncOrganizationForOtherAPI.java b/src/main/java/weaver/youhong/ai/pcn/hrorganization/wesmat/SyncOrganizationForOtherAPI.java new file mode 100644 index 0000000..465d9df --- /dev/null +++ b/src/main/java/weaver/youhong/ai/pcn/hrorganization/wesmat/SyncOrganizationForOtherAPI.java @@ -0,0 +1,213 @@ +package weaver.youhong.ai.pcn.hrorganization.wesmat; + +import aiyh.utils.Util; +import aiyh.utils.zwl.common.ToolUtil; +import com.weaver.esb.server.cache.ResourceComInfo; +import weaver.hrm.company.DepartmentComInfo; +import weaver.hrm.company.SubCompanyComInfo; +import weaver.hrm.job.JobTitlesComInfo; +import weaver.hrm.resource.HrmSynDAO; +import weaver.integration.logging.Logger; +import weaver.integration.logging.LoggerFactory; +import weaver.interfaces.hrm.*; +import weaver.matrix.MatrixUtil; +import weaver.youhong.ai.pcn.hrorganization.wesmat.model.Department; +import weaver.youhong.ai.pcn.hrorganization.wesmat.model.Employee; +import weaver.youhong.ai.pcn.hrorganization.wesmat.model.Position; +import weaver.youhong.ai.pcn.hrorganization.wesmat.result.GetOrganizationResult; +import weaver.youhong.ai.pcn.hrorganization.wesmat.util.SyncOrganizationUtils; + +import java.util.*; + + +/** + * @author EBU7-dev1-ayh + * @create 2021/7/20 0020 15:16 + * 同步第三方系统人员组织结构 + */ + + +public class SyncOrganizationForOtherAPI extends ToolUtil implements HrmSynService { + private final Logger log = LoggerFactory.getLogger(SyncOrganizationForOtherAPI.class); + private final GetOrganizationResult getOrganizationResult = new GetOrganizationResult(); + private final SyncOrganizationUtils organizationUtils = new SyncOrganizationUtils(); + String className = "SyncOrganizationForOtherAPI"; + private HashMap synResult; + + public SyncOrganizationForOtherAPI() { + this.writeDebuggerLog(className, "===========> create Object! <============"); + this.synResult = new HashMap<>(); + } + + /** + * 同步到分公司(分部) + */ + @Override + public String SynTimingToOASubCompany() { + this.writeDebuggerLog(className, "===========> synchronous company to OA system start <============"); + this.synResult.put("1", null); + this.writeDebuggerLog(className, "===========> synchronous company to OA system end <============"); + return null; + } + + /** + * 同步到部门 + */ + @Override + public String SynTimingToOADepartment() { + this.writeDebuggerLog(className, "===========> synchronous department to OA system starts <============"); + try { + List departmentList = getOrganizationResult.getDepartmentList(); + Collections.sort(departmentList); + List> synResultlist = new ArrayList<>(); + departmentList.forEach(department -> { + Map stringStringMap = organizationUtils.asyncDepartment(department); + synResultlist.add(buildItemMap("", "", department.getDEPARTMENTNAME(), stringStringMap.get("code"), stringStringMap.get("msg"))); + }); + this.writeDebuggerLog(className, departmentList.size() + " data pieces are updated this time"); + //清除OA中分部的缓存记录 + SubCompanyComInfo subCompanyComInfo = new SubCompanyComInfo(); + subCompanyComInfo.removeCompanyCache(); + subCompanyComInfo.removeCache(); + //清除部门缓存 + DepartmentComInfo departmentComInfo = new DepartmentComInfo(); + departmentComInfo.removeCompanyCache(); + departmentComInfo.removeCache(); + + //同步部门数据到矩阵 + MatrixUtil.sysDepartmentData(); + + this.writeDebuggerLog(className, "This time together step or update data " + departmentList.size()); + this.synResult.put("2", synResultlist); + this.writeDebuggerLog(className, "===========> synchronous department to OA system end <============"); + } catch (Exception e) { + this.writeErrorLog("同步部门出现错误:错误信息:" + Util.getErrString(e)); + } + return null; + } + + /** + * 同步到职位 + */ + @Override + public String SynTimingToOAJobtitle() { + this.writeDebuggerLog(className, "===========> synchronous job to OA system starts <============"); + try { + List positionList = getOrganizationResult.getPositionList(); + Collections.sort(positionList); + List> synResultlist = new ArrayList<>(); + positionList.forEach(position -> { + Map stringStringMap = organizationUtils.asyncPosition(position); + synResultlist.add(buildItemMap(position.getJOBCODE(), position.getJOBCODE(), position.getJOBFUNCTION(), stringStringMap.get("code"), stringStringMap.get("msg"))); + }); + this.writeDebuggerLog(className, positionList.size() + " data pieces are updated this time"); +// 清除职位缓存 + JobTitlesComInfo jobTitlesComInfo = new JobTitlesComInfo(); + jobTitlesComInfo.removeJobTitlesCache(); + jobTitlesComInfo.removeCache(); + this.synResult.put("3", synResultlist); + this.writeDebuggerLog(className, "===========> synchronous job to OA system end <============"); + } catch (Exception e) { + this.writeErrorLog("同步职位失败,失败信息:" + Util.getErrString(e)); + } + return null; + } + + /** + * 同步到人员 + */ + @Override + public String SynTimingToOAHrmResource() { + this.writeDebuggerLog(className, "===========> synchronous hrm to OA system starts <============"); + try { + List employeeList = getOrganizationResult.getEmployeeList(); + List> synResultlist = new ArrayList<>(); + Collections.sort(employeeList); + employeeList.forEach(employee -> { + Map stringStringMap = organizationUtils.asyncEmployee(employee); + synResultlist.add(buildItemMap(employee.getUSERCODE(), employee.getUSERCODE(), employee.getPreferred_Name() + "/" + employee.getUSERNAMECN(), stringStringMap.get("code"), stringStringMap.get("msg"))); + }); + this.writeDebuggerLog(className, employeeList.size() + " data pieces are updated this time"); + // 清除人员缓存 + try { + ResourceComInfo rsc = new ResourceComInfo(); + rsc.removeCache(); + } catch (Exception e) { + this.writeErrorLog(className, "removeCache error!"); + e.printStackTrace(); + } +// organizationUtils.asyncEmployee(employeeList.get(0)); + this.synResult.put("4", synResultlist); + this.writeDebuggerLog(className, "===========> synchronous hrm to OA system end <============"); + } catch (Exception e) { + this.writeErrorLog("同步人员信息失败,失败信息:" + Util.getErrString(e)); + } + return null; + } + + @Override + public void SynTimingFromOASubCompany(SubCompanyBean[] subCompanyBeans) { + + } + + @Override + public void SynTimingFromOADepartment(DepartmentBean[] departmentBeans) { + + } + + @Override + public void SynTimingFromOAJobtitle(JobTitleBean[] jobTitleBeans) { + + } + + @Override + public void SynTimingFromOAHrmResource(UserBean[] userBeans) { + + } + + @Override + public void SynInstantSubCompany(SubCompanyBean subCompanyBean) { + + } + + @Override + public void SynInstantDepartment(DepartmentBean departmentBean) { + + } + + @Override + public void SynInstantJobtitle(JobTitleBean jobTitleBean) { + + } + + @Override + public void SynInstantHrmResource(UserBean userBean) { + + } + + @Override + public boolean SynSendMessage(String s, String s1, String s2, String s3, String s4) { + return false; + } + + @Override + public HashMap getSynResult() { + return this.synResult; + } + + @Override + public void removeSynResult() { + this.synResult = new HashMap(); + } + + private Map buildItemMap(String pkcode, String pk, String memo, String succ, String error) { + //保存结果 + HashMap itemMap = new HashMap<>(); + itemMap.put(HrmSynDAO.OUTPK, pkcode); + itemMap.put(HrmSynDAO.PK, pk); + itemMap.put(HrmSynDAO.Memo, memo); + itemMap.put(HrmSynDAO.Success, succ); + itemMap.put(HrmSynDAO.ErrorMessage, error); + return itemMap; + } +} diff --git a/src/main/java/weaver/youhong/ai/pcn/hrorganization/wesmat/config/SyncOrganizationConfig.java b/src/main/java/weaver/youhong/ai/pcn/hrorganization/wesmat/config/SyncOrganizationConfig.java new file mode 100644 index 0000000..d4a7306 --- /dev/null +++ b/src/main/java/weaver/youhong/ai/pcn/hrorganization/wesmat/config/SyncOrganizationConfig.java @@ -0,0 +1,161 @@ +package weaver.youhong.ai.pcn.hrorganization.wesmat.config; + +import aiyh.utils.httpUtil.ResponeVo; +import aiyh.utils.httpUtil.util.HttpUtils; +import aiyh.utils.zwl.common.ToolUtil; +import com.alibaba.fastjson.JSON; +import com.alibaba.fastjson.TypeReference; +import com.ibm.icu.text.SimpleDateFormat; +import org.apache.http.client.methods.CloseableHttpResponse; +import weaver.youhong.ai.pcn.hrorganization.wesmat.result.ResultBean; + +import java.io.IOException; +import java.util.*; + +/** + * @author EBU7-dev1-ayh + * @create 2021/7/20 0020 16:40 + * 同步第三方系统人员组织结构配置类 + */ + + +public class SyncOrganizationConfig extends ToolUtil { + + /** + * api验证参数 + */ + private final String API_KEY = this.getSystemParamValue("CMS_API_KEY"); + /** + * 测试地址URL + */ + private String CMS_TEST_URL = this.getSystemParamValue("CMS_TEST_URL"); + /** + * 生产环境地址URL + */ + private String CMS_PROUD_URL = this.getSystemParamValue("CMS_PROUD_URL"); + /** + * 员工 + */ + private String EmployeeApi = this.getSystemParamValue("EmployeeApi"); + /** + * 部门 + */ + private String DepartmentApi = this.getSystemParamValue("DepartmentApi"); + /** + * 职位 + */ + private String PositionApi = this.getSystemParamValue("PositionApi"); + private String CMS_API_URL_MARK = this.getSystemParamValue("CMS_API_URL_MARK"); + private String REQUEST_API_RUL = ""; + /** + * 每页数据大小 + */ + private final String PAGE_SIZE = this.getSystemParamValue("CMS_API_GET_DATA_SIZE"); + private String CMS_API_QUERY_DATA = ""; + private HttpUtils httpUtils = new HttpUtils(); + + public SyncOrganizationConfig() { + if (0 == Integer.parseInt(CMS_API_URL_MARK)) { + this.REQUEST_API_RUL = this.CMS_TEST_URL; + this.CMS_API_QUERY_DATA = "?date=" + this.getSystemParamValue("CMS_API_QUERY_DATA"); + } else { + this.REQUEST_API_RUL = this.CMS_PROUD_URL; + this.CMS_API_QUERY_DATA = this.getDate(); + } + } + + private String getDate() { + Date date = new Date(); + SimpleDateFormat formatter = new SimpleDateFormat("yyyyMMdd"); + return "?date=" + formatter.format(date); + } + + // 封装整理接口数据 + public List getDataList(String url) { + int pageIndex = 1; + ArrayList employees = new ArrayList<>(); + while (true) { + ResultBean employeeResultBean = getDataResult(pageIndex, url); +// this.writeErrorLog("人员组织架构的响应互数据:" + employeeResultBean); + assert employeeResultBean != null; + employees.addAll(employeeResultBean.getItems()); + pageIndex++; +// || employeeResultBean.getItems().size() < employeeResultBean.getPageSize() + if (employeeResultBean.getPage() >= employeeResultBean.getTotalPage()) { + break; + } + } + return employees; + } + + + // 请求api接口数据 + private ResultBean getDataResult(int pageIndex, String url) { + this.writeErrorLog("人员组织架构请求地址: " + url + " 请求数据:PAGE_SIZE:" + PAGE_SIZE + " pageIndex:" + pageIndex + " apikey:" + API_KEY); +// DefaultHttpClient httpClient = HttpManager.getHttpClient(); + +// HttpPost httpPost = new HttpPost(url); + Map params = new HashMap(2); + Map heards = new HashMap(2); + heards.put("apikey", API_KEY); + heards.put("Content-Type", "application/json"); + params.put("pageSize", PAGE_SIZE); + params.put("pageIndex", Integer.toString(pageIndex)); + + +// List nvps = new ArrayList<>(); +// nvps.add(new BasicNameValuePair("pageSize","10")); +// nvps.add(new BasicNameValuePair("pageIndex","1")); +// httpPost.setEntity(new UrlEncodedFormEntity(nvps, HTTP.UTF_8)); +/* httpPost.setHeader("apikey", API_KEY); + httpPost.setHeader("Content-Type", "application/json"); + httpPost.setEntity(new StringEntity(JSON.toJSONString(params), HTTP.UTF_8));*/ + CloseableHttpResponse execute = null; + try { +// execute = httpClient.execute(httpPost); + ResponeVo responeVo = httpUtils.apiPost(url, params, heards); + if (responeVo.getCode() == 200) { + return JSON.parseObject(responeVo.getEntityString(), new TypeReference>() { + }); + } +/* if (execute.getStatusLine().getStatusCode() == 200) { + HttpEntity entity = execute.getEntity(); + String response = EntityUtils.toString(entity, "utf-8"); + + return JSON.parseObject(response, new TypeReference>() { + }); + }*/ +// HttpEntity entity = execute.getEntity(); +// String response = EntityUtils.toString(entity, "utf-8"); + this.writeErrorLog("人员组织架构的相应数据:" + responeVo.getEntityString()); +// System.out.println(url); +// System.out.println(response); +// System.out.println(JSON.parseObject(response, new TypeReference>() {})); + return null; + } catch (IOException e) { + try { + if (execute != null) { + execute.close(); + } + } catch (IOException ioException) { + ioException.printStackTrace(); + return null; + } + e.printStackTrace(); + this.writeErrorLog("转换错误!错误原因:" + e); + return null; + } + } + + public String getEMPLOYEE_API_RUL() { + return this.REQUEST_API_RUL + this.EmployeeApi + this.CMS_API_QUERY_DATA; + } + + public String getDEPARTMENT_API_URL() { + return this.REQUEST_API_RUL + this.DepartmentApi + this.CMS_API_QUERY_DATA; + } + + public String getPOSITION_API_URL() { + return this.REQUEST_API_RUL + this.PositionApi + this.CMS_API_QUERY_DATA; + } +} diff --git a/src/main/java/weaver/youhong/ai/pcn/hrorganization/wesmat/model/Department.java b/src/main/java/weaver/youhong/ai/pcn/hrorganization/wesmat/model/Department.java new file mode 100644 index 0000000..a55e20b --- /dev/null +++ b/src/main/java/weaver/youhong/ai/pcn/hrorganization/wesmat/model/Department.java @@ -0,0 +1,87 @@ +package weaver.youhong.ai.pcn.hrorganization.wesmat.model; + +import org.jetbrains.annotations.NotNull; + +/** + * @author EBU7-dev1-ayh + * @create 2021/7/20 0020 17:18 + * 部门实体类 + */ + + +public class Department implements Comparable { + /** + * 部门ID + */ + private Long DEPARTMENTID; + /** + * 部门名称 + */ + private String DEPARTMENTNAME; + /** + * 上级部门ID 此处为0时,表示该部门为根部门。对应所属公司,从【一级部门对应实体mapping表】上取值 + */ + private Long PARENTDEPARTMENDID; + + + public String getValue(String fieldName) { + if ("DEPARTMENTID".equals(fieldName)) { + return String.valueOf(this.getDEPARTMENTID()); + } + if ("DEPARTMENTNAME".equals(fieldName)) { + return this.getDEPARTMENTNAME(); + } + if ("PARENTDEPARTMENDID".equals(fieldName)) { + return String.valueOf(this.getPARENTDEPARTMENDID()); + } + return null; + } + + public Department() { + } + + public Department(Long DEPARTMENTID, String DEPARTMENTNAME, Long PARENTDEPARTMENDID) { + this.DEPARTMENTID = DEPARTMENTID; + this.DEPARTMENTNAME = DEPARTMENTNAME; + this.PARENTDEPARTMENDID = PARENTDEPARTMENDID; + } + + public Long getDEPARTMENTID() { + return DEPARTMENTID; + } + + public void setDEPARTMENTID(Long DEPARTMENTID) { + this.DEPARTMENTID = DEPARTMENTID; + } + + public String getDEPARTMENTNAME() { + return DEPARTMENTNAME; + } + + public void setDEPARTMENTNAME(String DEPARTMENTNAME) { + this.DEPARTMENTNAME = DEPARTMENTNAME; + } + + public Long getPARENTDEPARTMENDID() { + return PARENTDEPARTMENDID; + } + + public void setPARENTDEPARTMENDID(Long PARENTDEPARTMENDID) { + this.PARENTDEPARTMENDID = PARENTDEPARTMENDID; + } + + + @Override + public String toString() { + return "Department{" + + "DEPARTMENTID='" + DEPARTMENTID + '\'' + + ", DEPARTMENTNAME='" + DEPARTMENTNAME + '\'' + + ", PARENTDEPARTMENDID='" + PARENTDEPARTMENDID + '\'' + + '}'; + } + + @Override + public int compareTo(@NotNull Department o) { + return new Long(this.PARENTDEPARTMENDID - o.getPARENTDEPARTMENDID()).intValue(); + } +} diff --git a/src/main/java/weaver/youhong/ai/pcn/hrorganization/wesmat/model/Employee.java b/src/main/java/weaver/youhong/ai/pcn/hrorganization/wesmat/model/Employee.java new file mode 100644 index 0000000..13ced0d --- /dev/null +++ b/src/main/java/weaver/youhong/ai/pcn/hrorganization/wesmat/model/Employee.java @@ -0,0 +1,276 @@ +package weaver.youhong.ai.pcn.hrorganization.wesmat.model; + +import org.jetbrains.annotations.NotNull; + +/** + * @author EBU7-dev1-ayh + * @create 2021/7/20 0020 17:09 + * 员工实体类 + */ + +public class Employee implements Comparable { + /** + * 员工id + */ + private Long UserID; + /** + * 名 (英文) + */ + private String FIRSTNAMEEN; + /** + * 姓 (英文) + */ + private String LASTNAMEEN; + /** + * 中文姓名 + */ + private String USERNAMECN; + /** + * 员工编号 + */ + private String USERCODE; + /** + * 岗位id + */ + private Long JOBCODEID; + /** + * 部门id + */ + private Long DEPARTMENTID; + /** + * 部门名称 + */ + private String DEPARTMENTNAME; + /*成本中心编码*/ + private String COSTCENTERCODE; + /** + * 邮箱 + */ + private String EMAIL; + /** + * 公司实体 + */ + private String ORGANIZATION; + /** + * 电话号 + */ + private String MOBILENO; + /** + * 座机号 + */ + private String TEL; + /** + * 英文名 + */ + private String Preferred_Name; + + public String getValue(String fieldName) { + if ("UserID".equals(fieldName)) { + return String.valueOf(this.getUserID()); + } + if ("FIRSTNAMEEN".equals(fieldName)) { + return this.getFIRSTNAMEEN(); + } + if ("LASTNAMEEN".equals(fieldName)) { + return this.getLASTNAMEEN(); + } + if ("USERNAMECN".equals(fieldName)) { + return this.getUSERNAMECN(); + } + if ("USERCODE".equals(fieldName)) { + return this.getUSERCODE(); + } + if ("JOBCODEID".equals(fieldName)) { + return String.valueOf(this.getJOBCODEID()); + } + if ("DEPARTMENTID".equals(fieldName)) { + return String.valueOf(this.getDEPARTMENTID()); + } + if ("DEPARTMENTNAME".equals(fieldName)) { + return this.getDEPARTMENTNAME(); + } + if ("COSTCENTERCODE".equals(fieldName)) { + return this.getCOSTCENTERCODE(); + } + if ("EMAIL".equals(fieldName)) { + return this.getEMAIL(); + } + if ("ORGANIZATION".equals(fieldName)) { + return this.getORGANIZATION(); + } + if ("MOBILENO".equals(fieldName)) { + return this.getMOBILENO(); + } + if ("TEL".equals(fieldName)) { + return this.getTEL(); + } + if ("Preferred_Name".equals(fieldName)) { + return this.getPreferred_Name(); + } + return null; + } + + public Employee() { + } + + @Override + public String toString() { + return "Employee{" + + "UserID='" + UserID + '\'' + + ", FIRSTNAMEEN='" + FIRSTNAMEEN + '\'' + + ", LASTNAMEEN='" + LASTNAMEEN + '\'' + + ", USERNAMECN='" + USERNAMECN + '\'' + + ", USERCODE='" + USERCODE + '\'' + + ", JOBCODEID='" + JOBCODEID + '\'' + + ", DEPARTMENTID='" + DEPARTMENTID + '\'' + + ", DEPARTMENTNAME='" + DEPARTMENTNAME + '\'' + + ", COSTCENTERCODE='" + COSTCENTERCODE + '\'' + + ", EMAIL='" + EMAIL + '\'' + + ", ORGANIZATION='" + ORGANIZATION + '\'' + + ", MOBILENO='" + MOBILENO + '\'' + + ", TEL='" + TEL + '\'' + + ", Preferred_Name='" + Preferred_Name + '\'' + + '}'; + } + + public Employee(Long userID, String FIRSTNAMEEN, String LASTNAMEEN, String USERNAMECN, String USERCODE, Long JOBCODEID, Long DEPARTMENTID, String DEPARTMENTNAME, String COSTCENTERCODE, String EMAIL, String ORGANIZATION, String MOBILENO, String TEL, String preferred_Name) { + UserID = userID; + this.FIRSTNAMEEN = FIRSTNAMEEN; + this.LASTNAMEEN = LASTNAMEEN; + this.USERNAMECN = USERNAMECN; + this.USERCODE = USERCODE; + this.JOBCODEID = JOBCODEID; + this.DEPARTMENTID = DEPARTMENTID; + this.DEPARTMENTNAME = DEPARTMENTNAME; + this.COSTCENTERCODE = COSTCENTERCODE; + this.EMAIL = EMAIL; + this.ORGANIZATION = ORGANIZATION; + this.MOBILENO = MOBILENO; + this.TEL = TEL; + Preferred_Name = preferred_Name; + } + + public Long getUserID() { + return UserID; + } + + public void setUserID(Long userID) { + UserID = userID; + } + + public String getFIRSTNAMEEN() { + return FIRSTNAMEEN; + } + + public void setFIRSTNAMEEN(String FIRSTNAMEEN) { + this.FIRSTNAMEEN = FIRSTNAMEEN; + } + + public String getLASTNAMEEN() { + return LASTNAMEEN; + } + + public void setLASTNAMEEN(String LASTNAMEEN) { + this.LASTNAMEEN = LASTNAMEEN; + } + + public String getUSERNAMECN() { + return USERNAMECN; + } + + public void setUSERNAMECN(String USERNAMECN) { + this.USERNAMECN = USERNAMECN; + } + + public String getUSERCODE() { + return USERCODE; + } + + public void setUSERCODE(String USERCODE) { + this.USERCODE = USERCODE; + } + + public Long getJOBCODEID() { + return JOBCODEID; + } + + public void setJOBCODEID(Long JOBCODEID) { + this.JOBCODEID = JOBCODEID; + } + + public Long getDEPARTMENTID() { + return DEPARTMENTID; + } + + public void setDEPARTMENTID(Long DEPARTMENTID) { + this.DEPARTMENTID = DEPARTMENTID; + } + + public String getDEPARTMENTNAME() { + return DEPARTMENTNAME; + } + + public void setDEPARTMENTNAME(String DEPARTMENTNAME) { + this.DEPARTMENTNAME = DEPARTMENTNAME; + } + + public String getCOSTCENTERCODE() { + return COSTCENTERCODE; + } + + public void setCOSTCENTERCODE(String COSTCENTERCODE) { + this.COSTCENTERCODE = COSTCENTERCODE; + } + + public String getEMAIL() { + return EMAIL; + } + + public void setEMAIL(String EMAIL) { + this.EMAIL = EMAIL; + } + + public String getORGANIZATION() { + return ORGANIZATION; + } + + public void setORGANIZATION(String ORGANIZATION) { + this.ORGANIZATION = ORGANIZATION; + } + + public String getMOBILENO() { + return MOBILENO; + } + + public void setMOBILENO(String MOBILENO) { + this.MOBILENO = MOBILENO; + } + + public String getTEL() { + return TEL; + } + + public void setTEL(String TEL) { + this.TEL = TEL; + } + + public String getPreferred_Name() { + return Preferred_Name; + } + + public void setPreferred_Name(String preferred_Name) { + Preferred_Name = preferred_Name; + } + + + @Override + public int compareTo(@NotNull Employee o) { + if (this.getJOBCODEID() == null) { + return -1; + } + if (o.getJOBCODEID() == null) { + return 1; + } + return new Long(this.JOBCODEID - o.getJOBCODEID()).intValue(); + } +} diff --git a/src/main/java/weaver/youhong/ai/pcn/hrorganization/wesmat/model/Position.java b/src/main/java/weaver/youhong/ai/pcn/hrorganization/wesmat/model/Position.java new file mode 100644 index 0000000..690cd33 --- /dev/null +++ b/src/main/java/weaver/youhong/ai/pcn/hrorganization/wesmat/model/Position.java @@ -0,0 +1,132 @@ +package weaver.youhong.ai.pcn.hrorganization.wesmat.model; + +import org.jetbrains.annotations.NotNull; + +/** + * @author EBU7-dev1-ayh + * @create 2021/7/20 0020 17:20 + * 岗位实体类 + */ + + +public class Position implements Comparable { + /** + * 岗位id + */ + private long JOBCODEID; + /** + * 岗位编号 + */ + private String JOBCODE; + /** + * 岗位描述 + */ + private String JOBFUNCTION; + /** + * 上级岗位id 为空则表示该岗位无上级 + */ + private long SUPERIORJOBCODEID; + private long POSITIONOCCUPIED; + private String Company_Code; + + + public String getValue(String fieldName) { + if ("JOBCODEID".equals(fieldName)) { + return String.valueOf(this.getJOBCODEID()); + } + if ("JOBCODE".equals(fieldName)) { + return this.getJOBCODE(); + } + if ("JOBFUNCTION".equals(fieldName)) { + return this.getJOBFUNCTION(); + } + if ("SUPERIORJOBCODEID".equals(fieldName)) { + return String.valueOf(this.getSUPERIORJOBCODEID()); + } + if ("POSITIONOCCUPIED".equals(fieldName)) { + return String.valueOf(this.getPOSITIONOCCUPIED()); + } + if ("Company_Code".equals(fieldName)) { + return this.getCompany_Code(); + } + return null; + } + + public Position() { + } + + public Position(long JOBCODEID, String JOBCODE, String JOBFUNCTION, long SUPERIORJOBCODEID, long POSITIONOCCUPIED, String company_Code) { + this.JOBCODEID = JOBCODEID; + this.JOBCODE = JOBCODE; + this.JOBFUNCTION = JOBFUNCTION; + this.SUPERIORJOBCODEID = SUPERIORJOBCODEID; + this.POSITIONOCCUPIED = POSITIONOCCUPIED; + this.Company_Code = company_Code; + } + + + public int getJOBCODEID() { + return (int) JOBCODEID; + } + + public void setJOBCODEID(long JOBCODEID) { + this.JOBCODEID = JOBCODEID; + } + + public String getJOBCODE() { + return JOBCODE; + } + + public void setJOBCODE(String JOBCODE) { + this.JOBCODE = JOBCODE; + } + + public String getJOBFUNCTION() { + return JOBFUNCTION; + } + + public void setJOBFUNCTION(String JOBFUNCTION) { + this.JOBFUNCTION = JOBFUNCTION; + } + + public long getSUPERIORJOBCODEID() { + return SUPERIORJOBCODEID; + } + + public void setSUPERIORJOBCODEID(long SUPERIORJOBCODEID) { + this.SUPERIORJOBCODEID = SUPERIORJOBCODEID; + } + + public long getPOSITIONOCCUPIED() { + return POSITIONOCCUPIED; + } + + public void setPOSITIONOCCUPIED(long POSITIONOCCUPIED) { + this.POSITIONOCCUPIED = POSITIONOCCUPIED; + } + + public String getCompany_Code() { + return Company_Code; + } + + public void setCompany_Code(String company_Code) { + Company_Code = company_Code; + } + + @Override + public int compareTo(@NotNull Position o) { + return new Long(this.SUPERIORJOBCODEID - o.getSUPERIORJOBCODEID()).intValue(); + } + + @Override + public String toString() { + return "Position{" + + "JOBCODEID=" + JOBCODEID + + ", JOBCODE='" + JOBCODE + '\'' + + ", JOBFUNCTION='" + JOBFUNCTION + '\'' + + ", SUPERIORJOBCODEID=" + SUPERIORJOBCODEID + + ", POSITIONOCCUPIED=" + POSITIONOCCUPIED + + ", Company_Code='" + Company_Code + '\'' + + '}'; + } +} diff --git a/src/main/java/weaver/youhong/ai/pcn/hrorganization/wesmat/result/ApiAsyncConfigResult.java b/src/main/java/weaver/youhong/ai/pcn/hrorganization/wesmat/result/ApiAsyncConfigResult.java new file mode 100644 index 0000000..67c9ec1 --- /dev/null +++ b/src/main/java/weaver/youhong/ai/pcn/hrorganization/wesmat/result/ApiAsyncConfigResult.java @@ -0,0 +1,121 @@ +package weaver.youhong.ai.pcn.hrorganization.wesmat.result; + +/** + * @author EBU7-dev1-ayh + * @create 2021/7/23 0023 15:28 + * api配置结果查询结果 + */ + + +public class ApiAsyncConfigResult { + /** + * id + */ + private long id; + /** + * 同步类型,0表示部门信息,1表示人员信息,2表示职位信息 + */ + private int asyncType; + /** + * 第三方api返回的数据对应字段 + */ + private String apiField; + /** + * api对应字段的值需要插入到的OA系统的字段 + */ + private String oAField; + /** + * OA字段类型,0表示系统自带的字段,1表示用户自定义的字段 + */ + private int fieldType; + /** + * 同步数据时的转换规则,0表示不转换,1表示固定值,3表示自定义SQL转换 + */ + private int changeRules; + /** + * 自定义的转换规则 + */ + private String customRules; + + public ApiAsyncConfigResult() { + } + + public ApiAsyncConfigResult(long id, int asyncType, String apiField, String oAField, int fieldType, int changeRules, String customRules) { + this.id = id; + this.asyncType = asyncType; + this.apiField = apiField; + this.oAField = oAField; + this.fieldType = fieldType; + this.changeRules = changeRules; + this.customRules = customRules; + } + + public long getId() { + return id; + } + + public void setId(long id) { + this.id = id; + } + + public int getAsyncType() { + return asyncType; + } + + public void setAsyncType(int asyncType) { + this.asyncType = asyncType; + } + + public String getApiField() { + return apiField; + } + + public void setApiField(String apiField) { + this.apiField = apiField; + } + + public String getoAField() { + return oAField; + } + + public void setoAField(String oAField) { + this.oAField = oAField; + } + + public int getFieldType() { + return fieldType; + } + + public void setFieldType(int fieldType) { + this.fieldType = fieldType; + } + + public int getChangeRules() { + return changeRules; + } + + public void setChangeRules(int changeRules) { + this.changeRules = changeRules; + } + + public String getCustomRules() { + return customRules; + } + + public void setCustomRules(String customRules) { + this.customRules = customRules; + } + + @Override + public String toString() { + return "ApiAsyncConfigResult{" + + "id=" + id + + ", asyncType=" + asyncType + + ", apiField='" + apiField + '\'' + + ", oAField='" + oAField + '\'' + + ", fieldType=" + fieldType + + ", changeRules=" + changeRules + + ", customRules='" + customRules + '\'' + + '}'; + } +} diff --git a/src/main/java/weaver/youhong/ai/pcn/hrorganization/wesmat/result/GetOrganizationResult.java b/src/main/java/weaver/youhong/ai/pcn/hrorganization/wesmat/result/GetOrganizationResult.java new file mode 100644 index 0000000..dd4d9da --- /dev/null +++ b/src/main/java/weaver/youhong/ai/pcn/hrorganization/wesmat/result/GetOrganizationResult.java @@ -0,0 +1,49 @@ +package weaver.youhong.ai.pcn.hrorganization.wesmat.result; + +import com.alibaba.fastjson.JSON; +import com.alibaba.fastjson.JSONObject; +import weaver.youhong.ai.pcn.hrorganization.wesmat.config.SyncOrganizationConfig; +import weaver.youhong.ai.pcn.hrorganization.wesmat.model.Department; +import weaver.youhong.ai.pcn.hrorganization.wesmat.model.Employee; +import weaver.youhong.ai.pcn.hrorganization.wesmat.model.Position; + +import java.util.List; + +/** + * @author EBU7-dev1-ayh + * @create 2021/7/21 0021 15:13 + * 获取第三方api请求结果 + */ + + +public class GetOrganizationResult { + /** + * 获取员工数据 + */ + public List getEmployeeList() { + SyncOrganizationConfig employeeSyncOrganizationConfig = new SyncOrganizationConfig<>(); + List dataList = employeeSyncOrganizationConfig.getDataList(employeeSyncOrganizationConfig.getEMPLOYEE_API_RUL()); + String jsonString = JSON.toJSON(dataList).toString(); + return (List) JSONObject.parseArray(jsonString, Employee.class); + } + + /** + * 获取部门数据 + */ + public List getDepartmentList() { + SyncOrganizationConfig employeeSyncOrganizationConfig = new SyncOrganizationConfig<>(); + List dataList = employeeSyncOrganizationConfig.getDataList(employeeSyncOrganizationConfig.getDEPARTMENT_API_URL()); + String jsonString = JSON.toJSON(dataList).toString(); + return (List) JSONObject.parseArray(jsonString, Department.class); + } + + /** + * 获取职位数据 + */ + public List getPositionList() { + SyncOrganizationConfig employeeSyncOrganizationConfig = new SyncOrganizationConfig<>(); + List dataList = employeeSyncOrganizationConfig.getDataList(employeeSyncOrganizationConfig.getPOSITION_API_URL()); + String jsonString = JSON.toJSON(dataList).toString(); + return (List) JSONObject.parseArray(jsonString, Position.class); + } +} diff --git a/src/main/java/weaver/youhong/ai/pcn/hrorganization/wesmat/result/ResultBean.java b/src/main/java/weaver/youhong/ai/pcn/hrorganization/wesmat/result/ResultBean.java new file mode 100644 index 0000000..0309237 --- /dev/null +++ b/src/main/java/weaver/youhong/ai/pcn/hrorganization/wesmat/result/ResultBean.java @@ -0,0 +1,151 @@ +package weaver.youhong.ai.pcn.hrorganization.wesmat.result; + + +import java.util.ArrayList; + +/** + * @author EBU7-dev1-ayh + * @create 2021/7/21 0021 13:57 + */ + + +public class ResultBean { + /** + * 响应状态码 + */ + private boolean code; + private String errorMessage; + private String traceId; + /** + * 响应消息 + */ + private String msg; + /** + * 总页数 + */ + private int totalPage; + /** + * 当前页数 + */ + private int page; + /** + * 每页数据量 + */ + private int pageSize; + /** + * 数据总量 + */ + private int totalCount; + /** + * 响应数据 + */ + private ArrayList items; + + @Override + public String toString() { + return "ResultBean{" + + "code=" + code + + ", errorMessage='" + errorMessage + '\'' + + ", traceId='" + traceId + '\'' + + ", msg='" + msg + '\'' + + ", totalPage=" + totalPage + + ", page=" + page + + ", pageSize=" + pageSize + + ", totalCount=" + totalCount + + ", items=" + items + + '}'; + } + + public ResultBean() { + } + + public ResultBean(boolean code, String msg, int totalPage, int page, int pageSize, int totalCount, ArrayList items) { + this.code = code; + this.msg = msg; + this.totalPage = totalPage; + this.page = page; + this.pageSize = pageSize; + this.totalCount = totalCount; + this.items = items; + } + + public boolean getCode() { + return code; + } + + public void setCode(boolean code) { + this.code = code; + } + + public String getMsg() { + return msg; + } + + public void setMsg(String msg) { + this.msg = msg; + } + + public int getTotalPage() { + return totalPage; + } + + public void setTotalPage(int totalPage) { + this.totalPage = totalPage; + } + + public int getPage() { + return page; + } + + public void setPage(int page) { + this.page = page; + } + + public int getPageSize() { + return pageSize; + } + + public void setPageSize(int pageSize) { + this.pageSize = pageSize; + } + + public int getTotalCount() { + return totalCount; + } + + public void setTotalCount(int totalCount) { + this.totalCount = totalCount; + } + + public ArrayList getItems() { + return items; + } + + public boolean isCode() { + return code; + } + + public String getErrorMessage() { + return errorMessage; + } + + public String getTraceId() { + return traceId; + } + + public ResultBean(boolean code, String errorMessage, String traceId, String msg, int totalPage, int page, int pageSize, int totalCount, ArrayList items) { + this.code = code; + this.errorMessage = errorMessage; + this.traceId = traceId; + this.msg = msg; + this.totalPage = totalPage; + this.page = page; + this.pageSize = pageSize; + this.totalCount = totalCount; + this.items = items; + } + + public void setItems(ArrayList items) { + this.items = items; + } +} \ No newline at end of file diff --git a/src/main/java/weaver/youhong/ai/pcn/hrorganization/wesmat/util/GetModelValue.java b/src/main/java/weaver/youhong/ai/pcn/hrorganization/wesmat/util/GetModelValue.java new file mode 100644 index 0000000..35af0ea --- /dev/null +++ b/src/main/java/weaver/youhong/ai/pcn/hrorganization/wesmat/util/GetModelValue.java @@ -0,0 +1,20 @@ +package weaver.youhong.ai.pcn.hrorganization.wesmat.util; + + +import java.lang.reflect.InvocationTargetException; +import java.lang.reflect.Method; + +/** + * @author EBU7-dev1-ayh + * @create 2021/7/26 0026 8:55 + * 获取model类的属性值 + */ + + +public class GetModelValue { + public Object getValueForString(T obj, String mothodName) throws NoSuchMethodException, InvocationTargetException, IllegalAccessException { + Class clazz = obj.getClass(); + Method getValue = clazz.getDeclaredMethod("get" + mothodName); + return getValue.invoke(obj); + } +} diff --git a/src/main/java/weaver/youhong/ai/pcn/hrorganization/wesmat/util/SyncOrganizationUtils.java b/src/main/java/weaver/youhong/ai/pcn/hrorganization/wesmat/util/SyncOrganizationUtils.java new file mode 100644 index 0000000..603f1b1 --- /dev/null +++ b/src/main/java/weaver/youhong/ai/pcn/hrorganization/wesmat/util/SyncOrganizationUtils.java @@ -0,0 +1,917 @@ +package weaver.youhong.ai.pcn.hrorganization.wesmat.util; + +import aiyh.utils.zwl.common.ToolUtil; +import com.ibm.icu.text.MessageFormat; +import com.ibm.icu.text.SimpleDateFormat; +import com.weaver.formmodel.util.EncryptHelper; +import com.weaver.general.TimeUtil; +import com.weaver.general.Util; +import org.h2.util.StringUtils; +import weaver.conn.RecordSet; +import weaver.youhong.ai.pcn.hrorganization.wesmat.model.Department; +import weaver.youhong.ai.pcn.hrorganization.wesmat.model.Employee; +import weaver.youhong.ai.pcn.hrorganization.wesmat.model.Position; + +import java.lang.reflect.InvocationTargetException; +import java.util.Date; +import java.util.HashMap; +import java.util.Map; + +/** + * @author EBU7-dev1-ayh + * @create 2021/7/22 0022 10:06 + * 同步人员组织结构工具类 + */ + + +public class SyncOrganizationUtils extends ToolUtil { + private static final String className = "SyncOrganization_Cronjob"; + + public Map asyncDepartment(Department department) { +// writeErrorLog( "---------------"+className+" asyncDepartment Begin --------------------"); + GetModelValue getModelValue = new GetModelValue<>(); + Map successMark = new HashMap<>(); + RecordSet rs = new RecordSet(); +// 所属分部id + int subcompanyid1 = 0; +// 上级部门的id + int supDepId = 0; +// 如果该部门是属于根部门,则需要进行分部的同步 + // 查询手动维护的分部信息表,将分部信息保存到分部表hrmsubcompany中,并且将部门的分部id赋值 + if (department.getPARENTDEPARTMENDID() == 0) { +// 查询mapping表,查看分部与部门的映射关系,通过部门id查询分部信息 + String querySql = "select * from uf_sub_mapping where frist_company = " + + Util.null2String(String.valueOf(department.getDEPARTMENTID())); +// 查询数据库 + try { + rs.executeQuery(querySql); + } catch (Exception e) { + writeErrorLog(className, "select subcomany error:" + querySql); + writeErrorLog("error info:" + e.getMessage() + "\n"); + successMark.put("code", "0"); + successMark.put("msg", "查询分部信息出错,错误SQL:" + querySql); + return successMark; + } + if (rs.next()) { + subcompanyid1 = Util.getIntValue(rs.getString("subcompany"), 0); + } + +// Map stringIntegerMap = this.subCompanyHandler(department); +// subcompanyid1 = stringIntegerMap.get("subcompanyid1"); +// supDepId = stringIntegerMap.get("supDepId"); + } else { +// 如果不是根部门,需要查询到他的父级部门,然后查出他的分部id +// 查询部门的父级部门 + try { + rs.executeQuery("select * from hrmdepartment where outkey = ?", Util.null2String(String.valueOf(department.getPARENTDEPARTMENDID()))); + } catch (Exception e) { + writeErrorLog("select hrmdepartment error in 51 line,sql: select * from hrmdepartment where outkey = " + Util.null2String(String.valueOf(department.getPARENTDEPARTMENDID()))); + writeErrorLog("error info:" + e.getMessage() + "\n"); + successMark.put("code", "0"); + successMark.put("msg", "查询分部信息出错,错误SQL:" + "select hrmdepartment error in 51 line,sql: select * from hrmdepartment where outkey = " + Util.null2String(String.valueOf(department.getPARENTDEPARTMENDID()))); + return successMark; + } + rs.next(); +// 将上级部门的分部id保存起来 + subcompanyid1 = Util.getIntValue(Util.null2String(rs.getString("subcompanyid1"))); +// 将上级部门的id保存起来 + supDepId = Util.getIntValue(Util.null2String(rs.getString("id"))); + } +// 处理部门信息 +// 查询HR同步配置表用于更新或者插入字段 查询配置表 + Map> configTableInfo = this.queryConfigTableInfo(department, getModelValue, "m.api_field_type = 0"); + Map sysDep = configTableInfo.get("sys"); + Map defDep = configTableInfo.get("def"); + +// 查询部门表,是否存在该部门 + String depSql = "select * from hrmdepartment where outkey = " + department.getDEPARTMENTID(); + try { + rs.executeQuery(depSql); + } catch (Exception e) { + writeErrorLog("select hrmdepartment error in 70 line, sql: " + depSql); + writeErrorLog("error info:" + e.getMessage() + "\n"); + successMark.put("code", "0"); + successMark.put("msg", "查询分部信息出错,错误SQL:" + depSql); + return successMark; + } + int finalSubcompanyid = subcompanyid1; + if (rs.next()) { +// 存在该部门 +// 拼接更新SQL +// 查询父级部门的id并更新 + String querySupId = "select * from hrmdepartment where outkey = ?"; + RecordSet r_rs = new RecordSet(); + r_rs.executeQuery(querySupId, department.getPARENTDEPARTMENDID()); + String supDepId1; + if (r_rs.next()) { + supDepId1 = r_rs.getString("id"); + sysDep.put("supdepid", supDepId1); + } + sysDep.put("subcompanyid1", String.valueOf(finalSubcompanyid)); + StringBuilder sysSetSql = this.builderSql(sysDep, 1).get("update"); + StringBuilder defSetSql = this.builderSql(defDep, 1).get("update"); +// 添加更新默认值 + Map sysMap = new HashMap<>(); + sysMap.put("modified", this.getTime()); + this.addDefaultUpdateSql(sysSetSql, sysMap); +// 更新数据库 + this.executeUpdateData(sysSetSql, "hrmdepartment", "id = " + Util.null2String(rs.getString("id"))); + this.executeUpdateData(defSetSql, "hrmdepartmentdefined", "deptid = " + Util.null2String(rs.getString("id"))); + successMark.put("code", "2"); + successMark.put("msg", "更新部门" + department.getPARENTDEPARTMENDID() + "成功!"); + } else { +// 拼接插入SQL +// 不存在部门信息 + Map insertSysBuilderMap = this.builderSql(sysDep, 2); + StringBuilder sysInsertSqlField = insertSysBuilderMap.get("insertField"); + StringBuilder sysInsertSqlValue = insertSysBuilderMap.get("insertValue"); + Map insertDefBuilderMap = this.builderSql(defDep, 2); + StringBuilder defInsertSqlField = insertDefBuilderMap.get("insertField"); + StringBuilder defInsertSqlValue = insertDefBuilderMap.get("insertValue"); +// 加入默认值 + int finalSupDepId = supDepId; + + Map map = new HashMap() {{ + // 外部系统主键 + put("outkey", Util.getIntValue(String.valueOf(department.getDEPARTMENTID()), 0)); + // 所属分部id + put("subcompanyid1", finalSubcompanyid); + // 上级部门id + put("supdepid", finalSupDepId); + put("departmentmark", Util.null2String(department.getDEPARTMENTNAME())); + put("departmentname", Util.null2String(department.getDEPARTMENTNAME())); + }}; + // 创建时间 + map.put("created", this.getTime()); + this.addDefaultInsertSql(sysInsertSqlField, sysInsertSqlValue, map); + int departmentId = 0; + this.executeInsertData(sysInsertSqlField, sysInsertSqlValue, "hrmdepartment"); +// 查询刚添加的部门id + try { + rs.executeQuery("select * from hrmdepartment where outkey = ?", Util.null2String(String.valueOf(department.getDEPARTMENTID()))); + } catch (Exception e) { + writeErrorLog("select hrmdepartment error in 112 line, sql: select * from hrmdepartment where outkey = " + Util.null2String(String.valueOf(department.getDEPARTMENTID()))); + writeErrorLog("error info:" + e.getMessage() + "\n"); + successMark.put("code", "0"); + successMark.put("msg", "查询分部信息出错,错误SQL:" + "select * from hrmdepartment where outkey = " + Util.null2String(String.valueOf(department.getDEPARTMENTID()))); + return successMark; + } + rs.next(); + departmentId = Util.getIntValue(Util.null2String(rs.getString("id"))); +// 设置默认值 + if (defInsertSqlField.lastIndexOf(",") != -1 && defInsertSqlValue.lastIndexOf(",") != -1) { + this.addDefaultInsertSql(defInsertSqlField, defInsertSqlValue, "deptid", departmentId); + } + this.executeInsertData(defInsertSqlField, defInsertSqlValue, "hrmdepartmentdefined"); + successMark.put("code", "1"); + successMark.put("msg", "插入部门" + department.getPARENTDEPARTMENDID() + "成功!"); + } + return successMark; +// writeErrorLog( "---------------"+className+" asyncDepartment end --------------------"); + } + + + public Map asyncPosition(Position position) { +// writeErrorLog( "---------------"+className+" asyncPosition Begin --------------------"); +// 职位同步的SQL + RecordSet rs = new RecordSet(); + Map successMark = new HashMap<>(); + try { + rs.executeQuery("select id from hrmjobtitles where outkey = ?", Util.getIntValues(String.valueOf(position.getJOBCODEID()))); + } catch (Exception e) { + writeErrorLog("select htmjobtitles error in 131 line, sql: select id from hrmjobtitles where outkey = " + Util.getIntValues(String.valueOf(position.getJOBCODEID()))); + writeErrorLog("error info:" + e.getMessage() + "\n"); + successMark.put("code", "0"); + successMark.put("msg", "查询职位错误,错误SQL:" + "select id from hrmjobtitles where outkey = " + Util.getIntValues(String.valueOf(position.getJOBCODEID()))); + return successMark; + } +// 判断该职位是否存在于系统中 + if (rs.next()) { +// 存在该条职位,需要进行职位的更新 + String updateSqlStr = MessageFormat.format("update hrmjobtitles set " + + "modified = ''{0}'', jobtitlemark = ''{1}'', jobtitlename = ''{2}'', cmsSupJobId = ''{3}'', " + + "jobtitlecode = ''{4}'' where outkey = ''{5}''", + this.getTime(), Util.null2String(position.getJOBFUNCTION()), Util.null2String(position.getJOBFUNCTION()), + Util.null2String(String.valueOf(position.getSUPERIORJOBCODEID())), Util.null2String(position.getJOBCODE()), Util.null2String(String.valueOf(position.getJOBCODEID()))); + // id + try { + rs.executeUpdate(updateSqlStr); + successMark.put("code", "2"); + successMark.put("msg", "更新职位" + position.getJOBCODEID() + "成功!"); + } catch (Exception e) { + writeErrorLog(className, "update jobtitle error: " + updateSqlStr); + writeErrorLog("error info:" + e.getMessage() + "\n"); + successMark.put("code", "0"); + successMark.put("msg", "更新职位失败,错误SQL:" + updateSqlStr); + return successMark; + } + } else { + +// 不存在该条职位 +// 判断该职位是否属于根职位(是否存在上级职位id),如果属于根职位,则需要进行创建工作类型(插入数据到工作类型表中) +// 并且创建职责数据,然后将数据插入到职位表中 +// 如果不是根职位,则需要判断其上级职位是否属于根职位,如果上级职位属于根职位,则需要插入职责表,同时工作类型为父级岗位的 +// 工作类型,然后将数据插入到职位表中,职责类型为刚插入的职责数据id。如果上级职位不属于根职位,则插入数据到职位表中, +// 职责id为父级职位的职责id + +// 判断是否是根职位 + if (position.getSUPERIORJOBCODEID() == 0) { +// 是根职位,插入数据到工作类型表中hrmjobgroups + int groupId = this.insertJobGroup(position); +// 插入数据到工作职责表中,并且绑定工作类型id为刚插入的数据的id + int activityId = this.insertJobActive(position, groupId); +// 将职位插入到职位表中,职责id为刚插入数据的id + this.insertJobTitle(position, rs, activityId, 0); + } else { +// 不是根职位,判断父职位是否属于根职位 + try { + rs.executeQuery("select * from hrmjobtitles where outkey = ?", Util.getIntValues(String.valueOf(position.getSUPERIORJOBCODEID()))); + } catch (Exception e) { + writeErrorLog("select htmjobtitles error in 166 line, sql: select * from hrmjobtitles where outkey = " + Util.getIntValues(String.valueOf(position.getJOBCODEID()))); + writeErrorLog("error info:" + e.getMessage() + "\n"); + successMark.put("code", "0"); + successMark.put("msg", "查询父级职位失败,错误SQL:" + "select * from hrmjobtitles where outkey = " + Util.getIntValues(String.valueOf(position.getSUPERIORJOBCODEID()))); + } + if (rs.next()) { + if (Util.getIntValue(Util.null2String(rs.getString("cmssupjobid"))) == 0) { +// 父职位属于根职位,获取父级职位的工作类型id + try { + rs.executeQuery("select * from hrmjobactivities where id = ?", Util.getIntValue(Util.null2String(rs.getString("jobactivityid")))); + } catch (Exception e) { + writeErrorLog("select hrmjobactivities error in 175 line, sql: select * from hrmjobactivities where id = " + Util.getIntValue(Util.null2String(rs.getString("jobactivityid")))); + writeErrorLog("error info:" + e.getMessage() + "\n"); + successMark.put("code", "0"); + successMark.put("msg", "查询父职位工作类型错误,错误SQL:" + "select * from hrmjobactivities where id = " + Util.getIntValue(Util.null2String(rs.getString("jobactivityid")))); + } + rs.next(); + int groupId = Util.getIntValue(Util.null2String(rs.getString("jobgroupid"))); +// 将数据插入到工作职责表中 + int activityId = this.insertJobActive(position, groupId); +// 将数据插入到职位表中 + this.insertJobTitle(position, rs, activityId, Util.getIntValue(String.valueOf(position.getSUPERIORJOBCODEID()))); + } else { +// 父级职位不属于根职位,获取父级职责id并将数据插入到职位表中 + int activityId = Util.getIntValue(Util.null2String(rs.getString("jobactivityid"))); +// 将数据插入到职位表中 + this.insertJobTitle(position, rs, activityId, Util.getIntValue(String.valueOf(position.getSUPERIORJOBCODEID()))); + } + } + } + successMark.put("code", "1"); + successMark.put("msg", "插入" + position.getJOBCODEID() + "成功!"); + } + return successMark; +// writeErrorLog( "---------------"+className+" asyncPosition end --------------------"); + } + + + public Map asyncEmployee(Employee employee) { +// writeErrorLog( "---------------"+className+" asyncEmployee Begin --------------------"); +// 直接上级 + int managerId = 0; + String managerStr = ""; + Map successMark = new HashMap<>(); +// 安全级别 + String seclevel = getSystemParamValue("HR_SECLEVEL"); + if (seclevel == null || "".equals(seclevel)) { + seclevel = "0"; + } + String password = getSystemParamValue("PASSWORD"); + if (StringUtils.isNullOrEmpty(password)) { + password = employee.getUSERCODE(); + } +// 人员id + int hrmid = 0; +// 不知道是否需要判断组织编码是否存在 + GetModelValue getModelValue = new GetModelValue<>(); + RecordSet rs = new RecordSet(); +// 查询配置表信息 + Map> configTableInfo = this.queryConfigTableInfo(employee, getModelValue, "m.api_field_type = 1"); + Map sysDep = configTableInfo.get("sys"); + Map defDep = configTableInfo.get("def"); +// 获取自定义字段的scopeid + rs.executeQuery("select * from cus_formfield"); + +// 查询人员的职责表,获取分部id,和直接上级id + Map subIdAndManagerIdMap = this.getSubIdAndManagerId(employee); + managerId = Util.getIntValue(String.valueOf(subIdAndManagerIdMap.get("managerId")), 0); + String departmentid = subIdAndManagerIdMap.get("departmentId").toString(); + String subcompanyid1 = subIdAndManagerIdMap.get("subCompanyId").toString(); + String today = TimeUtil.getCurrentDateString(); + // 根据outkey,询是否存在该人员 + String query = "select id from hrmresource where outkey = ?"; + try { + rs.executeQuery(query, Util.null2String(String.valueOf(employee.getUserID()))); + } catch (Exception e) { + writeErrorLog("select hrmresource error: " + query + Util.null2String(String.valueOf(employee.getUserID()))); + writeErrorLog("error info:" + e.getMessage() + "\n"); + successMark.put("code", "0"); + successMark.put("msg", "查询出错,错误SQL:" + "select hrmresource error: " + query + Util.null2String(String.valueOf(employee.getUserID()))); + return successMark; + } + if (rs.next()) { +// 存在人员信息,获取到人员id + hrmid = Util.getIntValue(rs.getString("id")); +// 更新人员信息,拼接更新SQL + StringBuilder sysSetSql = this.builderSql(sysDep, 1).get("update"); +// StringBuilder defSetSql = this.builderSql(defDep, employee, getModelValue,1).get("update"); + Map sysMap = new HashMap() {{ + put("departmentid", subIdAndManagerIdMap.get("departmentId")); + put("subcompanyid1", subIdAndManagerIdMap.get("subCompanyId")); + }}; + // 查询该人员的职位信息 +// 查询到当前职位的id + String jobId = String.valueOf(subIdAndManagerIdMap.get("jobtitleId")); + sysMap.put("jobtitle", jobId); + if (null != subIdAndManagerIdMap.get("managerstr")) { + managerStr = subIdAndManagerIdMap.get("managerstr").toString(); + if (!managerStr.startsWith(",")) { + managerStr = "," + managerStr; + } + if (!managerStr.endsWith(",")) { + managerStr = managerStr + ","; + } + managerStr = managerStr + managerId + ","; + sysMap.put("managerstr", managerStr); + sysMap.put("managerid", managerId); + } + + sysMap.put("managerid", managerId); + sysMap.put("modified", this.getTime()); + + this.addDefaultUpdateSql(sysSetSql, sysMap); + + this.executeUpdateData(sysSetSql, "hrmresource", "id = '" + hrmid + "'"); +// 待完善更新自定义人员信息表 +// 判断该字段的scopeid + for (Map.Entry entry : defDep.entrySet()) { +// 判断该字段属于的scopeid + String fieldId = entry.getKey().replace("field", ""); + try { + rs.executeQuery("select * from cus_formfield where fieldid = '" + Util.null2String(fieldId) + "' and scope = 'HrmCustomFieldByInfoType'"); + } catch (Exception e) { + writeErrorLog("select cus_fromfield error: select * from cus_formfield where fieldid = '" + Util.null2String(fieldId) + "' and scope = 'HrmCustomFieldByInfoType'"); + writeErrorLog("error info:" + e.getMessage() + "\n"); + } + rs.next(); + String scopeid = Util.null2String(rs.getString("scopeid")); +// 判断是否存在该信息,如果存在着更新,不存在着插入 + rs.executeQuery("select id from cus_fielddata where id = '" + hrmid + "' and scope = 'HrmCustomFieldByInfoType' and scopeid = '" + scopeid + "'"); + if (rs.next()) { +// 存在该信息,更新指定信息 + try { + rs.executeUpdate("update cus_fielddata set " + entry.getKey() + " = '" + entry.getValue() + "' where scopeid = " + scopeid + " and id = " + hrmid); + } catch (Exception e) { + writeErrorLog(className, "update error, sql: update cus_fielddata set " + entry.getKey() + " = " + entry.getValue() + " where scopeid = \" + scopeid +\" and id = \" + hrmid"); + writeErrorLog("error info:" + e.getMessage() + "\n"); + } + + } else { +// 不存在该信息,插入 + try { + rs.executeUpdate("insert into cus_fielddata (id,scopeid,scope," + entry.getKey() + ") values ('" + hrmid + "','" + scopeid + "','HrmCustomFieldByInfoType','" + entry.getValue() + "')"); + } catch (Exception e) { + writeErrorLog(className, "insert into error, sql : \"insert into cus_fielddata (id,scopeid,scope,\" + entry.getKey() + \") values ('\" + hrmid + \"','\" + scopeid + \"','HrmCustomFieldByInfoType','\" + entry.getValue() + \"')\""); + writeErrorLog("error info:" + e.getMessage() + "\n"); + } + } +// + } +// this.executeUpdateData(defSetSql,"cus_fielddata",""); + successMark.put("code", "2"); + successMark.put("msg", "更新成功!"); + } else { +// 不存在人员信息需要将人员信息插入到数据库中 +// 获取当前人员表中的最大id + rs.executeProc("HrmResourceMaxId_Get", ""); + rs.next(); + hrmid = rs.getInt(1); + if (managerId == 0) { + managerId = hrmid; + } + +// 加入默认值 + String finalSeclevel = seclevel; + Map map = new HashMap() {{ + // 外部系统主键 + put("outkey", Util.null2String(String.valueOf(employee.getUserID()))); + // 所属分部id + put("subcompanyid1", subIdAndManagerIdMap.get("subCompanyId")); + // 部门id + put("departmentid", subIdAndManagerIdMap.get("departmentId")); +// 安全级别 + put("seclevel", finalSeclevel); +// 员工编号 + put("workcode", Util.null2String(employee.getUSERCODE())); +// 姓名 + put("lastname", Util.null2String(employee.getPreferred_Name()) + "/" + Util.null2String(employee.getUSERNAMECN())); + +// 岗位id + put("jobtitle", subIdAndManagerIdMap.get("jobtitleId")); +// 状态 + put("status", 1); +// 电话 + put("telephone", Util.null2String(employee.getTEL())); +// 移动电话 + put("mobile", Util.null2String(employee.getMOBILENO())); +// 电子邮件 + put("email", Util.null2String(employee.getEMAIL())); + + }}; + if (null != subIdAndManagerIdMap.get("managerstr")) { + managerStr = subIdAndManagerIdMap.get("managerstr").toString(); + if (!managerStr.startsWith(",")) { + managerStr = "," + managerStr; + } + if (!managerStr.endsWith(",")) { + managerStr = managerStr + ","; + } + managerStr = managerStr + managerId + ","; + map.put("managerstr", managerStr); + } +// userCode不为null的人员 + if (!StringUtils.isNullOrEmpty(employee.getUSERCODE())) { +// 登录名 + if (!map.containsKey("loginid")) { + map.put("loginid", employee.getUSERCODE()); + } +// 密码 + map.put("password", EncryptHelper.encodeMd5(password).toUpperCase()); + } else { + writeErrorLog("the employee hove not usercode: " + employee); + } + +// id + map.put("id", hrmid); +// 直接上级 + map.put("managerid", managerId); + // 创建时间 + map.put("created", this.getTime()); + for (Map.Entry entry : map.entrySet()) { + sysDep.remove(entry.getKey()); + } +// 拼接插入SQL + Map insertSysBuilderMap = this.builderSql(sysDep, 2); + StringBuilder sysInsertSqlField = insertSysBuilderMap.get("insertField"); + StringBuilder sysInsertSqlValue = insertSysBuilderMap.get("insertValue"); +// 拼接默认值SQL + this.addDefaultInsertSql(sysInsertSqlField, sysInsertSqlValue, map); + // 插入数据 + writeErrorLog("人员数据:" + employee.toString()); + this.executeInsertData(sysInsertSqlField, sysInsertSqlValue, "hrmresource"); + try { + if (departmentid == null || "".equals(departmentid)) { + departmentid = "0"; + } + if (subcompanyid1 == null || "".equals(subcompanyid1)) { + subcompanyid1 = "0"; + } + //共享信息 + char separator = Util.getSeparator(); + String p_para = "" + hrmid + separator + departmentid + separator + subcompanyid1 + separator + managerId + separator + seclevel + separator + managerStr + + separator + "0" + separator + "0" + separator + "0" + separator + "0" + separator + "0" + separator + "0"; +// this.writeDebuggerLog(p_para); + rs.executeProc("HrmResourceShare", p_para); + rs.executeProc("HrmResource_CreateInfo", "" + hrmid + separator + "1" + separator + today + separator + "1" + separator + today); + //触发器 + String para = "" + hrmid + separator + managerId + separator + departmentid + separator + subcompanyid1 + separator + "0" + separator + managerStr; + rs.executeProc("HrmResource_Trigger_Insert", para); + //入职维护状态 + rs.executeUpdate("insert into HrmInfoStatus (itemid,hrmid,status) values(1," + hrmid + ",1)"); + + rs.executeUpdate("insert into HrmInfoStatus (itemid,hrmid) values(2," + hrmid + ")"); + + rs.executeUpdate("insert into HrmInfoStatus (itemid,hrmid) values(3," + hrmid + ")"); + + rs.executeUpdate("insert into HrmInfoStatus (itemid,hrmid) values(10," + hrmid + ")"); + } catch (Exception e) { + writeErrorLog("error info:" + e.getMessage() + "\n"); + } +// 插入自定义信息表 + for (Map.Entry entry : defDep.entrySet()) { +// 判断该字段属于的scopeid + String fieldId = entry.getKey().replace("field", ""); + try { + rs.executeQuery("select * from cus_formfield where fieldid = '" + Util.null2String(fieldId) + "' and scope = 'HrmCustomFieldByInfoType'"); + } catch (Exception e) { + writeErrorLog("select cus_fromfield error: select * from cus_formfield where fieldid = '" + Util.null2String(fieldId) + "' and scope = 'HrmCustomFieldByInfoType'"); + writeErrorLog("error info:" + e.getMessage() + "\n"); + } + rs.next(); + String scopeid = rs.getString("scopeid"); +// 插入数据表中指定字段信息 + rs.executeUpdate("insert into cus_fielddata (id,scopeid,scope," + entry.getKey() + ") values ('" + hrmid + "','" + scopeid + "','HrmCustomFieldByInfoType','" + entry.getValue() + "')"); + } + successMark.put("code", "1"); + successMark.put("msg", "插入成功!"); + } + return successMark; +// writeErrorLog( "---------------"+className+" asyncEmployee end --------------------"); + } + + private void addDefaultUpdateSql(StringBuilder sqlBuilder, Map map) { + for (Map.Entry entry : map.entrySet()) { + sqlBuilder.append(entry.getKey()); + sqlBuilder.append(" = "); + sqlBuilder.append("'"); + sqlBuilder.append(entry.getValue()); + sqlBuilder.append("',"); + } + } + + /** + * 获取直接上级 + * + * @param employee 人员对象 + * @return 获取人员直接上级,分部id和部门id + */ + private Map getSubIdAndManagerId(Employee employee) { + Map map = new HashMap<>(); + RecordSet rs = new RecordSet(); +// 通过部门id查询该员工的分部id + String querySubIdAndId = "select id, subcompanyid1 from hrmdepartment where outkey = ?"; + try { + rs.executeQuery(querySubIdAndId, Util.null2String(String.valueOf(employee.getDEPARTMENTID()))); + } catch (Exception e) { + writeErrorLog("select hrmdepartment error: " + querySubIdAndId + Util.null2String(String.valueOf(employee.getDEPARTMENTID()))); + writeErrorLog("error info:" + e.getMessage() + "\n"); + } + rs.next(); +// 该员工所属部门id + String departmentId = Util.null2String(rs.getString("id")); +// 该员工所属分部id + String subCompanyId = Util.null2String(rs.getString("subcompanyid1")); + map.put("subCompanyId", subCompanyId); + map.put("departmentId", departmentId); +// 查询该员工的直接上级id => 查询该员工的职位的cmssupjobid对应的职位 +// 由于需要判断该员工的职位是否存在上级职位,所以不能一条SQL搞定,首先需要查询该员工的职位的上级职位id,也就是判断是否存在上级职位 + String queryJobTitleId = "select id,cmssupjobid from hrmjobtitles where outkey = ?"; +// 不知道需不需要在维护一下职位表中的所属部门id,如果需要的haunt将部门id更新进去就可以 +// 查询当前人员对应的职位id以及cms中的上级职位id + try { + rs.executeQuery(queryJobTitleId, Util.null2String(String.valueOf(employee.getJOBCODEID()))); + } catch (Exception e) { + writeErrorLog("select htmjobtitles error: " + queryJobTitleId + Util.null2String(String.valueOf(employee.getJOBCODEID()))); + writeErrorLog("error info:" + e.getMessage() + "\n"); + } + rs.next(); +// 获取职位id + map.put("jobtitleId", Util.null2String(rs.getString("id"))); +// 获取cms中的上级职位id,如果存在则查询上级职位的id,如果不存在则表示该人员表示没有直接上级 + int cmsSupId = Util.getIntValue(Util.null2String(rs.getString("cmssupjobid")), 0); +/* if (cmsSupId != 0) { +// 表示该职位拥有上级职位,需要查询上级职位对应的人员 + String queryManagerId = "select h.id,h.managerstr from hrmresource as h join hrmjobtitles as j on h.jobtitle = j.id where j.outkey = ?"; + try { + rs.executeQuery(queryManagerId, Util.null2String(String.valueOf(cmsSupId))); + } catch (Exception e) { + writeErrorLog("select hrmresource error: " + queryManagerId + Util.null2String(String.valueOf(cmsSupId))); + writeErrorLog("error info:" + e.getMessage() + "\n"); + } + if (rs.next()) { + map.put("managerId", Util.getIntValue(Util.null2String(rs.getString("id")))); + map.put("managerstr", Util.null2String(rs.getString("managerstr"))); + } else { + map.put("managerId", 0); + } + } else { +// 如果该职位没有上级职位,则将该员工的直接上级id设置为0 + map.put("managerId", 0); + }*/ + while (cmsSupId >= 0) { +// 表示该职位拥有上级职位,需要查询上级职位对应的人员 +// 新增 2022 04 22 根据日期排序 + String queryManagerId = "select h.id,h.managerstr from hrmresource as h join hrmjobtitles as j on h.jobtitle = j.id where j.outkey = ? and h.status in (0,1,2) ORDER BY h.id DESC"; + try { + rs.executeQuery(queryManagerId, Util.null2String(String.valueOf(cmsSupId))); + } catch (Exception e) { + writeErrorLog("select hrmresource error: " + queryManagerId + Util.null2String(String.valueOf(cmsSupId))); + writeErrorLog("error info:" + e.getMessage() + "\n"); + } + if (rs.next()) { + map.put("managerId", Util.getIntValue(Util.null2String(rs.getString("id")))); + map.put("managerstr", Util.null2String(rs.getString("managerstr"))); + break; + } else { + if (cmsSupId == 0) { + break; + } + queryJobTitleId = "select id,cmssupjobid from hrmjobtitles where outkey = ?"; +// 查询当前人员对应的职位id以及cms中的上级职位id + try { + rs.executeQuery(queryJobTitleId, Util.null2String(String.valueOf(cmsSupId))); + } catch (Exception e) { + writeErrorLog("select htmjobtitles error: " + queryJobTitleId + Util.null2String(String.valueOf(employee.getJOBCODEID()))); + writeErrorLog("error info:" + e.getMessage() + "\n"); + } + rs.next(); + cmsSupId = Util.getIntValue(Util.null2String(rs.getString("cmssupjobid"))); + map.put("managerId", 0); + } + } + /*else { +// 如果该职位没有上级职位,则将该员工的直接上级id设置为0 + map.put("managerId", 0); + }*/ + return map; + } + + /** + * 执行插入SQL + * + * @param insertFieldBuilder 需要插入的的字段 + * @param insertValueBuilder 需要插入的字段对应的值 + * @param table 表名 + */ + private void executeInsertData(StringBuilder insertFieldBuilder, StringBuilder insertValueBuilder, String table) { + RecordSet rs = new RecordSet(); + if (insertFieldBuilder.lastIndexOf(",") != -1 && insertValueBuilder.lastIndexOf(",") != -1) { +// 去除最后一个逗号 + String insertFiledStr = this.removeLastComma(insertFieldBuilder); + String insertValueStr = this.removeLastComma(insertValueBuilder); + String insertSysSql = "insert into " + table + " (" + insertFiledStr + ") values (" + insertValueStr + ")"; + try { + rs.executeUpdate(insertSysSql); + } catch (Exception e) { + writeErrorLog("insert " + table + " error: " + insertSysSql); + writeErrorLog("error info:" + e.getMessage() + "\n"); + } + } + writeWarningLog("不满足条件: " + insertFieldBuilder + ", " + insertValueBuilder); + } + + /** + * 执行更新语句 + * + * @param updateSqlBuilder 更新SQL的字符串 + * @param table 表名 + * @param conditions 条件 + */ + private void executeUpdateData(StringBuilder updateSqlBuilder, String table, String conditions) { + RecordSet rs = new RecordSet(); + if (updateSqlBuilder.lastIndexOf(",") != -1) { + String updateSqlBuilderStr = updateSqlBuilder.substring(0, updateSqlBuilder.lastIndexOf(",")); + String updateSql = "update " + table + " set " + updateSqlBuilderStr + " where " + conditions; + try { + rs.executeUpdate(updateSql); + } catch (Exception e) { + writeErrorLog("update " + table + " error: " + updateSql); + writeErrorLog("error info:" + e.getMessage() + "\n"); + } + } + } + + private String removeLastComma(StringBuilder sqlBuilder) { + return sqlBuilder.substring(0, sqlBuilder.lastIndexOf(",")); + } + + private void addDefaultInsertSql(StringBuilder filedBuilder, StringBuilder valueBuilder, String filedName, Object value) { + filedBuilder.append(filedName); + filedBuilder.append(","); + valueBuilder.append("'"); + valueBuilder.append(value); + valueBuilder.append("',"); + } + + private void addDefaultInsertSql(StringBuilder filedBuilder, StringBuilder valueBuilder, Map map) { + for (Map.Entry entry : map.entrySet()) { + filedBuilder.append(entry.getKey()); + filedBuilder.append(","); + valueBuilder.append("'"); + valueBuilder.append(entry.getValue()); + valueBuilder.append("',"); + } + } + + /** + * 分部信息处理 + * + * @param department 部门 + * @return + */ + private Map subCompanyHandler(Department department) { +// 企业(总部)id + int companyid = 1; +// 上级分部id + int supsubcomid = 0; + int subCompanyId; + int subcompanyid1 = 0; + int supDepId = 0; + RecordSet rs = new RecordSet(); + + + Map map = new HashMap<>(); +// 查询部门与手动维护的分部信息,并进行同步 + String subCompanySql = MessageFormat.format("select * from uf_subcompany where yjbmid = ''{0}''", String.valueOf(department.getDEPARTMENTID())); + if (rs.executeQuery(subCompanySql) && rs.next()) { + String subCompanyName = Util.null2String(rs.getString("fbmmc")); + String subCompanyDisc = Util.null2String(rs.getString("fbmms")); + subCompanyId = Util.getIntValue(Util.null2String(rs.getString("fbmid"))); +// 查询分部表,是否存在该分部 +// rs.executeQuery("select * from hrmsubcompany where id = ?", subCompanyId); + try { + rs.executeQuery("select * from hrmsubcompany where outkey = ?", Util.getIntValue(String.valueOf(subCompanyId))); + } catch (Exception e) { + writeErrorLog("select hrmsubcompany error: select * from hrmsubcompany where outkey = " + Util.getIntValue(String.valueOf(subCompanyId))); + writeErrorLog("error info:" + e.getMessage() + "\n"); + } + if (rs.next()) { +// 已经存在分部信息,保存部门对应分部id + subcompanyid1 = Util.getIntValue(Util.null2String(rs.getString("id"))); +// 设置上级部门id为0 + supDepId = 0; +// 更新分部信息 + String updateSql = "update hrmsubcompany set " + + "subcompanyname = '" + subCompanyName + + "', subcompanydesc = '" + subCompanyDisc + + "', modified = '" + this.getTime() + + "' where id = " + subcompanyid1; + rs.executeUpdate(updateSql); + + } else { +// 不存在分部信息 + String insertSql = "insert into hrmsubcompany " + + "(outkey,companyid,subcompanyname,subcompanydesc,created,supsubcomid) values ('" + + subCompanyId + "', '" + companyid + "', '" + subCompanyName + "','" + subCompanyDisc + "','" + + this.getTime() + "','" + supsubcomid + "')"; + rs.executeUpdate(insertSql); +// 查询刚插入的分部id + try { + rs.executeQuery("select * from hrmsubcompany where outkey = ?", subCompanyId); + } catch (Exception e) { + writeErrorLog("select hrmsubcompany error: select * from hrmsubcompany where outkey = " + subCompanyId); + writeErrorLog("error info:" + e.getMessage() + "\n"); + } + rs.next(); + subcompanyid1 = Util.getIntValue(Util.null2String(rs.getString("id"))); + } + } + map.put("subcompanyid1", subcompanyid1); + map.put("supDepId", supDepId); + return map; + } + + private Map builderSql(Map filedAndValue, int type) { + StringBuilder sql = new StringBuilder(); + Map map = new HashMap<>(); + if (type == 1) { +// 拼接更新SQL + for (Map.Entry entry : filedAndValue.entrySet()) { + sql.append(entry.getKey()).append(" = '"); + sql.append(entry.getValue()).append("',"); + } + map.put("update", sql); + return map; + } + if (type == 2) { +// 拼接插入SQL + StringBuilder sysInsertSqlField = new StringBuilder(); + StringBuilder sysInsertSqlValue = new StringBuilder(); + for (Map.Entry entry : filedAndValue.entrySet()) { + sysInsertSqlField.append(entry.getKey()); + sysInsertSqlField.append(","); + sysInsertSqlValue.append("'"); + sysInsertSqlValue.append(entry.getValue()); + sysInsertSqlValue.append("',"); + } + map.put("insertField", sysInsertSqlField); + map.put("insertValue", sysInsertSqlValue); + return map; + } + return map; + } + + private int insertJobGroup(Position position) { + RecordSet rs = new RecordSet(); + String insertJobGroups = MessageFormat.format("insert into hrmjobgroups (" + + "jobgroupname,jobgroupremark,created,outkey) values (" + + "''{0}'',''{1}'',''{2}'',''{3}'')", + position.getJOBFUNCTION(), position.getJOBFUNCTION(), this.getTime(), String.valueOf(position.getJOBCODEID())); + + try { + rs.executeUpdate(insertJobGroups); + } catch (Exception e) { + writeErrorLog("insert hrmjobgroups error: " + insertJobGroups); + writeErrorLog("error info:" + e.getMessage() + "\n"); + } + try { + rs.executeQuery("select * from hrmjobgroups where outkey = ?", Util.getIntValue(String.valueOf(position.getJOBCODEID()))); + } catch (Exception e) { + writeErrorLog("select hrmjobgroups error: select * from hrmjobgroups where outkey = " + Util.getIntValue(String.valueOf(position.getJOBCODEID()))); + writeErrorLog("error info:" + e.getMessage() + "\n"); + } + rs.next(); + return Util.getIntValue(Util.null2String(rs.getString("id"))); + } + + private int insertJobActive(Position position, int groupId) { + RecordSet rs = new RecordSet(); + String insertJobActive = MessageFormat.format("insert into hrmjobactivities (" + + "jobactivitymark,jobactivityname,jobgroupid,created,outkey) values (" + + "''{0}'',''{1}'',''{2}'',''{3}'',''{4}'')", + position.getJOBFUNCTION(), position.getJOBFUNCTION(), String.valueOf(groupId), this.getTime(), String.valueOf(position.getJOBCODEID())); + + try { + rs.executeUpdate(insertJobActive); + } catch (Exception e) { + writeErrorLog("insert hrmjobactivities error: " + insertJobActive); + writeErrorLog("error info:" + e.getMessage() + "\n"); + } + + try { + rs.executeQuery("select * from hrmjobactivities where outkey = ?", Util.getIntValue(String.valueOf(position.getJOBCODEID()))); + } catch (Exception e) { + writeErrorLog("select hrmjobactivities error: select * from hrmjobactivities where outkey = " + Util.getIntValue(String.valueOf(position.getJOBCODEID()))); + writeErrorLog("error info:" + e.getMessage() + "\n"); + } + rs.next(); + return Util.getIntValue(Util.null2String(rs.getString("id"))); + } + + private void insertJobTitle(Position position, RecordSet rs, int activityId, int cmsSupJobId) { + String insertJobTitle = MessageFormat.format("insert into hrmjobtitles (" + + "jobtitlemark,jobtitlename,jobactivityid,jobtitlecode,created,outkey,cmssupjobid) values (" + + "''{0}'',''{1}'',''{2}'',''{3}'',''{4}'',''{5}'',''{6}'')", + position.getJOBFUNCTION(), position.getJOBFUNCTION(), String.valueOf(activityId), position.getJOBCODE(), + this.getTime(), String.valueOf(position.getJOBCODEID()), String.valueOf(cmsSupJobId)); + try { + rs.executeUpdate(insertJobTitle); + } catch (Exception e) { + writeErrorLog("insert hrmjobtitles error: " + insertJobTitle); + writeErrorLog("error info:" + e.getMessage() + "\n"); + } + + } + + /** + * 查询配置表字段信息 + * + * @return + */ + public Map> queryConfigTableInfo(Object obj, GetModelValue getModelValue, String conditions) { + RecordSet rs = new RecordSet(); + Map> configResults = new HashMap<>(); + try { + rs.executeQuery("select d.id,m.api_field_type,d.api_field,d.change_rules,d.custom_rules_value,d.ao_field,oa_field_type from uf_cms_async as m " + + "inner join uf_cms_async_dt1 as d on d.mainid = m.id where " + conditions); + } catch (Exception e) { + writeErrorLog("select configTable error: " + "select d.id,m.api_field_type,d.api_field,d.change_rules,d.custom_rules_value,d.ao_field,oa_field_type from uf_cms_async as m " + + "inner join uf_cms_async_dt1 as d on d.mainid = m.id where " + conditions); + writeErrorLog("error info:" + e.getMessage() + "\n"); + } + Map sysDep = new HashMap<>(); + Map defDep = new HashMap<>(); +// 判断转换规则,如果是自定义SQL,则需要先执行SQL,如果是固定值,则需要进行直接赋值,如果是不转换,则按照默认走 + while (rs.next()) { + String apiFieldType = Util.null2String(rs.getString("api_field_type")); + String oaFieldType = Util.null2String(rs.getString("oa_field_type")); + String apiField = Util.null2String(rs.getString("api_field")); + int changeRules = Util.getIntValue(Util.null2String(rs.getString("change_rules"))); + if (changeRules == 0) { +// 转换规则为不转换,获取api字段对应的值 + try { + apiField = (String) getModelValue.getValueForString(obj, apiField); + } catch (NoSuchMethodException | InvocationTargetException | IllegalAccessException e) { + this.writeErrorLog(className, "changeRules error,args is: apiField[" + apiField + "],obj[" + obj + "]"); + e.printStackTrace(); + } + } else if (changeRules == 2) { +// 转换规则为自定义SQL + String customRulesValue = Util.null2String(rs.getString("custom_rules_value")); + if (customRulesValue.contains("delete") || customRulesValue.contains("update") || + customRulesValue.contains("exec") || customRulesValue.contains("drop") || + customRulesValue.contains("truncate")) { +// sql 不包含delete,update,exec,drop,truncate等危险关键字 + } else if (customRulesValue.contains("select")) { +// 包含查询关键词 + try { + rs.executeQuery(customRulesValue); + } catch (Exception e) { + writeErrorLog("execute custom sql error: " + customRulesValue); + writeErrorLog("error info:" + e.getMessage() + "\n"); + } + rs.next(); + apiField = Util.null2String(rs.getString(1)); + } + } else { + apiField = Util.null2String(rs.getString("custom_rules_value")); + } +// 如果属于系统字段 + if ("0".equals(oaFieldType)) { + sysDep.put(Util.null2String(rs.getString("ao_field").replace(apiFieldType + oaFieldType, "")).toLowerCase(), apiField); + } else { +// 属于自定义字段 + defDep.put(Util.null2String(rs.getString("ao_field").replace(apiFieldType + oaFieldType, "")).toLowerCase(), apiField); + } + } + configResults.put("sys", sysDep); + configResults.put("def", defDep); + return configResults; + } + + public String getTime() { + Date date = new Date(); + SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSS"); + return formatter.format(date); + } +} diff --git a/src/main/resources/WEB-INF/log4j.xml b/src/main/resources/WEB-INF/log4j.xml index 1f26a27..16d8f1a 100644 --- a/src/main/resources/WEB-INF/log4j.xml +++ b/src/main/resources/WEB-INF/log4j.xml @@ -3,17 +3,18 @@ - + - + - + - + \ No newline at end of file diff --git a/src/test/java/basetest/BaseTest.java b/src/test/java/basetest/BaseTest.java index 2255e2a..48eb512 100644 --- a/src/test/java/basetest/BaseTest.java +++ b/src/test/java/basetest/BaseTest.java @@ -28,9 +28,12 @@ public class BaseTest { private ApplicationContext ctx; private Properties properties; + protected final Logger log = Util.getLogger(); + private static Properties propertiesStatic; + @BeforeClass - public static void beforeStatic(){ + public static void beforeStatic() { BaseTest.getContextStatic(); GCONST.setServerName(propertiesStatic.getProperty("serverName")); GCONST.setRootPath(propertiesStatic.getProperty("rootPath")); @@ -57,22 +60,22 @@ public class BaseTest { // 使用properties对象加载输入流 try { properties.load(in); - if(in != null){ - try{ + if (in != null) { + try { in.close(); - }catch (IOException ex){ + } catch (IOException ex) { } } Enumeration enumeration = propertiesXml.propertyNames(); - while (enumeration.hasMoreElements()){ + while (enumeration.hasMoreElements()) { String key = (String) enumeration.nextElement(); String value = propertiesXml.getProperty(key); - properties.setProperty(key,value); + properties.setProperty(key, value); } this.properties = properties; } catch (IOException ex) { - throw new CustomerException("未发现application.properties",ex); + throw new CustomerException("未发现application.properties", ex); } } @@ -103,22 +106,22 @@ public class BaseTest { // 使用properties对象加载输入流 try { properties.load(in); - if(in != null){ - try{ + if (in != null) { + try { in.close(); - }catch (IOException ex){ + } catch (IOException ex) { } } Enumeration enumeration = propertiesXml.propertyNames(); - while (enumeration.hasMoreElements()){ + while (enumeration.hasMoreElements()) { String key = (String) enumeration.nextElement(); String value = propertiesXml.getProperty(key); - properties.setProperty(key,value); + properties.setProperty(key, value); } propertiesStatic = properties; } catch (IOException ex) { - throw new CustomerException("未发现application.properties",ex); + throw new CustomerException("未发现application.properties", ex); } } diff --git a/src/test/java/youhong/ai/pcn/TestOrganization.java b/src/test/java/youhong/ai/pcn/TestOrganization.java index d3c61ba..951c979 100644 --- a/src/test/java/youhong/ai/pcn/TestOrganization.java +++ b/src/test/java/youhong/ai/pcn/TestOrganization.java @@ -1,17 +1,14 @@ package youhong.ai.pcn; -import aiyh.utils.Util; -import com.alibaba.fastjson.JSON; -import ebu7common.youhong.ai.sftp.SftpConnectUtil; import basetest.BaseTest; -import org.apache.log4j.Logger; +import ebu7common.youhong.ai.sftp.SftpConnectUtil; import org.junit.Test; import weaver.general.GCONST; -import weaver.youhong.ai.pcn.hrorganization.sftp.FetchDataUtil; import java.io.BufferedReader; import java.io.FileNotFoundException; import java.io.FileReader; +import java.io.IOException; import java.util.ArrayList; import java.util.Arrays; import java.util.LinkedList; @@ -29,30 +26,29 @@ import java.util.regex.Pattern; public class TestOrganization extends BaseTest { - private Logger log = Util.getLogger(); - @Test - public void testSftp(){ + public void testSftp() throws IOException { SftpConnectUtil sftpConnectUtil = new SftpConnectUtil( "HR Digital_PROD", - "/Users/aoey.oct.22/company/Fan_wei/ssl/pcn/HR_Digital_PROD.pem",null,"222.73.197.242", - null,1000 * 100 + "/Users/aoey.oct.22/company/Fan_wei/ssl/pcn/HR_Digital_PROD.pem", null, "222.73.197.242", + null, 1000 * 100 ); - FetchDataUtil fetchDataUtil = new FetchDataUtil(); - fetchDataUtil.downloadFile(sftpConnectUtil, + + String hris_positionExport20221120 = sftpConnectUtil.downFile( "HRIS_PositionExport20221120", GCONST.getSysFilePath() + "HRIS_PositionExport20221120.csv"); + System.out.println(hris_positionExport20221120); } @Test - public void testStaticLog(){ + public void testStaticLog() { log.info("哈哈哈好的方式"); } @Test - public void testReadCsv(){ + public void testReadCsv() { String srcPath = GCONST.getSysFilePath() + "HRIS_PositionExport20221120" + ".csv"; // String charset = "utf-8"; // try (CSVReader csvReader = new CSVReaderBuilder(new BufferedReader(new InputStreamReader(new FileInputStream(new File(srcPath)), charset))).build()) {