Search in sources :

Example 1 with DbExtConfig

use of io.jpom.system.extconf.DbExtConfig in project Jpom by dromara.

the class BaseDbService method executeClear.

/**
 * 执行清理
 */
private void executeClear() {
    DbExtConfig dbExtConfig = SpringUtil.getBean(DbExtConfig.class);
    int h2DbLogStorageCount = dbExtConfig.getLogStorageCount();
    if (h2DbLogStorageCount <= 0) {
        return;
    }
    this.executeClearImpl(h2DbLogStorageCount);
}
Also used : DbExtConfig(io.jpom.system.extconf.DbExtConfig)

Example 2 with DbExtConfig

use of io.jpom.system.extconf.DbExtConfig in project Jpom by dromara.

the class TestYml method test2.

@Test
public void test2() {
    InputStream stream = ResourceUtil.getStream("bin/extConfig.yml");
    // String s = IoUtil.readUtf8(stream);
    // System.out.println(s);
    Dict dict = YamlUtil.load(stream, Dict.class);
    Object db = dict.get("db");
    StringWriter writer = new StringWriter();
    YamlUtil.dump(db, writer);
    ByteArrayInputStream inputStream = IoUtil.toStream(writer.toString(), CharsetUtil.CHARSET_UTF_8);
    DbExtConfig dbExtConfig1 = YamlUtil.load(inputStream, DbExtConfig.class);
    System.out.println(dbExtConfig1);
}
Also used : StringWriter(java.io.StringWriter) ByteArrayInputStream(java.io.ByteArrayInputStream) ByteArrayInputStream(java.io.ByteArrayInputStream) InputStream(java.io.InputStream) Dict(cn.hutool.core.lang.Dict) DbExtConfig(io.jpom.system.extconf.DbExtConfig) Test(org.junit.Test)

Example 3 with DbExtConfig

use of io.jpom.system.extconf.DbExtConfig in project Jpom by dromara.

the class SystemConfigController method saveConfig.

@PostMapping(value = "save_config.json", produces = MediaType.APPLICATION_JSON_VALUE)
@Feature(method = MethodFeature.EDIT)
@SystemPermission(superUser = true)
public String saveConfig(String nodeId, String content, String restart) throws IOException, SQLException {
    if (StrUtil.isNotEmpty(nodeId)) {
        return NodeForward.request(getNode(), getRequest(), NodeUrl.SystemSaveConfig).toString();
    }
    Assert.hasText(content, "内容不能为空");
    try {
        YamlPropertySourceLoader yamlPropertySourceLoader = new YamlPropertySourceLoader();
        // @author hjk 前端编辑器允许使用tab键,并设定为2个空格,再转换为yml时要把tab键换成2个空格
        ByteArrayResource resource = new ByteArrayResource(content.replace("\t", "  ").getBytes(StandardCharsets.UTF_8));
        yamlPropertySourceLoader.load("test", resource);
    } catch (Exception e) {
        DefaultSystemLog.getLog().warn("内容格式错误,请检查修正", e);
        return JsonMessage.getString(500, "内容格式错误,请检查修正:" + e.getMessage());
    }
    boolean restartBool = Convert.toBool(restart, false);
    // 修改数据库密码
    DbExtConfig oldDbExtConfig = DbExtConfig.parse(ExtConfigBean.getResource().getInputStream());
    DbExtConfig newDbExtConfig = DbExtConfig.parse(content);
    if (!StrUtil.equals(oldDbExtConfig.getUserName(), newDbExtConfig.getUserName()) || !StrUtil.equals(oldDbExtConfig.getUserPwd(), newDbExtConfig.getUserPwd())) {
        // 执行修改数据库账号密码
        Assert.state(restartBool, "修改数据库密码必须重启");
        initDb.alterUser(oldDbExtConfig.getUserName(), newDbExtConfig.getUserName(), newDbExtConfig.getUserPwd());
    }
    Assert.state(!JpomManifest.getInstance().isDebug(), "调试模式下不支持在线修改,请到resources目录下的bin目录修改extConfig.yml");
    File resourceFile = ExtConfigBean.getResourceFile();
    FileUtil.writeString(content, resourceFile, CharsetUtil.CHARSET_UTF_8);
    if (restartBool) {
        // 重启
        ThreadUtil.execute(() -> {
            ThreadUtil.sleep(2000);
            JpomApplication.restart();
        });
        return JsonMessage.getString(200, Const.UPGRADE_MSG);
    }
    return JsonMessage.getString(200, "修改成功");
}
Also used : DbExtConfig(io.jpom.system.extconf.DbExtConfig) YamlPropertySourceLoader(org.springframework.boot.env.YamlPropertySourceLoader) ByteArrayResource(org.springframework.core.io.ByteArrayResource) File(java.io.File) SQLException(java.sql.SQLException) IOException(java.io.IOException) SystemPermission(io.jpom.permission.SystemPermission) PostMapping(org.springframework.web.bind.annotation.PostMapping) Feature(io.jpom.permission.Feature) MethodFeature(io.jpom.permission.MethodFeature) ClassFeature(io.jpom.permission.ClassFeature)

