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

The following examples show how to use cn.hutool.core.io.FileUtil#del() . 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: 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 3
Source File: SshInstallAgentController.java    From Jpom with 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 4
Source File: BackupController.java    From blog-sharon with Apache License 2.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/");
        }
        File path = new File(ResourceUtils.getURL("classpath:").getPath());
        String srcPath = path.getAbsolutePath();
        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 5
Source File: BackupController.java    From stone with 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 6
Source File: BuildListController.java    From Jpom with MIT License 6 votes vote down vote up
@RequestMapping(value = "delete.json", method = RequestMethod.POST, produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
@ResponseBody
@OptLog(UserOperateLogV1.OptType.DelBuild)
@Feature(method = MethodFeature.DEL)
public String delete(@ValidatorItem(value = ValidatorRule.NOT_BLANK, msg = "没有数据id") String id) throws SQLException {
    BuildModel buildModel = buildService.getItem(id);
    Objects.requireNonNull(buildModel, "没有对应数据");
    dbBuildHistoryLogService.delByBuildId(buildModel.getId());
    //
    File file = BuildUtil.getBuildDataFile(buildModel.getId());
    if (!FileUtil.del(file)) {
        return JsonMessage.getString(500, "清理历史构建产物失败");
    }
    buildService.deleteItem(buildModel.getId());
    return JsonMessage.getString(200, "清理成功");
}
 
Example 7
Source File: BackupController.java    From blog-sharon with Apache License 2.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/");
        }
        String srcPath = System.getProperties().getProperty("user.home") + "/halo/";
        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 8
Source File: KillJobHandler.java    From datax-web with MIT License 5 votes vote down vote up
@Override
public ReturnT<String> execute(TriggerParam tgParam) {
    String processId = tgParam.getProcessId();
    boolean result = ProcessUtil.killProcessByPid(processId);
    //  删除临时文件
    if (!CollectionUtils.isEmpty(jobTmpFiles)) {
        String pathname = jobTmpFiles.get(processId);
        if (pathname != null) {
            FileUtil.del(new File(pathname));
            jobTmpFiles.remove(processId);
        }
    }
    return result ? IJobHandler.SUCCESS : IJobHandler.FAIL;
}
 
Example 9
Source File: CertService.java    From Jpom with MIT License 5 votes vote down vote up
/**
 * 删除证书
 *
 * @param id id
 */
@Override
public void deleteItem(String id) {
    CertModel certModel = getItem(id);
    if (certModel == null) {
        return;
    }
    String keyPath = certModel.getCert();
    super.deleteItem(id);
    if (StrUtil.isNotEmpty(keyPath)) {
        // 删除证书文件
        File parentFile = FileUtil.file(keyPath).getParentFile();
        FileUtil.del(parentFile);
    }
}
 
Example 10
Source File: ScriptServer.java    From Jpom with MIT License 5 votes vote down vote up
@Override
public void deleteItem(String id) {
    ScriptModel scriptModel = getItem(id);
    if (scriptModel != null) {
        FileUtil.del(scriptModel.getFile(true).getParentFile());
    }
    super.deleteItem(id);
}
 
Example 11
Source File: UploadController.java    From spring-boot-demo with 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 12
Source File: CertificateController.java    From Jpom with MIT License 5 votes vote down vote up
/**
 * 导出证书
 *
 * @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 13
Source File: UploadController.java    From spring-boot-demo with 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 14
Source File: UploadController.java    From spring-boot-demo with 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 15
Source File: ThemeController.java    From blog-sharon with Apache License 2.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()) {
            //获取项目根路径
            File basePath = new File(ResourceUtils.getURL("classpath:").getPath());
            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"));
}
 
Example 16
Source File: ThemeController.java    From blog-sharon with Apache License 2.0 5 votes vote down vote up
/**
 * 删除主题
 *
 * @param themeName 主题文件夹名
 * @return string 重定向到/admin/themes
 */
@GetMapping(value = "/remove")
public String removeTheme(@RequestParam("themeName") String themeName) {
    try {
        File basePath = new File(ResourceUtils.getURL("classpath:").getPath());
        File themePath = new File(basePath.getAbsolutePath(), "templates/themes/" + themeName);
        FileUtil.del(themePath);
        HaloConst.THEMES.clear();
        HaloConst.THEMES = HaloUtils.getThemes();
    } catch (Exception e) {
        log.error("Delete theme failed: {}", e.getMessage());
    }
    return "redirect:/admin/themes";
}
 
