新增:添加service,util包和主类(运行类)

dev
cs 3 months ago
parent 082e0631ce
commit 61825be40b

@ -0,0 +1,17 @@
package edu.ahbvc.recruit;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
/**
* @author c215
*/
@SpringBootApplication
@MapperScan(basePackages = "edu.ahbvc.recruit.mapper")
public class RecruitApplication {
public static void main(String[] args) {
SpringApplication.run(RecruitApplication.class, args);
}
}

@ -0,0 +1,54 @@
package edu.ahbvc.recruit.service;
import java.util.List;
import edu.ahbvc.recruit.mapper.AdminInter;
import org.springframework.stereotype.Service;
import edu.ahbvc.recruit.model.Admin;
/**
* @author c215
*/
@Service
public class AdminServiceImpl {
private final AdminInter mapper;
public AdminServiceImpl(AdminInter mapper) {
this.mapper = mapper;
}
public Admin getOne(int id) {
return mapper.getOne(id);
}
public String isAdmin(String phone) {
return mapper.isAdmin(phone);
}
public Integer getAdminsNum(String name,String phone) {
return mapper.getAdminsNum(name, phone);
}
public Admin login(String num, String pwd) {
return mapper.login(num, pwd);
}
public List<Admin> getAdmins(int offset, int size, String name, String phone) {
return mapper.getAdmins(offset, size, name, phone);
}
public int addAdmin(Admin admin) {
return mapper.addAdmin(admin);
}
public int delAdmin(int id) {
return mapper.delAdmin(id);
}
public int updateAdmin(Admin ad) {
return mapper.updateAdmin(ad);
}
}

@ -0,0 +1,251 @@
package edu.ahbvc.recruit.service;
import edu.ahbvc.recruit.mapper.ThingInter;
import edu.ahbvc.recruit.model.Batch;
import edu.ahbvc.recruit.model.Position;
import edu.ahbvc.recruit.model.Thing;
import edu.ahbvc.recruit.model.ThingWithUser;
import edu.ahbvc.recruit.model.export.Excel;
import edu.ahbvc.recruit.model.export.Ticket;
import edu.ahbvc.recruit.util.AdmissionTicketCreater;
import edu.ahbvc.recruit.util.ExcelExporter;
import edu.ahbvc.recruit.util.file.FilePatch;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.dao.DataIntegrityViolationException;
import org.springframework.stereotype.Service;
import java.util.ArrayList;
import java.util.List;
/**
* @author c215
*/
@Service
public class ThingServiceImpl {
private static final Logger log = LoggerFactory.getLogger(ThingServiceImpl.class);
private final ThingInter mapper;
@Autowired
public ThingServiceImpl(ThingInter mapper) {
this.mapper = mapper;
}
public List<ThingWithUser> getThings(List<Integer> id) {
return mapper.getThingsById(id);
}
public List<ThingWithUser> getThings(int currentPage, int size, List<Integer> jobTitles,
List<Integer> batch, List<Integer> status, String name) {
List<ThingWithUser> list = mapper.getThings(currentPage, size, jobTitles, batch, status, name);
if(!list.isEmpty()) {
System.out.println(list.get(list.size()-1).getTime());
}
return list;
}
public List<ThingWithUser> getAuditThings(int currentPage, int size, List<Integer> jobTitles,
List<Integer> batch) {
return mapper.getAuditThings(currentPage, size, jobTitles, batch);
}
public Integer getThingsNum(List<Integer> jobTitles, List<Integer> batch, List<Integer> status, String name) {
return mapper.getThingsNum(jobTitles, batch, status, name);
}
public int getUnsettledThingsNum() {
return mapper.getUnsettledThingsNum();
}
public List<Batch> getBatchOption() {
return mapper.getBatchOption();
}
public Batch getBatch(int id) {
return mapper.getBatch(id);
}
public int updateBatch(Batch batch) {
return mapper.updateBatch(batch);
}
public int switchBatchOpen(int id) {
mapper.updateBatchClose();
return mapper.updateBatchOpen(id);
}
public int addBatch(Batch batch) {
return mapper.addBatch(batch);
}
public int delBatch(int id) {
return mapper.delBatch(id);
}
public List<Batch> getBatches(int currentPage, int size, String key, Integer state) {
return mapper.getBatches(currentPage, size, key, state);
}
public Batch getCurrentBatches() {
return mapper.getCurrentBatch();
}
public List<Batch> getOpenBatches() {
return mapper.getBatches(0, Integer.MAX_VALUE, null, 1);
}
public int getBatchesNum(String key, Integer state) {
return mapper.getBatchesNum(key, state);
}
public List<Position> getPositionOption() {
return mapper.getPositionOption();
}
public List<Position> getPositions(int currentPage, int size) {
return mapper.getPositions(currentPage, size);
}
public int getPositionsNum() {
return mapper.getPositionsNum();
}
public List<Position> getSomePosition(int batchId, int offset, int size) {
return mapper.getSomePosition(batchId, offset, size);
}
public Position getOnePosition(int id) {
return mapper.getOnePosition(id);
}
public int addPosition(Position p) {
return mapper.addPosition(p);
}
public int delPosition(int id) {
return mapper.delPosition(id);
}
public int delPositions(List<Integer> id) {
int i;
try {
i = mapper.delPositions(id);
} catch (DataIntegrityViolationException e) {
// 记录异常信息
log.error(e.getMessage());
// 返回一个错误标志
return -1;
}
return i;
}
public int updatePosition(Position p) {
return mapper.updatePosition(p);
}
public List<Batch> getthingForuser(int userid, int batch) {
return mapper.getthingForuser(userid, batch);
}
public int refuseThing(int thingid, int status, String qualificationResult) {
return mapper.refuseThing(thingid, status, qualificationResult);
}
public int updateThingStatus(int thingid, int status) {
return mapper.updateThingStatus(thingid, status);
}
public int updateThingInfo(int thingid, String awardsAndPunishments, String note, String qualificationResult) {
return mapper.updateThingInfo(thingid, awardsAndPunishments, note, qualificationResult);
}
public int updateThingInfo(int thingid, String qualificationResult) {
return mapper.updateThingQualification(thingid, qualificationResult);
}
public ThingWithUser getOneThing(int thingid) {
return mapper.getOneThing(thingid);
}
public List<Thing> getThingAboutUser(int userid) {
return mapper.getThingAboutUser(userid);
}
public List<Thing> getRecruits(int currentPage, int size, List<Integer> jobTitles, List<Integer> batch) {
return mapper.getRecruits(currentPage, size, jobTitles, batch);
}
public int getRecruitNum(List<Integer> jobTitles, List<Integer> batch) {
return mapper.getRecruitNum(jobTitles, batch);
}
public int addRecruit(Integer batchid, Integer positionid) {
return mapper.addRecruit(batchid, positionid);
}
public int updateRecruit(Integer id, Integer batchid, Integer positionid) {
return mapper.updateRecruit(id, batchid, positionid);
}
public int deleteRecruit(int id) {
try {
return mapper.deleteRecruit(id);
} catch (DataIntegrityViolationException e) {
// 捕获外键约束违反异常
log.error(e.getMessage());
// 返回一个错误标志
return -1;
}
}
public String outPutExcel() {
String saveExcelFilePath = FilePatch.SaveExcelFilePath;
ArrayList<Excel> printData = mapper.getPrintData();
int excelFile = ExcelExporter.getExcelFile(saveExcelFilePath);
int excel = ExcelExporter.exportToExcel(printData,saveExcelFilePath);
if(excel!=0) {
return null;
}
return saveExcelFilePath + "招聘总表.xlsx";
}
public String previewTicket(Integer id, Integer recruitid) {
Ticket ticketData = mapper.getTicketData(recruitid, id);
return AdmissionTicketCreater.generateUserDocument(ticketData);
}
public int conformPrintTicket(Integer thingid, Integer recruitid) {
int ticketNum = mapper.getTicketNum(recruitid);
int printedTicket = mapper.isPrintedTicket(thingid);
int ticketData;
if(printedTicket==0)
// 如果是没有打印过准考证的,就去当前岗位中的最大值加一
{
ticketData = mapper.setTicketPrinted(ticketNum+1, thingid);
} else
// 否则就使用原来的准考证序号
{
ticketData = mapper.setTicketPrinted(printedTicket, thingid);
}
return ticketData;
}
public int getOldTicketNum(Integer thingid, Integer recruitid) {
return mapper.isPrintedTicket(thingid);
}
public boolean isPrintedTicket(Integer thingid) {
int ticketData = mapper.isPrintedTicket(thingid);
return ticketData!=0;
}
}