Example 4 with DbExtConfig

use of io.jpom.system.extconf.DbExtConfig in project Jpom by dromara.

the class InitDb method init.

@PreLoadMethod(value = Integer.MIN_VALUE)
private static void init() {
    // 
    DbConfig instance = DbConfig.getInstance();
    ServerExtConfigBean serverExtConfigBean = ServerExtConfigBean.getInstance();
    DbExtConfig dbExtConfig = SpringUtil.getBean(DbExtConfig.class);
    // 
    Setting setting = new Setting();
    String dbUrl = instance.getDbUrl();
    setting.set("url", dbUrl);
    setting.set("user", dbExtConfig.getUserName());
    setting.set("pass", dbExtConfig.getUserPwd());
    // 配置连接池大小
    setting.set("maxActive", dbExtConfig.getMaxActive() + "");
    setting.set("initialSize", dbExtConfig.getInitialSize() + "");
    setting.set("maxWait", dbExtConfig.getMaxWait() + "");
    setting.set("minIdle", dbExtConfig.getMinIdle() + "");
    // 调试模式显示sql 信息
    if (dbExtConfig.getShowSql()) {
        setting.set(SqlLog.KEY_SHOW_SQL, "true");
        /*
			  @author Hotstrip
			  sql log only show when it's needed,
			  if you want to check init sql,
			  set the [sqlLevel] from [DEBUG] to [INFO]
			 */
        setting.set(SqlLog.KEY_SQL_LEVEL, "DEBUG");
        setting.set(SqlLog.KEY_SHOW_PARAMS, "true");
    }
    Console.log("start load h2 db");
    String sqlFileNow = StrUtil.EMPTY;
    try {
        // 创建连接
        DSFactory dsFactory = DSFactory.create(setting);
        // 先执行恢复数据
        instance.executeRecoverDbSql(dsFactory);
        /*
			  @author Hotstrip
			  add another sql init file, if there are more sql file,
			  please add it with same way
			 */
        PathMatchingResourcePatternResolver pathMatchingResourcePatternResolver = new PathMatchingResourcePatternResolver();
        Resource[] resources = pathMatchingResourcePatternResolver.getResources("classpath:/sql/*.sql");
        // 加载 sql 变更记录,避免重复执行
        Set<String> executeSqlLog = instance.loadExecuteSqlLog();
        // 过滤 temp sql
        List<Resource> resourcesList = Arrays.stream(resources).sorted((o1, o2) -> StrUtil.compare(o1.getFilename(), o2.getFilename(), true)).filter(resource -> !StrUtil.containsIgnoreCase(resource.getFilename(), "temp")).collect(Collectors.toList());
        // 遍历
        for (Resource resource : resourcesList) {
            try (InputStream inputStream = resource.getInputStream()) {
                String sql = IoUtil.read(inputStream, CharsetUtil.CHARSET_UTF_8);
                String sha1 = SecureUtil.sha1(sql);
                if (executeSqlLog.contains(sha1)) {
                    // 已经执行过啦,不再执行
                    continue;
                }
                sqlFileNow = resource.getFilename();
                int rows = Db.use(dsFactory.getDataSource()).execute(sql);
                DefaultSystemLog.getLog().info("exec init SQL file: {} complete, and affected rows is: {}", sqlFileNow, rows);
                executeSqlLog.add(sha1);
            } catch (IOException ignored) {
            }
        }
        instance.saveExecuteSqlLog(executeSqlLog);
        GlobalDSFactory.set(dsFactory);
    // 
    } catch (Exception e) {
        DefaultSystemLog.getLog().error("初始化数据库失败 {}", sqlFileNow, e);
        System.exit(0);
        return;
    }
    instance.initOk();
    // json load to db
    InitDb.loadJsonToDb();
    Console.log("h2 db Successfully loaded, url is 【{}】", dbUrl);
    if (JpomManifest.getInstance().isDebug()) {
    // 
    } else {
        if (serverExtConfigBean.isH2ConsoleEnabled() && StrUtil.equals(dbExtConfig.getUserName(), DbConfig.DEFAULT_USER_OR_AUTHORIZATION) && StrUtil.equals(dbExtConfig.getUserPwd(), DbConfig.DEFAULT_USER_OR_AUTHORIZATION)) {
            Console.error("【安全警告】数据库账号密码使用默认的情况下不建议开启 h2 数据 web 控制台");
            System.exit(-2);
        }
    }
}
Also used : SignalHandler(sun.misc.SignalHandler) SecureUtil(cn.hutool.crypto.SecureUtil) Arrays(java.util.Arrays) DSFactory(cn.hutool.db.ds.DSFactory) DefaultSystemLog(cn.jiangzeyin.common.DefaultSystemLog) DbExtConfig(io.jpom.system.extconf.DbExtConfig) InitializingBean(org.springframework.beans.factory.InitializingBean) PathMatchingResourcePatternResolver(org.springframework.core.io.support.PathMatchingResourcePatternResolver) SQLException(java.sql.SQLException) PreLoadMethod(cn.jiangzeyin.common.PreLoadMethod) Map(java.util.Map) GlobalDSFactory(cn.hutool.db.ds.GlobalDSFactory) Signal(sun.misc.Signal) Setting(cn.hutool.setting.Setting) BaseGroupService(io.jpom.service.h2db.BaseGroupService) Resource(org.springframework.core.io.Resource) IoUtil(cn.hutool.core.io.IoUtil) DbConfig(io.jpom.system.db.DbConfig) WorkspaceService(io.jpom.service.system.WorkspaceService) Set(java.util.Set) IOException(java.io.IOException) Console(cn.hutool.core.lang.Console) BaseNodeService(io.jpom.service.h2db.BaseNodeService) SpringUtil(cn.jiangzeyin.common.spring.SpringUtil) Collectors(java.util.stream.Collectors) Db(cn.hutool.db.Db) SqlLog(cn.hutool.db.sql.SqlLog) PreLoadClass(cn.jiangzeyin.common.PreLoadClass) Configuration(org.springframework.context.annotation.Configuration) StrUtil(cn.hutool.core.util.StrUtil) Slf4j(lombok.extern.slf4j.Slf4j) List(java.util.List) JpomManifest(io.jpom.common.JpomManifest) DisposableBean(org.springframework.beans.factory.DisposableBean) CharsetUtil(cn.hutool.core.util.CharsetUtil) UserModel(io.jpom.model.data.UserModel) BaseServerController(io.jpom.common.BaseServerController) ServerExtConfigBean(io.jpom.system.ServerExtConfigBean) InputStream(java.io.InputStream) ServerExtConfigBean(io.jpom.system.ServerExtConfigBean) InputStream(java.io.InputStream) Setting(cn.hutool.setting.Setting) Resource(org.springframework.core.io.Resource) DSFactory(cn.hutool.db.ds.DSFactory) GlobalDSFactory(cn.hutool.db.ds.GlobalDSFactory) IOException(java.io.IOException) SQLException(java.sql.SQLException) IOException(java.io.IOException) DbExtConfig(io.jpom.system.extconf.DbExtConfig) DbConfig(io.jpom.system.db.DbConfig) PathMatchingResourcePatternResolver(org.springframework.core.io.support.PathMatchingResourcePatternResolver) PreLoadMethod(cn.jiangzeyin.common.PreLoadMethod)

