Spring-_-Bear 个人开发工具类

一、BaseDao

import com.bear.tools.db.util.JdbcUtils;
import org.apache.commons.dbutils.QueryRunner;
import org.apache.commons.dbutils.handlers.BeanHandler;
import org.apache.commons.dbutils.handlers.BeanListHandler;
import org.apache.commons.dbutils.handlers.ScalarHandler;

import java.sql.Connection;
import java.sql.SQLException;
import java.util.List;

/**
 * @author Spring-_-Bear
 * @datetime 2022/2/15 22:47
 */
public abstract class BaseDao {
    private final QueryRunner queryRunner = new QueryRunner();

    /**
     * 执行 insert、update、delete 语句
     *
     * @param sql  sql
     * @param args sql 实参
     * @return 执行语句受影响的行数
     */
    public int update(String sql, Object... args) {
        Connection connection = null;
        try {
            connection = JdbcUtils.getConnection();
            return queryRunner.update(connection, sql, args);
        } catch (SQLException e) {
            e.printStackTrace();
        } finally {
            JdbcUtils.close(connection);
        }
        return -1;
    }

    /**
     * 查询数据库表的一条记录
     *
     * @param clazz JavaBean class 对象
     * @param sql   sql
     * @param args  sql 实参
     * @param    返回类型泛型
     * @return 一条记录
     */
    public <T> T getRecord(Class<T> clazz, String sql, Object... args) {
        Connection connection = null;
        try {
            connection = JdbcUtils.getConnection();
            return queryRunner.query(connection, sql, new BeanHandler<>(clazz), args);
        } catch (SQLException e) {
            e.printStackTrace();
        } finally {
            JdbcUtils.close(connection);
        }
        return null;
    }

    /**
     * 查询返回多条数据库表记录
     *
     * @param clazz JavaBean 的 class 对象
     * @param sql   sql
     * @param args  sql 实参
     * @param    返回类型的泛型
     * @return 多条记录
     */
    public <T> List<T> listRecord(Class<T> clazz, String sql, Object... args) {
        Connection connection = null;
        try {
            connection = JdbcUtils.getConnection();
            return queryRunner.query(connection, sql, new BeanListHandler<>(clazz), args);
        } catch (SQLException e) {
            e.printStackTrace();
        } finally {
            JdbcUtils.close(connection);
        }
        return null;
    }

    /**
     * 查询返回单个数组
     *
     * @param sql  sql
     * @param args sql 实参
     * @return 某个单元格对象
     */
    public Object getSingleValue(String sql, Object... args) {
        Connection connection = null;
        try {
            connection = JdbcUtils.getConnection();
            return queryRunner.query(connection, sql, new ScalarHandler(), args);
        } catch (SQLException e) {
            e.printStackTrace();
        } finally {
            JdbcUtils.close(connection);
        }
        return null;
    }
}

二、BaseServlet

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;

/**
 * @author Spring-_-Bear
 * @datetime 2022/3/1 20:17
 */
public class BaseServlet extends HttpServlet {
    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        String action = req.getParameter("action");

        try {
            // 通过反射机制获取对应的方法对象
            Method declaredMethod = this.getClass().getDeclaredMethod(action, HttpServletRequest.class, HttpServletResponse.class);
            // 调用方法
            declaredMethod.invoke(this, req, resp);
        } catch (NoSuchMethodException | IllegalAccessException | InvocationTargetException e) {
            e.printStackTrace();
        }
    }

        @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        String action = req.getParameter("action");

        try {
            // 通过反射机制获取对应的方法对象
            Method declaredMethod = this.getClass().getDeclaredMethod(action, HttpServletRequest.class, HttpServletResponse.class);
            // 调用方法
            declaredMethod.invoke(this, req, resp);
        } catch (NoSuchMethodException | IllegalAccessException | InvocationTargetException e) {
            e.printStackTrace();
        }
    }
}

三、ThreadPoolUtil

import java.util.concurrent.*;

/**
 * @author Spring-_-Bear
 * @datetime 2021-12-18 20:47
 */
public class ThreadPoolUtil {
    /**
     * 线程池服务
     */
    private static final ExecutorService EXECUTOR_SERVICE = new ThreadPoolExecutor(
            12,
            24,
            0L,
            TimeUnit.MILLISECONDS,
            new LinkedBlockingQueue<>(512),
            Executors.defaultThreadFactory(),
            new ThreadPoolExecutor.AbortPolicy()
    );

    /**
     * 执行线程任务
     *
     * @param task 线程任务
     */
    public static void execute(Runnable task) {
        EXECUTOR_SERVICE.execute(task);
    }

    /**
     * 销毁线程池
     */
    public static void shutdown() {
        EXECUTOR_SERVICE.shutdown();
    }
}

