Java Code Examples for com.jfinal.kit.PathKit

The following examples show how to use com.jfinal.kit.PathKit. These examples are extracted from open source projects. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source Project: jfinal-ext3   Source File: SqlInXmlKit.java    License: Apache License 2.0 6 votes vote down vote up
static void init() {
    sqlMap = new HashMap<String, String>();
    File file = new File(PathKit.getRootClassPath());
    File[] files = file.listFiles(new FileFilter() {

        @Override
        public boolean accept(File pathname) {
            if (pathname.getName().endsWith("sql.xml")) {
                return true;
            }
            return false;
        }
    });
    for (File xmlfile : files) {
        SqlGroup group = JaxbKit.unmarshal(xmlfile, SqlGroup.class);
        String name = group.name;
        if (name == null || name.trim().equals("")) {
            name = xmlfile.getName();
        }
        for (SqlItem sqlItem : group.sqlItems) {
            sqlMap.put(name + "." + sqlItem.id, sqlItem.value);
        }
    }
    LOG.debug("sqlMap" + sqlMap);
}
 
Example 2
Source Project: jboot   Source File: DataSourceBuilder.java    License: Apache License 2.0 6 votes vote down vote up
public DataSource build() {

        String shardingConfigYaml = config.getShardingConfigYaml();

        // 不启用分库分表的配置
        if (StrUtil.isBlank(shardingConfigYaml)) {
            DataSource ds = createDataSource(config);
            return JbootSeataManager.me().wrapDataSource(ds);
        }


        File yamlFile = shardingConfigYaml.startsWith(File.separator)
                ? new File(shardingConfigYaml)
                : new File(PathKit.getRootClassPath(), shardingConfigYaml);

        try {
            return YamlShardingDataSourceFactory.createDataSource(yamlFile);
        } catch (Exception e) {
            throw new JbootException(e);
        }
    }
 
Example 3
Source Project: zrlog   Source File: ZrLogConfig.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * 配置JFinal的常用参数,这里可以看出来JFinal推崇使用代码进行配置的,而不是像Spring这样的通过预定配置方式。代码控制的好处在于高度可控制性,
 * 当然这也导致了很多程序员直接硬编码的问题。
 *
 * @param con
 */
@Override
public void configConstant(Constants con) {
    con.setDevMode(BlogBuildInfoUtil.isDev());
    con.setViewType(ViewType.JSP);
    con.setEncoding("utf-8");
    con.setJsonDatePattern("yyyy-MM-dd");
    con.setI18nDefaultBaseName(com.zrlog.common.Constants.I18N);
    con.setI18nDefaultLocale("zh_CN");
    con.setError404View(com.zrlog.common.Constants.NOT_FOUND_PAGE);
    con.setError500View(com.zrlog.common.Constants.ERROR_PAGE);
    con.setError403View(com.zrlog.common.Constants.FORBIDDEN_PAGE);
    con.setBaseUploadPath(PathKit.getWebRootPath() + com.zrlog.common.Constants.ATTACHED_FOLDER);
    //最大的提交的body的大小
    con.setMaxPostSize(1024 * 1024 * 1024);
}
 
Example 4
Source Project: NewsRecommendSystem   Source File: ModelGenerator.java    License: MIT License 6 votes vote down vote up
/**
 * @param dataSource
 * @param baseModelPackageName
 * @param baseModelOutputDir
 * @param modelPackageName
 * @param modelOutputDir
 */
