cn.hutool.extra.servlet.ServletUtil Java Examples

The following examples show how to use cn.hutool.extra.servlet.ServletUtil. 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: AdminUiService.java    From zuihou-admin-boot with Apache License 2.0 6 votes vote down vote up
/**
 * 超管账号登录
 *
 * @param account  账号
 * @param password 密码
 * @return
 */
public R<AuthInfo> adminLogin(String account, String password) {
    String basicHeader = ServletUtil.getHeader(WebUtils.request(), BASIC_HEADER_KEY, StrPool.UTF_8);
    String[] client = JwtUtil.getClient(basicHeader);

    GlobalUser user = this.globalUserService.getOne(Wrappers.<GlobalUser>lambdaQuery()
            .eq(GlobalUser::getAccount, account).eq(GlobalUser::getTenantCode, BizConstant.SUPER_TENANT));
    // 密码错误
    if (user == null) {
        throw new BizException(ExceptionCode.JWT_USER_INVALID.getCode(), ExceptionCode.JWT_USER_INVALID.getMsg());
    }

    String passwordMd5 = SecureUtil.md5(password);
    if (!user.getPassword().equalsIgnoreCase(passwordMd5)) {
        return R.fail("用户名或密码错误!");
    }
    JwtUserInfo userInfo = new JwtUserInfo(user.getId(), user.getAccount(), user.getName());

    AuthInfo authInfo = tokenUtil.createAuthInfo(userInfo, null);
    log.info("token={}", authInfo.getToken());
    return R.success(authInfo);
}
 
Example #2
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 #3
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 #4
Source File: ShiroFilter.java    From faster-framework-project with Apache License 2.0 6 votes vote down vote up
@Override
protected AuthenticationToken createToken(ServletRequest servletRequest, ServletResponse servletResponse) {
    HttpServletRequest httpServletRequest = (HttpServletRequest) servletRequest;
    String jwtToken = httpServletRequest.getHeader(HeaderConstants.AUTH_TOKEN);
    if (StringUtils.isEmpty(jwtToken)) {
        Cookie cookie = ServletUtil.getCookie((HttpServletRequest) servletRequest, HeaderConstants.AUTH_TOKEN.toLowerCase());
        if (cookie != null) {
            jwtToken = cookie.getValue();
        }
    }
    String finalJwtToken = jwtToken;
    return new AuthenticationToken() {
        @Override
        public Object getPrincipal() {
            return finalJwtToken;
        }

        @Override
        public Object getCredentials() {
            return finalJwtToken;
        }
    };
}
 
Example #5
Source File: AuthorizeInterceptor.java    From Jpom with MIT License 6 votes vote down vote up
@Override
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
    super.preHandle(request, response, handler);
    if (handler instanceof HandlerMethod) {
        HandlerMethod handlerMethod = (HandlerMethod) handler;
        NotAuthorize notAuthorize = handlerMethod.getMethodAnnotation(NotAuthorize.class);
        if (notAuthorize == null) {
            String authorize = ServletUtil.getHeaderIgnoreCase(request, ConfigBean.JPOM_AGENT_AUTHORIZE);
            if (StrUtil.isEmpty(authorize)) {
                this.error(response);
                return false;
            }
            if (!AgentAuthorize.getInstance().checkAuthorize(authorize)) {
                this.error(response);
                return false;
            }
        }
    }
    return true;
}
 
Example #6
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 #7
Source File: ThemeController.java    From mayday with GNU General Public License v3.0 6 votes vote down vote up
/**
 * 保存主题
 * 
 * @param theme
 * @param request
 * @return
 */
@PostMapping("/saveTheme")
@ResponseBody
public JsonResult saveTheme(Theme theme, HttpServletRequest request) {
	try {
		Theme th = themeService.findByThemeName(theme.getThemeName());
		if (th != null) {
			return new JsonResult(MaydayEnums.PRESERVE_ERROR.isFlag(), "该主题已存在");
		}
		themeService.saveTheme(theme);
		// 添加日志
		logService.save(new Log(LogConstant.PUBLISH_AN_THEME, LogConstant.SUCCESS, ServletUtil.getClientIP(request),
				DateUtil.date()));
	} catch (Exception e) {
		log.error(e.getMessage());
		return new JsonResult(MaydayEnums.PRESERVE_ERROR.isFlag(), MaydayEnums.PRESERVE_ERROR.getMessage());
	}
	return new JsonResult(MaydayEnums.PRESERVE_SUCCESS.isFlag(), MaydayEnums.PRESERVE_SUCCESS.getMessage());
}
 