Example 5 with DbExtConfig

use of io.jpom.system.extconf.DbExtConfig in project Jpom by dromara.

the class DbConfig method getDbUrl.

/**
 * 获取数据库的jdbc 连接
 *
 * @return jdbc
 */
public String getDbUrl() {
    DbExtConfig dbExtConfig = SpringUtil.getBean(DbExtConfig.class);
    String dbUrl = dbExtConfig.getUrl();
    if (StrUtil.isNotEmpty(dbUrl)) {
        return dbUrl;
    }
    File file = FileUtil.file(this.dbLocalPath(), this.getDbName());
    String path = FileUtil.getAbsolutePath(file);
    return StrUtil.format("jdbc:h2:{};CACHE_SIZE={};MODE=MYSQL", path, dbExtConfig.getCacheSize().toKilobytes());
}
Also used : DbExtConfig(io.jpom.system.extconf.DbExtConfig) File(java.io.File)

Aggregations

DbExtConfig (io.jpom.system.extconf.DbExtConfig)5 File (java.io.File)2 IOException (java.io.IOException)2 InputStream (java.io.InputStream)2 SQLException (java.sql.SQLException)2 IoUtil (cn.hutool.core.io.IoUtil)1 Console (cn.hutool.core.lang.Console)1 Dict (cn.hutool.core.lang.Dict)1 CharsetUtil (cn.hutool.core.util.CharsetUtil)1 StrUtil (cn.hutool.core.util.StrUtil)1 SecureUtil (cn.hutool.crypto.SecureUtil)1 Db (cn.hutool.db.Db)1 DSFactory (cn.hutool.db.ds.DSFactory)1 GlobalDSFactory (cn.hutool.db.ds.GlobalDSFactory)1 SqlLog (cn.hutool.db.sql.SqlLog)1 Setting (cn.hutool.setting.Setting)1 DefaultSystemLog (cn.jiangzeyin.common.DefaultSystemLog)1 PreLoadClass (cn.jiangzeyin.common.PreLoadClass)1 PreLoadMethod (cn.jiangzeyin.common.PreLoadMethod)1 SpringUtil (cn.jiangzeyin.common.spring.SpringUtil)1