cn.hutool.core.io.FileUtil Java Examples

The following examples show how to use cn.hutool.core.io.FileUtil. 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: Jpom   Author: jiangzeyin   File: BuildUtil.java    License: MIT License 6 votes vote down vote up
/**
 * 如果为文件夹自动打包为zip ,反之返回null
 *
 * @param file file
 * @return 压缩包文件
 */
public static File isDirPackage(File file) {
    if (file.isFile()) {
        return null;
    }
    String name = FileUtil.getName(file);
    if (StrUtil.isEmpty(name)) {
        name = "result";
    }
    File zipFile = FileUtil.file(file.getParentFile().getParentFile(), name + ".zip");
    if (!zipFile.exists()) {
        // 不存在则打包
        ZipUtil.zip(file.getAbsolutePath(), zipFile.getAbsolutePath());
    }
    return zipFile;
}
 
Example #2
Source Project: SENS   Author: saysky   File: SensUtils.java    License: GNU General Public License v3.0 6 votes vote down vote up
/**
 * 获取备份文件信息
 *
 * @param dir dir
 * @return List
 */
public static List<BackupDto> getBackUps(String dir) {
    String srcPathStr = System.getProperties().getProperty("user.home") + "/sens/backup/" + dir;
    File srcPath = new File(srcPathStr);
    File[] files = srcPath.listFiles();
    List<BackupDto> backupDtos = new ArrayList<>();
    BackupDto backupDto = null;
    //遍历文件
    if (null != files) {
        for (File file : files) {
            if (file.isFile()) {
                if (StringUtils.equals(file.getName(), ".DS_Store")) {
                    continue;
                }
                backupDto = new BackupDto();
                backupDto.setFileName(file.getName());
                backupDto.setCreateAt(getCreateTime(file.getAbsolutePath()));
                backupDto.setFileType(FileUtil.getType(file));
                backupDto.setFileSize(parseSize(file.length()));
                backupDto.setBackupType(dir);
                backupDtos.add(backupDto);
            }
        }
    }
    return backupDtos;
}
 
Example #3
Source Project: datax-web   Author: WeiYe-Jing   File: ExecutorJobHandler.java    License: MIT License 6 votes vote down vote up
private String generateTemJsonFile(String jobJson) {
    String tmpFilePath;
    String dataXHomePath = SystemUtils.getDataXHomePath();
    if (StringUtils.isNotEmpty(dataXHomePath)) {
        jsonPath = dataXHomePath + DEFAULT_JSON;
    }
    if (!FileUtil.exist(jsonPath)) {
        FileUtil.mkdir(jsonPath);
    }
    tmpFilePath = jsonPath + "jobTmp-" + IdUtil.simpleUUID() + ".conf";
    // 根据json写入到临时本地文件
    try (PrintWriter writer = new PrintWriter(tmpFilePath, "UTF-8")) {
        writer.println(jobJson);
    } catch (FileNotFoundException | UnsupportedEncodingException e) {
        JobLogger.log("JSON 临时文件写入异常:" + e.getMessage());
    }
    return tmpFilePath;
}
 
Example #4
Source Project: Jpom   Author: jiangzeyin   File: JsonFileUtil.java    License: MIT License 6 votes vote down vote up
/**
 * 读取json 文件,同步
 *
 * @param path 路径
 * @return JSON
 * @throws FileNotFoundException 文件异常
 */
public static JSON readJson(String path) throws FileNotFoundException {
    File file = new File(path);
    if (!file.exists()) {
        throw new FileNotFoundException("没有找到对应配置文件:" + path);
    }
    READ_LOCK.lock();
    // 防止多线程操作文件异常
    try {
        String json = FileUtil.readString(file, CharsetUtil.UTF_8);
        if (StrUtil.isEmpty(json)) {
            return new JSONObject();
        }
        try {
            return (JSON) JSON.parse(json);
        } catch (Exception e) {
            throw new JpomRuntimeException("数据文件内容错误,请检查文件是否被非法修改:" + path, e);
        }
    } finally {
        READ_LOCK.unlock();
    }
}
 
