diff --git a/.gitignore b/.gitignore index 0841741..5027de1 100644 --- a/.gitignore +++ b/.gitignore @@ -1,2 +1,4 @@ .idea /out +/logs +/target diff --git a/.gitignore b/.gitignore index 0841741..5027de1 100644 --- a/.gitignore +++ b/.gitignore @@ -1,2 +1,4 @@ .idea /out +/logs +/target diff --git a/CasicTimeGuard.iml b/CasicTimeGuard.iml index f54a89f..40532bb 100644 --- a/CasicTimeGuard.iml +++ b/CasicTimeGuard.iml @@ -1,12 +1,29 @@ - - - + + + + - + + + + - + + + + + + + + + + + + + + \ No newline at end of file diff --git a/.gitignore b/.gitignore index 0841741..5027de1 100644 --- a/.gitignore +++ b/.gitignore @@ -1,2 +1,4 @@ .idea /out +/logs +/target diff --git a/CasicTimeGuard.iml b/CasicTimeGuard.iml index f54a89f..40532bb 100644 --- a/CasicTimeGuard.iml +++ b/CasicTimeGuard.iml @@ -1,12 +1,29 @@ - - - + + + + - + + + + - + + + + + + + + + + + + + + \ No newline at end of file diff --git a/lib/guava-18.0.jar b/lib/guava-18.0.jar deleted file mode 100644 index 8f89e49..0000000 --- a/lib/guava-18.0.jar +++ /dev/null Binary files differ diff --git a/.gitignore b/.gitignore index 0841741..5027de1 100644 --- a/.gitignore +++ b/.gitignore @@ -1,2 +1,4 @@ .idea /out +/logs +/target diff --git a/CasicTimeGuard.iml b/CasicTimeGuard.iml index f54a89f..40532bb 100644 --- a/CasicTimeGuard.iml +++ b/CasicTimeGuard.iml @@ -1,12 +1,29 @@ - - - + + + + - + + + + - + + + + + + + + + + + + + + \ No newline at end of file diff --git a/lib/guava-18.0.jar b/lib/guava-18.0.jar deleted file mode 100644 index 8f89e49..0000000 --- a/lib/guava-18.0.jar +++ /dev/null Binary files differ diff --git a/pom.xml b/pom.xml new file mode 100644 index 0000000..3be19b5 --- /dev/null +++ b/pom.xml @@ -0,0 +1,44 @@ + + + 4.0.0 + + com.casic + CasicTimeGuard + 1.0-SNAPSHOT + + + 8 + 8 + 1.8 + + + + + org.projectlombok + lombok + 1.18.22 + true + + + + com.alibaba + fastjson + 1.2.79 + + + + + com.google.guava + guava + 31.0.1-jre + + + + com.squareup.okhttp3 + okhttp + 4.9.3 + + + \ No newline at end of file diff --git a/.gitignore b/.gitignore index 0841741..5027de1 100644 --- a/.gitignore +++ b/.gitignore @@ -1,2 +1,4 @@ .idea /out +/logs +/target diff --git a/CasicTimeGuard.iml b/CasicTimeGuard.iml index f54a89f..40532bb 100644 --- a/CasicTimeGuard.iml +++ b/CasicTimeGuard.iml @@ -1,12 +1,29 @@ - - - + + + + - + + + + - + + + + + + + + + + + + + + \ No newline at end of file diff --git a/lib/guava-18.0.jar b/lib/guava-18.0.jar deleted file mode 100644 index 8f89e49..0000000 --- a/lib/guava-18.0.jar +++ /dev/null Binary files differ diff --git a/pom.xml b/pom.xml new file mode 100644 index 0000000..3be19b5 --- /dev/null +++ b/pom.xml @@ -0,0 +1,44 @@ + + + 4.0.0 + + com.casic + CasicTimeGuard + 1.0-SNAPSHOT + + + 8 + 8 + 1.8 + + + + + org.projectlombok + lombok + 1.18.22 + true + + + + com.alibaba + fastjson + 1.2.79 + + + + + com.google.guava + guava + 31.0.1-jre + + + + com.squareup.okhttp3 + okhttp + 4.9.3 + + + \ No newline at end of file diff --git a/src/com/casic/swing/ui/TimeGuardNtp.form b/src/com/casic/swing/ui/TimeGuardNtp.form deleted file mode 100644 index cdba6f6..0000000 --- a/src/com/casic/swing/ui/TimeGuardNtp.form +++ /dev/null @@ -1,171 +0,0 @@ - -
- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - diff --git a/.gitignore b/.gitignore index 0841741..5027de1 100644 --- a/.gitignore +++ b/.gitignore @@ -1,2 +1,4 @@ .idea /out +/logs +/target diff --git a/CasicTimeGuard.iml b/CasicTimeGuard.iml index f54a89f..40532bb 100644 --- a/CasicTimeGuard.iml +++ b/CasicTimeGuard.iml @@ -1,12 +1,29 @@ - - - + + + + - + + + + - + + + + + + + + + + + + + + \ No newline at end of file diff --git a/lib/guava-18.0.jar b/lib/guava-18.0.jar deleted file mode 100644 index 8f89e49..0000000 --- a/lib/guava-18.0.jar +++ /dev/null Binary files differ diff --git a/pom.xml b/pom.xml new file mode 100644 index 0000000..3be19b5 --- /dev/null +++ b/pom.xml @@ -0,0 +1,44 @@ + + + 4.0.0 + + com.casic + CasicTimeGuard + 1.0-SNAPSHOT + + + 8 + 8 + 1.8 + + + + + org.projectlombok + lombok + 1.18.22 + true + + + + com.alibaba + fastjson + 1.2.79 + + + + + com.google.guava + guava + 31.0.1-jre + + + + com.squareup.okhttp3 + okhttp + 4.9.3 + + + \ No newline at end of file diff --git a/src/com/casic/swing/ui/TimeGuardNtp.form b/src/com/casic/swing/ui/TimeGuardNtp.form deleted file mode 100644 index cdba6f6..0000000 --- a/src/com/casic/swing/ui/TimeGuardNtp.form +++ /dev/null @@ -1,171 +0,0 @@ - -
- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - diff --git a/src/com/casic/swing/ui/TimeGuardNtp.java b/src/com/casic/swing/ui/TimeGuardNtp.java deleted file mode 100644 index 6df5b55..0000000 --- a/src/com/casic/swing/ui/TimeGuardNtp.java +++ /dev/null @@ -1,207 +0,0 @@ -package com.casic.swing.ui; - -import com.casic.swing.utils.CommandUtil; -import com.casic.swing.utils.StringHelper; -import com.casic.swing.utils.TimeOrDateUtil; -import com.google.common.util.concurrent.ThreadFactoryBuilder; - -import javax.swing.*; -import java.awt.*; -import java.awt.event.ActionEvent; -import java.awt.event.ActionListener; -import java.awt.event.ItemEvent; -import java.awt.event.ItemListener; -import java.util.concurrent.ScheduledExecutorService; -import java.util.concurrent.ScheduledThreadPoolExecutor; -import java.util.concurrent.TimeUnit; - -/** - * @author a203 - */ -public class TimeGuardNtp extends JFrame { - private JPanel ntpPanel; - private JComboBox hostComboBox; - private JLabel timeValueLabel; - private JButton updateTimeButton; - private JLabel dotView; - private JLabel currentTimeLabel; - private JCheckBox autoCheckBox; - private JComboBox periodComboBox; - private JPanel stateView; - - private final String[] HOST_NAME = {"NTP服务器(上海)", "中国国家授时中心", "清华大学", "北京大学", "自定义"}; - private final String[] HOST_IP = {"ntp.api.bz", "ntp.ntsc.ac.cn", "s1b.time.edu.cn", "s2m.time.edu.cn"}; - /** - * 同步周期,单位:小时 - */ - private final Integer[] PERIOD = {10, 20, 30}; - private final ScheduledExecutorService executorService = new ScheduledThreadPoolExecutor( - 1, new ThreadFactoryBuilder().setNameFormat("demo-pool-%d").build()); - private boolean hasNtp = false; - private String host = HOST_IP[0]; - - public static void main(String[] args) { - new TimeGuardNtp(); - } - - public TimeGuardNtp() { - setContentPane(ntpPanel); - setResizable(false); - setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); - pack(); - setSize(410, 280); - //居中 - setLocationRelativeTo(null); - setVisible(true); - dotView.setText("未同步"); - setStateView(Color.GRAY); - - StringHelper.createLogFile(); - - /** - * 时间间隔,单位为毫秒 - * */ - currentTimeLabel.setForeground(Color.BLUE); - new Timer(1000, new ActionListener() { - @Override - public void actionPerformed(ActionEvent e) { - String systemTime = TimeOrDateUtil.timestampToTime(System.currentTimeMillis()); - currentTimeLabel.setText(systemTime); - } - }).start(); - - String assertsData = StringHelper.getAssertsData(); - if (!"".equals(assertsData)) { - timeValueLabel.setText(assertsData); - } else { - timeValueLabel.setText("无法确定最近同步时间"); - } - - //初始化JComboBox - initComBox(); - hostComboBox.addItemListener(new ItemListener() { - @Override - public void itemStateChanged(ItemEvent e) { - String item = (String) e.getItem(); - if (e.getStateChange() == ItemEvent.SELECTED) { - if ("自定义".equals(item)) { - String inputContent = JOptionPane.showInputDialog(ntpPanel, "请输入授时中心域名或者IP地址", "", JOptionPane.INFORMATION_MESSAGE); - if (inputContent.isEmpty()) { - JOptionPane.showMessageDialog(ntpPanel, "输入错误,请检查", "Runtime Error", JOptionPane.ERROR_MESSAGE); - } else { - host = inputContent; - } - } else { - for (int i = 0; i < HOST_NAME.length; i++) { - if (item.equals(HOST_NAME[i])) { - host = HOST_IP[i]; - } - } - } - } - } - }); - - //检查环境 - new SwingWorker() { - - @Override - protected Boolean doInBackground() { - hasNtp = CommandUtil.checkEnv(); - return hasNtp; - } - - @Override - protected void done() { - if (!hasNtp) { - JOptionPane.showMessageDialog(ntpPanel, "未当前设备发现可用的NTP配置", "Runtime Error", JOptionPane.ERROR_MESSAGE); - //环境不对,关闭窗体 - dispose(); - } - super.done(); - } - }.execute(); - - autoCheckBox.addActionListener(new ActionListener() { - @Override - public void actionPerformed(ActionEvent e) { - JCheckBox checkBox = (JCheckBox) e.getSource(); - if (checkBox.isSelected()) { - updateTimeButton.setEnabled(false); - periodComboBox.setEnabled(true); - startAutoSynchronize(PERIOD[0]); - } else { - updateTimeButton.setEnabled(true); - periodComboBox.setEnabled(false); - } - } - }); - - periodComboBox.addItemListener(new ItemListener() { - @Override - public void itemStateChanged(ItemEvent e) { - int period = (Integer) e.getItem(); - if (e.getStateChange() == ItemEvent.SELECTED) { - startAutoSynchronize(period); - } - } - }); - - //按钮点击事件 - updateTimeButton.addActionListener(new ActionListener() { - @Override - public void actionPerformed(ActionEvent e) { - updateView(); - } - }); - } - - private void startAutoSynchronize(int period) { - /** - * 开启同步,只能开启一个同步线程 - * - * scheduleAtFixedRate - * 是以上一个任务开始的时间计时,period时间过去后,检测上一个任务是否执行完毕 - * 如果上一个任务执行完毕,则当前任务立即执行 - * 如果上一个任务没有执行完毕,则需要等上一个任务执行完毕后立即执行 - * */ - executorService.scheduleAtFixedRate(new Runnable() { - @Override - public void run() { - updateView(); - } - }, 0, period, TimeUnit.MINUTES); - } - - private void updateView() { - String result = CommandUtil.ntpDate(host); - System.out.println("命令执行结果 ===> " + result); - boolean isSuccess = result.contains("step time server") || result.contains("adjust time server"); - if (isSuccess) { - String systemTime = TimeOrDateUtil.timestampToTime(System.currentTimeMillis()); - setStateView(Color.GREEN); - dotView.setText("同步成功"); - timeValueLabel.setText(systemTime); - //同步成功之后将时间存入本地 - StringHelper.saveAssertsData(systemTime); - } else { - setStateView(Color.RED); - dotView.setText("同步失败"); - timeValueLabel.setText(""); - } - } - - private void initComBox() { - for (String s : HOST_NAME) { - hostComboBox.addItem(s); - } - for (Integer integer : PERIOD) { - periodComboBox.addItem(integer); - } - } - - private void setStateView(Color color) { - stateView.setPreferredSize(new Dimension(15, 15)); - stateView.setBackground(color); - } -} diff --git a/.gitignore b/.gitignore index 0841741..5027de1 100644 --- a/.gitignore +++ b/.gitignore @@ -1,2 +1,4 @@ .idea /out +/logs +/target diff --git a/CasicTimeGuard.iml b/CasicTimeGuard.iml index f54a89f..40532bb 100644 --- a/CasicTimeGuard.iml +++ b/CasicTimeGuard.iml @@ -1,12 +1,29 @@ - - - + + + + - + + + + - + + + + + + + + + + + + + + \ No newline at end of file diff --git a/lib/guava-18.0.jar b/lib/guava-18.0.jar deleted file mode 100644 index 8f89e49..0000000 --- a/lib/guava-18.0.jar +++ /dev/null Binary files differ diff --git a/pom.xml b/pom.xml new file mode 100644 index 0000000..3be19b5 --- /dev/null +++ b/pom.xml @@ -0,0 +1,44 @@ + + + 4.0.0 + + com.casic + CasicTimeGuard + 1.0-SNAPSHOT + + + 8 + 8 + 1.8 + + + + + org.projectlombok + lombok + 1.18.22 + true + + + + com.alibaba + fastjson + 1.2.79 + + + + + com.google.guava + guava + 31.0.1-jre + + + + com.squareup.okhttp3 + okhttp + 4.9.3 + + + \ No newline at end of file diff --git a/src/com/casic/swing/ui/TimeGuardNtp.form b/src/com/casic/swing/ui/TimeGuardNtp.form deleted file mode 100644 index cdba6f6..0000000 --- a/src/com/casic/swing/ui/TimeGuardNtp.form +++ /dev/null @@ -1,171 +0,0 @@ - -
- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - diff --git a/src/com/casic/swing/ui/TimeGuardNtp.java b/src/com/casic/swing/ui/TimeGuardNtp.java deleted file mode 100644 index 6df5b55..0000000 --- a/src/com/casic/swing/ui/TimeGuardNtp.java +++ /dev/null @@ -1,207 +0,0 @@ -package com.casic.swing.ui; - -import com.casic.swing.utils.CommandUtil; -import com.casic.swing.utils.StringHelper; -import com.casic.swing.utils.TimeOrDateUtil; -import com.google.common.util.concurrent.ThreadFactoryBuilder; - -import javax.swing.*; -import java.awt.*; -import java.awt.event.ActionEvent; -import java.awt.event.ActionListener; -import java.awt.event.ItemEvent; -import java.awt.event.ItemListener; -import java.util.concurrent.ScheduledExecutorService; -import java.util.concurrent.ScheduledThreadPoolExecutor; -import java.util.concurrent.TimeUnit; - -/** - * @author a203 - */ -public class TimeGuardNtp extends JFrame { - private JPanel ntpPanel; - private JComboBox hostComboBox; - private JLabel timeValueLabel; - private JButton updateTimeButton; - private JLabel dotView; - private JLabel currentTimeLabel; - private JCheckBox autoCheckBox; - private JComboBox periodComboBox; - private JPanel stateView; - - private final String[] HOST_NAME = {"NTP服务器(上海)", "中国国家授时中心", "清华大学", "北京大学", "自定义"}; - private final String[] HOST_IP = {"ntp.api.bz", "ntp.ntsc.ac.cn", "s1b.time.edu.cn", "s2m.time.edu.cn"}; - /** - * 同步周期,单位:小时 - */ - private final Integer[] PERIOD = {10, 20, 30}; - private final ScheduledExecutorService executorService = new ScheduledThreadPoolExecutor( - 1, new ThreadFactoryBuilder().setNameFormat("demo-pool-%d").build()); - private boolean hasNtp = false; - private String host = HOST_IP[0]; - - public static void main(String[] args) { - new TimeGuardNtp(); - } - - public TimeGuardNtp() { - setContentPane(ntpPanel); - setResizable(false); - setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); - pack(); - setSize(410, 280); - //居中 - setLocationRelativeTo(null); - setVisible(true); - dotView.setText("未同步"); - setStateView(Color.GRAY); - - StringHelper.createLogFile(); - - /** - * 时间间隔,单位为毫秒 - * */ - currentTimeLabel.setForeground(Color.BLUE); - new Timer(1000, new ActionListener() { - @Override - public void actionPerformed(ActionEvent e) { - String systemTime = TimeOrDateUtil.timestampToTime(System.currentTimeMillis()); - currentTimeLabel.setText(systemTime); - } - }).start(); - - String assertsData = StringHelper.getAssertsData(); - if (!"".equals(assertsData)) { - timeValueLabel.setText(assertsData); - } else { - timeValueLabel.setText("无法确定最近同步时间"); - } - - //初始化JComboBox - initComBox(); - hostComboBox.addItemListener(new ItemListener() { - @Override - public void itemStateChanged(ItemEvent e) { - String item = (String) e.getItem(); - if (e.getStateChange() == ItemEvent.SELECTED) { - if ("自定义".equals(item)) { - String inputContent = JOptionPane.showInputDialog(ntpPanel, "请输入授时中心域名或者IP地址", "", JOptionPane.INFORMATION_MESSAGE); - if (inputContent.isEmpty()) { - JOptionPane.showMessageDialog(ntpPanel, "输入错误,请检查", "Runtime Error", JOptionPane.ERROR_MESSAGE); - } else { - host = inputContent; - } - } else { - for (int i = 0; i < HOST_NAME.length; i++) { - if (item.equals(HOST_NAME[i])) { - host = HOST_IP[i]; - } - } - } - } - } - }); - - //检查环境 - new SwingWorker() { - - @Override - protected Boolean doInBackground() { - hasNtp = CommandUtil.checkEnv(); - return hasNtp; - } - - @Override - protected void done() { - if (!hasNtp) { - JOptionPane.showMessageDialog(ntpPanel, "未当前设备发现可用的NTP配置", "Runtime Error", JOptionPane.ERROR_MESSAGE); - //环境不对,关闭窗体 - dispose(); - } - super.done(); - } - }.execute(); - - autoCheckBox.addActionListener(new ActionListener() { - @Override - public void actionPerformed(ActionEvent e) { - JCheckBox checkBox = (JCheckBox) e.getSource(); - if (checkBox.isSelected()) { - updateTimeButton.setEnabled(false); - periodComboBox.setEnabled(true); - startAutoSynchronize(PERIOD[0]); - } else { - updateTimeButton.setEnabled(true); - periodComboBox.setEnabled(false); - } - } - }); - - periodComboBox.addItemListener(new ItemListener() { - @Override - public void itemStateChanged(ItemEvent e) { - int period = (Integer) e.getItem(); - if (e.getStateChange() == ItemEvent.SELECTED) { - startAutoSynchronize(period); - } - } - }); - - //按钮点击事件 - updateTimeButton.addActionListener(new ActionListener() { - @Override - public void actionPerformed(ActionEvent e) { - updateView(); - } - }); - } - - private void startAutoSynchronize(int period) { - /** - * 开启同步,只能开启一个同步线程 - * - * scheduleAtFixedRate - * 是以上一个任务开始的时间计时,period时间过去后,检测上一个任务是否执行完毕 - * 如果上一个任务执行完毕,则当前任务立即执行 - * 如果上一个任务没有执行完毕,则需要等上一个任务执行完毕后立即执行 - * */ - executorService.scheduleAtFixedRate(new Runnable() { - @Override - public void run() { - updateView(); - } - }, 0, period, TimeUnit.MINUTES); - } - - private void updateView() { - String result = CommandUtil.ntpDate(host); - System.out.println("命令执行结果 ===> " + result); - boolean isSuccess = result.contains("step time server") || result.contains("adjust time server"); - if (isSuccess) { - String systemTime = TimeOrDateUtil.timestampToTime(System.currentTimeMillis()); - setStateView(Color.GREEN); - dotView.setText("同步成功"); - timeValueLabel.setText(systemTime); - //同步成功之后将时间存入本地 - StringHelper.saveAssertsData(systemTime); - } else { - setStateView(Color.RED); - dotView.setText("同步失败"); - timeValueLabel.setText(""); - } - } - - private void initComBox() { - for (String s : HOST_NAME) { - hostComboBox.addItem(s); - } - for (Integer integer : PERIOD) { - periodComboBox.addItem(integer); - } - } - - private void setStateView(Color color) { - stateView.setPreferredSize(new Dimension(15, 15)); - stateView.setBackground(color); - } -} diff --git a/src/com/casic/swing/utils/CommandUtil.java b/src/com/casic/swing/utils/CommandUtil.java deleted file mode 100644 index c487e7d..0000000 --- a/src/com/casic/swing/utils/CommandUtil.java +++ /dev/null @@ -1,76 +0,0 @@ -package com.casic.swing.utils; - -import java.io.BufferedReader; -import java.io.IOException; -import java.io.InputStream; -import java.io.InputStreamReader; -import java.nio.charset.Charset; -import java.util.concurrent.TimeUnit; - -/** - * @author a203 - */ -public class CommandUtil { - /** - * 检查当前系统是否已安装NTP - */ - public static boolean checkEnv() { - System.out.println("检查当前系统是否支持NTP"); - try { - Process exec = Runtime.getRuntime().exec("rpm -q ntp"); - try { - //等待命令执行完成 - exec.waitFor(5, TimeUnit.SECONDS); - } catch (InterruptedException e) { - e.printStackTrace(); - } - String result = parseResult(exec.getInputStream()); - return !result.isEmpty(); - } catch (IOException e) { - e.printStackTrace(); - } - return false; - } - - /** - * 安装NTP - * yum -y install ntp - * */ - - /** - * 授时同步 - * ntpdate -u ntp.api.bz - */ - public static String ntpDate(String host) { - try { - String command = "ntpdate -u " + host; - System.out.println("授时同步 ===> " + command); - Process exec = Runtime.getRuntime().exec(command); - try { - //等待命令执行完成 - exec.waitFor(5, TimeUnit.SECONDS); - } catch (InterruptedException e) { - e.printStackTrace(); - } - return parseResult(exec.getInputStream()); - } catch (IOException e) { - e.printStackTrace(); - } - return ""; - } - - /** - * 解析命令结果 - */ - private static String parseResult(InputStream inputStream) throws IOException { - // 读取输出流内容 - InputStreamReader streamReader = new InputStreamReader(inputStream, Charset.defaultCharset()); - BufferedReader reader = new BufferedReader(streamReader); - StringBuilder builder = new StringBuilder(); - String line; - while ((line = reader.readLine()) != null) { - builder.append(line).append("\n"); - } - return builder.toString(); - } -} diff --git a/.gitignore b/.gitignore index 0841741..5027de1 100644 --- a/.gitignore +++ b/.gitignore @@ -1,2 +1,4 @@ .idea /out +/logs +/target diff --git a/CasicTimeGuard.iml b/CasicTimeGuard.iml index f54a89f..40532bb 100644 --- a/CasicTimeGuard.iml +++ b/CasicTimeGuard.iml @@ -1,12 +1,29 @@ - - - + + + + - + + + + - + + + + + + + + + + + + + + \ No newline at end of file diff --git a/lib/guava-18.0.jar b/lib/guava-18.0.jar deleted file mode 100644 index 8f89e49..0000000 --- a/lib/guava-18.0.jar +++ /dev/null Binary files differ diff --git a/pom.xml b/pom.xml new file mode 100644 index 0000000..3be19b5 --- /dev/null +++ b/pom.xml @@ -0,0 +1,44 @@ + + + 4.0.0 + + com.casic + CasicTimeGuard + 1.0-SNAPSHOT + + + 8 + 8 + 1.8 + + + + + org.projectlombok + lombok + 1.18.22 + true + + + + com.alibaba + fastjson + 1.2.79 + + + + + com.google.guava + guava + 31.0.1-jre + + + + com.squareup.okhttp3 + okhttp + 4.9.3 + + + \ No newline at end of file diff --git a/src/com/casic/swing/ui/TimeGuardNtp.form b/src/com/casic/swing/ui/TimeGuardNtp.form deleted file mode 100644 index cdba6f6..0000000 --- a/src/com/casic/swing/ui/TimeGuardNtp.form +++ /dev/null @@ -1,171 +0,0 @@ - -
- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - diff --git a/src/com/casic/swing/ui/TimeGuardNtp.java b/src/com/casic/swing/ui/TimeGuardNtp.java deleted file mode 100644 index 6df5b55..0000000 --- a/src/com/casic/swing/ui/TimeGuardNtp.java +++ /dev/null @@ -1,207 +0,0 @@ -package com.casic.swing.ui; - -import com.casic.swing.utils.CommandUtil; -import com.casic.swing.utils.StringHelper; -import com.casic.swing.utils.TimeOrDateUtil; -import com.google.common.util.concurrent.ThreadFactoryBuilder; - -import javax.swing.*; -import java.awt.*; -import java.awt.event.ActionEvent; -import java.awt.event.ActionListener; -import java.awt.event.ItemEvent; -import java.awt.event.ItemListener; -import java.util.concurrent.ScheduledExecutorService; -import java.util.concurrent.ScheduledThreadPoolExecutor; -import java.util.concurrent.TimeUnit; - -/** - * @author a203 - */ -public class TimeGuardNtp extends JFrame { - private JPanel ntpPanel; - private JComboBox hostComboBox; - private JLabel timeValueLabel; - private JButton updateTimeButton; - private JLabel dotView; - private JLabel currentTimeLabel; - private JCheckBox autoCheckBox; - private JComboBox periodComboBox; - private JPanel stateView; - - private final String[] HOST_NAME = {"NTP服务器(上海)", "中国国家授时中心", "清华大学", "北京大学", "自定义"}; - private final String[] HOST_IP = {"ntp.api.bz", "ntp.ntsc.ac.cn", "s1b.time.edu.cn", "s2m.time.edu.cn"}; - /** - * 同步周期,单位:小时 - */ - private final Integer[] PERIOD = {10, 20, 30}; - private final ScheduledExecutorService executorService = new ScheduledThreadPoolExecutor( - 1, new ThreadFactoryBuilder().setNameFormat("demo-pool-%d").build()); - private boolean hasNtp = false; - private String host = HOST_IP[0]; - - public static void main(String[] args) { - new TimeGuardNtp(); - } - - public TimeGuardNtp() { - setContentPane(ntpPanel); - setResizable(false); - setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); - pack(); - setSize(410, 280); - //居中 - setLocationRelativeTo(null); - setVisible(true); - dotView.setText("未同步"); - setStateView(Color.GRAY); - - StringHelper.createLogFile(); - - /** - * 时间间隔,单位为毫秒 - * */ - currentTimeLabel.setForeground(Color.BLUE); - new Timer(1000, new ActionListener() { - @Override - public void actionPerformed(ActionEvent e) { - String systemTime = TimeOrDateUtil.timestampToTime(System.currentTimeMillis()); - currentTimeLabel.setText(systemTime); - } - }).start(); - - String assertsData = StringHelper.getAssertsData(); - if (!"".equals(assertsData)) { - timeValueLabel.setText(assertsData); - } else { - timeValueLabel.setText("无法确定最近同步时间"); - } - - //初始化JComboBox - initComBox(); - hostComboBox.addItemListener(new ItemListener() { - @Override - public void itemStateChanged(ItemEvent e) { - String item = (String) e.getItem(); - if (e.getStateChange() == ItemEvent.SELECTED) { - if ("自定义".equals(item)) { - String inputContent = JOptionPane.showInputDialog(ntpPanel, "请输入授时中心域名或者IP地址", "", JOptionPane.INFORMATION_MESSAGE); - if (inputContent.isEmpty()) { - JOptionPane.showMessageDialog(ntpPanel, "输入错误,请检查", "Runtime Error", JOptionPane.ERROR_MESSAGE); - } else { - host = inputContent; - } - } else { - for (int i = 0; i < HOST_NAME.length; i++) { - if (item.equals(HOST_NAME[i])) { - host = HOST_IP[i]; - } - } - } - } - } - }); - - //检查环境 - new SwingWorker() { - - @Override - protected Boolean doInBackground() { - hasNtp = CommandUtil.checkEnv(); - return hasNtp; - } - - @Override - protected void done() { - if (!hasNtp) { - JOptionPane.showMessageDialog(ntpPanel, "未当前设备发现可用的NTP配置", "Runtime Error", JOptionPane.ERROR_MESSAGE); - //环境不对,关闭窗体 - dispose(); - } - super.done(); - } - }.execute(); - - autoCheckBox.addActionListener(new ActionListener() { - @Override - public void actionPerformed(ActionEvent e) { - JCheckBox checkBox = (JCheckBox) e.getSource(); - if (checkBox.isSelected()) { - updateTimeButton.setEnabled(false); - periodComboBox.setEnabled(true); - startAutoSynchronize(PERIOD[0]); - } else { - updateTimeButton.setEnabled(true); - periodComboBox.setEnabled(false); - } - } - }); - - periodComboBox.addItemListener(new ItemListener() { - @Override - public void itemStateChanged(ItemEvent e) { - int period = (Integer) e.getItem(); - if (e.getStateChange() == ItemEvent.SELECTED) { - startAutoSynchronize(period); - } - } - }); - - //按钮点击事件 - updateTimeButton.addActionListener(new ActionListener() { - @Override - public void actionPerformed(ActionEvent e) { - updateView(); - } - }); - } - - private void startAutoSynchronize(int period) { - /** - * 开启同步,只能开启一个同步线程 - * - * scheduleAtFixedRate - * 是以上一个任务开始的时间计时,period时间过去后,检测上一个任务是否执行完毕 - * 如果上一个任务执行完毕,则当前任务立即执行 - * 如果上一个任务没有执行完毕,则需要等上一个任务执行完毕后立即执行 - * */ - executorService.scheduleAtFixedRate(new Runnable() { - @Override - public void run() { - updateView(); - } - }, 0, period, TimeUnit.MINUTES); - } - - private void updateView() { - String result = CommandUtil.ntpDate(host); - System.out.println("命令执行结果 ===> " + result); - boolean isSuccess = result.contains("step time server") || result.contains("adjust time server"); - if (isSuccess) { - String systemTime = TimeOrDateUtil.timestampToTime(System.currentTimeMillis()); - setStateView(Color.GREEN); - dotView.setText("同步成功"); - timeValueLabel.setText(systemTime); - //同步成功之后将时间存入本地 - StringHelper.saveAssertsData(systemTime); - } else { - setStateView(Color.RED); - dotView.setText("同步失败"); - timeValueLabel.setText(""); - } - } - - private void initComBox() { - for (String s : HOST_NAME) { - hostComboBox.addItem(s); - } - for (Integer integer : PERIOD) { - periodComboBox.addItem(integer); - } - } - - private void setStateView(Color color) { - stateView.setPreferredSize(new Dimension(15, 15)); - stateView.setBackground(color); - } -} diff --git a/src/com/casic/swing/utils/CommandUtil.java b/src/com/casic/swing/utils/CommandUtil.java deleted file mode 100644 index c487e7d..0000000 --- a/src/com/casic/swing/utils/CommandUtil.java +++ /dev/null @@ -1,76 +0,0 @@ -package com.casic.swing.utils; - -import java.io.BufferedReader; -import java.io.IOException; -import java.io.InputStream; -import java.io.InputStreamReader; -import java.nio.charset.Charset; -import java.util.concurrent.TimeUnit; - -/** - * @author a203 - */ -public class CommandUtil { - /** - * 检查当前系统是否已安装NTP - */ - public static boolean checkEnv() { - System.out.println("检查当前系统是否支持NTP"); - try { - Process exec = Runtime.getRuntime().exec("rpm -q ntp"); - try { - //等待命令执行完成 - exec.waitFor(5, TimeUnit.SECONDS); - } catch (InterruptedException e) { - e.printStackTrace(); - } - String result = parseResult(exec.getInputStream()); - return !result.isEmpty(); - } catch (IOException e) { - e.printStackTrace(); - } - return false; - } - - /** - * 安装NTP - * yum -y install ntp - * */ - - /** - * 授时同步 - * ntpdate -u ntp.api.bz - */ - public static String ntpDate(String host) { - try { - String command = "ntpdate -u " + host; - System.out.println("授时同步 ===> " + command); - Process exec = Runtime.getRuntime().exec(command); - try { - //等待命令执行完成 - exec.waitFor(5, TimeUnit.SECONDS); - } catch (InterruptedException e) { - e.printStackTrace(); - } - return parseResult(exec.getInputStream()); - } catch (IOException e) { - e.printStackTrace(); - } - return ""; - } - - /** - * 解析命令结果 - */ - private static String parseResult(InputStream inputStream) throws IOException { - // 读取输出流内容 - InputStreamReader streamReader = new InputStreamReader(inputStream, Charset.defaultCharset()); - BufferedReader reader = new BufferedReader(streamReader); - StringBuilder builder = new StringBuilder(); - String line; - while ((line = reader.readLine()) != null) { - builder.append(line).append("\n"); - } - return builder.toString(); - } -} diff --git a/src/com/casic/swing/utils/StringHelper.java b/src/com/casic/swing/utils/StringHelper.java deleted file mode 100644 index b994e19..0000000 --- a/src/com/casic/swing/utils/StringHelper.java +++ /dev/null @@ -1,64 +0,0 @@ -package com.casic.swing.utils; - -import javax.swing.filechooser.FileSystemView; -import java.io.*; - -/** - * @author a203 - */ -public class StringHelper { - - private static final String FILE_NAME = "update.log"; - private static File logFile; - - public static void createLogFile() { - FileSystemView view = FileSystemView.getFileSystemView(); - File file = view.getHomeDirectory(); - File dir = new File(file.getAbsolutePath() + File.separator + "logs"); - if (!dir.exists()) { - dir.mkdir(); - } - logFile = new File(dir + File.separator + FILE_NAME); - if (!logFile.exists()) { - // 创建新文件,有同名的文件的话直接覆盖 - try { - logFile.createNewFile(); - } catch (IOException e) { - e.printStackTrace(); - } - } - System.out.println("同步记录路径 ===> " + logFile.getAbsolutePath()); - } - - public static void saveAssertsData(String data) { - try { - FileWriter writer = new FileWriter(logFile); - BufferedWriter out = new BufferedWriter(writer); - out.write(data); - out.flush(); - out.close(); - } catch (IOException e) { - e.printStackTrace(); - } - } - - public static String getAssertsData() { - try { - InputStreamReader inputStreamReader = new InputStreamReader(new FileInputStream(logFile)); - BufferedReader bufferedReader = new BufferedReader(inputStreamReader); - StringBuilder data = new StringBuilder(); - String s; - try { - while ((s = bufferedReader.readLine()) != null) { - data.append(s); - } - return data.toString(); - } catch (IOException e) { - e.printStackTrace(); - } - } catch (IOException e) { - e.printStackTrace(); - } - return ""; - } -} diff --git a/.gitignore b/.gitignore index 0841741..5027de1 100644 --- a/.gitignore +++ b/.gitignore @@ -1,2 +1,4 @@ .idea /out +/logs +/target diff --git a/CasicTimeGuard.iml b/CasicTimeGuard.iml index f54a89f..40532bb 100644 --- a/CasicTimeGuard.iml +++ b/CasicTimeGuard.iml @@ -1,12 +1,29 @@ - - - + + + + - + + + + - + + + + + + + + + + + + + + \ No newline at end of file diff --git a/lib/guava-18.0.jar b/lib/guava-18.0.jar deleted file mode 100644 index 8f89e49..0000000 --- a/lib/guava-18.0.jar +++ /dev/null Binary files differ diff --git a/pom.xml b/pom.xml new file mode 100644 index 0000000..3be19b5 --- /dev/null +++ b/pom.xml @@ -0,0 +1,44 @@ + + + 4.0.0 + + com.casic + CasicTimeGuard + 1.0-SNAPSHOT + + + 8 + 8 + 1.8 + + + + + org.projectlombok + lombok + 1.18.22 + true + + + + com.alibaba + fastjson + 1.2.79 + + + + + com.google.guava + guava + 31.0.1-jre + + + + com.squareup.okhttp3 + okhttp + 4.9.3 + + + \ No newline at end of file diff --git a/src/com/casic/swing/ui/TimeGuardNtp.form b/src/com/casic/swing/ui/TimeGuardNtp.form deleted file mode 100644 index cdba6f6..0000000 --- a/src/com/casic/swing/ui/TimeGuardNtp.form +++ /dev/null @@ -1,171 +0,0 @@ - -
- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - diff --git a/src/com/casic/swing/ui/TimeGuardNtp.java b/src/com/casic/swing/ui/TimeGuardNtp.java deleted file mode 100644 index 6df5b55..0000000 --- a/src/com/casic/swing/ui/TimeGuardNtp.java +++ /dev/null @@ -1,207 +0,0 @@ -package com.casic.swing.ui; - -import com.casic.swing.utils.CommandUtil; -import com.casic.swing.utils.StringHelper; -import com.casic.swing.utils.TimeOrDateUtil; -import com.google.common.util.concurrent.ThreadFactoryBuilder; - -import javax.swing.*; -import java.awt.*; -import java.awt.event.ActionEvent; -import java.awt.event.ActionListener; -import java.awt.event.ItemEvent; -import java.awt.event.ItemListener; -import java.util.concurrent.ScheduledExecutorService; -import java.util.concurrent.ScheduledThreadPoolExecutor; -import java.util.concurrent.TimeUnit; - -/** - * @author a203 - */ -public class TimeGuardNtp extends JFrame { - private JPanel ntpPanel; - private JComboBox hostComboBox; - private JLabel timeValueLabel; - private JButton updateTimeButton; - private JLabel dotView; - private JLabel currentTimeLabel; - private JCheckBox autoCheckBox; - private JComboBox periodComboBox; - private JPanel stateView; - - private final String[] HOST_NAME = {"NTP服务器(上海)", "中国国家授时中心", "清华大学", "北京大学", "自定义"}; - private final String[] HOST_IP = {"ntp.api.bz", "ntp.ntsc.ac.cn", "s1b.time.edu.cn", "s2m.time.edu.cn"}; - /** - * 同步周期,单位:小时 - */ - private final Integer[] PERIOD = {10, 20, 30}; - private final ScheduledExecutorService executorService = new ScheduledThreadPoolExecutor( - 1, new ThreadFactoryBuilder().setNameFormat("demo-pool-%d").build()); - private boolean hasNtp = false; - private String host = HOST_IP[0]; - - public static void main(String[] args) { - new TimeGuardNtp(); - } - - public TimeGuardNtp() { - setContentPane(ntpPanel); - setResizable(false); - setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); - pack(); - setSize(410, 280); - //居中 - setLocationRelativeTo(null); - setVisible(true); - dotView.setText("未同步"); - setStateView(Color.GRAY); - - StringHelper.createLogFile(); - - /** - * 时间间隔,单位为毫秒 - * */ - currentTimeLabel.setForeground(Color.BLUE); - new Timer(1000, new ActionListener() { - @Override - public void actionPerformed(ActionEvent e) { - String systemTime = TimeOrDateUtil.timestampToTime(System.currentTimeMillis()); - currentTimeLabel.setText(systemTime); - } - }).start(); - - String assertsData = StringHelper.getAssertsData(); - if (!"".equals(assertsData)) { - timeValueLabel.setText(assertsData); - } else { - timeValueLabel.setText("无法确定最近同步时间"); - } - - //初始化JComboBox - initComBox(); - hostComboBox.addItemListener(new ItemListener() { - @Override - public void itemStateChanged(ItemEvent e) { - String item = (String) e.getItem(); - if (e.getStateChange() == ItemEvent.SELECTED) { - if ("自定义".equals(item)) { - String inputContent = JOptionPane.showInputDialog(ntpPanel, "请输入授时中心域名或者IP地址", "", JOptionPane.INFORMATION_MESSAGE); - if (inputContent.isEmpty()) { - JOptionPane.showMessageDialog(ntpPanel, "输入错误,请检查", "Runtime Error", JOptionPane.ERROR_MESSAGE); - } else { - host = inputContent; - } - } else { - for (int i = 0; i < HOST_NAME.length; i++) { - if (item.equals(HOST_NAME[i])) { - host = HOST_IP[i]; - } - } - } - } - } - }); - - //检查环境 - new SwingWorker() { - - @Override - protected Boolean doInBackground() { - hasNtp = CommandUtil.checkEnv(); - return hasNtp; - } - - @Override - protected void done() { - if (!hasNtp) { - JOptionPane.showMessageDialog(ntpPanel, "未当前设备发现可用的NTP配置", "Runtime Error", JOptionPane.ERROR_MESSAGE); - //环境不对,关闭窗体 - dispose(); - } - super.done(); - } - }.execute(); - - autoCheckBox.addActionListener(new ActionListener() { - @Override - public void actionPerformed(ActionEvent e) { - JCheckBox checkBox = (JCheckBox) e.getSource(); - if (checkBox.isSelected()) { - updateTimeButton.setEnabled(false); - periodComboBox.setEnabled(true); - startAutoSynchronize(PERIOD[0]); - } else { - updateTimeButton.setEnabled(true); - periodComboBox.setEnabled(false); - } - } - }); - - periodComboBox.addItemListener(new ItemListener() { - @Override - public void itemStateChanged(ItemEvent e) { - int period = (Integer) e.getItem(); - if (e.getStateChange() == ItemEvent.SELECTED) { - startAutoSynchronize(period); - } - } - }); - - //按钮点击事件 - updateTimeButton.addActionListener(new ActionListener() { - @Override - public void actionPerformed(ActionEvent e) { - updateView(); - } - }); - } - - private void startAutoSynchronize(int period) { - /** - * 开启同步,只能开启一个同步线程 - * - * scheduleAtFixedRate - * 是以上一个任务开始的时间计时,period时间过去后,检测上一个任务是否执行完毕 - * 如果上一个任务执行完毕,则当前任务立即执行 - * 如果上一个任务没有执行完毕,则需要等上一个任务执行完毕后立即执行 - * */ - executorService.scheduleAtFixedRate(new Runnable() { - @Override - public void run() { - updateView(); - } - }, 0, period, TimeUnit.MINUTES); - } - - private void updateView() { - String result = CommandUtil.ntpDate(host); - System.out.println("命令执行结果 ===> " + result); - boolean isSuccess = result.contains("step time server") || result.contains("adjust time server"); - if (isSuccess) { - String systemTime = TimeOrDateUtil.timestampToTime(System.currentTimeMillis()); - setStateView(Color.GREEN); - dotView.setText("同步成功"); - timeValueLabel.setText(systemTime); - //同步成功之后将时间存入本地 - StringHelper.saveAssertsData(systemTime); - } else { - setStateView(Color.RED); - dotView.setText("同步失败"); - timeValueLabel.setText(""); - } - } - - private void initComBox() { - for (String s : HOST_NAME) { - hostComboBox.addItem(s); - } - for (Integer integer : PERIOD) { - periodComboBox.addItem(integer); - } - } - - private void setStateView(Color color) { - stateView.setPreferredSize(new Dimension(15, 15)); - stateView.setBackground(color); - } -} diff --git a/src/com/casic/swing/utils/CommandUtil.java b/src/com/casic/swing/utils/CommandUtil.java deleted file mode 100644 index c487e7d..0000000 --- a/src/com/casic/swing/utils/CommandUtil.java +++ /dev/null @@ -1,76 +0,0 @@ -package com.casic.swing.utils; - -import java.io.BufferedReader; -import java.io.IOException; -import java.io.InputStream; -import java.io.InputStreamReader; -import java.nio.charset.Charset; -import java.util.concurrent.TimeUnit; - -/** - * @author a203 - */ -public class CommandUtil { - /** - * 检查当前系统是否已安装NTP - */ - public static boolean checkEnv() { - System.out.println("检查当前系统是否支持NTP"); - try { - Process exec = Runtime.getRuntime().exec("rpm -q ntp"); - try { - //等待命令执行完成 - exec.waitFor(5, TimeUnit.SECONDS); - } catch (InterruptedException e) { - e.printStackTrace(); - } - String result = parseResult(exec.getInputStream()); - return !result.isEmpty(); - } catch (IOException e) { - e.printStackTrace(); - } - return false; - } - - /** - * 安装NTP - * yum -y install ntp - * */ - - /** - * 授时同步 - * ntpdate -u ntp.api.bz - */ - public static String ntpDate(String host) { - try { - String command = "ntpdate -u " + host; - System.out.println("授时同步 ===> " + command); - Process exec = Runtime.getRuntime().exec(command); - try { - //等待命令执行完成 - exec.waitFor(5, TimeUnit.SECONDS); - } catch (InterruptedException e) { - e.printStackTrace(); - } - return parseResult(exec.getInputStream()); - } catch (IOException e) { - e.printStackTrace(); - } - return ""; - } - - /** - * 解析命令结果 - */ - private static String parseResult(InputStream inputStream) throws IOException { - // 读取输出流内容 - InputStreamReader streamReader = new InputStreamReader(inputStream, Charset.defaultCharset()); - BufferedReader reader = new BufferedReader(streamReader); - StringBuilder builder = new StringBuilder(); - String line; - while ((line = reader.readLine()) != null) { - builder.append(line).append("\n"); - } - return builder.toString(); - } -} diff --git a/src/com/casic/swing/utils/StringHelper.java b/src/com/casic/swing/utils/StringHelper.java deleted file mode 100644 index b994e19..0000000 --- a/src/com/casic/swing/utils/StringHelper.java +++ /dev/null @@ -1,64 +0,0 @@ -package com.casic.swing.utils; - -import javax.swing.filechooser.FileSystemView; -import java.io.*; - -/** - * @author a203 - */ -public class StringHelper { - - private static final String FILE_NAME = "update.log"; - private static File logFile; - - public static void createLogFile() { - FileSystemView view = FileSystemView.getFileSystemView(); - File file = view.getHomeDirectory(); - File dir = new File(file.getAbsolutePath() + File.separator + "logs"); - if (!dir.exists()) { - dir.mkdir(); - } - logFile = new File(dir + File.separator + FILE_NAME); - if (!logFile.exists()) { - // 创建新文件,有同名的文件的话直接覆盖 - try { - logFile.createNewFile(); - } catch (IOException e) { - e.printStackTrace(); - } - } - System.out.println("同步记录路径 ===> " + logFile.getAbsolutePath()); - } - - public static void saveAssertsData(String data) { - try { - FileWriter writer = new FileWriter(logFile); - BufferedWriter out = new BufferedWriter(writer); - out.write(data); - out.flush(); - out.close(); - } catch (IOException e) { - e.printStackTrace(); - } - } - - public static String getAssertsData() { - try { - InputStreamReader inputStreamReader = new InputStreamReader(new FileInputStream(logFile)); - BufferedReader bufferedReader = new BufferedReader(inputStreamReader); - StringBuilder data = new StringBuilder(); - String s; - try { - while ((s = bufferedReader.readLine()) != null) { - data.append(s); - } - return data.toString(); - } catch (IOException e) { - e.printStackTrace(); - } - } catch (IOException e) { - e.printStackTrace(); - } - return ""; - } -} diff --git a/src/com/casic/swing/utils/TimeOrDateUtil.java b/src/com/casic/swing/utils/TimeOrDateUtil.java deleted file mode 100644 index 7adc5a6..0000000 --- a/src/com/casic/swing/utils/TimeOrDateUtil.java +++ /dev/null @@ -1,18 +0,0 @@ -package com.casic.swing.utils; - -import java.text.SimpleDateFormat; -import java.util.Date; - -/** - * @author a203 - */ -public class TimeOrDateUtil { - - /** - * 时间戳转时间 - */ - public static String timestampToTime(long millSeconds) { - SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); - return format.format(new Date(millSeconds)); - } -} diff --git a/.gitignore b/.gitignore index 0841741..5027de1 100644 --- a/.gitignore +++ b/.gitignore @@ -1,2 +1,4 @@ .idea /out +/logs +/target diff --git a/CasicTimeGuard.iml b/CasicTimeGuard.iml index f54a89f..40532bb 100644 --- a/CasicTimeGuard.iml +++ b/CasicTimeGuard.iml @@ -1,12 +1,29 @@ - - - + + + + - + + + + - + + + + + + + + + + + + + + \ No newline at end of file diff --git a/lib/guava-18.0.jar b/lib/guava-18.0.jar deleted file mode 100644 index 8f89e49..0000000 --- a/lib/guava-18.0.jar +++ /dev/null Binary files differ diff --git a/pom.xml b/pom.xml new file mode 100644 index 0000000..3be19b5 --- /dev/null +++ b/pom.xml @@ -0,0 +1,44 @@ + + + 4.0.0 + + com.casic + CasicTimeGuard + 1.0-SNAPSHOT + + + 8 + 8 + 1.8 + + + + + org.projectlombok + lombok + 1.18.22 + true + + + + com.alibaba + fastjson + 1.2.79 + + + + + com.google.guava + guava + 31.0.1-jre + + + + com.squareup.okhttp3 + okhttp + 4.9.3 + + + \ No newline at end of file diff --git a/src/com/casic/swing/ui/TimeGuardNtp.form b/src/com/casic/swing/ui/TimeGuardNtp.form deleted file mode 100644 index cdba6f6..0000000 --- a/src/com/casic/swing/ui/TimeGuardNtp.form +++ /dev/null @@ -1,171 +0,0 @@ - -
- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - diff --git a/src/com/casic/swing/ui/TimeGuardNtp.java b/src/com/casic/swing/ui/TimeGuardNtp.java deleted file mode 100644 index 6df5b55..0000000 --- a/src/com/casic/swing/ui/TimeGuardNtp.java +++ /dev/null @@ -1,207 +0,0 @@ -package com.casic.swing.ui; - -import com.casic.swing.utils.CommandUtil; -import com.casic.swing.utils.StringHelper; -import com.casic.swing.utils.TimeOrDateUtil; -import com.google.common.util.concurrent.ThreadFactoryBuilder; - -import javax.swing.*; -import java.awt.*; -import java.awt.event.ActionEvent; -import java.awt.event.ActionListener; -import java.awt.event.ItemEvent; -import java.awt.event.ItemListener; -import java.util.concurrent.ScheduledExecutorService; -import java.util.concurrent.ScheduledThreadPoolExecutor; -import java.util.concurrent.TimeUnit; - -/** - * @author a203 - */ -public class TimeGuardNtp extends JFrame { - private JPanel ntpPanel; - private JComboBox hostComboBox; - private JLabel timeValueLabel; - private JButton updateTimeButton; - private JLabel dotView; - private JLabel currentTimeLabel; - private JCheckBox autoCheckBox; - private JComboBox periodComboBox; - private JPanel stateView; - - private final String[] HOST_NAME = {"NTP服务器(上海)", "中国国家授时中心", "清华大学", "北京大学", "自定义"}; - private final String[] HOST_IP = {"ntp.api.bz", "ntp.ntsc.ac.cn", "s1b.time.edu.cn", "s2m.time.edu.cn"}; - /** - * 同步周期,单位:小时 - */ - private final Integer[] PERIOD = {10, 20, 30}; - private final ScheduledExecutorService executorService = new ScheduledThreadPoolExecutor( - 1, new ThreadFactoryBuilder().setNameFormat("demo-pool-%d").build()); - private boolean hasNtp = false; - private String host = HOST_IP[0]; - - public static void main(String[] args) { - new TimeGuardNtp(); - } - - public TimeGuardNtp() { - setContentPane(ntpPanel); - setResizable(false); - setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); - pack(); - setSize(410, 280); - //居中 - setLocationRelativeTo(null); - setVisible(true); - dotView.setText("未同步"); - setStateView(Color.GRAY); - - StringHelper.createLogFile(); - - /** - * 时间间隔,单位为毫秒 - * */ - currentTimeLabel.setForeground(Color.BLUE); - new Timer(1000, new ActionListener() { - @Override - public void actionPerformed(ActionEvent e) { - String systemTime = TimeOrDateUtil.timestampToTime(System.currentTimeMillis()); - currentTimeLabel.setText(systemTime); - } - }).start(); - - String assertsData = StringHelper.getAssertsData(); - if (!"".equals(assertsData)) { - timeValueLabel.setText(assertsData); - } else { - timeValueLabel.setText("无法确定最近同步时间"); - } - - //初始化JComboBox - initComBox(); - hostComboBox.addItemListener(new ItemListener() { - @Override - public void itemStateChanged(ItemEvent e) { - String item = (String) e.getItem(); - if (e.getStateChange() == ItemEvent.SELECTED) { - if ("自定义".equals(item)) { - String inputContent = JOptionPane.showInputDialog(ntpPanel, "请输入授时中心域名或者IP地址", "", JOptionPane.INFORMATION_MESSAGE); - if (inputContent.isEmpty()) { - JOptionPane.showMessageDialog(ntpPanel, "输入错误,请检查", "Runtime Error", JOptionPane.ERROR_MESSAGE); - } else { - host = inputContent; - } - } else { - for (int i = 0; i < HOST_NAME.length; i++) { - if (item.equals(HOST_NAME[i])) { - host = HOST_IP[i]; - } - } - } - } - } - }); - - //检查环境 - new SwingWorker() { - - @Override - protected Boolean doInBackground() { - hasNtp = CommandUtil.checkEnv(); - return hasNtp; - } - - @Override - protected void done() { - if (!hasNtp) { - JOptionPane.showMessageDialog(ntpPanel, "未当前设备发现可用的NTP配置", "Runtime Error", JOptionPane.ERROR_MESSAGE); - //环境不对,关闭窗体 - dispose(); - } - super.done(); - } - }.execute(); - - autoCheckBox.addActionListener(new ActionListener() { - @Override - public void actionPerformed(ActionEvent e) { - JCheckBox checkBox = (JCheckBox) e.getSource(); - if (checkBox.isSelected()) { - updateTimeButton.setEnabled(false); - periodComboBox.setEnabled(true); - startAutoSynchronize(PERIOD[0]); - } else { - updateTimeButton.setEnabled(true); - periodComboBox.setEnabled(false); - } - } - }); - - periodComboBox.addItemListener(new ItemListener() { - @Override - public void itemStateChanged(ItemEvent e) { - int period = (Integer) e.getItem(); - if (e.getStateChange() == ItemEvent.SELECTED) { - startAutoSynchronize(period); - } - } - }); - - //按钮点击事件 - updateTimeButton.addActionListener(new ActionListener() { - @Override - public void actionPerformed(ActionEvent e) { - updateView(); - } - }); - } - - private void startAutoSynchronize(int period) { - /** - * 开启同步,只能开启一个同步线程 - * - * scheduleAtFixedRate - * 是以上一个任务开始的时间计时,period时间过去后,检测上一个任务是否执行完毕 - * 如果上一个任务执行完毕,则当前任务立即执行 - * 如果上一个任务没有执行完毕,则需要等上一个任务执行完毕后立即执行 - * */ - executorService.scheduleAtFixedRate(new Runnable() { - @Override - public void run() { - updateView(); - } - }, 0, period, TimeUnit.MINUTES); - } - - private void updateView() { - String result = CommandUtil.ntpDate(host); - System.out.println("命令执行结果 ===> " + result); - boolean isSuccess = result.contains("step time server") || result.contains("adjust time server"); - if (isSuccess) { - String systemTime = TimeOrDateUtil.timestampToTime(System.currentTimeMillis()); - setStateView(Color.GREEN); - dotView.setText("同步成功"); - timeValueLabel.setText(systemTime); - //同步成功之后将时间存入本地 - StringHelper.saveAssertsData(systemTime); - } else { - setStateView(Color.RED); - dotView.setText("同步失败"); - timeValueLabel.setText(""); - } - } - - private void initComBox() { - for (String s : HOST_NAME) { - hostComboBox.addItem(s); - } - for (Integer integer : PERIOD) { - periodComboBox.addItem(integer); - } - } - - private void setStateView(Color color) { - stateView.setPreferredSize(new Dimension(15, 15)); - stateView.setBackground(color); - } -} diff --git a/src/com/casic/swing/utils/CommandUtil.java b/src/com/casic/swing/utils/CommandUtil.java deleted file mode 100644 index c487e7d..0000000 --- a/src/com/casic/swing/utils/CommandUtil.java +++ /dev/null @@ -1,76 +0,0 @@ -package com.casic.swing.utils; - -import java.io.BufferedReader; -import java.io.IOException; -import java.io.InputStream; -import java.io.InputStreamReader; -import java.nio.charset.Charset; -import java.util.concurrent.TimeUnit; - -/** - * @author a203 - */ -public class CommandUtil { - /** - * 检查当前系统是否已安装NTP - */ - public static boolean checkEnv() { - System.out.println("检查当前系统是否支持NTP"); - try { - Process exec = Runtime.getRuntime().exec("rpm -q ntp"); - try { - //等待命令执行完成 - exec.waitFor(5, TimeUnit.SECONDS); - } catch (InterruptedException e) { - e.printStackTrace(); - } - String result = parseResult(exec.getInputStream()); - return !result.isEmpty(); - } catch (IOException e) { - e.printStackTrace(); - } - return false; - } - - /** - * 安装NTP - * yum -y install ntp - * */ - - /** - * 授时同步 - * ntpdate -u ntp.api.bz - */ - public static String ntpDate(String host) { - try { - String command = "ntpdate -u " + host; - System.out.println("授时同步 ===> " + command); - Process exec = Runtime.getRuntime().exec(command); - try { - //等待命令执行完成 - exec.waitFor(5, TimeUnit.SECONDS); - } catch (InterruptedException e) { - e.printStackTrace(); - } - return parseResult(exec.getInputStream()); - } catch (IOException e) { - e.printStackTrace(); - } - return ""; - } - - /** - * 解析命令结果 - */ - private static String parseResult(InputStream inputStream) throws IOException { - // 读取输出流内容 - InputStreamReader streamReader = new InputStreamReader(inputStream, Charset.defaultCharset()); - BufferedReader reader = new BufferedReader(streamReader); - StringBuilder builder = new StringBuilder(); - String line; - while ((line = reader.readLine()) != null) { - builder.append(line).append("\n"); - } - return builder.toString(); - } -} diff --git a/src/com/casic/swing/utils/StringHelper.java b/src/com/casic/swing/utils/StringHelper.java deleted file mode 100644 index b994e19..0000000 --- a/src/com/casic/swing/utils/StringHelper.java +++ /dev/null @@ -1,64 +0,0 @@ -package com.casic.swing.utils; - -import javax.swing.filechooser.FileSystemView; -import java.io.*; - -/** - * @author a203 - */ -public class StringHelper { - - private static final String FILE_NAME = "update.log"; - private static File logFile; - - public static void createLogFile() { - FileSystemView view = FileSystemView.getFileSystemView(); - File file = view.getHomeDirectory(); - File dir = new File(file.getAbsolutePath() + File.separator + "logs"); - if (!dir.exists()) { - dir.mkdir(); - } - logFile = new File(dir + File.separator + FILE_NAME); - if (!logFile.exists()) { - // 创建新文件,有同名的文件的话直接覆盖 - try { - logFile.createNewFile(); - } catch (IOException e) { - e.printStackTrace(); - } - } - System.out.println("同步记录路径 ===> " + logFile.getAbsolutePath()); - } - - public static void saveAssertsData(String data) { - try { - FileWriter writer = new FileWriter(logFile); - BufferedWriter out = new BufferedWriter(writer); - out.write(data); - out.flush(); - out.close(); - } catch (IOException e) { - e.printStackTrace(); - } - } - - public static String getAssertsData() { - try { - InputStreamReader inputStreamReader = new InputStreamReader(new FileInputStream(logFile)); - BufferedReader bufferedReader = new BufferedReader(inputStreamReader); - StringBuilder data = new StringBuilder(); - String s; - try { - while ((s = bufferedReader.readLine()) != null) { - data.append(s); - } - return data.toString(); - } catch (IOException e) { - e.printStackTrace(); - } - } catch (IOException e) { - e.printStackTrace(); - } - return ""; - } -} diff --git a/src/com/casic/swing/utils/TimeOrDateUtil.java b/src/com/casic/swing/utils/TimeOrDateUtil.java deleted file mode 100644 index 7adc5a6..0000000 --- a/src/com/casic/swing/utils/TimeOrDateUtil.java +++ /dev/null @@ -1,18 +0,0 @@ -package com.casic.swing.utils; - -import java.text.SimpleDateFormat; -import java.util.Date; - -/** - * @author a203 - */ -public class TimeOrDateUtil { - - /** - * 时间戳转时间 - */ - public static String timestampToTime(long millSeconds) { - SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); - return format.format(new Date(millSeconds)); - } -} diff --git a/src/main/java/com/casic/swing/ui/TimeGuardNtp.form b/src/main/java/com/casic/swing/ui/TimeGuardNtp.form new file mode 100644 index 0000000..8732b4b --- /dev/null +++ b/src/main/java/com/casic/swing/ui/TimeGuardNtp.form @@ -0,0 +1,207 @@ + +
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/.gitignore b/.gitignore index 0841741..5027de1 100644 --- a/.gitignore +++ b/.gitignore @@ -1,2 +1,4 @@ .idea /out +/logs +/target diff --git a/CasicTimeGuard.iml b/CasicTimeGuard.iml index f54a89f..40532bb 100644 --- a/CasicTimeGuard.iml +++ b/CasicTimeGuard.iml @@ -1,12 +1,29 @@ - - - + + + + - + + + + - + + + + + + + + + + + + + + \ No newline at end of file diff --git a/lib/guava-18.0.jar b/lib/guava-18.0.jar deleted file mode 100644 index 8f89e49..0000000 --- a/lib/guava-18.0.jar +++ /dev/null Binary files differ diff --git a/pom.xml b/pom.xml new file mode 100644 index 0000000..3be19b5 --- /dev/null +++ b/pom.xml @@ -0,0 +1,44 @@ + + + 4.0.0 + + com.casic + CasicTimeGuard + 1.0-SNAPSHOT + + + 8 + 8 + 1.8 + + + + + org.projectlombok + lombok + 1.18.22 + true + + + + com.alibaba + fastjson + 1.2.79 + + + + + com.google.guava + guava + 31.0.1-jre + + + + com.squareup.okhttp3 + okhttp + 4.9.3 + + + \ No newline at end of file diff --git a/src/com/casic/swing/ui/TimeGuardNtp.form b/src/com/casic/swing/ui/TimeGuardNtp.form deleted file mode 100644 index cdba6f6..0000000 --- a/src/com/casic/swing/ui/TimeGuardNtp.form +++ /dev/null @@ -1,171 +0,0 @@ - -
- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - diff --git a/src/com/casic/swing/ui/TimeGuardNtp.java b/src/com/casic/swing/ui/TimeGuardNtp.java deleted file mode 100644 index 6df5b55..0000000 --- a/src/com/casic/swing/ui/TimeGuardNtp.java +++ /dev/null @@ -1,207 +0,0 @@ -package com.casic.swing.ui; - -import com.casic.swing.utils.CommandUtil; -import com.casic.swing.utils.StringHelper; -import com.casic.swing.utils.TimeOrDateUtil; -import com.google.common.util.concurrent.ThreadFactoryBuilder; - -import javax.swing.*; -import java.awt.*; -import java.awt.event.ActionEvent; -import java.awt.event.ActionListener; -import java.awt.event.ItemEvent; -import java.awt.event.ItemListener; -import java.util.concurrent.ScheduledExecutorService; -import java.util.concurrent.ScheduledThreadPoolExecutor; -import java.util.concurrent.TimeUnit; - -/** - * @author a203 - */ -public class TimeGuardNtp extends JFrame { - private JPanel ntpPanel; - private JComboBox hostComboBox; - private JLabel timeValueLabel; - private JButton updateTimeButton; - private JLabel dotView; - private JLabel currentTimeLabel; - private JCheckBox autoCheckBox; - private JComboBox periodComboBox; - private JPanel stateView; - - private final String[] HOST_NAME = {"NTP服务器(上海)", "中国国家授时中心", "清华大学", "北京大学", "自定义"}; - private final String[] HOST_IP = {"ntp.api.bz", "ntp.ntsc.ac.cn", "s1b.time.edu.cn", "s2m.time.edu.cn"}; - /** - * 同步周期,单位:小时 - */ - private final Integer[] PERIOD = {10, 20, 30}; - private final ScheduledExecutorService executorService = new ScheduledThreadPoolExecutor( - 1, new ThreadFactoryBuilder().setNameFormat("demo-pool-%d").build()); - private boolean hasNtp = false; - private String host = HOST_IP[0]; - - public static void main(String[] args) { - new TimeGuardNtp(); - } - - public TimeGuardNtp() { - setContentPane(ntpPanel); - setResizable(false); - setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); - pack(); - setSize(410, 280); - //居中 - setLocationRelativeTo(null); - setVisible(true); - dotView.setText("未同步"); - setStateView(Color.GRAY); - - StringHelper.createLogFile(); - - /** - * 时间间隔,单位为毫秒 - * */ - currentTimeLabel.setForeground(Color.BLUE); - new Timer(1000, new ActionListener() { - @Override - public void actionPerformed(ActionEvent e) { - String systemTime = TimeOrDateUtil.timestampToTime(System.currentTimeMillis()); - currentTimeLabel.setText(systemTime); - } - }).start(); - - String assertsData = StringHelper.getAssertsData(); - if (!"".equals(assertsData)) { - timeValueLabel.setText(assertsData); - } else { - timeValueLabel.setText("无法确定最近同步时间"); - } - - //初始化JComboBox - initComBox(); - hostComboBox.addItemListener(new ItemListener() { - @Override - public void itemStateChanged(ItemEvent e) { - String item = (String) e.getItem(); - if (e.getStateChange() == ItemEvent.SELECTED) { - if ("自定义".equals(item)) { - String inputContent = JOptionPane.showInputDialog(ntpPanel, "请输入授时中心域名或者IP地址", "", JOptionPane.INFORMATION_MESSAGE); - if (inputContent.isEmpty()) { - JOptionPane.showMessageDialog(ntpPanel, "输入错误,请检查", "Runtime Error", JOptionPane.ERROR_MESSAGE); - } else { - host = inputContent; - } - } else { - for (int i = 0; i < HOST_NAME.length; i++) { - if (item.equals(HOST_NAME[i])) { - host = HOST_IP[i]; - } - } - } - } - } - }); - - //检查环境 - new SwingWorker() { - - @Override - protected Boolean doInBackground() { - hasNtp = CommandUtil.checkEnv(); - return hasNtp; - } - - @Override - protected void done() { - if (!hasNtp) { - JOptionPane.showMessageDialog(ntpPanel, "未当前设备发现可用的NTP配置", "Runtime Error", JOptionPane.ERROR_MESSAGE); - //环境不对,关闭窗体 - dispose(); - } - super.done(); - } - }.execute(); - - autoCheckBox.addActionListener(new ActionListener() { - @Override - public void actionPerformed(ActionEvent e) { - JCheckBox checkBox = (JCheckBox) e.getSource(); - if (checkBox.isSelected()) { - updateTimeButton.setEnabled(false); - periodComboBox.setEnabled(true); - startAutoSynchronize(PERIOD[0]); - } else { - updateTimeButton.setEnabled(true); - periodComboBox.setEnabled(false); - } - } - }); - - periodComboBox.addItemListener(new ItemListener() { - @Override - public void itemStateChanged(ItemEvent e) { - int period = (Integer) e.getItem(); - if (e.getStateChange() == ItemEvent.SELECTED) { - startAutoSynchronize(period); - } - } - }); - - //按钮点击事件 - updateTimeButton.addActionListener(new ActionListener() { - @Override - public void actionPerformed(ActionEvent e) { - updateView(); - } - }); - } - - private void startAutoSynchronize(int period) { - /** - * 开启同步,只能开启一个同步线程 - * - * scheduleAtFixedRate - * 是以上一个任务开始的时间计时,period时间过去后,检测上一个任务是否执行完毕 - * 如果上一个任务执行完毕,则当前任务立即执行 - * 如果上一个任务没有执行完毕,则需要等上一个任务执行完毕后立即执行 - * */ - executorService.scheduleAtFixedRate(new Runnable() { - @Override - public void run() { - updateView(); - } - }, 0, period, TimeUnit.MINUTES); - } - - private void updateView() { - String result = CommandUtil.ntpDate(host); - System.out.println("命令执行结果 ===> " + result); - boolean isSuccess = result.contains("step time server") || result.contains("adjust time server"); - if (isSuccess) { - String systemTime = TimeOrDateUtil.timestampToTime(System.currentTimeMillis()); - setStateView(Color.GREEN); - dotView.setText("同步成功"); - timeValueLabel.setText(systemTime); - //同步成功之后将时间存入本地 - StringHelper.saveAssertsData(systemTime); - } else { - setStateView(Color.RED); - dotView.setText("同步失败"); - timeValueLabel.setText(""); - } - } - - private void initComBox() { - for (String s : HOST_NAME) { - hostComboBox.addItem(s); - } - for (Integer integer : PERIOD) { - periodComboBox.addItem(integer); - } - } - - private void setStateView(Color color) { - stateView.setPreferredSize(new Dimension(15, 15)); - stateView.setBackground(color); - } -} diff --git a/src/com/casic/swing/utils/CommandUtil.java b/src/com/casic/swing/utils/CommandUtil.java deleted file mode 100644 index c487e7d..0000000 --- a/src/com/casic/swing/utils/CommandUtil.java +++ /dev/null @@ -1,76 +0,0 @@ -package com.casic.swing.utils; - -import java.io.BufferedReader; -import java.io.IOException; -import java.io.InputStream; -import java.io.InputStreamReader; -import java.nio.charset.Charset; -import java.util.concurrent.TimeUnit; - -/** - * @author a203 - */ -public class CommandUtil { - /** - * 检查当前系统是否已安装NTP - */ - public static boolean checkEnv() { - System.out.println("检查当前系统是否支持NTP"); - try { - Process exec = Runtime.getRuntime().exec("rpm -q ntp"); - try { - //等待命令执行完成 - exec.waitFor(5, TimeUnit.SECONDS); - } catch (InterruptedException e) { - e.printStackTrace(); - } - String result = parseResult(exec.getInputStream()); - return !result.isEmpty(); - } catch (IOException e) { - e.printStackTrace(); - } - return false; - } - - /** - * 安装NTP - * yum -y install ntp - * */ - - /** - * 授时同步 - * ntpdate -u ntp.api.bz - */ - public static String ntpDate(String host) { - try { - String command = "ntpdate -u " + host; - System.out.println("授时同步 ===> " + command); - Process exec = Runtime.getRuntime().exec(command); - try { - //等待命令执行完成 - exec.waitFor(5, TimeUnit.SECONDS); - } catch (InterruptedException e) { - e.printStackTrace(); - } - return parseResult(exec.getInputStream()); - } catch (IOException e) { - e.printStackTrace(); - } - return ""; - } - - /** - * 解析命令结果 - */ - private static String parseResult(InputStream inputStream) throws IOException { - // 读取输出流内容 - InputStreamReader streamReader = new InputStreamReader(inputStream, Charset.defaultCharset()); - BufferedReader reader = new BufferedReader(streamReader); - StringBuilder builder = new StringBuilder(); - String line; - while ((line = reader.readLine()) != null) { - builder.append(line).append("\n"); - } - return builder.toString(); - } -} diff --git a/src/com/casic/swing/utils/StringHelper.java b/src/com/casic/swing/utils/StringHelper.java deleted file mode 100644 index b994e19..0000000 --- a/src/com/casic/swing/utils/StringHelper.java +++ /dev/null @@ -1,64 +0,0 @@ -package com.casic.swing.utils; - -import javax.swing.filechooser.FileSystemView; -import java.io.*; - -/** - * @author a203 - */ -public class StringHelper { - - private static final String FILE_NAME = "update.log"; - private static File logFile; - - public static void createLogFile() { - FileSystemView view = FileSystemView.getFileSystemView(); - File file = view.getHomeDirectory(); - File dir = new File(file.getAbsolutePath() + File.separator + "logs"); - if (!dir.exists()) { - dir.mkdir(); - } - logFile = new File(dir + File.separator + FILE_NAME); - if (!logFile.exists()) { - // 创建新文件,有同名的文件的话直接覆盖 - try { - logFile.createNewFile(); - } catch (IOException e) { - e.printStackTrace(); - } - } - System.out.println("同步记录路径 ===> " + logFile.getAbsolutePath()); - } - - public static void saveAssertsData(String data) { - try { - FileWriter writer = new FileWriter(logFile); - BufferedWriter out = new BufferedWriter(writer); - out.write(data); - out.flush(); - out.close(); - } catch (IOException e) { - e.printStackTrace(); - } - } - - public static String getAssertsData() { - try { - InputStreamReader inputStreamReader = new InputStreamReader(new FileInputStream(logFile)); - BufferedReader bufferedReader = new BufferedReader(inputStreamReader); - StringBuilder data = new StringBuilder(); - String s; - try { - while ((s = bufferedReader.readLine()) != null) { - data.append(s); - } - return data.toString(); - } catch (IOException e) { - e.printStackTrace(); - } - } catch (IOException e) { - e.printStackTrace(); - } - return ""; - } -} diff --git a/src/com/casic/swing/utils/TimeOrDateUtil.java b/src/com/casic/swing/utils/TimeOrDateUtil.java deleted file mode 100644 index 7adc5a6..0000000 --- a/src/com/casic/swing/utils/TimeOrDateUtil.java +++ /dev/null @@ -1,18 +0,0 @@ -package com.casic.swing.utils; - -import java.text.SimpleDateFormat; -import java.util.Date; - -/** - * @author a203 - */ -public class TimeOrDateUtil { - - /** - * 时间戳转时间 - */ - public static String timestampToTime(long millSeconds) { - SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); - return format.format(new Date(millSeconds)); - } -} diff --git a/src/main/java/com/casic/swing/ui/TimeGuardNtp.form b/src/main/java/com/casic/swing/ui/TimeGuardNtp.form new file mode 100644 index 0000000..8732b4b --- /dev/null +++ b/src/main/java/com/casic/swing/ui/TimeGuardNtp.form @@ -0,0 +1,207 @@ + +
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/src/main/java/com/casic/swing/ui/TimeGuardNtp.java b/src/main/java/com/casic/swing/ui/TimeGuardNtp.java new file mode 100644 index 0000000..9c7fef7 --- /dev/null +++ b/src/main/java/com/casic/swing/ui/TimeGuardNtp.java @@ -0,0 +1,239 @@ +package com.casic.swing.ui; + +import com.alibaba.fastjson.JSONException; +import com.alibaba.fastjson.JSONObject; +import com.casic.swing.utils.*; +import com.google.common.util.concurrent.ThreadFactoryBuilder; +import okhttp3.Request; + +import javax.swing.*; +import java.awt.*; +import java.awt.event.ActionEvent; +import java.awt.event.ActionListener; +import java.awt.event.ItemEvent; +import java.awt.event.ItemListener; +import java.net.InetAddress; +import java.util.concurrent.ScheduledExecutorService; +import java.util.concurrent.ScheduledThreadPoolExecutor; +import java.util.concurrent.TimeUnit; + +/** + * @author a203 + */ +public class TimeGuardNtp extends JFrame { + private JPanel ntpPanel; + private JLabel timeValueLabel; + private JButton updateTimeButton; + private JLabel currentTimeLabel; + private JCheckBox autoCheckBox; + private JComboBox periodComboBox; + private JLabel stateView; + private JPanel dotPanel; + private JTextField hostTextField; + private JComboBox localHostBox; + private JTextField serverTextField; + + private final ScheduledExecutorService executorService = new ScheduledThreadPoolExecutor( + 1, new ThreadFactoryBuilder().setNameFormat("demo-pool-%d").build()); + private boolean hasNtp = false; + + public static void main(String[] args) { + new TimeGuardNtp(); + } + + public TimeGuardNtp() { + setContentPane(ntpPanel); + setResizable(false); + setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); + pack(); + setSize(400, 330); + //居中 + setLocationRelativeTo(null); + setVisible(true); + stateView.setText("未同步"); + setStateView(Color.GRAY); + + StringHelper.createLogFile(); + + /** + * 时间间隔,单位为毫秒 + * */ + currentTimeLabel.setForeground(Color.BLUE); + new Timer(1000, new ActionListener() { + @Override + public void actionPerformed(ActionEvent e) { + String systemTime = TimeOrDateUtil.timestampToTime(System.currentTimeMillis()); + currentTimeLabel.setText(systemTime); + } + }).start(); + + String assertsData = StringHelper.getAssertsData(); + if (!"".equals(assertsData)) { + timeValueLabel.setText(assertsData); + } else { + timeValueLabel.setText("无法确定最近同步时间"); + } + + //初始化JComboBox + for (Integer integer : Constant.PERIOD) { + periodComboBox.addItem(integer); + } + java.util.List addressList = HttpRequestHelper.localHost(); + for (InetAddress address : addressList) { + localHostBox.addItem(address.getHostAddress()); + } + + //检查环境 +// new SwingWorker() { +// +// @Override +// protected Boolean doInBackground() { +// hasNtp = CommandUtil.checkEnv(); +// return hasNtp; +// } +// +// @Override +// protected void done() { +// if (!hasNtp) { +// JOptionPane.showMessageDialog(ntpPanel, "未当前设备发现可用的NTP配置", "Runtime Error", JOptionPane.ERROR_MESSAGE); +// //环境不对,关闭窗体 +// dispose(); +// } +// super.done(); +// } +// }.execute(); + + autoCheckBox.addActionListener(new ActionListener() { + @Override + public void actionPerformed(ActionEvent e) { + JCheckBox checkBox = (JCheckBox) e.getSource(); + if (checkBox.isSelected()) { + updateTimeButton.setEnabled(false); + periodComboBox.setEnabled(true); + hostTextField.setEnabled(false); + serverTextField.setEnabled(false); + startAutoSynchronize(Constant.PERIOD[0]); + } else { + updateTimeButton.setEnabled(true); + periodComboBox.setEnabled(false); + hostTextField.setEnabled(true); + serverTextField.setEnabled(true); + } + } + }); + + periodComboBox.addItemListener(new ItemListener() { + @Override + public void itemStateChanged(ItemEvent e) { + int period = (Integer) e.getItem(); + if (e.getStateChange() == ItemEvent.SELECTED) { + startAutoSynchronize(period); + } + } + }); + + //按钮点击事件 + updateTimeButton.addActionListener(new ActionListener() { + @Override + public void actionPerformed(ActionEvent e) { + updateView(); + } + }); + } + + private void startAutoSynchronize(int period) { + /** + * 开启同步,只能开启一个同步线程 + * + * scheduleAtFixedRate + * 是以上一个任务开始的时间计时,period时间过去后,检测上一个任务是否执行完毕 + * 如果上一个任务执行完毕,则当前任务立即执行 + * 如果上一个任务没有执行完毕,则需要等上一个任务执行完毕后立即执行 + * */ + executorService.scheduleAtFixedRate(new Runnable() { + @Override + public void run() { + updateView(); + } + }, 0, period, TimeUnit.MINUTES); + } + + private void updateView() { + String host = hostTextField.getText().trim(); + if (host.isEmpty()) { + autoCheckBox.setSelected(false); + JOptionPane.showMessageDialog(ntpPanel, "授时中心服务器输入错误,请检查", "Runtime Error", JOptionPane.ERROR_MESSAGE); + return; + } + String server = serverTextField.getText().trim(); + if (server.isEmpty()) { + autoCheckBox.setSelected(false); + JOptionPane.showMessageDialog(ntpPanel, "后台服务器地址输入错误,请检查", "Runtime Error", JOptionPane.ERROR_MESSAGE); + return; + } +// String result = "5 Jan 11:20:24 ntpdate[807910]: adjust time server 114.118.7.161 offset -0.004064 sec"; +// String result = "5 Jan 11:24:06 ntpdate[824403]: no server suitable for synchronization found"; + String result = CommandUtil.ntpDate(host); + System.out.println("命令执行结果 ===> " + result); + + if ("".equals(result)) { + setStateView(Color.RED); + stateView.setText("同步失败"); + timeValueLabel.setText(""); + } else { + String systemTime = TimeOrDateUtil.timestampToTime(System.currentTimeMillis()); + + String resultString = result.split(":")[3]; + boolean isSuccess = !resultString.contains("no server suitable"); + if (isSuccess) { + setStateView(Color.GREEN); + stateView.setText("同步成功"); + timeValueLabel.setText(systemTime); + //同步成功之后将时间存入本地 + StringHelper.saveAssertsData(systemTime); + } else { + setStateView(Color.RED); + stateView.setText("同步失败"); + timeValueLabel.setText(""); + } + //POST提交 + JSONObject object = new JSONObject(); + try { + object.put("deviceIp", localHostBox.getSelectedItem()); + object.put("ntpResult", result); + + String[] dataSplit = resultString.split(" "); + object.put("deltaTime", dataSplit[6]); + object.put("createTime", systemTime); + if (autoCheckBox.isSelected()) { + object.put("frequency", periodComboBox.getSelectedItem()); + } else { + object.put("frequency", ""); + } + } catch (JSONException e) { + e.printStackTrace(); + } + Request request = new Request.Builder() + .url("http://" + server + "/ntp/saveResult") + .post(HttpRequestHelper.createRequestBody(object.toJSONString())) + .build(); + HttpRequestHelper.doPost(request, new IHttpCallback() { + + @Override + public void onSuccess(String s) { + + } + + @Override + public void onFailure(Exception e) { + e.printStackTrace(); + } + }); + } + } + + private void setStateView(Color color) { + dotPanel.setPreferredSize(new Dimension(15, 15)); + dotPanel.setBackground(color); + } +} diff --git a/.gitignore b/.gitignore index 0841741..5027de1 100644 --- a/.gitignore +++ b/.gitignore @@ -1,2 +1,4 @@ .idea /out +/logs +/target diff --git a/CasicTimeGuard.iml b/CasicTimeGuard.iml index f54a89f..40532bb 100644 --- a/CasicTimeGuard.iml +++ b/CasicTimeGuard.iml @@ -1,12 +1,29 @@ - - - + + + + - + + + + - + + + + + + + + + + + + + + \ No newline at end of file diff --git a/lib/guava-18.0.jar b/lib/guava-18.0.jar deleted file mode 100644 index 8f89e49..0000000 --- a/lib/guava-18.0.jar +++ /dev/null Binary files differ diff --git a/pom.xml b/pom.xml new file mode 100644 index 0000000..3be19b5 --- /dev/null +++ b/pom.xml @@ -0,0 +1,44 @@ + + + 4.0.0 + + com.casic + CasicTimeGuard + 1.0-SNAPSHOT + + + 8 + 8 + 1.8 + + + + + org.projectlombok + lombok + 1.18.22 + true + + + + com.alibaba + fastjson + 1.2.79 + + + + + com.google.guava + guava + 31.0.1-jre + + + + com.squareup.okhttp3 + okhttp + 4.9.3 + + + \ No newline at end of file diff --git a/src/com/casic/swing/ui/TimeGuardNtp.form b/src/com/casic/swing/ui/TimeGuardNtp.form deleted file mode 100644 index cdba6f6..0000000 --- a/src/com/casic/swing/ui/TimeGuardNtp.form +++ /dev/null @@ -1,171 +0,0 @@ - -
- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - diff --git a/src/com/casic/swing/ui/TimeGuardNtp.java b/src/com/casic/swing/ui/TimeGuardNtp.java deleted file mode 100644 index 6df5b55..0000000 --- a/src/com/casic/swing/ui/TimeGuardNtp.java +++ /dev/null @@ -1,207 +0,0 @@ -package com.casic.swing.ui; - -import com.casic.swing.utils.CommandUtil; -import com.casic.swing.utils.StringHelper; -import com.casic.swing.utils.TimeOrDateUtil; -import com.google.common.util.concurrent.ThreadFactoryBuilder; - -import javax.swing.*; -import java.awt.*; -import java.awt.event.ActionEvent; -import java.awt.event.ActionListener; -import java.awt.event.ItemEvent; -import java.awt.event.ItemListener; -import java.util.concurrent.ScheduledExecutorService; -import java.util.concurrent.ScheduledThreadPoolExecutor; -import java.util.concurrent.TimeUnit; - -/** - * @author a203 - */ -public class TimeGuardNtp extends JFrame { - private JPanel ntpPanel; - private JComboBox hostComboBox; - private JLabel timeValueLabel; - private JButton updateTimeButton; - private JLabel dotView; - private JLabel currentTimeLabel; - private JCheckBox autoCheckBox; - private JComboBox periodComboBox; - private JPanel stateView; - - private final String[] HOST_NAME = {"NTP服务器(上海)", "中国国家授时中心", "清华大学", "北京大学", "自定义"}; - private final String[] HOST_IP = {"ntp.api.bz", "ntp.ntsc.ac.cn", "s1b.time.edu.cn", "s2m.time.edu.cn"}; - /** - * 同步周期,单位:小时 - */ - private final Integer[] PERIOD = {10, 20, 30}; - private final ScheduledExecutorService executorService = new ScheduledThreadPoolExecutor( - 1, new ThreadFactoryBuilder().setNameFormat("demo-pool-%d").build()); - private boolean hasNtp = false; - private String host = HOST_IP[0]; - - public static void main(String[] args) { - new TimeGuardNtp(); - } - - public TimeGuardNtp() { - setContentPane(ntpPanel); - setResizable(false); - setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); - pack(); - setSize(410, 280); - //居中 - setLocationRelativeTo(null); - setVisible(true); - dotView.setText("未同步"); - setStateView(Color.GRAY); - - StringHelper.createLogFile(); - - /** - * 时间间隔,单位为毫秒 - * */ - currentTimeLabel.setForeground(Color.BLUE); - new Timer(1000, new ActionListener() { - @Override - public void actionPerformed(ActionEvent e) { - String systemTime = TimeOrDateUtil.timestampToTime(System.currentTimeMillis()); - currentTimeLabel.setText(systemTime); - } - }).start(); - - String assertsData = StringHelper.getAssertsData(); - if (!"".equals(assertsData)) { - timeValueLabel.setText(assertsData); - } else { - timeValueLabel.setText("无法确定最近同步时间"); - } - - //初始化JComboBox - initComBox(); - hostComboBox.addItemListener(new ItemListener() { - @Override - public void itemStateChanged(ItemEvent e) { - String item = (String) e.getItem(); - if (e.getStateChange() == ItemEvent.SELECTED) { - if ("自定义".equals(item)) { - String inputContent = JOptionPane.showInputDialog(ntpPanel, "请输入授时中心域名或者IP地址", "", JOptionPane.INFORMATION_MESSAGE); - if (inputContent.isEmpty()) { - JOptionPane.showMessageDialog(ntpPanel, "输入错误,请检查", "Runtime Error", JOptionPane.ERROR_MESSAGE); - } else { - host = inputContent; - } - } else { - for (int i = 0; i < HOST_NAME.length; i++) { - if (item.equals(HOST_NAME[i])) { - host = HOST_IP[i]; - } - } - } - } - } - }); - - //检查环境 - new SwingWorker() { - - @Override - protected Boolean doInBackground() { - hasNtp = CommandUtil.checkEnv(); - return hasNtp; - } - - @Override - protected void done() { - if (!hasNtp) { - JOptionPane.showMessageDialog(ntpPanel, "未当前设备发现可用的NTP配置", "Runtime Error", JOptionPane.ERROR_MESSAGE); - //环境不对,关闭窗体 - dispose(); - } - super.done(); - } - }.execute(); - - autoCheckBox.addActionListener(new ActionListener() { - @Override - public void actionPerformed(ActionEvent e) { - JCheckBox checkBox = (JCheckBox) e.getSource(); - if (checkBox.isSelected()) { - updateTimeButton.setEnabled(false); - periodComboBox.setEnabled(true); - startAutoSynchronize(PERIOD[0]); - } else { - updateTimeButton.setEnabled(true); - periodComboBox.setEnabled(false); - } - } - }); - - periodComboBox.addItemListener(new ItemListener() { - @Override - public void itemStateChanged(ItemEvent e) { - int period = (Integer) e.getItem(); - if (e.getStateChange() == ItemEvent.SELECTED) { - startAutoSynchronize(period); - } - } - }); - - //按钮点击事件 - updateTimeButton.addActionListener(new ActionListener() { - @Override - public void actionPerformed(ActionEvent e) { - updateView(); - } - }); - } - - private void startAutoSynchronize(int period) { - /** - * 开启同步,只能开启一个同步线程 - * - * scheduleAtFixedRate - * 是以上一个任务开始的时间计时,period时间过去后,检测上一个任务是否执行完毕 - * 如果上一个任务执行完毕,则当前任务立即执行 - * 如果上一个任务没有执行完毕,则需要等上一个任务执行完毕后立即执行 - * */ - executorService.scheduleAtFixedRate(new Runnable() { - @Override - public void run() { - updateView(); - } - }, 0, period, TimeUnit.MINUTES); - } - - private void updateView() { - String result = CommandUtil.ntpDate(host); - System.out.println("命令执行结果 ===> " + result); - boolean isSuccess = result.contains("step time server") || result.contains("adjust time server"); - if (isSuccess) { - String systemTime = TimeOrDateUtil.timestampToTime(System.currentTimeMillis()); - setStateView(Color.GREEN); - dotView.setText("同步成功"); - timeValueLabel.setText(systemTime); - //同步成功之后将时间存入本地 - StringHelper.saveAssertsData(systemTime); - } else { - setStateView(Color.RED); - dotView.setText("同步失败"); - timeValueLabel.setText(""); - } - } - - private void initComBox() { - for (String s : HOST_NAME) { - hostComboBox.addItem(s); - } - for (Integer integer : PERIOD) { - periodComboBox.addItem(integer); - } - } - - private void setStateView(Color color) { - stateView.setPreferredSize(new Dimension(15, 15)); - stateView.setBackground(color); - } -} diff --git a/src/com/casic/swing/utils/CommandUtil.java b/src/com/casic/swing/utils/CommandUtil.java deleted file mode 100644 index c487e7d..0000000 --- a/src/com/casic/swing/utils/CommandUtil.java +++ /dev/null @@ -1,76 +0,0 @@ -package com.casic.swing.utils; - -import java.io.BufferedReader; -import java.io.IOException; -import java.io.InputStream; -import java.io.InputStreamReader; -import java.nio.charset.Charset; -import java.util.concurrent.TimeUnit; - -/** - * @author a203 - */ -public class CommandUtil { - /** - * 检查当前系统是否已安装NTP - */ - public static boolean checkEnv() { - System.out.println("检查当前系统是否支持NTP"); - try { - Process exec = Runtime.getRuntime().exec("rpm -q ntp"); - try { - //等待命令执行完成 - exec.waitFor(5, TimeUnit.SECONDS); - } catch (InterruptedException e) { - e.printStackTrace(); - } - String result = parseResult(exec.getInputStream()); - return !result.isEmpty(); - } catch (IOException e) { - e.printStackTrace(); - } - return false; - } - - /** - * 安装NTP - * yum -y install ntp - * */ - - /** - * 授时同步 - * ntpdate -u ntp.api.bz - */ - public static String ntpDate(String host) { - try { - String command = "ntpdate -u " + host; - System.out.println("授时同步 ===> " + command); - Process exec = Runtime.getRuntime().exec(command); - try { - //等待命令执行完成 - exec.waitFor(5, TimeUnit.SECONDS); - } catch (InterruptedException e) { - e.printStackTrace(); - } - return parseResult(exec.getInputStream()); - } catch (IOException e) { - e.printStackTrace(); - } - return ""; - } - - /** - * 解析命令结果 - */ - private static String parseResult(InputStream inputStream) throws IOException { - // 读取输出流内容 - InputStreamReader streamReader = new InputStreamReader(inputStream, Charset.defaultCharset()); - BufferedReader reader = new BufferedReader(streamReader); - StringBuilder builder = new StringBuilder(); - String line; - while ((line = reader.readLine()) != null) { - builder.append(line).append("\n"); - } - return builder.toString(); - } -} diff --git a/src/com/casic/swing/utils/StringHelper.java b/src/com/casic/swing/utils/StringHelper.java deleted file mode 100644 index b994e19..0000000 --- a/src/com/casic/swing/utils/StringHelper.java +++ /dev/null @@ -1,64 +0,0 @@ -package com.casic.swing.utils; - -import javax.swing.filechooser.FileSystemView; -import java.io.*; - -/** - * @author a203 - */ -public class StringHelper { - - private static final String FILE_NAME = "update.log"; - private static File logFile; - - public static void createLogFile() { - FileSystemView view = FileSystemView.getFileSystemView(); - File file = view.getHomeDirectory(); - File dir = new File(file.getAbsolutePath() + File.separator + "logs"); - if (!dir.exists()) { - dir.mkdir(); - } - logFile = new File(dir + File.separator + FILE_NAME); - if (!logFile.exists()) { - // 创建新文件,有同名的文件的话直接覆盖 - try { - logFile.createNewFile(); - } catch (IOException e) { - e.printStackTrace(); - } - } - System.out.println("同步记录路径 ===> " + logFile.getAbsolutePath()); - } - - public static void saveAssertsData(String data) { - try { - FileWriter writer = new FileWriter(logFile); - BufferedWriter out = new BufferedWriter(writer); - out.write(data); - out.flush(); - out.close(); - } catch (IOException e) { - e.printStackTrace(); - } - } - - public static String getAssertsData() { - try { - InputStreamReader inputStreamReader = new InputStreamReader(new FileInputStream(logFile)); - BufferedReader bufferedReader = new BufferedReader(inputStreamReader); - StringBuilder data = new StringBuilder(); - String s; - try { - while ((s = bufferedReader.readLine()) != null) { - data.append(s); - } - return data.toString(); - } catch (IOException e) { - e.printStackTrace(); - } - } catch (IOException e) { - e.printStackTrace(); - } - return ""; - } -} diff --git a/src/com/casic/swing/utils/TimeOrDateUtil.java b/src/com/casic/swing/utils/TimeOrDateUtil.java deleted file mode 100644 index 7adc5a6..0000000 --- a/src/com/casic/swing/utils/TimeOrDateUtil.java +++ /dev/null @@ -1,18 +0,0 @@ -package com.casic.swing.utils; - -import java.text.SimpleDateFormat; -import java.util.Date; - -/** - * @author a203 - */ -public class TimeOrDateUtil { - - /** - * 时间戳转时间 - */ - public static String timestampToTime(long millSeconds) { - SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); - return format.format(new Date(millSeconds)); - } -} diff --git a/src/main/java/com/casic/swing/ui/TimeGuardNtp.form b/src/main/java/com/casic/swing/ui/TimeGuardNtp.form new file mode 100644 index 0000000..8732b4b --- /dev/null +++ b/src/main/java/com/casic/swing/ui/TimeGuardNtp.form @@ -0,0 +1,207 @@ + +
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/src/main/java/com/casic/swing/ui/TimeGuardNtp.java b/src/main/java/com/casic/swing/ui/TimeGuardNtp.java new file mode 100644 index 0000000..9c7fef7 --- /dev/null +++ b/src/main/java/com/casic/swing/ui/TimeGuardNtp.java @@ -0,0 +1,239 @@ +package com.casic.swing.ui; + +import com.alibaba.fastjson.JSONException; +import com.alibaba.fastjson.JSONObject; +import com.casic.swing.utils.*; +import com.google.common.util.concurrent.ThreadFactoryBuilder; +import okhttp3.Request; + +import javax.swing.*; +import java.awt.*; +import java.awt.event.ActionEvent; +import java.awt.event.ActionListener; +import java.awt.event.ItemEvent; +import java.awt.event.ItemListener; +import java.net.InetAddress; +import java.util.concurrent.ScheduledExecutorService; +import java.util.concurrent.ScheduledThreadPoolExecutor; +import java.util.concurrent.TimeUnit; + +/** + * @author a203 + */ +public class TimeGuardNtp extends JFrame { + private JPanel ntpPanel; + private JLabel timeValueLabel; + private JButton updateTimeButton; + private JLabel currentTimeLabel; + private JCheckBox autoCheckBox; + private JComboBox periodComboBox; + private JLabel stateView; + private JPanel dotPanel; + private JTextField hostTextField; + private JComboBox localHostBox; + private JTextField serverTextField; + + private final ScheduledExecutorService executorService = new ScheduledThreadPoolExecutor( + 1, new ThreadFactoryBuilder().setNameFormat("demo-pool-%d").build()); + private boolean hasNtp = false; + + public static void main(String[] args) { + new TimeGuardNtp(); + } + + public TimeGuardNtp() { + setContentPane(ntpPanel); + setResizable(false); + setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); + pack(); + setSize(400, 330); + //居中 + setLocationRelativeTo(null); + setVisible(true); + stateView.setText("未同步"); + setStateView(Color.GRAY); + + StringHelper.createLogFile(); + + /** + * 时间间隔,单位为毫秒 + * */ + currentTimeLabel.setForeground(Color.BLUE); + new Timer(1000, new ActionListener() { + @Override + public void actionPerformed(ActionEvent e) { + String systemTime = TimeOrDateUtil.timestampToTime(System.currentTimeMillis()); + currentTimeLabel.setText(systemTime); + } + }).start(); + + String assertsData = StringHelper.getAssertsData(); + if (!"".equals(assertsData)) { + timeValueLabel.setText(assertsData); + } else { + timeValueLabel.setText("无法确定最近同步时间"); + } + + //初始化JComboBox + for (Integer integer : Constant.PERIOD) { + periodComboBox.addItem(integer); + } + java.util.List addressList = HttpRequestHelper.localHost(); + for (InetAddress address : addressList) { + localHostBox.addItem(address.getHostAddress()); + } + + //检查环境 +// new SwingWorker() { +// +// @Override +// protected Boolean doInBackground() { +// hasNtp = CommandUtil.checkEnv(); +// return hasNtp; +// } +// +// @Override +// protected void done() { +// if (!hasNtp) { +// JOptionPane.showMessageDialog(ntpPanel, "未当前设备发现可用的NTP配置", "Runtime Error", JOptionPane.ERROR_MESSAGE); +// //环境不对,关闭窗体 +// dispose(); +// } +// super.done(); +// } +// }.execute(); + + autoCheckBox.addActionListener(new ActionListener() { + @Override + public void actionPerformed(ActionEvent e) { + JCheckBox checkBox = (JCheckBox) e.getSource(); + if (checkBox.isSelected()) { + updateTimeButton.setEnabled(false); + periodComboBox.setEnabled(true); + hostTextField.setEnabled(false); + serverTextField.setEnabled(false); + startAutoSynchronize(Constant.PERIOD[0]); + } else { + updateTimeButton.setEnabled(true); + periodComboBox.setEnabled(false); + hostTextField.setEnabled(true); + serverTextField.setEnabled(true); + } + } + }); + + periodComboBox.addItemListener(new ItemListener() { + @Override + public void itemStateChanged(ItemEvent e) { + int period = (Integer) e.getItem(); + if (e.getStateChange() == ItemEvent.SELECTED) { + startAutoSynchronize(period); + } + } + }); + + //按钮点击事件 + updateTimeButton.addActionListener(new ActionListener() { + @Override + public void actionPerformed(ActionEvent e) { + updateView(); + } + }); + } + + private void startAutoSynchronize(int period) { + /** + * 开启同步,只能开启一个同步线程 + * + * scheduleAtFixedRate + * 是以上一个任务开始的时间计时,period时间过去后,检测上一个任务是否执行完毕 + * 如果上一个任务执行完毕,则当前任务立即执行 + * 如果上一个任务没有执行完毕,则需要等上一个任务执行完毕后立即执行 + * */ + executorService.scheduleAtFixedRate(new Runnable() { + @Override + public void run() { + updateView(); + } + }, 0, period, TimeUnit.MINUTES); + } + + private void updateView() { + String host = hostTextField.getText().trim(); + if (host.isEmpty()) { + autoCheckBox.setSelected(false); + JOptionPane.showMessageDialog(ntpPanel, "授时中心服务器输入错误,请检查", "Runtime Error", JOptionPane.ERROR_MESSAGE); + return; + } + String server = serverTextField.getText().trim(); + if (server.isEmpty()) { + autoCheckBox.setSelected(false); + JOptionPane.showMessageDialog(ntpPanel, "后台服务器地址输入错误,请检查", "Runtime Error", JOptionPane.ERROR_MESSAGE); + return; + } +// String result = "5 Jan 11:20:24 ntpdate[807910]: adjust time server 114.118.7.161 offset -0.004064 sec"; +// String result = "5 Jan 11:24:06 ntpdate[824403]: no server suitable for synchronization found"; + String result = CommandUtil.ntpDate(host); + System.out.println("命令执行结果 ===> " + result); + + if ("".equals(result)) { + setStateView(Color.RED); + stateView.setText("同步失败"); + timeValueLabel.setText(""); + } else { + String systemTime = TimeOrDateUtil.timestampToTime(System.currentTimeMillis()); + + String resultString = result.split(":")[3]; + boolean isSuccess = !resultString.contains("no server suitable"); + if (isSuccess) { + setStateView(Color.GREEN); + stateView.setText("同步成功"); + timeValueLabel.setText(systemTime); + //同步成功之后将时间存入本地 + StringHelper.saveAssertsData(systemTime); + } else { + setStateView(Color.RED); + stateView.setText("同步失败"); + timeValueLabel.setText(""); + } + //POST提交 + JSONObject object = new JSONObject(); + try { + object.put("deviceIp", localHostBox.getSelectedItem()); + object.put("ntpResult", result); + + String[] dataSplit = resultString.split(" "); + object.put("deltaTime", dataSplit[6]); + object.put("createTime", systemTime); + if (autoCheckBox.isSelected()) { + object.put("frequency", periodComboBox.getSelectedItem()); + } else { + object.put("frequency", ""); + } + } catch (JSONException e) { + e.printStackTrace(); + } + Request request = new Request.Builder() + .url("http://" + server + "/ntp/saveResult") + .post(HttpRequestHelper.createRequestBody(object.toJSONString())) + .build(); + HttpRequestHelper.doPost(request, new IHttpCallback() { + + @Override + public void onSuccess(String s) { + + } + + @Override + public void onFailure(Exception e) { + e.printStackTrace(); + } + }); + } + } + + private void setStateView(Color color) { + dotPanel.setPreferredSize(new Dimension(15, 15)); + dotPanel.setBackground(color); + } +} diff --git a/src/main/java/com/casic/swing/utils/CommandUtil.java b/src/main/java/com/casic/swing/utils/CommandUtil.java new file mode 100644 index 0000000..2515971 --- /dev/null +++ b/src/main/java/com/casic/swing/utils/CommandUtil.java @@ -0,0 +1,77 @@ +package com.casic.swing.utils; + +import java.io.BufferedReader; +import java.io.IOException; +import java.io.InputStream; +import java.io.InputStreamReader; +import java.nio.charset.Charset; +import java.util.concurrent.TimeUnit; + +/** + * @author a203 + */ +public class CommandUtil { + /** + * 检查当前系统是否已安装NTP + */ + public static boolean checkEnv() { + System.out.println("检查当前系统是否支持NTP"); + try { +// Process exec = Runtime.getRuntime().exec("ls"); + Process exec = Runtime.getRuntime().exec("rpm -q ntp"); + try { + //等待命令执行完成 + exec.waitFor(5, TimeUnit.SECONDS); + } catch (InterruptedException e) { + e.printStackTrace(); + } + String result = parseResult(exec.getInputStream()); + return !result.isEmpty(); + } catch (IOException e) { + e.printStackTrace(); + } + return false; + } + + /** + * 安装NTP + * yum -y install ntp + * */ + + /** + * 授时同步 + * ntpdate -u ntp.api.bz + */ + public static String ntpDate(String host) { + try { + String command = "ntpdate -u " + host; + System.out.println("授时同步 ===> " + command); + Process exec = Runtime.getRuntime().exec(command); + try { + //等待命令执行完成 + exec.waitFor(5, TimeUnit.SECONDS); + } catch (InterruptedException e) { + e.printStackTrace(); + } + return parseResult(exec.getInputStream()); + } catch (IOException e) { + e.printStackTrace(); + } + return ""; + } + + /** + * 解析命令结果 + */ + private static String parseResult(InputStream inputStream) throws IOException { + // 读取输出流内容 + InputStreamReader streamReader = new InputStreamReader(inputStream, Charset.defaultCharset()); + BufferedReader reader = new BufferedReader(streamReader); + StringBuilder builder = new StringBuilder(); + String line; + while ((line = reader.readLine()) != null) { + builder.append(line).append("\n"); + } + return builder.toString(); + } +} diff --git a/.gitignore b/.gitignore index 0841741..5027de1 100644 --- a/.gitignore +++ b/.gitignore @@ -1,2 +1,4 @@ .idea /out +/logs +/target diff --git a/CasicTimeGuard.iml b/CasicTimeGuard.iml index f54a89f..40532bb 100644 --- a/CasicTimeGuard.iml +++ b/CasicTimeGuard.iml @@ -1,12 +1,29 @@ - - - + + + + - + + + + - + + + + + + + + + + + + + + \ No newline at end of file diff --git a/lib/guava-18.0.jar b/lib/guava-18.0.jar deleted file mode 100644 index 8f89e49..0000000 --- a/lib/guava-18.0.jar +++ /dev/null Binary files differ diff --git a/pom.xml b/pom.xml new file mode 100644 index 0000000..3be19b5 --- /dev/null +++ b/pom.xml @@ -0,0 +1,44 @@ + + + 4.0.0 + + com.casic + CasicTimeGuard + 1.0-SNAPSHOT + + + 8 + 8 + 1.8 + + + + + org.projectlombok + lombok + 1.18.22 + true + + + + com.alibaba + fastjson + 1.2.79 + + + + + com.google.guava + guava + 31.0.1-jre + + + + com.squareup.okhttp3 + okhttp + 4.9.3 + + + \ No newline at end of file diff --git a/src/com/casic/swing/ui/TimeGuardNtp.form b/src/com/casic/swing/ui/TimeGuardNtp.form deleted file mode 100644 index cdba6f6..0000000 --- a/src/com/casic/swing/ui/TimeGuardNtp.form +++ /dev/null @@ -1,171 +0,0 @@ - -
- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - diff --git a/src/com/casic/swing/ui/TimeGuardNtp.java b/src/com/casic/swing/ui/TimeGuardNtp.java deleted file mode 100644 index 6df5b55..0000000 --- a/src/com/casic/swing/ui/TimeGuardNtp.java +++ /dev/null @@ -1,207 +0,0 @@ -package com.casic.swing.ui; - -import com.casic.swing.utils.CommandUtil; -import com.casic.swing.utils.StringHelper; -import com.casic.swing.utils.TimeOrDateUtil; -import com.google.common.util.concurrent.ThreadFactoryBuilder; - -import javax.swing.*; -import java.awt.*; -import java.awt.event.ActionEvent; -import java.awt.event.ActionListener; -import java.awt.event.ItemEvent; -import java.awt.event.ItemListener; -import java.util.concurrent.ScheduledExecutorService; -import java.util.concurrent.ScheduledThreadPoolExecutor; -import java.util.concurrent.TimeUnit; - -/** - * @author a203 - */ -public class TimeGuardNtp extends JFrame { - private JPanel ntpPanel; - private JComboBox hostComboBox; - private JLabel timeValueLabel; - private JButton updateTimeButton; - private JLabel dotView; - private JLabel currentTimeLabel; - private JCheckBox autoCheckBox; - private JComboBox periodComboBox; - private JPanel stateView; - - private final String[] HOST_NAME = {"NTP服务器(上海)", "中国国家授时中心", "清华大学", "北京大学", "自定义"}; - private final String[] HOST_IP = {"ntp.api.bz", "ntp.ntsc.ac.cn", "s1b.time.edu.cn", "s2m.time.edu.cn"}; - /** - * 同步周期,单位:小时 - */ - private final Integer[] PERIOD = {10, 20, 30}; - private final ScheduledExecutorService executorService = new ScheduledThreadPoolExecutor( - 1, new ThreadFactoryBuilder().setNameFormat("demo-pool-%d").build()); - private boolean hasNtp = false; - private String host = HOST_IP[0]; - - public static void main(String[] args) { - new TimeGuardNtp(); - } - - public TimeGuardNtp() { - setContentPane(ntpPanel); - setResizable(false); - setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); - pack(); - setSize(410, 280); - //居中 - setLocationRelativeTo(null); - setVisible(true); - dotView.setText("未同步"); - setStateView(Color.GRAY); - - StringHelper.createLogFile(); - - /** - * 时间间隔,单位为毫秒 - * */ - currentTimeLabel.setForeground(Color.BLUE); - new Timer(1000, new ActionListener() { - @Override - public void actionPerformed(ActionEvent e) { - String systemTime = TimeOrDateUtil.timestampToTime(System.currentTimeMillis()); - currentTimeLabel.setText(systemTime); - } - }).start(); - - String assertsData = StringHelper.getAssertsData(); - if (!"".equals(assertsData)) { - timeValueLabel.setText(assertsData); - } else { - timeValueLabel.setText("无法确定最近同步时间"); - } - - //初始化JComboBox - initComBox(); - hostComboBox.addItemListener(new ItemListener() { - @Override - public void itemStateChanged(ItemEvent e) { - String item = (String) e.getItem(); - if (e.getStateChange() == ItemEvent.SELECTED) { - if ("自定义".equals(item)) { - String inputContent = JOptionPane.showInputDialog(ntpPanel, "请输入授时中心域名或者IP地址", "", JOptionPane.INFORMATION_MESSAGE); - if (inputContent.isEmpty()) { - JOptionPane.showMessageDialog(ntpPanel, "输入错误,请检查", "Runtime Error", JOptionPane.ERROR_MESSAGE); - } else { - host = inputContent; - } - } else { - for (int i = 0; i < HOST_NAME.length; i++) { - if (item.equals(HOST_NAME[i])) { - host = HOST_IP[i]; - } - } - } - } - } - }); - - //检查环境 - new SwingWorker() { - - @Override - protected Boolean doInBackground() { - hasNtp = CommandUtil.checkEnv(); - return hasNtp; - } - - @Override - protected void done() { - if (!hasNtp) { - JOptionPane.showMessageDialog(ntpPanel, "未当前设备发现可用的NTP配置", "Runtime Error", JOptionPane.ERROR_MESSAGE); - //环境不对,关闭窗体 - dispose(); - } - super.done(); - } - }.execute(); - - autoCheckBox.addActionListener(new ActionListener() { - @Override - public void actionPerformed(ActionEvent e) { - JCheckBox checkBox = (JCheckBox) e.getSource(); - if (checkBox.isSelected()) { - updateTimeButton.setEnabled(false); - periodComboBox.setEnabled(true); - startAutoSynchronize(PERIOD[0]); - } else { - updateTimeButton.setEnabled(true); - periodComboBox.setEnabled(false); - } - } - }); - - periodComboBox.addItemListener(new ItemListener() { - @Override - public void itemStateChanged(ItemEvent e) { - int period = (Integer) e.getItem(); - if (e.getStateChange() == ItemEvent.SELECTED) { - startAutoSynchronize(period); - } - } - }); - - //按钮点击事件 - updateTimeButton.addActionListener(new ActionListener() { - @Override - public void actionPerformed(ActionEvent e) { - updateView(); - } - }); - } - - private void startAutoSynchronize(int period) { - /** - * 开启同步,只能开启一个同步线程 - * - * scheduleAtFixedRate - * 是以上一个任务开始的时间计时,period时间过去后,检测上一个任务是否执行完毕 - * 如果上一个任务执行完毕,则当前任务立即执行 - * 如果上一个任务没有执行完毕,则需要等上一个任务执行完毕后立即执行 - * */ - executorService.scheduleAtFixedRate(new Runnable() { - @Override - public void run() { - updateView(); - } - }, 0, period, TimeUnit.MINUTES); - } - - private void updateView() { - String result = CommandUtil.ntpDate(host); - System.out.println("命令执行结果 ===> " + result); - boolean isSuccess = result.contains("step time server") || result.contains("adjust time server"); - if (isSuccess) { - String systemTime = TimeOrDateUtil.timestampToTime(System.currentTimeMillis()); - setStateView(Color.GREEN); - dotView.setText("同步成功"); - timeValueLabel.setText(systemTime); - //同步成功之后将时间存入本地 - StringHelper.saveAssertsData(systemTime); - } else { - setStateView(Color.RED); - dotView.setText("同步失败"); - timeValueLabel.setText(""); - } - } - - private void initComBox() { - for (String s : HOST_NAME) { - hostComboBox.addItem(s); - } - for (Integer integer : PERIOD) { - periodComboBox.addItem(integer); - } - } - - private void setStateView(Color color) { - stateView.setPreferredSize(new Dimension(15, 15)); - stateView.setBackground(color); - } -} diff --git a/src/com/casic/swing/utils/CommandUtil.java b/src/com/casic/swing/utils/CommandUtil.java deleted file mode 100644 index c487e7d..0000000 --- a/src/com/casic/swing/utils/CommandUtil.java +++ /dev/null @@ -1,76 +0,0 @@ -package com.casic.swing.utils; - -import java.io.BufferedReader; -import java.io.IOException; -import java.io.InputStream; -import java.io.InputStreamReader; -import java.nio.charset.Charset; -import java.util.concurrent.TimeUnit; - -/** - * @author a203 - */ -public class CommandUtil { - /** - * 检查当前系统是否已安装NTP - */ - public static boolean checkEnv() { - System.out.println("检查当前系统是否支持NTP"); - try { - Process exec = Runtime.getRuntime().exec("rpm -q ntp"); - try { - //等待命令执行完成 - exec.waitFor(5, TimeUnit.SECONDS); - } catch (InterruptedException e) { - e.printStackTrace(); - } - String result = parseResult(exec.getInputStream()); - return !result.isEmpty(); - } catch (IOException e) { - e.printStackTrace(); - } - return false; - } - - /** - * 安装NTP - * yum -y install ntp - * */ - - /** - * 授时同步 - * ntpdate -u ntp.api.bz - */ - public static String ntpDate(String host) { - try { - String command = "ntpdate -u " + host; - System.out.println("授时同步 ===> " + command); - Process exec = Runtime.getRuntime().exec(command); - try { - //等待命令执行完成 - exec.waitFor(5, TimeUnit.SECONDS); - } catch (InterruptedException e) { - e.printStackTrace(); - } - return parseResult(exec.getInputStream()); - } catch (IOException e) { - e.printStackTrace(); - } - return ""; - } - - /** - * 解析命令结果 - */ - private static String parseResult(InputStream inputStream) throws IOException { - // 读取输出流内容 - InputStreamReader streamReader = new InputStreamReader(inputStream, Charset.defaultCharset()); - BufferedReader reader = new BufferedReader(streamReader); - StringBuilder builder = new StringBuilder(); - String line; - while ((line = reader.readLine()) != null) { - builder.append(line).append("\n"); - } - return builder.toString(); - } -} diff --git a/src/com/casic/swing/utils/StringHelper.java b/src/com/casic/swing/utils/StringHelper.java deleted file mode 100644 index b994e19..0000000 --- a/src/com/casic/swing/utils/StringHelper.java +++ /dev/null @@ -1,64 +0,0 @@ -package com.casic.swing.utils; - -import javax.swing.filechooser.FileSystemView; -import java.io.*; - -/** - * @author a203 - */ -public class StringHelper { - - private static final String FILE_NAME = "update.log"; - private static File logFile; - - public static void createLogFile() { - FileSystemView view = FileSystemView.getFileSystemView(); - File file = view.getHomeDirectory(); - File dir = new File(file.getAbsolutePath() + File.separator + "logs"); - if (!dir.exists()) { - dir.mkdir(); - } - logFile = new File(dir + File.separator + FILE_NAME); - if (!logFile.exists()) { - // 创建新文件,有同名的文件的话直接覆盖 - try { - logFile.createNewFile(); - } catch (IOException e) { - e.printStackTrace(); - } - } - System.out.println("同步记录路径 ===> " + logFile.getAbsolutePath()); - } - - public static void saveAssertsData(String data) { - try { - FileWriter writer = new FileWriter(logFile); - BufferedWriter out = new BufferedWriter(writer); - out.write(data); - out.flush(); - out.close(); - } catch (IOException e) { - e.printStackTrace(); - } - } - - public static String getAssertsData() { - try { - InputStreamReader inputStreamReader = new InputStreamReader(new FileInputStream(logFile)); - BufferedReader bufferedReader = new BufferedReader(inputStreamReader); - StringBuilder data = new StringBuilder(); - String s; - try { - while ((s = bufferedReader.readLine()) != null) { - data.append(s); - } - return data.toString(); - } catch (IOException e) { - e.printStackTrace(); - } - } catch (IOException e) { - e.printStackTrace(); - } - return ""; - } -} diff --git a/src/com/casic/swing/utils/TimeOrDateUtil.java b/src/com/casic/swing/utils/TimeOrDateUtil.java deleted file mode 100644 index 7adc5a6..0000000 --- a/src/com/casic/swing/utils/TimeOrDateUtil.java +++ /dev/null @@ -1,18 +0,0 @@ -package com.casic.swing.utils; - -import java.text.SimpleDateFormat; -import java.util.Date; - -/** - * @author a203 - */ -public class TimeOrDateUtil { - - /** - * 时间戳转时间 - */ - public static String timestampToTime(long millSeconds) { - SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); - return format.format(new Date(millSeconds)); - } -} diff --git a/src/main/java/com/casic/swing/ui/TimeGuardNtp.form b/src/main/java/com/casic/swing/ui/TimeGuardNtp.form new file mode 100644 index 0000000..8732b4b --- /dev/null +++ b/src/main/java/com/casic/swing/ui/TimeGuardNtp.form @@ -0,0 +1,207 @@ + +
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/src/main/java/com/casic/swing/ui/TimeGuardNtp.java b/src/main/java/com/casic/swing/ui/TimeGuardNtp.java new file mode 100644 index 0000000..9c7fef7 --- /dev/null +++ b/src/main/java/com/casic/swing/ui/TimeGuardNtp.java @@ -0,0 +1,239 @@ +package com.casic.swing.ui; + +import com.alibaba.fastjson.JSONException; +import com.alibaba.fastjson.JSONObject; +import com.casic.swing.utils.*; +import com.google.common.util.concurrent.ThreadFactoryBuilder; +import okhttp3.Request; + +import javax.swing.*; +import java.awt.*; +import java.awt.event.ActionEvent; +import java.awt.event.ActionListener; +import java.awt.event.ItemEvent; +import java.awt.event.ItemListener; +import java.net.InetAddress; +import java.util.concurrent.ScheduledExecutorService; +import java.util.concurrent.ScheduledThreadPoolExecutor; +import java.util.concurrent.TimeUnit; + +/** + * @author a203 + */ +public class TimeGuardNtp extends JFrame { + private JPanel ntpPanel; + private JLabel timeValueLabel; + private JButton updateTimeButton; + private JLabel currentTimeLabel; + private JCheckBox autoCheckBox; + private JComboBox periodComboBox; + private JLabel stateView; + private JPanel dotPanel; + private JTextField hostTextField; + private JComboBox localHostBox; + private JTextField serverTextField; + + private final ScheduledExecutorService executorService = new ScheduledThreadPoolExecutor( + 1, new ThreadFactoryBuilder().setNameFormat("demo-pool-%d").build()); + private boolean hasNtp = false; + + public static void main(String[] args) { + new TimeGuardNtp(); + } + + public TimeGuardNtp() { + setContentPane(ntpPanel); + setResizable(false); + setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); + pack(); + setSize(400, 330); + //居中 + setLocationRelativeTo(null); + setVisible(true); + stateView.setText("未同步"); + setStateView(Color.GRAY); + + StringHelper.createLogFile(); + + /** + * 时间间隔,单位为毫秒 + * */ + currentTimeLabel.setForeground(Color.BLUE); + new Timer(1000, new ActionListener() { + @Override + public void actionPerformed(ActionEvent e) { + String systemTime = TimeOrDateUtil.timestampToTime(System.currentTimeMillis()); + currentTimeLabel.setText(systemTime); + } + }).start(); + + String assertsData = StringHelper.getAssertsData(); + if (!"".equals(assertsData)) { + timeValueLabel.setText(assertsData); + } else { + timeValueLabel.setText("无法确定最近同步时间"); + } + + //初始化JComboBox + for (Integer integer : Constant.PERIOD) { + periodComboBox.addItem(integer); + } + java.util.List addressList = HttpRequestHelper.localHost(); + for (InetAddress address : addressList) { + localHostBox.addItem(address.getHostAddress()); + } + + //检查环境 +// new SwingWorker() { +// +// @Override +// protected Boolean doInBackground() { +// hasNtp = CommandUtil.checkEnv(); +// return hasNtp; +// } +// +// @Override +// protected void done() { +// if (!hasNtp) { +// JOptionPane.showMessageDialog(ntpPanel, "未当前设备发现可用的NTP配置", "Runtime Error", JOptionPane.ERROR_MESSAGE); +// //环境不对,关闭窗体 +// dispose(); +// } +// super.done(); +// } +// }.execute(); + + autoCheckBox.addActionListener(new ActionListener() { + @Override + public void actionPerformed(ActionEvent e) { + JCheckBox checkBox = (JCheckBox) e.getSource(); + if (checkBox.isSelected()) { + updateTimeButton.setEnabled(false); + periodComboBox.setEnabled(true); + hostTextField.setEnabled(false); + serverTextField.setEnabled(false); + startAutoSynchronize(Constant.PERIOD[0]); + } else { + updateTimeButton.setEnabled(true); + periodComboBox.setEnabled(false); + hostTextField.setEnabled(true); + serverTextField.setEnabled(true); + } + } + }); + + periodComboBox.addItemListener(new ItemListener() { + @Override + public void itemStateChanged(ItemEvent e) { + int period = (Integer) e.getItem(); + if (e.getStateChange() == ItemEvent.SELECTED) { + startAutoSynchronize(period); + } + } + }); + + //按钮点击事件 + updateTimeButton.addActionListener(new ActionListener() { + @Override + public void actionPerformed(ActionEvent e) { + updateView(); + } + }); + } + + private void startAutoSynchronize(int period) { + /** + * 开启同步,只能开启一个同步线程 + * + * scheduleAtFixedRate + * 是以上一个任务开始的时间计时,period时间过去后,检测上一个任务是否执行完毕 + * 如果上一个任务执行完毕,则当前任务立即执行 + * 如果上一个任务没有执行完毕,则需要等上一个任务执行完毕后立即执行 + * */ + executorService.scheduleAtFixedRate(new Runnable() { + @Override + public void run() { + updateView(); + } + }, 0, period, TimeUnit.MINUTES); + } + + private void updateView() { + String host = hostTextField.getText().trim(); + if (host.isEmpty()) { + autoCheckBox.setSelected(false); + JOptionPane.showMessageDialog(ntpPanel, "授时中心服务器输入错误,请检查", "Runtime Error", JOptionPane.ERROR_MESSAGE); + return; + } + String server = serverTextField.getText().trim(); + if (server.isEmpty()) { + autoCheckBox.setSelected(false); + JOptionPane.showMessageDialog(ntpPanel, "后台服务器地址输入错误,请检查", "Runtime Error", JOptionPane.ERROR_MESSAGE); + return; + } +// String result = "5 Jan 11:20:24 ntpdate[807910]: adjust time server 114.118.7.161 offset -0.004064 sec"; +// String result = "5 Jan 11:24:06 ntpdate[824403]: no server suitable for synchronization found"; + String result = CommandUtil.ntpDate(host); + System.out.println("命令执行结果 ===> " + result); + + if ("".equals(result)) { + setStateView(Color.RED); + stateView.setText("同步失败"); + timeValueLabel.setText(""); + } else { + String systemTime = TimeOrDateUtil.timestampToTime(System.currentTimeMillis()); + + String resultString = result.split(":")[3]; + boolean isSuccess = !resultString.contains("no server suitable"); + if (isSuccess) { + setStateView(Color.GREEN); + stateView.setText("同步成功"); + timeValueLabel.setText(systemTime); + //同步成功之后将时间存入本地 + StringHelper.saveAssertsData(systemTime); + } else { + setStateView(Color.RED); + stateView.setText("同步失败"); + timeValueLabel.setText(""); + } + //POST提交 + JSONObject object = new JSONObject(); + try { + object.put("deviceIp", localHostBox.getSelectedItem()); + object.put("ntpResult", result); + + String[] dataSplit = resultString.split(" "); + object.put("deltaTime", dataSplit[6]); + object.put("createTime", systemTime); + if (autoCheckBox.isSelected()) { + object.put("frequency", periodComboBox.getSelectedItem()); + } else { + object.put("frequency", ""); + } + } catch (JSONException e) { + e.printStackTrace(); + } + Request request = new Request.Builder() + .url("http://" + server + "/ntp/saveResult") + .post(HttpRequestHelper.createRequestBody(object.toJSONString())) + .build(); + HttpRequestHelper.doPost(request, new IHttpCallback() { + + @Override + public void onSuccess(String s) { + + } + + @Override + public void onFailure(Exception e) { + e.printStackTrace(); + } + }); + } + } + + private void setStateView(Color color) { + dotPanel.setPreferredSize(new Dimension(15, 15)); + dotPanel.setBackground(color); + } +} diff --git a/src/main/java/com/casic/swing/utils/CommandUtil.java b/src/main/java/com/casic/swing/utils/CommandUtil.java new file mode 100644 index 0000000..2515971 --- /dev/null +++ b/src/main/java/com/casic/swing/utils/CommandUtil.java @@ -0,0 +1,77 @@ +package com.casic.swing.utils; + +import java.io.BufferedReader; +import java.io.IOException; +import java.io.InputStream; +import java.io.InputStreamReader; +import java.nio.charset.Charset; +import java.util.concurrent.TimeUnit; + +/** + * @author a203 + */ +public class CommandUtil { + /** + * 检查当前系统是否已安装NTP + */ + public static boolean checkEnv() { + System.out.println("检查当前系统是否支持NTP"); + try { +// Process exec = Runtime.getRuntime().exec("ls"); + Process exec = Runtime.getRuntime().exec("rpm -q ntp"); + try { + //等待命令执行完成 + exec.waitFor(5, TimeUnit.SECONDS); + } catch (InterruptedException e) { + e.printStackTrace(); + } + String result = parseResult(exec.getInputStream()); + return !result.isEmpty(); + } catch (IOException e) { + e.printStackTrace(); + } + return false; + } + + /** + * 安装NTP + * yum -y install ntp + * */ + + /** + * 授时同步 + * ntpdate -u ntp.api.bz + */ + public static String ntpDate(String host) { + try { + String command = "ntpdate -u " + host; + System.out.println("授时同步 ===> " + command); + Process exec = Runtime.getRuntime().exec(command); + try { + //等待命令执行完成 + exec.waitFor(5, TimeUnit.SECONDS); + } catch (InterruptedException e) { + e.printStackTrace(); + } + return parseResult(exec.getInputStream()); + } catch (IOException e) { + e.printStackTrace(); + } + return ""; + } + + /** + * 解析命令结果 + */ + private static String parseResult(InputStream inputStream) throws IOException { + // 读取输出流内容 + InputStreamReader streamReader = new InputStreamReader(inputStream, Charset.defaultCharset()); + BufferedReader reader = new BufferedReader(streamReader); + StringBuilder builder = new StringBuilder(); + String line; + while ((line = reader.readLine()) != null) { + builder.append(line).append("\n"); + } + return builder.toString(); + } +} diff --git a/src/main/java/com/casic/swing/utils/Constant.java b/src/main/java/com/casic/swing/utils/Constant.java new file mode 100644 index 0000000..f4a6742 --- /dev/null +++ b/src/main/java/com/casic/swing/utils/Constant.java @@ -0,0 +1,13 @@ +package com.casic.swing.utils; + +/** + * @author a203 + */ +public class Constant { + public static final String[] HOST_NAME = {"NTP服务器(上海)", "中国国家授时中心", "清华大学", "北京大学", "自定义"}; + public static final String[] HOST_IP = {"ntp.api.bz", "ntp.ntsc.ac.cn", "s1b.time.edu.cn", "s2m.time.edu.cn"}; + /** + * 同步周期,单位:分钟 + */ + public static final Integer[] PERIOD = {10, 20, 30}; +} diff --git a/.gitignore b/.gitignore index 0841741..5027de1 100644 --- a/.gitignore +++ b/.gitignore @@ -1,2 +1,4 @@ .idea /out +/logs +/target diff --git a/CasicTimeGuard.iml b/CasicTimeGuard.iml index f54a89f..40532bb 100644 --- a/CasicTimeGuard.iml +++ b/CasicTimeGuard.iml @@ -1,12 +1,29 @@ - - - + + + + - + + + + - + + + + + + + + + + + + + + \ No newline at end of file diff --git a/lib/guava-18.0.jar b/lib/guava-18.0.jar deleted file mode 100644 index 8f89e49..0000000 --- a/lib/guava-18.0.jar +++ /dev/null Binary files differ diff --git a/pom.xml b/pom.xml new file mode 100644 index 0000000..3be19b5 --- /dev/null +++ b/pom.xml @@ -0,0 +1,44 @@ + + + 4.0.0 + + com.casic + CasicTimeGuard + 1.0-SNAPSHOT + + + 8 + 8 + 1.8 + + + + + org.projectlombok + lombok + 1.18.22 + true + + + + com.alibaba + fastjson + 1.2.79 + + + + + com.google.guava + guava + 31.0.1-jre + + + + com.squareup.okhttp3 + okhttp + 4.9.3 + + + \ No newline at end of file diff --git a/src/com/casic/swing/ui/TimeGuardNtp.form b/src/com/casic/swing/ui/TimeGuardNtp.form deleted file mode 100644 index cdba6f6..0000000 --- a/src/com/casic/swing/ui/TimeGuardNtp.form +++ /dev/null @@ -1,171 +0,0 @@ - -
- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - diff --git a/src/com/casic/swing/ui/TimeGuardNtp.java b/src/com/casic/swing/ui/TimeGuardNtp.java deleted file mode 100644 index 6df5b55..0000000 --- a/src/com/casic/swing/ui/TimeGuardNtp.java +++ /dev/null @@ -1,207 +0,0 @@ -package com.casic.swing.ui; - -import com.casic.swing.utils.CommandUtil; -import com.casic.swing.utils.StringHelper; -import com.casic.swing.utils.TimeOrDateUtil; -import com.google.common.util.concurrent.ThreadFactoryBuilder; - -import javax.swing.*; -import java.awt.*; -import java.awt.event.ActionEvent; -import java.awt.event.ActionListener; -import java.awt.event.ItemEvent; -import java.awt.event.ItemListener; -import java.util.concurrent.ScheduledExecutorService; -import java.util.concurrent.ScheduledThreadPoolExecutor; -import java.util.concurrent.TimeUnit; - -/** - * @author a203 - */ -public class TimeGuardNtp extends JFrame { - private JPanel ntpPanel; - private JComboBox hostComboBox; - private JLabel timeValueLabel; - private JButton updateTimeButton; - private JLabel dotView; - private JLabel currentTimeLabel; - private JCheckBox autoCheckBox; - private JComboBox periodComboBox; - private JPanel stateView; - - private final String[] HOST_NAME = {"NTP服务器(上海)", "中国国家授时中心", "清华大学", "北京大学", "自定义"}; - private final String[] HOST_IP = {"ntp.api.bz", "ntp.ntsc.ac.cn", "s1b.time.edu.cn", "s2m.time.edu.cn"}; - /** - * 同步周期,单位:小时 - */ - private final Integer[] PERIOD = {10, 20, 30}; - private final ScheduledExecutorService executorService = new ScheduledThreadPoolExecutor( - 1, new ThreadFactoryBuilder().setNameFormat("demo-pool-%d").build()); - private boolean hasNtp = false; - private String host = HOST_IP[0]; - - public static void main(String[] args) { - new TimeGuardNtp(); - } - - public TimeGuardNtp() { - setContentPane(ntpPanel); - setResizable(false); - setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); - pack(); - setSize(410, 280); - //居中 - setLocationRelativeTo(null); - setVisible(true); - dotView.setText("未同步"); - setStateView(Color.GRAY); - - StringHelper.createLogFile(); - - /** - * 时间间隔,单位为毫秒 - * */ - currentTimeLabel.setForeground(Color.BLUE); - new Timer(1000, new ActionListener() { - @Override - public void actionPerformed(ActionEvent e) { - String systemTime = TimeOrDateUtil.timestampToTime(System.currentTimeMillis()); - currentTimeLabel.setText(systemTime); - } - }).start(); - - String assertsData = StringHelper.getAssertsData(); - if (!"".equals(assertsData)) { - timeValueLabel.setText(assertsData); - } else { - timeValueLabel.setText("无法确定最近同步时间"); - } - - //初始化JComboBox - initComBox(); - hostComboBox.addItemListener(new ItemListener() { - @Override - public void itemStateChanged(ItemEvent e) { - String item = (String) e.getItem(); - if (e.getStateChange() == ItemEvent.SELECTED) { - if ("自定义".equals(item)) { - String inputContent = JOptionPane.showInputDialog(ntpPanel, "请输入授时中心域名或者IP地址", "", JOptionPane.INFORMATION_MESSAGE); - if (inputContent.isEmpty()) { - JOptionPane.showMessageDialog(ntpPanel, "输入错误,请检查", "Runtime Error", JOptionPane.ERROR_MESSAGE); - } else { - host = inputContent; - } - } else { - for (int i = 0; i < HOST_NAME.length; i++) { - if (item.equals(HOST_NAME[i])) { - host = HOST_IP[i]; - } - } - } - } - } - }); - - //检查环境 - new SwingWorker() { - - @Override - protected Boolean doInBackground() { - hasNtp = CommandUtil.checkEnv(); - return hasNtp; - } - - @Override - protected void done() { - if (!hasNtp) { - JOptionPane.showMessageDialog(ntpPanel, "未当前设备发现可用的NTP配置", "Runtime Error", JOptionPane.ERROR_MESSAGE); - //环境不对,关闭窗体 - dispose(); - } - super.done(); - } - }.execute(); - - autoCheckBox.addActionListener(new ActionListener() { - @Override - public void actionPerformed(ActionEvent e) { - JCheckBox checkBox = (JCheckBox) e.getSource(); - if (checkBox.isSelected()) { - updateTimeButton.setEnabled(false); - periodComboBox.setEnabled(true); - startAutoSynchronize(PERIOD[0]); - } else { - updateTimeButton.setEnabled(true); - periodComboBox.setEnabled(false); - } - } - }); - - periodComboBox.addItemListener(new ItemListener() { - @Override - public void itemStateChanged(ItemEvent e) { - int period = (Integer) e.getItem(); - if (e.getStateChange() == ItemEvent.SELECTED) { - startAutoSynchronize(period); - } - } - }); - - //按钮点击事件 - updateTimeButton.addActionListener(new ActionListener() { - @Override - public void actionPerformed(ActionEvent e) { - updateView(); - } - }); - } - - private void startAutoSynchronize(int period) { - /** - * 开启同步,只能开启一个同步线程 - * - * scheduleAtFixedRate - * 是以上一个任务开始的时间计时,period时间过去后,检测上一个任务是否执行完毕 - * 如果上一个任务执行完毕,则当前任务立即执行 - * 如果上一个任务没有执行完毕,则需要等上一个任务执行完毕后立即执行 - * */ - executorService.scheduleAtFixedRate(new Runnable() { - @Override - public void run() { - updateView(); - } - }, 0, period, TimeUnit.MINUTES); - } - - private void updateView() { - String result = CommandUtil.ntpDate(host); - System.out.println("命令执行结果 ===> " + result); - boolean isSuccess = result.contains("step time server") || result.contains("adjust time server"); - if (isSuccess) { - String systemTime = TimeOrDateUtil.timestampToTime(System.currentTimeMillis()); - setStateView(Color.GREEN); - dotView.setText("同步成功"); - timeValueLabel.setText(systemTime); - //同步成功之后将时间存入本地 - StringHelper.saveAssertsData(systemTime); - } else { - setStateView(Color.RED); - dotView.setText("同步失败"); - timeValueLabel.setText(""); - } - } - - private void initComBox() { - for (String s : HOST_NAME) { - hostComboBox.addItem(s); - } - for (Integer integer : PERIOD) { - periodComboBox.addItem(integer); - } - } - - private void setStateView(Color color) { - stateView.setPreferredSize(new Dimension(15, 15)); - stateView.setBackground(color); - } -} diff --git a/src/com/casic/swing/utils/CommandUtil.java b/src/com/casic/swing/utils/CommandUtil.java deleted file mode 100644 index c487e7d..0000000 --- a/src/com/casic/swing/utils/CommandUtil.java +++ /dev/null @@ -1,76 +0,0 @@ -package com.casic.swing.utils; - -import java.io.BufferedReader; -import java.io.IOException; -import java.io.InputStream; -import java.io.InputStreamReader; -import java.nio.charset.Charset; -import java.util.concurrent.TimeUnit; - -/** - * @author a203 - */ -public class CommandUtil { - /** - * 检查当前系统是否已安装NTP - */ - public static boolean checkEnv() { - System.out.println("检查当前系统是否支持NTP"); - try { - Process exec = Runtime.getRuntime().exec("rpm -q ntp"); - try { - //等待命令执行完成 - exec.waitFor(5, TimeUnit.SECONDS); - } catch (InterruptedException e) { - e.printStackTrace(); - } - String result = parseResult(exec.getInputStream()); - return !result.isEmpty(); - } catch (IOException e) { - e.printStackTrace(); - } - return false; - } - - /** - * 安装NTP - * yum -y install ntp - * */ - - /** - * 授时同步 - * ntpdate -u ntp.api.bz - */ - public static String ntpDate(String host) { - try { - String command = "ntpdate -u " + host; - System.out.println("授时同步 ===> " + command); - Process exec = Runtime.getRuntime().exec(command); - try { - //等待命令执行完成 - exec.waitFor(5, TimeUnit.SECONDS); - } catch (InterruptedException e) { - e.printStackTrace(); - } - return parseResult(exec.getInputStream()); - } catch (IOException e) { - e.printStackTrace(); - } - return ""; - } - - /** - * 解析命令结果 - */ - private static String parseResult(InputStream inputStream) throws IOException { - // 读取输出流内容 - InputStreamReader streamReader = new InputStreamReader(inputStream, Charset.defaultCharset()); - BufferedReader reader = new BufferedReader(streamReader); - StringBuilder builder = new StringBuilder(); - String line; - while ((line = reader.readLine()) != null) { - builder.append(line).append("\n"); - } - return builder.toString(); - } -} diff --git a/src/com/casic/swing/utils/StringHelper.java b/src/com/casic/swing/utils/StringHelper.java deleted file mode 100644 index b994e19..0000000 --- a/src/com/casic/swing/utils/StringHelper.java +++ /dev/null @@ -1,64 +0,0 @@ -package com.casic.swing.utils; - -import javax.swing.filechooser.FileSystemView; -import java.io.*; - -/** - * @author a203 - */ -public class StringHelper { - - private static final String FILE_NAME = "update.log"; - private static File logFile; - - public static void createLogFile() { - FileSystemView view = FileSystemView.getFileSystemView(); - File file = view.getHomeDirectory(); - File dir = new File(file.getAbsolutePath() + File.separator + "logs"); - if (!dir.exists()) { - dir.mkdir(); - } - logFile = new File(dir + File.separator + FILE_NAME); - if (!logFile.exists()) { - // 创建新文件,有同名的文件的话直接覆盖 - try { - logFile.createNewFile(); - } catch (IOException e) { - e.printStackTrace(); - } - } - System.out.println("同步记录路径 ===> " + logFile.getAbsolutePath()); - } - - public static void saveAssertsData(String data) { - try { - FileWriter writer = new FileWriter(logFile); - BufferedWriter out = new BufferedWriter(writer); - out.write(data); - out.flush(); - out.close(); - } catch (IOException e) { - e.printStackTrace(); - } - } - - public static String getAssertsData() { - try { - InputStreamReader inputStreamReader = new InputStreamReader(new FileInputStream(logFile)); - BufferedReader bufferedReader = new BufferedReader(inputStreamReader); - StringBuilder data = new StringBuilder(); - String s; - try { - while ((s = bufferedReader.readLine()) != null) { - data.append(s); - } - return data.toString(); - } catch (IOException e) { - e.printStackTrace(); - } - } catch (IOException e) { - e.printStackTrace(); - } - return ""; - } -} diff --git a/src/com/casic/swing/utils/TimeOrDateUtil.java b/src/com/casic/swing/utils/TimeOrDateUtil.java deleted file mode 100644 index 7adc5a6..0000000 --- a/src/com/casic/swing/utils/TimeOrDateUtil.java +++ /dev/null @@ -1,18 +0,0 @@ -package com.casic.swing.utils; - -import java.text.SimpleDateFormat; -import java.util.Date; - -/** - * @author a203 - */ -public class TimeOrDateUtil { - - /** - * 时间戳转时间 - */ - public static String timestampToTime(long millSeconds) { - SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); - return format.format(new Date(millSeconds)); - } -} diff --git a/src/main/java/com/casic/swing/ui/TimeGuardNtp.form b/src/main/java/com/casic/swing/ui/TimeGuardNtp.form new file mode 100644 index 0000000..8732b4b --- /dev/null +++ b/src/main/java/com/casic/swing/ui/TimeGuardNtp.form @@ -0,0 +1,207 @@ + +
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/src/main/java/com/casic/swing/ui/TimeGuardNtp.java b/src/main/java/com/casic/swing/ui/TimeGuardNtp.java new file mode 100644 index 0000000..9c7fef7 --- /dev/null +++ b/src/main/java/com/casic/swing/ui/TimeGuardNtp.java @@ -0,0 +1,239 @@ +package com.casic.swing.ui; + +import com.alibaba.fastjson.JSONException; +import com.alibaba.fastjson.JSONObject; +import com.casic.swing.utils.*; +import com.google.common.util.concurrent.ThreadFactoryBuilder; +import okhttp3.Request; + +import javax.swing.*; +import java.awt.*; +import java.awt.event.ActionEvent; +import java.awt.event.ActionListener; +import java.awt.event.ItemEvent; +import java.awt.event.ItemListener; +import java.net.InetAddress; +import java.util.concurrent.ScheduledExecutorService; +import java.util.concurrent.ScheduledThreadPoolExecutor; +import java.util.concurrent.TimeUnit; + +/** + * @author a203 + */ +public class TimeGuardNtp extends JFrame { + private JPanel ntpPanel; + private JLabel timeValueLabel; + private JButton updateTimeButton; + private JLabel currentTimeLabel; + private JCheckBox autoCheckBox; + private JComboBox periodComboBox; + private JLabel stateView; + private JPanel dotPanel; + private JTextField hostTextField; + private JComboBox localHostBox; + private JTextField serverTextField; + + private final ScheduledExecutorService executorService = new ScheduledThreadPoolExecutor( + 1, new ThreadFactoryBuilder().setNameFormat("demo-pool-%d").build()); + private boolean hasNtp = false; + + public static void main(String[] args) { + new TimeGuardNtp(); + } + + public TimeGuardNtp() { + setContentPane(ntpPanel); + setResizable(false); + setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); + pack(); + setSize(400, 330); + //居中 + setLocationRelativeTo(null); + setVisible(true); + stateView.setText("未同步"); + setStateView(Color.GRAY); + + StringHelper.createLogFile(); + + /** + * 时间间隔,单位为毫秒 + * */ + currentTimeLabel.setForeground(Color.BLUE); + new Timer(1000, new ActionListener() { + @Override + public void actionPerformed(ActionEvent e) { + String systemTime = TimeOrDateUtil.timestampToTime(System.currentTimeMillis()); + currentTimeLabel.setText(systemTime); + } + }).start(); + + String assertsData = StringHelper.getAssertsData(); + if (!"".equals(assertsData)) { + timeValueLabel.setText(assertsData); + } else { + timeValueLabel.setText("无法确定最近同步时间"); + } + + //初始化JComboBox + for (Integer integer : Constant.PERIOD) { + periodComboBox.addItem(integer); + } + java.util.List addressList = HttpRequestHelper.localHost(); + for (InetAddress address : addressList) { + localHostBox.addItem(address.getHostAddress()); + } + + //检查环境 +// new SwingWorker() { +// +// @Override +// protected Boolean doInBackground() { +// hasNtp = CommandUtil.checkEnv(); +// return hasNtp; +// } +// +// @Override +// protected void done() { +// if (!hasNtp) { +// JOptionPane.showMessageDialog(ntpPanel, "未当前设备发现可用的NTP配置", "Runtime Error", JOptionPane.ERROR_MESSAGE); +// //环境不对,关闭窗体 +// dispose(); +// } +// super.done(); +// } +// }.execute(); + + autoCheckBox.addActionListener(new ActionListener() { + @Override + public void actionPerformed(ActionEvent e) { + JCheckBox checkBox = (JCheckBox) e.getSource(); + if (checkBox.isSelected()) { + updateTimeButton.setEnabled(false); + periodComboBox.setEnabled(true); + hostTextField.setEnabled(false); + serverTextField.setEnabled(false); + startAutoSynchronize(Constant.PERIOD[0]); + } else { + updateTimeButton.setEnabled(true); + periodComboBox.setEnabled(false); + hostTextField.setEnabled(true); + serverTextField.setEnabled(true); + } + } + }); + + periodComboBox.addItemListener(new ItemListener() { + @Override + public void itemStateChanged(ItemEvent e) { + int period = (Integer) e.getItem(); + if (e.getStateChange() == ItemEvent.SELECTED) { + startAutoSynchronize(period); + } + } + }); + + //按钮点击事件 + updateTimeButton.addActionListener(new ActionListener() { + @Override + public void actionPerformed(ActionEvent e) { + updateView(); + } + }); + } + + private void startAutoSynchronize(int period) { + /** + * 开启同步,只能开启一个同步线程 + * + * scheduleAtFixedRate + * 是以上一个任务开始的时间计时,period时间过去后,检测上一个任务是否执行完毕 + * 如果上一个任务执行完毕,则当前任务立即执行 + * 如果上一个任务没有执行完毕,则需要等上一个任务执行完毕后立即执行 + * */ + executorService.scheduleAtFixedRate(new Runnable() { + @Override + public void run() { + updateView(); + } + }, 0, period, TimeUnit.MINUTES); + } + + private void updateView() { + String host = hostTextField.getText().trim(); + if (host.isEmpty()) { + autoCheckBox.setSelected(false); + JOptionPane.showMessageDialog(ntpPanel, "授时中心服务器输入错误,请检查", "Runtime Error", JOptionPane.ERROR_MESSAGE); + return; + } + String server = serverTextField.getText().trim(); + if (server.isEmpty()) { + autoCheckBox.setSelected(false); + JOptionPane.showMessageDialog(ntpPanel, "后台服务器地址输入错误,请检查", "Runtime Error", JOptionPane.ERROR_MESSAGE); + return; + } +// String result = "5 Jan 11:20:24 ntpdate[807910]: adjust time server 114.118.7.161 offset -0.004064 sec"; +// String result = "5 Jan 11:24:06 ntpdate[824403]: no server suitable for synchronization found"; + String result = CommandUtil.ntpDate(host); + System.out.println("命令执行结果 ===> " + result); + + if ("".equals(result)) { + setStateView(Color.RED); + stateView.setText("同步失败"); + timeValueLabel.setText(""); + } else { + String systemTime = TimeOrDateUtil.timestampToTime(System.currentTimeMillis()); + + String resultString = result.split(":")[3]; + boolean isSuccess = !resultString.contains("no server suitable"); + if (isSuccess) { + setStateView(Color.GREEN); + stateView.setText("同步成功"); + timeValueLabel.setText(systemTime); + //同步成功之后将时间存入本地 + StringHelper.saveAssertsData(systemTime); + } else { + setStateView(Color.RED); + stateView.setText("同步失败"); + timeValueLabel.setText(""); + } + //POST提交 + JSONObject object = new JSONObject(); + try { + object.put("deviceIp", localHostBox.getSelectedItem()); + object.put("ntpResult", result); + + String[] dataSplit = resultString.split(" "); + object.put("deltaTime", dataSplit[6]); + object.put("createTime", systemTime); + if (autoCheckBox.isSelected()) { + object.put("frequency", periodComboBox.getSelectedItem()); + } else { + object.put("frequency", ""); + } + } catch (JSONException e) { + e.printStackTrace(); + } + Request request = new Request.Builder() + .url("http://" + server + "/ntp/saveResult") + .post(HttpRequestHelper.createRequestBody(object.toJSONString())) + .build(); + HttpRequestHelper.doPost(request, new IHttpCallback() { + + @Override + public void onSuccess(String s) { + + } + + @Override + public void onFailure(Exception e) { + e.printStackTrace(); + } + }); + } + } + + private void setStateView(Color color) { + dotPanel.setPreferredSize(new Dimension(15, 15)); + dotPanel.setBackground(color); + } +} diff --git a/src/main/java/com/casic/swing/utils/CommandUtil.java b/src/main/java/com/casic/swing/utils/CommandUtil.java new file mode 100644 index 0000000..2515971 --- /dev/null +++ b/src/main/java/com/casic/swing/utils/CommandUtil.java @@ -0,0 +1,77 @@ +package com.casic.swing.utils; + +import java.io.BufferedReader; +import java.io.IOException; +import java.io.InputStream; +import java.io.InputStreamReader; +import java.nio.charset.Charset; +import java.util.concurrent.TimeUnit; + +/** + * @author a203 + */ +public class CommandUtil { + /** + * 检查当前系统是否已安装NTP + */ + public static boolean checkEnv() { + System.out.println("检查当前系统是否支持NTP"); + try { +// Process exec = Runtime.getRuntime().exec("ls"); + Process exec = Runtime.getRuntime().exec("rpm -q ntp"); + try { + //等待命令执行完成 + exec.waitFor(5, TimeUnit.SECONDS); + } catch (InterruptedException e) { + e.printStackTrace(); + } + String result = parseResult(exec.getInputStream()); + return !result.isEmpty(); + } catch (IOException e) { + e.printStackTrace(); + } + return false; + } + + /** + * 安装NTP + * yum -y install ntp + * */ + + /** + * 授时同步 + * ntpdate -u ntp.api.bz + */ + public static String ntpDate(String host) { + try { + String command = "ntpdate -u " + host; + System.out.println("授时同步 ===> " + command); + Process exec = Runtime.getRuntime().exec(command); + try { + //等待命令执行完成 + exec.waitFor(5, TimeUnit.SECONDS); + } catch (InterruptedException e) { + e.printStackTrace(); + } + return parseResult(exec.getInputStream()); + } catch (IOException e) { + e.printStackTrace(); + } + return ""; + } + + /** + * 解析命令结果 + */ + private static String parseResult(InputStream inputStream) throws IOException { + // 读取输出流内容 + InputStreamReader streamReader = new InputStreamReader(inputStream, Charset.defaultCharset()); + BufferedReader reader = new BufferedReader(streamReader); + StringBuilder builder = new StringBuilder(); + String line; + while ((line = reader.readLine()) != null) { + builder.append(line).append("\n"); + } + return builder.toString(); + } +} diff --git a/src/main/java/com/casic/swing/utils/Constant.java b/src/main/java/com/casic/swing/utils/Constant.java new file mode 100644 index 0000000..f4a6742 --- /dev/null +++ b/src/main/java/com/casic/swing/utils/Constant.java @@ -0,0 +1,13 @@ +package com.casic.swing.utils; + +/** + * @author a203 + */ +public class Constant { + public static final String[] HOST_NAME = {"NTP服务器(上海)", "中国国家授时中心", "清华大学", "北京大学", "自定义"}; + public static final String[] HOST_IP = {"ntp.api.bz", "ntp.ntsc.ac.cn", "s1b.time.edu.cn", "s2m.time.edu.cn"}; + /** + * 同步周期,单位:分钟 + */ + public static final Integer[] PERIOD = {10, 20, 30}; +} diff --git a/src/main/java/com/casic/swing/utils/HttpRequestHelper.java b/src/main/java/com/casic/swing/utils/HttpRequestHelper.java new file mode 100644 index 0000000..ae7f057 --- /dev/null +++ b/src/main/java/com/casic/swing/utils/HttpRequestHelper.java @@ -0,0 +1,78 @@ +package com.casic.swing.utils; + +import okhttp3.*; +import org.jetbrains.annotations.NotNull; + +import java.io.IOException; +import java.net.Inet4Address; +import java.net.InetAddress; +import java.net.NetworkInterface; +import java.net.SocketException; +import java.util.ArrayList; +import java.util.Enumeration; +import java.util.List; +import java.util.Objects; +import java.util.concurrent.TimeUnit; + +/** + * @author a203 + */ +public class HttpRequestHelper { + public static RequestBody createRequestBody(String value) { + return RequestBody.create(MediaType.parse("application/json; charset=utf-8"), value); + } + + public static void doPost(Request request, IHttpCallback httpCallback) { + OkHttpClient httpClient = new OkHttpClient.Builder() + .connectTimeout(15, TimeUnit.SECONDS) + .writeTimeout(15, TimeUnit.SECONDS) + .readTimeout(15, TimeUnit.SECONDS) + .build(); + Call call = httpClient.newCall(request); + call.enqueue(new Callback() { + @Override + public void onFailure(@NotNull Call call, @NotNull IOException e) { + + } + + @Override + public void onResponse(@NotNull Call call, @NotNull Response response) throws IOException { + try { + if (response.body() != null) { + String string = Objects.requireNonNull(response.body()).string(); + httpCallback.onSuccess(string); + } else { + httpCallback.onFailure(new NullPointerException()); + } + } catch (IOException e) { + httpCallback.onFailure(e); + } + } + }); + } + + public static List localHost() { + List addressList = new ArrayList<>(); + try { + Enumeration interfaces = NetworkInterface.getNetworkInterfaces(); + InetAddress ip; + while (interfaces.hasMoreElements()) { + NetworkInterface netInterface = interfaces.nextElement(); + if (netInterface.isLoopback() || netInterface.isVirtual() || !netInterface.isUp()) { + continue; + } else { + Enumeration addresses = netInterface.getInetAddresses(); + while (addresses.hasMoreElements()) { + ip = addresses.nextElement(); + if (ip instanceof Inet4Address) { + addressList.add(ip); + } + } + } + } + } catch (SocketException e) { + e.printStackTrace(); + } + return addressList; + } +} diff --git a/.gitignore b/.gitignore index 0841741..5027de1 100644 --- a/.gitignore +++ b/.gitignore @@ -1,2 +1,4 @@ .idea /out +/logs +/target diff --git a/CasicTimeGuard.iml b/CasicTimeGuard.iml index f54a89f..40532bb 100644 --- a/CasicTimeGuard.iml +++ b/CasicTimeGuard.iml @@ -1,12 +1,29 @@ - - - + + + + - + + + + - + + + + + + + + + + + + + + \ No newline at end of file diff --git a/lib/guava-18.0.jar b/lib/guava-18.0.jar deleted file mode 100644 index 8f89e49..0000000 --- a/lib/guava-18.0.jar +++ /dev/null Binary files differ diff --git a/pom.xml b/pom.xml new file mode 100644 index 0000000..3be19b5 --- /dev/null +++ b/pom.xml @@ -0,0 +1,44 @@ + + + 4.0.0 + + com.casic + CasicTimeGuard + 1.0-SNAPSHOT + + + 8 + 8 + 1.8 + + + + + org.projectlombok + lombok + 1.18.22 + true + + + + com.alibaba + fastjson + 1.2.79 + + + + + com.google.guava + guava + 31.0.1-jre + + + + com.squareup.okhttp3 + okhttp + 4.9.3 + + + \ No newline at end of file diff --git a/src/com/casic/swing/ui/TimeGuardNtp.form b/src/com/casic/swing/ui/TimeGuardNtp.form deleted file mode 100644 index cdba6f6..0000000 --- a/src/com/casic/swing/ui/TimeGuardNtp.form +++ /dev/null @@ -1,171 +0,0 @@ - -
- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - diff --git a/src/com/casic/swing/ui/TimeGuardNtp.java b/src/com/casic/swing/ui/TimeGuardNtp.java deleted file mode 100644 index 6df5b55..0000000 --- a/src/com/casic/swing/ui/TimeGuardNtp.java +++ /dev/null @@ -1,207 +0,0 @@ -package com.casic.swing.ui; - -import com.casic.swing.utils.CommandUtil; -import com.casic.swing.utils.StringHelper; -import com.casic.swing.utils.TimeOrDateUtil; -import com.google.common.util.concurrent.ThreadFactoryBuilder; - -import javax.swing.*; -import java.awt.*; -import java.awt.event.ActionEvent; -import java.awt.event.ActionListener; -import java.awt.event.ItemEvent; -import java.awt.event.ItemListener; -import java.util.concurrent.ScheduledExecutorService; -import java.util.concurrent.ScheduledThreadPoolExecutor; -import java.util.concurrent.TimeUnit; - -/** - * @author a203 - */ -public class TimeGuardNtp extends JFrame { - private JPanel ntpPanel; - private JComboBox hostComboBox; - private JLabel timeValueLabel; - private JButton updateTimeButton; - private JLabel dotView; - private JLabel currentTimeLabel; - private JCheckBox autoCheckBox; - private JComboBox periodComboBox; - private JPanel stateView; - - private final String[] HOST_NAME = {"NTP服务器(上海)", "中国国家授时中心", "清华大学", "北京大学", "自定义"}; - private final String[] HOST_IP = {"ntp.api.bz", "ntp.ntsc.ac.cn", "s1b.time.edu.cn", "s2m.time.edu.cn"}; - /** - * 同步周期,单位:小时 - */ - private final Integer[] PERIOD = {10, 20, 30}; - private final ScheduledExecutorService executorService = new ScheduledThreadPoolExecutor( - 1, new ThreadFactoryBuilder().setNameFormat("demo-pool-%d").build()); - private boolean hasNtp = false; - private String host = HOST_IP[0]; - - public static void main(String[] args) { - new TimeGuardNtp(); - } - - public TimeGuardNtp() { - setContentPane(ntpPanel); - setResizable(false); - setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); - pack(); - setSize(410, 280); - //居中 - setLocationRelativeTo(null); - setVisible(true); - dotView.setText("未同步"); - setStateView(Color.GRAY); - - StringHelper.createLogFile(); - - /** - * 时间间隔,单位为毫秒 - * */ - currentTimeLabel.setForeground(Color.BLUE); - new Timer(1000, new ActionListener() { - @Override - public void actionPerformed(ActionEvent e) { - String systemTime = TimeOrDateUtil.timestampToTime(System.currentTimeMillis()); - currentTimeLabel.setText(systemTime); - } - }).start(); - - String assertsData = StringHelper.getAssertsData(); - if (!"".equals(assertsData)) { - timeValueLabel.setText(assertsData); - } else { - timeValueLabel.setText("无法确定最近同步时间"); - } - - //初始化JComboBox - initComBox(); - hostComboBox.addItemListener(new ItemListener() { - @Override - public void itemStateChanged(ItemEvent e) { - String item = (String) e.getItem(); - if (e.getStateChange() == ItemEvent.SELECTED) { - if ("自定义".equals(item)) { - String inputContent = JOptionPane.showInputDialog(ntpPanel, "请输入授时中心域名或者IP地址", "", JOptionPane.INFORMATION_MESSAGE); - if (inputContent.isEmpty()) { - JOptionPane.showMessageDialog(ntpPanel, "输入错误,请检查", "Runtime Error", JOptionPane.ERROR_MESSAGE); - } else { - host = inputContent; - } - } else { - for (int i = 0; i < HOST_NAME.length; i++) { - if (item.equals(HOST_NAME[i])) { - host = HOST_IP[i]; - } - } - } - } - } - }); - - //检查环境 - new SwingWorker() { - - @Override - protected Boolean doInBackground() { - hasNtp = CommandUtil.checkEnv(); - return hasNtp; - } - - @Override - protected void done() { - if (!hasNtp) { - JOptionPane.showMessageDialog(ntpPanel, "未当前设备发现可用的NTP配置", "Runtime Error", JOptionPane.ERROR_MESSAGE); - //环境不对,关闭窗体 - dispose(); - } - super.done(); - } - }.execute(); - - autoCheckBox.addActionListener(new ActionListener() { - @Override - public void actionPerformed(ActionEvent e) { - JCheckBox checkBox = (JCheckBox) e.getSource(); - if (checkBox.isSelected()) { - updateTimeButton.setEnabled(false); - periodComboBox.setEnabled(true); - startAutoSynchronize(PERIOD[0]); - } else { - updateTimeButton.setEnabled(true); - periodComboBox.setEnabled(false); - } - } - }); - - periodComboBox.addItemListener(new ItemListener() { - @Override - public void itemStateChanged(ItemEvent e) { - int period = (Integer) e.getItem(); - if (e.getStateChange() == ItemEvent.SELECTED) { - startAutoSynchronize(period); - } - } - }); - - //按钮点击事件 - updateTimeButton.addActionListener(new ActionListener() { - @Override - public void actionPerformed(ActionEvent e) { - updateView(); - } - }); - } - - private void startAutoSynchronize(int period) { - /** - * 开启同步,只能开启一个同步线程 - * - * scheduleAtFixedRate - * 是以上一个任务开始的时间计时,period时间过去后,检测上一个任务是否执行完毕 - * 如果上一个任务执行完毕,则当前任务立即执行 - * 如果上一个任务没有执行完毕,则需要等上一个任务执行完毕后立即执行 - * */ - executorService.scheduleAtFixedRate(new Runnable() { - @Override - public void run() { - updateView(); - } - }, 0, period, TimeUnit.MINUTES); - } - - private void updateView() { - String result = CommandUtil.ntpDate(host); - System.out.println("命令执行结果 ===> " + result); - boolean isSuccess = result.contains("step time server") || result.contains("adjust time server"); - if (isSuccess) { - String systemTime = TimeOrDateUtil.timestampToTime(System.currentTimeMillis()); - setStateView(Color.GREEN); - dotView.setText("同步成功"); - timeValueLabel.setText(systemTime); - //同步成功之后将时间存入本地 - StringHelper.saveAssertsData(systemTime); - } else { - setStateView(Color.RED); - dotView.setText("同步失败"); - timeValueLabel.setText(""); - } - } - - private void initComBox() { - for (String s : HOST_NAME) { - hostComboBox.addItem(s); - } - for (Integer integer : PERIOD) { - periodComboBox.addItem(integer); - } - } - - private void setStateView(Color color) { - stateView.setPreferredSize(new Dimension(15, 15)); - stateView.setBackground(color); - } -} diff --git a/src/com/casic/swing/utils/CommandUtil.java b/src/com/casic/swing/utils/CommandUtil.java deleted file mode 100644 index c487e7d..0000000 --- a/src/com/casic/swing/utils/CommandUtil.java +++ /dev/null @@ -1,76 +0,0 @@ -package com.casic.swing.utils; - -import java.io.BufferedReader; -import java.io.IOException; -import java.io.InputStream; -import java.io.InputStreamReader; -import java.nio.charset.Charset; -import java.util.concurrent.TimeUnit; - -/** - * @author a203 - */ -public class CommandUtil { - /** - * 检查当前系统是否已安装NTP - */ - public static boolean checkEnv() { - System.out.println("检查当前系统是否支持NTP"); - try { - Process exec = Runtime.getRuntime().exec("rpm -q ntp"); - try { - //等待命令执行完成 - exec.waitFor(5, TimeUnit.SECONDS); - } catch (InterruptedException e) { - e.printStackTrace(); - } - String result = parseResult(exec.getInputStream()); - return !result.isEmpty(); - } catch (IOException e) { - e.printStackTrace(); - } - return false; - } - - /** - * 安装NTP - * yum -y install ntp - * */ - - /** - * 授时同步 - * ntpdate -u ntp.api.bz - */ - public static String ntpDate(String host) { - try { - String command = "ntpdate -u " + host; - System.out.println("授时同步 ===> " + command); - Process exec = Runtime.getRuntime().exec(command); - try { - //等待命令执行完成 - exec.waitFor(5, TimeUnit.SECONDS); - } catch (InterruptedException e) { - e.printStackTrace(); - } - return parseResult(exec.getInputStream()); - } catch (IOException e) { - e.printStackTrace(); - } - return ""; - } - - /** - * 解析命令结果 - */ - private static String parseResult(InputStream inputStream) throws IOException { - // 读取输出流内容 - InputStreamReader streamReader = new InputStreamReader(inputStream, Charset.defaultCharset()); - BufferedReader reader = new BufferedReader(streamReader); - StringBuilder builder = new StringBuilder(); - String line; - while ((line = reader.readLine()) != null) { - builder.append(line).append("\n"); - } - return builder.toString(); - } -} diff --git a/src/com/casic/swing/utils/StringHelper.java b/src/com/casic/swing/utils/StringHelper.java deleted file mode 100644 index b994e19..0000000 --- a/src/com/casic/swing/utils/StringHelper.java +++ /dev/null @@ -1,64 +0,0 @@ -package com.casic.swing.utils; - -import javax.swing.filechooser.FileSystemView; -import java.io.*; - -/** - * @author a203 - */ -public class StringHelper { - - private static final String FILE_NAME = "update.log"; - private static File logFile; - - public static void createLogFile() { - FileSystemView view = FileSystemView.getFileSystemView(); - File file = view.getHomeDirectory(); - File dir = new File(file.getAbsolutePath() + File.separator + "logs"); - if (!dir.exists()) { - dir.mkdir(); - } - logFile = new File(dir + File.separator + FILE_NAME); - if (!logFile.exists()) { - // 创建新文件,有同名的文件的话直接覆盖 - try { - logFile.createNewFile(); - } catch (IOException e) { - e.printStackTrace(); - } - } - System.out.println("同步记录路径 ===> " + logFile.getAbsolutePath()); - } - - public static void saveAssertsData(String data) { - try { - FileWriter writer = new FileWriter(logFile); - BufferedWriter out = new BufferedWriter(writer); - out.write(data); - out.flush(); - out.close(); - } catch (IOException e) { - e.printStackTrace(); - } - } - - public static String getAssertsData() { - try { - InputStreamReader inputStreamReader = new InputStreamReader(new FileInputStream(logFile)); - BufferedReader bufferedReader = new BufferedReader(inputStreamReader); - StringBuilder data = new StringBuilder(); - String s; - try { - while ((s = bufferedReader.readLine()) != null) { - data.append(s); - } - return data.toString(); - } catch (IOException e) { - e.printStackTrace(); - } - } catch (IOException e) { - e.printStackTrace(); - } - return ""; - } -} diff --git a/src/com/casic/swing/utils/TimeOrDateUtil.java b/src/com/casic/swing/utils/TimeOrDateUtil.java deleted file mode 100644 index 7adc5a6..0000000 --- a/src/com/casic/swing/utils/TimeOrDateUtil.java +++ /dev/null @@ -1,18 +0,0 @@ -package com.casic.swing.utils; - -import java.text.SimpleDateFormat; -import java.util.Date; - -/** - * @author a203 - */ -public class TimeOrDateUtil { - - /** - * 时间戳转时间 - */ - public static String timestampToTime(long millSeconds) { - SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); - return format.format(new Date(millSeconds)); - } -} diff --git a/src/main/java/com/casic/swing/ui/TimeGuardNtp.form b/src/main/java/com/casic/swing/ui/TimeGuardNtp.form new file mode 100644 index 0000000..8732b4b --- /dev/null +++ b/src/main/java/com/casic/swing/ui/TimeGuardNtp.form @@ -0,0 +1,207 @@ + +
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/src/main/java/com/casic/swing/ui/TimeGuardNtp.java b/src/main/java/com/casic/swing/ui/TimeGuardNtp.java new file mode 100644 index 0000000..9c7fef7 --- /dev/null +++ b/src/main/java/com/casic/swing/ui/TimeGuardNtp.java @@ -0,0 +1,239 @@ +package com.casic.swing.ui; + +import com.alibaba.fastjson.JSONException; +import com.alibaba.fastjson.JSONObject; +import com.casic.swing.utils.*; +import com.google.common.util.concurrent.ThreadFactoryBuilder; +import okhttp3.Request; + +import javax.swing.*; +import java.awt.*; +import java.awt.event.ActionEvent; +import java.awt.event.ActionListener; +import java.awt.event.ItemEvent; +import java.awt.event.ItemListener; +import java.net.InetAddress; +import java.util.concurrent.ScheduledExecutorService; +import java.util.concurrent.ScheduledThreadPoolExecutor; +import java.util.concurrent.TimeUnit; + +/** + * @author a203 + */ +public class TimeGuardNtp extends JFrame { + private JPanel ntpPanel; + private JLabel timeValueLabel; + private JButton updateTimeButton; + private JLabel currentTimeLabel; + private JCheckBox autoCheckBox; + private JComboBox periodComboBox; + private JLabel stateView; + private JPanel dotPanel; + private JTextField hostTextField; + private JComboBox localHostBox; + private JTextField serverTextField; + + private final ScheduledExecutorService executorService = new ScheduledThreadPoolExecutor( + 1, new ThreadFactoryBuilder().setNameFormat("demo-pool-%d").build()); + private boolean hasNtp = false; + + public static void main(String[] args) { + new TimeGuardNtp(); + } + + public TimeGuardNtp() { + setContentPane(ntpPanel); + setResizable(false); + setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); + pack(); + setSize(400, 330); + //居中 + setLocationRelativeTo(null); + setVisible(true); + stateView.setText("未同步"); + setStateView(Color.GRAY); + + StringHelper.createLogFile(); + + /** + * 时间间隔,单位为毫秒 + * */ + currentTimeLabel.setForeground(Color.BLUE); + new Timer(1000, new ActionListener() { + @Override + public void actionPerformed(ActionEvent e) { + String systemTime = TimeOrDateUtil.timestampToTime(System.currentTimeMillis()); + currentTimeLabel.setText(systemTime); + } + }).start(); + + String assertsData = StringHelper.getAssertsData(); + if (!"".equals(assertsData)) { + timeValueLabel.setText(assertsData); + } else { + timeValueLabel.setText("无法确定最近同步时间"); + } + + //初始化JComboBox + for (Integer integer : Constant.PERIOD) { + periodComboBox.addItem(integer); + } + java.util.List addressList = HttpRequestHelper.localHost(); + for (InetAddress address : addressList) { + localHostBox.addItem(address.getHostAddress()); + } + + //检查环境 +// new SwingWorker() { +// +// @Override +// protected Boolean doInBackground() { +// hasNtp = CommandUtil.checkEnv(); +// return hasNtp; +// } +// +// @Override +// protected void done() { +// if (!hasNtp) { +// JOptionPane.showMessageDialog(ntpPanel, "未当前设备发现可用的NTP配置", "Runtime Error", JOptionPane.ERROR_MESSAGE); +// //环境不对,关闭窗体 +// dispose(); +// } +// super.done(); +// } +// }.execute(); + + autoCheckBox.addActionListener(new ActionListener() { + @Override + public void actionPerformed(ActionEvent e) { + JCheckBox checkBox = (JCheckBox) e.getSource(); + if (checkBox.isSelected()) { + updateTimeButton.setEnabled(false); + periodComboBox.setEnabled(true); + hostTextField.setEnabled(false); + serverTextField.setEnabled(false); + startAutoSynchronize(Constant.PERIOD[0]); + } else { + updateTimeButton.setEnabled(true); + periodComboBox.setEnabled(false); + hostTextField.setEnabled(true); + serverTextField.setEnabled(true); + } + } + }); + + periodComboBox.addItemListener(new ItemListener() { + @Override + public void itemStateChanged(ItemEvent e) { + int period = (Integer) e.getItem(); + if (e.getStateChange() == ItemEvent.SELECTED) { + startAutoSynchronize(period); + } + } + }); + + //按钮点击事件 + updateTimeButton.addActionListener(new ActionListener() { + @Override + public void actionPerformed(ActionEvent e) { + updateView(); + } + }); + } + + private void startAutoSynchronize(int period) { + /** + * 开启同步,只能开启一个同步线程 + * + * scheduleAtFixedRate + * 是以上一个任务开始的时间计时,period时间过去后,检测上一个任务是否执行完毕 + * 如果上一个任务执行完毕,则当前任务立即执行 + * 如果上一个任务没有执行完毕,则需要等上一个任务执行完毕后立即执行 + * */ + executorService.scheduleAtFixedRate(new Runnable() { + @Override + public void run() { + updateView(); + } + }, 0, period, TimeUnit.MINUTES); + } + + private void updateView() { + String host = hostTextField.getText().trim(); + if (host.isEmpty()) { + autoCheckBox.setSelected(false); + JOptionPane.showMessageDialog(ntpPanel, "授时中心服务器输入错误,请检查", "Runtime Error", JOptionPane.ERROR_MESSAGE); + return; + } + String server = serverTextField.getText().trim(); + if (server.isEmpty()) { + autoCheckBox.setSelected(false); + JOptionPane.showMessageDialog(ntpPanel, "后台服务器地址输入错误,请检查", "Runtime Error", JOptionPane.ERROR_MESSAGE); + return; + } +// String result = "5 Jan 11:20:24 ntpdate[807910]: adjust time server 114.118.7.161 offset -0.004064 sec"; +// String result = "5 Jan 11:24:06 ntpdate[824403]: no server suitable for synchronization found"; + String result = CommandUtil.ntpDate(host); + System.out.println("命令执行结果 ===> " + result); + + if ("".equals(result)) { + setStateView(Color.RED); + stateView.setText("同步失败"); + timeValueLabel.setText(""); + } else { + String systemTime = TimeOrDateUtil.timestampToTime(System.currentTimeMillis()); + + String resultString = result.split(":")[3]; + boolean isSuccess = !resultString.contains("no server suitable"); + if (isSuccess) { + setStateView(Color.GREEN); + stateView.setText("同步成功"); + timeValueLabel.setText(systemTime); + //同步成功之后将时间存入本地 + StringHelper.saveAssertsData(systemTime); + } else { + setStateView(Color.RED); + stateView.setText("同步失败"); + timeValueLabel.setText(""); + } + //POST提交 + JSONObject object = new JSONObject(); + try { + object.put("deviceIp", localHostBox.getSelectedItem()); + object.put("ntpResult", result); + + String[] dataSplit = resultString.split(" "); + object.put("deltaTime", dataSplit[6]); + object.put("createTime", systemTime); + if (autoCheckBox.isSelected()) { + object.put("frequency", periodComboBox.getSelectedItem()); + } else { + object.put("frequency", ""); + } + } catch (JSONException e) { + e.printStackTrace(); + } + Request request = new Request.Builder() + .url("http://" + server + "/ntp/saveResult") + .post(HttpRequestHelper.createRequestBody(object.toJSONString())) + .build(); + HttpRequestHelper.doPost(request, new IHttpCallback() { + + @Override + public void onSuccess(String s) { + + } + + @Override + public void onFailure(Exception e) { + e.printStackTrace(); + } + }); + } + } + + private void setStateView(Color color) { + dotPanel.setPreferredSize(new Dimension(15, 15)); + dotPanel.setBackground(color); + } +} diff --git a/src/main/java/com/casic/swing/utils/CommandUtil.java b/src/main/java/com/casic/swing/utils/CommandUtil.java new file mode 100644 index 0000000..2515971 --- /dev/null +++ b/src/main/java/com/casic/swing/utils/CommandUtil.java @@ -0,0 +1,77 @@ +package com.casic.swing.utils; + +import java.io.BufferedReader; +import java.io.IOException; +import java.io.InputStream; +import java.io.InputStreamReader; +import java.nio.charset.Charset; +import java.util.concurrent.TimeUnit; + +/** + * @author a203 + */ +public class CommandUtil { + /** + * 检查当前系统是否已安装NTP + */ + public static boolean checkEnv() { + System.out.println("检查当前系统是否支持NTP"); + try { +// Process exec = Runtime.getRuntime().exec("ls"); + Process exec = Runtime.getRuntime().exec("rpm -q ntp"); + try { + //等待命令执行完成 + exec.waitFor(5, TimeUnit.SECONDS); + } catch (InterruptedException e) { + e.printStackTrace(); + } + String result = parseResult(exec.getInputStream()); + return !result.isEmpty(); + } catch (IOException e) { + e.printStackTrace(); + } + return false; + } + + /** + * 安装NTP + * yum -y install ntp + * */ + + /** + * 授时同步 + * ntpdate -u ntp.api.bz + */ + public static String ntpDate(String host) { + try { + String command = "ntpdate -u " + host; + System.out.println("授时同步 ===> " + command); + Process exec = Runtime.getRuntime().exec(command); + try { + //等待命令执行完成 + exec.waitFor(5, TimeUnit.SECONDS); + } catch (InterruptedException e) { + e.printStackTrace(); + } + return parseResult(exec.getInputStream()); + } catch (IOException e) { + e.printStackTrace(); + } + return ""; + } + + /** + * 解析命令结果 + */ + private static String parseResult(InputStream inputStream) throws IOException { + // 读取输出流内容 + InputStreamReader streamReader = new InputStreamReader(inputStream, Charset.defaultCharset()); + BufferedReader reader = new BufferedReader(streamReader); + StringBuilder builder = new StringBuilder(); + String line; + while ((line = reader.readLine()) != null) { + builder.append(line).append("\n"); + } + return builder.toString(); + } +} diff --git a/src/main/java/com/casic/swing/utils/Constant.java b/src/main/java/com/casic/swing/utils/Constant.java new file mode 100644 index 0000000..f4a6742 --- /dev/null +++ b/src/main/java/com/casic/swing/utils/Constant.java @@ -0,0 +1,13 @@ +package com.casic.swing.utils; + +/** + * @author a203 + */ +public class Constant { + public static final String[] HOST_NAME = {"NTP服务器(上海)", "中国国家授时中心", "清华大学", "北京大学", "自定义"}; + public static final String[] HOST_IP = {"ntp.api.bz", "ntp.ntsc.ac.cn", "s1b.time.edu.cn", "s2m.time.edu.cn"}; + /** + * 同步周期,单位:分钟 + */ + public static final Integer[] PERIOD = {10, 20, 30}; +} diff --git a/src/main/java/com/casic/swing/utils/HttpRequestHelper.java b/src/main/java/com/casic/swing/utils/HttpRequestHelper.java new file mode 100644 index 0000000..ae7f057 --- /dev/null +++ b/src/main/java/com/casic/swing/utils/HttpRequestHelper.java @@ -0,0 +1,78 @@ +package com.casic.swing.utils; + +import okhttp3.*; +import org.jetbrains.annotations.NotNull; + +import java.io.IOException; +import java.net.Inet4Address; +import java.net.InetAddress; +import java.net.NetworkInterface; +import java.net.SocketException; +import java.util.ArrayList; +import java.util.Enumeration; +import java.util.List; +import java.util.Objects; +import java.util.concurrent.TimeUnit; + +/** + * @author a203 + */ +public class HttpRequestHelper { + public static RequestBody createRequestBody(String value) { + return RequestBody.create(MediaType.parse("application/json; charset=utf-8"), value); + } + + public static void doPost(Request request, IHttpCallback httpCallback) { + OkHttpClient httpClient = new OkHttpClient.Builder() + .connectTimeout(15, TimeUnit.SECONDS) + .writeTimeout(15, TimeUnit.SECONDS) + .readTimeout(15, TimeUnit.SECONDS) + .build(); + Call call = httpClient.newCall(request); + call.enqueue(new Callback() { + @Override + public void onFailure(@NotNull Call call, @NotNull IOException e) { + + } + + @Override + public void onResponse(@NotNull Call call, @NotNull Response response) throws IOException { + try { + if (response.body() != null) { + String string = Objects.requireNonNull(response.body()).string(); + httpCallback.onSuccess(string); + } else { + httpCallback.onFailure(new NullPointerException()); + } + } catch (IOException e) { + httpCallback.onFailure(e); + } + } + }); + } + + public static List localHost() { + List addressList = new ArrayList<>(); + try { + Enumeration interfaces = NetworkInterface.getNetworkInterfaces(); + InetAddress ip; + while (interfaces.hasMoreElements()) { + NetworkInterface netInterface = interfaces.nextElement(); + if (netInterface.isLoopback() || netInterface.isVirtual() || !netInterface.isUp()) { + continue; + } else { + Enumeration addresses = netInterface.getInetAddresses(); + while (addresses.hasMoreElements()) { + ip = addresses.nextElement(); + if (ip instanceof Inet4Address) { + addressList.add(ip); + } + } + } + } + } catch (SocketException e) { + e.printStackTrace(); + } + return addressList; + } +} diff --git a/src/main/java/com/casic/swing/utils/IHttpCallback.java b/src/main/java/com/casic/swing/utils/IHttpCallback.java new file mode 100644 index 0000000..fc01a75 --- /dev/null +++ b/src/main/java/com/casic/swing/utils/IHttpCallback.java @@ -0,0 +1,20 @@ +package com.casic.swing.utils; + +/** + * @author a203 + */ +public interface IHttpCallback { + /** + * 接口请求成功 + * + * @param s + */ + void onSuccess(String s); + + /** + * 接口请求失败 + * + * @param e + */ + void onFailure(Exception e); +} diff --git a/.gitignore b/.gitignore index 0841741..5027de1 100644 --- a/.gitignore +++ b/.gitignore @@ -1,2 +1,4 @@ .idea /out +/logs +/target diff --git a/CasicTimeGuard.iml b/CasicTimeGuard.iml index f54a89f..40532bb 100644 --- a/CasicTimeGuard.iml +++ b/CasicTimeGuard.iml @@ -1,12 +1,29 @@ - - - + + + + - + + + + - + + + + + + + + + + + + + + \ No newline at end of file diff --git a/lib/guava-18.0.jar b/lib/guava-18.0.jar deleted file mode 100644 index 8f89e49..0000000 --- a/lib/guava-18.0.jar +++ /dev/null Binary files differ diff --git a/pom.xml b/pom.xml new file mode 100644 index 0000000..3be19b5 --- /dev/null +++ b/pom.xml @@ -0,0 +1,44 @@ + + + 4.0.0 + + com.casic + CasicTimeGuard + 1.0-SNAPSHOT + + + 8 + 8 + 1.8 + + + + + org.projectlombok + lombok + 1.18.22 + true + + + + com.alibaba + fastjson + 1.2.79 + + + + + com.google.guava + guava + 31.0.1-jre + + + + com.squareup.okhttp3 + okhttp + 4.9.3 + + + \ No newline at end of file diff --git a/src/com/casic/swing/ui/TimeGuardNtp.form b/src/com/casic/swing/ui/TimeGuardNtp.form deleted file mode 100644 index cdba6f6..0000000 --- a/src/com/casic/swing/ui/TimeGuardNtp.form +++ /dev/null @@ -1,171 +0,0 @@ - -
- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - diff --git a/src/com/casic/swing/ui/TimeGuardNtp.java b/src/com/casic/swing/ui/TimeGuardNtp.java deleted file mode 100644 index 6df5b55..0000000 --- a/src/com/casic/swing/ui/TimeGuardNtp.java +++ /dev/null @@ -1,207 +0,0 @@ -package com.casic.swing.ui; - -import com.casic.swing.utils.CommandUtil; -import com.casic.swing.utils.StringHelper; -import com.casic.swing.utils.TimeOrDateUtil; -import com.google.common.util.concurrent.ThreadFactoryBuilder; - -import javax.swing.*; -import java.awt.*; -import java.awt.event.ActionEvent; -import java.awt.event.ActionListener; -import java.awt.event.ItemEvent; -import java.awt.event.ItemListener; -import java.util.concurrent.ScheduledExecutorService; -import java.util.concurrent.ScheduledThreadPoolExecutor; -import java.util.concurrent.TimeUnit; - -/** - * @author a203 - */ -public class TimeGuardNtp extends JFrame { - private JPanel ntpPanel; - private JComboBox hostComboBox; - private JLabel timeValueLabel; - private JButton updateTimeButton; - private JLabel dotView; - private JLabel currentTimeLabel; - private JCheckBox autoCheckBox; - private JComboBox periodComboBox; - private JPanel stateView; - - private final String[] HOST_NAME = {"NTP服务器(上海)", "中国国家授时中心", "清华大学", "北京大学", "自定义"}; - private final String[] HOST_IP = {"ntp.api.bz", "ntp.ntsc.ac.cn", "s1b.time.edu.cn", "s2m.time.edu.cn"}; - /** - * 同步周期,单位:小时 - */ - private final Integer[] PERIOD = {10, 20, 30}; - private final ScheduledExecutorService executorService = new ScheduledThreadPoolExecutor( - 1, new ThreadFactoryBuilder().setNameFormat("demo-pool-%d").build()); - private boolean hasNtp = false; - private String host = HOST_IP[0]; - - public static void main(String[] args) { - new TimeGuardNtp(); - } - - public TimeGuardNtp() { - setContentPane(ntpPanel); - setResizable(false); - setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); - pack(); - setSize(410, 280); - //居中 - setLocationRelativeTo(null); - setVisible(true); - dotView.setText("未同步"); - setStateView(Color.GRAY); - - StringHelper.createLogFile(); - - /** - * 时间间隔,单位为毫秒 - * */ - currentTimeLabel.setForeground(Color.BLUE); - new Timer(1000, new ActionListener() { - @Override - public void actionPerformed(ActionEvent e) { - String systemTime = TimeOrDateUtil.timestampToTime(System.currentTimeMillis()); - currentTimeLabel.setText(systemTime); - } - }).start(); - - String assertsData = StringHelper.getAssertsData(); - if (!"".equals(assertsData)) { - timeValueLabel.setText(assertsData); - } else { - timeValueLabel.setText("无法确定最近同步时间"); - } - - //初始化JComboBox - initComBox(); - hostComboBox.addItemListener(new ItemListener() { - @Override - public void itemStateChanged(ItemEvent e) { - String item = (String) e.getItem(); - if (e.getStateChange() == ItemEvent.SELECTED) { - if ("自定义".equals(item)) { - String inputContent = JOptionPane.showInputDialog(ntpPanel, "请输入授时中心域名或者IP地址", "", JOptionPane.INFORMATION_MESSAGE); - if (inputContent.isEmpty()) { - JOptionPane.showMessageDialog(ntpPanel, "输入错误,请检查", "Runtime Error", JOptionPane.ERROR_MESSAGE); - } else { - host = inputContent; - } - } else { - for (int i = 0; i < HOST_NAME.length; i++) { - if (item.equals(HOST_NAME[i])) { - host = HOST_IP[i]; - } - } - } - } - } - }); - - //检查环境 - new SwingWorker() { - - @Override - protected Boolean doInBackground() { - hasNtp = CommandUtil.checkEnv(); - return hasNtp; - } - - @Override - protected void done() { - if (!hasNtp) { - JOptionPane.showMessageDialog(ntpPanel, "未当前设备发现可用的NTP配置", "Runtime Error", JOptionPane.ERROR_MESSAGE); - //环境不对,关闭窗体 - dispose(); - } - super.done(); - } - }.execute(); - - autoCheckBox.addActionListener(new ActionListener() { - @Override - public void actionPerformed(ActionEvent e) { - JCheckBox checkBox = (JCheckBox) e.getSource(); - if (checkBox.isSelected()) { - updateTimeButton.setEnabled(false); - periodComboBox.setEnabled(true); - startAutoSynchronize(PERIOD[0]); - } else { - updateTimeButton.setEnabled(true); - periodComboBox.setEnabled(false); - } - } - }); - - periodComboBox.addItemListener(new ItemListener() { - @Override - public void itemStateChanged(ItemEvent e) { - int period = (Integer) e.getItem(); - if (e.getStateChange() == ItemEvent.SELECTED) { - startAutoSynchronize(period); - } - } - }); - - //按钮点击事件 - updateTimeButton.addActionListener(new ActionListener() { - @Override - public void actionPerformed(ActionEvent e) { - updateView(); - } - }); - } - - private void startAutoSynchronize(int period) { - /** - * 开启同步,只能开启一个同步线程 - * - * scheduleAtFixedRate - * 是以上一个任务开始的时间计时,period时间过去后,检测上一个任务是否执行完毕 - * 如果上一个任务执行完毕,则当前任务立即执行 - * 如果上一个任务没有执行完毕,则需要等上一个任务执行完毕后立即执行 - * */ - executorService.scheduleAtFixedRate(new Runnable() { - @Override - public void run() { - updateView(); - } - }, 0, period, TimeUnit.MINUTES); - } - - private void updateView() { - String result = CommandUtil.ntpDate(host); - System.out.println("命令执行结果 ===> " + result); - boolean isSuccess = result.contains("step time server") || result.contains("adjust time server"); - if (isSuccess) { - String systemTime = TimeOrDateUtil.timestampToTime(System.currentTimeMillis()); - setStateView(Color.GREEN); - dotView.setText("同步成功"); - timeValueLabel.setText(systemTime); - //同步成功之后将时间存入本地 - StringHelper.saveAssertsData(systemTime); - } else { - setStateView(Color.RED); - dotView.setText("同步失败"); - timeValueLabel.setText(""); - } - } - - private void initComBox() { - for (String s : HOST_NAME) { - hostComboBox.addItem(s); - } - for (Integer integer : PERIOD) { - periodComboBox.addItem(integer); - } - } - - private void setStateView(Color color) { - stateView.setPreferredSize(new Dimension(15, 15)); - stateView.setBackground(color); - } -} diff --git a/src/com/casic/swing/utils/CommandUtil.java b/src/com/casic/swing/utils/CommandUtil.java deleted file mode 100644 index c487e7d..0000000 --- a/src/com/casic/swing/utils/CommandUtil.java +++ /dev/null @@ -1,76 +0,0 @@ -package com.casic.swing.utils; - -import java.io.BufferedReader; -import java.io.IOException; -import java.io.InputStream; -import java.io.InputStreamReader; -import java.nio.charset.Charset; -import java.util.concurrent.TimeUnit; - -/** - * @author a203 - */ -public class CommandUtil { - /** - * 检查当前系统是否已安装NTP - */ - public static boolean checkEnv() { - System.out.println("检查当前系统是否支持NTP"); - try { - Process exec = Runtime.getRuntime().exec("rpm -q ntp"); - try { - //等待命令执行完成 - exec.waitFor(5, TimeUnit.SECONDS); - } catch (InterruptedException e) { - e.printStackTrace(); - } - String result = parseResult(exec.getInputStream()); - return !result.isEmpty(); - } catch (IOException e) { - e.printStackTrace(); - } - return false; - } - - /** - * 安装NTP - * yum -y install ntp - * */ - - /** - * 授时同步 - * ntpdate -u ntp.api.bz - */ - public static String ntpDate(String host) { - try { - String command = "ntpdate -u " + host; - System.out.println("授时同步 ===> " + command); - Process exec = Runtime.getRuntime().exec(command); - try { - //等待命令执行完成 - exec.waitFor(5, TimeUnit.SECONDS); - } catch (InterruptedException e) { - e.printStackTrace(); - } - return parseResult(exec.getInputStream()); - } catch (IOException e) { - e.printStackTrace(); - } - return ""; - } - - /** - * 解析命令结果 - */ - private static String parseResult(InputStream inputStream) throws IOException { - // 读取输出流内容 - InputStreamReader streamReader = new InputStreamReader(inputStream, Charset.defaultCharset()); - BufferedReader reader = new BufferedReader(streamReader); - StringBuilder builder = new StringBuilder(); - String line; - while ((line = reader.readLine()) != null) { - builder.append(line).append("\n"); - } - return builder.toString(); - } -} diff --git a/src/com/casic/swing/utils/StringHelper.java b/src/com/casic/swing/utils/StringHelper.java deleted file mode 100644 index b994e19..0000000 --- a/src/com/casic/swing/utils/StringHelper.java +++ /dev/null @@ -1,64 +0,0 @@ -package com.casic.swing.utils; - -import javax.swing.filechooser.FileSystemView; -import java.io.*; - -/** - * @author a203 - */ -public class StringHelper { - - private static final String FILE_NAME = "update.log"; - private static File logFile; - - public static void createLogFile() { - FileSystemView view = FileSystemView.getFileSystemView(); - File file = view.getHomeDirectory(); - File dir = new File(file.getAbsolutePath() + File.separator + "logs"); - if (!dir.exists()) { - dir.mkdir(); - } - logFile = new File(dir + File.separator + FILE_NAME); - if (!logFile.exists()) { - // 创建新文件,有同名的文件的话直接覆盖 - try { - logFile.createNewFile(); - } catch (IOException e) { - e.printStackTrace(); - } - } - System.out.println("同步记录路径 ===> " + logFile.getAbsolutePath()); - } - - public static void saveAssertsData(String data) { - try { - FileWriter writer = new FileWriter(logFile); - BufferedWriter out = new BufferedWriter(writer); - out.write(data); - out.flush(); - out.close(); - } catch (IOException e) { - e.printStackTrace(); - } - } - - public static String getAssertsData() { - try { - InputStreamReader inputStreamReader = new InputStreamReader(new FileInputStream(logFile)); - BufferedReader bufferedReader = new BufferedReader(inputStreamReader); - StringBuilder data = new StringBuilder(); - String s; - try { - while ((s = bufferedReader.readLine()) != null) { - data.append(s); - } - return data.toString(); - } catch (IOException e) { - e.printStackTrace(); - } - } catch (IOException e) { - e.printStackTrace(); - } - return ""; - } -} diff --git a/src/com/casic/swing/utils/TimeOrDateUtil.java b/src/com/casic/swing/utils/TimeOrDateUtil.java deleted file mode 100644 index 7adc5a6..0000000 --- a/src/com/casic/swing/utils/TimeOrDateUtil.java +++ /dev/null @@ -1,18 +0,0 @@ -package com.casic.swing.utils; - -import java.text.SimpleDateFormat; -import java.util.Date; - -/** - * @author a203 - */ -public class TimeOrDateUtil { - - /** - * 时间戳转时间 - */ - public static String timestampToTime(long millSeconds) { - SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); - return format.format(new Date(millSeconds)); - } -} diff --git a/src/main/java/com/casic/swing/ui/TimeGuardNtp.form b/src/main/java/com/casic/swing/ui/TimeGuardNtp.form new file mode 100644 index 0000000..8732b4b --- /dev/null +++ b/src/main/java/com/casic/swing/ui/TimeGuardNtp.form @@ -0,0 +1,207 @@ + +
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/src/main/java/com/casic/swing/ui/TimeGuardNtp.java b/src/main/java/com/casic/swing/ui/TimeGuardNtp.java new file mode 100644 index 0000000..9c7fef7 --- /dev/null +++ b/src/main/java/com/casic/swing/ui/TimeGuardNtp.java @@ -0,0 +1,239 @@ +package com.casic.swing.ui; + +import com.alibaba.fastjson.JSONException; +import com.alibaba.fastjson.JSONObject; +import com.casic.swing.utils.*; +import com.google.common.util.concurrent.ThreadFactoryBuilder; +import okhttp3.Request; + +import javax.swing.*; +import java.awt.*; +import java.awt.event.ActionEvent; +import java.awt.event.ActionListener; +import java.awt.event.ItemEvent; +import java.awt.event.ItemListener; +import java.net.InetAddress; +import java.util.concurrent.ScheduledExecutorService; +import java.util.concurrent.ScheduledThreadPoolExecutor; +import java.util.concurrent.TimeUnit; + +/** + * @author a203 + */ +public class TimeGuardNtp extends JFrame { + private JPanel ntpPanel; + private JLabel timeValueLabel; + private JButton updateTimeButton; + private JLabel currentTimeLabel; + private JCheckBox autoCheckBox; + private JComboBox periodComboBox; + private JLabel stateView; + private JPanel dotPanel; + private JTextField hostTextField; + private JComboBox localHostBox; + private JTextField serverTextField; + + private final ScheduledExecutorService executorService = new ScheduledThreadPoolExecutor( + 1, new ThreadFactoryBuilder().setNameFormat("demo-pool-%d").build()); + private boolean hasNtp = false; + + public static void main(String[] args) { + new TimeGuardNtp(); + } + + public TimeGuardNtp() { + setContentPane(ntpPanel); + setResizable(false); + setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); + pack(); + setSize(400, 330); + //居中 + setLocationRelativeTo(null); + setVisible(true); + stateView.setText("未同步"); + setStateView(Color.GRAY); + + StringHelper.createLogFile(); + + /** + * 时间间隔,单位为毫秒 + * */ + currentTimeLabel.setForeground(Color.BLUE); + new Timer(1000, new ActionListener() { + @Override + public void actionPerformed(ActionEvent e) { + String systemTime = TimeOrDateUtil.timestampToTime(System.currentTimeMillis()); + currentTimeLabel.setText(systemTime); + } + }).start(); + + String assertsData = StringHelper.getAssertsData(); + if (!"".equals(assertsData)) { + timeValueLabel.setText(assertsData); + } else { + timeValueLabel.setText("无法确定最近同步时间"); + } + + //初始化JComboBox + for (Integer integer : Constant.PERIOD) { + periodComboBox.addItem(integer); + } + java.util.List addressList = HttpRequestHelper.localHost(); + for (InetAddress address : addressList) { + localHostBox.addItem(address.getHostAddress()); + } + + //检查环境 +// new SwingWorker() { +// +// @Override +// protected Boolean doInBackground() { +// hasNtp = CommandUtil.checkEnv(); +// return hasNtp; +// } +// +// @Override +// protected void done() { +// if (!hasNtp) { +// JOptionPane.showMessageDialog(ntpPanel, "未当前设备发现可用的NTP配置", "Runtime Error", JOptionPane.ERROR_MESSAGE); +// //环境不对,关闭窗体 +// dispose(); +// } +// super.done(); +// } +// }.execute(); + + autoCheckBox.addActionListener(new ActionListener() { + @Override + public void actionPerformed(ActionEvent e) { + JCheckBox checkBox = (JCheckBox) e.getSource(); + if (checkBox.isSelected()) { + updateTimeButton.setEnabled(false); + periodComboBox.setEnabled(true); + hostTextField.setEnabled(false); + serverTextField.setEnabled(false); + startAutoSynchronize(Constant.PERIOD[0]); + } else { + updateTimeButton.setEnabled(true); + periodComboBox.setEnabled(false); + hostTextField.setEnabled(true); + serverTextField.setEnabled(true); + } + } + }); + + periodComboBox.addItemListener(new ItemListener() { + @Override + public void itemStateChanged(ItemEvent e) { + int period = (Integer) e.getItem(); + if (e.getStateChange() == ItemEvent.SELECTED) { + startAutoSynchronize(period); + } + } + }); + + //按钮点击事件 + updateTimeButton.addActionListener(new ActionListener() { + @Override + public void actionPerformed(ActionEvent e) { + updateView(); + } + }); + } + + private void startAutoSynchronize(int period) { + /** + * 开启同步,只能开启一个同步线程 + * + * scheduleAtFixedRate + * 是以上一个任务开始的时间计时,period时间过去后,检测上一个任务是否执行完毕 + * 如果上一个任务执行完毕,则当前任务立即执行 + * 如果上一个任务没有执行完毕,则需要等上一个任务执行完毕后立即执行 + * */ + executorService.scheduleAtFixedRate(new Runnable() { + @Override + public void run() { + updateView(); + } + }, 0, period, TimeUnit.MINUTES); + } + + private void updateView() { + String host = hostTextField.getText().trim(); + if (host.isEmpty()) { + autoCheckBox.setSelected(false); + JOptionPane.showMessageDialog(ntpPanel, "授时中心服务器输入错误,请检查", "Runtime Error", JOptionPane.ERROR_MESSAGE); + return; + } + String server = serverTextField.getText().trim(); + if (server.isEmpty()) { + autoCheckBox.setSelected(false); + JOptionPane.showMessageDialog(ntpPanel, "后台服务器地址输入错误,请检查", "Runtime Error", JOptionPane.ERROR_MESSAGE); + return; + } +// String result = "5 Jan 11:20:24 ntpdate[807910]: adjust time server 114.118.7.161 offset -0.004064 sec"; +// String result = "5 Jan 11:24:06 ntpdate[824403]: no server suitable for synchronization found"; + String result = CommandUtil.ntpDate(host); + System.out.println("命令执行结果 ===> " + result); + + if ("".equals(result)) { + setStateView(Color.RED); + stateView.setText("同步失败"); + timeValueLabel.setText(""); + } else { + String systemTime = TimeOrDateUtil.timestampToTime(System.currentTimeMillis()); + + String resultString = result.split(":")[3]; + boolean isSuccess = !resultString.contains("no server suitable"); + if (isSuccess) { + setStateView(Color.GREEN); + stateView.setText("同步成功"); + timeValueLabel.setText(systemTime); + //同步成功之后将时间存入本地 + StringHelper.saveAssertsData(systemTime); + } else { + setStateView(Color.RED); + stateView.setText("同步失败"); + timeValueLabel.setText(""); + } + //POST提交 + JSONObject object = new JSONObject(); + try { + object.put("deviceIp", localHostBox.getSelectedItem()); + object.put("ntpResult", result); + + String[] dataSplit = resultString.split(" "); + object.put("deltaTime", dataSplit[6]); + object.put("createTime", systemTime); + if (autoCheckBox.isSelected()) { + object.put("frequency", periodComboBox.getSelectedItem()); + } else { + object.put("frequency", ""); + } + } catch (JSONException e) { + e.printStackTrace(); + } + Request request = new Request.Builder() + .url("http://" + server + "/ntp/saveResult") + .post(HttpRequestHelper.createRequestBody(object.toJSONString())) + .build(); + HttpRequestHelper.doPost(request, new IHttpCallback() { + + @Override + public void onSuccess(String s) { + + } + + @Override + public void onFailure(Exception e) { + e.printStackTrace(); + } + }); + } + } + + private void setStateView(Color color) { + dotPanel.setPreferredSize(new Dimension(15, 15)); + dotPanel.setBackground(color); + } +} diff --git a/src/main/java/com/casic/swing/utils/CommandUtil.java b/src/main/java/com/casic/swing/utils/CommandUtil.java new file mode 100644 index 0000000..2515971 --- /dev/null +++ b/src/main/java/com/casic/swing/utils/CommandUtil.java @@ -0,0 +1,77 @@ +package com.casic.swing.utils; + +import java.io.BufferedReader; +import java.io.IOException; +import java.io.InputStream; +import java.io.InputStreamReader; +import java.nio.charset.Charset; +import java.util.concurrent.TimeUnit; + +/** + * @author a203 + */ +public class CommandUtil { + /** + * 检查当前系统是否已安装NTP + */ + public static boolean checkEnv() { + System.out.println("检查当前系统是否支持NTP"); + try { +// Process exec = Runtime.getRuntime().exec("ls"); + Process exec = Runtime.getRuntime().exec("rpm -q ntp"); + try { + //等待命令执行完成 + exec.waitFor(5, TimeUnit.SECONDS); + } catch (InterruptedException e) { + e.printStackTrace(); + } + String result = parseResult(exec.getInputStream()); + return !result.isEmpty(); + } catch (IOException e) { + e.printStackTrace(); + } + return false; + } + + /** + * 安装NTP + * yum -y install ntp + * */ + + /** + * 授时同步 + * ntpdate -u ntp.api.bz + */ + public static String ntpDate(String host) { + try { + String command = "ntpdate -u " + host; + System.out.println("授时同步 ===> " + command); + Process exec = Runtime.getRuntime().exec(command); + try { + //等待命令执行完成 + exec.waitFor(5, TimeUnit.SECONDS); + } catch (InterruptedException e) { + e.printStackTrace(); + } + return parseResult(exec.getInputStream()); + } catch (IOException e) { + e.printStackTrace(); + } + return ""; + } + + /** + * 解析命令结果 + */ + private static String parseResult(InputStream inputStream) throws IOException { + // 读取输出流内容 + InputStreamReader streamReader = new InputStreamReader(inputStream, Charset.defaultCharset()); + BufferedReader reader = new BufferedReader(streamReader); + StringBuilder builder = new StringBuilder(); + String line; + while ((line = reader.readLine()) != null) { + builder.append(line).append("\n"); + } + return builder.toString(); + } +} diff --git a/src/main/java/com/casic/swing/utils/Constant.java b/src/main/java/com/casic/swing/utils/Constant.java new file mode 100644 index 0000000..f4a6742 --- /dev/null +++ b/src/main/java/com/casic/swing/utils/Constant.java @@ -0,0 +1,13 @@ +package com.casic.swing.utils; + +/** + * @author a203 + */ +public class Constant { + public static final String[] HOST_NAME = {"NTP服务器(上海)", "中国国家授时中心", "清华大学", "北京大学", "自定义"}; + public static final String[] HOST_IP = {"ntp.api.bz", "ntp.ntsc.ac.cn", "s1b.time.edu.cn", "s2m.time.edu.cn"}; + /** + * 同步周期,单位:分钟 + */ + public static final Integer[] PERIOD = {10, 20, 30}; +} diff --git a/src/main/java/com/casic/swing/utils/HttpRequestHelper.java b/src/main/java/com/casic/swing/utils/HttpRequestHelper.java new file mode 100644 index 0000000..ae7f057 --- /dev/null +++ b/src/main/java/com/casic/swing/utils/HttpRequestHelper.java @@ -0,0 +1,78 @@ +package com.casic.swing.utils; + +import okhttp3.*; +import org.jetbrains.annotations.NotNull; + +import java.io.IOException; +import java.net.Inet4Address; +import java.net.InetAddress; +import java.net.NetworkInterface; +import java.net.SocketException; +import java.util.ArrayList; +import java.util.Enumeration; +import java.util.List; +import java.util.Objects; +import java.util.concurrent.TimeUnit; + +/** + * @author a203 + */ +public class HttpRequestHelper { + public static RequestBody createRequestBody(String value) { + return RequestBody.create(MediaType.parse("application/json; charset=utf-8"), value); + } + + public static void doPost(Request request, IHttpCallback httpCallback) { + OkHttpClient httpClient = new OkHttpClient.Builder() + .connectTimeout(15, TimeUnit.SECONDS) + .writeTimeout(15, TimeUnit.SECONDS) + .readTimeout(15, TimeUnit.SECONDS) + .build(); + Call call = httpClient.newCall(request); + call.enqueue(new Callback() { + @Override + public void onFailure(@NotNull Call call, @NotNull IOException e) { + + } + + @Override + public void onResponse(@NotNull Call call, @NotNull Response response) throws IOException { + try { + if (response.body() != null) { + String string = Objects.requireNonNull(response.body()).string(); + httpCallback.onSuccess(string); + } else { + httpCallback.onFailure(new NullPointerException()); + } + } catch (IOException e) { + httpCallback.onFailure(e); + } + } + }); + } + + public static List localHost() { + List addressList = new ArrayList<>(); + try { + Enumeration interfaces = NetworkInterface.getNetworkInterfaces(); + InetAddress ip; + while (interfaces.hasMoreElements()) { + NetworkInterface netInterface = interfaces.nextElement(); + if (netInterface.isLoopback() || netInterface.isVirtual() || !netInterface.isUp()) { + continue; + } else { + Enumeration addresses = netInterface.getInetAddresses(); + while (addresses.hasMoreElements()) { + ip = addresses.nextElement(); + if (ip instanceof Inet4Address) { + addressList.add(ip); + } + } + } + } + } catch (SocketException e) { + e.printStackTrace(); + } + return addressList; + } +} diff --git a/src/main/java/com/casic/swing/utils/IHttpCallback.java b/src/main/java/com/casic/swing/utils/IHttpCallback.java new file mode 100644 index 0000000..fc01a75 --- /dev/null +++ b/src/main/java/com/casic/swing/utils/IHttpCallback.java @@ -0,0 +1,20 @@ +package com.casic.swing.utils; + +/** + * @author a203 + */ +public interface IHttpCallback { + /** + * 接口请求成功 + * + * @param s + */ + void onSuccess(String s); + + /** + * 接口请求失败 + * + * @param e + */ + void onFailure(Exception e); +} diff --git a/src/main/java/com/casic/swing/utils/StringHelper.java b/src/main/java/com/casic/swing/utils/StringHelper.java new file mode 100644 index 0000000..53797ee --- /dev/null +++ b/src/main/java/com/casic/swing/utils/StringHelper.java @@ -0,0 +1,60 @@ +package com.casic.swing.utils; + +import java.io.*; + +/** + * @author a203 + */ +public class StringHelper { + + private static File logFile; + + public static void createLogFile() { + File rootDir = new File(System.getProperty("user.dir") + File.separator + "logs"); + if (!rootDir.exists()) { + rootDir.mkdir(); + } + logFile = new File(rootDir + File.separator + "update.log"); + if (!logFile.exists()) { + // 创建新文件,有同名的文件的话直接覆盖 + try { + logFile.createNewFile(); + } catch (IOException e) { + e.printStackTrace(); + } + } + System.out.println("同步记录路径 ===> " + logFile.getAbsolutePath()); + } + + public static void saveAssertsData(String data) { + try { + FileWriter writer = new FileWriter(logFile); + BufferedWriter out = new BufferedWriter(writer); + out.write(data); + out.flush(); + out.close(); + } catch (IOException e) { + e.printStackTrace(); + } + } + + public static String getAssertsData() { + try { + InputStreamReader inputStreamReader = new InputStreamReader(new FileInputStream(logFile)); + BufferedReader bufferedReader = new BufferedReader(inputStreamReader); + StringBuilder data = new StringBuilder(); + String s; + try { + while ((s = bufferedReader.readLine()) != null) { + data.append(s); + } + return data.toString(); + } catch (IOException e) { + e.printStackTrace(); + } + } catch (IOException e) { + e.printStackTrace(); + } + return ""; + } +} diff --git a/.gitignore b/.gitignore index 0841741..5027de1 100644 --- a/.gitignore +++ b/.gitignore @@ -1,2 +1,4 @@ .idea /out +/logs +/target diff --git a/CasicTimeGuard.iml b/CasicTimeGuard.iml index f54a89f..40532bb 100644 --- a/CasicTimeGuard.iml +++ b/CasicTimeGuard.iml @@ -1,12 +1,29 @@ - - - + + + + - + + + + - + + + + + + + + + + + + + + \ No newline at end of file diff --git a/lib/guava-18.0.jar b/lib/guava-18.0.jar deleted file mode 100644 index 8f89e49..0000000 --- a/lib/guava-18.0.jar +++ /dev/null Binary files differ diff --git a/pom.xml b/pom.xml new file mode 100644 index 0000000..3be19b5 --- /dev/null +++ b/pom.xml @@ -0,0 +1,44 @@ + + + 4.0.0 + + com.casic + CasicTimeGuard + 1.0-SNAPSHOT + + + 8 + 8 + 1.8 + + + + + org.projectlombok + lombok + 1.18.22 + true + + + + com.alibaba + fastjson + 1.2.79 + + + + + com.google.guava + guava + 31.0.1-jre + + + + com.squareup.okhttp3 + okhttp + 4.9.3 + + + \ No newline at end of file diff --git a/src/com/casic/swing/ui/TimeGuardNtp.form b/src/com/casic/swing/ui/TimeGuardNtp.form deleted file mode 100644 index cdba6f6..0000000 --- a/src/com/casic/swing/ui/TimeGuardNtp.form +++ /dev/null @@ -1,171 +0,0 @@ - -
- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - diff --git a/src/com/casic/swing/ui/TimeGuardNtp.java b/src/com/casic/swing/ui/TimeGuardNtp.java deleted file mode 100644 index 6df5b55..0000000 --- a/src/com/casic/swing/ui/TimeGuardNtp.java +++ /dev/null @@ -1,207 +0,0 @@ -package com.casic.swing.ui; - -import com.casic.swing.utils.CommandUtil; -import com.casic.swing.utils.StringHelper; -import com.casic.swing.utils.TimeOrDateUtil; -import com.google.common.util.concurrent.ThreadFactoryBuilder; - -import javax.swing.*; -import java.awt.*; -import java.awt.event.ActionEvent; -import java.awt.event.ActionListener; -import java.awt.event.ItemEvent; -import java.awt.event.ItemListener; -import java.util.concurrent.ScheduledExecutorService; -import java.util.concurrent.ScheduledThreadPoolExecutor; -import java.util.concurrent.TimeUnit; - -/** - * @author a203 - */ -public class TimeGuardNtp extends JFrame { - private JPanel ntpPanel; - private JComboBox hostComboBox; - private JLabel timeValueLabel; - private JButton updateTimeButton; - private JLabel dotView; - private JLabel currentTimeLabel; - private JCheckBox autoCheckBox; - private JComboBox periodComboBox; - private JPanel stateView; - - private final String[] HOST_NAME = {"NTP服务器(上海)", "中国国家授时中心", "清华大学", "北京大学", "自定义"}; - private final String[] HOST_IP = {"ntp.api.bz", "ntp.ntsc.ac.cn", "s1b.time.edu.cn", "s2m.time.edu.cn"}; - /** - * 同步周期,单位:小时 - */ - private final Integer[] PERIOD = {10, 20, 30}; - private final ScheduledExecutorService executorService = new ScheduledThreadPoolExecutor( - 1, new ThreadFactoryBuilder().setNameFormat("demo-pool-%d").build()); - private boolean hasNtp = false; - private String host = HOST_IP[0]; - - public static void main(String[] args) { - new TimeGuardNtp(); - } - - public TimeGuardNtp() { - setContentPane(ntpPanel); - setResizable(false); - setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); - pack(); - setSize(410, 280); - //居中 - setLocationRelativeTo(null); - setVisible(true); - dotView.setText("未同步"); - setStateView(Color.GRAY); - - StringHelper.createLogFile(); - - /** - * 时间间隔,单位为毫秒 - * */ - currentTimeLabel.setForeground(Color.BLUE); - new Timer(1000, new ActionListener() { - @Override - public void actionPerformed(ActionEvent e) { - String systemTime = TimeOrDateUtil.timestampToTime(System.currentTimeMillis()); - currentTimeLabel.setText(systemTime); - } - }).start(); - - String assertsData = StringHelper.getAssertsData(); - if (!"".equals(assertsData)) { - timeValueLabel.setText(assertsData); - } else { - timeValueLabel.setText("无法确定最近同步时间"); - } - - //初始化JComboBox - initComBox(); - hostComboBox.addItemListener(new ItemListener() { - @Override - public void itemStateChanged(ItemEvent e) { - String item = (String) e.getItem(); - if (e.getStateChange() == ItemEvent.SELECTED) { - if ("自定义".equals(item)) { - String inputContent = JOptionPane.showInputDialog(ntpPanel, "请输入授时中心域名或者IP地址", "", JOptionPane.INFORMATION_MESSAGE); - if (inputContent.isEmpty()) { - JOptionPane.showMessageDialog(ntpPanel, "输入错误,请检查", "Runtime Error", JOptionPane.ERROR_MESSAGE); - } else { - host = inputContent; - } - } else { - for (int i = 0; i < HOST_NAME.length; i++) { - if (item.equals(HOST_NAME[i])) { - host = HOST_IP[i]; - } - } - } - } - } - }); - - //检查环境 - new SwingWorker() { - - @Override - protected Boolean doInBackground() { - hasNtp = CommandUtil.checkEnv(); - return hasNtp; - } - - @Override - protected void done() { - if (!hasNtp) { - JOptionPane.showMessageDialog(ntpPanel, "未当前设备发现可用的NTP配置", "Runtime Error", JOptionPane.ERROR_MESSAGE); - //环境不对,关闭窗体 - dispose(); - } - super.done(); - } - }.execute(); - - autoCheckBox.addActionListener(new ActionListener() { - @Override - public void actionPerformed(ActionEvent e) { - JCheckBox checkBox = (JCheckBox) e.getSource(); - if (checkBox.isSelected()) { - updateTimeButton.setEnabled(false); - periodComboBox.setEnabled(true); - startAutoSynchronize(PERIOD[0]); - } else { - updateTimeButton.setEnabled(true); - periodComboBox.setEnabled(false); - } - } - }); - - periodComboBox.addItemListener(new ItemListener() { - @Override - public void itemStateChanged(ItemEvent e) { - int period = (Integer) e.getItem(); - if (e.getStateChange() == ItemEvent.SELECTED) { - startAutoSynchronize(period); - } - } - }); - - //按钮点击事件 - updateTimeButton.addActionListener(new ActionListener() { - @Override - public void actionPerformed(ActionEvent e) { - updateView(); - } - }); - } - - private void startAutoSynchronize(int period) { - /** - * 开启同步,只能开启一个同步线程 - * - * scheduleAtFixedRate - * 是以上一个任务开始的时间计时,period时间过去后,检测上一个任务是否执行完毕 - * 如果上一个任务执行完毕,则当前任务立即执行 - * 如果上一个任务没有执行完毕,则需要等上一个任务执行完毕后立即执行 - * */ - executorService.scheduleAtFixedRate(new Runnable() { - @Override - public void run() { - updateView(); - } - }, 0, period, TimeUnit.MINUTES); - } - - private void updateView() { - String result = CommandUtil.ntpDate(host); - System.out.println("命令执行结果 ===> " + result); - boolean isSuccess = result.contains("step time server") || result.contains("adjust time server"); - if (isSuccess) { - String systemTime = TimeOrDateUtil.timestampToTime(System.currentTimeMillis()); - setStateView(Color.GREEN); - dotView.setText("同步成功"); - timeValueLabel.setText(systemTime); - //同步成功之后将时间存入本地 - StringHelper.saveAssertsData(systemTime); - } else { - setStateView(Color.RED); - dotView.setText("同步失败"); - timeValueLabel.setText(""); - } - } - - private void initComBox() { - for (String s : HOST_NAME) { - hostComboBox.addItem(s); - } - for (Integer integer : PERIOD) { - periodComboBox.addItem(integer); - } - } - - private void setStateView(Color color) { - stateView.setPreferredSize(new Dimension(15, 15)); - stateView.setBackground(color); - } -} diff --git a/src/com/casic/swing/utils/CommandUtil.java b/src/com/casic/swing/utils/CommandUtil.java deleted file mode 100644 index c487e7d..0000000 --- a/src/com/casic/swing/utils/CommandUtil.java +++ /dev/null @@ -1,76 +0,0 @@ -package com.casic.swing.utils; - -import java.io.BufferedReader; -import java.io.IOException; -import java.io.InputStream; -import java.io.InputStreamReader; -import java.nio.charset.Charset; -import java.util.concurrent.TimeUnit; - -/** - * @author a203 - */ -public class CommandUtil { - /** - * 检查当前系统是否已安装NTP - */ - public static boolean checkEnv() { - System.out.println("检查当前系统是否支持NTP"); - try { - Process exec = Runtime.getRuntime().exec("rpm -q ntp"); - try { - //等待命令执行完成 - exec.waitFor(5, TimeUnit.SECONDS); - } catch (InterruptedException e) { - e.printStackTrace(); - } - String result = parseResult(exec.getInputStream()); - return !result.isEmpty(); - } catch (IOException e) { - e.printStackTrace(); - } - return false; - } - - /** - * 安装NTP - * yum -y install ntp - * */ - - /** - * 授时同步 - * ntpdate -u ntp.api.bz - */ - public static String ntpDate(String host) { - try { - String command = "ntpdate -u " + host; - System.out.println("授时同步 ===> " + command); - Process exec = Runtime.getRuntime().exec(command); - try { - //等待命令执行完成 - exec.waitFor(5, TimeUnit.SECONDS); - } catch (InterruptedException e) { - e.printStackTrace(); - } - return parseResult(exec.getInputStream()); - } catch (IOException e) { - e.printStackTrace(); - } - return ""; - } - - /** - * 解析命令结果 - */ - private static String parseResult(InputStream inputStream) throws IOException { - // 读取输出流内容 - InputStreamReader streamReader = new InputStreamReader(inputStream, Charset.defaultCharset()); - BufferedReader reader = new BufferedReader(streamReader); - StringBuilder builder = new StringBuilder(); - String line; - while ((line = reader.readLine()) != null) { - builder.append(line).append("\n"); - } - return builder.toString(); - } -} diff --git a/src/com/casic/swing/utils/StringHelper.java b/src/com/casic/swing/utils/StringHelper.java deleted file mode 100644 index b994e19..0000000 --- a/src/com/casic/swing/utils/StringHelper.java +++ /dev/null @@ -1,64 +0,0 @@ -package com.casic.swing.utils; - -import javax.swing.filechooser.FileSystemView; -import java.io.*; - -/** - * @author a203 - */ -public class StringHelper { - - private static final String FILE_NAME = "update.log"; - private static File logFile; - - public static void createLogFile() { - FileSystemView view = FileSystemView.getFileSystemView(); - File file = view.getHomeDirectory(); - File dir = new File(file.getAbsolutePath() + File.separator + "logs"); - if (!dir.exists()) { - dir.mkdir(); - } - logFile = new File(dir + File.separator + FILE_NAME); - if (!logFile.exists()) { - // 创建新文件,有同名的文件的话直接覆盖 - try { - logFile.createNewFile(); - } catch (IOException e) { - e.printStackTrace(); - } - } - System.out.println("同步记录路径 ===> " + logFile.getAbsolutePath()); - } - - public static void saveAssertsData(String data) { - try { - FileWriter writer = new FileWriter(logFile); - BufferedWriter out = new BufferedWriter(writer); - out.write(data); - out.flush(); - out.close(); - } catch (IOException e) { - e.printStackTrace(); - } - } - - public static String getAssertsData() { - try { - InputStreamReader inputStreamReader = new InputStreamReader(new FileInputStream(logFile)); - BufferedReader bufferedReader = new BufferedReader(inputStreamReader); - StringBuilder data = new StringBuilder(); - String s; - try { - while ((s = bufferedReader.readLine()) != null) { - data.append(s); - } - return data.toString(); - } catch (IOException e) { - e.printStackTrace(); - } - } catch (IOException e) { - e.printStackTrace(); - } - return ""; - } -} diff --git a/src/com/casic/swing/utils/TimeOrDateUtil.java b/src/com/casic/swing/utils/TimeOrDateUtil.java deleted file mode 100644 index 7adc5a6..0000000 --- a/src/com/casic/swing/utils/TimeOrDateUtil.java +++ /dev/null @@ -1,18 +0,0 @@ -package com.casic.swing.utils; - -import java.text.SimpleDateFormat; -import java.util.Date; - -/** - * @author a203 - */ -public class TimeOrDateUtil { - - /** - * 时间戳转时间 - */ - public static String timestampToTime(long millSeconds) { - SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); - return format.format(new Date(millSeconds)); - } -} diff --git a/src/main/java/com/casic/swing/ui/TimeGuardNtp.form b/src/main/java/com/casic/swing/ui/TimeGuardNtp.form new file mode 100644 index 0000000..8732b4b --- /dev/null +++ b/src/main/java/com/casic/swing/ui/TimeGuardNtp.form @@ -0,0 +1,207 @@ + +
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/src/main/java/com/casic/swing/ui/TimeGuardNtp.java b/src/main/java/com/casic/swing/ui/TimeGuardNtp.java new file mode 100644 index 0000000..9c7fef7 --- /dev/null +++ b/src/main/java/com/casic/swing/ui/TimeGuardNtp.java @@ -0,0 +1,239 @@ +package com.casic.swing.ui; + +import com.alibaba.fastjson.JSONException; +import com.alibaba.fastjson.JSONObject; +import com.casic.swing.utils.*; +import com.google.common.util.concurrent.ThreadFactoryBuilder; +import okhttp3.Request; + +import javax.swing.*; +import java.awt.*; +import java.awt.event.ActionEvent; +import java.awt.event.ActionListener; +import java.awt.event.ItemEvent; +import java.awt.event.ItemListener; +import java.net.InetAddress; +import java.util.concurrent.ScheduledExecutorService; +import java.util.concurrent.ScheduledThreadPoolExecutor; +import java.util.concurrent.TimeUnit; + +/** + * @author a203 + */ +public class TimeGuardNtp extends JFrame { + private JPanel ntpPanel; + private JLabel timeValueLabel; + private JButton updateTimeButton; + private JLabel currentTimeLabel; + private JCheckBox autoCheckBox; + private JComboBox periodComboBox; + private JLabel stateView; + private JPanel dotPanel; + private JTextField hostTextField; + private JComboBox localHostBox; + private JTextField serverTextField; + + private final ScheduledExecutorService executorService = new ScheduledThreadPoolExecutor( + 1, new ThreadFactoryBuilder().setNameFormat("demo-pool-%d").build()); + private boolean hasNtp = false; + + public static void main(String[] args) { + new TimeGuardNtp(); + } + + public TimeGuardNtp() { + setContentPane(ntpPanel); + setResizable(false); + setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); + pack(); + setSize(400, 330); + //居中 + setLocationRelativeTo(null); + setVisible(true); + stateView.setText("未同步"); + setStateView(Color.GRAY); + + StringHelper.createLogFile(); + + /** + * 时间间隔,单位为毫秒 + * */ + currentTimeLabel.setForeground(Color.BLUE); + new Timer(1000, new ActionListener() { + @Override + public void actionPerformed(ActionEvent e) { + String systemTime = TimeOrDateUtil.timestampToTime(System.currentTimeMillis()); + currentTimeLabel.setText(systemTime); + } + }).start(); + + String assertsData = StringHelper.getAssertsData(); + if (!"".equals(assertsData)) { + timeValueLabel.setText(assertsData); + } else { + timeValueLabel.setText("无法确定最近同步时间"); + } + + //初始化JComboBox + for (Integer integer : Constant.PERIOD) { + periodComboBox.addItem(integer); + } + java.util.List addressList = HttpRequestHelper.localHost(); + for (InetAddress address : addressList) { + localHostBox.addItem(address.getHostAddress()); + } + + //检查环境 +// new SwingWorker() { +// +// @Override +// protected Boolean doInBackground() { +// hasNtp = CommandUtil.checkEnv(); +// return hasNtp; +// } +// +// @Override +// protected void done() { +// if (!hasNtp) { +// JOptionPane.showMessageDialog(ntpPanel, "未当前设备发现可用的NTP配置", "Runtime Error", JOptionPane.ERROR_MESSAGE); +// //环境不对,关闭窗体 +// dispose(); +// } +// super.done(); +// } +// }.execute(); + + autoCheckBox.addActionListener(new ActionListener() { + @Override + public void actionPerformed(ActionEvent e) { + JCheckBox checkBox = (JCheckBox) e.getSource(); + if (checkBox.isSelected()) { + updateTimeButton.setEnabled(false); + periodComboBox.setEnabled(true); + hostTextField.setEnabled(false); + serverTextField.setEnabled(false); + startAutoSynchronize(Constant.PERIOD[0]); + } else { + updateTimeButton.setEnabled(true); + periodComboBox.setEnabled(false); + hostTextField.setEnabled(true); + serverTextField.setEnabled(true); + } + } + }); + + periodComboBox.addItemListener(new ItemListener() { + @Override + public void itemStateChanged(ItemEvent e) { + int period = (Integer) e.getItem(); + if (e.getStateChange() == ItemEvent.SELECTED) { + startAutoSynchronize(period); + } + } + }); + + //按钮点击事件 + updateTimeButton.addActionListener(new ActionListener() { + @Override + public void actionPerformed(ActionEvent e) { + updateView(); + } + }); + } + + private void startAutoSynchronize(int period) { + /** + * 开启同步,只能开启一个同步线程 + * + * scheduleAtFixedRate + * 是以上一个任务开始的时间计时,period时间过去后,检测上一个任务是否执行完毕 + * 如果上一个任务执行完毕,则当前任务立即执行 + * 如果上一个任务没有执行完毕,则需要等上一个任务执行完毕后立即执行 + * */ + executorService.scheduleAtFixedRate(new Runnable() { + @Override + public void run() { + updateView(); + } + }, 0, period, TimeUnit.MINUTES); + } + + private void updateView() { + String host = hostTextField.getText().trim(); + if (host.isEmpty()) { + autoCheckBox.setSelected(false); + JOptionPane.showMessageDialog(ntpPanel, "授时中心服务器输入错误,请检查", "Runtime Error", JOptionPane.ERROR_MESSAGE); + return; + } + String server = serverTextField.getText().trim(); + if (server.isEmpty()) { + autoCheckBox.setSelected(false); + JOptionPane.showMessageDialog(ntpPanel, "后台服务器地址输入错误,请检查", "Runtime Error", JOptionPane.ERROR_MESSAGE); + return; + } +// String result = "5 Jan 11:20:24 ntpdate[807910]: adjust time server 114.118.7.161 offset -0.004064 sec"; +// String result = "5 Jan 11:24:06 ntpdate[824403]: no server suitable for synchronization found"; + String result = CommandUtil.ntpDate(host); + System.out.println("命令执行结果 ===> " + result); + + if ("".equals(result)) { + setStateView(Color.RED); + stateView.setText("同步失败"); + timeValueLabel.setText(""); + } else { + String systemTime = TimeOrDateUtil.timestampToTime(System.currentTimeMillis()); + + String resultString = result.split(":")[3]; + boolean isSuccess = !resultString.contains("no server suitable"); + if (isSuccess) { + setStateView(Color.GREEN); + stateView.setText("同步成功"); + timeValueLabel.setText(systemTime); + //同步成功之后将时间存入本地 + StringHelper.saveAssertsData(systemTime); + } else { + setStateView(Color.RED); + stateView.setText("同步失败"); + timeValueLabel.setText(""); + } + //POST提交 + JSONObject object = new JSONObject(); + try { + object.put("deviceIp", localHostBox.getSelectedItem()); + object.put("ntpResult", result); + + String[] dataSplit = resultString.split(" "); + object.put("deltaTime", dataSplit[6]); + object.put("createTime", systemTime); + if (autoCheckBox.isSelected()) { + object.put("frequency", periodComboBox.getSelectedItem()); + } else { + object.put("frequency", ""); + } + } catch (JSONException e) { + e.printStackTrace(); + } + Request request = new Request.Builder() + .url("http://" + server + "/ntp/saveResult") + .post(HttpRequestHelper.createRequestBody(object.toJSONString())) + .build(); + HttpRequestHelper.doPost(request, new IHttpCallback() { + + @Override + public void onSuccess(String s) { + + } + + @Override + public void onFailure(Exception e) { + e.printStackTrace(); + } + }); + } + } + + private void setStateView(Color color) { + dotPanel.setPreferredSize(new Dimension(15, 15)); + dotPanel.setBackground(color); + } +} diff --git a/src/main/java/com/casic/swing/utils/CommandUtil.java b/src/main/java/com/casic/swing/utils/CommandUtil.java new file mode 100644 index 0000000..2515971 --- /dev/null +++ b/src/main/java/com/casic/swing/utils/CommandUtil.java @@ -0,0 +1,77 @@ +package com.casic.swing.utils; + +import java.io.BufferedReader; +import java.io.IOException; +import java.io.InputStream; +import java.io.InputStreamReader; +import java.nio.charset.Charset; +import java.util.concurrent.TimeUnit; + +/** + * @author a203 + */ +public class CommandUtil { + /** + * 检查当前系统是否已安装NTP + */ + public static boolean checkEnv() { + System.out.println("检查当前系统是否支持NTP"); + try { +// Process exec = Runtime.getRuntime().exec("ls"); + Process exec = Runtime.getRuntime().exec("rpm -q ntp"); + try { + //等待命令执行完成 + exec.waitFor(5, TimeUnit.SECONDS); + } catch (InterruptedException e) { + e.printStackTrace(); + } + String result = parseResult(exec.getInputStream()); + return !result.isEmpty(); + } catch (IOException e) { + e.printStackTrace(); + } + return false; + } + + /** + * 安装NTP + * yum -y install ntp + * */ + + /** + * 授时同步 + * ntpdate -u ntp.api.bz + */ + public static String ntpDate(String host) { + try { + String command = "ntpdate -u " + host; + System.out.println("授时同步 ===> " + command); + Process exec = Runtime.getRuntime().exec(command); + try { + //等待命令执行完成 + exec.waitFor(5, TimeUnit.SECONDS); + } catch (InterruptedException e) { + e.printStackTrace(); + } + return parseResult(exec.getInputStream()); + } catch (IOException e) { + e.printStackTrace(); + } + return ""; + } + + /** + * 解析命令结果 + */ + private static String parseResult(InputStream inputStream) throws IOException { + // 读取输出流内容 + InputStreamReader streamReader = new InputStreamReader(inputStream, Charset.defaultCharset()); + BufferedReader reader = new BufferedReader(streamReader); + StringBuilder builder = new StringBuilder(); + String line; + while ((line = reader.readLine()) != null) { + builder.append(line).append("\n"); + } + return builder.toString(); + } +} diff --git a/src/main/java/com/casic/swing/utils/Constant.java b/src/main/java/com/casic/swing/utils/Constant.java new file mode 100644 index 0000000..f4a6742 --- /dev/null +++ b/src/main/java/com/casic/swing/utils/Constant.java @@ -0,0 +1,13 @@ +package com.casic.swing.utils; + +/** + * @author a203 + */ +public class Constant { + public static final String[] HOST_NAME = {"NTP服务器(上海)", "中国国家授时中心", "清华大学", "北京大学", "自定义"}; + public static final String[] HOST_IP = {"ntp.api.bz", "ntp.ntsc.ac.cn", "s1b.time.edu.cn", "s2m.time.edu.cn"}; + /** + * 同步周期,单位:分钟 + */ + public static final Integer[] PERIOD = {10, 20, 30}; +} diff --git a/src/main/java/com/casic/swing/utils/HttpRequestHelper.java b/src/main/java/com/casic/swing/utils/HttpRequestHelper.java new file mode 100644 index 0000000..ae7f057 --- /dev/null +++ b/src/main/java/com/casic/swing/utils/HttpRequestHelper.java @@ -0,0 +1,78 @@ +package com.casic.swing.utils; + +import okhttp3.*; +import org.jetbrains.annotations.NotNull; + +import java.io.IOException; +import java.net.Inet4Address; +import java.net.InetAddress; +import java.net.NetworkInterface; +import java.net.SocketException; +import java.util.ArrayList; +import java.util.Enumeration; +import java.util.List; +import java.util.Objects; +import java.util.concurrent.TimeUnit; + +/** + * @author a203 + */ +public class HttpRequestHelper { + public static RequestBody createRequestBody(String value) { + return RequestBody.create(MediaType.parse("application/json; charset=utf-8"), value); + } + + public static void doPost(Request request, IHttpCallback httpCallback) { + OkHttpClient httpClient = new OkHttpClient.Builder() + .connectTimeout(15, TimeUnit.SECONDS) + .writeTimeout(15, TimeUnit.SECONDS) + .readTimeout(15, TimeUnit.SECONDS) + .build(); + Call call = httpClient.newCall(request); + call.enqueue(new Callback() { + @Override + public void onFailure(@NotNull Call call, @NotNull IOException e) { + + } + + @Override + public void onResponse(@NotNull Call call, @NotNull Response response) throws IOException { + try { + if (response.body() != null) { + String string = Objects.requireNonNull(response.body()).string(); + httpCallback.onSuccess(string); + } else { + httpCallback.onFailure(new NullPointerException()); + } + } catch (IOException e) { + httpCallback.onFailure(e); + } + } + }); + } + + public static List localHost() { + List addressList = new ArrayList<>(); + try { + Enumeration interfaces = NetworkInterface.getNetworkInterfaces(); + InetAddress ip; + while (interfaces.hasMoreElements()) { + NetworkInterface netInterface = interfaces.nextElement(); + if (netInterface.isLoopback() || netInterface.isVirtual() || !netInterface.isUp()) { + continue; + } else { + Enumeration addresses = netInterface.getInetAddresses(); + while (addresses.hasMoreElements()) { + ip = addresses.nextElement(); + if (ip instanceof Inet4Address) { + addressList.add(ip); + } + } + } + } + } catch (SocketException e) { + e.printStackTrace(); + } + return addressList; + } +} diff --git a/src/main/java/com/casic/swing/utils/IHttpCallback.java b/src/main/java/com/casic/swing/utils/IHttpCallback.java new file mode 100644 index 0000000..fc01a75 --- /dev/null +++ b/src/main/java/com/casic/swing/utils/IHttpCallback.java @@ -0,0 +1,20 @@ +package com.casic.swing.utils; + +/** + * @author a203 + */ +public interface IHttpCallback { + /** + * 接口请求成功 + * + * @param s + */ + void onSuccess(String s); + + /** + * 接口请求失败 + * + * @param e + */ + void onFailure(Exception e); +} diff --git a/src/main/java/com/casic/swing/utils/StringHelper.java b/src/main/java/com/casic/swing/utils/StringHelper.java new file mode 100644 index 0000000..53797ee --- /dev/null +++ b/src/main/java/com/casic/swing/utils/StringHelper.java @@ -0,0 +1,60 @@ +package com.casic.swing.utils; + +import java.io.*; + +/** + * @author a203 + */ +public class StringHelper { + + private static File logFile; + + public static void createLogFile() { + File rootDir = new File(System.getProperty("user.dir") + File.separator + "logs"); + if (!rootDir.exists()) { + rootDir.mkdir(); + } + logFile = new File(rootDir + File.separator + "update.log"); + if (!logFile.exists()) { + // 创建新文件,有同名的文件的话直接覆盖 + try { + logFile.createNewFile(); + } catch (IOException e) { + e.printStackTrace(); + } + } + System.out.println("同步记录路径 ===> " + logFile.getAbsolutePath()); + } + + public static void saveAssertsData(String data) { + try { + FileWriter writer = new FileWriter(logFile); + BufferedWriter out = new BufferedWriter(writer); + out.write(data); + out.flush(); + out.close(); + } catch (IOException e) { + e.printStackTrace(); + } + } + + public static String getAssertsData() { + try { + InputStreamReader inputStreamReader = new InputStreamReader(new FileInputStream(logFile)); + BufferedReader bufferedReader = new BufferedReader(inputStreamReader); + StringBuilder data = new StringBuilder(); + String s; + try { + while ((s = bufferedReader.readLine()) != null) { + data.append(s); + } + return data.toString(); + } catch (IOException e) { + e.printStackTrace(); + } + } catch (IOException e) { + e.printStackTrace(); + } + return ""; + } +} diff --git a/src/main/java/com/casic/swing/utils/TimeOrDateUtil.java b/src/main/java/com/casic/swing/utils/TimeOrDateUtil.java new file mode 100644 index 0000000..7adc5a6 --- /dev/null +++ b/src/main/java/com/casic/swing/utils/TimeOrDateUtil.java @@ -0,0 +1,18 @@ +package com.casic.swing.utils; + +import java.text.SimpleDateFormat; +import java.util.Date; + +/** + * @author a203 + */ +public class TimeOrDateUtil { + + /** + * 时间戳转时间 + */ + public static String timestampToTime(long millSeconds) { + SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); + return format.format(new Date(millSeconds)); + } +}