@ -0,0 +1,356 @@
package edu.ahbvc.recruit.service;
import ch.qos.logback.classic.Logger;
import edu.ahbvc.recruit.mapper.UserInter;
import edu.ahbvc.recruit.model.ThingWithUser;
import edu.ahbvc.recruit.model.User;
import edu.ahbvc.recruit.model.resume.*;
import edu.ahbvc.recruit.util.file.FilePatch;
import jakarta.servlet.http.HttpServletResponse;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.dao.DataIntegrityViolationException;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Service;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
/**
* @author c215
*/
@Service
public class UserServiceImpl {
private static final org.slf4j.Logger log = LoggerFactory.getLogger(UserServiceImpl.class);
private final UserInter mapper;
private boolean isDev;
@Autowired
public UserServiceImpl(UserInter mapper) {
this.mapper = mapper;
}
public User getOne(int id) {
return mapper.getOne(id);
}
public UserInfo getOneInfo(int id) {
return mapper.getOneInfo(id);
}
public List<User> getUsers(int offset, int size, String name, String tel, String idNum, Integer degree) {
return mapper.getUsers(offset, size, name, tel, idNum);
}
public int getUsersNum(String name, String tel, String idNum, Integer degree) {
return mapper.getUsersNum(name, tel, idNum, degree);
}
public int getUsersNum() {
return mapper.getUsersNum(null, null, null, null);
}
public User login(String account, String pwd) {
return mapper.login(account, pwd);
}
/**
* @param phone
* @param pwd
* @return ,newUser,
*
*/
public User registerByPhone(String phone, String pwd) {
int i = mapper.registerByPhone(phone, pwd);
if (i == 1) {
return getNewUser();
}
return null;
}
public int abandon(int userid, int thingId) {
return mapper.abandon(thingId, userid);
}
public int applyJob(int userid, int recruitId) {
int thingExist = mapper.thingExist(userid, recruitId);
if (thingExist == 1) {
return 2;
}
return mapper.applyJob(userid, recruitId);
}
public int applyJob2(int userid, int recruitId, String awardsAndPunishments, String note) {
int thingExist = mapper.thingExist(userid, recruitId);
if (thingExist == 1) {
return 2;
}
return mapper.applyJob2(userid, recruitId, awardsAndPunishments, note);
}
public int reTryJob(int userid, int thingId) {
int thingExist = mapper.thingExist2(thingId);
System.out.println(thingExist + "thingExist");
if (thingExist == 1) {
return mapper.reTryJob(thingId);
}
return thingExist;
}
public List<User> getThingUsers(int thingId) {
return mapper.getThingUsers(thingId);
}
/**
* @param idNum
* @return ,01
*/
public int exists(String idNum) {
return mapper.exists(idNum);
}
/**
* @param userId id
* @return boolean:
*/
public boolean alreadyRecruit(String userId) {
int i = mapper.alreadyRecruit(userId);
return i != 0;
}
public int existsByPhone(String phone) {
return mapper.existsByPhone(phone);
}
public User getNewUser() {
return mapper.getNewUser();
}
public int addUser(User u) {
return mapper.addUser(u);
}
public int delUser(int id) {
try {
return mapper.delUser(id);
} catch (DataIntegrityViolationException e) {
// 捕获外键约束违反异常
log.error(e.getMessage());
// 返回一个错误标志
return -1;
}
}
public int updateUserName(User user) {
return mapper.updateUserName(user);
}
public int updateUserPwd(int id, String pwd) {
return mapper.updateUserPwd(id, pwd);
}
public int updateUserPwdByOld(int id, String oldPwd, String pwd) {
return mapper.updateUserPwdByOld(id, pwd, oldPwd);
}
public int updateUser2(User user) {
return mapper.updateUser2(user);
}
public int updateUser(UserInfo user) {
return mapper.updateUser(user);
}
public int updateRealName(int id, String idNum, String name) {
int exist = mapper.exists(idNum);
if (exist != 0) {
return 2;
}
return mapper.updateRealName(id, idNum, name);
}
public void delUserResumeAllData(int processedUserid) {
mapper.delUserResumeAllData(processedUserid);
}
public int addEducation(int userId, ArrayList<Education> e) {
if (e.isEmpty()) {
return 0;
}
for (Education education : e) {
education.setId(userId);
}
return mapper.addEducation(e);
}
public ArrayList<Education> getEducation(int userId) {
return mapper.getEducation(userId);
}
public int addWorkExperience(int userId, ArrayList<WorkExperience> e) {
if (e.isEmpty()) {
return 0;
}
for (WorkExperience workExperience : e) {
workExperience.setId(userId);
}
return mapper.addWorkExperience(e);
}
public ArrayList<WorkExperience> getWorkExperience(int userId) {
return mapper.getWorkExperience(userId);
}
public int addPaper(int userId, ArrayList<Paper> e) {
if (e.isEmpty()) {
return 0;
}
for (Paper paper : e) {
paper.setId(userId);
}
return mapper.addPaper(e);
}
public ArrayList<Paper> getPaper(int userId) {
return mapper.getPaper(userId);
}
public int addProject(int userId, ArrayList<Project> e) {
if (e.isEmpty()) {
return 0;
}
for (Project project : e) {
project.setId(userId);
}
return mapper.addProject(e);
}
public ArrayList<Project> getProject(int userId) {
return mapper.getProject(userId);
}
public int addResearch(int userId, ArrayList<Research> e) {
if (e.isEmpty()) {
return 0;
}
for (Research research : e) {
research.setId(userId);
}
return mapper.addResearch(e);
}
public ArrayList<Research> getResearch(int userId) {
return mapper.getResearch(userId);
}
public int addFamilyConnections(int userId, ArrayList<FamilyConnections> e) {
if (e.isEmpty()) {
return 0;
}
for (FamilyConnections familyConnections : e) {
familyConnections.setId(userId);
}
return mapper.addFamilyConnections(e);
}
/**
*
*
* @return
*/
public User getCurrentUser() {
Object principal = SecurityContextHolder.getContext().getAuthentication().getPrincipal();
if (principal == null) {
return null;
}
if (principal instanceof User) {
return (User) principal;
} else {
log.warn("当前用户不是 User 类型");
throw new IllegalStateException("用户状态异常:非User类型");
}
}
public ArrayList<FamilyConnections> getFamilyConnections(int userId) {
return mapper.getFamilyConnections(userId);
}
public static void writeFileToResponse(boolean isExcel,String filePath, HttpServletResponse response) throws IOException {
System.out.println(filePath);
filePath = filePath.replaceAll("\\\\", "/");
// 设置响应类型(根据实际情况调整)
response.setContentType("application/octet-stream");
response.setHeader("Content-Disposition", "attachment; filename=\""
+ filePath.substring(filePath.lastIndexOf('/') + 1) + "\"");
OutputStream outputStream = response.getOutputStream();
try (FileInputStream fileInputStream = new FileInputStream(filePath)) {
byte[] buffer;
if (isExcel) {
// 针对excel文件缓冲区大小设置为1.6kb
buffer = new byte[4096 * 4];
} else {
// 针对其他文件缓冲区大小设置为4K
buffer = new byte[4096];
}
int bytesRead;
while ((bytesRead = fileInputStream.read(buffer)) != -1) {
outputStream.write(buffer, 0, bytesRead);
}
} finally {
// 刷新缓冲区
outputStream.flush();
}
}
/**
* ,,,url
* @param thingInfo
* @return ,,url
*/
public HashMap<String, Object> getThingAndResume(ThingWithUser thingInfo) {
Integer userId = thingInfo.getUserId();
String code = thingInfo.getCode();
User user = this.getOne(userId);
ArrayList<Education> education = this.getEducation(userId);
ArrayList<WorkExperience> workExperience = this.getWorkExperience(userId);
ArrayList<Paper> paper = this.getPaper(userId);
ArrayList<Project> project = this.getProject(userId);
ArrayList<Research> research = this.getResearch(userId);
ArrayList<FamilyConnections> familyConnections = this.getFamilyConnections(userId);
HashMap<String, Object> map = new HashMap<>();
for (int i = 0; i < 7; i++) {
List<String> fileUrl = FilePatch.getFileUrl(code, userId, i, isDev, false);
map.put("file" + i, fileUrl);
}
List<String> IDPhotos = FilePatch.getFileUrl(code, userId, 0, isDev, true);
String onePhoto = null;
if (IDPhotos != null && !IDPhotos.isEmpty()) {
onePhoto = IDPhotos.get(IDPhotos.size() - 1);
}
map.put("userinfo", user);
map.put("education", education);
map.put("workExperience", workExperience);
map.put("paper", paper);
map.put("project", project);
map.put("research", research);
map.put("family", familyConnections);
map.put("note", thingInfo.getNote());
map.put("qualificationResult", thingInfo.getQualificationResult());
map.put("awardsAndPunishments", thingInfo.getAwardsAndPunishments());
map.put("IDPhoto", onePhoto);
return map;
}
}

