cn.hutool.core.util.ZipUtil Java Examples

The following examples show how to use cn.hutool.core.util.ZipUtil. 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: BackupController.java    From blog-sharon with Apache License 2.0 6 votes vote down vote up
/**
 * 备份文章,导出markdown文件
 *
 * @return JsonResult
 */
public JsonResult backupPosts() {
    List<Post> posts = postService.findAll(PostTypeEnum.POST_TYPE_POST.getDesc());
    posts.addAll(postService.findAll(PostTypeEnum.POST_TYPE_PAGE.getDesc()));
    try {
        if (HaloUtils.getBackUps(BackupTypeEnum.POSTS.getDesc()).size() > CommonParamsEnum.TEN.getValue()) {
            FileUtil.del(System.getProperties().getProperty("user.home") + "/halo/backup/posts/");
        }
        //打包好的文件名
        String distName = "posts_backup_" + DateUtil.format(DateUtil.date(), "yyyyMMddHHmmss");
        String srcPath = System.getProperties().getProperty("user.home") + "/halo/backup/posts/" + distName;
        for (Post post : posts) {
            HaloUtils.postToFile(post.getPostContentMd(), srcPath, post.getPostTitle() + ".md");
        }
        //打包导出好的文章
        ZipUtil.zip(srcPath, srcPath + ".zip");
        FileUtil.del(srcPath);
        log.info("Current time: {}, performed an article backup.", DateUtil.now());
        return new JsonResult(ResultCodeEnum.SUCCESS.getCode(), localeMessageUtil.getMessage("code.admin.backup.backup-success"));
    } catch (Exception e) {
        log.error("Backup article failed: {}", e.getMessage());
        return new JsonResult(ResultCodeEnum.FAIL.getCode(), localeMessageUtil.getMessage("code.admin.backup.backup-failed"));
    }
}
 
Example #2
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 #3
Source File: BackupController.java    From stone with 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 #4
Source File: BackupController.java    From stone with GNU General Public License v3.0 6 votes vote down vote up
/**
 * 备份文章,导出markdown文件
 *
 * @return JsonResult
 */
public JsonResult backupPosts() {
    final List<Post> posts = postService.findAll(PostTypeEnum.POST_TYPE_POST.getDesc());
    posts.addAll(postService.findAll(PostTypeEnum.POST_TYPE_PAGE.getDesc()));
    try {
        if (HaloUtils.getBackUps(BackupTypeEnum.POSTS.getDesc()).size() > CommonParamsEnum.TEN.getValue()) {
            FileUtil.del(System.getProperties().getProperty("user.home") + "/halo/backup/posts/");
        }
        //打包好的文件名
        final String distName = "posts_backup_" + DateUtil.format(DateUtil.date(), "yyyyMMddHHmmss");
        final String srcPath = System.getProperties().getProperty("user.home") + "/halo/backup/posts/" + distName;
        for (Post post : posts) {
            HaloUtils.postToFile(post.getPostContentMd(), srcPath, post.getPostTitle() + ".md");
        }
        //打包导出好的文章
        ZipUtil.zip(srcPath, srcPath + ".zip");
        FileUtil.del(srcPath);
        log.info("Current time: {}, performed an article backup.", DateUtil.now());
        return new JsonResult(ResultCodeEnum.SUCCESS.getCode(), localeMessageUtil.getMessage("code.admin.backup.backup-success"));
    } catch (Exception e) {
        log.error("Backup article failed: {}", e.getMessage());
        return new JsonResult(ResultCodeEnum.FAIL.getCode(), localeMessageUtil.getMessage("code.admin.backup.backup-failed"));
    }
}
 
Example #5
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 #6
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 #7
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 #8
Source File: VelocityKit.java    From kvf-admin with MIT License 6 votes vote down vote up
/**
 * 所有模板统一生成
 * @param config 代码生成配置数据
 */
public static void allToFile(GenConfigVO config) {
    VelocityContext ctx = VelocityKit.getContext();
    ctx.put("config", config);
    ctx.put("pack", new ConfigConstant.PackageConfig());
    ctx.put("createTime", DateUtil.now());
    ctx.put("author", ConfigConstant.AUTHOR);
    for (TemplateTypeEnum typeEnum : TemplateTypeEnum.values()) {
        if ("TABLE".equals(typeEnum.getType()) || "TREE_GRID".equals(typeEnum.getType())) {
            if (config.getTableType().equalsIgnoreCase(typeEnum.getType())) {
                VelocityKit.toFile(typeEnum.getName(), ctx,
                        AuxiliaryKit.getGenerateCodePath(typeEnum, config.getModuleName(), config.getFunName()));
            }
        } else {
            VelocityKit.toFile(typeEnum.getName(), ctx,
                    AuxiliaryKit.getGenerateCodePath(typeEnum, config.getModuleName(), config.getFunName()));
        }
    }

    // 所有代码文件打包zip压缩包
    final String srcPath = ConfigConstant.CODE_GEN_PATH + "/" + ConfigConstant.CODE_FOLDER_NAME;
    ZipUtil.zip(srcPath, ConfigConstant.CODE_GEN_PATH + "/" + ConfigConstant.CODE_ZIP_FILENAME);
}
 
