测试连接:MYSQL、Doris、ORACLE、SQLSERVER、PostgreSQL、Hive、Elasticsearch、minIO

        <dependency>
            <groupId>com.jcraftgroupId>
            <artifactId>jschartifactId>
            <version>0.1.54version>
        dependency>
        <dependency>
            <groupId>cn.hutoolgroupId>
            <artifactId>hutool-allartifactId>
            <version>5.8.5version>
        dependency>
        <dependency>
            <groupId>commons-netgroupId>
            <artifactId>commons-netartifactId>
            <version>3.8.0version>
        dependency>
        <dependency>
            <groupId>io.miniogroupId>
            <artifactId>minioartifactId>
            <version>8.3.5version>
        dependency>
    /**
     * 数据源url拼接及连接测试
     *
     * @param sysDatasource 数据源对象
     * @return Response对象
     */
    private Map<Object, Object> testConn(SysDatasource sysDatasource) {
        Map<Object, Object> result = new HashMap<>();

        //检测库名
        if ("".equals(sysDatasource.getDatabaseName()) || null == sysDatasource.getDatabaseName()) {
            result.put("Response", Response.builderFail("1", "库名不能为空"));
            return result;
        }

//        String path = "C:/Users/xxx/Desktop/";
        String path = "/data/temp";
        //获得数据源类型、账号、密码、ip、端口
        String dataType = sysDatasource.getDatasourceType();
        String username = sysDatasource.getUsername();
        String password = sysDatasource.getPassword();
        String ip = sysDatasource.getHost();
        Integer port = sysDatasource.getPort();
        String databaseName = sysDatasource.getDatabaseName();
        String url = "";
        String configParam = sysDatasource.getConfigParam();
        String connectParam = sysDatasource.getConnectParam();
        StringBuilder param = new StringBuilder();
        boolean flag = false;

        if (!"".equals(connectParam) && null != connectParam) {
            flag = true;
            JSONObject map = JSONUtil.parseObj(connectParam);
            for (Object obj : map.entrySet()) {
                param.append(obj).append("&");
            }
            if (-1 != param.lastIndexOf("&")) {
                param.deleteCharAt(param.lastIndexOf("&"));
            }
        }

        //比较数据源类型获得不同的驱动类字符串、连接字符串
        switch (dataType) {
            case "MYSQL":
            case "Apache Doris":
                url = flag ? "jdbc:mysql://" + ip + ":" + port + "/" + databaseName + "?" + param : "jdbc:mysql://" + ip + ":" + port + "/" + databaseName;
                result.put("Response", conn(url, username, password));
                result.put("address", url);
                break;
            case "ORACLE":
                url = flag ? "jdbc:oracle:thin:@" + ip + ":" + port + "/" + databaseName + "?" + param : "jdbc:oracle:thin:@" + ip + ":" + port + "/" + databaseName;
                result.put("Response", conn(url, username, password));
                result.put("address", url);
                break;
            case "SQLSERVER":
                if (flag) {
                    param = new StringBuilder();
                    JSONObject map = JSONUtil.parseObj(connectParam);
                    for (Object obj : map.entrySet()) {
                        param.append(obj).append(";");
                    }
                    if (-1 != param.lastIndexOf(";")) {
                        param.deleteCharAt(param.lastIndexOf(";"));
                    }
                }

                url = flag ? "jdbc:sqlserver://" + ip + ":" + port + ";DatabaseName=" + databaseName + ";" + param : "jdbc:sqlserver://" + ip + ":" + port + ";DatabaseName=" + databaseName;
                result.put("Response", conn(url, username, password));
                result.put("address", url);
                break;
            case "PostgreSQL":
                url = flag ? "jdbc:postgresql://" + ip + ":" + port + "/" + databaseName + "?" + param : "jdbc:postgresql://" + ip + ":" + port + "/" + databaseName;
                result.put("Response", conn(url, username, password));
                result.put("address", url);
                break;
            case "Apache Hive":
                if (!"".equals(sysDatasource.getAddress()) && null != sysDatasource.getAddress()) {
                    url = sysDatasource.getAddress();
                }
                if (null != configParam && "1".equals(JSONUtil.parseObj(configParam).getStr("isKerberos"))) {
                    JSONObject cpJson = JSONUtil.parseObj(configParam);
                    String krb5Path = path + cpJson.getByPath("krb5.krb5Name");
                    String keytabPath = path + cpJson.getByPath("keytab.keytabName");
                    String principal = cpJson.getStr("principal");
                    String hadoopWinutilsPath = cpJson.getStr("hadoopHomeDir");
                    System.setProperty("java.security.krb5.conf", krb5Path);
                    System.setProperty("hadoop.home.dir", hadoopWinutilsPath);
                    Configuration config = new Configuration();
                    config.set("hadoop.security.authentication", "kerberos");
                    UserGroupInformation.setConfiguration(config);
                    try {
                        UserGroupInformation.loginUserFromKeytab(principal, keytabPath);
                    } catch (IOException e) {
                        LOGGER.error("error", e);
                        result.put("Response", Response.builderFail("1001", e.getMessage()));
                        return result;
                    }
                    url = "".equals(url) ? "jdbc:hive2://" + ip + ":" + port + "/;principal=" + principal : url + "/;principal=" + principal;
                } else {
                    url = "".equals(url) ? "jdbc:hive2://" + ip + ":" + port : url;
                }

                //测试连接
                Connection connection = null;
                try {
                    connection = DriverManager.getConnection(url);
                    result.put("Response", Response.builderSuccess(""));
                    result.put("address", url);
                } catch (SQLException e) {
                    LOGGER.error("error", e);
                    result.put("Response", Response.builderFail("1001", e.getErrorCode() + "-" + e.getMessage()));
                    result.put("address", url);
                } finally {
                    try {
                        if (null != connection) {
                            connection.close();
                        }
                    } catch (SQLException throwables) {
                        LOGGER.error("error", throwables);
                    }
                }
                break;
            case "Elasticsearch":
                //遍历serverAddress,测试所有地址
                List<String> serverAddresses = sysDatasource.getServerAddress();
                for (String serverAddress : serverAddresses) {
                    String[] split;
                    if (serverAddress.contains("//")) {
                        split = serverAddress.split("//")[1].split(":");
                    } else {
                        split = serverAddress.split(":");
                    }
                    ip = split[0];
                    port = Integer.valueOf(split[split.length - 1]);
                    url = "http://" + ip + ":" + port + "/_cluster/health";
                    String s;
                    if (null != configParam && "1".equals(JSONUtil.parseObj(configParam).getStr("isAuth"))) {
                        Authenticator.setDefault(new Authenticator() {
                            @Override
                            protected PasswordAuthentication getPasswordAuthentication() {
                                return new PasswordAuthentication(username, password.toCharArray());
                            }
                        });
                        String json = "{'username':'" + username + "', 'password':'" + password + "'}";
                        s = HttpRequest.get(url).body(json).execute().body();
                    } else {
                        s = HttpRequest.get(url).execute().body();
                    }
                    try {
                        JSON parse = JSONUtil.parse(s);
                        if (null != parse.getByPath("error")) {
                            result.put("Response", Response.builderFail("3", parse.getByPath("error.reason")));
                        } else {
                            switch (parse.getByPath("status").toString()) {
                                case "green":
                                    result.put("Response", Response.builderSuccess(""));
                                    break;
                                case "red":
                                    result.put("Response", Response.builderFail("2", serverAddress + "status : red, 连接失败!"));
                                    break;
                                case "yellow":
                                    result.put("Response", Response.builderSuccess("status : yellow, 连接成功!"));
                                    break;
                            }
                        }
                    } catch (Exception e) {
                        LOGGER.error("error", e);
                        result.put("Response", Response.builderFail("1", e.getMessage()));
                    }
                }
                break;
            case "FTP":
                if (null != configParam && "1".equals(JSONUtil.parseObj(configParam).getStr("isSftp"))) {
                    Session session = null;
                    ChannelSftp sftp = null;
                    port = 22;

                    try {
                        JSch jSch = new JSch();
                        session = jSch.getSession(username, ip, port);
                        session.setPassword(password);
                        session.setConfig("StrictHostKeyChecking", "no");
                        session.connect();
                        Channel channel = session.openChannel("sftp");
                        channel.connect();
                        sftp = (ChannelSftp) channel;
                        result.put("Response", Response.builderSuccess(""));
                    } catch (JSchException e) {
                        LOGGER.error("error", e);
                        result.put("Response", Response.builderFail("1001", "连接失败!"));
                    } finally {
                        if (null != sftp) {
                            if (sftp.isConnected()) {
                                sftp.disconnect();
                            }
                        }
                        if (null != session) {
                            session.disconnect();
                        }
                    }
                } else {
                    FTPClient ftpClient = new FTPClient();
                    try {
                        ftpClient.connect(ip);
                        ftpClient.login(username, password);
                        if (!FTPReply.isPositiveCompletion(ftpClient.getReplyCode())) {
                            ftpClient.disconnect();
                            result.put("Response", Response.builderFail("2", "连接失败,账号或密码错误!"));
                        } else {
                            result.put("Response", Response.builderSuccess(""));
                        }
                    } catch (IOException e) {
                        try {
                            ftpClient.disconnect();
                        } catch (IOException ioException) {
                            LOGGER.error("error", ioException);
                        }
                        LOGGER.error("error", e);
                        result.put("Response", Response.builderFail("1", e.getMessage() + " 请检查ip地址或服务器状态"));
                    } finally {
                        try {
                            ftpClient.disconnect();
                        } catch (IOException e) {
                            LOGGER.error("error", e);
                        }
                    }
                }
                break;
            case "minIO":
                String[] split;
                String address = sysDatasource.getAddress();
                if (address.contains("//")) {
                    split = address.split("//")[1].split(":");
                } else {
                    split = address.split(":");
                }
                ip = split[0];
                port = Integer.valueOf(split[split.length - 1]);
                url = "http://" + ip + ":" + port;
                MinioClient minioClient = null;
                List<Bucket> buckets = new ArrayList<>();
                try {
                    minioClient = MinioClient.builder()
                            .endpoint(url)
                            .credentials(username, password)
                            .build();
                    buckets = minioClient.listBuckets();
                    result.put("Response", Response.builderSuccess(""));
                    result.put("address", url);
                } catch (Exception e) {
                    LOGGER.error("error", e);
                    result.put("Response", Response.builderFail("1001", e.getMessage()));
                }
                break;
        }
        return result;
    }

    /**
     * jdbc方式数据源连接
     *
     * @param url      连接url
     * @param username 用户名
     * @param password 密码
     * @return Response对象
     */
    private Response conn(String url, String username, String password) {
        //测试连接
        Connection connection = null;
        try {
            connection = DriverManager.getConnection(url, username, password);
        } catch (SQLException e) {
            LOGGER.error("error", e);
            return Response.builderFail("1001", e.getErrorCode() + "-" + e.getMessage());
        } finally {
            if (connection != null) {
                try {
                    connection.close();
                } catch (SQLException throwables) {
                    LOGGER.error("error", throwables);
                }
            }
        }

        return Response.builderSuccess("");
    }

你可能感兴趣的:(mysql,oracle,sqlserver)