@ -0,0 +1,29 @@
package edu.ahbvc.recruit.service.api;
import edu.ahbvc.recruit.model.api.ImageCaptchaResponse;
import edu.ahbvc.recruit.model.api.SMApiResponse;
import org.springframework.context.annotation.Bean;
import org.springframework.stereotype.Repository;
import org.springframework.stereotype.Service;
/**
* API
* @author c215
*/
@Service
public interface ApiService {
String MOCK_CAPTCHA = "1";
/**
*
* @return
*/
ImageCaptchaResponse getImgCode();
/**
*
* @param captcha
* @param tel
* @return
*/
SMApiResponse sendSM(String captcha, String tel);
}

@ -0,0 +1,59 @@
package edu.ahbvc.recruit.service.api;
import edu.ahbvc.recruit.model.api.ImageCaptchaResponse;
import edu.ahbvc.recruit.model.api.JsonReader;
import edu.ahbvc.recruit.model.api.SMApiResponse;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Profile;
import org.springframework.stereotype.Repository;
/**
* @author c215
*/
@Profile("dev")
//上方注解表示该类在开发环境下才会被加载
@Repository
//上方注解表示该类是一个Repository, 用于数据访问
public class MockApiServiceImpl implements ApiService {
/**
* 使Log4j2 LogManagerLogger
*
*/
private static final Logger logger = LogManager.getLogger(MockApiServiceImpl.class);
/**
*
* Image verification code
* @return ,
* @see <a href="https://www.apispace.com/eolink/api/lwtpyzmsc/apiDocument"></a>
*/
@Override
public ImageCaptchaResponse getImgCode() {
JsonReader<ImageCaptchaResponse> jsonReader = new JsonReader<>();
String json = "{\"statusCode\":\"000000\",\"desc\":\"请求成功\",\"result\":{\"fileName\":\"https://data.apishop.net/checkcode/ar4wb9us16f5ezn3.png\",\"verifyCode\":\"1\"}}";
// 输出api返回的结果
logger.debug("开发模式图片验证码api返回模拟数据");
return jsonReader.processApiResponse(json, ImageCaptchaResponse.class);
}
@Override
public SMApiResponse sendSM(String captcha, String tel){
// 开发环境下直接返回
// String json = "{\"code\":\"0\",\"msg\":\"SUCCESS\",\"smUuid\":\"38801_1_0_17756800661_1_4lDRlmcSyW_1\"}";
SMApiResponse processApiResponse = new SMApiResponse();
processApiResponse.setCode("0");
processApiResponse.setMessage("SUCCESS");
processApiResponse.setSmUuid("38801_1_0_17756800661_1_4lDRlmcSyW_1");
return processApiResponse;
}
}

@ -0,0 +1,140 @@
package edu.ahbvc.recruit.service.api;
import edu.ahbvc.recruit.model.api.ImageCaptchaResponse;
import edu.ahbvc.recruit.model.api.JsonReader;
import edu.ahbvc.recruit.model.api.SMApiResponse;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.springframework.context.annotation.Profile;
import org.springframework.http.*;
import org.springframework.stereotype.Repository;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.util.MultiValueMap;
import org.springframework.web.client.RestTemplate;
import java.net.URI;
import java.net.URISyntaxException;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;
/**
* @author c215
*/
@Profile("prod")
@Repository
public class RealApiServiceImpl implements ApiService {
/**
* 使Log4j2 LogManagerLogger
*
*/
private static final Logger logger = LogManager.getLogger(RealApiServiceImpl.class);
/**
*
* Image verification code
* @return ,
* @see <a href="https://www.apispace.com/eolink/api/lwtpyzmsc/apiDocument"></a>
*/
@Override
public ImageCaptchaResponse getImgCode() {
URI url = null;
try {
url = new URI("https://eolink.o.apispace.com/lwtpyzmsc/common/verify/getComplicateVerifyImage");
} catch (URISyntaxException e) {
logger.error("图片验证码URI异常");
logger.error(e);
}
// 准备调用api的请求头
HttpHeaders headers = new HttpHeaders();
String MyKey = "p4jb13padiv8g31wdaqlva6xoeoygdnw";
headers.add("X-APISpace-Token", MyKey);
headers.add("Authorization-Type", "apikey");
headers.setContentType(MediaType.APPLICATION_FORM_URLENCODED);
JsonReader<ImageCaptchaResponse> jsonReader = new JsonReader<>();
// 准备调用api的请求体
MultiValueMap<String, String> requestBody = new LinkedMultiValueMap<>();
//验证码类型
// (1:纯数字,2:小写字母,3:大写字母,4:数字+小写字母,5:数字+大写字母,6:数字+大小写字母,7:大小写字母)
requestBody.add("codeType", "1");
RestTemplate restTemplate = new RestTemplate();
// 发送调用api请求
RequestEntity<MultiValueMap<String, String>> requestEntity = new RequestEntity<>(
requestBody, headers, HttpMethod.POST, url);
// 返回结果是JSON,转换成字符串
ResponseEntity<String> responseEntity = restTemplate.exchange(requestEntity, String.class);
// api返回的内容是JSON
String responseData = responseEntity.getBody();
// 输出api返回的结果
logger.debug("图片验证码api返回结果" + responseData);
ImageCaptchaResponse processApiResponse;
processApiResponse = jsonReader.processApiResponse(responseData, ImageCaptchaResponse.class);
return processApiResponse;
}
@Override
public SMApiResponse sendSM(String captcha, String tel){
URI url = null;
try {
url = new URI("http://api.1cloudsp.com/api/v2/single_send");
} catch (URISyntaxException e) {
logger.info("短信验证码URI异常");
logger.error(e);
}
// 准备调用api的请求头
HttpHeaders headers = new HttpHeaders();
headers.add("Authorization-Type", "apikey");
headers.setContentType(MediaType.APPLICATION_FORM_URLENCODED);
// 用户开发key
String accesskey = "nBWSTPoSwKmBbP81";
// 用户开发秘钥
String accessSecret = "Tp5u0ff4K3qpzoqDcxtHaDgcTYGphSQw";
// 准备调用api的请求体
MultiValueMap<String, String> requestBody = new LinkedMultiValueMap<>();
requestBody.add("accesskey", accesskey);
requestBody.add("secret", accessSecret);
requestBody.add("sign", "299439");
requestBody.add("templateId", "277804");
requestBody.add("mobile", tel);
requestBody.add("content", URLEncoder.encode(captcha, StandardCharsets.UTF_8));
RestTemplate restTemplate = new RestTemplate();
JsonReader<SMApiResponse> jsonReader = new JsonReader<>();
// 发送调用api请求
RequestEntity<MultiValueMap<String, String>> requestEntity = new RequestEntity<>(
requestBody, headers, HttpMethod.POST, url);
// 返回结果是JSON,转换成字符串
ResponseEntity<String> responseEntity = restTemplate.exchange(requestEntity, String.class);
// api返回的内容是JSON
String responseData = responseEntity.getBody();
// 输出api返回的结果
logger.info("短信验证码api返回结果" + responseData);
SMApiResponse processApiResponse;
processApiResponse = jsonReader.processApiResponse(responseData, SMApiResponse.class);
return processApiResponse;
}
}