Example #9
Source File: ApiController.java    From littleca with Apache License 2.0 6 votes vote down vote up
@RequestMapping(value = "downCertZip", method = RequestMethod.GET)
public void downCertZip(String serialNumber, Integer catype, HttpServletResponse resp, HttpServletRequest req) throws SerialException {
    try {
        CAConstant.KeyType keyType = CAConstant.KeyType.forValue(catype);
        CaConfig caConfig = appConfig.getByKeyType(catype);
        String certDir = caConfig.getClientCertBasePath() + "/" + serialNumber;
        String destPath = caConfig.getClientCertBasePath() + "/" + UUID.randomUUID().toString() + ".zip";
        String readmeDoc = certDir + "/readme.txt";
        String readmeTxt = "证书类型为["+keyType.name+"]p12 alias:taoyuanx-client\r\n p12 密码:123456";
        FileUtils.writeStringToFile(new File(readmeDoc), readmeTxt, "UTF-8");
        ZipUtil.zip(certDir, destPath);
        // 下载
        File destZipFile = new File(destPath);
        resp.setContentType(req.getServletContext().getMimeType(destZipFile.getName()));
        resp.setHeader("Content-type", "application/octet-stream");
        resp.setHeader("Content-Disposition",
                "attachment;fileName=" + URLEncoder.encode(keyType.name+"_cert.zip","UTF-8"));
        resp.getOutputStream().write(FileUtils.readFileToByteArray(destZipFile));

    } catch (Exception e) {
        throw new SerialException("下载失败");
    }
}
 
Example #10
Source File: ApiController.java    From littleca with Apache License 2.0 6 votes vote down vote up
@RequestMapping(value = "downCertZip", method = RequestMethod.GET)
public void downCertZip(String serialNumber, String password, HttpServletResponse resp, HttpServletRequest req) throws SerialException {
    try {
        File zipFile = new File(appConfig.getCertBaseDir(), Math.abs(HashUtil.bkdrHash(serialNumber)) + "_cert.zip");
        String destPath = zipFile.getAbsolutePath();
        if (!zipFile.exists()) {
            String certDir = appConfig.getCertBaseDir() + File.separator + serialNumber;
            String readmeDoc = certDir + File.separator + "readme.txt";
            String readmeTxt = "p12 alias:lient\r\n p12 密码:" + password;
            FileUtils.writeStringToFile(new File(readmeDoc), readmeTxt, "UTF-8");
            ZipUtil.zip(certDir, destPath);
        }
        // 下载
        resp.setContentType(req.getServletContext().getMimeType(zipFile.getName()));
        resp.setHeader("Content-type", "application/octet-stream");
        resp.setHeader("Content-Disposition",
                "attachment;fileName=" + URLEncoder.encode(serialNumber + "_cert.zip", "UTF-8"));
        resp.getOutputStream().write(FileUtils.readFileToByteArray(zipFile));
    } catch (Exception e) {
        LOG.error("下载异常", e);
        throw new SerialException("下载失败");
    }
}
 
Example #11
Source File: GeneratorServiceImpl.java    From yshopmall with Apache License 2.0 5 votes vote down vote up
@Override
public void download(GenConfig genConfig, List<ColumnConfig> columns, HttpServletRequest request, HttpServletResponse response) {
    if(genConfig.getId() == null){
        throw new BadRequestException("请先配置生成器");
    }
    try {
        File file = new File(GenUtil.download(columns, genConfig));
        String zipPath = file.getPath()  + ".zip";
        ZipUtil.zip(file.getPath(), zipPath);
        FileUtil.downloadFile(request, response, new File(zipPath), true);
    } catch (IOException e) {
        throw new BadRequestException("打包失败");
    }
}
 
