List of usage examples for org.apache.commons.lang.time DateFormatUtils format
public static String format(Date date, String pattern)
Formats a date/time into a specific pattern.
From source file:org.b3log.latke.servlet.renderer.freemarker.AbstractFreeMarkerRenderer.java
/** * Processes the specified FreeMarker template with the specified request, * data model. /* w w w .jav a 2s . c o m*/ * * @param request the specified request * @param dataModel the specified data model * @param template the specified FreeMarker template * @return generated HTML * @throws Exception exception */ protected String genHTML(final HttpServletRequest request, final Map<String, Object> dataModel, final Template template) throws Exception { final StringWriter stringWriter = new StringWriter(); template.setOutputEncoding("UTF-8"); template.process(dataModel, stringWriter); final StringBuilder pageContentBuilder = new StringBuilder(stringWriter.toString()); final long endimeMillis = System.currentTimeMillis(); final String dateString = DateFormatUtils.format(endimeMillis, "yyyy/MM/dd HH:mm:ss"); final long startTimeMillis = (Long) request.getAttribute(Keys.HttpRequest.START_TIME_MILLIS); final String msg = String.format("<!-- Generated by B3log Latke(%1$d ms), %2$s -->", endimeMillis - startTimeMillis, dateString); pageContentBuilder.append(msg); final String ret = pageContentBuilder.toString(); request.setAttribute(PageCaches.CACHED_CONTENT, ret); return ret; }
From source file:org.b3log.solo.filter.PageCacheFilter.java
/** * Try to write response from cache./*w w w. ja v a 2s. c om*/ * * @param request the specified request * @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 long startTimeMillis = System.currentTimeMillis(); request.setAttribute(Keys.HttpRequest.START_TIME_MILLIS, startTimeMillis); final HttpServletRequest httpServletRequest = (HttpServletRequest) request; final String requestURI = httpServletRequest.getRequestURI(); LOGGER.log(Level.FINER, "Request URI[{0}]", requestURI); if (StaticResources.isStatic(httpServletRequest)) { final String path = httpServletRequest.getServletPath() + httpServletRequest.getPathInfo(); LOGGER.log(Level.FINEST, "Requests a static resource, forwards to servlet[path={0}]", path); request.getRequestDispatcher(path).forward(request, response); return; } if (!Latkes.isPageCacheEnabled()) { LOGGER.log(Level.FINEST, "Page cache is disabled"); chain.doFilter(request, response); return; } final String skinDirName = (String) httpServletRequest.getAttribute(Keys.TEMAPLTE_DIR_NAME); if ("mobile".equals(skinDirName)) { // Mobile request, bypasses page caching chain.doFilter(request, response); return; } String pageCacheKey; final String queryString = httpServletRequest.getQueryString(); pageCacheKey = (String) request.getAttribute(Keys.PAGE_CACHE_KEY); if (Strings.isEmptyOrNull(pageCacheKey)) { pageCacheKey = PageCaches.getPageCacheKey(requestURI, queryString); request.setAttribute(Keys.PAGE_CACHE_KEY, pageCacheKey); } final JSONObject cachedPageContentObject = PageCaches.get(pageCacheKey, httpServletRequest, (HttpServletResponse) response); if (null == cachedPageContentObject) { LOGGER.log(Level.FINER, "Page cache miss for request URI[{0}]", requestURI); chain.doFilter(request, response); return; } final String cachedType = cachedPageContentObject.optString(PageCaches.CACHED_TYPE); try { // If cached an article that has view password, dispatches the password form if (langPropsService.get(PageTypes.ARTICLE.getLangeLabel()).equals(cachedType) && cachedPageContentObject.has(PageCaches.CACHED_PWD)) { JSONObject article = new JSONObject(); final String articleId = cachedPageContentObject.optString(PageCaches.CACHED_OID); article.put(Keys.OBJECT_ID, articleId); article.put(Article.ARTICLE_VIEW_PWD, cachedPageContentObject.optString(PageCaches.CACHED_PWD)); if (articles.needViewPwd(httpServletRequest, article)) { article = articleRepository.get(articleId); // Loads the article entity final HttpServletResponse httpServletResponse = (HttpServletResponse) response; try { httpServletResponse.sendRedirect(Latkes.getServePath() + "/console/article-pwd" + articles.buildArticleViewPwdFormParameters(article)); return; } catch (final Exception e) { httpServletResponse.sendError(HttpServletResponse.SC_NOT_FOUND); return; } } } } catch (final Exception e) { LOGGER.log(Level.SEVERE, e.getMessage(), e); chain.doFilter(request, response); } try { LOGGER.log(Level.FINEST, "Writes resposne for page[pageCacheKey={0}] from cache", pageCacheKey); response.setContentType("text/html"); response.setCharacterEncoding("UTF-8"); final PrintWriter writer = response.getWriter(); String cachedPageContent = cachedPageContentObject.getString(PageCaches.CACHED_CONTENT); final String topBarHTML = TopBars.getTopBarHTML((HttpServletRequest) request, (HttpServletResponse) response); cachedPageContent = cachedPageContent.replace(Common.TOP_BAR_REPLACEMENT_FLAG, topBarHTML); final String cachedTitle = cachedPageContentObject.getString(PageCaches.CACHED_TITLE); LOGGER.log(Level.FINEST, "Cached value[key={0}, type={1}, title={2}]", new Object[] { pageCacheKey, cachedType, cachedTitle }); statistics.incBlogViewCount((HttpServletRequest) request, (HttpServletResponse) response); final long endimeMillis = System.currentTimeMillis(); final String dateString = DateFormatUtils.format(endimeMillis, "yyyy/MM/dd HH:mm:ss"); final String msg = String.format("<!-- Cached by B3log Solo(%1$d ms), %2$s -->", endimeMillis - startTimeMillis, dateString); LOGGER.finer(msg); cachedPageContent += Strings.LINE_SEPARATOR + msg; writer.write(cachedPageContent); writer.flush(); writer.close(); } catch (final JSONException e) { LOGGER.log(Level.SEVERE, e.getMessage(), e); chain.doFilter(request, response); } catch (final RepositoryException e) { LOGGER.log(Level.SEVERE, e.getMessage(), e); chain.doFilter(request, response); } catch (final ServiceException e) { LOGGER.log(Level.SEVERE, e.getMessage(), e); chain.doFilter(request, response); } }
From source file:org.b3log.solo.processor.api.B3CommentReceiver.java
/** * Adds a comment with the specified request. * <p>/*from ww w . j a v a 2 s. c o m*/ * Request json: * <pre> * { * "comment": { * "userB3Key": "", * "oId": "", * "commentSymphonyArticleId": "", * "commentOnArticleId": "", * "commentAuthorName": "", * "commentAuthorEmail": "", * "commentAuthorURL": "", * "commentAuthorThumbnailURL": "", * "commentContent": "", * "commentOriginalCommentId": "" // optional, if exists this key, the comment is an reply * } * } * </pre> * </p> * <p> * Renders the response with a json object, for example, * <pre> * { * "sc": true * } * </pre> * </p> * * @param context the specified http request context */ @RequestProcessing(value = "/apis/symphony/comment", method = HttpMethod.PUT) public void addComment(final RequestContext context) { final JsonRenderer renderer = new JsonRenderer(); context.setRenderer(renderer); final JSONObject ret = new JSONObject(); renderer.setJSONObject(ret); final JSONObject requestJSONObject = context.requestJSON(); final Transaction transaction = commentRepository.beginTransaction(); try { final JSONObject symphonyCmt = requestJSONObject.optJSONObject(Comment.COMMENT); final JSONObject preference = preferenceQueryService.getPreference(); final String keyOfSolo = preference.optString(Option.ID_C_KEY_OF_SOLO); final String key = symphonyCmt.optString("userB3Key"); if (StringUtils.isBlank(keyOfSolo) || !keyOfSolo.equals(key)) { ret.put(Keys.STATUS_CODE, HttpServletResponse.SC_FORBIDDEN); ret.put(Keys.MSG, "Wrong key"); return; } final String articleId = symphonyCmt.getString("commentOnArticleId"); final JSONObject article = articleRepository.get(articleId); if (null == article) { ret.put(Keys.STATUS_CODE, HttpServletResponse.SC_NOT_FOUND); ret.put(Keys.MSG, "Not found the specified article[id=" + articleId + "]"); return; } final String commentName = symphonyCmt.getString("commentAuthorName"); final String commentEmail = symphonyCmt.getString("commentAuthorEmail").trim().toLowerCase(); String commentURL = symphonyCmt.optString("commentAuthorURL"); if (!commentURL.contains("://")) { commentURL = "http://" + commentURL; } try { new URL(commentURL); } catch (final MalformedURLException e) { LOGGER.log(Level.WARN, "The comment URL is invalid [{0}]", commentURL); commentURL = ""; } final String commentThumbnailURL = symphonyCmt.getString("commentAuthorThumbnailURL"); final String commentId = symphonyCmt.optString(Keys.OBJECT_ID); String commentContent = symphonyCmt.getString(Comment.COMMENT_CONTENT); // commentContent += "<p class='cmtFromSym'><i>? <a href='" + SoloServletListener.B3LOG_SYMPHONY_SERVE_PATH // + "/article/" + symphonyCmt.optString("commentSymphonyArticleId") + "#" + commentId // + "' target='_blank'></a></i></p>"; final String originalCommentId = symphonyCmt.optString(Comment.COMMENT_ORIGINAL_COMMENT_ID); // Step 1: Add comment final JSONObject comment = new JSONObject(); JSONObject originalComment = null; comment.put(Keys.OBJECT_ID, commentId); comment.put(Comment.COMMENT_NAME, commentName); comment.put(Comment.COMMENT_EMAIL, commentEmail); comment.put(Comment.COMMENT_URL, commentURL); comment.put(Comment.COMMENT_THUMBNAIL_URL, commentThumbnailURL); comment.put(Comment.COMMENT_CONTENT, commentContent); final Date date = new Date(); comment.put(Comment.COMMENT_CREATED, date.getTime()); ret.put(Comment.COMMENT_T_DATE, DateFormatUtils.format(date, "yyyy-MM-dd HH:mm:ss")); if (StringUtils.isNotBlank(originalCommentId)) { originalComment = commentRepository.get(originalCommentId); if (null != originalComment) { comment.put(Comment.COMMENT_ORIGINAL_COMMENT_ID, originalCommentId); final String originalCommentName = originalComment.getString(Comment.COMMENT_NAME); comment.put(Comment.COMMENT_ORIGINAL_COMMENT_NAME, originalCommentName); ret.put(Comment.COMMENT_ORIGINAL_COMMENT_NAME, originalCommentName); } else { comment.put(Comment.COMMENT_ORIGINAL_COMMENT_ID, ""); comment.put(Comment.COMMENT_ORIGINAL_COMMENT_NAME, ""); LOGGER.log(Level.WARN, "Not found orginal comment[id={0}] of reply[name={1}, content={2}]", originalCommentId, commentName, commentContent); } } else { comment.put(Comment.COMMENT_ORIGINAL_COMMENT_ID, ""); comment.put(Comment.COMMENT_ORIGINAL_COMMENT_NAME, ""); } ret.put(Comment.COMMENT_THUMBNAIL_URL, comment.getString(Comment.COMMENT_THUMBNAIL_URL)); // Sets comment on article.... comment.put(Comment.COMMENT_ON_ID, articleId); comment.put(Comment.COMMENT_ON_TYPE, Article.ARTICLE); final String commentSharpURL = Comment.getCommentSharpURLForArticle(article, commentId); comment.put(Comment.COMMENT_SHARP_URL, commentSharpURL); commentRepository.add(comment); // Step 2: Update article comment count articleMgmtService.incArticleCommentCount(articleId); // Step 3: Update blog statistic comment count statisticMgmtService.incBlogCommentCount(); statisticMgmtService.incPublishedBlogCommentCount(); // Step 4: Send an email to admin try { commentMgmtService.sendNotificationMail(article, comment, originalComment, preference); } catch (final Exception e) { LOGGER.log(Level.WARN, "Send mail failed", e); } // Step 5: Fire add comment event final JSONObject eventData = new JSONObject(); eventData.put(Comment.COMMENT, comment); eventData.put(Article.ARTICLE, article); eventManager.fireEventSynchronously( new Event<>(EventTypes.ADD_COMMENT_TO_ARTICLE_FROM_SYMPHONY, eventData)); transaction.commit(); ret.put(Keys.STATUS_CODE, true); ret.put(Keys.OBJECT_ID, commentId); ret.put(Keys.OBJECT_ID, articleId); ret.put(Keys.MSG, "add a comment to an article from symphony succ"); ret.put(Keys.STATUS_CODE, true); renderer.setJSONObject(ret); } catch (final Exception e) { LOGGER.log(Level.ERROR, e.getMessage(), e); final JSONObject jsonObject = new JSONObject().put(Keys.STATUS_CODE, false); renderer.setJSONObject(jsonObject); jsonObject.put(Keys.MSG, e.getMessage()); } }
From source file:org.b3log.solo.processor.ArticleProcessorTestCase.java
/** * getArchivesArticlesByPage.// www .java 2 s . c o m * * @throws Exception exception */ @Test(dependsOnMethods = "init") public void getArchivesArticlesByPage() throws Exception { final HttpServletRequest request = mock(HttpServletRequest.class); when(request.getServletContext()).thenReturn(mock(ServletContext.class)); when(request.getRequestURI()).thenReturn( "/articles/archives/" + DateFormatUtils.format(System.currentTimeMillis(), "yyyy/MM") + "/1"); when(request.getMethod()).thenReturn("GET"); when(request.getAttribute(Keys.TEMAPLTE_DIR_NAME)).thenReturn("next"); when(request.getAttribute(Keys.HttpRequest.START_TIME_MILLIS)).thenReturn(System.currentTimeMillis()); final MockDispatcherServlet dispatcherServlet = new MockDispatcherServlet(); dispatcherServlet.init(); final StringWriter stringWriter = new StringWriter(); final PrintWriter printWriter = new PrintWriter(stringWriter); final HttpServletResponse response = mock(HttpServletResponse.class); when(response.getWriter()).thenReturn(printWriter); dispatcherServlet.service(request, response); final String content = stringWriter.toString(); Assert.assertTrue(StringUtils.contains(content, "{\"sc\":true")); }
From source file:org.b3log.solo.processor.ArticleProcessorTestCase.java
/** * showArchiveArticles./*from www . j a v a 2s . c o m*/ * * @throws Exception exception */ @Test(dependsOnMethods = "init") public void showArchiveArticles() throws Exception { final HttpServletRequest request = mock(HttpServletRequest.class); when(request.getServletContext()).thenReturn(mock(ServletContext.class)); when(request.getRequestURI()) .thenReturn("/archives/" + DateFormatUtils.format(System.currentTimeMillis(), "yyyy/MM") + "/1"); when(request.getMethod()).thenReturn("GET"); when(request.getAttribute(Keys.TEMAPLTE_DIR_NAME)).thenReturn("next"); when(request.getAttribute(Keys.HttpRequest.START_TIME_MILLIS)).thenReturn(System.currentTimeMillis()); final MockDispatcherServlet dispatcherServlet = new MockDispatcherServlet(); dispatcherServlet.init(); final StringWriter stringWriter = new StringWriter(); final PrintWriter printWriter = new PrintWriter(stringWriter); final HttpServletResponse response = mock(HttpServletResponse.class); when(response.getWriter()).thenReturn(printWriter); dispatcherServlet.service(request, response); final String content = stringWriter.toString(); Assert.assertTrue(StringUtils.contains(content, "Solo </title>")); }
From source file:org.b3log.solo.processor.SkinRenderer.java
/** * Processes the specified FreeMarker template with the specified request, data model, pjax hacking. * * @param request the specified request * @param dataModel the specified data model * @param template the specified FreeMarker template * @return generated HTML//w w w .ja v a 2 s . co m * @throws Exception exception */ @Override protected String genHTML(final HttpServletRequest request, final Map<String, Object> dataModel, final Template template) throws Exception { final boolean isPJAX = isPJAX(request); dataModel.put("pjax", isPJAX); if (!isPJAX) { return super.genHTML(request, dataModel, template); } final StringWriter stringWriter = new StringWriter(); template.setOutputEncoding("UTF-8"); template.process(dataModel, stringWriter); final long endTimeMillis = System.currentTimeMillis(); final String dateString = DateFormatUtils.format(endTimeMillis, "yyyy/MM/dd HH:mm:ss"); final long startTimeMillis = (Long) request.getAttribute(Keys.HttpRequest.START_TIME_MILLIS); final String latke = String.format( "\n<!-- Generated by Latke (https://github.com/b3log/latke) in %1$dms, %2$s -->", endTimeMillis - startTimeMillis, dateString); final String pjaxContainer = request.getHeader("X-PJAX-Container"); final String html = stringWriter.toString(); final String[] containers = StringUtils.substringsBetween(html, "<!---- pjax {" + pjaxContainer + "} start ---->", "<!---- pjax {" + pjaxContainer + "} end ---->"); if (null == containers) { return html + latke; } return String.join("", containers) + latke; }
From source file:org.b3log.solo.service.DataModelService.java
/** * Fills archive dates./*from w w w .j ava 2 s. c o m*/ * * @param dataModel data model * @param preference the specified preference * @throws ServiceException service exception */ public void fillArchiveDates(final Map<String, Object> dataModel, final JSONObject preference) throws ServiceException { Stopwatchs.start("Fill Archive Dates"); try { LOGGER.debug("Filling archive dates...."); final List<JSONObject> archiveDates = archiveDateRepository.getArchiveDates(); final List<JSONObject> archiveDates2 = new ArrayList<JSONObject>(); dataModel.put(ArchiveDate.ARCHIVE_DATES, archiveDates2); if (archiveDates.isEmpty()) { return; } archiveDates2.add(archiveDates.get(0)); if (1 < archiveDates.size()) { // XXX: Workaround, remove the duplicated archive dates for (int i = 1; i < archiveDates.size(); i++) { final JSONObject archiveDate = archiveDates.get(i); final long time = archiveDate.getLong(ArchiveDate.ARCHIVE_TIME); final String dateString = DateFormatUtils.format(time, "yyyy/MM"); final JSONObject last = archiveDates2.get(archiveDates2.size() - 1); final String lastDateString = DateFormatUtils.format(last.getLong(ArchiveDate.ARCHIVE_TIME), "yyyy/MM"); if (!dateString.equals(lastDateString)) { archiveDates2.add(archiveDate); } else { LOGGER.log(Level.DEBUG, "Found a duplicated archive date [{0}]", dateString); } } } final String localeString = preference.getString(Option.ID_C_LOCALE_STRING); final String language = Locales.getLanguage(localeString); for (final JSONObject archiveDate : archiveDates2) { final long time = archiveDate.getLong(ArchiveDate.ARCHIVE_TIME); final String dateString = DateFormatUtils.format(time, "yyyy/MM"); final String[] dateStrings = dateString.split("/"); final String year = dateStrings[0]; final String month = dateStrings[1]; archiveDate.put(ArchiveDate.ARCHIVE_DATE_YEAR, year); archiveDate.put(ArchiveDate.ARCHIVE_DATE_MONTH, month); if ("en".equals(language)) { final String monthName = Dates.EN_MONTHS.get(month); archiveDate.put(Common.MONTH_NAME, monthName); } } dataModel.put(ArchiveDate.ARCHIVE_DATES, archiveDates2); } catch (final Exception e) { LOGGER.log(Level.ERROR, "Fills archive dates failed", e); throw new ServiceException(e); } finally { Stopwatchs.end(); } }
From source file:org.b3log.solo.service.ExportService.java
/** * Exports as Hexo markdown format./* w w w. ja va2 s .c o m*/ * * @return posts, password posts and drafts, <pre> * { * "posts": [ * { * "front": "", // yaml front matter, * "title": "", * "content": "" * }, .... * ], * "passwords": [], // format is same as post * "drafts": [] // format is same as post * } * </pre> */ public JSONObject exportHexoMDs() { final JSONObject ret = new JSONObject(); final List<JSONObject> posts = new ArrayList<>(); ret.put("posts", (Object) posts); final List<JSONObject> passwords = new ArrayList<>(); ret.put("passwords", (Object) passwords); final List<JSONObject> drafts = new ArrayList<>(); ret.put("drafts", (Object) drafts); final JSONArray articles = getJSONs(articleRepository); for (int i = 0; i < articles.length(); i++) { final JSONObject article = articles.optJSONObject(i); final Map<String, Object> front = new LinkedHashMap<>(); final String title = article.optString(Article.ARTICLE_TITLE); front.put("title", title); final String date = DateFormatUtils.format(article.optLong(Article.ARTICLE_CREATED), "yyyy-MM-dd HH:mm:ss"); front.put("date", date); front.put("updated", DateFormatUtils.format(article.optLong(Article.ARTICLE_UPDATED), "yyyy-MM-dd HH:mm:ss")); final List<String> tags = Arrays.stream(article.optString(Article.ARTICLE_TAGS_REF).split(",")) .filter(StringUtils::isNotBlank).map(String::trim).collect(Collectors.toList()); if (tags.isEmpty()) { tags.add("Solo"); } front.put("tags", tags); front.put("permalink", article.optString(Article.ARTICLE_PERMALINK)); final JSONObject one = new JSONObject(); one.put("front", new Yaml().dump(front)); one.put("title", title); one.put("content", article.optString(Article.ARTICLE_CONTENT)); if (StringUtils.isNotBlank(article.optString(Article.ARTICLE_VIEW_PWD))) { passwords.add(one); continue; } else if (article.optBoolean(Article.ARTICLE_IS_PUBLISHED)) { posts.add(one); continue; } else { drafts.add(one); } } return ret; }
From source file:org.b3log.solo.util.Images.java
/** * Gets an image URL randomly. Sees https://github.com/b3log/bing for more details. * * @return an image URL/*from w w w . jav a2s .c o m*/ */ public static final String randImage() { try { final long min = DateUtils.parseDate("20171104", new String[] { "yyyyMMdd" }).getTime(); final long max = System.currentTimeMillis(); final long delta = max - min; final long time = ThreadLocalRandom.current().nextLong(0, delta) + min; return "https://img.hacpai.com/bing/" + DateFormatUtils.format(time, "yyyyMMdd") + ".jpg"; } catch (final Exception e) { LOGGER.log(Level.ERROR, "Generates random image URL failed", e); return "https://img.hacpai.com/bing/20171104.jpg"; } }
From source file:org.b3log.symphony.api.CommentProcessor.java
/** * The demand format date./*from w ww . j a v a 2 s .c o m*/ * * @param date the original date * @return the format date like "2015-08-03T07:26:57Z" */ private String formatDate(final Object date) { return DateFormatUtils.format(((Date) date).getTime(), "yyyy-MM-dd") + "T" + DateFormatUtils.format(((Date) date).getTime(), "HH:mm:ss") + "Z"; }