public static void main(String[] args)
{
	// base model 所使用的包名
	String baseModelPackageName = "top.qianxinyao.model.base";
	// base model 文件保存路径
	String baseModelOutputDir = PathKit.getRootClassPath() + "/../../src/top/qianxinyao/model/base";
	System.out.println("rootclasspath:"+baseModelOutputDir);
	// model 所使用的包名 (MappingKit 默认使用的包名)
	String modelPackageName = "top.qianxinyao.model";
	// model 文件保存路径 (MappingKit 与 DataDictionary 文件默认保存路径)
	String modelOutputDir = baseModelOutputDir+"/..";
	System.out.println(baseModelOutputDir);
	// 创建生成器
	Generator gernerator = new Generator(DBKit.getDataSource(), baseModelPackageName, baseModelOutputDir,
			modelPackageName, modelOutputDir);
	gernerator.setDialect(new MysqlDialect());
	// 设置是否在 Model 中生成 dao 对象
	gernerator.setGenerateDaoInModel(true);
	// 设置是否生成字典文件
	gernerator.setGenerateDataDictionary(false);
	// 生成
	gernerator.generate();
}
 
Example 5
Source Project: jpress   Source File: AddonManager.java    License: GNU Lesser General Public License v3.0 6 votes vote down vote up
/**
 * 启动的时候,加载所有插件
 * 备注:插件可能是复制到插件目录下,而非通过后台进行 "安装"
 */
private void doInitAddons() {

    File addonDir = new File(PathKit.getWebRootPath(), "WEB-INF/addons");
    if (!addonDir.exists()) {
        return;
    }

    File[] addonJarFiles = addonDir.listFiles((dir, name) -> name.endsWith(".jar"));
    if (addonJarFiles == null || addonJarFiles.length == 0) {
        return;
    }

    initAddonsMap(addonJarFiles);
    doInstallAddonsInApplicationStarted();
    doStartAddonInApplicationStarted();

}
 
Example 6
public void doBatchDelRootFile() {
    String fileNames = getPara("names");
    if (StrUtil.isBlank(fileNames) || fileNames.contains("..") || fileNames.contains("/") || fileNames.contains("\\")) {
        renderFailJson();
        return;
    }

    String[] fileNamaArray = fileNames.split(",");
    for (String fileName : fileNamaArray) {
        if (StrUtil.isNotBlank(fileName)) {
            File file = new File(PathKit.getWebRootPath(), fileName.trim());
            file.delete();
        }
    }
    renderOkJson();
}
 
Example 7
Source Project: zrlog   Source File: WarUpdateVersionThread.java    License: Apache License 2.0 6 votes vote down vote up
private File generatorUpgradeWarFile(String warName) throws IOException {
    ZipUtil.unZip(file.toString(), tempFilePath + File.separator);
    updateProcessMsg("解压安装包 " + file);
    Map<String, String> copyFileMap = new LinkedHashMap<>();
    copyFileMap.put(PathKit.getWebRootPath() + "/WEB-INF/db.properties", tempFilePath + "/WEB-INF/");
    copyFileMap.put(PathKit.getWebRootPath() + "/WEB-INF/install.lock", tempFilePath + "/WEB-INF/");
    copyFileMap.put(PathKit.getWebRootPath() + Constants.ATTACHED_FOLDER, tempFilePath.toString());
    copyFileMap.put(PathKit.getWebRootPath() + "/favicon.ico", tempFilePath.toString());
    copyFileMap.put(PathKit.getWebRootPath() + "/error", tempFilePath.toString());
    fillTemplateCopyInfo(tempFilePath, copyFileMap);
    doCopy(copyFileMap);
    List<File> fileList = new ArrayList<>();
    fileList.add(tempFilePath);
    File tempWarFile = new File(tempFilePath.getParent() + File.separator + warName);
    JarPackageUtil.inJar(fileList, tempFilePath + File.separator, tempWarFile.toString());
    updateProcessMsg("合成更新包 " + tempWarFile);
    return tempWarFile;
}
 
