Skip to content

Commit c05b28b

Browse files
committed
Refactoring: Separate duplicated logic into method
1 parent 7ad24ab commit c05b28b

File tree

1 file changed

+21
-16
lines changed

1 file changed

+21
-16
lines changed

src/main/java/root/core/repository/implement/LinuxServerMonitoringRepository.java

Lines changed: 21 additions & 16 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,6 @@
11
package root.core.repository.implement;
22

3+
import java.io.IOException;
34
import java.io.InputStream;
45
import java.time.LocalDate;
56
import java.util.ArrayList;
@@ -10,6 +11,7 @@
1011
import org.apache.commons.io.IOUtils;
1112

1213
import com.jcraft.jsch.Channel;
14+
import com.jcraft.jsch.JSchException;
1315
import com.jcraft.jsch.Session;
1416

1517
import lombok.extern.slf4j.Slf4j;
@@ -40,33 +42,22 @@ public String getServerName() {
4042
public int getAlertLogFileLineCount(AlertLogCommand alc) {
4143
int fileLineCnt = 0;
4244
try {
43-
Session session = jsch.getSession();
44-
session.connect();
45-
Channel channel = jsch.openExecChannel(session, "cat " + alc.getReadFilePath() + " | wc -l");
46-
InputStream in = jsch.connectChannel(channel);
47-
String result = IOUtils.toString(in, "UTF-8");
48-
fileLineCnt = Integer.parseInt(result.trim());
49-
jsch.disConnectChannel(channel);
50-
jsch.disConnect(session);
45+
String command = "cat " + alc.getReadFilePath() + " | wc -l";
46+
String executeResult = executeCommand(command);
47+
fileLineCnt = Integer.parseInt(executeResult.trim());
5148
} catch (Exception e) {
5249
log.error(e.getMessage());
5350
}
5451

5552
return fileLineCnt;
5653
}
57-
54+
5855
@Override
5956
public String checkAlertLog(AlertLogCommand alc) {
6057
String result = "";
6158
try {
62-
Session session = jsch.getSession();
63-
session.connect();
6459
String command = "tail -" + alc.getReadLine() + " " + alc.getReadFilePath();
65-
Channel channel = jsch.openExecChannel(session, command);
66-
InputStream in = jsch.connectChannel(channel);
67-
result = IOUtils.toString(in, "UTF-8");
68-
jsch.disConnectChannel(channel);
69-
jsch.disConnect(session);
60+
result = executeCommand(command);
7061
} catch (Exception e) {
7162
log.error(e.getMessage());
7263
}
@@ -261,4 +252,18 @@ private String getAlertLogStringFromCertainDate(AlertLogCommand alc, String star
261252

262253
return fullAlertLogString;
263254
}
255+
256+
private String executeCommand(String command) throws JSchException, IOException {
257+
String result = null;
258+
259+
Session session = jsch.getSession();
260+
session.connect();
261+
Channel channel = jsch.openExecChannel(session, command);
262+
InputStream in = jsch.connectChannel(channel);
263+
result = IOUtils.toString(in, "UTF-8");
264+
jsch.disConnectChannel(channel);
265+
jsch.disConnect(session);
266+
267+
return result;
268+
}
264269
}

0 commit comments

Comments
 (0)