Example #8
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 #9
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 #10
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 #11
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 #12
Source File: UrlRedirectUtil.java    From Jpom with MIT License 6 votes vote down vote up
/**
 * 获取 protocol 协议完全跳转
 *
 * @param request 请求
 * @param url     跳转url
 * @see javax.servlet.http.HttpUtils#getRequestURL
 */
public static String getRedirect(HttpServletRequest request, String url, int port) {
    String proto = ServletUtil.getHeaderIgnoreCase(request, "X-Forwarded-Proto");
    if (proto == null) {
        return url;
    } else {
        String host = request.getHeader(HttpHeaders.HOST);
        if (StrUtil.isEmpty(host)) {
            throw new RuntimeException("请配置host header");
        }
        if ("http".equals(proto) && port == 0) {
            port = 80;
        } else if ("https".equals(proto) && port == 0) {
            port = 443;
        }
        String format = StrUtil.format("{}://{}:{}{}", proto, host, port, url);
        return URLUtil.normalize(format);
    }
}
 
Example #13
Source File: MockFilterHandler.java    From v-mock with MIT License 6 votes vote down vote up
/**
 * 包装请求参数为json
 *
 * @param request 请求
 * @return requestJson
 */
@SneakyThrows
private String requestToJson(HttpServletRequest request) {
    JSONObject requestJsonObj = new JSONObject();
    // get all header
    Map<String, String> headerMap = ServletUtil.getHeaderMap(request);
    requestJsonObj.put("headers", headerMap);
    // get all param
    Map<String, String> paramMap = ServletUtil.getParamMap(request);
    requestJsonObj.put("params", paramMap);
    // body
    @Cleanup BufferedReader reader = request.getReader();
    String body = reader.lines().collect(Collectors.joining(System.lineSeparator()));
    requestJsonObj.put("body", body);
    return requestJsonObj.toString();
}
 
Example #14
Source File: LoginStatusDTO.java    From zuihou-admin-boot with Apache License 2.0 6 votes vote down vote up
private LoginStatusDTO setInfo() {
    RequestAttributes requestAttributes = RequestContextHolder.getRequestAttributes();
    if (requestAttributes == null) {
        return this;
    }
    HttpServletRequest request = ((ServletRequestAttributes) requestAttributes).getRequest();
    if (request == null) {
        return this;
    }
    String ua = StrUtil.sub(request.getHeader("user-agent"), 0, 500);
    String ip = ServletUtil.getClientIP(request);
    String location = AddressUtil.getRegion(ip);
    this.ua = ua;
    this.ip = ip;
    this.location = location;
    return this;
}
 
Example #15
Source File: AdminUiService.java    From zuihou-admin-cloud with Apache License 2.0 6 votes vote down vote up
/**
 * 超管账号登录
 *
 * @param account  账号
 * @param password 密码
 * @return
 */
public R<AuthInfo> adminLogin(String account, String password) {
    String basicHeader = ServletUtil.getHeader(WebUtils.request(), BASIC_HEADER_KEY, StrPool.UTF_8);
    String[] client = JwtUtil.getClient(basicHeader);

    GlobalUser user = this.globalUserService.getOne(Wrappers.<GlobalUser>lambdaQuery()
            .eq(GlobalUser::getAccount, account).eq(GlobalUser::getTenantCode, BizConstant.SUPER_TENANT));
    // 密码错误
    if (user == null) {
        throw new BizException(ExceptionCode.JWT_USER_INVALID.getCode(), ExceptionCode.JWT_USER_INVALID.getMsg());
    }

    String passwordMd5 = SecureUtil.md5(password);
    if (!user.getPassword().equalsIgnoreCase(passwordMd5)) {
        return R.fail("用户名或密码错误!");
    }
    JwtUserInfo userInfo = new JwtUserInfo(user.getId(), user.getAccount(), user.getName());

    AuthInfo authInfo = tokenUtil.createAuthInfo(userInfo, null);
    log.info("token={}", authInfo.getToken());
    return R.success(authInfo);
}
 
