Java Code Examples for cn.hutool.extra.servlet.ServletUtil#write()

The following examples show how to use cn.hutool.extra.servlet.ServletUtil#write() . 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: 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 2
Source File: NodeForward.java    From Jpom with MIT License 6 votes vote down vote up
/**
 * 下载文件消息转发
 *
 * @param nodeModel 节点
 * @param request   请求
 * @param response  响应
 * @param nodeUrl   节点的url
 */
public static void requestDownload(NodeModel nodeModel, HttpServletRequest request, HttpServletResponse response, NodeUrl nodeUrl) {
    String url = nodeModel.getRealUrl(nodeUrl);
    HttpRequest httpRequest = HttpUtil.createGet(url);
    addUser(httpRequest, nodeModel, nodeUrl);
    //
    Map params = ServletUtil.getParams(request);
    httpRequest.form(params);
    //
    HttpResponse response1;
    try {
        response1 = httpRequest.execute();
    } catch (Exception e) {
        throw new AgentException(nodeModel.getName() + "节点异常:" + e.getMessage(), e);
    }
    String contentDisposition = response1.header("Content-Disposition");
    response.setHeader("Content-Disposition", contentDisposition);
    String contentType = response1.header("Content-Type");
    response.setContentType(contentType);
    ServletUtil.write(response, response1.bodyStream());
}
 
Example 3
Source File: GlobalDefaultExceptionHandler.java    From Jpom with MIT License 6 votes vote down vote up
/**
 * 声明要捕获的异常
 *
 * @param request  请求
 * @param response 响应
 * @param e        异常
 */
@ExceptionHandler({AgentException.class, AuthorizeException.class, RuntimeException.class, Exception.class})
public void paramExceptionHandler(HttpServletRequest request, HttpServletResponse response, Exception e) {
    DefaultSystemLog.getLog().error("controller " + request.getRequestURI(), e);
    if (BaseJpomInterceptor.isPage(request)) {
        try {
            String id = IdUtil.fastUUID();
            TIMED_CACHE.put(id, getErrorMsg(e));
            BaseJpomInterceptor.sendRedirects(request, response, "/error.html?id=" + id);
        } catch (IOException ex) {
            ex.printStackTrace();
        }
    } else {
        if (e instanceof AuthorizeException) {
            AuthorizeException authorizeException = (AuthorizeException) e;
            ServletUtil.write(response, authorizeException.getJsonMessage().toString(), MediaType.APPLICATION_JSON_UTF8_VALUE);
        } else if (e instanceof AgentException || e instanceof JpomRuntimeException) {
            ServletUtil.write(response, JsonMessage.getString(500, e.getMessage()), MediaType.APPLICATION_JSON_UTF8_VALUE);
        } else {
            ServletUtil.write(response, JsonMessage.getString(500, "服务异常:" + e.getMessage()), MediaType.APPLICATION_JSON_UTF8_VALUE);
        }
    }
}
 
Example 4
Source File: LoginInterceptor.java    From Jpom with MIT License 6 votes vote down vote up
/**
 * 提示登录
 *
 * @param request       req
 * @param response      res
 * @param handlerMethod 方法
 * @throws IOException 异常
 */
private void responseLogin(HttpServletRequest request, HttpServletResponse response, HandlerMethod handlerMethod) throws IOException {
    if (isPage(handlerMethod)) {
        String url = "/login.html?";
        String uri = request.getRequestURI();
        if (StrUtil.isNotEmpty(uri) && !StrUtil.SLASH.equals(uri)) {
            String queryString = request.getQueryString();
            if (queryString != null) {
                uri += "?" + queryString;
            }
            // 补全
            String newUri = BaseJpomInterceptor.getHeaderProxyPath(request) + uri;
            newUri = UrlRedirectUtil.getRedirect(request, newUri);
            url += "&url=" + URLUtil.encodeAll(newUri);
        }
        String header = request.getHeader(HttpHeaders.REFERER);
        if (header != null) {
            url += "&r=" + header;
        }
        sendRedirects(request, response, url);
        return;
    }
    ServletUtil.write(response, JsonMessage.getString(800, "登录信息已失效,重新登录"), MediaType.APPLICATION_JSON_UTF8_VALUE);
}
 
Example 5
Source File: OpenApiInterceptor.java    From Jpom with MIT License 6 votes vote down vote up
private boolean checkOpenApi(HttpServletRequest request, HttpServletResponse response) {
    String header = request.getHeader(ServerOpenApi.HEAD);
    if (StrUtil.isEmpty(header)) {
        ServletUtil.write(response, JsonMessage.getString(300, "token empty"), MediaType.APPLICATION_JSON_UTF8_VALUE);
        return false;
    }
    String authorizeToken = ServerExtConfigBean.getInstance().getAuthorizeToken();
    if (StrUtil.isEmpty(authorizeToken)) {
        ServletUtil.write(response, JsonMessage.getString(300, "not config token"), MediaType.APPLICATION_JSON_UTF8_VALUE);
        return false;
    }
    String md5 = SecureUtil.md5(authorizeToken);
    md5 = SecureUtil.sha1(md5 + ServerOpenApi.HEAD);
    if (!StrUtil.equals(header, md5)) {
        ServletUtil.write(response, JsonMessage.getString(300, "not config token"), MediaType.APPLICATION_JSON_UTF8_VALUE);
        return false;
    }
    return true;
}
 