Example #12
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 #13
Source File: GeneratorServiceImpl.java    From eladmin with Apache License 2.0 5 votes vote down vote up
@Override
public void download(GenConfig genConfig, List<ColumnInfo> columns, HttpServletRequest request, HttpServletResponse response) {
    if (genConfig.getId() == null) {
        throw new BadRequestException("请先配置生成器");
    }
    try {
        File file = new File(GenUtil.download(columns, genConfig));
        String zipPath = file.getPath() + ".zip";
        ZipUtil.zip(file.getPath(), zipPath);
        FileUtil.downloadFile(request, response, new File(zipPath), true);
    } catch (IOException e) {
        throw new BadRequestException("打包失败");
    }
}
 
Example #14
Source File: FileManagerServiceImpl.java    From efo with MIT License 5 votes vote down vote up
@Override
public JSONObject compress(JSONObject object) {
    JSONArray array = object.getJSONArray("items");
    File[] files = new File[array.size()];
    int i = 0;
    for (Object file : array) {
        files[i++] = new File(file.toString());
    }
    String dest = object.getString("destination");
    String name = object.getString("compressedFilename");
    File zip = ZipUtil.zip(new File(dest + File.separator + name), ValueConsts.FALSE, files);
    return getBasicResponse(zip.exists());
}
 
Example #15
Source File: FileManagerServiceImpl.java    From efo with MIT License 5 votes vote down vote up
@Override
public void multiDownload(HttpServletResponse response, String[] items, String destFile) throws IOException {
    File zip = ZipUtil.zip(new File(ValueConsts.USER_DESKTOP + File.separator + destFile), ValueConsts.FALSE,
            FileExecutor.getFiles(items));
    if (zip.exists()) {
        response.getOutputStream().write(FileExecutor.readFileToByteArray(zip));
        FileExecutor.deleteFile(zip);
    }
}
 
Example #16
Source File: GeneratorServiceImpl.java    From sk-admin with Apache License 2.0 5 votes vote down vote up
@Override
public void download(GenConfig genConfig, List<ColumnInfo> columns, HttpServletRequest request, HttpServletResponse response) {
    if (genConfig.getId() == null) {
        throw new SkException("请先配置生成器");
    }
    try {
        File file = new File(GenUtil.download(columns, genConfig));
        String zipPath = file.getPath() + ".zip";
        ZipUtil.zip(file.getPath(), zipPath);
        FileUtils.downloadFile(request, response, new File(zipPath), true);
    } catch (IOException e) {
        throw new SkException("打包失败");
    }
}
 
Example #17
Source File: LogController.java    From zfile with MIT License 5 votes vote down vote up
/**
 * 系统日志下载
 */
@GetMapping("/log")
public ResponseEntity<Object> downloadLog(HttpServletResponse response) {
    if (log.isDebugEnabled()) {
        log.debug("下载诊断日志");
    }
    String userHome = System.getProperty("user.home");
    File fileZip = ZipUtil.zip(userHome + "/.zfile/logs");
    String currentDate = DateUtil.format(new Date(), "yyyy-MM-dd HH:mm:ss");
    return FileUtil.export(fileZip, "ZFile 诊断日志 - " + currentDate + ".zip");
}
 
Example #18
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 #19
Source File: ThemeController.java    From stone with 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"));
}
 
Example #20
Source File: FileManagerServiceImpl.java    From efo with MIT License 4 votes vote down vote up
@Override
public JSONObject extract(JSONObject object) {
    String destination = object.getString("destination") + File.separator + object.getString("folderName");
    String zipFile = object.getString("item");
    return getBasicResponse(ZipUtil.unzip(zipFile, destination).exists());
}
 
Example #21
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 #22
Source File: TestFile.java    From Jpom with MIT License 4 votes vote down vote up
public static void main(String[] args) throws IOException {
    InputStream inputStream = new FileInputStream("D:\\SystemDocument\\Desktop\\Desktop.zip");

    String code = IoUtil.readHex28Upper(inputStream);
    System.out.println(code);

    System.out.println(FileUtil.getMimeType("D:\\SystemDocument\\Desktop\\Desktop.zip"));


    System.out.println(FileUtil.getMimeType("D:\\SystemDocument\\Desktop\\Desktop.tar.gz"));

    System.out.println(FileUtil.getMimeType("D:\\SystemDocument\\Desktop\\Desktop.7z"));

    ZipUtil.unzip(new File("D:\\SystemDocument\\Desktop\\Desktop.tar.gz"), new File("D:\\SystemDocument\\Desktop\\Desktop.7z\""));

    ZipUtil.unzip(new File("D:\\SystemDocument\\Desktop\\Desktop.7z"), new File("D:\\SystemDocument\\Desktop\\Desktop.7z\""));

    System.out.println(FileUtil.extName("test.zip"));
}