@ -0,0 +1,147 @@
package edu.ahbvc.recruit.util;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.List;
import edu.ahbvc.recruit.model.export.Ticket;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.apache.poi.xwpf.usermodel.ParagraphAlignment;
import org.apache.poi.xwpf.usermodel.XWPFDocument;
import org.apache.poi.xwpf.usermodel.XWPFParagraph;
import org.apache.poi.xwpf.usermodel.XWPFRun;
import org.apache.poi.xwpf.usermodel.XWPFTable;
import org.apache.poi.xwpf.usermodel.XWPFTableCell;
import org.apache.poi.xwpf.usermodel.XWPFTableRow;
/**
* @author c215
*/
public class AdmissionTicketCreater {
private static final Logger logger = LogManager.getLogger(AdmissionTicketCreater.class);
/**
*
*/
public static final String templatePath
= "C:/ahbvcSystem/Recruit/template/template.docx";
/**
*
*/
public static final String outputBasePath
= "C:/ahbvcSystem/Recruit/admission_ticket";
/**
* @param data
* @return docx
*/
public static String generateUserDocument(Ticket data) {
if (data == null) {
throw new IllegalArgumentException("data cannot be null");
}
XWPFDocument document = null;
String result;
try {
// 读取模板文件
FileInputStream templateFile = new FileInputStream(templatePath);
document = new XWPFDocument(templateFile);
String ticketNum = null;
// 处理模板中的表格
for (XWPFTable table : document.getTables()) {
for (XWPFTableRow row : table.getRows()) {
for (XWPFTableCell cell : row.getTableCells()) {
String text = cell.getText();
if (!text.startsWith("{{")) {
continue;
}
List<XWPFParagraph> paragraphs = cell.getParagraphs();
XWPFParagraph paragraph = paragraphs.get(0);
List<XWPFRun> runs = paragraph.getRuns();
XWPFRun templateXwpfRun = runs.get(0);
// 保存文本对齐方式
ParagraphAlignment alignment = paragraph.getAlignment();
// 添加新段落
XWPFParagraph addParagraph = cell.addParagraph();
// 重新应用文本对齐方式
addParagraph.setAlignment(alignment);
if (data.getTicketNumber().length() == 1) {
ticketNum = data.getCode() + "000" + data.getTicketNumber();
} else if (data.getTicketNumber().length() == 2) {
ticketNum = data.getCode() + "00" + data.getTicketNumber();
} else if (data.getTicketNumber().length() == 3) {
ticketNum = data.getCode() + "0" + data.getTicketNumber();
}
if (ticketNum != null) {
text = text.replace("{{ticketNum}}", ticketNum);
}
text = text.replace("{{name}}", data.getName());
text = text.replace("{{idnum}}", data.getIdnum());
text = text.replace("{{positionid}}", data.getCode());
populateCellWithFormattedText(cell, text, templateXwpfRun, addParagraph);
}
}
}
logger.info("准考证填充完成,准备保存");
String path = outputBasePath + File.separatorChar + data.getCode() + File.separatorChar;
File folder = new File(path);
boolean success = folder.mkdir();
if (success) {
logger.info("文件夹创建成功");
} else {
if (folder.exists()) {
logger.info("文件夹已经存在");
} else {
logger.info("文件夹创建失败");
}
}
// 保存生成的文档
FileOutputStream outputFile = new FileOutputStream(
path + data.getName() + "_" + ticketNum + ".docx");
//admission_ticket\null3416212.docx (系统找不到指定的路径。)
document.write(outputFile);
result = path + data.getName() + "_" + ticketNum + ".docx";
/*
* C:\ahbvcSystem\Recruit\admission_ticket\4000189\341621200302160414.docx
* C:\ahbvcSystem\Recruit\admission_ticket\4000189\341621200302160414.docx
*/
logger.info(result + "保存成功");
outputFile.close();
} catch (IOException e) {
logger.error("生成准考证失败", e);
return null;
} finally {
if (document != null) {
try {
document.close();
} catch (IOException e) {
logger.error("关闭文档失败", e);
}
}
}
return result;
}
public static void populateCellWithFormattedText(XWPFTableCell cell, String text, XWPFRun templateXwpfRun, XWPFParagraph addParagraph) {
for (int i = 0; i < text.length(); i++) {
XWPFRun newRun = addParagraph.createRun();
newRun.setText(String.valueOf(text.charAt(i)));
newRun.setFontFamily(templateXwpfRun.getFontFamily());
Double fontSize = templateXwpfRun.getFontSizeAsDouble();
if (fontSize != null) {
newRun.setFontSize(fontSize);
}
newRun.setBold(templateXwpfRun.isBold());
}
cell.removeParagraph(0);
}
}