Example 17
Source File: BackupController.java    From blog-sharon with 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 18
Source File: CertificateController.java    From Jpom with MIT License 4 votes vote down vote up
private String getCertFile(CertModel certModel, boolean add) throws IOException {
    String certPath = null;
    try {
        String path = AgentConfigBean.getInstance().getTempPathName();
        MultipartFileBuilder cert = createMultipart().addFieldName("file").setSavePath(path);
        certPath = cert.save();
        Object val = getUpdateFileInfo(certModel, certPath);
        if (val instanceof String) {
            return val.toString();
        }
        JSONObject jsonObject = (JSONObject) val;
        String domain = jsonObject.getString("domain");
        if (add) {
            List<CertModel> array = certService.list();
            if (array != null) {
                for (CertModel certModel1 : array) {
                    if (StrUtil.emptyToDefault(domain, "").equals(certModel1.getDomain())) {
                        return JsonMessage.getString(405, "证书的域名已经存在啦");
                    }
                }
            }
        } else {
            if (!StrUtil.emptyToDefault(domain, "").equals(certModel.getDomain())) {
                return JsonMessage.getString(405, "新证书的域名不一致");
            }
        }
        // 移动位置
        String temporary = certModel.getWhitePath() + "/" + certModel.getId() + "/";
        File pemFile = FileUtil.file(temporary + certModel.getId() + "." + certModel.getType().name());
        File keyFile = FileUtil.file(temporary + certModel.getId() + ".key");
        if (add) {
            if (pemFile.exists()) {
                return JsonMessage.getString(405, pemFile.getAbsolutePath() + " 已经被占用啦");
            }
            if (keyFile.exists()) {
                return JsonMessage.getString(405, keyFile.getAbsolutePath() + " 已经被占用啦");
            }
        }
        String pemPath = jsonObject.getString("pemPath");
        String keyPath = jsonObject.getString("keyPath");
        FileUtil.move(FileUtil.file(pemPath), pemFile, true);
        FileUtil.move(FileUtil.file(keyPath), keyFile, true);
        certModel.setCert(pemFile.getAbsolutePath());
        certModel.setKey(keyFile.getAbsolutePath());
        //
        certModel.setDomain(domain);
        certModel.setExpirationTime(jsonObject.getLongValue("expirationTime"));
        certModel.setEffectiveTime(jsonObject.getLongValue("effectiveTime"));
    } finally {
        if (certPath != null) {
            FileUtil.del(certPath);
        }
    }
    return null;
}
 
