List of usage examples for org.apache.commons.lang StringUtils substringAfter
public static String substringAfter(String str, String separator)
Gets the substring after the first occurrence of a separator.
From source file:org.b3log.solo.filter.PermalinkFilter.java
/** * Tries to dispatch request to article processor. * * @param request the specified request/* w w w. j a v a 2 s . c o m*/ * @param response the specified response * @param chain filter chain * @throws IOException io exception * @throws ServletException servlet exception */ @Override public void doFilter(final ServletRequest request, final ServletResponse response, final FilterChain chain) throws IOException, ServletException { final HttpServletRequest httpServletRequest = (HttpServletRequest) request; final HttpServletResponse httpServletResponse = (HttpServletResponse) response; final String requestURI = httpServletRequest.getRequestURI(); LOGGER.log(Level.FINER, "Request URI[{0}]", requestURI); final String contextPath = Latkes.getContextPath(); final String permalink = StringUtils.substringAfter(requestURI, contextPath); if (Permalinks.invalidPermalinkFormat(permalink)) { LOGGER.log(Level.FINER, "Skip filter request[URI={0}]", permalink); chain.doFilter(request, response); return; } JSONObject article; JSONObject page = null; try { article = articleRepository.getByPermalink(permalink); if (null == article) { page = pageRepository.getByPermalink(permalink); } if (null == page && null == article) { LOGGER.log(Level.FINER, "Not found article/page with permalink[{0}]", permalink); chain.doFilter(request, response); return; } } catch (final RepositoryException e) { LOGGER.log(Level.SEVERE, "Processes article permalink filter failed", e); httpServletResponse.sendError(HttpServletResponse.SC_NOT_FOUND); return; } // If requests an article and the article need view passowrd, sends redirect to the password form if (null != article && articles.needViewPwd(httpServletRequest, article)) { try { httpServletResponse.sendRedirect(Latkes.getServePath() + "/console/article-pwd" + articles.buildArticleViewPwdFormParameters(article)); return; } catch (final Exception e) { httpServletResponse.sendError(HttpServletResponse.SC_NOT_FOUND); return; } } dispatchToArticleOrPageProcessor(request, response, article, page); }
From source file:org.b3log.solo.processor.FileUploadProcessor.java
@Override public void doGet(final HttpServletRequest req, final HttpServletResponse resp) throws ServletException, IOException { if (QN_ENABLED) { return;/*from w w w . jav a2 s . com*/ } final String uri = req.getRequestURI(); String key = StringUtils.substringAfter(uri, "/upload/"); key = StringUtils.substringBeforeLast(key, "?"); // Erase Qiniu template key = StringUtils.substringBeforeLast(key, "?"); // Erase Qiniu template String path = UPLOAD_DIR + key; path = URLDecoder.decode(path, "UTF-8"); if (!FileUtil.isExistingFile(new File(path))) { resp.sendError(HttpServletResponse.SC_NOT_FOUND); return; } final byte[] data = IOUtils.toByteArray(new FileInputStream(path)); final String ifNoneMatch = req.getHeader("If-None-Match"); final String etag = "\"" + MD5.hash(new String(data)) + "\""; resp.addHeader("Cache-Control", "public, max-age=31536000"); resp.addHeader("ETag", etag); resp.setHeader("Server", "Latke Static Server (v" + SoloServletListener.VERSION + ")"); if (etag.equals(ifNoneMatch)) { resp.setStatus(HttpServletResponse.SC_NOT_MODIFIED); return; } final OutputStream output = resp.getOutputStream(); IOUtils.write(data, output); output.flush(); IOUtils.closeQuietly(output); }
From source file:org.b3log.solo.processor.FileUploadProcessor.java
@Override public void doPost(final HttpServletRequest req, final HttpServletResponse resp) throws ServletException, IOException { if (QN_ENABLED) { return;/* w ww . ja va 2 s. com*/ } final MultipartRequestInputStream multipartRequestInputStream = new MultipartRequestInputStream( req.getInputStream()); multipartRequestInputStream.readBoundary(); multipartRequestInputStream.readDataHeader("UTF-8"); String fileName = multipartRequestInputStream.getLastHeader().getFileName(); String suffix = StringUtils.substringAfterLast(fileName, "."); if (StringUtils.isBlank(suffix)) { final String mimeType = multipartRequestInputStream.getLastHeader().getContentType(); String[] exts = MimeTypes.findExtensionsByMimeTypes(mimeType, false); if (null != exts && 0 < exts.length) { suffix = exts[0]; } else { suffix = StringUtils.substringAfter(mimeType, "/"); } } final String name = StringUtils.substringBeforeLast(fileName, "."); final String processName = name.replaceAll("\\W", ""); final String uuid = UUID.randomUUID().toString().replaceAll("-", ""); if (StringUtils.isBlank(processName)) { fileName = uuid + "." + suffix; } else { fileName = uuid + '_' + processName + "." + suffix; } final OutputStream output = new FileOutputStream(UPLOAD_DIR + fileName); IOUtils.copy(multipartRequestInputStream, output); IOUtils.closeQuietly(multipartRequestInputStream); IOUtils.closeQuietly(output); final JSONObject data = new JSONObject(); data.put("key", Latkes.getServePath() + "/upload/" + fileName); data.put("name", fileName); resp.setContentType("application/json"); final PrintWriter writer = resp.getWriter(); writer.append(data.toString()); writer.flush(); writer.close(); }
From source file:org.b3log.solo.processor.IndexProcessor.java
/** * Gets the request page number from the specified request URI. * /*from w w w . j a va 2s.c o m*/ * @param requestURI the specified request URI * @return page number, returns {@code -1} if the specified request URI * can not convert to an number */ private static int getCurrentPageNum(final String requestURI) { final String pageNumString = StringUtils.substringAfter(requestURI, "/"); return Requests.getCurrentPageNum(pageNumString); }
From source file:org.b3log.solo.service.ImportService.java
private JSONObject parseArticle(final String fileName, String fileContent) { fileContent = StringUtils.trim(fileContent); String frontMatter = StringUtils.substringBefore(fileContent, "---"); if (StringUtils.isBlank(frontMatter)) { fileContent = StringUtils.substringAfter(fileContent, "---"); frontMatter = StringUtils.substringBefore(fileContent, "---"); }//w w w . j a va 2s.c om final JSONObject ret = new JSONObject(); final Yaml yaml = new Yaml(); Map elems; try { elems = (Map) yaml.load(frontMatter); } catch (final Exception e) { // treat it as plain markdown ret.put(Article.ARTICLE_TITLE, StringUtils.substringBeforeLast(fileName, ".")); ret.put(Article.ARTICLE_CONTENT, fileContent); ret.put(Article.ARTICLE_ABSTRACT, Article.getAbstract(fileContent)); ret.put(Article.ARTICLE_TAGS_REF, DEFAULT_TAG); ret.put(Article.ARTICLE_IS_PUBLISHED, true); ret.put(Article.ARTICLE_COMMENTABLE, true); ret.put(Article.ARTICLE_VIEW_PWD, ""); return ret; } String title = (String) elems.get("title"); if (StringUtils.isBlank(title)) { title = StringUtils.substringBeforeLast(fileName, "."); } ret.put(Article.ARTICLE_TITLE, title); String content = StringUtils.substringAfter(fileContent, frontMatter); if (StringUtils.startsWith(content, "---")) { content = StringUtils.substringAfter(content, "---"); content = StringUtils.trim(content); } ret.put(Article.ARTICLE_CONTENT, content); final String abs = parseAbstract(elems, content); ret.put(Article.ARTICLE_ABSTRACT, abs); final Date date = parseDate(elems); ret.put(Article.ARTICLE_CREATED, date.getTime()); final String permalink = (String) elems.get("permalink"); if (StringUtils.isNotBlank(permalink)) { ret.put(Article.ARTICLE_PERMALINK, permalink); } final List<String> tags = parseTags(elems); final StringBuilder tagBuilder = new StringBuilder(); for (final String tag : tags) { tagBuilder.append(tag).append(","); } tagBuilder.deleteCharAt(tagBuilder.length() - 1); ret.put(Article.ARTICLE_TAGS_REF, tagBuilder.toString()); ret.put(Article.ARTICLE_IS_PUBLISHED, true); ret.put(Article.ARTICLE_COMMENTABLE, true); ret.put(Article.ARTICLE_VIEW_PWD, ""); return ret; }
From source file:org.b3log.symphony.api.v2.ArticleAPI2.java
/** * Gets tag articles./* ww w. ja va2 s . c om*/ * * @param context the specified context * @param request the specified request * @param tagURI the specified tag URI */ @RequestProcessing(value = { "/api/v2/articles/tag/{tagURI}", "/api/v2/articles/tag/{tagURI}/hot", "/api/v2/articles/tag/{tagURI}/good", "/api/v2/articles/tag/{tagURI}/reply", "/api/v2/articles/tag/{tagURI}/perfect" }, method = HTTPRequestMethod.GET) @Before(adviceClass = { StopwatchStartAdvice.class, AnonymousViewCheck.class }) @After(adviceClass = { PermissionGrant.class, StopwatchEndAdvice.class }) public void getTagArticles(final HTTPRequestContext context, final HttpServletRequest request, final String tagURI) { int page = 1; final String p = request.getParameter("p"); if (Strings.isNumeric(p)) { page = Integer.parseInt(p); } final JSONObject ret = new JSONObject(); context.renderJSONPretty(ret); ret.put(Keys.STATUS_CODE, StatusCodes.ERR); ret.put(Keys.MSG, ""); JSONObject data = null; try { final JSONObject tag = tagQueryService.getTagByURI(tagURI); if (null == tag) { ret.put(Keys.MSG, "Tag not found"); ret.put(Keys.STATUS_CODE, StatusCodes.NOT_FOUND); return; } data = new JSONObject(); data.put(Tag.TAG, tag); V2s.cleanTag(tag); String sortModeStr = StringUtils.substringAfter(request.getRequestURI(), "/tag/" + tagURI); int sortMode; switch (sortModeStr) { case "": sortMode = 0; break; case "/hot": sortMode = 1; break; case "/good": sortMode = 2; break; case "/reply": sortMode = 3; break; case "/perfect": sortMode = 4; break; default: sortMode = 0; } final int avatarViewMode = (int) request.getAttribute(UserExt.USER_AVATAR_VIEW_MODE); final List<JSONObject> articles = articleQueryService.getArticlesByTag(avatarViewMode, sortMode, tag, page, V2s.PAGE_SIZE); data.put(Article.ARTICLES, articles); V2s.cleanArticles(articles); final int tagRefCnt = tag.getInt(Tag.TAG_REFERENCE_CNT); final int pageCount = (int) Math.ceil(tagRefCnt / (double) V2s.PAGE_SIZE); final JSONObject pagination = new JSONObject(); final List<Integer> pageNums = Paginator.paginate(page, V2s.PAGE_SIZE, pageCount, V2s.WINDOW_SIZE); pagination.put(Pagination.PAGINATION_PAGE_COUNT, pageCount); pagination.put(Pagination.PAGINATION_PAGE_NUMS, pageNums); data.put(Pagination.PAGINATION, pagination); ret.put(Keys.STATUS_CODE, StatusCodes.SUCC); } catch (final Exception e) { final String msg = "Gets tag [uri=" + tagURI + "] articles failed"; LOGGER.log(Level.ERROR, msg, e); ret.put(Keys.MSG, msg); } ret.put(Common.DATA, data); }
From source file:org.b3log.symphony.api.v2.ArticleAPI2.java
/** * Gets latest articles./*from w w w . j a v a 2 s . c om*/ * * @param context the specified context * @param request the specified request */ @RequestProcessing(value = { "/api/v2/articles/latest", "/api/v2/articles/latest/hot", "/api/v2/articles/latest/good", "/api/v2/articles/latest/reply" }, method = HTTPRequestMethod.GET) @Before(adviceClass = { StopwatchStartAdvice.class, AnonymousViewCheck.class }) @After(adviceClass = { PermissionGrant.class, StopwatchEndAdvice.class }) public void getLatestArticles(final HTTPRequestContext context, final HttpServletRequest request) { int page = 1; final String p = request.getParameter("p"); if (Strings.isNumeric(p)) { page = Integer.parseInt(p); } final JSONObject ret = new JSONObject(); context.renderJSONPretty(ret); ret.put(Keys.STATUS_CODE, StatusCodes.ERR); ret.put(Keys.MSG, ""); JSONObject data = null; try { final int avatarViewMode = (int) request.getAttribute(UserExt.USER_AVATAR_VIEW_MODE); String sortModeStr = StringUtils.substringAfter(request.getRequestURI(), "/latest"); int sortMode; switch (sortModeStr) { case "": sortMode = 0; break; case "/hot": sortMode = 1; break; case "/good": sortMode = 2; break; case "/reply": sortMode = 3; break; default: sortMode = 0; } data = articleQueryService.getRecentArticles(avatarViewMode, sortMode, page, V2s.PAGE_SIZE); final List<JSONObject> articles = (List<JSONObject>) data.opt(Article.ARTICLES); V2s.cleanArticles(articles); ret.put(Keys.STATUS_CODE, StatusCodes.SUCC); } catch (final Exception e) { final String msg = "Gets latest articles failed"; LOGGER.log(Level.ERROR, msg, e); ret.put(Keys.MSG, msg); } ret.put(Common.DATA, data); }
From source file:org.b3log.symphony.processor.ChatRoomProcessor.java
/** * XiaoV replies Stm.//from w w w. jav a2s . c o m * * @param context the specified context * @param request the specified request * @param response the specified response * @throws IOException io exception * @throws ServletException servlet exception */ @RequestProcessing(value = "/cron/xiaov", method = HTTPRequestMethod.GET) public void xiaoVReply(final HTTPRequestContext context, final HttpServletRequest request, final HttpServletResponse response) throws IOException, ServletException { context.renderJSON(); try { final JSONObject xiaoV = userQueryService.getUserByName(TuringQueryService.ROBOT_NAME); if (null == xiaoV) { return; } final int avatarViewMode = (int) request.getAttribute(UserExt.USER_AVATAR_VIEW_MODE); final String xiaoVUserId = xiaoV.optString(Keys.OBJECT_ID); final String xiaoVEmail = xiaoV.optString(User.USER_EMAIL); final JSONObject result = notificationQueryService.getAtNotifications(avatarViewMode, xiaoVUserId, 1, 1); // Just get the latest one final List<JSONObject> notifications = (List<JSONObject>) result.get(Keys.RESULTS); for (final JSONObject notification : notifications) { if (notification.optBoolean(Notification.NOTIFICATION_HAS_READ)) { continue; } String xiaoVSaid = ""; final JSONObject comment = new JSONObject(); String articleId = StringUtils.substringBetween(notification.optString(Common.URL), "/article/", "#"); String q = ""; if (!StringUtils.isBlank(articleId)) { final String originalCmtId = StringUtils.substringAfter(notification.optString(Common.URL), "#"); final JSONObject originalCmt = commentQueryService.getCommentById(avatarViewMode, originalCmtId); q = originalCmt.optString(Comment.COMMENT_CONTENT); } else { articleId = StringUtils.substringAfter(notification.optString(Common.URL), "/article/"); final JSONObject article = articleQueryService.getArticleById(avatarViewMode, articleId); q = article.optString(Article.ARTICLE_CONTENT); } if (StringUtils.isNotBlank(q)) { q = Jsoup.parse(q).text(); if (!StringUtils.contains(q, "@" + TuringQueryService.ROBOT_NAME + " ")) { continue; } q = StringUtils.replace(q, "@" + TuringQueryService.ROBOT_NAME + " ", ""); xiaoVSaid = turingQueryService.chat(articleId, q); comment.put(Comment.COMMENT_CONTENT, xiaoVSaid); comment.put(Comment.COMMENT_AUTHOR_ID, xiaoVUserId); comment.put(Comment.COMMENT_AUTHOR_EMAIL, xiaoVEmail); comment.put(Comment.COMMENT_ON_ARTICLE_ID, articleId); xiaoV.remove(UserExt.USER_T_POINT_CC); xiaoV.remove(UserExt.USER_T_POINT_HEX); comment.put(Comment.COMMENT_T_COMMENTER, xiaoV); commentMgmtService.addComment(comment); } notificationMgmtService.makeRead(notification); } context.renderTrueResult(); } catch (final Exception e) { LOGGER.log(Level.ERROR, "Update user latest comment time failed", e); } }
From source file:org.b3log.symphony.processor.FetchUploadProcessor.java
/** * Fetches the remote file and upload it. * * @param context the specified context/*from w w w .ja v a2s . c o m*/ * @param request the specified request * @param response the specified response * @throws Exception exception */ @RequestProcessing(value = "/fetch-upload", method = HTTPRequestMethod.POST) @Before(adviceClass = { StopwatchStartAdvice.class, LoginCheck.class }) @After(adviceClass = { StopwatchEndAdvice.class }) public void fetchUpload(final HTTPRequestContext context, final HttpServletRequest request, final HttpServletResponse response) throws Exception { context.renderJSON(); JSONObject requestJSONObject; try { requestJSONObject = Requests.parseRequestJSONObject(request, response); request.setAttribute(Keys.REQUEST, requestJSONObject); } catch (final Exception e) { LOGGER.warn(e.getMessage()); return; } final String originalURL = requestJSONObject.optString(Common.URL); HttpResponse res = null; byte[] data; String contentType; try { final HttpRequest req = HttpRequest.get(originalURL); res = req.send(); if (HttpServletResponse.SC_OK != res.statusCode()) { return; } data = res.bodyBytes(); contentType = res.contentType(); } catch (final Exception e) { LOGGER.log(Level.ERROR, "Fetch file [url=" + originalURL + "] failed", e); return; } finally { if (null != res) { try { res.close(); } catch (final Exception e) { LOGGER.log(Level.ERROR, "Close response failed", e); } } } String suffix; String[] exts = MimeTypes.findExtensionsByMimeTypes(contentType, false); if (null != exts && 0 < exts.length) { suffix = exts[0]; } else { suffix = StringUtils.substringAfter(contentType, "/"); } final String fileName = UUID.randomUUID().toString().replace("-", "") + "." + suffix; if (Symphonys.getBoolean("qiniu.enabled")) { final Auth auth = Auth.create(Symphonys.get("qiniu.accessKey"), Symphonys.get("qiniu.secretKey")); final UploadManager uploadManager = new UploadManager(); uploadManager.put(data, "e/" + fileName, auth.uploadToken(Symphonys.get("qiniu.bucket")), null, contentType, false); context.renderJSONValue(Common.URL, Symphonys.get("qiniu.domain") + "/e/" + fileName); context.renderJSONValue("originalURL", originalURL); } else { final OutputStream output = new FileOutputStream(Symphonys.get("upload.dir") + fileName); IOUtils.write(data, output); IOUtils.closeQuietly(output); context.renderJSONValue(Common.URL, Latkes.getServePath() + "/upload/" + fileName); context.renderJSONValue("originalURL", originalURL); } context.renderTrueResult(); }
From source file:org.b3log.symphony.processor.FileUploadServlet.java
@Override public void doGet(final HttpServletRequest req, final HttpServletResponse resp) throws ServletException, IOException { if (QN_ENABLED) { return;//from ww w.j ava 2 s . com } final LatkeBeanManager beanManager = Lifecycle.getBeanManager(); final UserQueryService userQueryService = beanManager.getReference(UserQueryService.class); final UserMgmtService userMgmtService = beanManager.getReference(UserMgmtService.class); final OptionQueryService optionQueryService = beanManager.getReference(OptionQueryService.class); try { final JSONObject option = optionQueryService.getOption(Option.ID_C_MISC_ALLOW_ANONYMOUS_VIEW); if (!"0".equals(option.optString(Option.OPTION_VALUE))) { if (null == userQueryService.getCurrentUser(req) && !userMgmtService.tryLogInWithCookie(req, resp)) { final String referer = req.getHeader("Referer"); if (!StringUtils.contains(referer, "fangstar.net")) { final String authorization = req.getHeader("Authorization"); LOGGER.debug("Referer [" + referer + "], Authorization [" + authorization + "]"); if (!StringUtils.contains(authorization, "Basic ")) { resp.sendError(HttpServletResponse.SC_FORBIDDEN); return; } else { String usernamePwd = StringUtils.substringAfter(authorization, "Basic "); usernamePwd = Base64.decodeToString(usernamePwd); final String username = usernamePwd.split(":")[0]; final String password = usernamePwd.split(":")[1]; if (!StringUtils.equals(username, Symphonys.get("http.basic.auth.username")) || !StringUtils.equals(password, Symphonys.get("http.basic.auth.password"))) { resp.sendError(HttpServletResponse.SC_FORBIDDEN); return; } } } } } } catch (final Exception e) { LOGGER.log(Level.ERROR, "Gets file failed", e); resp.sendError(HttpServletResponse.SC_FORBIDDEN); return; } final String uri = req.getRequestURI(); String key = uri.substring("/upload/".length()); key = StringUtils.substringBeforeLast(key, "-64.jpg"); // Erase Qiniu template key = StringUtils.substringBeforeLast(key, "-260.jpg"); // Erase Qiniu template String path = UPLOAD_DIR + key; if (!FileUtil.isExistingFile(new File(path))) { resp.sendError(HttpServletResponse.SC_NOT_FOUND); return; } final byte[] data = IOUtils.toByteArray(new FileInputStream(path)); final String ifNoneMatch = req.getHeader("If-None-Match"); final String etag = "\"" + MD5.hash(new String(data)) + "\""; resp.addHeader("Cache-Control", "public, max-age=31536000"); resp.addHeader("ETag", etag); resp.setHeader("Server", "Latke Static Server (v" + SymphonyServletListener.VERSION + ")"); if (etag.equals(ifNoneMatch)) { resp.setStatus(HttpServletResponse.SC_NOT_MODIFIED); return; } final OutputStream output = resp.getOutputStream(); IOUtils.write(data, output); output.flush(); IOUtils.closeQuietly(output); }