@ -0,0 +1,173 @@
package edu.ahbvc.recruit.util;
import edu.ahbvc.recruit.model.export.Excel;
import edu.ahbvc.recruit.model.resume.Education;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.apache.poi.ss.usermodel.*;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.ArrayList;
/**
* @author c215
*/
public class ExcelExporter {
/**
* 使Log4j2 LogManagerLogger
*/
private static final Logger logger = LogManager.getLogger(ExcelExporter.class);
/**
* @param data Excel
* @param path Excel
* @return 0:,,-1:
*/
public static int exportToExcel(ArrayList<Excel> data, String path) {
if (data == null) {
logger.warn("传入数据为空");
return -1;
}
logger.info("开始生成总表");
Workbook workbook = new XSSFWorkbook();
Sheet sheet = workbook.createSheet("Data");
// 设置样式解决含有'\n'不自动换行的问题
CellStyle cellStyle = workbook.createCellStyle();
// 设置单元格样式为自动换行
cellStyle.setWrapText(true);
// Create header row
Row headerRow = sheet.createRow(0);
// Assuming first column is "No", second is "Code", etc.
String[] columnHeaders = {"序号", "岗位代码", "姓名", "性别", "出生日期", "身份证号码", "政治面貌", "民族", "毕业学校", "所学专业", "学历", "学位",
"毕业时间", "联系电话", "资格审查结果", "备注"};
for (int i = 0; i < columnHeaders.length; i++) {
Cell cell = headerRow.createCell(i);
cell.setCellValue(columnHeaders[i]);
}
// Fill data
int rowNum = 1;
for (Excel item : data) {
Row row = sheet.createRow(rowNum++);
row.createCell(0).setCellValue(rowNum - 1);
row.createCell(1).setCellValue(item.getCode());
row.createCell(2).setCellValue(item.getName());
row.createCell(3).setCellValue(item.getSex() == 1 ? "男" : "女");
row.createCell(4).setCellValue(item.getBirthday());
row.createCell(5).setCellValue(item.getIdnum());
row.createCell(6).setCellValue(item.getZzmm());
row.createCell(7).setCellValue(item.getNation());
StringBuilder school = new StringBuilder();
StringBuilder specialty = new StringBuilder();
StringBuilder education = new StringBuilder();
StringBuilder degree = new StringBuilder();
StringBuilder graduationTime = new StringBuilder();
for (int i = 0; i < item.getEducation().size(); i++) {
boolean end = i == item.getEducation().size() - 1;
Education e = item.getEducation().get(i);
String educations = switch (e.getEducation()) {
case 0 -> "专科";
case 1 -> "本科";
case 2 -> "研究生";
default -> "异常";
};
/* 将学历转换成汉字 */
String degrees = switch (e.getDegree()) {
case 0 -> "暂无";
case 1 -> "学士";
case 2 -> "硕士";
case 3 -> "博士";
default -> "异常";
};
school.append(e.getSchool());
specialty.append(e.getSpecialty());
education.append(educations);
degree.append(degrees);
graduationTime.append(e.getGraduationTime());
if (!end) {
school.append("\n");
specialty.append("\n");
education.append("\n");
degree.append("\n");
graduationTime.append("\n");
}
}
Cell schoolcell = row.createCell(8);
schoolcell.setCellStyle(cellStyle);
schoolcell.setCellValue(school.toString());
Cell specialtycell = row.createCell(9);
specialtycell.setCellStyle(cellStyle);
specialtycell.setCellValue(specialty.toString());
Cell educationcell = row.createCell(10);
educationcell.setCellStyle(cellStyle);
educationcell.setCellValue(education.toString());
Cell degreecell = row.createCell(11);
degreecell.setCellStyle(cellStyle);
degreecell.setCellValue(degree.toString());
Cell graduationTimecell = row.createCell(12);
graduationTimecell.setCellStyle(cellStyle);
graduationTimecell.setCellValue(graduationTime.toString());
row.createCell(13).setCellValue(item.getPhone());
String sta = switch (item.getStatus()) {
case -2 -> "已拒绝";
case -1 -> "拒绝待确认";
case 0 -> "未处理";
case 1 -> "同意待确认";
case 2 -> "已同意";
default -> "异常";
};
row.createCell(14).setCellValue(sta);
row.createCell(15).setCellValue(item.getNote());
}
int graduationTimeColumnIndex = 12;
// 生日列设12个字符宽
sheet.setColumnWidth(4, 12 * 256);
// 身份证号列设18个字符宽
sheet.setColumnWidth(5, 20 * 256);
// 毕业院校列设18个字符宽
sheet.setColumnWidth(8, 18 * 256);
// 专业列设18个字符宽
sheet.setColumnWidth(9, 18 * 256);
// 毕业时间列设8个字符宽
sheet.setColumnWidth(12, 8 * 256);
// 手机号列设12个字符宽
sheet.setColumnWidth(13, 12 * 256);
sheet.setColumnWidth(graduationTimeColumnIndex, 20 * 256);
logger.error("生成总表Excel成功,开始保存 ");
// Write the workbook to a file
try {
FileOutputStream outputStream = new FileOutputStream(path + "招聘总表.xlsx");
workbook.write(outputStream);
workbook.close();
} catch (IOException e) {
logger.error("保存导出的Excel发生IO错误");
return -1;
}
return 0;
}
public static int getExcelFile(String path) {
File folder = new File(path);
File[] fileList = folder.listFiles();
if (fileList == null || fileList.length == 0) {
return 0;
} else if (fileList.length > 1) {
return 2;
}
return 1;
}
}

File diff suppressed because it is too large Load Diff

File diff suppressed because it is too large Load Diff

@ -0,0 +1,92 @@
package edu.ahbvc.recruit.util;
import edu.ahbvc.recruit.model.token.Token;
import io.jsonwebtoken.Claims;
import io.jsonwebtoken.JwtException;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import java.lang.reflect.Field;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
public class JwtUtil {
private static final Logger logger = LogManager.getLogger(JwtUtil.class);
private static final String KEY = "321ahbvc431e21y123342h1f1u32dia2323ej322133f21h11jskl23afh1djl3a1hfj21kdlahf";
public static String createJWT(Token token) {
if (token.getUserId() != null) {
Date expiration = token.getExpiration();
Map<String, Object> map = new HashMap<>();
Field[] fields = token.getClass().getDeclaredFields();
for (Field field : fields) {
field.setAccessible(true);
try {
map.put(field.getName(), field.get(token));
} catch (IllegalAccessException e) {
logger.error(e);
}
}
return Jwts.builder().signWith(SignatureAlgorithm.HS256, KEY)
.setExpiration(expiration).setClaims(map).compact();
}
return null;
}
public static Token parseJWT(String authorizationHeader) {
String stringToken;
// 根据具体情况定义对应的对象类型
Token token = new Token();
if (authorizationHeader != null && authorizationHeader.startsWith("Bearer ")) {
stringToken = authorizationHeader.substring(7);
} else {
logger.warn("用户递交非法token请求头");
return null;
}
Claims claims;
try {
claims = Jwts.parser().setSigningKey(KEY).parseClaimsJws(stringToken).getBody();
} catch (JwtException e) {
// 处理其他JwtException情况例如签名不匹配等
logger.warn("用户递交无效token请求头");
return null;
}
// 判断token是否过期
Date expiration = claims.getExpiration();
Date now = new Date();
if (expiration != null && expiration.before(now)) {
// token已过期
logger.info("用户递交token请求头已经过期");
return null;
}
// 读取token对应的信息
Field[] fields = token.getClass().getDeclaredFields();
for (Field field : fields) {
field.setAccessible(true);
if (claims.containsKey(field.getName())) {
// 将属性值设置到对象中
try {
Object value = claims.get(field.getName());
if (value instanceof Long && (field.getType().equals(Date.class))) {
value = new Date((Long) value);
}
field.set(token, value);
} catch (IllegalArgumentException | IllegalAccessException e) {
logger.error("读取token失败");
logger.error(e);
return null;
}
}
}
return token;
}
}