Example #5
Source Project: Jpom   Author: jiangzeyin   File: JvmUtil.java    License: MIT License 6 votes vote down vote up
private static boolean checkFile(String fileName, String mainClass) {
    try {
        File file = FileUtil.file(fileName);
        if (!file.exists() || file.isDirectory()) {
            return false;
        }
        try (JarFile jarFile1 = new JarFile(file)) {
            Manifest manifest = jarFile1.getManifest();
            Attributes attributes = manifest.getMainAttributes();
            String jarMainClass = attributes.getValue(Attributes.Name.MAIN_CLASS);
            String jarStartClass = attributes.getValue("Start-Class");
            return StrUtil.equals(mainClass, jarMainClass) || StrUtil.equals(mainClass, jarStartClass);
        }
    } catch (Exception e) {
        return false;
    }
}
 
Example #6
Source Project: stone   Author: Alension   File: BackupController.java    License: GNU General Public License v3.0 6 votes vote down vote up
/**
 * 备份数据库
 *
 * @return 重定向到/admin/backup
 */
public JsonResult backupDatabase() {
    try {
        if (HaloUtils.getBackUps(BackupTypeEnum.DATABASES.getDesc()).size() > CommonParamsEnum.TEN.getValue()) {
            FileUtil.del(System.getProperties().getProperty("user.home") + "/halo/backup/databases/");
        }
        final String srcPath = System.getProperties().getProperty("user.home") + "/halo/";
        final String distName = "databases_backup_" + DateUtil.format(DateUtil.date(), "yyyyMMddHHmmss");
        //压缩文件
        ZipUtil.zip(srcPath + "halo.mv.db", System.getProperties().getProperty("user.home") + "/halo/backup/databases/" + distName + ".zip");
        log.info("Current time: {}, database backup was performed.", DateUtil.now());
        return new JsonResult(ResultCodeEnum.SUCCESS.getCode(), localeMessageUtil.getMessage("code.admin.backup.backup-success"));
    } catch (Exception e) {
        log.error("Backup database failed: {}", e.getMessage());
        return new JsonResult(ResultCodeEnum.FAIL.getCode(), localeMessageUtil.getMessage("code.admin.backup.backup-failed"));
    }
}
 
Example #7
Source Project: stone   Author: Alension   File: BackupController.java    License: GNU General Public License v3.0 6 votes vote down vote up
/**
 * 备份资源文件 重要
 *
 * @return JsonResult
 */
public JsonResult backupResources() {
    try {
        if (HaloUtils.getBackUps(BackupTypeEnum.RESOURCES.getDesc()).size() > CommonParamsEnum.TEN.getValue()) {
            FileUtil.del(System.getProperties().getProperty("user.home") + "/halo/backup/resources/");
        }
        final File path = new File(ResourceUtils.getURL("classpath:").getPath());
        final String srcPath = path.getAbsolutePath();
        final String distName = "resources_backup_" + DateUtil.format(DateUtil.date(), "yyyyMMddHHmmss");
        //执行打包
        ZipUtil.zip(srcPath, System.getProperties().getProperty("user.home") + "/halo/backup/resources/" + distName + ".zip");
        log.info("Current time: {}, the resource file backup was performed.", DateUtil.now());
        return new JsonResult(ResultCodeEnum.SUCCESS.getCode(), localeMessageUtil.getMessage("code.admin.backup.backup-success"));
    } catch (Exception e) {
        log.error("Backup resource file failed: {}", e.getMessage());
        return new JsonResult(ResultCodeEnum.FAIL.getCode(), localeMessageUtil.getMessage("code.admin.backup.backup-failed"));
    }
}
 
Example #8
Source Project: mall4j   Author: gz-yami   File: AttachFileServiceImpl.java    License: GNU Affero General Public License v3.0 6 votes vote down vote up
@Override
@Transactional(rollbackFor = Exception.class)
public String uploadFile(byte[] bytes,String originalName) throws QiniuException {
	String extName = FileUtil.extName(originalName);
	String fileName =DateUtil.format(new Date(), NORM_MONTH_PATTERN)+ IdUtil.simpleUUID() + "." + extName;


	AttachFile attachFile = new AttachFile();
	attachFile.setFilePath(fileName);
	attachFile.setFileSize(bytes.length);
	attachFile.setFileType(extName);
	attachFile.setUploadTime(new Date());
	attachFileMapper.insert(attachFile);

	String upToken = auth.uploadToken(qiniu.getBucket(),fileName);
    Response response = uploadManager.put(bytes, fileName, upToken);
    Json.parseObject(response.bodyString(),  DefaultPutRet.class);
	return fileName;
}
 
