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 File: SshInstallAgentController.java From Jpom with MIT License | 6 votes |
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 #2
Source File: JvmUtil.java From Jpom with MIT License | 6 votes |
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 #3
Source File: SensUtils.java From SENS with GNU General Public License v3.0 | 6 votes |
/** * 获取备份文件信息 * * @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 #4
Source File: BackupController.java From stone with GNU General Public License v3.0 | 6 votes |
/** * 备份数据库 * * @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 #5
Source File: JsonFileUtil.java From Jpom with MIT License | 6 votes |
/** * 读取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 #6
Source File: ExecutorJobHandler.java From datax-web with MIT License | 6 votes |
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 #7
Source File: BackupController.java From stone with GNU General Public License v3.0 | 6 votes |
/** * 备份资源文件 重要 * * @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 File: AttachFileServiceImpl.java From mall4j with GNU Affero General Public License v3.0 | 6 votes |
@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 File: DataMigrationUtils.java From v-mock with MIT License | 6 votes |
/** * 获取所有历史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 File: AgentWebSocketTomcatHandle.java From Jpom with MIT License | 6 votes |
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 File: CacheManageController.java From Jpom with MIT License | 6 votes |
/** * 清空缓存 * * @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 File: SvnKitUtil.java From Jpom with MIT License | 6 votes |
/** * 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 File: ProjectFileControl.java From Jpom with MIT License | 6 votes |
@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 #14
Source File: BuildUtil.java From Jpom with MIT License | 6 votes |
/** * 如果为文件夹自动打包为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 #15
Source File: ProjectInfoModel.java From Jpom with MIT License | 6 votes |
/** * 获取项目文件中的所有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 #16
Source File: AgentCacheManageController.java From Jpom with MIT License | 6 votes |
/** * 清空缓存 * * @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 #17
Source File: AutoBackLog.java From Jpom with MIT License | 6 votes |
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 #18
Source File: InternalController.java From Jpom with MIT License | 6 votes |
/** * 导出内存信息 * * @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 #19
Source File: IndexController.java From Jpom with MIT License | 6 votes |
/** * 返回节点项目状态信息 * * @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 #20
Source File: SshFileController.java From Jpom with MIT License | 6 votes |
@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 #21
Source File: TomcatManageController.java From Jpom with MIT License | 6 votes |
/** * 下载文件 * * @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 #22
Source File: TomcatManageController.java From Jpom with MIT License | 6 votes |
/** * 上传文件 * * @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 #23
Source File: ManageEditProjectController.java From Jpom with MIT License | 6 votes |
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 #24
Source File: BackupController.java From blog-sharon with Apache License 2.0 | 5 votes |
/** * 删除备份 * * @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 #25
Source File: SystemConfigController.java From Jpom with MIT License | 5 votes |
@RequestMapping(value = "save_config.json", method = RequestMethod.POST, produces = MediaType.APPLICATION_JSON_UTF8_VALUE) public String saveConfig(String content, String restart) { if (StrUtil.isEmpty(content)) { return JsonMessage.getString(405, "内容不能为空"); } try { YamlPropertySourceLoader yamlPropertySourceLoader = new YamlPropertySourceLoader(); ByteArrayResource resource = new ByteArrayResource(content.getBytes()); yamlPropertySourceLoader.load("test", resource); } catch (Exception e) { DefaultSystemLog.getLog().warn("内容格式错误,请检查修正", e); return JsonMessage.getString(500, "内容格式错误,请检查修正:" + e.getMessage()); } if (JpomManifest.getInstance().isDebug()) { return JsonMessage.getString(405, "调试模式不支持在线修改,请到resource目录下"); } File resourceFile = ExtConfigBean.getResourceFile(); FileUtil.writeString(content, resourceFile, CharsetUtil.CHARSET_UTF_8); if (Convert.toBool(restart, false)) { // 重启 ThreadUtil.execute(() -> { try { Thread.sleep(2000); } catch (InterruptedException ignored) { } JpomApplication.restart(); }); } return JsonMessage.getString(200, "修改成功"); }
Example #26
Source File: CertificateController.java From Jpom with MIT License | 5 votes |
/** * 导出证书 * * @param id 项目id * @return 结果 */ @RequestMapping(value = "/export", method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_UTF8_VALUE) public String export(String id) { CertModel item = certService.getItem(id); if (null == item) { return JsonMessage.getString(400, "导出失败"); } String parent = FileUtil.file(item.getCert()).getParent(); File zip = ZipUtil.zip(parent); ServletUtil.write(getResponse(), zip); FileUtil.del(zip); return JsonMessage.getString(400, "导出成功"); }
Example #27
Source File: LogManageController.java From Jpom with MIT License | 5 votes |
@RequestMapping(value = "log_download", method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_UTF8_VALUE) @ResponseBody @Feature(method = MethodFeature.DOWNLOAD) public void logDownload(String nodeId, @ValidatorItem(value = ValidatorRule.NOT_BLANK, msg = "path错误") String path) { if (StrUtil.isNotEmpty(nodeId)) { NodeForward.requestDownload(getNode(), getRequest(), getResponse(), NodeUrl.DownloadSystemLog); return; } WebAopLog webAopLog = SpringUtil.getBean(WebAopLog.class); File file = FileUtil.file(webAopLog.getPropertyValue(), path); if (file.isFile()) { ServletUtil.write(getResponse(), file); } }
Example #28
Source File: MybatisUtil.java From MooTool with MIT License | 5 votes |
/** * 初始化数据库文件 */ 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 #29
Source File: TomcatManageController.java From Jpom with MIT License | 5 votes |
/** * 删除文件 * * @param id tomcat id * @param filename 文件名 * @param path tomcat路径 * @return 操作结果 */ @RequestMapping(value = "deleteFile", method = RequestMethod.POST, produces = MediaType.APPLICATION_JSON_UTF8_VALUE) public String deleteFile(String id, String path, String filename) { TomcatInfoModel tomcatInfoModel = tomcatEditService.getItem(id); if (tomcatInfoModel == null) { return JsonMessage.getString(500, "tomcat不存在"); } File file; if ("_tomcat_log".equals(path)) { //删除日志文件 file = FileUtil.file(tomcatInfoModel.getPath(), "logs", filename); // 判断修改时间 long modified = file.lastModified(); if (System.currentTimeMillis() - modified < TimeUnit.DAYS.toMillis(1)) { return JsonMessage.getString(405, "不能删除当天的日志"); } // 判断最后修改日期 AgentFileTailWatcher.offlineFile(file); } else { file = FileUtil.file(tomcatInfoModel.getAppBase(), path, filename); } if (file.exists()) { if (file.delete()) { return JsonMessage.getString(200, "删除成功"); } else { return JsonMessage.getString(500, "删除失败"); } } else { return JsonMessage.getString(404, "文件不存在"); } }
Example #30
Source File: ThymeleafUtil.java From Jpom with MIT License | 5 votes |
/** * 模板名称需要在 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); }