From c68b83cebf0d9aa30803e68d61ff899e9db9848c Mon Sep 17 00:00:00 2001 From: Koda Date: Sat, 1 Aug 2015 04:24:32 +0900 Subject: [PATCH] =?UTF-8?q?=E3=83=9E=E3=83=BC=E3=82=AF=E3=83=80=E3=82=A6?= =?UTF-8?q?=E3=83=B3=E3=81=AE=E3=83=91=E3=83=BC=E3=82=B9=E5=87=A6=E7=90=86?= =?UTF-8?q?=E3=81=A7=E3=82=A8=E3=83=A9=E3=83=BC=E3=81=8C=E7=99=BA=E7=94=9F?= =?UTF-8?q?=E3=81=99=E3=82=8B=E4=BA=8B=E3=81=8C=E3=81=82=E3=82=8B=20#77=20?= =?UTF-8?q?IE11=E3=81=A7=E6=B7=BB=E4=BB=98=E3=83=95=E3=82=A1=E3=82=A4?= =?UTF-8?q?=E3=83=AB=EF=BC=88=E6=97=A5=E6=9C=AC=E8=AA=9E=EF=BC=89=E3=81=AE?= =?UTF-8?q?=E3=83=95=E3=82=A1=E3=82=A4=E3=83=AB=E5=90=8D=E3=81=8C=E6=96=87?= =?UTF-8?q?=E5=AD=97=E5=8C=96=E3=81=91=E3=81=99=E3=82=8B=20#58=20=E3=82=BF?= =?UTF-8?q?=E3=82=B0=E3=81=8C=E6=95=B0=E6=96=87=E5=AD=97=E3=81=A7=E3=82=B9?= =?UTF-8?q?=E3=82=AF=E3=83=AD=E3=83=BC=E3=83=AB=E3=81=97=E3=81=A6=E6=B6=88?= =?UTF-8?q?=E3=81=88=E3=81=A6=E3=81=97=E3=81=BE=E3=81=86=20#74?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- pom.xml | 8 +- .../control/open/KnowledgeControl.java | 16 +- .../project/knowledge/logic/GroupLogic.java | 3 +- .../knowledge/logic/MarkdownLogic.java | 152 +- .../project/knowledge/vo/MarkDown.java | 53 + src/main/resources/appresource.properties | 2 +- src/main/resources/appresource_ja.properties | 2 +- src/main/resources/log4j.xml | 2 +- .../support/project/knowledge/logic/marked.js | 1266 +++++++++++++++++ .../views/protect/knowledge/view_add.jsp | 2 +- .../views/protect/knowledge/view_edit.jsp | 2 +- src/main/webapp/css/knowledge-edit.css | 3 + .../knowledge/logic/MarkdownLogicTest.java | 55 +- .../knowledge/logic/markdown/markdown-6-2.md | 40 + .../knowledge/logic/markdown/markdown-6.md | 33 + .../knowledge/logic/markdown/result-6-2.txt | 21 + .../knowledge/logic/markdown/result-6.txt | 17 + 17 files changed, 1649 insertions(+), 28 deletions(-) create mode 100644 src/main/java/org/support/project/knowledge/vo/MarkDown.java create mode 100644 src/main/resources/org/support/project/knowledge/logic/marked.js create mode 100644 src/test/resources/org/support/project/knowledge/logic/markdown/markdown-6-2.md create mode 100644 src/test/resources/org/support/project/knowledge/logic/markdown/markdown-6.md create mode 100644 src/test/resources/org/support/project/knowledge/logic/markdown/result-6-2.txt create mode 100644 src/test/resources/org/support/project/knowledge/logic/markdown/result-6.txt diff --git a/pom.xml b/pom.xml index 12d7f16ff..327e1420d 100644 --- a/pom.xml +++ b/pom.xml @@ -78,7 +78,13 @@ org.apache.tika tika-parsers - 1.6 + 1.9 + + + org.ow2.asm + asm-debug-all + + diff --git a/src/main/java/org/support/project/knowledge/control/open/KnowledgeControl.java b/src/main/java/org/support/project/knowledge/control/open/KnowledgeControl.java index 3ebd3d30f..bb87e0be5 100644 --- a/src/main/java/org/support/project/knowledge/control/open/KnowledgeControl.java +++ b/src/main/java/org/support/project/knowledge/control/open/KnowledgeControl.java @@ -28,6 +28,7 @@ import org.support.project.knowledge.logic.TargetLogic; import org.support.project.knowledge.logic.UploadedFileLogic; import org.support.project.knowledge.vo.LikeCount; +import org.support.project.knowledge.vo.MarkDown; import org.support.project.knowledge.vo.UploadFile; import org.support.project.web.bean.LabelValue; import org.support.project.web.bean.LoginedUser; @@ -104,7 +105,8 @@ public Boundary view() throws InvalidParamException, ParseException { } //Markdownを処理 entity.setTitle(sanitize(entity.getTitle())); - entity.setContent(MarkdownLogic.get().markdownToHtml(entity.getContent())); + MarkDown markDown = MarkdownLogic.get().markdownToHtml(entity.getContent()); + entity.setContent(markDown.getHtml()); setAttributeOnProperty(entity); @@ -132,7 +134,8 @@ public Boundary view() throws InvalidParamException, ParseException { List comments = commentsDao.selectOnKnowledgeId(knowledgeId); // Markdown を処理 for (CommentsEntity commentsEntity : comments) { - commentsEntity.setComment(MarkdownLogic.get().markdownToHtml(commentsEntity.getComment())); + MarkDown markDown2 = MarkdownLogic.get().markdownToHtml(commentsEntity.getComment()); + commentsEntity.setComment(markDown2.getHtml()); } setAttribute("comments", comments); @@ -186,8 +189,10 @@ public Boundary list() throws Exception { int userId = Integer.parseInt(user); knowledges.addAll(knowledgeLogic.showKnowledgeOnUser(userId, loginedUser, offset * PAGE_LIMIT, PAGE_LIMIT)); UsersEntity usersEntity = UsersDao.get().selectOnKey(userId); - usersEntity.setPassword(""); - setAttribute("selectedUser", usersEntity); + if (user != null) { + usersEntity.setPassword(""); + setAttribute("selectedUser", usersEntity); + } } else if (StringUtils.isNotEmpty(tagNames)) { // タグとキーワードで検索 LOG.trace("show on Tags and keyword"); @@ -313,7 +318,8 @@ public Boundary escape(KnowledgesEntity entity) throws ParseException { public Boundary marked(KnowledgesEntity entity) throws ParseException { super.setSendEscapeHtml(false); entity.setTitle(sanitize(entity.getTitle())); - entity.setContent(MarkdownLogic.get().markdownToHtml(entity.getContent())); + MarkDown markDown = MarkdownLogic.get().markdownToHtml(entity.getContent()); + entity.setContent(markDown.getHtml()); return super.send(entity); } diff --git a/src/main/java/org/support/project/knowledge/logic/GroupLogic.java b/src/main/java/org/support/project/knowledge/logic/GroupLogic.java index a7ca19747..16292962f 100644 --- a/src/main/java/org/support/project/knowledge/logic/GroupLogic.java +++ b/src/main/java/org/support/project/knowledge/logic/GroupLogic.java @@ -3,7 +3,6 @@ import java.util.ArrayList; import java.util.List; -import org.apache.commons.httpclient.HttpStatus; import org.support.project.aop.Aspect; import org.support.project.common.log.Log; import org.support.project.common.log.LogFactory; @@ -281,7 +280,7 @@ public MessageResult addUsers(LoginedUser loginedUser, Integer groupId, String u if (groupsDao.selectAccessAbleGroup(groupId, loginedUser) == null) { MessageResult messageResult = new MessageResult(); messageResult.setStatus(MessageStatus.Error.getValue()); - messageResult.setCode(HttpStatus.SC_FORBIDDEN); + messageResult.setCode(org.support.project.web.common.HttpStatus.SC_403_FORBIDDEN); return messageResult; // アクセス権がないユーザ } } diff --git a/src/main/java/org/support/project/knowledge/logic/MarkdownLogic.java b/src/main/java/org/support/project/knowledge/logic/MarkdownLogic.java index 07ad8a2e1..4f8e62171 100644 --- a/src/main/java/org/support/project/knowledge/logic/MarkdownLogic.java +++ b/src/main/java/org/support/project/knowledge/logic/MarkdownLogic.java @@ -1,5 +1,15 @@ package org.support.project.knowledge.logic; +import java.io.IOException; +import java.io.InputStreamReader; +import java.io.Reader; +import java.nio.charset.Charset; +import java.util.Date; + +import javax.script.ScriptEngine; +import javax.script.ScriptEngineManager; +import javax.script.ScriptException; + import org.pegdown.Extensions; import org.pegdown.LinkRenderer; import org.pegdown.PegDownProcessor; @@ -10,39 +20,161 @@ import org.support.project.di.Container; import org.support.project.di.DI; import org.support.project.di.Instance; +import org.support.project.knowledge.vo.MarkDown; import org.support.project.web.logic.SanitizingLogic; -@DI(instance=Instance.Singleton) +@DI(instance = Instance.Singleton) public class MarkdownLogic { /** ログ */ private static Log LOG = LogFactory.getLog(MarkdownLogic.class); + + public static final int ENGINE_PEGDOWN = 1; + public static final int ENGINE_MARKEDJS = 2; + + private ScriptEngine engine = null; + private boolean initEngine = false; + public static MarkdownLogic get() { return Container.getComp(MarkdownLogic.class); } - public String markdownToHtml(String markdown) throws ParseException { + /** + * マークダウンをパースしてHTMLを取得 + * @param markdown + * @return + * @throws ParseException + */ + public MarkDown markdownToHtml(String markdown) throws ParseException { + return markdownToHtml(markdown, ENGINE_PEGDOWN); + } + /** + * マークダウンをパースしてHTMLを取得(エンジンを指定) + * @param markdown + * @param engine + * @return + * @throws ParseException + */ + public MarkDown markdownToHtml(String markdown, int engine) throws ParseException { + MarkDown result = new MarkDown(); + if (engine == ENGINE_MARKEDJS) { + markdownToHtmlOnMarkedJs(markdown, result); + } else { + markdownToHtmlOnPegDown(markdown, result); + } + return sanitize(markdown, result); + } + + + /** + * サニタイジング + * @param markdown + * @param result + * @return + * @throws ParseException + */ + private MarkDown sanitize(String markdown, MarkDown result) throws ParseException { + try { + String html = result.getHtml(); + if (LOG.isDebugEnabled()) { + LOG.debug("[Markdown] : " + markdown); + LOG.debug("[ParsedHtml] : " + html); + } + // 危険なHTMLは削除 + html = SanitizingLogic.get().sanitize(html); + if (LOG.isDebugEnabled()) { + LOG.debug("[SanitizeHtml] : " + html); + } + result.setHtml(html); + return result; + } catch (Exception e) { + // サニタイズではエラーにならないはず + throw new ParseException(e); + } + } + + /** + * PegDownでMarkDownのパース + * @param markdown + * @param result + */ + private void markdownToHtmlOnPegDown(String markdown, MarkDown result) { + Date start = new Date(); + result.setMarkdown(markdown); + String html = markdown; try { // Markdownのパース PegDownProcessor processor = new PegDownProcessor(Extensions.ALL - Extensions.ANCHORLINKS); - String html = processor.markdownToHtml(markdown, new LinkRenderer() { + html = processor.markdownToHtml(markdown, new LinkRenderer() { @Override public Rendering render(AnchorLinkNode node) { return new Rendering(node.getText(), node.getText()); } }); + result.setHtml(html); + result.setParsed(true); if (LOG.isDebugEnabled()) { - LOG.debug("[Markdown] : " + markdown); - LOG.debug("[ParsedHtml] : " + html); + Date end = new Date(); + LOG.debug("Parse time (PegDown): " + (end.getTime() - start.getTime()) + " [ms]"); } - // 危険なHTMLは削除 - html = SanitizingLogic.get().sanitize(html); + } catch (Exception e) { + // Markdownのパースに失敗する事がある + LOG.error("Markdown parse error.", e); + // PegDownをデフォルトとして、失敗した場合、Marked.jsでパースしてみる + markdownToHtmlOnMarkedJs(markdown, result); + } + } + + private ScriptEngine getScriptEngine() throws ScriptException, IOException { + if (initEngine) { + return engine; + } + ScriptEngineManager manager = new ScriptEngineManager(); + engine = manager.getEngineByName("js"); + if (engine == null) { + System.out.println("JavaScriptはサポート外"); + initEngine = true; + return null; + } + Reader fr = null; + try { + fr = new InputStreamReader(this.getClass().getResourceAsStream("/org/support/project/knowledge/logic/marked.js"), Charset.forName("UTF-8")); + engine.eval(fr); + initEngine = true; + return engine; + } finally { + if (fr != null) { + fr.close(); + } + } + } + + + /** + * marked.jsでMarkDownのパース + * @param markdown + * @param result + */ + private void markdownToHtmlOnMarkedJs(String markdown, MarkDown result) { + Date start = new Date(); + result.setMarkdown(markdown); + String html = markdown; + try { + engine = getScriptEngine(); + if (engine == null) { + return; + } + engine.put("content", markdown); + html = (String) engine.eval("marked(content)"); + result.setHtml(html); + result.setParsed(true); if (LOG.isDebugEnabled()) { - LOG.debug("[SanitizeHtml] : " + html); + Date end = new Date(); + LOG.debug("Parse time (marked.js): " + (end.getTime() - start.getTime()) + " [ms]"); } - return html; } catch (Exception e) { - throw new ParseException(e); + LOG.error("Markdown parse error.", e); } } + } diff --git a/src/main/java/org/support/project/knowledge/vo/MarkDown.java b/src/main/java/org/support/project/knowledge/vo/MarkDown.java new file mode 100644 index 000000000..13315bea5 --- /dev/null +++ b/src/main/java/org/support/project/knowledge/vo/MarkDown.java @@ -0,0 +1,53 @@ +package org.support.project.knowledge.vo; + +public class MarkDown { + + private String markdown; + + private String html; + + private boolean parsed = false; + + /** + * @return the markdown + */ + public String getMarkdown() { + return markdown; + } + + /** + * @param markdown the markdown to set + */ + public void setMarkdown(String markdown) { + this.markdown = markdown; + } + + /** + * @return the html + */ + public String getHtml() { + return html; + } + + /** + * @param html the html to set + */ + public void setHtml(String html) { + this.html = html; + } + + /** + * @return the parsed + */ + public boolean isParsed() { + return parsed; + } + + /** + * @param parsed the parsed to set + */ + public void setParsed(boolean parsed) { + this.parsed = parsed; + } + +} diff --git a/src/main/resources/appresource.properties b/src/main/resources/appresource.properties index 3e0742808..7451c75d1 100644 --- a/src/main/resources/appresource.properties +++ b/src/main/resources/appresource.properties @@ -53,7 +53,7 @@ message.allready.updated=Allready updated. message.allready.started=Allready started. # Common Label -label.version=0.5.3 pre3 +label.version=0.5.3 pre4 label.login=Sign in label.previous = Previous label.next=Next diff --git a/src/main/resources/appresource_ja.properties b/src/main/resources/appresource_ja.properties index d570e1e83..6536e20e7 100644 --- a/src/main/resources/appresource_ja.properties +++ b/src/main/resources/appresource_ja.properties @@ -53,7 +53,7 @@ message.allready.updated=すでに更新されています message.allready.started=すでに開始済です # Common Label -label.version=0.5.3 pre3 +label.version=0.5.3 pre4 label.login=サインイン label.previous = 前へ label.next = 次へ diff --git a/src/main/resources/log4j.xml b/src/main/resources/log4j.xml index 5de90db80..f7fc043fa 100644 --- a/src/main/resources/log4j.xml +++ b/src/main/resources/log4j.xml @@ -43,7 +43,7 @@ - + diff --git a/src/main/resources/org/support/project/knowledge/logic/marked.js b/src/main/resources/org/support/project/knowledge/logic/marked.js new file mode 100644 index 000000000..e2f08c998 --- /dev/null +++ b/src/main/resources/org/support/project/knowledge/logic/marked.js @@ -0,0 +1,1266 @@ +/** + * marked - a markdown parser + * Copyright (c) 2011-2014, Christopher Jeffrey. (MIT Licensed) + * https://github.com/chjj/marked + */ + +;(function() { + +/** + * Block-Level Grammar + */ + +var block = { + newline: /^\n+/, + code: /^( {4}[^\n]+\n*)+/, + fences: noop, + hr: /^( *[-*_]){3,} *(?:\n+|$)/, + heading: /^ *(#{1,6}) *([^\n]+?) *#* *(?:\n+|$)/, + nptable: noop, + lheading: /^([^\n]+)\n *(=|-){2,} *(?:\n+|$)/, + blockquote: /^( *>[^\n]+(\n(?!def)[^\n]+)*\n*)+/, + list: /^( *)(bull) [\s\S]+?(?:hr|def|\n{2,}(?! )(?!\1bull )\n*|\s*$)/, + html: /^ *(?:comment|closed|closing) *(?:\n{2,}|\s*$)/, + def: /^ *\[([^\]]+)\]: *]+)>?(?: +["(]([^\n]+)[")])? *(?:\n+|$)/, + table: noop, + paragraph: /^((?:[^\n]+\n?(?!hr|heading|lheading|blockquote|tag|def))+)\n*/, + text: /^[^\n]+/ +}; + +block.bullet = /(?:[*+-]|\d+\.)/; +block.item = /^( *)(bull) [^\n]*(?:\n(?!\1bull )[^\n]*)*/; +block.item = replace(block.item, 'gm') + (/bull/g, block.bullet) + (); + +block.list = replace(block.list) + (/bull/g, block.bullet) + ('hr', '\\n+(?=\\1?(?:[-*_] *){3,}(?:\\n+|$))') + ('def', '\\n+(?=' + block.def.source + ')') + (); + +block.blockquote = replace(block.blockquote) + ('def', block.def) + (); + +block._tag = '(?!(?:' + + 'a|em|strong|small|s|cite|q|dfn|abbr|data|time|code' + + '|var|samp|kbd|sub|sup|i|b|u|mark|ruby|rt|rp|bdi|bdo' + + '|span|br|wbr|ins|del|img)\\b)\\w+(?!:/|[^\\w\\s@]*@)\\b'; + +block.html = replace(block.html) + ('comment', //) + ('closed', /<(tag)[\s\S]+?<\/\1>/) + ('closing', /])*?>/) + (/tag/g, block._tag) + (); + +block.paragraph = replace(block.paragraph) + ('hr', block.hr) + ('heading', block.heading) + ('lheading', block.lheading) + ('blockquote', block.blockquote) + ('tag', '<' + block._tag) + ('def', block.def) + (); + +/** + * Normal Block Grammar + */ + +block.normal = merge({}, block); + +/** + * GFM Block Grammar + */ + +block.gfm = merge({}, block.normal, { + fences: /^ *(`{3,}|~{3,}) *(\S+)? *\n([\s\S]+?)\s*\1 *(?:\n+|$)/, + paragraph: /^/ +}); + +block.gfm.paragraph = replace(block.paragraph) + ('(?!', '(?!' + + block.gfm.fences.source.replace('\\1', '\\2') + '|' + + block.list.source.replace('\\1', '\\3') + '|') + (); + +/** + * GFM + Tables Block Grammar + */ + +block.tables = merge({}, block.gfm, { + nptable: /^ *(\S.*\|.*)\n *([-:]+ *\|[-| :]*)\n((?:.*\|.*(?:\n|$))*)\n*/, + table: /^ *\|(.+)\n *\|( *[-:]+[-| :]*)\n((?: *\|.*(?:\n|$))*)\n*/ +}); + +/** + * Block Lexer + */ + +function Lexer(options) { + this.tokens = []; + this.tokens.links = {}; + this.options = options || marked.defaults; + this.rules = block.normal; + + if (this.options.gfm) { + if (this.options.tables) { + this.rules = block.tables; + } else { + this.rules = block.gfm; + } + } +} + +/** + * Expose Block Rules + */ + +Lexer.rules = block; + +/** + * Static Lex Method + */ + +Lexer.lex = function(src, options) { + var lexer = new Lexer(options); + return lexer.lex(src); +}; + +/** + * Preprocessing + */ + +Lexer.prototype.lex = function(src) { + src = src + .replace(/\r\n|\r/g, '\n') + .replace(/\t/g, ' ') + .replace(/\u00a0/g, ' ') + .replace(/\u2424/g, '\n'); + + return this.token(src, true); +}; + +/** + * Lexing + */ + +Lexer.prototype.token = function(src, top, bq) { + var src = src.replace(/^ +$/gm, '') + , next + , loose + , cap + , bull + , b + , item + , space + , i + , l; + + while (src) { + // newline + if (cap = this.rules.newline.exec(src)) { + src = src.substring(cap[0].length); + if (cap[0].length > 1) { + this.tokens.push({ + type: 'space' + }); + } + } + + // code + if (cap = this.rules.code.exec(src)) { + src = src.substring(cap[0].length); + cap = cap[0].replace(/^ {4}/gm, ''); + this.tokens.push({ + type: 'code', + text: !this.options.pedantic + ? cap.replace(/\n+$/, '') + : cap + }); + continue; + } + + // fences (gfm) + if (cap = this.rules.fences.exec(src)) { + src = src.substring(cap[0].length); + this.tokens.push({ + type: 'code', + lang: cap[2], + text: cap[3] + }); + continue; + } + + // heading + if (cap = this.rules.heading.exec(src)) { + src = src.substring(cap[0].length); + this.tokens.push({ + type: 'heading', + depth: cap[1].length, + text: cap[2] + }); + continue; + } + + // table no leading pipe (gfm) + if (top && (cap = this.rules.nptable.exec(src))) { + src = src.substring(cap[0].length); + + item = { + type: 'table', + header: cap[1].replace(/^ *| *\| *$/g, '').split(/ *\| */), + align: cap[2].replace(/^ *|\| *$/g, '').split(/ *\| */), + cells: cap[3].replace(/\n$/, '').split('\n') + }; + + for (i = 0; i < item.align.length; i++) { + if (/^ *-+: *$/.test(item.align[i])) { + item.align[i] = 'right'; + } else if (/^ *:-+: *$/.test(item.align[i])) { + item.align[i] = 'center'; + } else if (/^ *:-+ *$/.test(item.align[i])) { + item.align[i] = 'left'; + } else { + item.align[i] = null; + } + } + + for (i = 0; i < item.cells.length; i++) { + item.cells[i] = item.cells[i].split(/ *\| */); + } + + this.tokens.push(item); + + continue; + } + + // lheading + if (cap = this.rules.lheading.exec(src)) { + src = src.substring(cap[0].length); + this.tokens.push({ + type: 'heading', + depth: cap[2] === '=' ? 1 : 2, + text: cap[1] + }); + continue; + } + + // hr + if (cap = this.rules.hr.exec(src)) { + src = src.substring(cap[0].length); + this.tokens.push({ + type: 'hr' + }); + continue; + } + + // blockquote + if (cap = this.rules.blockquote.exec(src)) { + src = src.substring(cap[0].length); + + this.tokens.push({ + type: 'blockquote_start' + }); + + cap = cap[0].replace(/^ *> ?/gm, ''); + + // Pass `top` to keep the current + // "toplevel" state. This is exactly + // how markdown.pl works. + this.token(cap, top, true); + + this.tokens.push({ + type: 'blockquote_end' + }); + + continue; + } + + // list + if (cap = this.rules.list.exec(src)) { + src = src.substring(cap[0].length); + bull = cap[2]; + + this.tokens.push({ + type: 'list_start', + ordered: bull.length > 1 + }); + + // Get each top-level item. + cap = cap[0].match(this.rules.item); + + next = false; + l = cap.length; + i = 0; + + for (; i < l; i++) { + item = cap[i]; + + // Remove the list item's bullet + // so it is seen as the next token. + space = item.length; + item = item.replace(/^ *([*+-]|\d+\.) +/, ''); + + // Outdent whatever the + // list item contains. Hacky. + if (~item.indexOf('\n ')) { + space -= item.length; + item = !this.options.pedantic + ? item.replace(new RegExp('^ {1,' + space + '}', 'gm'), '') + : item.replace(/^ {1,4}/gm, ''); + } + + // Determine whether the next list item belongs here. + // Backpedal if it does not belong in this list. + if (this.options.smartLists && i !== l - 1) { + b = block.bullet.exec(cap[i + 1])[0]; + if (bull !== b && !(bull.length > 1 && b.length > 1)) { + src = cap.slice(i + 1).join('\n') + src; + i = l - 1; + } + } + + // Determine whether item is loose or not. + // Use: /(^|\n)(?! )[^\n]+\n\n(?!\s*$)/ + // for discount behavior. + loose = next || /\n\n(?!\s*$)/.test(item); + if (i !== l - 1) { + next = item.charAt(item.length - 1) === '\n'; + if (!loose) loose = next; + } + + this.tokens.push({ + type: loose + ? 'loose_item_start' + : 'list_item_start' + }); + + // Recurse. + this.token(item, false, bq); + + this.tokens.push({ + type: 'list_item_end' + }); + } + + this.tokens.push({ + type: 'list_end' + }); + + continue; + } + + // html + if (cap = this.rules.html.exec(src)) { + src = src.substring(cap[0].length); + this.tokens.push({ + type: this.options.sanitize + ? 'paragraph' + : 'html', + pre: cap[1] === 'pre' || cap[1] === 'script' || cap[1] === 'style', + text: cap[0] + }); + continue; + } + + // def + if ((!bq && top) && (cap = this.rules.def.exec(src))) { + src = src.substring(cap[0].length); + this.tokens.links[cap[1].toLowerCase()] = { + href: cap[2], + title: cap[3] + }; + continue; + } + + // table (gfm) + if (top && (cap = this.rules.table.exec(src))) { + src = src.substring(cap[0].length); + + item = { + type: 'table', + header: cap[1].replace(/^ *| *\| *$/g, '').split(/ *\| */), + align: cap[2].replace(/^ *|\| *$/g, '').split(/ *\| */), + cells: cap[3].replace(/(?: *\| *)?\n$/, '').split('\n') + }; + + for (i = 0; i < item.align.length; i++) { + if (/^ *-+: *$/.test(item.align[i])) { + item.align[i] = 'right'; + } else if (/^ *:-+: *$/.test(item.align[i])) { + item.align[i] = 'center'; + } else if (/^ *:-+ *$/.test(item.align[i])) { + item.align[i] = 'left'; + } else { + item.align[i] = null; + } + } + + for (i = 0; i < item.cells.length; i++) { + item.cells[i] = item.cells[i] + .replace(/^ *\| *| *\| *$/g, '') + .split(/ *\| */); + } + + this.tokens.push(item); + + continue; + } + + // top-level paragraph + if (top && (cap = this.rules.paragraph.exec(src))) { + src = src.substring(cap[0].length); + this.tokens.push({ + type: 'paragraph', + text: cap[1].charAt(cap[1].length - 1) === '\n' + ? cap[1].slice(0, -1) + : cap[1] + }); + continue; + } + + // text + if (cap = this.rules.text.exec(src)) { + // Top-level should never reach here. + src = src.substring(cap[0].length); + this.tokens.push({ + type: 'text', + text: cap[0] + }); + continue; + } + + if (src) { + throw new + Error('Infinite loop on byte: ' + src.charCodeAt(0)); + } + } + + return this.tokens; +}; + +/** + * Inline-Level Grammar + */ + +var inline = { + escape: /^\\([\\`*{}\[\]()#+\-.!_>])/, + autolink: /^<([^ >]+(@|:\/)[^ >]+)>/, + url: noop, + tag: /^|^<\/?\w+(?:"[^"]*"|'[^']*'|[^'">])*?>/, + link: /^!?\[(inside)\]\(href\)/, + reflink: /^!?\[(inside)\]\s*\[([^\]]*)\]/, + nolink: /^!?\[((?:\[[^\]]*\]|[^\[\]])*)\]/, + strong: /^__([\s\S]+?)__(?!_)|^\*\*([\s\S]+?)\*\*(?!\*)/, + em: /^\b_((?:__|[\s\S])+?)_\b|^\*((?:\*\*|[\s\S])+?)\*(?!\*)/, + code: /^(`+)\s*([\s\S]*?[^`])\s*\1(?!`)/, + br: /^ {2,}\n(?!\s*$)/, + del: noop, + text: /^[\s\S]+?(?=[\\?(?:\s+['"]([\s\S]*?)['"])?\s*/; + +inline.link = replace(inline.link) + ('inside', inline._inside) + ('href', inline._href) + (); + +inline.reflink = replace(inline.reflink) + ('inside', inline._inside) + (); + +/** + * Normal Inline Grammar + */ + +inline.normal = merge({}, inline); + +/** + * Pedantic Inline Grammar + */ + +inline.pedantic = merge({}, inline.normal, { + strong: /^__(?=\S)([\s\S]*?\S)__(?!_)|^\*\*(?=\S)([\s\S]*?\S)\*\*(?!\*)/, + em: /^_(?=\S)([\s\S]*?\S)_(?!_)|^\*(?=\S)([\s\S]*?\S)\*(?!\*)/ +}); + +/** + * GFM Inline Grammar + */ + +inline.gfm = merge({}, inline.normal, { + escape: replace(inline.escape)('])', '~|])')(), + url: /^(https?:\/\/[^\s<]+[^<.,:;"')\]\s])/, + del: /^~~(?=\S)([\s\S]*?\S)~~/, + text: replace(inline.text) + (']|', '~]|') + ('|', '|https?://|') + () +}); + +/** + * GFM + Line Breaks Inline Grammar + */ + +inline.breaks = merge({}, inline.gfm, { + br: replace(inline.br)('{2,}', '*')(), + text: replace(inline.gfm.text)('{2,}', '*')() +}); + +/** + * Inline Lexer & Compiler + */ + +function InlineLexer(links, options) { + this.options = options || marked.defaults; + this.links = links; + this.rules = inline.normal; + this.renderer = this.options.renderer || new Renderer; + this.renderer.options = this.options; + + if (!this.links) { + throw new + Error('Tokens array requires a `links` property.'); + } + + if (this.options.gfm) { + if (this.options.breaks) { + this.rules = inline.breaks; + } else { + this.rules = inline.gfm; + } + } else if (this.options.pedantic) { + this.rules = inline.pedantic; + } +} + +/** + * Expose Inline Rules + */ + +InlineLexer.rules = inline; + +/** + * Static Lexing/Compiling Method + */ + +InlineLexer.output = function(src, links, options) { + var inline = new InlineLexer(links, options); + return inline.output(src); +}; + +/** + * Lexing/Compiling + */ + +InlineLexer.prototype.output = function(src) { + var out = '' + , link + , text + , href + , cap; + + while (src) { + // escape + if (cap = this.rules.escape.exec(src)) { + src = src.substring(cap[0].length); + out += cap[1]; + continue; + } + + // autolink + if (cap = this.rules.autolink.exec(src)) { + src = src.substring(cap[0].length); + if (cap[2] === '@') { + text = cap[1].charAt(6) === ':' + ? this.mangle(cap[1].substring(7)) + : this.mangle(cap[1]); + href = this.mangle('mailto:') + text; + } else { + text = escape(cap[1]); + href = text; + } + out += this.renderer.link(href, null, text); + continue; + } + + // url (gfm) + if (!this.inLink && (cap = this.rules.url.exec(src))) { + src = src.substring(cap[0].length); + text = escape(cap[1]); + href = text; + out += this.renderer.link(href, null, text); + continue; + } + + // tag + if (cap = this.rules.tag.exec(src)) { + if (!this.inLink && /^/i.test(cap[0])) { + this.inLink = false; + } + src = src.substring(cap[0].length); + out += this.options.sanitize + ? escape(cap[0]) + : cap[0]; + continue; + } + + // link + if (cap = this.rules.link.exec(src)) { + src = src.substring(cap[0].length); + this.inLink = true; + out += this.outputLink(cap, { + href: cap[2], + title: cap[3] + }); + this.inLink = false; + continue; + } + + // reflink, nolink + if ((cap = this.rules.reflink.exec(src)) + || (cap = this.rules.nolink.exec(src))) { + src = src.substring(cap[0].length); + link = (cap[2] || cap[1]).replace(/\s+/g, ' '); + link = this.links[link.toLowerCase()]; + if (!link || !link.href) { + out += cap[0].charAt(0); + src = cap[0].substring(1) + src; + continue; + } + this.inLink = true; + out += this.outputLink(cap, link); + this.inLink = false; + continue; + } + + // strong + if (cap = this.rules.strong.exec(src)) { + src = src.substring(cap[0].length); + out += this.renderer.strong(this.output(cap[2] || cap[1])); + continue; + } + + // em + if (cap = this.rules.em.exec(src)) { + src = src.substring(cap[0].length); + out += this.renderer.em(this.output(cap[2] || cap[1])); + continue; + } + + // code + if (cap = this.rules.code.exec(src)) { + src = src.substring(cap[0].length); + out += this.renderer.codespan(escape(cap[2], true)); + continue; + } + + // br + if (cap = this.rules.br.exec(src)) { + src = src.substring(cap[0].length); + out += this.renderer.br(); + continue; + } + + // del (gfm) + if (cap = this.rules.del.exec(src)) { + src = src.substring(cap[0].length); + out += this.renderer.del(this.output(cap[1])); + continue; + } + + // text + if (cap = this.rules.text.exec(src)) { + src = src.substring(cap[0].length); + out += escape(this.smartypants(cap[0])); + continue; + } + + if (src) { + throw new + Error('Infinite loop on byte: ' + src.charCodeAt(0)); + } + } + + return out; +}; + +/** + * Compile Link + */ + +InlineLexer.prototype.outputLink = function(cap, link) { + var href = escape(link.href) + , title = link.title ? escape(link.title) : null; + + return cap[0].charAt(0) !== '!' + ? this.renderer.link(href, title, this.output(cap[1])) + : this.renderer.image(href, title, escape(cap[1])); +}; + +/** + * Smartypants Transformations + */ + +InlineLexer.prototype.smartypants = function(text) { + if (!this.options.smartypants) return text; + return text + // em-dashes + .replace(/--/g, '\u2014') + // opening singles + .replace(/(^|[-\u2014/(\[{"\s])'/g, '$1\u2018') + // closing singles & apostrophes + .replace(/'/g, '\u2019') + // opening doubles + .replace(/(^|[-\u2014/(\[{\u2018\s])"/g, '$1\u201c') + // closing doubles + .replace(/"/g, '\u201d') + // ellipses + .replace(/\.{3}/g, '\u2026'); +}; + +/** + * Mangle Links + */ + +InlineLexer.prototype.mangle = function(text) { + var out = '' + , l = text.length + , i = 0 + , ch; + + for (; i < l; i++) { + ch = text.charCodeAt(i); + if (Math.random() > 0.5) { + ch = 'x' + ch.toString(16); + } + out += '&#' + ch + ';'; + } + + return out; +}; + +/** + * Renderer + */ + +function Renderer(options) { + this.options = options || {}; +} + +Renderer.prototype.code = function(code, lang, escaped) { + if (this.options.highlight) { + var out = this.options.highlight(code, lang); + if (out != null && out !== code) { + escaped = true; + code = out; + } + } + + if (!lang) { + return '
'
+      + (escaped ? code : escape(code, true))
+      + '\n
'; + } + + return '
'
+    + (escaped ? code : escape(code, true))
+    + '\n
\n'; +}; + +Renderer.prototype.blockquote = function(quote) { + return '
\n' + quote + '
\n'; +}; + +Renderer.prototype.html = function(html) { + return html; +}; + +Renderer.prototype.heading = function(text, level, raw) { + return '' + + text + + '\n'; +}; + +Renderer.prototype.hr = function() { + return this.options.xhtml ? '
\n' : '
\n'; +}; + +Renderer.prototype.list = function(body, ordered) { + var type = ordered ? 'ol' : 'ul'; + return '<' + type + '>\n' + body + '\n'; +}; + +Renderer.prototype.listitem = function(text) { + return '
  • ' + text + '
  • \n'; +}; + +Renderer.prototype.paragraph = function(text) { + return '

    ' + text + '

    \n'; +}; + +Renderer.prototype.table = function(header, body) { + return '\n' + + '\n' + + header + + '\n' + + '\n' + + body + + '\n' + + '
    \n'; +}; + +Renderer.prototype.tablerow = function(content) { + return '\n' + content + '\n'; +}; + +Renderer.prototype.tablecell = function(content, flags) { + var type = flags.header ? 'th' : 'td'; + var tag = flags.align + ? '<' + type + ' style="text-align:' + flags.align + '">' + : '<' + type + '>'; + return tag + content + '\n'; +}; + +// span level renderer +Renderer.prototype.strong = function(text) { + return '' + text + ''; +}; + +Renderer.prototype.em = function(text) { + return '' + text + ''; +}; + +Renderer.prototype.codespan = function(text) { + return '' + text + ''; +}; + +Renderer.prototype.br = function() { + return this.options.xhtml ? '
    ' : '
    '; +}; + +Renderer.prototype.del = function(text) { + return '' + text + ''; +}; + +Renderer.prototype.link = function(href, title, text) { + if (this.options.sanitize) { + try { + var prot = decodeURIComponent(unescape(href)) + .replace(/[^\w:]/g, '') + .toLowerCase(); + } catch (e) { + return ''; + } + if (prot.indexOf('javascript:') === 0) { + return ''; + } + } + var out = '
    '; + return out; +}; + +Renderer.prototype.image = function(href, title, text) { + var out = '' + text + '' : '>'; + return out; +}; + +/** + * Parsing & Compiling + */ + +function Parser(options) { + this.tokens = []; + this.token = null; + this.options = options || marked.defaults; + this.options.renderer = this.options.renderer || new Renderer; + this.renderer = this.options.renderer; + this.renderer.options = this.options; +} + +/** + * Static Parse Method + */ + +Parser.parse = function(src, options, renderer) { + var parser = new Parser(options, renderer); + return parser.parse(src); +}; + +/** + * Parse Loop + */ + +Parser.prototype.parse = function(src) { + this.inline = new InlineLexer(src.links, this.options, this.renderer); + this.tokens = src.reverse(); + + var out = ''; + while (this.next()) { + out += this.tok(); + } + + return out; +}; + +/** + * Next Token + */ + +Parser.prototype.next = function() { + return this.token = this.tokens.pop(); +}; + +/** + * Preview Next Token + */ + +Parser.prototype.peek = function() { + return this.tokens[this.tokens.length - 1] || 0; +}; + +/** + * Parse Text Tokens + */ + +Parser.prototype.parseText = function() { + var body = this.token.text; + + while (this.peek().type === 'text') { + body += '\n' + this.next().text; + } + + return this.inline.output(body); +}; + +/** + * Parse Current Token + */ + +Parser.prototype.tok = function() { + switch (this.token.type) { + case 'space': { + return ''; + } + case 'hr': { + return this.renderer.hr(); + } + case 'heading': { + return this.renderer.heading( + this.inline.output(this.token.text), + this.token.depth, + this.token.text); + } + case 'code': { + return this.renderer.code(this.token.text, + this.token.lang, + this.token.escaped); + } + case 'table': { + var header = '' + , body = '' + , i + , row + , cell + , flags + , j; + + // header + cell = ''; + for (i = 0; i < this.token.header.length; i++) { + flags = { header: true, align: this.token.align[i] }; + cell += this.renderer.tablecell( + this.inline.output(this.token.header[i]), + { header: true, align: this.token.align[i] } + ); + } + header += this.renderer.tablerow(cell); + + for (i = 0; i < this.token.cells.length; i++) { + row = this.token.cells[i]; + + cell = ''; + for (j = 0; j < row.length; j++) { + cell += this.renderer.tablecell( + this.inline.output(row[j]), + { header: false, align: this.token.align[j] } + ); + } + + body += this.renderer.tablerow(cell); + } + return this.renderer.table(header, body); + } + case 'blockquote_start': { + var body = ''; + + while (this.next().type !== 'blockquote_end') { + body += this.tok(); + } + + return this.renderer.blockquote(body); + } + case 'list_start': { + var body = '' + , ordered = this.token.ordered; + + while (this.next().type !== 'list_end') { + body += this.tok(); + } + + return this.renderer.list(body, ordered); + } + case 'list_item_start': { + var body = ''; + + while (this.next().type !== 'list_item_end') { + body += this.token.type === 'text' + ? this.parseText() + : this.tok(); + } + + return this.renderer.listitem(body); + } + case 'loose_item_start': { + var body = ''; + + while (this.next().type !== 'list_item_end') { + body += this.tok(); + } + + return this.renderer.listitem(body); + } + case 'html': { + var html = !this.token.pre && !this.options.pedantic + ? this.inline.output(this.token.text) + : this.token.text; + return this.renderer.html(html); + } + case 'paragraph': { + return this.renderer.paragraph(this.inline.output(this.token.text)); + } + case 'text': { + return this.renderer.paragraph(this.parseText()); + } + } +}; + +/** + * Helpers + */ + +function escape(html, encode) { + return html + .replace(!encode ? /&(?!#?\w+;)/g : /&/g, '&') + .replace(//g, '>') + .replace(/"/g, '"') + .replace(/'/g, '''); +} + +function unescape(html) { + return html.replace(/&([#\w]+);/g, function(_, n) { + n = n.toLowerCase(); + if (n === 'colon') return ':'; + if (n.charAt(0) === '#') { + return n.charAt(1) === 'x' + ? String.fromCharCode(parseInt(n.substring(2), 16)) + : String.fromCharCode(+n.substring(1)); + } + return ''; + }); +} + +function replace(regex, opt) { + regex = regex.source; + opt = opt || ''; + return function self(name, val) { + if (!name) return new RegExp(regex, opt); + val = val.source || val; + val = val.replace(/(^|[^\[])\^/g, '$1'); + regex = regex.replace(name, val); + return self; + }; +} + +function noop() {} +noop.exec = noop; + +function merge(obj) { + var i = 1 + , target + , key; + + for (; i < arguments.length; i++) { + target = arguments[i]; + for (key in target) { + if (Object.prototype.hasOwnProperty.call(target, key)) { + obj[key] = target[key]; + } + } + } + + return obj; +} + + +/** + * Marked + */ + +function marked(src, opt, callback) { + if (callback || typeof opt === 'function') { + if (!callback) { + callback = opt; + opt = null; + } + + opt = merge({}, marked.defaults, opt || {}); + + var highlight = opt.highlight + , tokens + , pending + , i = 0; + + try { + tokens = Lexer.lex(src, opt) + } catch (e) { + return callback(e); + } + + pending = tokens.length; + + var done = function() { + var out, err; + + try { + out = Parser.parse(tokens, opt); + } catch (e) { + err = e; + } + + opt.highlight = highlight; + + return err + ? callback(err) + : callback(null, out); + }; + + if (!highlight || highlight.length < 3) { + return done(); + } + + delete opt.highlight; + + if (!pending) return done(); + + for (; i < tokens.length; i++) { + (function(token) { + if (token.type !== 'code') { + return --pending || done(); + } + return highlight(token.text, token.lang, function(err, code) { + if (code == null || code === token.text) { + return --pending || done(); + } + token.text = code; + token.escaped = true; + --pending || done(); + }); + })(tokens[i]); + } + + return; + } + try { + if (opt) opt = merge({}, marked.defaults, opt); + return Parser.parse(Lexer.lex(src, opt), opt); + } catch (e) { + e.message += '\nPlease report this to https://github.com/chjj/marked.'; + if ((opt || marked.defaults).silent) { + return '

    An error occured:

    '
    +        + escape(e.message + '', true)
    +        + '
    '; + } + throw e; + } +} + +/** + * Options + */ + +marked.options = +marked.setOptions = function(opt) { + merge(marked.defaults, opt); + return marked; +}; + +marked.defaults = { + gfm: true, + tables: true, + breaks: false, + pedantic: false, + sanitize: false, + smartLists: false, + silent: false, + highlight: null, + langPrefix: 'lang-', + smartypants: false, + headerPrefix: '', + renderer: new Renderer, + xhtml: false +}; + +/** + * Expose + */ + +marked.Parser = Parser; +marked.parser = Parser.parse; + +marked.Renderer = Renderer; + +marked.Lexer = Lexer; +marked.lexer = Lexer.lex; + +marked.InlineLexer = InlineLexer; +marked.inlineLexer = InlineLexer.output; + +marked.parse = marked; + +if (typeof exports === 'object') { + module.exports = marked; +} else if (typeof define === 'function' && define.amd) { + define(function() { return marked; }); +} else { + this.marked = marked; +} + +}).call(function() { + return this || (typeof window !== 'undefined' ? window : global); +}()); diff --git a/src/main/webapp/WEB-INF/views/protect/knowledge/view_add.jsp b/src/main/webapp/WEB-INF/views/protect/knowledge/view_add.jsp index ce0bcb134..825abc5a5 100644 --- a/src/main/webapp/WEB-INF/views/protect/knowledge/view_add.jsp +++ b/src/main/webapp/WEB-INF/views/protect/knowledge/view_add.jsp @@ -154,7 +154,7 @@ _TAGS.push('<%= jspUtil.out("tagitem.tagName") %>');

    - " value="<%= jspUtil.out("tagNames") %>" />

    diff --git a/src/main/webapp/WEB-INF/views/protect/knowledge/view_edit.jsp b/src/main/webapp/WEB-INF/views/protect/knowledge/view_edit.jsp index 05c7551bd..3252f93ce 100644 --- a/src/main/webapp/WEB-INF/views/protect/knowledge/view_edit.jsp +++ b/src/main/webapp/WEB-INF/views/protect/knowledge/view_edit.jsp @@ -156,7 +156,7 @@ _TAGS.push('<%= jspUtil.out("tagitem.tagName") %>');

    - " value="<%= jspUtil.out("tagNames") %>" />

    diff --git a/src/main/webapp/css/knowledge-edit.css b/src/main/webapp/css/knowledge-edit.css index 321c9d74b..00ecf7fd2 100644 --- a/src/main/webapp/css/knowledge-edit.css +++ b/src/main/webapp/css/knowledge-edit.css @@ -5,6 +5,9 @@ .bootstrap-tagsinput { width: 100%; } +.bootstrap-tagsinput input { + min-width: 300px; +} .filediv { diff --git a/src/test/java/org/support/project/knowledge/logic/MarkdownLogicTest.java b/src/test/java/org/support/project/knowledge/logic/MarkdownLogicTest.java index 46fe7a224..1731e68a2 100644 --- a/src/test/java/org/support/project/knowledge/logic/MarkdownLogicTest.java +++ b/src/test/java/org/support/project/knowledge/logic/MarkdownLogicTest.java @@ -76,7 +76,7 @@ private String[] read(String str) throws IOException { public void test1() throws Exception { String markdown = FileUtil.read(getClass().getResourceAsStream("markdown/markdown-1.md")); String html = FileUtil.read(getClass().getResourceAsStream("markdown/result-1.txt")); - String result = MarkdownLogic.get().markdownToHtml(markdown); + String result = MarkdownLogic.get().markdownToHtml(markdown).getHtml(); try { org.junit.Assert.assertArrayEquals(read(html), read(result)); } catch (AssertionError e) { @@ -94,7 +94,7 @@ public void test1() throws Exception { public void test2() throws UnsupportedEncodingException, IOException, ParseException, TransformerFactoryConfigurationError, TransformerException { String markdown = FileUtil.read(getClass().getResourceAsStream("markdown/markdown-2.md")); String html = FileUtil.read(getClass().getResourceAsStream("markdown/result-2.txt")); - String result = MarkdownLogic.get().markdownToHtml(markdown); + String result = MarkdownLogic.get().markdownToHtml(markdown).getHtml(); try { org.junit.Assert.assertArrayEquals(read(html), read(result)); } catch (AssertionError e) { @@ -112,7 +112,7 @@ public void test2() throws UnsupportedEncodingException, IOException, ParseExcep public void test3() throws ParseException, UnsupportedEncodingException, IOException, TransformerFactoryConfigurationError, TransformerException { String markdown = FileUtil.read(getClass().getResourceAsStream("markdown/markdown-3.md")); String html = FileUtil.read(getClass().getResourceAsStream("markdown/result-3.txt")); - String result = MarkdownLogic.get().markdownToHtml(markdown); + String result = MarkdownLogic.get().markdownToHtml(markdown).getHtml(); try { org.junit.Assert.assertArrayEquals(read(html), read(result)); } catch (AssertionError e) { @@ -130,7 +130,7 @@ public void test3() throws ParseException, UnsupportedEncodingException, IOExcep public void test4() throws ParseException, UnsupportedEncodingException, IOException, TransformerFactoryConfigurationError, TransformerException { String markdown = FileUtil.read(getClass().getResourceAsStream("markdown/markdown-4.md")); String html = FileUtil.read(getClass().getResourceAsStream("markdown/result-4.txt")); - String result = MarkdownLogic.get().markdownToHtml(markdown); + String result = MarkdownLogic.get().markdownToHtml(markdown).getHtml(); try { org.junit.Assert.assertArrayEquals(read(html), read(result)); } catch (AssertionError e) { @@ -148,7 +148,7 @@ public void test4() throws ParseException, UnsupportedEncodingException, IOExcep public void test5() throws ParseException, UnsupportedEncodingException, IOException, TransformerFactoryConfigurationError, TransformerException { String markdown = FileUtil.read(getClass().getResourceAsStream("markdown/markdown-5.md")); String html = FileUtil.read(getClass().getResourceAsStream("markdown/result-5.txt")); - String result = MarkdownLogic.get().markdownToHtml(markdown); + String result = MarkdownLogic.get().markdownToHtml(markdown).getHtml(); try { org.junit.Assert.assertArrayEquals(read(html), read(result)); } catch (AssertionError e) { @@ -162,6 +162,51 @@ public void test5() throws ParseException, UnsupportedEncodingException, IOExcep } + @Test + @Order(order= 6) + public void test6() throws ParseException, UnsupportedEncodingException, IOException, TransformerFactoryConfigurationError, TransformerException { + String markdown = FileUtil.read(getClass().getResourceAsStream("markdown/markdown-6.md")); + String html = FileUtil.read(getClass().getResourceAsStream("markdown/result-6.txt")); + String result = MarkdownLogic.get().markdownToHtml(markdown, MarkdownLogic.ENGINE_MARKEDJS).getHtml(); + try { + org.junit.Assert.assertArrayEquals(read(html), read(result)); + } catch (AssertionError e) { + LOG.info("test5"); + LOG.info("[Markdown] : " + markdown); + LOG.info("[Html] : " + html); + LOG.info("[Parsed] : " + result); + LOG.info("[Indent] : " + SanitizingLogic.get().indent(result)); + throw e; + } + + markdown = FileUtil.read(getClass().getResourceAsStream("markdown/markdown-6-2.md")); + html = FileUtil.read(getClass().getResourceAsStream("markdown/result-6-2.txt")); + result = MarkdownLogic.get().markdownToHtml(markdown, MarkdownLogic.ENGINE_MARKEDJS).getHtml(); + try { + org.junit.Assert.assertArrayEquals(read(html), read(result)); + } catch (AssertionError e) { + LOG.info("test5"); + LOG.info("[Markdown] : " + markdown); + LOG.info("[Html] : " + html); + LOG.info("[Parsed] : " + result); + LOG.info("[Indent] : " + SanitizingLogic.get().indent(result)); + throw e; + } + markdown = FileUtil.read(getClass().getResourceAsStream("markdown/markdown-6-2.md")); + html = FileUtil.read(getClass().getResourceAsStream("markdown/result-6-2.txt")); + result = MarkdownLogic.get().markdownToHtml(markdown, MarkdownLogic.ENGINE_MARKEDJS).getHtml(); + try { + org.junit.Assert.assertArrayEquals(read(html), read(result)); + } catch (AssertionError e) { + LOG.info("test5"); + LOG.info("[Markdown] : " + markdown); + LOG.info("[Html] : " + html); + LOG.info("[Parsed] : " + result); + LOG.info("[Indent] : " + SanitizingLogic.get().indent(result)); + throw e; + } + } + } diff --git a/src/test/resources/org/support/project/knowledge/logic/markdown/markdown-6-2.md b/src/test/resources/org/support/project/knowledge/logic/markdown/markdown-6-2.md new file mode 100644 index 000000000..addfbd463 --- /dev/null +++ b/src/test/resources/org/support/project/knowledge/logic/markdown/markdown-6-2.md @@ -0,0 +1,40 @@ +# テスト +- 簡単なmarkdown +- HTMLのタグを使える? + - インデント + - 少しだけ複雑 +- どうなるか? + +## 見出し2 +- Javascriptで簡単にパースしていたけど、Java側で実行した方が制御しやすいね +- 危険な + +1. テスト +2. ほげ + 1. テスト + 2. 階層 +3. 数値 + + +### Script + +これ通る? +

    通らない

    + +- PegDownProcessorだけだと、そのまま出力する(XSSでやばそう) +- サニタイジングする + +```ruby:qiita.rb +puts 'The best way to log and share programmers knowledge.' +``` + +```html + +``` + +```java +private List params = new ArrayList<>(); +``` + + + diff --git a/src/test/resources/org/support/project/knowledge/logic/markdown/markdown-6.md b/src/test/resources/org/support/project/knowledge/logic/markdown/markdown-6.md new file mode 100644 index 000000000..0dfd95a4b --- /dev/null +++ b/src/test/resources/org/support/project/knowledge/logic/markdown/markdown-6.md @@ -0,0 +1,33 @@ +# テスト +- 簡単なmarkdown +- HTMLのタグを使える? + - インデント + - 少しだけ複雑 +- どうなるか? + +## 見出し2 +- Javascriptで簡単にパースしていたけど、Java側で実行した方が制御しやすいね +- 危険な + +### Script + +これ通る? +

    通らない

    + +- PegDownProcessorだけだと、そのまま出力する(XSSでやばそう) +- サニタイジングする + +```ruby:qiita.rb +puts 'The best way to log and share programmers knowledge.' +``` + +```html + +``` + +```java +private List params = new ArrayList<>(); +``` + + + diff --git a/src/test/resources/org/support/project/knowledge/logic/markdown/result-6-2.txt b/src/test/resources/org/support/project/knowledge/logic/markdown/result-6-2.txt new file mode 100644 index 000000000..eb392cbe1 --- /dev/null +++ b/src/test/resources/org/support/project/knowledge/logic/markdown/result-6-2.txt @@ -0,0 +1,21 @@ +

    テスト

    +
    • 簡単なmarkdown
    • HTMLのタグを使える?
      • インデント
        • 少しだけ複雑
        +
      +
    • どうなるか?
    +

    見出し2

    +
    • Javascriptで簡単にパースしていたけど、Java側で実行した方が制御しやすいね
    • 危険な

      +
    • テスト

      +
    • ほげ
      1. テスト
        1. 階層
        +
      +
    • 数値
    +

    Script

    +

    +これ通る?

    +

    通らない

    +
    • PegDownProcessorだけだと、そのまま出力する(XSSでやばそう)
    • サニタイジングする
    +
    puts 'The best way to log and share programmers knowledge.'
    +
    +
    <button>hogehoge</button>
    +
    +
    private List<Object> params = new ArrayList<>();
    +
    diff --git a/src/test/resources/org/support/project/knowledge/logic/markdown/result-6.txt b/src/test/resources/org/support/project/knowledge/logic/markdown/result-6.txt new file mode 100644 index 000000000..47c5955d8 --- /dev/null +++ b/src/test/resources/org/support/project/knowledge/logic/markdown/result-6.txt @@ -0,0 +1,17 @@ +

    テスト

    +
    • 簡単なmarkdown
    • HTMLのタグを使える?
      • インデント
        • 少しだけ複雑
        +
      +
    • どうなるか?
    +

    見出し2

    +
    • Javascriptで簡単にパースしていたけど、Java側で実行した方が制御しやすいね
    • 危険な
    +

    Script

    +

    +これ通る?

    +

    通らない

    +
    • PegDownProcessorだけだと、そのまま出力する(XSSでやばそう)
    • サニタイジングする
    +
    puts 'The best way to log and share programmers knowledge.'
    +
    +
    <button>hogehoge</button>
    +
    +
    private List<Object> params = new ArrayList<>();
    +
    \ No newline at end of file