package com.banben.site; import java.io.IOException; import java.net.InetSocketAddress; import java.net.Socket; import java.nio.charset.CharacterCodingException; import java.nio.charset.Charset; import java.nio.charset.CharsetDecoder; import java.nio.charset.CodingErrorAction; import java.nio.charset.StandardCharsets; import java.nio.file.Files; import java.nio.file.Path; import java.sql.Connection; import java.sql.DriverManager; import java.sql.ResultSet; import java.sql.ResultSetMetaData; import java.sql.SQLException; import java.sql.Statement; import java.time.LocalDateTime; import java.time.format.DateTimeFormatter; import java.util.ArrayList; import java.util.List; import java.util.Locale; import java.util.Properties; /** * 现场离线验证:按配置文件连接外部库,确认端口、账号和查询能不能读到数据。 * 不依赖项目里的 Spring,光盘上的 java 目录和 lib 目录就能跑。 */ public class SiteProbe { private static final Charset GBK = Charset.forName("GBK"); private static final int CONNECT_MS = 8000; private static final int QUERY_SECONDS = 30; private static final int SAMPLE_ROWS = 5; public static void main(String[] args) { Path config = Path.of(args.length > 0 ? args[0] : "config.txt"); Path report = Path.of(args.length > 1 ? args[1] : "result.txt"); StringBuilder out = new StringBuilder(); line(out, "现场库验证"); line(out, "时间:" + LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"))); line(out, "配置:" + config.toAbsolutePath()); line(out, ""); int failed = 0; int checked = 0; try { List sources = parse(readText(config)); if (sources.isEmpty()) { line(out, "配置里没有数据源。请打开 config.txt,按里面的说明填好后再运行。"); failed = 1; } for (int i = 0; i < sources.size(); i++) { Source source = sources.get(i); line(out, "======== 第 " + (i + 1) + " 个:" + source.name + " ========"); if (source.host.isBlank()) { line(out, "结果:跳过。地址还没填。"); line(out, ""); continue; } checked++; if (!probe(source, out)) { failed++; } line(out, ""); } } catch (Exception e) { line(out, "读取配置失败:" + e.getMessage()); failed++; } line(out, checked == 0 ? "没有实际检查任何库。" : (failed == 0 ? "全部通过。" : "有 " + failed + " 个没有通过,看上面的原因。")); String text = out.toString(); System.out.print(text); try { Files.writeString(report, text, GBK); System.out.println("结果文件:" + report.toAbsolutePath()); } catch (IOException e) { System.out.println("结果写不进文件(如果程序还在光盘上,请先把整个文件夹复制到桌面再运行):" + e.getMessage()); } System.exit(failed == 0 && checked > 0 ? 0 : 1); } private static boolean probe(Source source, StringBuilder out) { if (source.type.isBlank()) { line(out, "结果:失败。类型还没填。只能填 MYSQL、ORACLE、SQLSERVER、POSTGRESQL、HIGHGO。瀚高填 HIGHGO。"); return false; } if (source.port <= 0 || source.port > 65535) { line(out, "结果:失败。端口还没填,或不是 1 到 65535 的数字。"); return false; } line(out, "类型:" + source.type); line(out, "地址:" + source.host + ":" + source.port + "/" + source.database); line(out, "用户:" + source.user); long started = System.currentTimeMillis(); try (Socket socket = new Socket()) { socket.connect(new InetSocketAddress(source.host, source.port), CONNECT_MS); } catch (IOException e) { line(out, "结果:失败。端口不通,还没有检查账号。"); line(out, "说明:这台电脑到 " + source.host + ":" + source.port + " 连不上。请核对 IP、端口,以及现场网络是否允许访问。"); return false; } line(out, "端口:通"); boolean viewNameMissing = source.sql.contains("【视图名】"); String sql = source.sql.isBlank() || viewNameMissing ? pingSql(source.type) : source.sql; boolean business = !source.sql.isBlank() && !viewNameMissing; if (!isSelect(sql)) { line(out, "结果:失败。查询只能写一条 SELECT,不能是增删改。"); return false; } try { Class.forName(driver(source.type)); } catch (ClassNotFoundException e) { line(out, "结果:失败。光盘里的驱动不完整,缺少 " + source.type + "。"); return false; } Properties props = new Properties(); props.setProperty("user", source.user); props.setProperty("password", source.password); if ("ORACLE".equals(source.type)) { props.setProperty("oracle.net.CONNECT_TIMEOUT", String.valueOf(CONNECT_MS)); props.setProperty("oracle.jdbc.ReadTimeout", "30000"); } try (Connection connection = DriverManager.getConnection(url(source), props); Statement statement = connection.createStatement()) { statement.setQueryTimeout(QUERY_SECONDS); statement.setMaxRows(SAMPLE_ROWS); String product = connection.getMetaData().getDatabaseProductName(); String version = connection.getMetaData().getDatabaseProductVersion(); line(out, "登录:成功(" + product + " " + oneLine(version, 80) + ")"); try (ResultSet rs = statement.executeQuery(sql)) { ResultSetMetaData meta = rs.getMetaData(); int columns = Math.min(meta.getColumnCount(), 12); StringBuilder names = new StringBuilder(); for (int i = 1; i <= columns; i++) { if (i > 1) { names.append(" | "); } names.append(meta.getColumnLabel(i)); } if (meta.getColumnCount() > columns) { names.append(" | ...共 ").append(meta.getColumnCount()).append(" 列"); } int rows = 0; List samples = new ArrayList<>(); while (rs.next()) { rows++; if (samples.size() < SAMPLE_ROWS) { StringBuilder row = new StringBuilder(); for (int i = 1; i <= columns; i++) { if (i > 1) { row.append(" | "); } row.append(oneLine(rs.getString(i), 40)); } samples.add(row.toString()); } } line(out, "查询:成功,返回 " + rows + " 行" + (business ? "(最多展示 " + SAMPLE_ROWS + " 行)" : "(这条只证明账号能执行查询)")); line(out, "列名:" + names); for (int i = 0; i < samples.size(); i++) { line(out, "第" + (i + 1) + "行:" + samples.get(i)); } if (viewNameMissing) { line(out, "注意:账号已经能登录。查询里的【视图名】还没改成陆工大现场的真实视图名,所以这次还没有读到图书数据。改完后再运行一次。"); } else if (!business) { line(out, "注意:查询那一行还是空的,现在只能说明库能登录。把现场的表或视图写进查询后,再运行一次,才能确认业务数据。"); } else if (rows == 0) { line(out, "注意:语句执行了,但没有行。请确认表名、视图名和筛选条件。"); } else { line(out, "结论:这个库可以读到数据。"); } } line(out, "耗时:" + (System.currentTimeMillis() - started) + " 毫秒"); return business; } catch (SQLException e) { line(out, "结果:失败。" + explain(e, source.password)); line(out, "耗时:" + (System.currentTimeMillis() - started) + " 毫秒"); return false; } } private static boolean isSelect(String sql) { String text = sql.trim(); if (text.endsWith(";")) { text = text.substring(0, text.length() - 1).trim(); } if (text.indexOf(';') >= 0) { return false; } String head = text.toLowerCase(Locale.ROOT); return head.startsWith("select") || head.startsWith("with"); } private static String pingSql(String type) { return "ORACLE".equals(type) ? "SELECT 1 FROM dual" : "SELECT 1"; } private static String driver(String type) { return switch (type) { case "MYSQL" -> "com.mysql.cj.jdbc.Driver"; case "ORACLE" -> "oracle.jdbc.OracleDriver"; case "SQLSERVER" -> "com.microsoft.sqlserver.jdbc.SQLServerDriver"; case "POSTGRESQL", "HIGHGO" -> "org.postgresql.Driver"; default -> throw new IllegalArgumentException("类型只能填 MYSQL、ORACLE、SQLSERVER、POSTGRESQL、HIGHGO"); }; } private static String url(Source source) { return switch (source.type) { case "MYSQL" -> "jdbc:mysql://" + source.host + ":" + source.port + "/" + source.database + "?useSSL=false&allowPublicKeyRetrieval=true&characterEncoding=utf8&serverTimezone=Asia/Shanghai&connectTimeout=" + CONNECT_MS; case "ORACLE" -> "jdbc:oracle:thin:@//" + source.host + ":" + source.port + "/" + source.database; case "SQLSERVER" -> "jdbc:sqlserver://" + source.host + ":" + source.port + ";databaseName=" + source.database + ";encrypt=false;trustServerCertificate=true;loginTimeout=8"; case "POSTGRESQL", "HIGHGO" -> "jdbc:postgresql://" + source.host + ":" + source.port + "/" + source.database + "?connectTimeout=8"; default -> throw new IllegalArgumentException("类型只能填 MYSQL、ORACLE、SQLSERVER、POSTGRESQL、HIGHGO"); }; } private static String explain(SQLException exception, String password) { String message = exception.getMessage() == null ? "查询失败" : exception.getMessage(); String lower = message.toLowerCase(Locale.ROOT); String text; if (lower.contains("access denied") || lower.contains("password authentication failed") || lower.contains("login failed") || lower.contains("ora-01017")) { text = "用户名或密码错误"; } else if (lower.contains("unknown database") || lower.contains("does not exist") || lower.contains("ora-12514") || lower.contains("cannot open database")) { text = "库名不对。Oracle 的库名要填服务名"; } else if (lower.contains("timeout") || lower.contains("timed out")) { text = "登录或查询超时"; } else { text = oneLine(message, 300); } if (password != null && !password.isBlank()) { text = text.replace(password, "******"); } return text; } private static List parse(String text) { List sources = new ArrayList<>(); Source current = null; for (String raw : text.split("\\R")) { String line = raw.trim(); if (line.isEmpty() || line.startsWith("#")) { continue; } if ("[数据源]".equals(line)) { current = new Source(); sources.add(current); continue; } int split = line.indexOf('='); if (split <= 0 || current == null) { continue; } String key = line.substring(0, split).trim(); String value = line.substring(split + 1).trim(); switch (key) { case "名称" -> current.name = value.isBlank() ? "未命名" : value; case "类型" -> current.type = value.isBlank() ? "" : normalizeType(value); case "地址" -> current.host = value; case "端口" -> current.port = value.isBlank() ? 0 : parsePort(value); case "库名" -> current.database = value; case "用户名" -> current.user = value; case "密码" -> current.password = value; case "查询" -> current.sql = placeholder(value) ? "" : strip(value); default -> { } } } return sources; } private static boolean placeholder(String value) { return value.isBlank() || value.contains("这里换成") || value.contains("现场填写"); } private static String strip(String sql) { String text = sql.trim(); if (text.endsWith(";")) { text = text.substring(0, text.length() - 1).trim(); } return text; } private static String normalizeType(String value) { String text = value.trim().toUpperCase(Locale.ROOT).replace(" ", ""); return switch (text) { case "MYSQL" -> "MYSQL"; case "ORACLE" -> "ORACLE"; case "SQLSERVER", "MSSQL" -> "SQLSERVER"; case "POSTGRESQL", "POSTGRES", "PG" -> "POSTGRESQL"; case "HIGHGO", "瀚高" -> "HIGHGO"; default -> throw new IllegalArgumentException("无法识别的数据库类型:" + value); }; } private static int parsePort(String value) { try { return Integer.parseInt(value.trim()); } catch (NumberFormatException e) { throw new IllegalArgumentException("端口不是数字:" + value); } } private static String readText(Path path) throws IOException { if (!Files.exists(path)) { throw new IllegalArgumentException("找不到配置文件 " + path.toAbsolutePath()); } byte[] bytes = Files.readAllBytes(path); if (bytes.length >= 3 && bytes[0] == (byte) 0xEF && bytes[1] == (byte) 0xBB && bytes[2] == (byte) 0xBF) { return new String(bytes, 3, bytes.length - 3, StandardCharsets.UTF_8); } CharsetDecoder decoder = StandardCharsets.UTF_8.newDecoder() .onMalformedInput(CodingErrorAction.REPORT) .onUnmappableCharacter(CodingErrorAction.REPORT); try { return decoder.decode(java.nio.ByteBuffer.wrap(bytes)).toString(); } catch (CharacterCodingException e) { return new String(bytes, GBK); } } private static String oneLine(String text, int max) { if (text == null) { return ""; } String flat = text.replace('\r', ' ').replace('\n', ' ').trim(); return flat.length() <= max ? flat : flat.substring(0, max) + "..."; } private static void line(StringBuilder out, String text) { out.append(text).append(System.lineSeparator()); } private static final class Source { private String name = "未命名"; private String type = ""; private String host = ""; private int port = 5432; private String database = ""; private String user = ""; private String password = ""; private String sql = ""; } }