Example 8
Source Project: zrlog   Source File: WarUpdateVersionThread.java    License: Apache License 2.0 6 votes vote down vote up
private String getWarNameAndBackup() {
    String warName;
    String contextPath = JFinal.me().getServletContext().getContextPath();
    if ("/".equals(contextPath) || "".equals(contextPath)) {
        warName = "/ROOT.war";
    } else {
        warName = contextPath + ".war";
    }
    String backupFolder = new File(PathKit.getWebRootPath()).getParentFile().getParentFile() + File.separator + "backup" + File.separator + new SimpleDateFormat("yyyy-MM-dd_HH_mm").format(new Date()) + File.separator;
    new File(backupFolder).mkdirs();
    FileUtils.moveOrCopyFolder(PathKit.getWebRootPath(), backupFolder, false);
    String warPath = new File(PathKit.getWebRootPath()).getParent() + File.separator + warName;
    if (new File(warPath).exists()) {
        FileUtils.moveOrCopyFolder(warPath, backupFolder, false);
    }
    updateProcessMsg("备份当前版本到 " + backupFolder);
    return warName;
}
 
Example 9
Source Project: zrlog   Source File: UploadController.java    License: Apache License 2.0 6 votes vote down vote up
public UploadFileResponse thumbnail() throws IOException {
    String uploadFieldName = "imgFile";
    String uri = generatorUri(uploadFieldName);
    File imgFile = getFile(uploadFieldName).getFile();
    String finalFilePath = PathKit.getWebRootPath() + uri;
    byte[] bytes = IOUtil.getByteByInputStream(new FileInputStream(imgFile));
    File thumbnailFile = new File(finalFilePath);
    if (!thumbnailFile.getParentFile().exists()) {
        thumbnailFile.getParentFile().mkdirs();
    }
    int height = -1;
    int width = -1;
    if (!".gif".endsWith(uri)) {
        IOUtil.writeBytesToFile(ThumbnailUtil.jpeg(bytes, 1f), thumbnailFile);
        BufferedImage bimg = ImageIO.read(thumbnailFile);
        height = bimg.getHeight();
        width = bimg.getWidth();
    } else {
        IOUtil.writeBytesToFile(bytes, thumbnailFile);
    }
    UploadFileResponse uploadFileResponse = new UploadService().getCloudUrl(getRequest().getContextPath(), uri, finalFilePath, getRequest(), AdminTokenThreadLocal.getUser());
    uploadFileResponse.setUrl(uploadFileResponse.getUrl() + "?h=" + height + "&w=" + width);
    imgFile.delete();
    return uploadFileResponse;
}
 
Example 10
Source Project: zrlog   Source File: AdminArticlePageController.java    License: Apache License 2.0 6 votes vote down vote up
public String preview() {
    Integer logId = getParaToInt("id");
    if (logId != null) {
        Log log = new Log().adminFindLogByLogId(logId);
        if (log != null) {
            log.put("lastLog", new Log().findLastLog(logId, I18nUtil.getStringFromRes("noLastLog")));
            log.put("nextLog", new Log().findNextLog(logId, I18nUtil.getStringFromRes("noNextLog")));
            setAttr("log", log.getAttrs());
            TemplateHelper.fillArticleInfo(log, getRequest(), "");
        }
        return getTemplatePath() + "/detail" + ZrLogUtil.getViewExt(new TemplateService().getTemplateVO(JFinal.me().getContextPath(),
                new File(PathKit.getWebRootPath() + getTemplatePath())).getViewType());
    } else {
        return Constants.NOT_FOUND_PAGE;
    }
}
 
Example 11
Source Project: zrlog   Source File: InstallController.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * 检查数据库是否可以正常连接使用,无法连接时给出相应的提示
 */
public String testDbConn() {
    Map<String, String> dbConn = new HashMap<>();
    dbConn.put("jdbcUrl", "jdbc:mysql://" + getPara("dbhost") + ":" + getPara("port") + "/" + getPara("dbname")
            + "?" + ZrLogConfig.JDBC_URL_BASE_QUERY_PARAM);
    dbConn.put("user", getPara("dbuser"));
    dbConn.put("password", getPara("dbpwd"));
    dbConn.put("driverClass", "com.mysql.cj.jdbc.Driver");
    TestConnectDbResult testConnectDbResult = new InstallService(PathKit.getWebRootPath() + "/WEB-INF", dbConn).testDbConn();
    if (testConnectDbResult.getError() != 0) {
        setAttr("errorMsg", "[Error-" + testConnectDbResult.getError() + "] - " + I18nUtil.getStringFromRes("connectDbError_" + testConnectDbResult.getError()));
        return index();
    } else {
        JFinal.me().getServletContext().setAttribute("dbConn", dbConn);
        return "/install/message";
    }
}
 