Example 6
Source File: NodeWelcomeController.java    From Jpom with MIT License 6 votes vote down vote up
@RequestMapping(value = "exportTop")
public void exportTop(String time) throws UnsupportedEncodingException {
    PageResult<SystemMonitorLog> monitorData = getList(time, getCycleMillis());
    if (monitorData.getTotal() <= 0) {
        //            NodeForward.requestDownload(node, getRequest(), getResponse(), NodeUrl.exportTop);
    } else {
        NodeModel node = getNode();
        StringBuilder buf = new StringBuilder();
        buf.append("监控时间").append(",占用cpu").append(",占用内存").append(",占用磁盘").append("\r\n");
        for (SystemMonitorLog log : monitorData) {
            long monitorTime = log.getMonitorTime();
            buf.append(DateUtil.date(monitorTime).toString()).append(",")
                    .append(log.getOccupyCpu()).append("%").append(",")
                    .append(log.getOccupyMemory()).append("%").append(",")
                    .append(log.getOccupyDisk()).append("%").append("\r\n");
        }
        String fileName = URLEncoder.encode("Jpom系统监控-" + node.getId(), "UTF-8");
        HttpServletResponse response = getResponse();
        response.setHeader("Content-Disposition", "attachment;filename=" + new String(fileName.getBytes(StandardCharsets.UTF_8), "GBK") + ".csv");
        response.setContentType("text/csv;charset=utf-8");
        ServletUtil.write(getResponse(), buf.toString(), CharsetUtil.UTF_8);
    }
}
 
Example 7
Source File: BuildHistoryController.java    From Jpom with MIT License 6 votes vote down vote up
@RequestMapping(value = "download_log.html", method = RequestMethod.GET)
@ResponseBody
@Feature(method = MethodFeature.DOWNLOAD)
public void downloadLog(@ValidatorItem(value = ValidatorRule.NOT_BLANK, msg = "没有数据") String logId) throws IOException {
    BuildHistoryLog buildHistoryLog = dbBuildHistoryLogService.getByKey(logId);
    Objects.requireNonNull(buildHistoryLog);
    BuildModel item = buildService.getItem(buildHistoryLog.getBuildDataId());
    Objects.requireNonNull(item);
    File logFile = BuildUtil.getLogFile(item.getId(), buildHistoryLog.getBuildNumberId());
    if (!logFile.exists()) {
        return;
    }
    if (logFile.isFile()) {
        ServletUtil.write(getResponse(), logFile);
    }
}
 
