Java Code Examples for cn.hutool.core.io.FileUtil#file()

The following examples show how to use cn.hutool.core.io.FileUtil#file() . 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: JpomApplicationEvent.java    From Jpom with MIT License 8 votes vote down vote up
private static void checkPath() {
    String path = ExtConfigBean.getInstance().getPath();
    String extConfigPath = null;
    try {
        extConfigPath = ExtConfigBean.getResource().getURL().toString();
    } catch (IOException ignored) {
    }
    File file = FileUtil.file(path);
    try {
        FileUtil.mkdir(file);
        file = FileUtil.createTempFile("jpom", ".temp", file, true);
    } catch (Exception e) {
        DefaultSystemLog.getLog().error(StrUtil.format("Jpom创建数据目录失败,目录位置:{},请检查当前用户是否有此目录权限或修改配置文件:{}中的jpom.path为可创建目录的路径", path, extConfigPath), e);
        System.exit(-1);
    }
    FileUtil.del(file);
    DefaultSystemLog.getLog().info("Jpom[{}]外部配置文件路径:{}", JpomManifest.getInstance().getVersion(), extConfigPath);
}
 
Example 2
Source File: BuildUtil.java    From Jpom with 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 3
Source File: SshFileController.java    From Jpom with 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 4
Source File: LogBackController.java    From Jpom with MIT License 6 votes vote down vote up
@RequestMapping(value = "logBack_download", method = RequestMethod.GET)
public String download(String key, String copyId) {
    key = pathSafe(key);
    if (StrUtil.isEmpty(key)) {
        return JsonMessage.getString(405, "非法操作");
    }
    try {
        ProjectInfoModel pim = getProjectInfoModel();
        ProjectInfoModel.JavaCopyItem copyItem = pim.findCopyItem(copyId);
        File logBack = copyItem == null ? pim.getLogBack() : pim.getLogBack(copyItem);
        if (logBack.exists() && logBack.isDirectory()) {
            logBack = FileUtil.file(logBack, key);
            ServletUtil.write(getResponse(), logBack);
        } else {
            return "没有对应文件";
        }
    } catch (Exception e) {
        DefaultSystemLog.getLog().error("下载文件异常", e);
    }
    return "下载失败。请刷新页面后重试";
}
 
Example 5
Source File: LogManageController.java    From Jpom with MIT License 6 votes vote down vote up
/**
 * 删除 需要验证是否最后修改时间
 *
 * @param nodeId 节点
 * @param path   路径
 * @return json
 */