@ -0,0 +1,132 @@
package edu.ahbvc.recruit.util.file;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.multipart.MultipartFile;
import java.io.*;
import java.nio.file.Paths;
import java.util.ArrayList;
import java.util.List;
/**
* @author c215
*/
public class FilePatch {
public static final String SEP = File.separator;
public static final String SaveExcelFilePath = "";
public static final String SaveUserFileNodePath = "user_resume_files";
private static final Logger logger = LoggerFactory.getLogger(FilePatch.class);
public static String SaveUserFileContextPath = "C:\\ahbvcSystem\\.metadata\\.plugins\\org.eclipse.wst.server.core\\tmp1\\wtpwebapps\\Recruit\\";
public static String getSaveUserFileContextPath() {
return SaveUserFileContextPath;
}
public static void setSaveUserFileContextPath(String saveUserFileContextPath) {
SaveUserFileContextPath = saveUserFileContextPath;
}
/**
* @param code
* @param userid id
* @param part 0:,1:,2:,3:,4:,5:,6:,7:,8:,9:,10:,11:,12:,13:,14:,15:,16:,17:,18:
* @param isDev
* @param isIdNum
* @return
*/
public static List<String> getFileUrl(String code, Integer userid, int part, boolean isDev, boolean isIdNum) {
String path;
if (isIdNum) {
path = SaveUserFileContextPath + SaveUserFileNodePath + SEP + "userPhoto" + SEP + userid;
} else {
path = SaveUserFileContextPath + SaveUserFileNodePath + SEP + code + SEP + userid + SEP + part;
}
// 获取目标路径下的文件列表
File folder = new File(path);
File[] fileList = folder.listFiles();
List<String> paths = new ArrayList<>();
if (fileList != null) {
for (File fileItem : fileList) {
String absolutePath = fileItem.getAbsolutePath();
logger.info("文件列表\n" + absolutePath);
System.out.println("文件列表\n" + absolutePath);
int index = absolutePath.indexOf("user_resume");
// 相对路径(user_resume_file/1/2/3/filename.txt)
String relativePath = absolutePath.substring(index);
if (isDev) {
relativePath = "https://supposedly-credible-cougar.ngrok-free.app/Recruit/" + relativePath;
}
relativePath = relativePath.replace("\\", "/");
paths.add(relativePath.replaceAll("\\\\", "/"));
}
return paths;
}
// 目标路径文件列表为空,返回空
return null;
}
public static String setFile(String realPath, String code, Integer userid, Integer part, Boolean isIdNum,
MultipartFile file) {
if (!"".equals(realPath)) {
if ("".equals(SaveUserFileContextPath)) {
SaveUserFileContextPath = realPath;
}
}
if (file != null) {
String path = buildFilePath(userid, code, part, isIdNum);
try {
// 将文件保存到指定路径
file.transferTo(Paths.get(path, file.getOriginalFilename()));
return path;
} catch (IllegalStateException | IOException e) {
logger.error("文件保存失败", e);
return null;
}
}
return null;
}
public static String buildFilePath(Integer userid, String code, Integer part, Boolean isIdNum) {
//
//10:33:40.496 [http-nio-8092-exec-10] INFO edu.ahbvc.controller.UserController:系统上下文物理地址
//10:33:40.496 [http-nio-8092-exec-10] INFO edu.ahbvc.controller.UserController:C:\ahbvcSystem\.metadata\.plugins\org.eclipse.wst.server.core\tmp1\wtpwebapps\Recruit\
//目录创建成功:{}C:\ahbvcSystem\.metadata\.plugins\org.eclipse.wst.server.core\tmp1\wtpwebapps\Recruit\(Unicode 无效)user_resume_files\15\22\61\1091\img
String path;
if (isIdNum) {
path = SaveUserFileContextPath + SaveUserFileNodePath + SEP + "userPhoto" + SEP + userid;
} else {
path = SaveUserFileContextPath + SaveUserFileNodePath + SEP + code + SEP + userid + SEP + part;
}
File directory = new File(path);
if (!directory.exists() && directory.mkdirs()) {
logger.info("目录创建成功:{}", path);
System.out.println("目录创建成功:{}" + path);
} else {
logger.info("目录已存在或创建失败:{}", path);
System.out.println("目录已存在或创建失败:{}" + path);
}
return path;
}
public static void modifyLogToFile(String oldIdnum, String oldName, String idnum2, String name2) {
// 声明打印流对象
PrintStream ps = null;
// 如果现在是使用FileOuputStream实例化意味着所有的输出是向文件之中
try {
ps = new PrintStream(new FileOutputStream(SaveUserFileContextPath + "userModifyLog.txt"));
} catch (FileNotFoundException e) {
logger.error("修改记录的txt未找到");
logger.error("请在" + SaveUserFileContextPath + "下建立:userModifyLog.txt");
}
if (ps != null) {
ps.println("更改:");
ps.println(" " + oldName + "," + oldIdnum + ",到:" + name2 + "," + idnum2);
ps.close();
}
}
}

@ -0,0 +1,28 @@
package edu.ahbvc.recruit.util.file;
public class FilePathModel {
private String path = "";
public FilePathModel() {
super();
}
public FilePathModel(String path) {
super();
this.path = path;
}
public String getPath() {
return path;
}
public void setPath(String path) {
this.path = path;
}
@Override
public String toString() {
return "FilePath [path=" + path + "]";
}
}