Example #16
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 #17
Source File: LoginStatusDTO.java    From zuihou-admin-cloud with Apache License 2.0 6 votes vote down vote up
private LoginStatusDTO setInfo() {
    RequestAttributes requestAttributes = RequestContextHolder.getRequestAttributes();
    if (requestAttributes == null) {
        return this;
    }
    HttpServletRequest request = ((ServletRequestAttributes) requestAttributes).getRequest();
    if (request == null) {
        return this;
    }
    String ua = StrUtil.sub(request.getHeader("user-agent"), 0, 500);
    String ip = ServletUtil.getClientIP(request);
    String location = AddressUtil.getRegion(ip);
    this.ua = ua;
    this.ip = ip;
    this.location = location;
    return this;
}
 
Example #18
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 #19
Source File: DefaultAuthenticationFailureHandler.java    From halo with GNU General Public License v3.0 6 votes vote down vote up
@Override
public void onFailure(HttpServletRequest request, HttpServletResponse response, AbstractHaloException exception) throws IOException, ServletException {
    log.warn("Handle unsuccessful authentication, ip: [{}]", ServletUtil.getClientIP(request));
    log.error("Authentication failure", exception);

    BaseResponse<Object> errorDetail = new BaseResponse<>();

    errorDetail.setStatus(exception.getStatus().value());
    errorDetail.setMessage(exception.getMessage());
    errorDetail.setData(exception.getErrorData());

    if (!productionEnv) {
        errorDetail.setDevMessage(ExceptionUtils.getStackTrace(exception));
    }

    response.setContentType(MediaType.APPLICATION_JSON_UTF8_VALUE);
    response.setStatus(exception.getStatus().value());
    response.getWriter().write(objectMapper.writeValueAsString(errorDetail));
}
 
Example #20
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 #21
Source File: LogFilter.java    From halo with GNU General Public License v3.0 6 votes vote down vote up
@Override
protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException {

    String remoteAddr = ServletUtil.getClientIP(request);

    log.debug("");
    log.debug("Starting url: [{}], method: [{}], ip: [{}]", request.getRequestURL(), request.getMethod(), remoteAddr);

    // Set start time
    long startTime = System.currentTimeMillis();

    // Do filter
    filterChain.doFilter(request, response);

    log.debug("Ending   url: [{}], method: [{}], ip: [{}], status: [{}], usage: [{}] ms", request.getRequestURL(), request.getMethod(), remoteAddr, response.getStatus(), System.currentTimeMillis() - startTime);
    log.debug("");
}
 
Example #22
Source File: AttachmentController.java    From mayday with GNU General Public License v3.0 5 votes vote down vote up
/**
 * 删除附件
 * 
 * @param id
 * @return
 */
@PostMapping(value = "deleteAttachment")
@ResponseBody
public JsonResult deleteAttachment(@RequestParam(value = "id") int id, HttpServletRequest request) {
	Attachment attachment = attachmentService.findById(id);
	try {
		// 获取用户目录
		String userPath = System.getProperties().getProperty("user.home") + "/mayday";
		// 获取文件路径
		String picturePath = attachment.getPicturePath();
		String pictureSmallPath = attachment.getPictureSmallPath();
		File picturePathFile = new File(new StringBuffer(userPath).append(picturePath).toString());
		File pictureSmallPathFile = new File(new StringBuffer(userPath).append(pictureSmallPath).toString());
		if (picturePathFile.isFile() && picturePathFile.exists()) {
			System.gc();
			if (pictureSmallPathFile.delete() && picturePathFile.delete()) {
				attachmentService.deleteAttachment(id);
				log.info("删除文件" + attachment.getPictureName() + "成功");
				// 添加日志
				logService.save(new Log(LogConstant.DELETE_ATTACHMENT, LogConstant.DELETE_SUCCESS,
						ServletUtil.getClientIP(request), DateUtil.date()));
			} else {
				log.error("删除文件" + attachment.getPictureName() + "失败");
				return new JsonResult(MaydayEnums.OPERATION_ERROR.isFlag(),
						MaydayEnums.OPERATION_ERROR.getMessage());
			}
		}
	} catch (Exception e) {
		log.error("删除文件" + attachment.getPictureName() + "失败");
		return new JsonResult(MaydayEnums.ERROR.isFlag(), MaydayEnums.ERROR.getMessage());
	}
	return new JsonResult(MaydayEnums.OPERATION_SUCCESS.isFlag(), MaydayEnums.OPERATION_SUCCESS.getMessage());
}
 
Example #23
Source File: LogsServiceImpl.java    From blog-sharon with Apache License 2.0 5 votes vote down vote up
/**
 * 保存日志
 *
 * @param logTitle   logTitle
 * @param logContent logContent
 * @param request    request
 */