Example 19
Source File: SshInstallAgentController.java    From Jpom with MIT License 4 votes vote down vote up
@RequestMapping(value = "installAgentSubmit.json", method = RequestMethod.POST, produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
@ResponseBody
@Feature(method = MethodFeature.INSTALL)
@OptLog(UserOperateLogV1.OptType.SshInstallAgent)
public String installAgentSubmit(@ValidatorItem(value = ValidatorRule.NOT_BLANK) String id,
                                 @ValidatorItem(value = ValidatorRule.NOT_BLANK, msg = "节点数据") String nodeData,
                                 @ValidatorItem(value = ValidatorRule.NOT_BLANK, msg = "安装路径") String path) throws Exception {
    // 判断输入的节点信息
    Object object = getNodeModel(nodeData);
    if (object instanceof JsonMessage) {
        return object.toString();
    }
    NodeModel nodeModel = (NodeModel) object;
    //
    SshModel sshModel = sshService.getItem(id);
    Objects.requireNonNull(sshModel, "没有找到对应ssh");
    //
    String tempFilePath = ServerConfigBean.getInstance().getUserTempPath().getAbsolutePath();
    MultipartFileBuilder cert = createMultipart().addFieldName("file").setSavePath(tempFilePath);
    String filePath = cert.save();
    //
    File outFle = FileUtil.file(tempFilePath, Type.Agent.name() + "_" + IdUtil.fastSimpleUUID());
    try {
        try (ZipFile zipFile = new ZipFile(filePath)) {
            // 判断文件是否正确
            ZipEntry sh = zipFile.getEntry(Type.Agent.name() + ".sh");
            ZipEntry lib = zipFile.getEntry("lib" + StrUtil.SLASH);
            if (sh == null || null == lib || !lib.isDirectory()) {
                return JsonMessage.getString(405, "不能jpom 插件包");
            }
            ZipUtil.unzip(zipFile, outFle);
        }
        // 获取上传的tag
        File shFile = FileUtil.file(outFle, Type.Agent.name() + ".sh");
        List<String> lines = FileUtil.readLines(shFile, CharsetUtil.CHARSET_UTF_8);
        String tag = null;
        for (String line : lines) {
            line = line.trim();
            if (StrUtil.startWith(line, "Tag=\"") && StrUtil.endWith(line, "\"")) {
                tag = line.substring(5, line.length() - 1);
                break;
            }
        }
        if (StrUtil.isEmpty(tag)) {
            return JsonMessage.getString(405, "管理命令中不存在tag");
        }
        //  读取授权信息
        File configFile = FileUtil.file(outFle, "extConfig.yml");
        if (configFile.exists()) {
            List<Map<String, Object>> load = YmlUtil.load(configFile);
            Map<String, Object> map = load.get(0);
            Object user = map.get(ConfigBean.AUTHORIZE_USER_KEY);
            nodeModel.setLoginName(Convert.toStr(user, ""));
            //
            Object pwd = map.get(ConfigBean.AUTHORIZE_PWD_KEY);
            nodeModel.setLoginPwd(Convert.toStr(pwd, ""));
        }
        // 查询远程是否运行
        if (sshService.checkSshRun(sshModel, tag)) {
            return JsonMessage.getString(300, "对应服务器中已经存在Jpom 插件端,不需要再次安装啦");
        }
        // 上传文件到服务器
        sshService.uploadDir(sshModel, path, outFle);
        //
        String shPtah = FileUtil.normalize(path + "/" + Type.Agent.name() + ".sh");
        String command = StrUtil.format("sh {} start upgrade", shPtah);
        String result = sshService.exec(sshModel, command);
        // 休眠10秒
        Thread.sleep(10 * 1000);
        if (StrUtil.isEmpty(nodeModel.getLoginName()) || StrUtil.isEmpty(nodeModel.getLoginPwd())) {
            String error = this.getAuthorize(sshModel, nodeModel, path);
            if (error != null) {
                return error;
            }
        }
        nodeModel.setOpenStatus(true);
        // 绑定关系
        nodeModel.setSshId(sshModel.getId());
        nodeService.addItem(nodeModel);
        //
        return JsonMessage.getString(200, "操作成功:" + result);
    } finally {
        // 清理资源
        FileUtil.del(filePath);
        FileUtil.del(outFle);
    }
}
 
Example 20
Source File: ExecutorJobHandler.java    From datax-web with MIT License 4 votes vote down vote up
@Override
public ReturnT<String> execute(TriggerParam trigger) {

    int exitValue = -1;
    Thread errThread = null;
    String tmpFilePath;
    LogStatistics logStatistics = null;
    //Generate JSON temporary file
    tmpFilePath = generateTemJsonFile(trigger.getJobJson());

    try {
        String[] cmdarrayFinal = buildDataXExecutorCmd(trigger, tmpFilePath,dataXPyPath);
        final Process process = Runtime.getRuntime().exec(cmdarrayFinal);
        String prcsId = ProcessUtil.getProcessId(process);
        JobLogger.log("------------------DataX process id: " + prcsId);
        jobTmpFiles.put(prcsId, tmpFilePath);
        //update datax process id
        HandleProcessCallbackParam prcs = new HandleProcessCallbackParam(trigger.getLogId(), trigger.getLogDateTime(), prcsId);
        ProcessCallbackThread.pushCallBack(prcs);
        // log-thread
        Thread futureThread = null;
        FutureTask<LogStatistics> futureTask = new FutureTask<>(() -> analysisStatisticsLog(new BufferedInputStream(process.getInputStream())));
        futureThread = new Thread(futureTask);
        futureThread.start();

        errThread = new Thread(() -> {
            try {
                analysisStatisticsLog(new BufferedInputStream(process.getErrorStream()));
            } catch (IOException e) {
                JobLogger.log(e);
            }
        });

        logStatistics = futureTask.get();
        errThread.start();
        // process-wait
        exitValue = process.waitFor();      // exit code: 0=success, 1=error
        // log-thread join
        errThread.join();
    } catch (Exception e) {
        JobLogger.log(e);
    } finally {
        if (errThread != null && errThread.isAlive()) {
            errThread.interrupt();
        }
        //  删除临时文件
        if (FileUtil.exist(tmpFilePath)) {
            FileUtil.del(new File(tmpFilePath));
        }
    }
    if (exitValue == 0) {
        return new ReturnT<>(200, logStatistics.toString());
    } else {
        return new ReturnT<>(IJobHandler.FAIL.getCode(), "command exit value(" + exitValue + ") is failed");
    }
}