Example #9
Source Project: v-mock   Author: i-am-vt   File: DataMigrationUtils.java    License: MIT License 6 votes vote down vote up
/**
 * 获取所有历史DB文件集合
 *
 * @return List<File>集合
 */
private static List<File> getHistoryDataFileList() {
    // 历史数据库文件都是存在临时目录下
    String tempFilePath = System.getProperty("java.io.tmpdir");
    File[] tempFileArr = FileUtil.ls(tempFilePath);
    // 临时目录没文件,返回 null
    if (ArrayUtil.isEmpty(tempFileArr)) {
        return null;
    }
    // 过滤掉非db文件
    Stream<File> filesStream = Arrays.stream(tempFileArr)
            .filter(file -> file.isFile() && file.getName().matches("sqlite-jdbc-tmp-.*\\.db"));
    // 转为List返回
    List<File> fileList = filesStream.collect(Collectors.toList());
    return fileList;
}
 
Example #10
Source Project: Jpom   Author: jiangzeyin   File: AgentWebSocketTomcatHandle.java    License: MIT License 6 votes vote down vote up
private void runMsg(Session session, JSONObject reqJson) throws Exception {
    try {
        String fileName = reqJson.getString("fileName");
        WebAopLog webAopLog = SpringUtil.getBean(WebAopLog.class);
        // 进入管理页面后需要实时加载日志
        File file = FileUtil.file(webAopLog.getPropertyValue(), fileName);
        File file1 = CACHE_FILE.get(session.getId());
        if (file1 != null && !file1.equals(file)) {
            // 离线上一个日志
            AgentFileTailWatcher.offlineFile(file, session);
        }
        try {
            AgentFileTailWatcher.addWatcher(file, session);
            CACHE_FILE.put(session.getId(), file);
        } catch (IOException io) {
            DefaultSystemLog.getLog().error("监听日志变化", io);
            SocketSessionUtil.send(session, io.getMessage());
        }
    } catch (Exception e) {
        DefaultSystemLog.getLog().error("执行命令失败", e);
        SocketSessionUtil.send(session, "执行命令失败,详情如下:");
        SocketSessionUtil.send(session, ExceptionUtil.stacktraceToString(e));
    }
}
 
Example #11
Source Project: Jpom   Author: jiangzeyin   File: CacheManageController.java    License: MIT License 6 votes vote down vote up
/**
 * 清空缓存
 *
 * @param type 类型
 * @return json
 */