Example 12
Source Project: zrlog   Source File: InstallController.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * 数据库检查通过后,根据填写信息,执行数据表,表数据的初始化
 */
public String install() {
    Map<String, String> dbConn = (Map<String, String>) JFinal.me().getServletContext().getAttribute("dbConn");
    Map<String, String> configMsg = new HashMap<>();
    configMsg.put("title", getPara("title"));
    configMsg.put("second_title", getPara("second_title"));
    configMsg.put("username", getPara("username"));
    configMsg.put("password", getPara("password"));
    configMsg.put("email", getPara("email"));
    if (new InstallService(PathKit.getWebRootPath() + "/WEB-INF", dbConn, configMsg).install()) {
        final ZrLogConfig config = (ZrLogConfig) JFinal.me().getServletContext().getAttribute("config");
        //通知启动插件,配置库连接等操作
        config.installFinish();
        return "/install/success";
    } else {
        setAttr("errorMsg", "[Error-" + TestConnectDbResult.UNKNOWN.getError() + "] - " + I18nUtil.getStringFromRes("connectDbError_" + TestConnectDbResult.UNKNOWN.getError()));
        return "/install/message";
    }
}
 
Example 13
public static void main(String[] args) {
	// base model 所使用的包名
	String baseModelPackageName = "com.demo.common.model.base";
	// base model 文件保存路径
	String baseModelOutputDir = PathKit.getWebRootPath() + "/src/main/java/com/demo/common/model/base";
	
	// model 所使用的包名 (MappingKit 默认使用的包名)
	String modelPackageName = "com.demo.common.model";
	// model 文件保存路径 (MappingKit 与 DataDictionary 文件默认保存路径)
	String modelOutputDir = baseModelOutputDir + "/..";
	
	// 创建生成器
	Generator generator = new Generator(getDataSource(), baseModelPackageName, baseModelOutputDir, modelPackageName, modelOutputDir);
	
	// 配置是否生成备注
	generator.setGenerateRemarks(true);
	
	// 设置数据库方言
	generator.setDialect(new MysqlDialect());
	
	// 设置是否生成链式 setter 方法
	generator.setGenerateChainSetter(false);
	
	// 添加不需要生成的表名
	generator.addExcludedTable("adv");
	
	// 设置是否在 Model 中生成 dao 对象
	generator.setGenerateDaoInModel(false);
	
	// 设置是否生成字典文件
	generator.setGenerateDataDictionary(false);
	
	// 设置需要被移除的表名前缀用于生成modelName。例如表名 "osc_user",移除前缀 "osc_"后生成的model名为 "User"而非 OscUser
	generator.setRemovedTableNamePrefixes("t_");
	
	// 生成
	generator.generate();
}
 
Example 14
Source Project: jfinal-ext3   Source File: SpringPlugin.java    License: Apache License 2.0 5 votes vote down vote up
public boolean start() {
	if (ctx != null)
		IocInterceptor.ctx = ctx;
	else if (configurations != null)
		IocInterceptor.ctx = new FileSystemXmlApplicationContext(configurations);
	else
		IocInterceptor.ctx = new FileSystemXmlApplicationContext(PathKit.getWebRootPath() + "/WEB-INF/applicationContext.xml");
	return true;
}
 
Example 15
Source Project: jfinal-ext3   Source File: ConfigKit.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * @param includeResources
 * @param excludeResources
 * @param reload
 */