@ -0,0 +1,513 @@
package edu.ahbvc.recruit.util.file;
import edu.ahbvc.recruit.model.resume.*;
import edu.ahbvc.recruit.util.AdmissionTicketCreater;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.apache.poi.xwpf.usermodel.*;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
/**
* @author c215
*/
public class UserQualificationsCreator {
/**
*
*/
public static final String TEMPLATE_PATH =
"C:/ahbvcSystem/Recruit/template/uiTemplate.docx";
/**
*
*/
public static final String BLANK_TEMPLATE_PATH =
"C:/ahbvcSystem/Recruit/template/uiTemplate2.docx";
/**
*
*/
public static final String OUTPUT_BASE_PATH = "C:\\ahbvcSystem\\Recruit\\UserQualifications";
private static final Logger logger = LogManager.getLogger(UserQualificationsCreator.class);
/**
* @param data
* @return docx
*/
public static String generateUserDocument(UserResume data) {
XWPFDocument document = null;
String result;
try {
// 读取模板文件
FileInputStream templateFile = new FileInputStream(TEMPLATE_PATH);
document = new XWPFDocument(templateFile);
// 遍历段落,查找并替换内容
List<XWPFParagraph> paragraphsHead = document.getParagraphs();
for (XWPFParagraph paragraph : paragraphsHead) {
// 获取段落中所有的运行对象
for (XWPFRun run : paragraph.getRuns()) {
// 获取运行对象中的文本内容
String runText = run.getText(0);
if (runText != null && runText.contains("{{code}}")) {
// 替换文本内容
runText = runText.replace("{{code}}", data.getCode());
// 清空运行对象中的文本内容
run.setText("", 0);
// 添加替换后的文本内容
run.setText(runText, 0);
}
}
}
// 处理模板中的表格
for (XWPFTable table : document.getTables()) {
int rowOffset = 0;
ArrayList<Project> projects = data.getProject();
ArrayList<Project> projects0 = new ArrayList<>();
ArrayList<Project> projects1 = new ArrayList<>();
ArrayList<Project> projects2 = new ArrayList<>();
for (Project project : projects) {
if (project.getType() == 0) {
projects0.add(project);
} else if (project.getType() == 1) {
projects1.add(project);
} else if (project.getType() == 2) {
projects2.add(project);
}
}
List<XWPFTableRow> rows = table.getRows();
for (int rowIndex = 0; rowIndex < rows.size(); rowIndex++) {
logger.info("总行数" + rows.size());
XWPFTableRow row = rows.get(rowIndex);
if (rowIndex <= 8) {
// 第九行以前的
for (XWPFTableCell cell : row.getTableCells()) {
String text = cell.getText();
if (!text.startsWith("{{")) {
continue;
}
UserInfo info = data.getInfo();
// 将模板中的占位符替换成数据源中对应的数据
text = repleteString(text, info);
if (text == null) {
text = "";
}
List<XWPFParagraph> paragraphs = cell.getParagraphs();
XWPFParagraph paragraph = paragraphs.get(0);
List<XWPFRun> runs = paragraph.getRuns();
XWPFRun templateXwpfRun = runs.get(0);
// 保存文本对齐方式
ParagraphAlignment alignment = paragraph.getAlignment();
// 添加新段落
// 重新应用文本对齐方式
XWPFParagraph addParagraph = cell.addParagraph();
addParagraph.setAlignment(alignment);
AdmissionTicketCreater.populateCellWithFormattedText(cell, text, templateXwpfRun, addParagraph);
}
// } else if (lineCount == 910) {
} else if (rowIndex == 9) {
ArrayList<Education> education = data.getEducation();
int educationSize = education.size();
List<XWPFTableCell> tableCells = row.getTableCells();
if (educationSize == 1) {
// // 替换值
loadEducationData(education.get(0), tableCells);
}
if (education.size() > 1) {
XWPFTableRow backupRow = new XWPFTableRow(row.getCtRow(), table);
for (int i = 0; i < education.size() - 1; i++) {
XWPFTableRow blankRow = new XWPFTableRow(backupRow.getCtRow(), table);
loadEducationData(education.get(i), blankRow.getTableCells());
table.addRow(blankRow, 9);
rowOffset++;
rowIndex++;
}
loadEducationData(education.get(education.size() - 1), tableCells);
}
} else if (rowIndex == 13 + rowOffset) {
// 工作经历
ArrayList<WorkExperience> workExperiences = data.getWorkExperience();
logger.info("准备装载" + workExperiences);
int workExperienceSize = workExperiences.size();
List<XWPFTableCell> tableCells = row.getTableCells();
if (workExperienceSize == 1) {
// 替换值
loadWorkExperienceData(workExperiences.get(0), tableCells);
}
if (workExperiences.size() > 1) {
XWPFTableRow backupRow = new XWPFTableRow(row.getCtRow(), table);
for (int i = 0; i < workExperiences.size() - 1; i++) {
XWPFTableRow blankRow = new XWPFTableRow(backupRow.getCtRow(), table);
loadWorkExperienceData(workExperiences.get(i), blankRow.getTableCells());
table.addRow(blankRow, 13 + rowOffset);
rowOffset++;
rowIndex++;
}
loadWorkExperienceData(workExperiences.get(workExperiences.size() - 1), tableCells);
}
} else if (rowIndex == 16 + rowOffset) {
// 论文
ArrayList<Paper> paper = data.getPaper();
logger.info("准备装载" + paper);
int paperSize = paper.size();
List<XWPFTableCell> tableCells = row.getTableCells();
if (paperSize == 1) {
loadPaperData(paper.get(0), tableCells);
}
if (paperSize > 1) {
XWPFTableRow backupRow = new XWPFTableRow(row.getCtRow(), table);
for (int i = 0; i < paper.size() - 1; i++) {
XWPFTableRow blankRow = new XWPFTableRow(backupRow.getCtRow(), table);
loadPaperData(paper.get(i), blankRow.getTableCells());
table.addRow(blankRow, rowIndex);
rowOffset++;
rowIndex++;
}
loadPaperData(paper.get(paperSize - 1), tableCells);
}
} else if (rowIndex == 19 + rowOffset) {
// 教/科研项目
logger.info("准备装载" + projects0);
int paperSize = projects0.size();
List<XWPFTableCell> tableCells = row.getTableCells();
if (paperSize == 1) {
loadProjectData(projects0.get(0), tableCells);
}
if (paperSize > 1) {
XWPFTableRow backupRow = new XWPFTableRow(row.getCtRow(), table);
for (int i = 0; i < projects0.size() - 1; i++) {
XWPFTableRow blankRow = new XWPFTableRow(backupRow.getCtRow(), table);
loadProjectData(projects0.get(i), blankRow.getTableCells());
table.addRow(blankRow, 19 + rowOffset);
rowOffset++;
rowIndex++;
}
loadProjectData(projects0.get(paperSize - 1), tableCells);
}
} else if (rowIndex == 22 + rowOffset) {
// 4.教学成果奖或教学竞赛奖励
logger.info("准备装载" + projects1);
int paperSize = projects1.size();
List<XWPFTableCell> tableCells = row.getTableCells();
if (paperSize == 1) {
loadProjectData(projects1.get(0), tableCells);
}
if (paperSize > 1) {
XWPFTableRow backupRow = new XWPFTableRow(row.getCtRow(), table);
for (int i = 0; i < projects1.size() - 1; i++) {
XWPFTableRow blankRow = new XWPFTableRow(backupRow.getCtRow(), table);
loadProjectData(projects1.get(i), blankRow.getTableCells());
table.addRow(blankRow, 22 + rowOffset);
rowOffset++;
rowIndex++;
}
loadProjectData(projects1.get(paperSize - 1), tableCells);
}
} else if (rowIndex == 25 + rowOffset) {
// 5.指导竞赛
logger.info("准备装载" + projects2);
int paperSize = projects2.size();
List<XWPFTableCell> tableCells = row.getTableCells();
if (paperSize == 1) {
loadProjectData(projects2.get(0), tableCells);
}
if (paperSize > 1) {
XWPFTableRow backupRow = new XWPFTableRow(row.getCtRow(), table);
for (int i = 0; i < projects2.size() - 1; i++) {
XWPFTableRow blankRow = new XWPFTableRow(backupRow.getCtRow(), table);
loadProjectData(projects2.get(i), blankRow.getTableCells());
table.addRow(blankRow, 25 + rowOffset);
rowOffset++;
rowIndex++;
}
loadProjectData(projects2.get(paperSize - 1), tableCells);
}
} else if (rowIndex == 28 + rowOffset) {
// 成果推广
ArrayList<Research> research = data.getResearch();
logger.info("准备装载" + research);
int paperSize = research.size();
List<XWPFTableCell> tableCells = row.getTableCells();
if (paperSize == 1) {
loadResearchData(research.get(0), tableCells);
}
if (paperSize > 1) {
XWPFTableRow backupRow = new XWPFTableRow(row.getCtRow(), table);
for (int i = 0; i < research.size() - 1; i++) {
XWPFTableRow blankRow = new XWPFTableRow(backupRow.getCtRow(), table);
loadResearchData(research.get(i), blankRow.getTableCells());
table.addRow(blankRow, 28 + rowOffset);
rowOffset++;
rowIndex++;
}
loadResearchData(research.get(paperSize - 1), tableCells);
}
} else if (rowIndex == 29 + rowOffset) {
// 奖惩
List<XWPFTableCell> tableCells = row.getTableCells();
for (XWPFTableCell tableCell : tableCells) {
if ("{{awardsAndPunishments}}".equals(tableCell.getText())) {
if (!tableCell.getParagraphs().isEmpty()) {
tableCell.removeParagraph(0);
}
tableCell.setText(data.getAwardsAndPunishments());
}
}
} else if (rowIndex == 31 + rowOffset) {
// 家庭关系
ArrayList<FamilyConnections> familyConnections = data.getFamily();
logger.info("准备装载" + familyConnections);
int paperSize = familyConnections.size();
List<XWPFTableCell> tableCells = row.getTableCells();
if (paperSize == 1) {
loadFamilyConnectionsData(familyConnections.get(0), tableCells);
}
if (paperSize > 1) {
XWPFTableRow backupRow = new XWPFTableRow(row.getCtRow(), table);
for (int i = 0; i < familyConnections.size() - 1; i++) {
XWPFTableRow blankRow = new XWPFTableRow(backupRow.getCtRow(), table);
loadFamilyConnectionsData(familyConnections.get(i), blankRow.getTableCells());
table.addRow(blankRow, 31 + rowOffset);
rowOffset++;
rowIndex++;
}
loadFamilyConnectionsData(familyConnections.get(paperSize - 1), tableCells);
}
} else if (row.getTableCells().size() == 2) {
if ("{{note}}".equals(row.getCell(1).getText())) {
row.getCell(1).removeParagraph(0);
row.getCell(1).setText(data.getNote());
}
}
}
}
String path = OUTPUT_BASE_PATH + File.separatorChar + data.getCode() + File.separatorChar;
File folder = new File(path);
boolean success = folder.mkdir();
if (success) {
logger.info("文件夹创建成功");
} else {
if (folder.exists()) {
logger.info("文件夹已经存在");
} else {
logger.info("文件夹创建失败");
}
}
String fileName = data.getInfo().getName() + "_" + data.getInfo().getIdNum();
// 保存生成的文档
FileOutputStream outputFile = new FileOutputStream(path + File.separatorChar + fileName + ".docx");
document.write(outputFile);
// admission_ticket\null3416212.docx (系统找不到指定的路径。)
result = path + fileName + ".docx";
logger.info(result + "保存成功");
outputFile.close();
} catch (IOException e) {
logger.error(e);
return null;
} finally {
if (document != null) {
try {
document.close();
} catch (IOException e) {
logger.error(e);
}
}
}
return result;
}
private static void loadEducationData(Education education, List<XWPFTableCell> tableCells) {
String ed = degreeEducated(false, education.getEducation());
String de = degreeEducated(true, education.getDegree());
for (int cellIndex = 0; cellIndex < tableCells.size(); cellIndex++) {
XWPFTableCell xwpfTableCell = tableCells.get(cellIndex);
String text = "";
switch (cellIndex) {
case 0 -> text = ed;
case 1 -> text = de;
case 2 -> text = education.getSchool();
case 3 -> text = education.getSpecialty();
case 4 -> text = education.getGraduationTime();
default -> {
}
}
if (!xwpfTableCell.getParagraphs().isEmpty()) {
xwpfTableCell.removeParagraph(0);
}
xwpfTableCell.setText(text);
}
}
private static void loadWorkExperienceData(WorkExperience experience, List<XWPFTableCell> tableCells) {
String workTime = experience.getWorkTimeStart() + "到" + experience.getWorkTimeEnd();
for (int cellIndex = 0; cellIndex < tableCells.size(); cellIndex++) {
XWPFTableCell xwpfTableCell = tableCells.get(cellIndex);
String text = "";
switch (cellIndex) {
case 0 -> text = workTime;
case 1 -> text = experience.getCompany();
case 2 -> text = experience.getPosition();
default -> {
}
}
if (!xwpfTableCell.getParagraphs().isEmpty()) {
xwpfTableCell.removeParagraph(0);
}
xwpfTableCell.setText(text);
}
}
private static void loadPaperData(Paper paper, List<XWPFTableCell> tableCells) {
for (int cellIndex = 0; cellIndex < tableCells.size(); cellIndex++) {
XWPFTableCell xwpfTableCell = tableCells.get(cellIndex);
String text = "";
switch (cellIndex) {
case 0 -> text = paper.getJournal();
case 1 -> text = paper.getTitle();
case 2 -> text = paper.getTime();
case 3 -> text = paper.getJournalNum();
default -> {
}
}
if (!xwpfTableCell.getParagraphs().isEmpty()) {
xwpfTableCell.removeParagraph(0);
}
xwpfTableCell.setText(text);
}
}
private static void loadProjectData(Project project, List<XWPFTableCell> tableCells) {
for (int cellIndex = 0; cellIndex < tableCells.size(); cellIndex++) {
XWPFTableCell xwpfTableCell = tableCells.get(cellIndex);
String text = "";
switch (cellIndex) {
case 0 -> text = project.getTime();
case 1 -> text = project.getTitle();
case 2 -> text = project.getLevel();
case 3 -> text = project.getRank();
default -> {
}
}
if (!xwpfTableCell.getParagraphs().isEmpty()) {
xwpfTableCell.removeParagraph(0);
}
xwpfTableCell.setText(text);
}
}
private static void loadResearchData(Research research, List<XWPFTableCell> tableCells) {
for (int cellIndex = 0; cellIndex < tableCells.size(); cellIndex++) {
XWPFTableCell xwpfTableCell = tableCells.get(cellIndex);
String text = "";
if (cellIndex == 0) {
text = research.getName();
}
if (!xwpfTableCell.getParagraphs().isEmpty()) {
xwpfTableCell.removeParagraph(0);
}
xwpfTableCell.setText(text);
}
}
private static void loadFamilyConnectionsData(FamilyConnections project, List<XWPFTableCell> tableCells) {
for (int cellIndex = 0; cellIndex < tableCells.size(); cellIndex++) {
XWPFTableCell xwpfTableCell = tableCells.get(cellIndex);
String text = "";
switch (cellIndex) {
case 1 -> text = project.getName();
case 2 -> text = project.getConnection();
case 3 -> text = project.getWork();
default -> {
}
}
if (!xwpfTableCell.getParagraphs().isEmpty()) {
xwpfTableCell.removeParagraph(0);
}
xwpfTableCell.setText(text);
}
}
private static String repleteString(String text, UserInfo info) {
if ("{{name}}".equals(text)) {
return info.getName();
}
if ("{{sex}}".equals(text)) {
if (info.getSex() == 1) {
return "男";
} else {
return "女";
}
}
if ("{{phone}}".equals(text)) {
return info.getPhone();
}
if ("{{birthPlace}}".equals(text)) {
return info.getBirthPlace();
}
if ("{{nation}}".equals(text)) {
return info.getNation();
}
if ("{{zzmm}}".equals(text)) {
return info.getPoliticalStatus();
}
if ("{{email}}".equals(text)) {
return info.getEmail();
}
if ("{{birthday}}".equals(text)) {
return info.getBirthday();
}
if ("{{idnum}}".equals(text)) {
return info.getIdNum();
}
if ("{{married}}".equals(text)) {
return info.getMarried();
}
if ("{{native_place}}".equals(text)) {
return info.getNativePlace();
}
if ("{{address}}".equals(text)) {
return info.getAddress();
}
if ("{{specialtiesCertificates}}".equals(text)) {
return info.getSpecialtiesCertificates();
}
return "";
}
private static String degreeEducated(Boolean isDegree, int data) {
// 填充数据
if (isDegree) {
return switch (data) {
case 0 -> "暂无";
case 1 -> "学士";
case 2 -> "硕士";
case 3 -> "博士";
default -> "异常";
};
} else {
/* 将学历转换成汉字 */
return switch (data) {
case 0 -> "专科";
case 1 -> "本科";
case 2 -> "研究生";
default -> "异常";
};
}
}
}
Loading…
Cancel
Save