@RequestMapping(value = "log_del.json", method = RequestMethod.POST, produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
@ResponseBody
@OptLog(UserOperateLogV1.OptType.DelSysLog)
@Feature(method = MethodFeature.DEL_LOG)
public String logData(String nodeId,
                      @ValidatorItem(value = ValidatorRule.NOT_BLANK, msg = "path错误") String path) {
    if (StrUtil.isNotEmpty(nodeId)) {
        return NodeForward.request(getNode(), getRequest(), NodeUrl.DelSystemLog).toString();
    }
    WebAopLog webAopLog = SpringUtil.getBean(WebAopLog.class);
    File file = FileUtil.file(webAopLog.getPropertyValue(), path);
    // 判断修改时间
    long modified = file.lastModified();
    if (System.currentTimeMillis() - modified < TimeUnit.DAYS.toMillis(1)) {
        return JsonMessage.getString(405, "不能删除当天的日志");
    }
    if (FileUtil.del(file)) {
        // 离线上一个日志
        ServiceFileTailWatcher.offlineFile(file);
        return JsonMessage.getString(200, "删除成功");
    }
    return JsonMessage.getString(500, "删除失败");
}
 
Example 6
Source File: JvmUtil.java    From Jpom with 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 7
Source File: TomcatManageController.java    From Jpom with 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 8
Source File: JpomManifest.java    From Jpom with MIT License 5 votes vote down vote up
/**
 * 获取当前的管理名文件
 *
 * @return file
 */
public static File getScriptFile() {
    File runPath = getRunPath().getParentFile().getParentFile();
    String type = JpomApplication.getAppType().name();
    File scriptFile = FileUtil.file(runPath, StrUtil.format("{}.{}", type, CommandUtil.SUFFIX));
    if (!scriptFile.exists() || scriptFile.isDirectory()) {
        throw new JpomRuntimeException("当前服务中没有命令脚本:" + StrUtil.format("{}.{}", type, CommandUtil.SUFFIX));
    }
    return scriptFile;
}
 
Example 9
Source File: CheckAuthorize.java    From Jpom with MIT License 5 votes vote down vote up
/**
 * 修护脚本模板路径
 */
@PreLoadMethod
private static void repairScriptPath() {
    if (!JpomManifest.getInstance().isDebug()) {
        if (StrUtil.compareVersion(JpomManifest.getInstance().getVersion(), "2.4.2") < 0) {
            return;
        }
    }
    File oldDir = FileUtil.file(ExtConfigBean.getInstance().getPath(), AgentConfigBean.SCRIPT_DIRECTORY);
    if (!oldDir.exists()) {
        return;
    }
    File newDir = FileUtil.file(ConfigBean.getInstance().getDataPath(), AgentConfigBean.SCRIPT_DIRECTORY);
    FileUtil.move(oldDir, newDir, true);
}
 
Example 10
Source File: LogManageController.java    From Jpom with MIT License 5 votes vote down vote up
@RequestMapping(value = "log_del.json", method = RequestMethod.POST, produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
@ResponseBody
public String logData(@ValidatorItem(value = ValidatorRule.NOT_BLANK, msg = "path错误") String path) {
    WebAopLog webAopLog = SpringUtil.getBean(WebAopLog.class);
    File file = FileUtil.file(webAopLog.getPropertyValue(), path);
    // 判断修改时间
    long modified = file.lastModified();
    if (System.currentTimeMillis() - modified < TimeUnit.DAYS.toMillis(1)) {
        return JsonMessage.getString(405, "不能删除当天的日志");
    }
    if (FileUtil.del(file)) {
        return JsonMessage.getString(200, "删除成功");
    }
    return JsonMessage.getString(500, "删除失败");
}
 
Example 11
Source File: InstallIdController.java    From Jpom with MIT License 5 votes vote down vote up
@RequestMapping(value = ServerOpenApi.INSTALL_ID, method = RequestMethod.POST, produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
public String install() throws FileNotFoundException {
    File file = FileUtil.file(ConfigBean.getInstance().getDataPath(), ServerConfigBean.INSTALL);
    if (!file.exists()) {
        return JsonMessage.getString(500, "服务端的安装信息文件不存在");
    }
    JSONObject json = (JSONObject) JsonFileUtil.readJson(file.getAbsolutePath());
    String installId = json.getString("installId");
    if (StrUtil.isEmpty(installId)) {
        return JsonMessage.getString(500, "服务端的安装Id为空");
    }
    return JsonMessage.getString(200, "ok", installId);
}
 
Example 12
Source File: TestFileModify.java    From Jpom with MIT License 5 votes vote down vote up
public static void main(String[] args) {
    File file = FileUtil.file("D:\\jpom\\server\\data\\mail_config.json");
    WatchMonitor monitor = WatchUtil.create(file, WatchMonitor.ENTRY_MODIFY);
    monitor.setWatcher(new SimpleWatcher() {
        @Override
        public void onModify(WatchEvent<?> event, Path currentPath) {
            System.out.println("刷新邮箱");
        }
    });
    monitor.start();
}
 
Example 13
Source File: QrCodeForm.java    From MooTool with MIT License 5 votes vote down vote up
public static void generate() {
    try {
        qrCodeForm = getInstance();
        String nowTime = DateUtil.now().replace(":", "-").replace(" ", "-");
        qrCodeImageTempFile = FileUtil.file(tempDir + File.separator + "qrCode-" + nowTime + ".jpg");

        int size = Integer.parseInt(qrCodeForm.getSizeTextField().getText());
        QrConfig config = new QrConfig(size, size);
        String logoPath = qrCodeForm.getLogoPathTextField().getText();
        if (StringUtils.isNotBlank(logoPath)) {
            config.setImg(logoPath);
        }
        String errorCorrectionLevel = (String) qrCodeForm.getErrorCorrectionLevelComboBox().getSelectedItem();
        if ("低".equals(errorCorrectionLevel)) {
            config.setErrorCorrection(ErrorCorrectionLevel.L);
        } else if ("中低".equals(errorCorrectionLevel)) {
            config.setErrorCorrection(ErrorCorrectionLevel.M);
        } else if ("中高".equals(errorCorrectionLevel)) {
            config.setErrorCorrection(ErrorCorrectionLevel.Q);
        } else if ("高".equals(errorCorrectionLevel)) {
            config.setErrorCorrection(ErrorCorrectionLevel.H);
        }
        QrCodeUtil.generate(qrCodeForm.getToGenerateContentTextArea().getText(), config, qrCodeImageTempFile);
        BufferedImage image = ImageIO.read(qrCodeImageTempFile);
        ImageIcon imageIcon = new ImageIcon(image);
        qrCodeForm.getQrCodeImageLabel().setIcon(imageIcon);
        qrCodeForm.getQrCodePanel().updateUI();

        saveConfig();
    } catch (Exception ex) {
        ex.printStackTrace();
        JOptionPane.showMessageDialog(App.mainFrame, "生成失败!\n\n" + ex.getMessage(), "失败",
                JOptionPane.ERROR_MESSAGE);
        logger.error(ExceptionUtils.getStackTrace(ex));
    }
}
 
Example 14
Source File: JvmUtil.java    From Jpom with MIT License 5 votes vote down vote up
/**
 * 获取jdk 中agent
 *
 * @return 路径
 */
private static String getManagementAgent() {
    File file = FileUtil.file(SystemUtil.getJavaRuntimeInfo().getHomeDir(), "lib", "management-agent.jar");
    if (file.exists() && file.isFile()) {
        return file.getAbsolutePath();
    }
    throw new JpomRuntimeException("JDK中" + file.getAbsolutePath() + " 文件不存在");
}
 
Example 15
Source File: ScriptController.java    From Jpom with MIT License 5 votes vote down vote up
@RequestMapping(value = "upload.json", method = RequestMethod.POST, produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
public String upload() throws IOException {
    MultipartFileBuilder multipartFileBuilder = createMultipart()
            .addFieldName("file").setFileExt("bat", "sh");
    multipartFileBuilder.setSavePath(AgentConfigBean.getInstance().getTempPathName());
    multipartFileBuilder.setUseOriginalFilename(true);
    String path = multipartFileBuilder.save();
    File file = FileUtil.file(path);
    String context = FileUtil.readString(path, JpomApplication.getCharset());
    if (StrUtil.isEmpty(context)) {
        return JsonMessage.getString(405, "脚本内容为空");
    }
    String id = file.getName();
    ScriptModel eModel = scriptServer.getItem(id);
    if (eModel != null) {
        return JsonMessage.getString(405, "对应脚本模板已经存在啦");
    }
    eModel = new ScriptModel();
    eModel.setId(id);
    eModel.setName(id);
    eModel.setContext(context);
    file = eModel.getFile(true);
    if (file.exists() || file.isDirectory()) {
        return JsonMessage.getString(405, "当地id路径文件已经存在来,请修改");
    }
    scriptServer.addItem(eModel);
    return JsonMessage.getString(200, "导入成功");
}
 
Example 16
Source File: OutGivingProjectController.java    From Jpom with MIT License 4 votes vote down vote up
/**
 * 节点分发文件
 *
 * @param id       分发id
 * @param afterOpt 之后的操作
 * @return json
 * @throws IOException IO
 */
@RequestMapping(value = "upload", method = RequestMethod.POST, produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
@ResponseBody
@OptLog(UserOperateLogV1.OptType.UploadOutGiving)
@Feature(method = MethodFeature.UPLOAD)
public String upload(String id, String afterOpt, String clearOld) throws IOException {
    OutGivingModel outGivingModel = outGivingServer.getItem(id);
    if (outGivingModel == null) {
        return JsonMessage.getString(400, "上传失败,没有找到对应的分发项目");
    }
    // 检查状态
    List<OutGivingNodeProject> outGivingNodeProjectList = outGivingModel.getOutGivingNodeProjectList();
    Objects.requireNonNull(outGivingNodeProjectList);
    for (OutGivingNodeProject outGivingNodeProject : outGivingNodeProjectList) {
        if (outGivingNodeProject.getStatus() == OutGivingNodeProject.Status.Ing.getCode()) {
            return JsonMessage.getString(400, "当前还在分发中,请等待分发结束");
        }
    }
    AfterOpt afterOpt1 = BaseEnum.getEnum(AfterOpt.class, Convert.toInt(afterOpt, 0));
    if (afterOpt1 == null) {
        return JsonMessage.getString(400, "请选择分发后的操作");
    }
    MultipartFileBuilder multipartFileBuilder = createMultipart();
    multipartFileBuilder
            .setFileExt(StringUtil.PACKAGE_EXT)
            .addFieldName("file")
            .setSavePath(ServerConfigBean.getInstance().getUserTempPath().getAbsolutePath());
    String path = multipartFileBuilder.save();
    //
    File src = FileUtil.file(path);
    File dest = null;
    for (String i : StringUtil.PACKAGE_EXT) {
        if (FileUtil.pathEndsWith(src, i)) {
            dest = FileUtil.file(ConfigBean.getInstance().getDataPath(), ServerConfigBean.OUTGIVING_FILE, id + "." + i);
            break;
        }
    }
    FileUtil.move(src, dest, true);
    //
    outGivingModel = outGivingServer.getItem(id);
    outGivingModel.setClearOld(Convert.toBool(clearOld, false));
    outGivingModel.setAfterOpt(afterOpt1.getCode());

    outGivingServer.updateItem(outGivingModel);
    // 开启
    OutGivingRun.startRun(outGivingModel.getId(), dest, getUser(), true);
    return JsonMessage.getString(200, "分发成功");
}
 
Example 17
Source File: BuildUtil.java    From Jpom with MIT License 4 votes vote down vote up
public static File getBuildDataDir() {
    return FileUtil.file(ConfigBean.getInstance().getDataPath(), "build");
}
 
Example 18
Source File: BuildUtil.java    From Jpom with MIT License 4 votes vote down vote up
public static File getBuildDataFile(String id) {
    return FileUtil.file(ConfigBean.getInstance().getDataPath(), "build", id);
}
 
Example 19
Source File: ProjectInfoModel.java    From Jpom with MIT License 2 votes vote down vote up
/**
 * 副本的控制台日志文件
 *
 * @param javaCopyItem 副本信息
 * @return file
 */
public File getLog(JavaCopyItem javaCopyItem) {
    File file = FileUtil.file(getLog());
    return FileUtil.file(file.getParentFile(), getId() + "_" + javaCopyItem.getId() + ".log");
}
 
Example 20
Source File: AgentConfigBean.java    From Jpom with MIT License 2 votes vote down vote up
/**
 * 获取脚本模板路径
 *
 * @return file
 */
public File getScriptPath() {
    return FileUtil.file(ConfigBean.getInstance().getDataPath(), SCRIPT_DIRECTORY);
}