static void init(List<String> includeResources, List<String> excludeResources, boolean reload) {
    ConfigKit.includeResources = includeResources;
    ConfigKit.excludeResources = excludeResources;
    ConfigKit.reload = reload;
    for (final String resource : includeResources) {
    LOG.debug("include :" + resource);
        File[] propertiesFiles = new File(PathKit.getRootClassPath()).listFiles(new FileFilter() {

            @Override
            public boolean accept(File pathname) {
                return Pattern.compile(resource).matcher(pathname.getName()).matches();
            }
            
        });
        for (File file : propertiesFiles) {
            String fileName = file.getName();
            LOG.debug("fileName:" + fileName);
            boolean excluded = false;
            for (String exclude : excludeResources) {
                if (Pattern.compile(exclude).matcher(file.getName()).matches()) {
                    excluded = true;
                }
            }
            if (excluded) {
                continue;
            }
            lastmodifies.put(fileName, new File(fileName).lastModified());
            Map<String, String> mapData = Maps.fromProperties(new Prop(fileName).getProperties());
            map.putAll(mapData);
        }
    }
    LOG.debug("map" + map);
    LOG.info("config init success!");
}
 
Example 16
Source Project: jboot   Source File: JbootCoreConfig.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * 设置必要的系统参数:
 * 有些组件,比如 apollo、sentinel 等配置需要通过 System Properites来进行配置的
 */
private void initSystemProperties() {

    //加载 jboot-system.properties 代替启动参数的 -D 配置
    File spf = new File(PathKit.getRootClassPath(), "jboot-system.properties");
    if (spf.exists() && spf.isFile()) {
        Properties properties = PropKit.use(spf).getProperties();
        if (properties != null && !properties.isEmpty()) {
            for (Object key : properties.keySet()) {
                if (StrUtil.isNotBlank(key)) {
                    String newKey = key.toString().trim();
                    String systemValue = System.getProperty(newKey);
                    if (StrUtil.isNotBlank(systemValue)) {
                        continue;
                    }
                    String newValue = properties.getProperty(newKey);
                    if (StrUtil.isNotBlank(newValue)) {
                        System.setProperty(newKey, newValue.trim());
                    }
                }
            }
        }
    }

    //apollo 配置
    ApolloServerConfig apolloConfig = Jboot.config(ApolloServerConfig.class);
    if (apolloConfig.isEnable() && apolloConfig.isConfigOk()) {
        System.setProperty("app.id", apolloConfig.getAppId());
        System.setProperty("apollo.meta", apolloConfig.getMeta());
    }

}
 
Example 17
Source Project: jboot   Source File: JbootScheduleManager.java    License: Apache License 2.0 5 votes vote down vote up
public JbootScheduleManager() {
    config = Jboot.config(JbooScheduleConfig.class);
    fixedScheduler = new ScheduledThreadPoolExecutor(config.getPoolSize(),new NamedThreadFactory("jboot-scheduler"));

    File cron4jProperties = new File(PathKit.getRootClassPath(), config.getCron4jFile());
    cron4jPlugin = cron4jProperties.exists()
            ? new JbootCron4jPlugin(new Prop(config.getCron4jFile()))
            : new JbootCron4jPlugin();
}
 
Example 18
Source Project: jboot   Source File: JbootEhcacheImpl.java    License: Apache License 2.0 5 votes vote down vote up
public JbootEhcacheImpl() {
    JbootEhCacheConfig config = Jboot.config(JbootEhCacheConfig.class);
    if (StrUtil.isBlank(config.getConfigFileName())) {
        cacheManager = CacheManager.create();
    } else {
        String configPath = config.getConfigFileName();
        if (!configPath.startsWith("/")){
            configPath = PathKit.getRootClassPath()+"/"+configPath;
        }
        cacheManager = CacheManager.create(configPath);
    }
}
 
Example 19
@Override
public void onInit() {
    try {
        URL resourceUrl = JPressCoreInitializer.class.getResource("/");
        if (resourceUrl != null) {
            PathKit.setWebRootPath(resourceUrl.toURI().getPath());
        }
        EhcacheManager.init();
    } catch (URISyntaxException e) {
        e.printStackTrace();
    }
}
 