@RequestMapping(value = "clearCache.json", method = RequestMethod.POST, produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
@ResponseBody
@OptLog(UserOperateLogV1.OptType.ClearCache)
@Feature(method = MethodFeature.CACHE)
public String clearCache(@ValidatorItem(value = ValidatorRule.NOT_BLANK, msg = "类型错误") String type) {
    switch (type) {
        case "serviceCacheFileSize":
            boolean clean = FileUtil.clean(ConfigBean.getInstance().getTempPath());
            if (!clean) {
                return JsonMessage.getString(504, "清空文件缓存失败");
            }
            break;
        case "serviceIpSize":
            LoginControl.LFU_CACHE.clear();
            break;
        default:
            return NodeForward.request(getNode(), getRequest(), NodeUrl.ClearCache).toString();

    }
    return JsonMessage.getString(200, "清空成功");
}
 
Example #12
Source Project: Jpom   Author: jiangzeyin   File: SvnKitUtil.java    License: MIT License 6 votes vote down vote up
/**
 * SVN检出
 *
 * @param userName   用户名
 * @param userPwd    密码
 * @param svnPath    仓库路径
 * @param targetPath 目录
 * @return Boolean
 * @throws SVNException svn
 */
public static String checkOut(String svnPath, String userName, String userPwd, File targetPath) throws SVNException {
    DefaultSVNOptions options = SVNWCUtil.createDefaultOptions(true);
    // 实例化客户端管理类
    SVNClientManager ourClientManager = SVNClientManager.newInstance(options, userName, userPwd);
    try {
        if (targetPath.exists()) {
            if (!FileUtil.file(targetPath, SVNFileUtil.getAdminDirectoryName()).exists()) {
                FileUtil.del(targetPath);
            } else {
                // 判断url是否变更
                if (!checkUrl(targetPath, svnPath, userName, userPwd)) {
                    FileUtil.del(targetPath);
                } else {
                    ourClientManager.getWCClient().doCleanup(targetPath);
                }
            }
        }
        return checkOut(ourClientManager, svnPath, targetPath);
    } finally {
        ourClientManager.dispose();
    }
}
 
Example #13
Source Project: Jpom   Author: jiangzeyin   File: ManageEditProjectController.java    License: MIT License 6 votes vote down vote up
private void moveTo(ProjectInfoModel old, ProjectInfoModel news) {
    // 移动目录
    if (!old.allLib().equals(news.allLib())) {
        File oldLib = new File(old.allLib());
        if (oldLib.exists()) {
            File newsLib = new File(news.allLib());
            FileUtil.move(oldLib, newsLib, true);
        }
    }
    // log
    if (!old.getLog().equals(news.getLog())) {
        File oldLog = new File(old.getLog());
        if (oldLog.exists()) {
            File newsLog = new File(news.getLog());
            FileUtil.move(oldLog, newsLog, true);
        }
        // logBack
        File oldLogBack = old.getLogBack();
        if (oldLogBack.exists()) {
            FileUtil.move(oldLogBack, news.getLogBack(), true);
        }
    }

}
 
Example #14
Source Project: Jpom   Author: jiangzeyin   File: ProjectFileControl.java    License: MIT License 6 votes vote down vote up
@RequestMapping(value = "download", method = RequestMethod.GET)
public String download(String id, String filename, String levelName) {
    String safeFileName = pathSafe(filename);
    if (StrUtil.isEmpty(safeFileName)) {
        return JsonMessage.getString(405, "非法操作");
    }
    try {
        ProjectInfoModel pim = projectInfoService.getItem(id);
        File file;
        if (StrUtil.isEmpty(levelName)) {
            file = FileUtil.file(pim.allLib(), filename);
        } else {
            file = FileUtil.file(pim.allLib(), levelName, filename);
        }
        if (file.isDirectory()) {
            return "暂不支持下载文件夹";
        }
        ServletUtil.write(getResponse(), file);
    } catch (Exception e) {
        DefaultSystemLog.getLog().error("下载文件异常", e);
    }
    return "下载失败。请刷新页面后重试";
}
 
Example #15
Source Project: Jpom   Author: jiangzeyin   File: TomcatManageController.java    License: MIT License 6 votes vote down vote up
/**
 * 上传文件
 *
 * @param id   tomcat id
 * @param path 文件路径
 * @return 操作结果
 */
@RequestMapping(value = "upload", method = RequestMethod.POST, produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
public String upload(String id, String path) {
    TomcatInfoModel tomcatInfoModel = tomcatEditService.getItem(id);

    MultipartFileBuilder multipartFileBuilder = createMultipart()
            .addFieldName("file");

    File dir = new File(tomcatInfoModel.getAppBase().concat(FileUtil.normalize(path)));

    multipartFileBuilder.setSavePath(dir.getAbsolutePath())
            .setUseOriginalFilename(true);
    // 保存
    try {
        multipartFileBuilder.save();
    } catch (IOException e) {
        return JsonMessage.getString(500, "上传异常");
    }

    return JsonMessage.getString(200, "上传成功");
}
 
Example #16
Source Project: Jpom   Author: jiangzeyin   File: TomcatManageController.java    License: MIT License 6 votes vote down vote up
/**
 * 下载文件
 *
 * @param id       tomcat id
 * @param filename 文件名
 * @param path     tomcat路径
 * @return 操作结果
 */
@RequestMapping(value = "download", method = RequestMethod.GET)
public String download(String id, String path, String filename) {
    filename = FileUtil.normalize(filename);
    path = FileUtil.normalize(path);
    try {
        TomcatInfoModel tomcatInfoModel = tomcatEditService.getItem(id);
        File file;
        //下载日志文件
        if ("_tomcat_log".equals(path)) {
            file = FileUtil.file(tomcatInfoModel.getPath(), "logs", filename);
        } else {
            file = FileUtil.file(tomcatInfoModel.getAppBase(), path, filename);
        }
        if (file.isDirectory()) {
            return "暂不支持下载文件夹";
        }
        ServletUtil.write(getResponse(), file);
    } catch (Exception e) {
        DefaultSystemLog.getLog().error("下载文件异常", e);
    }
    return "下载失败。请刷新页面后重试";
}
 
Example #17
Source Project: Jpom   Author: jiangzeyin   File: SshFileController.java    License: MIT License 6 votes vote down vote up
@RequestMapping(value = "list_file_data.json", method = RequestMethod.POST, produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
@ResponseBody
@Feature(method = MethodFeature.FILE)
public String listData(String id, String path, String children) throws SftpException {
    SshModel sshModel = sshService.getItem(id);
    if (sshModel == null) {
        return JsonMessage.getString(404, "不存在对应ssh");
    }
    if (StrUtil.isEmpty(path)) {
        return JsonMessage.getString(405, "请选择文件夹");
    }
    if (StrUtil.isNotEmpty(children)) {
        // 判断是否合法
        children = FileUtil.normalize(children);
        FileUtil.file(path, children);
    }
    List<String> fileDirs = sshModel.getFileDirs();
    if (!fileDirs.contains(path)) {
        return JsonMessage.getString(405, "没有配置此文件夹");
    }
    JSONArray jsonArray = listDir(sshModel, path, children);
    return JsonMessage.getString(200, "ok", jsonArray);
}
 
Example #18
Source Project: Jpom   Author: jiangzeyin   File: IndexController.java    License: MIT License 6 votes vote down vote up
/**
 * 返回节点项目状态信息
 *
 * @return array
 */
@RequestMapping(value = "status", method = RequestMethod.POST, produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
public String status() {
    List<ProjectInfoModel> projectInfoModels = projectInfoService.list();
    JSONObject jsonObject = new JSONObject();
    jsonObject.put("javaVirtualCount", JvmUtil.getJavaVirtualCount());
    jsonObject.put("osName", SystemUtil.getOsInfo().getName());
    jsonObject.put("jpomVersion", JpomManifest.getInstance().getVersion());
    jsonObject.put("javaVersion", SystemUtil.getJavaRuntimeInfo().getVersion());
    //  获取JVM中内存总大小
    long totalMemory = SystemUtil.getTotalMemory();
    jsonObject.put("totalMemory", FileUtil.readableFileSize(totalMemory));
    //
    long freeMemory = SystemUtil.getFreeMemory();
    jsonObject.put("freeMemory", FileUtil.readableFileSize(freeMemory));
    int count = 0;
    if (projectInfoModels != null) {
        count = projectInfoModels.size();
    }
    jsonObject.put("count", count);
    // 运行时间
    jsonObject.put("runTime", JpomManifest.getInstance().getUpTime());
    return JsonMessage.getString(200, "", jsonObject);
}
 
Example #19
Source Project: Jpom   Author: jiangzeyin   File: InternalController.java    License: MIT License 6 votes vote down vote up
/**
     * 导出内存信息
     *
     * @param tag 程序运行标识
     * @return json
     */
    @RequestMapping(value = "internal_ram", method = RequestMethod.GET)
    @ResponseBody
    public String ram(String tag, String copyId) {
        tag = ProjectInfoModel.JavaCopyItem.getTagId(tag, copyId);
        //
        String fileName = AgentConfigBean.getInstance().getTempPathName() + "/" + tag + "_java_ram.txt";
        fileName = FileUtil.normalize(fileName);
        try {
            int pid = AbstractProjectCommander.getInstance().getPid(tag);
            if (pid <= 0) {
                return JsonMessage.getString(400, "未运行");
            }
            String command = String.format("jmap -histo:live %s >> %s", pid, fileName);
            CommandUtil.execSystemCommand(command);
            downLoad(getResponse(), fileName);
        } catch (Exception e) {
            DefaultSystemLog.getLog().error(e.getMessage(), e);
//            getResponse().sendRedirect("internal?tag=" + tag);
        }
        return JsonMessage.getString(200, "");
    }
 
Example #20
Source Project: Jpom   Author: jiangzeyin   File: AutoBackLog.java    License: MIT License 6 votes vote down vote up
private static void checkProject(ProjectInfoModel projectInfoModel, ProjectInfoModel.JavaCopyItem javaCopyItem) {
    File file = javaCopyItem == null ? new File(projectInfoModel.getLog()) : projectInfoModel.getLog(javaCopyItem);
    if (!file.exists()) {
        return;
    }
    long len = file.length();
    if (len > MAX_SIZE.getSize()) {
        try {
            AbstractProjectCommander.getInstance().backLog(projectInfoModel, javaCopyItem);
        } catch (Exception ignored) {
        }
    }
    // 清理过期的文件
    File logFile = javaCopyItem == null ? projectInfoModel.getLogBack() : projectInfoModel.getLogBack(javaCopyItem);
    DateTime nowTime = DateTime.now();
    List<File> files = FileUtil.loopFiles(logFile, pathname -> {
        DateTime dateTime = DateUtil.date(pathname.lastModified());
        long days = DateUtil.betweenDay(dateTime, nowTime, false);
        long saveDays = AgentExtConfigBean.getInstance().getLogSaveDays();
        return days > saveDays;
    });
    files.forEach(FileUtil::del);
}
 
Example #21
Source Project: Jpom   Author: jiangzeyin   File: AgentCacheManageController.java    License: MIT License 6 votes vote down vote up
/**
 * 清空缓存
 *
 * @param type 缓存类型
 * @return json
 */
@RequestMapping(value = "clearCache", method = RequestMethod.POST, produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
public String clearCache(@ValidatorItem(value = ValidatorRule.NOT_BLANK, msg = "类型错误") String type) {
    switch (type) {
        case "pidPort":
            AbstractProjectCommander.PID_PORT.clear();
            break;
        case "pidName":
            AbstractProjectCommander.PID_JPOM_NAME.clear();
            break;
        case "fileSize":
            boolean clean = FileUtil.clean(ConfigBean.getInstance().getTempPath());
            if (!clean) {
                return JsonMessage.getString(504, "清空文件缓存失败");
            }
            break;
        case "pidError":
            JvmUtil.PID_ERROR.clear();
            break;
        default:
            return JsonMessage.getString(405, "没有对应类型:" + type);

    }
    return JsonMessage.getString(200, "清空成功");
}
 
Example #22
Source Project: Jpom   Author: jiangzeyin   File: ProjectInfoModel.java    License: MIT License 6 votes vote down vote up
/**
 * 获取项目文件中的所有jar 文件
 *
 * @param projectInfoModel 项目
 * @return list
 */
public static List<File> listJars(ProjectInfoModel projectInfoModel) {
    File fileLib = new File(projectInfoModel.allLib());
    File[] files = fileLib.listFiles();
    List<File> files1 = new ArrayList<>();
    if (files != null) {
        for (File file : files) {
            if (!file.isFile()) {
                continue;
            }
            if (projectInfoModel.getRunMode() == RunMode.ClassPath || projectInfoModel.getRunMode() == RunMode.Jar) {
                if (!StrUtil.endWith(file.getName(), FileUtil.JAR_FILE_EXT, true)) {
                    continue;
                }
            } else if (projectInfoModel.getRunMode() == RunMode.JarWar) {
                if (!StrUtil.endWith(file.getName(), "war", true)) {
                    continue;
                }
            }
            files1.add(file);
        }
    }
    return files1;
}
 
Example #23
Source Project: Jpom   Author: jiangzeyin   File: SshInstallAgentController.java    License: MIT License 6 votes vote down vote up
private String getAuthorize(SshModel sshModel, NodeModel nodeModel, String path) {
    File saveFile = null;
    try {
        String tempFilePath = ServerConfigBean.getInstance().getUserTempPath().getAbsolutePath();
        //  获取远程的授权信息
        String normalize = FileUtil.normalize(StrUtil.format("{}/{}/{}", path, ConfigBean.DATA, ConfigBean.AUTHORIZE));
        saveFile = FileUtil.file(tempFilePath, IdUtil.fastSimpleUUID() + ConfigBean.AUTHORIZE);
        sshService.download(sshModel, normalize, saveFile);
        //
        String json = FileUtil.readString(saveFile, CharsetUtil.CHARSET_UTF_8);
        AgentAutoUser autoUser = JSONObject.parseObject(json, AgentAutoUser.class);
        nodeModel.setLoginPwd(autoUser.getAgentPwd());
        nodeModel.setLoginName(autoUser.getAgentName());
    } catch (Exception e) {
        DefaultSystemLog.getLog().error("拉取授权信息失败", e);
        return JsonMessage.getString(500, "获取授权信息失败", e);
    } finally {
        FileUtil.del(saveFile);
    }
    return null;
}
 
Example #24
Source Project: simple-robot-core   Author: ForteScarlet   File: ImageCQCode.java    License: Apache License 2.0 5 votes vote down vote up
/**
     * 私有构造 为了测试暂时的公共构造
     * @param params 参数列表
     */
    private ImageCQCode(Map<String, String> params) throws IOException {
        super(CQ_CODE_TYPE.getFunction(), CQ_CODE_TYPE, params);
        //获取文件md5参数
        String fileId = params.get("file");
        if(fileId == null){
            throw new CQParamsException("noParam", "file");
        }
        //解析参数以获取图片地址
        this.IMAGE_FILE = CQUtils.getImageFile(fileId);

        //获取文件中的参数并赋值
        List<String> datas = FileUtil.readLines(this.IMAGE_FILE, this.ENCODING);
//        List<String> datas = FileUtils.readLines(this.IMAGE_FILE, this.ENCODING);
        //使用properties接收参数,则将字符串集合转化为Reader流对象

                                                //跳过第一行的数据
        Reader listReader = new StringListReader(datas.stream().skip(1).collect(Collectors.toList()));

        //加载参数
        Properties properties = new Properties();
        properties.load(listReader);

        //将参数赋值
        /*
            [image]
            md5=0A02C3998CC3AF7F390D1D8608441637
            width=1009
            height=1794
            size=225910
            url=https://gchat.qpic.cn/gchatpic_new/2209278137/581250423-2837957861-0A02C3998CC3AF7F390D1D8608441637/0?vuin=2257290268&term=2
            addtime=1555648320
     */
        MD5 = properties.getProperty("md5");
        WIDTH = Double.parseDouble(properties.getProperty("width"));
        HEIGHT = Double.parseDouble(properties.getProperty("height"));
        SIZE = Long.parseLong(properties.getProperty("size"));
        URL = properties.getProperty("url");
        ADD_TIME = Long.parseLong(properties.getProperty("addtime"));
    }
 
Example #25
Source Project: spring-boot-demo   Author: jiangsongHB   File: UploadController.java    License: MIT License 5 votes vote down vote up
@PostMapping(value = "/yun", consumes = MediaType.MULTIPART_FORM_DATA_VALUE)
public Dict yun(@RequestParam("file") MultipartFile file) {
	if (file.isEmpty()) {
		return Dict.create().set("code", 400).set("message", "文件内容为空");
	}
	String fileName = file.getOriginalFilename();
	String rawFileName = StrUtil.subBefore(fileName, ".", true);
	String fileType = StrUtil.subAfter(fileName, ".", true);
	String localFilePath = StrUtil.appendIfMissing(fileTempPath, "/") + rawFileName + "-" + DateUtil.current(false) + "." + fileType;
	try {
		file.transferTo(new File(localFilePath));
		Response response = qiNiuService.uploadFile(new File(localFilePath));
		if (response.isOK()) {
			JSONObject jsonObject = JSONUtil.parseObj(response.bodyString());

			String yunFileName = jsonObject.getStr("key");
			String yunFilePath = StrUtil.appendIfMissing(prefix, "/") + yunFileName;

			FileUtil.del(new File(localFilePath));

			log.info("【文件上传至七牛云】绝对路径:{}", yunFilePath);
			return Dict.create().set("code", 200).set("message", "上传成功").set("data", Dict.create().set("fileName", yunFileName).set("filePath", yunFilePath));
		} else {
			log.error("【文件上传至七牛云】失败,{}", JSONUtil.toJsonStr(response));
			FileUtil.del(new File(localFilePath));
			return Dict.create().set("code", 500).set("message", "文件上传失败");
		}
	} catch (IOException e) {
		log.error("【文件上传至七牛云】失败,绝对路径:{}", localFilePath);
		return Dict.create().set("code", 500).set("message", "文件上传失败");
	}
}
 
Example #26
Source Project: blog-sharon   Author: qinxuewu   File: BackupController.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * 删除备份
 *
 * @param fileName 文件名
 * @param type     备份类型
 * @return JsonResult
 */
@GetMapping(value = "delBackup")
@ResponseBody
public JsonResult delBackup(@RequestParam("fileName") String fileName,
                            @RequestParam("type") String type) {
    String srcPath = System.getProperties().getProperty("user.home") + "/halo/backup/" + type + "/" + fileName;
    try {
        FileUtil.del(srcPath);
        return new JsonResult(ResultCodeEnum.SUCCESS.getCode(), localeMessageUtil.getMessage("code.admin.common.delete-success"));
    } catch (Exception e) {
        return new JsonResult(ResultCodeEnum.FAIL.getCode(), localeMessageUtil.getMessage("code.admin.common.delete-failed"));
    }
}
 
Example #27
Source Project: MooTool   Author: rememberber   File: MybatisUtil.java    License: MIT License 5 votes vote down vote up
/**
 * 初始化数据库文件
 */
public static void initDbFile() throws SQLException {
    File configHomeDir = new File(SystemUtil.configHome);
    if (!configHomeDir.exists()) {
        configHomeDir.mkdirs();
    }
    // 不存在db文件时会自动创建一个
    String sql = FileUtil.readString(MybatisUtil.class.getResource("/db_init.sql"), CharsetUtil.UTF_8);
    executeSql(sql);
    needInit = true;
}
 
Example #28
Source Project: Jpom   Author: jiangzeyin   File: ThymeleafUtil.java    License: MIT License 5 votes vote down vote up
/**
 * 模板名称需要在 classpath:templates/plugin 下
 *
 * @param template  模板名称
 * @param variables 变量
 * @return 转换后的
 */
public static String process(String template, Map<String, Object> variables) {
    Context context = new Context();
    if (variables == null) {
        variables = new HashMap<>(10);
    }
    String normalize = FileUtil.normalize("plugin/" + template);
    // 用户变量
    UserModel userModel = BaseServerController.getUserModel();
    variables.put(LoginInterceptor.SESSION_NAME, userModel);
    context.setVariables(variables);
    ThymeleafUtil thymeleafUtil = SpringUtil.getBean(ThymeleafUtil.class);
    return thymeleafUtil.springTemplateEngine.process(normalize, context);
}
 
Example #29
Source Project: Jpom   Author: jiangzeyin   File: Test.java    License: MIT License 5 votes vote down vote up
public static void main(String[] args) {

        System.out.println(FileUtil.normalize("sss/ss/../ssss"));
        System.out.println(FileUtil.normalize("./ssss/ssss"));
        CacheControllerFeature.init();
        Map<ClassFeature, Set<MethodFeature>> classFeatureSetMap = CacheControllerFeature.getFeatureMap();
        ClassFeature monitor = ClassFeature.valueOf("MONITOR");
        System.out.println(monitor.getName());
        System.out.println(classFeatureSetMap);

        Class<?> typeArgument = ClassUtil.getTypeArgument(RoleService.class);
        System.out.println(typeArgument);
    }
 
Example #30
Source Project: stone   Author: Alension   File: ThemeController.java    License: GNU General Public License v3.0 5 votes vote down vote up
/**
 * 上传主题
 *
 * @param file 文件
 *
 * @return JsonResult
 */
@RequestMapping(value = "/upload", method = RequestMethod.POST)
@ResponseBody
public JsonResult uploadTheme(@RequestParam("file") MultipartFile file,
                              HttpServletRequest request) {
    try {
        if (!file.isEmpty()) {
            //获取项目根路径
            final File basePath = new File(ResourceUtils.getURL("classpath:").getPath());
            final File themePath = new File(basePath.getAbsolutePath(), new StringBuffer("templates/themes/").append(file.getOriginalFilename()).toString());
            file.transferTo(themePath);
            log.info("Upload topic success, path is " + themePath.getAbsolutePath());
            logsService.save(LogsRecord.UPLOAD_THEME, file.getOriginalFilename(), request);
            ZipUtil.unzip(themePath, new File(basePath.getAbsolutePath(), "templates/themes/"));
            FileUtil.del(themePath);
            HaloConst.THEMES.clear();
            HaloConst.THEMES = HaloUtils.getThemes();
        } else {
            log.error("Upload theme failed, no file selected");
            return new JsonResult(ResultCodeEnum.FAIL.getCode(), localeMessageUtil.getMessage("code.admin.theme.upload-no-file"));
        }
    } catch (Exception e) {
        log.error("Upload theme failed: {}", e.getMessage());
        return new JsonResult(ResultCodeEnum.FAIL.getCode(), localeMessageUtil.getMessage("code.admin.theme.upload-failed"));
    }
    return new JsonResult(ResultCodeEnum.SUCCESS.getCode(), localeMessageUtil.getMessage("code.admin.theme.upload-success"));
}