四、JdbcUtil

import javax.sql.DataSource;
import java.io.InputStream;
import java.sql.Connection;
import java.sql.SQLException;
import java.util.Properties;

/**
 * @author Spring-_-Bear
 * @datetime 2022/2/15 22:40
 */
public class JdbcUtils {
    static DataSource dataSource;

    // 读取配置文件,获取配置信息
    static {
        Properties properties = new Properties();
        try {
            InputStream resourceAsStream = JdbcUtils.class.getClassLoader().getResourceAsStream("druid.properties");
            properties.load(resourceAsStream);
            dataSource = DruidDataSourceFactory.createDataSource(properties);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }


    /**
     * 从数据库连接池中获取一个数据库连接对象
     *
     * @return Connection
     * @throws SQLException exception
     */
    public static Connection getConnection() throws SQLException {
        return dataSource.getConnection();
    }

    /**
     * 归还数据库连接对象到数据库连接池
     *
     * @param connection Connection
     */
    public static void close(Connection connection) {
        try {
            if (connection != null) {
                connection.close();
            }
        } catch (SQLException e) {
            throw new RuntimeException(e);
        }
    }
}

五、DatabaseUtil

import java.io.*;
import java.util.Properties;

/**
 * @author Spring-_-Bear
 * @datetime 2021-12-19 21:39
 */
public class DatabaseUtil {

    private static final String PATH = "resources\\druid.properties";
    private static String serverIp;
    private static String username;
    private static String password;
    private static String dbName;

