重构一时爽, 构错火葬场
重构的原因很简单: 最近在学Java, 刚好Selenium有Java版本,
所以就有了这个项目.
经验教训
之前的版本中, 信息采用硬编码, 于是就出现了发出来没删干净的情况,
这次重构把配置文件分离出来了.
代码风格可能不太好, 轻喷
配置信息的读取
一开始用的是EasyExcel, 但是一直读不到数据, 于是换成了POI
代码如下:
点我查看完整代码
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40
| package HealthReport;
import java.io.FileInputStream;
import org.apache.poi.ss.usermodel.CellType; import org.apache.poi.xssf.usermodel.XSSFCell; import org.apache.poi.xssf.usermodel.XSSFRow; import org.apache.poi.xssf.usermodel.XSSFSheet; import org.apache.poi.xssf.usermodel.XSSFWorkbook;
public class GetData { public ConfigData read(String fileName) throws Exception{ FileInputStream inputStream = new FileInputStream(fileName); XSSFWorkbook workbook = new XSSFWorkbook(inputStream); XSSFSheet sheet = workbook.getSheetAt(0); XSSFRow row = sheet.getRow(1); XSSFCell studentNumber = row.getCell(0); studentNumber.setCellType(CellType.STRING); XSSFCell studentPassword = row.getCell(1); studentPassword.setCellType(CellType.STRING); XSSFCell senderEmailAdress = row.getCell(2); senderEmailAdress.setCellType(CellType.STRING); XSSFCell senderEmailServerPassword = row.getCell(3); senderEmailServerPassword.setCellType(CellType.STRING); XSSFCell senderEmailServerAdress = row.getCell(4); senderEmailServerAdress.setCellType(CellType.STRING); XSSFCell receiverEmailAdress = row.getCell(5); receiverEmailAdress.setCellType(CellType.STRING); ConfigData data = new ConfigData(studentNumber.toString(), studentPassword.toString(), senderEmailAdress.toString(), senderEmailServerPassword.toString(), senderEmailServerAdress.toString(), receiverEmailAdress.toString()); System.out.println(data.toString()); workbook.close(); return data; } }
|
配置信息的存储
一开始用EasyEXcel的时候写的,
然后就继承下来了(才不会说是懒得删)
点我查看完整代码
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52
| package HealthReport;
public class ConfigData { private String studentNumber; private String studentPassword; private String senderEmailAdress; private String senderEmailServerPassword; private String senderEmailServerAdress; private String receiverEmailAdress; public ConfigData() { } public ConfigData(String studentNumber, String studentPassword, String senderEmailAdress, String senderEmailServerPassword, String senderEmailServerAdress, String receiverEmailAdress) { this.studentNumber = studentNumber; this.studentPassword = studentPassword; this.senderEmailAdress = senderEmailAdress; this.senderEmailServerPassword = senderEmailServerPassword; this.senderEmailServerAdress = senderEmailServerAdress; this.receiverEmailAdress = receiverEmailAdress; } public String toString() { return "ConfigData{" + "studentNumber = " + studentNumber + ", " + "studentPassword = " + studentPassword + ", " + "senderEmailAdress = " + senderEmailAdress + ", " + "senderEmailServerPassword = " + senderEmailServerPassword + ", " + "senderEmailServerAdres = " + senderEmailServerAdress + ", " + "receiverEmailAdress = " + receiverEmailAdress + "}"; } public String getStudentNumber() { return studentNumber; } public String getStudentPassword() { return studentPassword; } public String getSenderEmailAdress() { return senderEmailAdress; } public String getSenderEmailServerPassword() { return senderEmailServerPassword; } public String getSenderEmailServerAdress() { return senderEmailServerAdress; } public String getReceiverEmailAdress() { return receiverEmailAdress; } }
|
核心-网页处理
老伙伴Selenium, 不用多说
点我查看完整代码
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114
| package HealthReport;
import java.util.ArrayList; import java.util.List; import java.util.Set;
import org.openqa.selenium.By; import org.openqa.selenium.JavascriptExecutor; import org.openqa.selenium.WebDriver; import org.openqa.selenium.WebElement; import org.openqa.selenium.firefox.FirefoxDriver; import org.openqa.selenium.support.ui.ExpectedConditions; import org.openqa.selenium.support.ui.WebDriverWait;
public class Selenium { private String header; private String text; public Selenium clockIn(ConfigData data) { header = "今日疫情填报情况"; text = "无法获取历史填报信息"; String url = "http://ids.hhu.edu.cn/amserver/UI/Login?goto=http://form.hhu.edu.cn:80/pdc/form/list"; try { WebDriver driver = new FirefoxDriver(); driver.get(url); driver.manage().window().maximize(); driver.findElement(By.id("IDToken1")).sendKeys(data.getStudentNumber()); driver.findElement(By.id("IDToken2")).sendKeys(data.getStudentPassword()); WebDriverWait w = new WebDriverWait(driver, 180); w.until(ExpectedConditions.presenceOfAllElementsLocatedBy(By.xpath("//*[contains(@onclick, 'defaultSubmit()')]"))); ((JavascriptExecutor) driver).executeScript("defaultSubmit()"); w.until(ExpectedConditions.presenceOfAllElementsLocatedBy(By.className("datav-flex-box"))); driver.findElement(By.className("datav-flex-box")).click(); w.until(ExpectedConditions.presenceOfAllElementsLocatedBy(By.id("saveBtn"))); ((JavascriptExecutor) driver).executeScript("window.scrollTo(0,document.body.scrollHeight)"); Thread.sleep(5000); ((JavascriptExecutor) driver).executeScript("save()"); w.until(ExpectedConditions.presenceOfAllElementsLocatedBy(By.className("panel-body"))); driver.navigate().back(); driver.navigate().back(); driver.navigate().back(); driver.navigate().back(); driver.navigate().back(); driver.findElement(By.id("IDToken2")).sendKeys(data.getStudentPassword()); w.until(ExpectedConditions.presenceOfAllElementsLocatedBy(By.xpath("//*[contains(@onclick, 'defaultSubmit()')]"))); ((JavascriptExecutor) driver).executeScript("defaultSubmit()"); w.until(ExpectedConditions.presenceOfAllElementsLocatedBy(By.className("datav-flex-box"))); driver.findElement(By.className("datav-flex-box")).click(); w.until(ExpectedConditions.presenceOfAllElementsLocatedBy(By.id("showHistoryBtn"))); ((JavascriptExecutor) driver).executeScript("window.scrollTo(0,document.body.scrollHeight)"); Thread.sleep(5000); ((JavascriptExecutor) driver).executeScript("showFormFilled()"); Set<String> winHandels = driver.getWindowHandles(); List<String> it = new ArrayList<String>(winHandels); driver.switchTo().window(it.get(1)); w.until(ExpectedConditions.presenceOfAllElementsLocatedBy(By.xpath("//*[@id=\"countTableBody\"]/tr[1]/td[1]"))); WebElement table = driver.findElement(By.xpath("//*[@id=\"countTableBody\"]/tr[1]/td[1]")); String getTime = table.getText(); if (DateDeal.judge(getTime)) { text = "今日疫情填报已完成, "; } else { text = "今日疫情填报未完成, "; } text += "最后填报时间: " + getTime; driver.quit(); } catch (Exception e){ header = "疫情填报异常"; try { WebDriver driver = new FirefoxDriver(); driver.get(url); driver.manage().window().maximize(); driver.findElement(By.id("IDToken1")).sendKeys(data.getStudentNumber()); driver.findElement(By.id("IDToken2")).sendKeys(data.getStudentPassword()); WebDriverWait w = new WebDriverWait(driver, 180); w.until(ExpectedConditions.presenceOfAllElementsLocatedBy(By.xpath("//*[contains(@onclick, 'defaultSubmit()')]"))); ((JavascriptExecutor) driver).executeScript("defaultSubmit()"); w.until(ExpectedConditions.presenceOfAllElementsLocatedBy(By.className("datav-flex-box"))); driver.findElement(By.className("datav-flex-box")).click(); w.until(ExpectedConditions.presenceOfAllElementsLocatedBy(By.id("showHistoryBtn"))); ((JavascriptExecutor) driver).executeScript("window.scrollTo(0,document.body.scrollHeight)"); Thread.sleep(5000); ((JavascriptExecutor) driver).executeScript("showFormFilled()"); Set<String> winHandels = driver.getWindowHandles(); List<String> it = new ArrayList<String>(winHandels); driver.switchTo().window(it.get(1)); w.until(ExpectedConditions.presenceOfAllElementsLocatedBy(By.xpath("//*[@id=\"countTableBody\"]/tr[1]/td[1]"))); WebElement table = driver.findElement(By.xpath("//*[@id=\"countTableBody\"]/tr[1]/td[1]")); String getTime = table.getText(); if (DateDeal.judge(getTime)) { text = "今日疫情填报已完成, "; } else { text = "今日疫情填报未完成, "; } text += "最后填报时间: " + getTime; header += ", 获取填报信息正常"; driver.quit(); } catch (Exception f){ header += ", 获取填报信息异常"; } } return this; } public String getHeader() { return header; } public String getText() { return text; } }
|
时间处理
LocalDate和LocalDateTime, 需要注意的是这里并不能直接用 ==
判断是否相等(想念操作符重载), 要用 isEqual()
点我查看完整代码
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20
| package HealthReport;
import java.time.*; import java.time.format.*;
public class DateDeal { public static boolean judge(String getTime) { LocalDate today = LocalDate.now(); DateTimeFormatter dtf = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"); LocalDateTime getDateTime = LocalDateTime.parse(getTime, dtf); LocalDate getDay = getDateTime.toLocalDate(); if (getDay.isEqual(today)) { return true; } else { return false; } } }
|
邮件部分
JavaMail, 需要注意的是QQ邮箱需要开SSL,
另外setForm()中填写的地址要和connect()中填写的写信人地址一致(在这里查了两个小时bug),
还要记得在配置完之后调用saveChanges()保存哦
点我查看完整代码
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37
| package HealthReport;
import java.util.Properties;
import javax.mail.*; import javax.mail.internet.*;
public class Mail { public void sendMail(ConfigData data, Selenium mail) throws Exception{ Properties props = new Properties(); final String smtpPort = "465"; props.setProperty("mail.smtp.auth", "true"); props.setProperty("mail.host", data.getSenderEmailServerAdress()); props.setProperty("mail.transport.protocol", "smtp"); props.setProperty("mail.smtp.socketFactory.class", "javax.net.ssl.SSLSocketFactory"); props.setProperty("mail.smtp.socketFactory.fallback", "false"); props.setProperty("mail.smtp.socketFactory.port", smtpPort); Session session= Session.getDefaultInstance(props); MimeMessage message = new MimeMessage(session); message.setFrom(new InternetAddress(data.getSenderEmailAdress(), "", "UTF-8")); message.addRecipient(MimeMessage.RecipientType.TO, new InternetAddress(data.getReceiverEmailAdress(), "", "UTF-8")); message.setSubject(mail.getHeader(), "UTF-8"); message.setContent(mail.getText(), "text/html;charset=UTF-8"); message.saveChanges();
Transport transport = session.getTransport(); transport.connect(data.getSenderEmailServerAdress(), data.getSenderEmailAdress(), data.getSenderEmailServerPassword()); transport.sendMessage(message, message.getAllRecipients()); transport.close(); } }
|
主方法
把前面的方法整合起来, 没什么好说的.
点我查看完整代码
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29
| package HealthReport;
public class Main { public static void main(String[] args) { String fileName = "HealthReport.xlsx"; GetData get = new GetData(); ConfigData data = null; try { data = get.read(fileName); } catch (Exception e) { System.out.println("获取配置信息失败"); e.printStackTrace(); } Selenium mail = new Selenium(); mail = mail.clockIn(data); Mail send = new Mail(); try { send.sendMail(data, mail); } catch (Exception e) { e.printStackTrace(); } System.out.println(mail.getHeader()); System.out.println(mail.getText()); } }
|