Example 20
Source Project: jpress   Source File: AddonManager.java    License: GNU Lesser General Public License v3.0 5 votes vote down vote up
private void doBackupOldAddon(AddonInfo oldAddon) throws IOException {

        //备份 资源文件
        String resPath = PathKit.getWebRootPath()
                + File.separator
                + "addons"
                + File.separator
                + oldAddon.getId();

        String resBakPath = resPath + "_bak";

        //清空之前的备份文件
        File resBakPathDir = new File(resBakPath);
        if (resBakPathDir.exists()) {
            FileUtils.deleteDirectory(resBakPathDir);
        }

        //备份资源文件
        FileUtils.moveDirectory(new File(resPath), resBakPathDir);

        File jarFile = oldAddon.buildJarFile();

        File bakJarFile = new File(jarFile.getAbsolutePath() + "_bak");
        if (bakJarFile.exists()) {
            FileUtils.deleteQuietly(bakJarFile);
        }

        //备份jar文件
        FileUtils.moveFile(jarFile, bakJarFile);
    }
 
Example 21
Source Project: jpress   Source File: AddonManager.java    License: GNU Lesser General Public License v3.0 5 votes vote down vote up
private void doDeleteNewAddon(AddonInfo addon) {
    AddonUtil.clearAddonInfoCache(addon.buildJarFile());

    //删除已解压缩的资源文件
    FileUtils.deleteQuietly(new File(PathKit.getWebRootPath(), "addons/" + addon.getId()));

    //删除jar包
    AddonUtil.forceDelete(addon.buildJarFile());

    //删除插件列表缓存
    addonsMap.remove(addon.getId());
}
 
Example 22
Source Project: jpress   Source File: AddonInfo.java    License: GNU Lesser General Public License v3.0 5 votes vote down vote up
public File buildJarFile() {

        String webRoot = PathKit.getWebRootPath();

        StringBuilder fileName = new StringBuilder(webRoot);
        fileName.append(File.separator);
        fileName.append("WEB-INF");
        fileName.append(File.separator);
        fileName.append("addons");
        fileName.append(File.separator);
        fileName.append(getId());
        fileName.append(".jar");

        return new File(fileName.toString());
    }
 
Example 23
Source Project: jpress   Source File: AddonUtil.java    License: GNU Lesser General Public License v3.0 5 votes vote down vote up
public static String getAddonBasePath(String addonId) {
    StringBuilder basePath = new StringBuilder(PathKit.getWebRootPath());
    basePath.append(File.separator)
            .append("addons")
            .append(File.separator)
            .append(addonId);
    return basePath.toString();
}
 
Example 24
public List<Template> getInstalledTemplates() {
    String basePath = PathKit.getWebRootPath() + "/templates";

    List<File> templateFolderList = new ArrayList<File>();
    scanTemplateFloders(new File(basePath), templateFolderList);

    List<Template> templatelist = null;
    if (templateFolderList.size() > 0) {
        templatelist = new ArrayList<>();
        for (File templateFolder : templateFolderList) {
            templatelist.add(new Template(templateFolder));
        }
    }
    return templatelist;
}
 
Example 25
Source Project: jpress   Source File: Template.java    License: GNU Lesser General Public License v3.0 5 votes vote down vote up
/**
 * 卸载模板
 */
public void uninstall() {
    StringBuilder newFileName = new StringBuilder(PathKit.getWebRootPath());
    newFileName.append(File.separator);
    newFileName.append("templates");
    newFileName.append(File.separator);
    newFileName.append("dockers");
    File templateRootPath = new File(newFileName.toString());

    File delPath = findInstallPath(templateRootPath,getAbsolutePathFile());
    FileUtils.deleteQuietly(delPath);
}
 
