如何创建计划方法并将请求发送到端点

问题描述 投票:0回答:1

我必须每 20 天重置一次密码。所以我想用预定的方法自动执行此操作。

我手动将数据插入到我的数据库表中。键列将是 PASSWORDS,parentKey 列将是 test&prod,值列将保存新密码。

我该如何实现这个实现,如何向端点发出请求并获取响应,然后更新现有表上的 pw。有什么建议吗?

这是 put 请求的示例:

curl -- 位置 -- 请求 PUT 'https://api/reset-password'
-- header 'Content-Type: application/json'
-- 原始数据' {"location": "mandalorian", "currentPw": "1234", "newPw":"6778, "email":"[电子邮件受保护]"} '

我如何向端点发出请求并获取响应,然后更新现有表上的密码。有什么建议吗?

java spring-boot scheduled-tasks
1个回答
0
投票
public class PasswordResetTask implements Runnable {

    private final Logger logger = LoggerFactory.getLogger(PasswordResetTask.class);
    private final ScheduledExecutorService scheduler;

    public PasswordResetTask() {
        this.scheduler = Executors.newScheduledThreadPool(1);
    }

    @Override
    public void run() {
        scheduler.scheduleAtFixedRate(this::resetPassword, 0, 1, TimeUnit.MINUTES); // Check every minute
    }

    public void resetPassword() {
        // Prepare the JSON payload for the PUT request
        JSONObject requestBody = new JSONObject();
        String email = "[email protected]";
        String newPassword = "new Password";
        requestBody.put("location", "mandalorian");
        requestBody.put("currentPw", "1234");
        requestBody.put("newPw", newPassword);
        requestBody.put("email", email);

        HttpClient client = HttpClient.newHttpClient();

        // Create HttpRequest
        HttpRequest request = HttpRequest.newBuilder()
                .uri(URI.create("https://api/reset-password")) // Change with your api uri
                .header("Content-Type", "application/json")
                .PUT(HttpRequest.BodyPublishers.ofString(requestBody.toString()))
                .build();

        try {
            // Send the request and handle the response
            HttpResponse<String> response = client.send(request, HttpResponse.BodyHandlers.ofString());
            if (response.statusCode() == 200) {
                logger.info("Password reset successful");
                Properties properties = getProperties();
                savePasswordToDatabase(properties.getProperty("db.url"),
                        properties.getProperty("db.user"),
                        properties.getProperty("db.password"),
                        newPassword,
                        email);
            } else System.out.println("Password reset failed: " + response.body());
        } catch (IOException | InterruptedException e) {
            logger.error(e.getMessage());
        }
    }

    private void savePasswordToDatabase(String dbUrl, String dbUser, String dbPassword, String newPassword, String userMail) {
        try (Connection conn = DriverManager.getConnection(dbUrl, dbUser, dbPassword)) {
            String sql = "UPDATE users SET password = ? WHERE email = ?";
            try (PreparedStatement preparedStatement = conn.prepareStatement(sql)) {
                preparedStatement.setString(1, newPassword);
                preparedStatement.setString(2, userMail);
                int rowsAffected = preparedStatement.executeUpdate();
                if (rowsAffected > 0)
                    System.out.println("Password saved to the database");
                else
                    System.out.println("Failed to save password to the database");
            }
        } catch (SQLException e) {
            logger.error(e.getMessage());
        }
    }

    // For safety
    private Properties getProperties() {
        Properties properties = new Properties();
        try (InputStream input = new FileInputStream("config.properties")) {
            properties.load(input);
        } catch (IOException e) {
            logger.error(e.getMessage());
        }

        return properties;
    }

}

工作原理:

预定执行:

run 方法使用 ScheduledExecutorService 安排 ResetPassword 方法定期运行。 密码重置任务以固定速率执行,每分钟检查一次密码重置。

密码重置:

resetPassword 方法构造一个 JSON 负载,其中包含密码重置所需的信息,例如电子邮件和新密码。 然后,它将 PUT 请求发送到指定的 API 端点 (https://api/reset-password),并将 JSON 负载作为请求正文。 收到响应后,它检查状态代码。如果状态代码为 200(正常),它将记录一条成功的密码重置消息,并继续更新数据库中的密码。 如果状态代码指示失败,则会在响应正文中记录一条错误消息。

数据库更新:

savePasswordToDatabase 方法更新数据库中的用户密码。 它使用 JDBC 建立与数据库的连接,并对用户表执行 UPDATE 操作,为通过电子邮件地址标识的用户设置新密码。 执行更新语句后,它会检查受影响的行数以确定密码更新是否成功。

属性加载:

getProperties 方法从名为 config.properties 的配置文件加载数据库连接属性,以确保敏感信息与代码分离。 注意事项: 密码重置检查的频率(每分钟)可以根据系统要求和性能考虑进行调整。 应评估在配置文件中以明文形式存储密码的安全性。建议在生产环境中使用加密或散列等安全方法。 正确的异常处理和日志记录可确保正确捕获和报告错误以进行故障排除。

© www.soinside.com 2019 - 2024. All rights reserved.