    static {
        Properties properties = new Properties();
        try {
            properties.load(new FileInputStream(PATH));
            serverIp = properties.getProperty("serverIp");
            username = properties.getProperty("username");
            password = properties.getProperty("password");
            dbName = "ebrss";
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    /**
     * 备份 MySQL 数据库
     *
     * @param fileSavePath 备份文件保存路径
     */
    public static void databaseBackup(String fileSavePath) {
        // 组合备份 MySQL 数据库命令并发送到控制台执行
        String command = "mysqldump -h" + serverIp + " -u" + username + " -p" + password + " -B " + dbName + " > " + fileSavePath + "\\" + dbName + ".sql";
        try {
            Runtime.getRuntime().exec("cmd /c" + command);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

六、AppendObjectOutputStream

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectOutputStream;

/**
 * 解决 java.io.StreamCorruptedException: invalid type code: AC 异常
 * 原因分析参考博客:https://blog.csdn.net/weixin_51008866/article/details/121061149
 *
 * @author Spring-_-Bear
 * @version 2021-10-30 21:48
 */
public class AppendObjectOutputStream extends ObjectOutputStream {
    private static File file = null;

    public static void setFile(File file) {
        AppendObjectOutputStream.file = file;
    }

    /**
     * 调用父类的构造器,初始化父类
     *
     * @param file The path of the file
     * @throws IOException I/O异常
     */
    public AppendObjectOutputStream(File file) throws IOException {
        super(new FileOutputStream(file, true));
    }

    /**
     * 重写父类的 writeSteamHeader() 方法以实现文件中只存在一个StreamHeader
     *
     * @throws IOException I/O 异常
     */
    @Override
    public void writeStreamHeader() throws IOException {
        // 如果文件为空直接写入 StreamHeader
        if (file == null) {
            super.writeStreamHeader();
        } else {
            // 文件长度为0即文件中没有内容时也写入 StreamHeader
            if (file.length() == 0) {
                super.writeStreamHeader();
            } else {
                // 文件存在且文件中存在内容,则说明文件中已经存在了一个 StreamHeader
                // 则调用父类的 reset() 方法保证文件中只存在一个 StreamHeader
                this.reset();
            }
        }
    }
}

七、FileUtil

import java.io.*;
import java.util.Objects;

/**
 * @author Spring-_-Bear
 * @datetime 2021-12-19 10:06
 */
public class FileUtil {
    /**
     * 从磁盘加载指定路径的文件并得到文件字节数据
     *
     * @param filePath 文件路径
     * @return 文件字节数据或 null
     */
    public static byte[] getFileDataFromDisk(String filePath) {
        File file = new File(filePath);

        if (!file.exists() && file.isFile()) {
            return null;
        }

        ByteArrayOutputStream byteArrayOutputStream = null;
        FileInputStream fileInputStream = null;
        try {
            byteArrayOutputStream = new ByteArrayOutputStream();
            fileInputStream = new FileInputStream(file);

            int readLen;
            byte[] buf = new byte[1024];
            // 从文件中读取字节数据
            while ((readLen = fileInputStream.read(buf)) != -1) {
                byteArrayOutputStream.write(buf, 0, readLen);
            }
            return byteArrayOutputStream.toByteArray();
        } catch (IOException e) {
            e.printStackTrace();
            return null;
        } finally {
            try {
                Objects.requireNonNull(byteArrayOutputStream).close();
                Objects.requireNonNull(fileInputStream).close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    /**
     * 将文件字节信息保存到指定的磁盘路径,磁盘路径应包含文件名和文件类型
     *
     * @param fileData 文件字节数据
     * @param savePath 文件保存全路径
     * @return true - 保存成功
     */
    public static boolean saveFileToDisk(byte[] fileData, String savePath) {
        if (fileData == null) {
            return false;
        }

        FileOutputStream fileOutputStream = null;
        try {
            fileOutputStream = new FileOutputStream(savePath);
            fileOutputStream.write(fileData);
            fileOutputStream.flush();
            return true;
        } catch (IOException e) {
            e.printStackTrace();
            return false;
        } finally {
            try {
                Objects.requireNonNull(fileOutputStream).close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
}

八、EmailUtil

package com.bear.bookhouse.util;

import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;
import java.util.Date;
import java.util.Properties;
import java.util.Random;

/**
 * @author Spring-_-Bear
 * @datetime 2022/3/15 16:56
 */
public class EmailUtil {
    /**
     * 发件人邮箱账号
     */
    private static final String FROM_EMAIL = "";
    /**
     * 发件人邮箱授权码
     */
    private static final String FROM_EMAIL_PW = "";
    /**
     * 发件人邮箱服务器
     */
    private static final String MY_EMAIL_SMTP_HOST = "smtp.163.com";

    /**
     * 验证码长度
     */
    private static final int VERIFY_CODE_LEN = 6;
    /**
     * 验证码
     */
    private String verifyCode;
    /**
     * 会话对象
     */
    private static Session session;
    /**
     * 邮件工具类对象
     */
    private static final EmailUtil EMAIL_UTIL_OBJ = new EmailUtil();

    public String getVerifyCode() {
        return verifyCode;
    }

    public static EmailUtil getInstance() {
        return EMAIL_UTIL_OBJ;
    }

    /**
     * 配置属性信息
     */
    private EmailUtil() {
        Properties properties = new Properties();
        // 使用的协议(JavaMail 规范要求)
        properties.setProperty("mail.transport.protocol", "smtp");
        // 发件人的邮箱的 SMTP 服务器地址
        properties.setProperty("mail.smtp.host", MY_EMAIL_SMTP_HOST);
        // 需要请求认证
        properties.setProperty("mail.smtp.auth", "true");
        session = Session.getInstance(properties);
        // 设置为debug模式, 可以查看详细的发送 log
        // session.setDebug(true);
    }

    /**
     * 构建邮件内容
     *
     * @param dstEmail 收件人邮箱地址
     * @return 邮件内容
     * @throws Exception exception
     */
    private MimeMessage createMailContent(String dstEmail) throws Exception {
        MimeMessage message = new MimeMessage(session);
        // 设置发件人
        message.setFrom(new InternetAddress(FROM_EMAIL, "Book House", "UTF-8"));
        // 设置收件人
        message.setRecipient(MimeMessage.RecipientType.TO, new InternetAddress(dstEmail));
        // 邮件主题
        message.setSubject("身份验证", "UTF-8");
        // 邮件正文
        verifyCode = randomGenerateCode();
        message.setContent("您好!您的验证码是:" + verifyCode + " ,您正在进行身份验证,打死都不要告诉别人哦!", "text/html;charset=UTF-8");
        // 设置发件时间
        message.setSentDate(new Date());
        // 保存设置
        message.saveChanges();
        return message;
    }

    /**
     * 发送邮件
     *
     * @param dstEmail 收件人邮箱地址
     * @throws Exception exception
     */
    public void sendEmail(String dstEmail) throws Exception {
        Transport transport = session.getTransport();
        transport.connect(FROM_EMAIL, FROM_EMAIL_PW);
        // 生成邮件内容并发送
        MimeMessage message = createMailContent(dstEmail);
        transport.sendMessage(message, message.getAllRecipients());
        transport.close();
    }

    /**
     * 随机生成验证码
     *
     * @return 6 位数验证码字符串
     */
    private String randomGenerateCode() {
        StringBuilder builder = new StringBuilder();
        for (int j = 1; j <= VERIFY_CODE_LEN; j++) {
            int randomNum = new Random().nextInt(36);
            builder.append("1QAZ2WSX3EDC4RFV5TGB6YHN7UJM8IK9OL0P".charAt(randomNum));
        }
        return builder.toString();
    }
}

你可能感兴趣的:(程序人生,java,tools)