package space.apps.moudules.website.template.util; import java.sql.Timestamp; import java.text.SimpleDateFormat; import java.util.Date; import java.util.Iterator; import java.util.List; import java.util.Locale; import java.util.Map; import java.util.regex.Pattern; import javax.servlet.http.HttpServletRequest; import apps.pojo.Article; import apps.pojo.Website; import apps.pojo.WebsiteNavigation; import space.apps.moudules.website.template.common.WebsiteArticleManager; import space.common.exception.SpaceNullPointerException; import space.core.common.CommonVars; import space.core.common.utils.DateTimeUtil; import space.core.common.utils.FileUtil; import space.core.common.utils.GsonUtil; import space.core.common.utils.StringUtil; import space.core.db.bean.base.PageBean; import space.core.db.jdbc.GeneralDBAccess; import space.core.db.jdbc.SqlCommandImpl; /** * 文章工具类 * * @author SPACE * @date 2020年02月15日 */ public class WebsiteTemplateArticleUtil { private static final Long ARTICLE_DCODE_USE = 61L; private static final Long ARTICLE_DCODE_CHANGING = 31L; private static final Long ARTICLE_ASCODE_RELEASED = 10010L; private static final String CHANGE_LOG_OBJECT_ARTICLE = "Article"; private static final String PUBLISHED_CONTENT_SNAPSHOT_FIELD = "publishedContentSnapshot"; private static final String PUBLISHED_EDIT_CONTENT_SNAPSHOT_FIELD = "publishedEditContentSnapshot"; private static final Pattern LOCAL_UPLOAD_ABSOLUTE_URL_PATTERN = Pattern.compile( "(?i)(?:https?:)?//(?:ht\\.gzhxtc\\.edu\\.cn|localhost|127\\.0\\.0\\.1|ffkj-[a-z0-9-]+\\.localhost)(?::\\d+)?(/web/upload/[^\"'<>\\s]*)"); /** * 获取栏目的子栏目文章列表 * * @param gdba 数据库 * @param navId 栏目ID * @param isThumbnailFlag 是否只查询有上传缩略图的文章,为真则查询,否则不查询 * @param pb 分页对象 * @return ArticleList * @throws Exception * @author SPACE * @log Oct 9, 2020 8:48:37 AM */ public static List> getAllChildrenArticleList(GeneralDBAccess gdba, Long navId, boolean isThumbnailFlag, PageBean pb) throws Exception { String sql = "SELECT a.*, w.protocol, w.port, w.domains FROM article a left join website w on a.websiteid = w.websiteid where w.dcode = 61 and " + getPublishedOrChangingArticleSql("a") + " and (a.navigationid in (Select navigationid from website_navigation where parent_nid = :navigationid1 ) " + " or a.articleid in (Select ac.articleid from article_copy ac, article ca where ca.articleid = ac.articleid and ac.dcode = 61 " + " and " + getPublishedOrChangingArticleSql("ca") + " and ac.navigationid in (Select navigationid from website_navigation where parent_nid = :navigationid2 ) ))" + (isThumbnailFlag ? " and a.thumbnail is not null" : "") // thumbnail + " order by a.sticktop desc, a.release_time desc, a.articleid desc"; SqlCommandImpl sqlCmd = new SqlCommandImpl(sql); sqlCmd.setString("navigationid1", navId).setString("navigationid2", navId); List> articleList = gdba.selectAsMapList(sqlCmd, pb); restoreChangingArticleListPublishedVersion(gdba, articleList); transformArticleURL(articleList); return articleList; } /** * 根据 Request 获取文章对象 * * @param gdba 数据库对象 * @param website 网站对象 * @param request request * @return Article * @throws Exception * @author SPACE * @date 2020年02月15日 */ public static Article getArticleByRequest(GeneralDBAccess gdba, Website website, HttpServletRequest request) throws Exception { return getArticleByURI(gdba, website, request.getRequestURI()); } /** * 根据 URI 获取文章对象 * * @param gdba 数据库对象 * @param website 网站对象 * @param uri URI * @return Article * @throws Exception * @author SPACE * @date 2020年02月15日 */ public static Article getArticleByURI(GeneralDBAccess gdba, Website website, String uri) throws Exception { String sql = "SELECT a.* FROM article a, website_navigation wn where a.navigationid = wn.navigationid " + "and wn.websiteid = :websiteid and wn.dcode = 61 and a.dcode = 61 and a.ascode = '10010' and a.url = :uri "; SqlCommandImpl sqlCmd = new SqlCommandImpl(sql); sqlCmd.setString("websiteid", website.getWebsiteid()).setString("uri", uri); Article a = (Article) gdba.selectAsBean(sqlCmd, Article.class); return a == null ? getChangingArticlePublishedVersionByURI(gdba, website, uri) : a; } /** * 根据文章获取文章内容 * * @param article 文章对象 * @return html * @throws Exception 如文件不存在或读取文件时出现问题,则抛出异常 * @author SPACE * @date 2020年02月15日 */ public static String getArticleContentByArticle(Article article) throws Exception { return getArticleContentByPath(article.getContent()); } /** * 根据文章路径读取文件内容 * * @param contentPath 文章文件路径 * @return 文章内容 * @throws Exception * @author SPACE * @date 2020年02月27日 */ public static String getArticleContentByPath(String contentPath) throws Exception { if (StringUtil.isNull(contentPath)) { throw new SpaceNullPointerException(" Article content path is null "); } return FileUtil.readFile(CommonVars.getWebRootPath() + contentPath); } /** * 获取文章列表 * * @param gdba 数据库对象 * @param navId 栏目ID * @param isThumbnailFlag 是否只查询有上传缩略图的文章,为真则查询,否则不查询 * @param pb 分页对象 * @return ArticleList * @author SPACE * @throws Exception * @date 2020年02月13日 */ public static List> getArticleList(GeneralDBAccess gdba, Long navId, boolean isThumbnailFlag, PageBean pb) throws Exception { String sql = "SELECT a.*, w.protocol, w.port, w.domains FROM article a left join website w on a.websiteid = w.websiteid " + "where w.dcode = 61 and " + getPublishedOrChangingArticleSql("a") + " and (a.navigationid = :navigationid1 " + "or a.articleid in (Select ac.articleid from article_copy ac, article ca " + "where ca.articleid = ac.articleid and ac.dcode = 61 and " + getPublishedOrChangingArticleSql("ca") + " and ac.navigationid = :navigationid2 ))" + (isThumbnailFlag ? " and a.thumbnail is not null" : "") // thumbnail + " order by a.sticktop desc, a.release_time desc "; SqlCommandImpl sqlCmd = new SqlCommandImpl(sql); sqlCmd.setString("navigationid1", navId).setString("navigationid2", navId); List> articleList = gdba.selectAsMapList(sqlCmd, pb); restoreChangingArticleListPublishedVersion(gdba, articleList); transformArticleURL(articleList); return articleList; } /** * 获取文章列表 * * @param gdba 数据库对象 * @param navId 栏目ID * @param pb 分页对象 * @return ArticleList * @throws Exception * @author SPACE * @log Oct 9, 2020 5:11:26 AM */ public static List> getArticleList(GeneralDBAccess gdba, Long navId, PageBean pb) throws Exception { return getArticleList(gdba, navId, false, pb); } /** * 查询文章列表 * * @param gdba 数据库 * @param keyword 文章标题关键字 * @param pb 分页对象 * @return 文章列表 * @throws Exception * @author SPACE * @log Oct 9, 2020 10:37:47 AM */ public static List> getArticleList(GeneralDBAccess gdba, String keyword, PageBean pb) throws Exception { String sql = "SELECT a.*, w.protocol, w.port, w.domains FROM article a left join website w on a.websiteid = w.websiteid where w.dcode = 61 and " + getPublishedOrChangingArticleSql("a") + " and title like :keyword order by a.sticktop desc, a.release_time desc"; SqlCommandImpl sqlCmd = new SqlCommandImpl(sql); sqlCmd.setString("keyword", "%" + keyword + "%"); List> articleList = gdba.selectAsMapList(sqlCmd, pb); restoreChangingArticleListPublishedVersion(gdba, articleList); transformArticleURL(articleList); return articleList; } /** * 查询当前站群内文章列表。主站搜索主站及下级站点,子站搜索其所属主站站群。 * * @param gdba 数据库 * @param website 当前网站 * @param keyword 文章标题或摘要关键字 * @param pb 分页对象 * @return 文章列表 * @throws Exception */ public static List> getArticleList(GeneralDBAccess gdba, Website website, String keyword, PageBean pb) throws Exception { Long rootWebsiteId = website.getParentWid() == null ? website.getWebsiteid() : website.getParentWid(); String sql = "SELECT a.*, w.protocol, w.port, w.domains, w.name website_name, wn.name navigation_name " + "FROM article a " + "left join website w on a.websiteid = w.websiteid " + "left join website_navigation wn on a.navigationid = wn.navigationid " + "where w.dcode = 61 and " + getPublishedOrChangingArticleSql("a") + " " + "and (w.websiteid = :rootWebsiteId1 " + "or w.parent_wid = :rootWebsiteId2 " + "or w.parent_wid in (select sw.websiteid from website sw where sw.dcode = 61 and sw.parent_wid = :rootWebsiteId3) " + "or w.parent_wid in (select tw.websiteid from website tw where tw.dcode = 61 and tw.parent_wid in " + "(select sw2.websiteid from website sw2 where sw2.dcode = 61 and sw2.parent_wid = :rootWebsiteId4))) " + "and (a.title like :keyword1 or a.`desc` like :keyword2) " + "order by a.sticktop desc, a.release_time desc, a.articleid desc"; SqlCommandImpl sqlCmd = new SqlCommandImpl(sql); sqlCmd.setString("rootWebsiteId1", rootWebsiteId).setString("rootWebsiteId2", rootWebsiteId) .setString("rootWebsiteId3", rootWebsiteId).setString("rootWebsiteId4", rootWebsiteId) .setString("keyword1", "%" + keyword + "%").setString("keyword2", "%" + keyword + "%"); List> articleList = gdba.selectAsMapList(sqlCmd, pb); restoreChangingArticleListPublishedVersion(gdba, articleList); transformArticleURL(articleList); return articleList; } private static String getPublishedOrChangingArticleSql(String alias) { return "((" + alias + ".dcode = 61 and " + alias + ".ascode = '10010') or " + alias + ".dcode = 31)"; } private static Article getChangingArticlePublishedVersionByURI(GeneralDBAccess gdba, Website website, String uri) throws Exception { String sql = "SELECT cl.content FROM change_log cl where cl.object = :object and cl.content like :uriLike " + "and cl.objectid in (select ca.articleid from article ca where ca.dcode = :changingDcode) " + "order by cl.change_logid desc limit 0,20"; SqlCommandImpl sqlCmd = new SqlCommandImpl(sql); sqlCmd.setString("object", CHANGE_LOG_OBJECT_ARTICLE).setString("uriLike", "%" + uri + "%") .setString("changingDcode", ARTICLE_DCODE_CHANGING); List> logList = gdba.selectAsMapList(sqlCmd); if (logList == null || logList.size() == 0) { return null; } for (Map log : logList) { Article article = buildPublishedArticleFromChangeLog(log.get("content"), website.getWebsiteid(), uri); if (article != null) { return article; } } return null; } private static Article getChangingArticlePublishedVersionByArticleID(GeneralDBAccess gdba, Long articleid) throws Exception { String sql = "SELECT content FROM change_log where object = :object and objectid = :articleid " + "order by change_logid desc limit 0,20"; SqlCommandImpl sqlCmd = new SqlCommandImpl(sql); sqlCmd.setString("object", CHANGE_LOG_OBJECT_ARTICLE).setString("articleid", articleid); List> logList = gdba.selectAsMapList(sqlCmd); if (logList == null || logList.size() == 0) { return null; } for (Map log : logList) { Article article = buildPublishedArticleFromChangeLog(log.get("content"), null, null); if (article != null) { return article; } } return null; } private static Article buildPublishedArticleFromChangeLog(Object logContent, Long websiteid, String uri) { if (StringUtil.isNull(logContent)) { return null; } Map articleMap = GsonUtil.jsonToMap(logContent.toString()); if (!ARTICLE_DCODE_USE.equals(getLongValue(articleMap, "dcode")) || !ARTICLE_ASCODE_RELEASED.equals(getLongValue(articleMap, "ascode"))) { return null; } if (websiteid != null && !websiteid.equals(getLongValue(articleMap, "websiteid"))) { return null; } if (uri != null && !uri.equals(getStringValue(articleMap, "url"))) { return null; } Article article = new Article(); article.setArticleid(getLongValue(articleMap, "articleid")); article.setDcode(ARTICLE_DCODE_USE); article.setWebsiteid(getLongValue(articleMap, "websiteid")); article.setUnitid(getLongValue(articleMap, "unitid")); article.setAscode(ARTICLE_ASCODE_RELEASED); article.setNavigationid(getLongValue(articleMap, "navigationid")); article.setTitle(getStringValue(articleMap, "title")); article.setAjtcode(getLongValue(articleMap, "ajtcode")); article.setDesc(getStringValue(articleMap, "desc")); article.setSource(getStringValue(articleMap, "source")); article.setThumbnail(getStringValue(articleMap, "thumbnail")); article.setSticktop(getLongValue(articleMap, "sticktop")); article.setSticktopEndTime(getTimestampValue(articleMap, "sticktopEndTime")); article.setSticktopSchedulesid(getLongValue(articleMap, "sticktopSchedulesid")); article.setRelease(getLongValue(articleMap, "release")); article.setReleaseTime(getTimestampValue(articleMap, "releaseTime")); article.setReleaseTaskSchedulesid(getLongValue(articleMap, "releaseTaskSchedulesid")); article.setContent(getStringValue(articleMap, PUBLISHED_CONTENT_SNAPSHOT_FIELD)); if (StringUtil.isNull(article.getContent())) { article.setContent(getStringValue(articleMap, "content")); } article.setEditContent(getStringValue(articleMap, PUBLISHED_EDIT_CONTENT_SNAPSHOT_FIELD)); if (StringUtil.isNull(article.getEditContent())) { article.setEditContent(getStringValue(articleMap, "editContent")); } article.setUrl(getStringValue(articleMap, "url")); article.setReadCount(getLongValue(articleMap, "readCount")); article.setCreateTime(getTimestampValue(articleMap, "createTime")); article.setLastChangeTime(getTimestampValue(articleMap, "lastChangeTime")); article.setCreatePid(getLongValue(articleMap, "createPid")); article.setLastChangePid(getLongValue(articleMap, "lastChangePid")); return article; } private static void restoreChangingArticleListPublishedVersion(GeneralDBAccess gdba, List> articleList) throws Exception { if (articleList == null || articleList.size() == 0) { return; } Iterator> iterator = articleList.iterator(); while (iterator.hasNext()) { Map articleMap = iterator.next(); if (!ARTICLE_DCODE_CHANGING.equals(getLongValue(articleMap, "dcode"))) { continue; } Article article = getChangingArticlePublishedVersionByArticleID(gdba, getLongValue(articleMap, "articleid")); if (article == null) { iterator.remove(); continue; } putArticleValueToMap(articleMap, article); } } private static void putArticleValueToMap(Map articleMap, Article article) { articleMap.put("articleid", article.getArticleid()); articleMap.put("dcode", article.getDcode()); articleMap.put("websiteid", article.getWebsiteid()); articleMap.put("unitid", article.getUnitid()); articleMap.put("ascode", article.getAscode()); articleMap.put("navigationid", article.getNavigationid()); articleMap.put("title", article.getTitle()); articleMap.put("ajtcode", article.getAjtcode()); articleMap.put("desc", article.getDesc()); articleMap.put("source", article.getSource()); articleMap.put("thumbnail", article.getThumbnail()); articleMap.put("sticktop", article.getSticktop()); articleMap.put("sticktop_end_time", article.getSticktopEndTime()); articleMap.put("sticktop_schedulesid", article.getSticktopSchedulesid()); articleMap.put("release", article.getRelease()); articleMap.put("release_time", article.getReleaseTime()); articleMap.put("release_task_schedulesid", article.getReleaseTaskSchedulesid()); articleMap.put("content", article.getContent()); articleMap.put("edit_content", article.getEditContent()); articleMap.put("url", article.getUrl()); articleMap.put("read_count", article.getReadCount()); articleMap.put("create_time", article.getCreateTime()); articleMap.put("last_change_time", article.getLastChangeTime()); articleMap.put("create_pid", article.getCreatePid()); articleMap.put("last_change_pid", article.getLastChangePid()); } private static String getStringValue(Map map, String key) { Object value = map.get(key); return StringUtil.isNull(value) ? null : value.toString(); } private static Long getLongValue(Map map, String key) { Object value = map.get(key); if (StringUtil.isNull(value)) { return null; } if (value instanceof Number) { return ((Number) value).longValue(); } return Long.valueOf(value.toString()); } private static Timestamp getTimestampValue(Map map, String key) { String value = getStringValue(map, key); if (StringUtil.isNull(value)) { return null; } String[] patterns = new String[] { "MMM d, yyyy h:mm:ss a", "yyyy-MM-dd HH:mm:ss", "yyyy-MM-dd HH:mm" }; for (String pattern : patterns) { try { Date date = new SimpleDateFormat(pattern, Locale.ENGLISH).parse(value); return new Timestamp(date.getTime()); } catch (Exception e) { // 尝试下一种历史日志里的时间格式。 } } try { return Timestamp.valueOf(value); } catch (Exception e) { return null; } } /** * 获取文章列表 * * @param gdba 数据库 * @param wn 栏目 * @param pb 分页 * @return 文章列表 * @throws Exception * @author SPACE * @date 2020年02月27日 */ public static List> getArticleList(GeneralDBAccess gdba, WebsiteNavigation wn, PageBean pb) throws Exception { return getArticleList(gdba, wn.getNavigationid(), pb); } /** * 生成文章的URL * * @param wn 栏目对象 * @return /栏目URL/12为随机数.html * @author SPACE * @throws SpaceNullPointerException * @date 2020年02月14日 */ public static String getArticleURL(WebsiteNavigation wn) throws SpaceNullPointerException { if (StringUtil.isNull(wn.getUrl())) { throw new SpaceNullPointerException("栏目URL为空"); } String wnUrl = wn.getUrl().endsWith("/") ? wn.getUrl() : wn.getUrl() + "/"; return wnUrl + DateTimeUtil.getSimpleYear() + DateTimeUtil.getNowDate("MMdd") + "/" + StringUtil.getNonceStr(12) + ".htm"; } /** * 获取栏目下的第一篇文章 * * @param wn 栏目对象 * @return 文章对象Map * @author SPACE * @throws Exception * @date 2020年02月26日 */ public static Map getFristArticleByWn(GeneralDBAccess gdba, WebsiteNavigation wn) throws Exception { PageBean pb = new PageBean(); pb.setRowCountPerPage(1); List> articleList = getArticleList(gdba, wn, pb); return (articleList == null || articleList.size() == 0) ? null : articleList.get(0); } private static void setArticleAttrToRequest(HttpServletRequest request, Website website, Long articleID, String title, Object desc, String source, String releaseTime, String contentPath) throws Exception { request.setAttribute("articleTitle", title); request.setAttribute("articleSource", source); request.setAttribute("articleReleaseTime", releaseTime); request.setAttribute("articleDescription", StringUtil.isNull(desc) ? title : desc); request.setAttribute("articleContent", normalizeLocalUploadResourceUrl( WebsiteArticleManager.getArticleContent(website, articleID, contentPath))); } private static String normalizeLocalUploadResourceUrl(String content) { if (StringUtil.isNull(content) || content.indexOf("/web/upload/") < 0) { return content; } return LOCAL_UPLOAD_ABSOLUTE_URL_PATTERN.matcher(content).replaceAll("$1"); } /** * 将页面需要的文章属性放到 Request 中
* articleTitle: 文章标题
* articleSource: 文章来源
* articleReleaseTime: 文章发布时间
* articleDescription: 文章摘要
* articleContent: 文章正文(HTML)
* * @param article 文章对象 * @param request 请求 * @throws Exception * @author SPACE * @log Oct 7, 2020 10:37:32 PM */ public static void setArticleAttrToRequest(Website website, Article article, HttpServletRequest request) throws Exception { setArticleAttrToRequest(request, website, article.getArticleid(), article.getTitle(), article.getDesc(), article.getSource(), DateTimeUtil.formatDate(article.getReleaseTime(), "yyyy-MM-dd HH:mm"), article.getContent()); } /** * 将页面需要的文章属性放到 Request 中
* articleTitle: 文章标题
* articleSource: 文章来源
* articleReleaseTime: 文章发布时间
* articleDescription: 文章摘要
* articleContent: 文章正文(HTML)
* * @param articleMap 文章 Map * @param request 请求 * @throws Exception * @author SPACE * @log Oct 7, 2020 10:48:01 PM */ public static void setArticleAttrToRequest(Website website, Map articleMap, HttpServletRequest request) throws Exception { setArticleAttrToRequest(request, website, Long.valueOf(articleMap.get("articleid").toString()), articleMap.get("title").toString(), articleMap.get("desc"), articleMap.get("source").toString(), DateTimeUtil.formatDate(articleMap.get("release_time").toString(), "yyyy-MM-dd HH:mm"), articleMap.get("content").toString()); } /** * 转换文章的URL * * @param articleList 文章列表 * @author SPACE * @log Oct 9, 2020 8:27:29 AM */ private static void transformArticleURL(List> articleList) { if (articleList == null || articleList.size() == 0) { return; } // 文章URL加入网站域名,如一个网站绑定了多个域名,默认取第一个 for (Map map : articleList) { String url = map.get("url").toString(); String ajtCode = map.get("ajtcode").toString(); String href = null; // 最终跳转的链接 String target = null; // 跳转方式 // 动作:跳转正文页 if ("10000".equals(ajtCode)) { String domains = map.get("domains").toString(); // 域名 String protocol = map.get("protocol").toString(); // 协议 String port = map.get("port").toString(); // 端口 String[] domainsAry = domains.split(";"); if (domainsAry.length > 0) { port = "80".equals(port) ? "" : (":" + port); // 非 80 端口进行特殊处理 if (domainsAry[0].endsWith("/")) { domainsAry[0] = domainsAry[0].substring(0, domainsAry[0].lastIndexOf("/")); } href = protocol + "://" + domainsAry[0] + port + url; target = "_blank"; } // 未找到域名 else { href = "javascript:alert('website domain is null!');"; target = "_self"; } } // 动作:自定义链接 else if ("10020".equals(ajtCode)) { href = url; target = "_blank"; } // 动作:无动作 else if ("10030".equals(ajtCode)) { href = "javascript:void(0);"; target = "_self"; } map.put("url", href); map.put("target", target); Object thumbnail = map.get("thumbnail"); // 缩略图 if (StringUtil.notNull(thumbnail)) { map.put("thumbnail", normalizeThumbnailURL(thumbnail.toString())); } } } private static String normalizeThumbnailURL(String thumbnail) { if (thumbnail == null) { return thumbnail; } String value = thumbnail.trim(); if (value.length() == 0) { return value; } int uploadPathIndex = value.indexOf("/web/upload/"); if (uploadPathIndex >= 0) { return normalizeLocalPath(value.substring(uploadPathIndex)); } if (value.startsWith("http://") || value.startsWith("https://") || value.startsWith("//")) { return value; } return normalizeLocalPath(value.startsWith("/") ? value : "/" + value); } private static String normalizeLocalPath(String path) { return path.replaceAll("/{2,}", "/"); } }