Example 26
Source Project: jpress   Source File: Installer.java    License: GNU Lesser General Public License v3.0 5 votes vote down vote up
private static void init() {
    File lockFile = new File(PathKit.getRootClassPath(), "install.lock");
    boolean lockFileOk = lockFile.exists() && lockFile.isFile();

    File propertieFile = new File(PathKit.getRootClassPath(), "jboot.properties");
    boolean propertieFileOk = propertieFile.exists() && propertieFile.isFile();

    installed = lockFileOk && propertieFileOk;
}
 
Example 27
Source Project: zrlog   Source File: TemplateService.java    License: Apache License 2.0 5 votes vote down vote up
public UploadTemplateResponse upload(String templateName, File file) throws IOException {
    String finalPath = PathKit.getWebRootPath() + Constants.TEMPLATE_BASE_PATH;
    String finalFile = finalPath + templateName;
    FileUtils.deleteFile(finalFile);
    //start extract template file
    FileUtils.moveOrCopyFile(file.toString(), finalFile, true);
    UploadTemplateResponse response = new UploadTemplateResponse();
    response.setMessage(I18nUtil.getStringFromRes("templateUploadSuccess"));
    String extractFolder = finalPath + templateName.replace(".zip", "") + "/";
    FileUtils.deleteFile(extractFolder);
    ZipUtil.unZip(finalFile, extractFolder);
    return response;
}
 
Example 28
@AdminMenu(text = "根目录", groupId = JPressConsts.SYSTEM_MENU_ATTACHMENT, order = 99)
public void root() {
    File rootFile = new File(PathKit.getWebRootPath());
    String name = getPara("name");
    File[] files = StrUtil.isBlank(name)
            ? rootFile.listFiles(pathname -> !pathname.isDirectory())
            : rootFile.listFiles(pathname -> !pathname.isDirectory() && pathname.getName().contains(name));

    setAttr("files", RootFile.toFiles(files));
    render("attachment/root.html");
}
 
Example 29
public void doUplaodRootFile() {
    if (!isMultipartRequest()) {
        renderError(404);
        return;
    }

    UploadFile uploadFile = getFile();
    if (uploadFile == null) {
        renderJson(Ret.fail().set("message", "请选择要上传的文件"));
        return;
    }

    File file = uploadFile.getFile();
    if (AttachmentUtils.isUnSafe(file)) {
        file.delete();
        renderJson(Ret.fail().set("message", "不支持此类文件上传"));
        return;
    }

    File rootFile = new File(PathKit.getWebRootPath(), file.getName());
    if (rootFile.exists()) {
        file.delete();
        renderJson(Ret.fail().set("message", "该文件已经存在,请手动删除后再重新上传。"));
        return;
    }

    try {
        FileUtils.moveFile(file, rootFile);
        rootFile.setReadable(true, false);
        renderOkJson();
        return;
    } catch (IOException e) {
        e.printStackTrace();
    }

    renderJson(Ret.fail().set("message", "系统错误。"));
}
 
Example 30
public void detail() {
    Long id = getIdPara();

    Attachment attachment = service.findById(id);

    setAttr("attachment", attachment);

    File attachmentFile = new File(PathKit.getWebRootPath(), attachment.getPath());
    setAttr("attachmentName", attachmentFile.getName());

    long fileLen = attachmentFile.length();
    String fileLenUnit = "Byte";
    if (fileLen > 1024) {
        fileLen = fileLen / 1024;
        fileLenUnit = "KB";
    }
    if (fileLen > 1024) {
        fileLen = fileLen / 1024;
        fileLenUnit = "MB";
    }
    setAttr("attachmentSize", fileLen + fileLenUnit);
    try {
        if (AttachmentUtils.isImage(attachment.getPath())) {
            String ratio = ImageUtils.ratioAsString(attachmentFile.getAbsolutePath());
            setAttr("attachmentRatio", ratio == null ? "unknow" : ratio);
        }
    } catch (Throwable e) {
        LOG.error("detail() ratioAsString error", e);
    }

    render("attachment/detail.html");
}