@Override
public void save(String logTitle, String logContent, HttpServletRequest request) {
    Logs logs = new Logs();
    logs.setLogTitle(logTitle);
    logs.setLogContent(logContent);
    logs.setLogCreated(new Date());
    logs.setLogIp(ServletUtil.getClientIP(request));
    logsRepository.save(logs);
}
 
Example #24
Source File: AbstractTokenGranter.java    From zuihou-admin-cloud with Apache License 2.0 5 votes vote down vote up
/**
 * 检测 client
 *
 * @return
 */
protected R<String[]> checkClient() {
    String basicHeader = ServletUtil.getHeader(WebUtils.request(), BASIC_HEADER_KEY, StrPool.UTF_8);
    String[] client = JwtUtil.getClient(basicHeader);
    Application application = applicationService.getOne(Wraps.<Application>lbQ().eq(Application::getClientId, client[0])
            .eq(Application::getClientSecret, client[1]));

    if (application == null) {
        return R.fail("请填写正确的客户端ID或者客户端秘钥");
    }
    if (!application.getStatus()) {
        return R.fail("客户端[%s]已被禁用", application.getClientId());
    }
    return R.success(client);
}
 
Example #25
Source File: IndexController.java    From mayday with GNU General Public License v3.0 5 votes vote down vote up
/**
 * 检测同一IP十分钟以内重复访问同一篇文章
 * 
 * @param request
 * @param id
 *            文章id
 * @return
 */
public boolean checkRepeatIp(HttpServletRequest request, int id) {

	String value = ServletUtil.getClientIP(request) + ":" + id;
	Integer count = cache.hget("hits:frequency", value);
	if (count != null && count > 0) {
		return true;
	}
	cache.hset("hits:frequency", value, 1, MaydayConst.IP_REPEAT_TIME);
	return false;
}
 
Example #26
Source File: RibbonController.java    From fw-spring-cloud with Apache License 2.0 5 votes vote down vote up
@GetMapping("/{id:\\d+}")
    public User getUserById(@PathVariable Long id, HttpServletRequest req) throws InterruptedException {
//        int millis = new Random().nextInt(3000);
//        System.out.println("client线程休眠时间:"+millis);
//        Thread.sleep(millis);
//        if(millis>1000){
//            throw new RuntimeException("error");
//        }
        log.info(ServletUtil.getClientIP(req));
        String url = req.getRequestURL().toString();
        User user = userService.getUserById(id);
        user.setRemark(user.getRemark()+":提供服务的是:"+url);
        return user;
    }
 
Example #27
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 #28
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 #29
Source File: AbstractTokenGranter.java    From zuihou-admin-boot with Apache License 2.0 5 votes vote down vote up
/**
 * 检测 client
 *
 * @return
 */
protected R<String[]> checkClient() {
    String basicHeader = ServletUtil.getHeader(WebUtils.request(), BASIC_HEADER_KEY, StrPool.UTF_8);
    String[] client = JwtUtil.getClient(basicHeader);
    Application application = applicationService.getOne(Wraps.<Application>lbQ().eq(Application::getClientId, client[0])
            .eq(Application::getClientSecret, client[1]));

    if (application == null) {
        return R.fail("请填写正确的客户端ID或者客户端秘钥");
    }
    if (!application.getStatus()) {
        return R.fail("客户端[%s]已被禁用", application.getClientId());
    }
    return R.success(client);
}
 
Example #30
Source File: ControllerLogAop.java    From halo with GNU General Public License v3.0 5 votes vote down vote up
private void printRequestLog(HttpServletRequest request, String clazzName, String methodName, Object[] args) throws JsonProcessingException {
    log.debug("Request URL: [{}], URI: [{}], Request Method: [{}], IP: [{}]",
        request.getRequestURL(),
        request.getRequestURI(),
        request.getMethod(),
        ServletUtil.getClientIP(request));

    if (args == null || !log.isDebugEnabled()) {
        return;
    }

    boolean shouldNotLog = false;
    for (Object arg : args) {
        if (arg == null ||
            arg instanceof HttpServletRequest ||
            arg instanceof HttpServletResponse ||
            arg instanceof MultipartFile ||
            arg.getClass().isAssignableFrom(MultipartFile[].class)) {
            shouldNotLog = true;
            break;
        }
    }

    if (!shouldNotLog) {
        String requestBody = JsonUtils.objectToJson(args);
        log.debug("{}.{} Parameters: [{}]", clazzName, methodName, requestBody);
    }
}