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

The following examples show how to use cn.hutool.core.io.FileUtil#normalize() . 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: 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 2
Source File: InternalController.java    From Jpom with MIT License 6 votes vote down vote up
/**
     * 导出堆栈信息
     *
     * @param tag 程序运行标识
     * @return json
     */
    @RequestMapping(value = "internal_stack", method = RequestMethod.GET)
    @ResponseBody
    public String stack(String tag, String copyId) {
        tag = ProjectInfoModel.JavaCopyItem.getTagId(tag, copyId);
        //
        String fileName = AgentConfigBean.getInstance().getTempPathName() + "/" + tag + "_java_cpu.txt";
        fileName = FileUtil.normalize(fileName);
        try {
            int pid = AbstractProjectCommander.getInstance().getPid(tag);
            if (pid <= 0) {
                return JsonMessage.getString(400, "未运行");
            }
            String command = String.format("jstack -F %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 3
Source File: InternalController.java    From Jpom with MIT License 6 votes vote down vote up
/**
     * 导出内存信息
     *
     * @param tag 程序运行标识
     * @return json
     */
    @RequestMapping(value = "internal_ram", method = RequestMethod.GET)
    @ResponseBody
    public String ram(String tag, String copyId) {
        tag = ProjectInfoModel.JavaCopyItem.getTagId(tag, copyId);
        //
        String fileName = AgentConfigBean.getInstance().getTempPathName() + "/" + tag + "_java_ram.txt";
        fileName = FileUtil.normalize(fileName);
        try {
            int pid = AbstractProjectCommander.getInstance().getPid(tag);
            if (pid <= 0) {
                return JsonMessage.getString(400, "未运行");
            }
            String command = String.format("jmap -histo:live %s >> %s", pid, fileName);
            CommandUtil.execSystemCommand(command);
            downLoad(getResponse(), fileName);
        } catch (Exception e) {
            DefaultSystemLog.getLog().error(e.getMessage(), e);
//            getResponse().sendRedirect("internal?tag=" + tag);
        }
        return JsonMessage.getString(200, "");
    }
 
Example 4
Source File: StringUtil.java    From Jpom with MIT License 6 votes vote down vote up
/**
 * 删除文件开始的路径
 *
 * @param file      要删除的文件
 * @param startPath 开始的路径
 * @param inName    是否返回文件名
 * @return /test/a.txt /test/  a.txt
 */
public static String delStartPath(File file, String startPath, boolean inName) {
    String newWhitePath;
    if (inName) {
        newWhitePath = FileUtil.getAbsolutePath(file.getAbsolutePath());
    } else {
        newWhitePath = FileUtil.getAbsolutePath(file.getParentFile());
    }
    String itemAbsPath = FileUtil.getAbsolutePath(new File(startPath));
    itemAbsPath = FileUtil.normalize(itemAbsPath);
    newWhitePath = FileUtil.normalize(newWhitePath);
    String path = newWhitePath.substring(newWhitePath.indexOf(itemAbsPath) + itemAbsPath.length());
    path = FileUtil.normalize(path);
    if (path.startsWith(StrUtil.SLASH)) {
        path = path.substring(1);
    }
    return path;
}
 
Example 5
Source File: UrlRedirectUtil.java    From Jpom with MIT License 6 votes vote down vote up
/**
 * 二级代理路径
 *
 * @param request req
 * @return context-path+nginx配置
 */
public static String getHeaderProxyPath(HttpServletRequest request, String headName, Function<String, String> function) {
    String proxyPath = ServletUtil.getHeaderIgnoreCase(request, headName);
    //
    if (StrUtil.isEmpty(proxyPath)) {
        return request.getContextPath();
    }
    // 回调处理
    if (function != null) {
        proxyPath = function.apply(proxyPath);
    }
    //
    proxyPath = FileUtil.normalize(request.getContextPath() + StrUtil.SLASH + proxyPath);
    if (proxyPath.endsWith(StrUtil.SLASH)) {
        proxyPath = proxyPath.substring(0, proxyPath.length() - 1);
    }
    return proxyPath;
}
 
Example 6
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 7
Source File: BaseJpomController.java    From Jpom with MIT License 5 votes vote down vote up
/**
 * 路径安全格式化
 *
 * @param path 路径
 * @return 去掉 提权字符串
 */
public static String pathSafe(String path) {
    if (path == null) {
        return null;
    }
    String newPath = path.replace("../", StrUtil.EMPTY);
    newPath = newPath.replace("..\\", StrUtil.EMPTY);
    newPath = newPath.replace("+", StrUtil.EMPTY);
    return FileUtil.normalize(newPath);
}
 
Example 8
Source File: IndexControl.java    From Jpom with MIT License 5 votes vote down vote up
private boolean testMenus(JSONObject jsonObject, UserModel userModel, String secondary) {
    String url = jsonObject.getString("url");
    if (StrUtil.isNotEmpty(url)) {
        url = FileUtil.normalize(secondary + url);
        url = StrUtil.SLASH + url;
        if (CacheControllerFeature.isSystemUrl(url) && !userModel.isSystemUser()) {
            // 系统管理员权限
            return false;
        }
        CacheControllerFeature.UrlFeature urlFeature = CacheControllerFeature.getUrlFeature(url);
        if (urlFeature != null) {
            // 功能权限
            boolean b = roleService.errorMethodPermission(userModel, urlFeature.getClassFeature(), urlFeature.getMethodFeature());
            if (b) {
                return false;
            }
        }
    }
    //
    String dynamic = jsonObject.getString("dynamic");
    if (StrUtil.isNotEmpty(dynamic)) {
        if ("showOutGiving".equals(dynamic)) {
            // 是否显示节点分发菜单
            List<NodeModel> list = nodeService.list();
            return list != null && list.size() > 1;
        }
    }
    return true;
}
 
Example 9
Source File: ThymeleafUtil.java    From Jpom with MIT License 5 votes vote down vote up
/**
 * 模板名称需要在 classpath:templates/plugin 下
 *
 * @param template  模板名称
 * @param variables 变量
 * @return 转换后的
 */
public static String process(String template, Map<String, Object> variables) {
    Context context = new Context();
    if (variables == null) {
        variables = new HashMap<>(10);
    }
    String normalize = FileUtil.normalize("plugin/" + template);
    // 用户变量
    UserModel userModel = BaseServerController.getUserModel();
    variables.put(LoginInterceptor.SESSION_NAME, userModel);
    context.setVariables(variables);
    ThymeleafUtil thymeleafUtil = SpringUtil.getBean(ThymeleafUtil.class);
    return thymeleafUtil.springTemplateEngine.process(normalize, context);
}
 
Example 10
Source File: JdkInfoService.java    From Jpom with MIT License 5 votes vote down vote up
/**
 * 使用中的jdk
 *
 * @return JdkInfoModel
 */
private JdkInfoModel getDefaultJdk() {
    JavaRuntimeInfo info = new JavaRuntimeInfo();
    String homeDir = info.getHomeDir();
    String version = new JavaInfo().getVersion();
    if (StrUtil.isEmpty(homeDir) || StrUtil.isEmpty(version)) {
        return null;
    }
    String path = FileUtil.normalize(homeDir.replace("jre", ""));
    JdkInfoModel jdkInfoModel = new JdkInfoModel();
    jdkInfoModel.setId(IdUtil.fastUUID());
    jdkInfoModel.setVersion(version);
    jdkInfoModel.setPath(path);
    return jdkInfoModel;
}
 
Example 11
Source File: SshHandler.java    From Jpom with MIT License 4 votes vote down vote up
@Override
public void afterConnectionEstablished(WebSocketSession session) throws Exception {
    SshModel sshItem = (SshModel) session.getAttributes().get("sshItem");
    Map<String, String[]> parameterMap = (Map<String, String[]>) session.getAttributes().get("parameterMap");
    String[] fileDirAlls = null;
    //判断url是何操作请求
    if (parameterMap.containsKey("tail")) {
        fileDirAlls = parameterMap.get("tail");
    } else if (parameterMap.containsKey("gz")) {
        fileDirAlls = parameterMap.get("gz");
    } else {
        fileDirAlls = parameterMap.get("zip");
    }
    //检查文件路径
    String fileDirAll = null;
    if (fileDirAlls != null && fileDirAlls.length > 0 && !StrUtil.isEmptyOrUndefined(fileDirAlls[0])) {
        fileDirAll = fileDirAlls[0];
        List<String> fileDirs = sshItem.getFileDirs();
        if (fileDirs == null) {
            sendBinary(session, "没有配置路径");
            return;
        }
        File file = FileUtil.file(fileDirAll);
        boolean find = false;
        for (String fileDir : fileDirs) {
            if (FileUtil.isSub(FileUtil.file(fileDir), file)) {
                find = true;
                break;
            }
        }
        if (!find) {
            sendBinary(session, "非法路径");
            return;
        }
    }
    Session openSession = SshService.getSession(sshItem);
    //JschUtil.openSession(sshItem.getHost(), sshItem.getPort(), sshItem.getUser(), sshItem.getPassword());
    Channel channel = JschUtil.createChannel(openSession, ChannelType.SHELL);
    InputStream inputStream = channel.getInputStream();
    OutputStream outputStream = channel.getOutputStream();
    //
    Charset charset = sshItem.getCharsetT();
    HandlerItem handlerItem = new HandlerItem(session, inputStream, outputStream, openSession, channel, charset);
    handlerItem.startRead();
    HANDLER_ITEM_CONCURRENT_HASH_MAP.put(session.getId(), handlerItem);
    //
    Thread.sleep(1000);
    //截取当前操作文件父路径
    String fileLocalPath = null;
    if (fileDirAll != null && fileDirAll.lastIndexOf("/") > -1) {
        fileLocalPath = fileDirAll.substring(0, fileDirAll.lastIndexOf("/"));
    }
    if (fileDirAll == null) {
        this.call(session, StrUtil.CR);
    } else if (parameterMap.containsKey("tail")) {
        // 查看文件
        fileDirAll = FileUtil.normalize(fileDirAll);
        this.call(session, StrUtil.format("tail -f {}", fileDirAll));
        this.call(session, StrUtil.CR);
    } else if (parameterMap.containsKey("zip")) {
        //解压zip
        fileDirAll = FileUtil.normalize(fileDirAll);
        this.call(session, StrUtil.format("unzip -o {} -d " + "{}", fileDirAll, fileLocalPath));
        this.call(session, StrUtil.CR);
    } else {
        //解压 tar和tar.gz
        fileDirAll = FileUtil.normalize(fileDirAll);
        this.call(session, StrUtil.format("tar -xzvf {} -C " + "{}", fileDirAll, fileLocalPath));
        this.call(session, StrUtil.CR);
    }
}
 
Example 12
Source File: BuildListController.java    From Jpom with MIT License 4 votes vote down vote up
private String formatSsh(BuildModel buildModel) {
    //
    String releaseMethodDataId = getParameter("releaseMethodDataId_3");
    if (StrUtil.isEmpty(releaseMethodDataId)) {
        return JsonMessage.getString(405, "请选择分发SSH项");
    }
    String releasePath = getParameter("releasePath");
    if (StrUtil.isEmpty(releasePath)) {
        return JsonMessage.getString(405, "请输入发布到ssh中的目录");
    }
    releasePath = FileUtil.normalize(releasePath);
    if (releasePath.startsWith(StrUtil.SLASH)) {
        // 以根路径开始
        SshModel sshServiceItem = sshService.getItem(releaseMethodDataId);
        if (sshServiceItem == null) {
            return JsonMessage.getString(405, "没有对应的ssh项");
        }
        List<String> fileDirs = sshServiceItem.getFileDirs();
        if (fileDirs == null || fileDirs.isEmpty()) {
            return JsonMessage.getString(405, "此ssh未授权操作此目录");
        }
        boolean find = false;
        for (String fileDir : fileDirs) {
            if (FileUtil.isSub(new File(fileDir), new File(releasePath))) {
                find = true;
            }
        }
        if (!find) {
            return JsonMessage.getString(405, "此ssh未授权操作此目录");
        }
    }
    //
    String releaseCommand = getParameter("releaseCommand");
    if (StrUtil.isEmpty(releaseCommand)) {
        return JsonMessage.getString(405, "请输入发布命令");
    }

    buildModel.setReleasePath(releasePath);
    buildModel.setReleaseCommand(releaseCommand);
    buildModel.setReleaseMethodDataId(releaseMethodDataId);
    String clearOld = getParameter("clearOld");
    buildModel.setClearOld(Convert.toBool(clearOld, false));
    return null;
}
 
Example 13
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 14
Source File: ConfigBean.java    From Jpom with MIT License 4 votes vote down vote up
/**
 * 获取项目运行数据存储文件夹路径
 *
 * @return 文件夹路径
 */
public String getDataPath() {
    String dataPath = FileUtil.normalize(ExtConfigBean.getInstance().getPath() + "/" + DATA);
    FileUtil.mkdir(dataPath);
    return dataPath;
}
 
Example 15
Source File: TomcatInfoModel.java    From Jpom with MIT License 4 votes vote down vote up
public String getAppBase() {
    if (StrUtil.isEmpty(appBase)) {
        return FileUtil.normalize(path + "/webapps/");
    }
    return FileUtil.normalize(appBase + "/");
}
 
Example 16
Source File: BaseBuildModule.java    From Jpom with MIT License 4 votes vote down vote up
public String getResultDirFile() {
    if (resultDirFile == null) {
        return null;
    }
    return FileUtil.normalize(this.resultDirFile.trim());
}
 
Example 17
Source File: TomcatInfoModel.java    From Jpom with MIT License 4 votes vote down vote up
public String getPath() {
    if (path == null) {
        return null;
    }
    return FileUtil.normalize(path + "/");
}
 
Example 18
Source File: AgentConfigBean.java    From Jpom with MIT License 2 votes vote down vote up
/**
 * 获取当前登录用户的临时文件存储路径,如果没有登录则抛出异常
 *
 * @return 文件夹
 */
public String getTempPathName() {
    File file = getTempPath();
    return FileUtil.normalize(file.getPath());
}
 
Example 19
Source File: BaseDataService.java    From Jpom with MIT License 2 votes vote down vote up
/**
 * 获取数据文件的路径,如果文件不存在,则创建一个
 *
 * @param filename 文件名
 * @return path
 */
protected String getDataFilePath(String filename) {
    return FileUtil.normalize(ConfigBean.getInstance().getDataPath() + StrUtil.SLASH + filename);
}
 
Example 20
Source File: ConfigBean.java    From Jpom with MIT License 2 votes vote down vote up
/**
 * 获取 agent 端自动生成的授权文件路径
 *
 * @param dataPath 指定数据路径
 * @return file
 */
public String getAgentAutoAuthorizeFile(String dataPath) {
    return FileUtil.normalize(dataPath + "/" + ConfigBean.AUTHORIZE);
}