Example 8
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 9
Source File: ProjectFileControl.java    From Jpom with MIT License 6 votes vote down vote up
@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 10
Source File: LogManageController.java    From Jpom with MIT License 5 votes vote down vote up
@RequestMapping(value = "log_download", method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
@ResponseBody
public void logDownload(@ValidatorItem(value = ValidatorRule.NOT_BLANK, msg = "path错误") String path) {
    WebAopLog webAopLog = SpringUtil.getBean(WebAopLog.class);
    File file = FileUtil.file(webAopLog.getPropertyValue(), path);
    if (file.isFile()) {
        ServletUtil.write(getResponse(), file);
    }
}
 
Example 11
Source File: AgentExceptionHandler.java    From Jpom with MIT License 5 votes vote down vote up
/**
 * 声明要捕获的异常
 *
 * @param request  请求
 * @param response 响应
 * @param e        异常
 */
@ExceptionHandler({JpomRuntimeException.class, RuntimeException.class, Exception.class})
public void paramExceptionHandler(HttpServletRequest request, HttpServletResponse response, Exception e) {
    DefaultSystemLog.getLog().error("controller " + request.getRequestURI(), e);
    if (e instanceof JpomRuntimeException) {
        ServletUtil.write(response, JsonMessage.getString(500, e.getMessage()), MediaType.APPLICATION_JSON_UTF8_VALUE);
    } else {
        ServletUtil.write(response, JsonMessage.getString(500, "服务异常:" + e.getMessage()), MediaType.APPLICATION_JSON_UTF8_VALUE);
    }
}
 
Example 12
Source File: CommonController.java    From kvf-admin with MIT License 5 votes vote down vote up
@GetMapping(value = "download")
public void download(String filePath) {
    if (StrUtil.isBlank(filePath)) {
        throw new KvfException("不存在的文件:" + filePath);
    }
    HttpServletResponse response = HttpServletContextKit.getHttpServletResponse();
    ServletUtil.write(response, new File(filePath));
}
 
Example 13
Source File: InternalController.java    From Jpom with MIT License 5 votes vote down vote up
/**
 * 下载文件
 *
 * @param response response
 * @param fileName 文件名字
 */
private void downLoad(HttpServletResponse response, String fileName) {
    //获取项目根路径
    File file = new File(fileName);
    ServletUtil.write(response, file);
    FileUtil.del(file);
}
 
Example 14
Source File: SshFileController.java    From Jpom with MIT License 5 votes vote down vote up
@RequestMapping(value = "download.html", method = RequestMethod.GET)
@ResponseBody
@Feature(method = MethodFeature.DOWNLOAD)
public void download(String id, String path, String name) throws IOException {
    HttpServletResponse response = getResponse();
    SshModel sshModel = sshService.getItem(id);
    if (sshModel == null) {
        ServletUtil.write(response, "ssh error", MediaType.TEXT_HTML_VALUE);
        return;
    }
    List<String> fileDirs = sshModel.getFileDirs();
    //
    if (StrUtil.isEmpty(path) || !fileDirs.contains(path)) {
        ServletUtil.write(response, "没有配置此文件夹", MediaType.TEXT_HTML_VALUE);
        return;
    }
    if (StrUtil.isEmpty(name)) {
        ServletUtil.write(response, "name error", MediaType.TEXT_HTML_VALUE);
        return;
    }
    try {
        this.downloadFile(sshModel, path, name, response);
    } catch (SftpException e) {
        DefaultSystemLog.getLog().error("下载失败", e);
        ServletUtil.write(response, "download error", MediaType.TEXT_HTML_VALUE);
    }
}
 
Example 15
Source File: LogManageController.java    From Jpom with MIT License 5 votes vote down vote up
@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 16
Source File: CommonController.java    From kvf-admin with MIT License 5 votes vote down vote up
/**
 * 使用流访问项目外部的静态文件
 */
@GetMapping(value = "static/{uploadType}/{fileType}/{yyyyMMdd}/{filename}")
public void staticFile(@PathVariable String uploadType, @PathVariable String fileType, @PathVariable String yyyyMMdd, @PathVariable String filename) {
    String basePath = System.getProperty("user.dir") + File.separator + Constants.BASE_USER_FILE_PATH;
    String fileUrl = basePath + "/" + uploadType + "/" + fileType + "/" + yyyyMMdd + "/" + filename;
    HttpServletResponse response = HttpServletContextKit.getHttpServletResponse();
    ServletUtil.write(response, new File(fileUrl));
}
 
Example 17
Source File: LogBackController.java    From Jpom with MIT License 5 votes vote down vote up
@RequestMapping(value = "export.html", method = RequestMethod.GET)
@ResponseBody
public String export(String copyId) {
    ProjectInfoModel pim = getProjectInfoModel();
    ProjectInfoModel.JavaCopyItem copyItem = pim.findCopyItem(copyId);
    File file = copyItem == null ? new File(pim.getLog()) : pim.getLog(copyItem);
    if (!file.exists()) {
        return JsonMessage.getString(400, "没有日志文件:" + file.getPath());
    }
    HttpServletResponse response = getResponse();
    ServletUtil.write(response, file);
    return JsonMessage.getString(200, "");
}
 
Example 18
Source File: CommonController.java    From kvf-admin with MIT License 5 votes vote down vote up
/**
 * 访问项目外部静态图片
 */
@GetMapping(value = "static/{fileType}/{yyyyMMdd}/{filename}")
public void staticImage(@PathVariable String fileType, @PathVariable String yyyyMMdd, @PathVariable String filename) {
    String basePath = System.getProperty("user.dir") + File.separator + Constants.BASE_USER_FILE_PATH;
    String fileUrl = basePath + "/" + fileType + "/" + yyyyMMdd + "/" + filename;
    String suffix = filename.substring(filename.lastIndexOf(".") + 1);
    try {
        HttpServletResponse response = HttpServletContextKit.getHttpServletResponse();
        ServletUtil.write(response, new FileInputStream(new File(fileUrl)), "image/" + suffix);
    } catch (IOException e) {
        log.error(e.getMessage(), e);
        throw new KvfException("访问静态图片【" + fileUrl + "】出错:" + e.getMessage());
    }
}
 
Example 19
Source File: AuthorizeInterceptor.java    From Jpom with MIT License 4 votes vote down vote up
private void error(HttpServletResponse response) {
    ServletUtil.write(response, JsonMessage.getString(ConfigBean.AUTHORIZE_ERROR, "授权信息错误"), MediaType.APPLICATION_JSON_UTF8_VALUE);
}
 
Example 20
Source File: GenController.java    From kvf-admin with MIT License 4 votes vote down vote up
@GetMapping(value = "download/codeZip")
public void downloadCodeZip() {
    String fileUrl = ConfigConstant.CODE_GEN_PATH + "/" + ConfigConstant.CODE_ZIP_FILENAME;
    File file = new File(fileUrl);
    ServletUtil.write(HttpServletContextKit.getHttpServletResponse(), file);
}