text
stringlengths
101
200k
repo_name
stringlengths
5
73
stars
stringlengths
3
6
repo_language
stringlengths
1
24
file_name
stringlengths
2
57
mime_type
stringclasses
22 values
hash
int64
-9,223,369,786,400,666,000
9,223,339,290B
body { font-szie: 18; margin: 10px auto; line-height: 2em; width: 90%; } pre { margin: -15px; } .panel-usage { width:48%; } .panel-usage-simple { float: left; } .panel-usage-complicated { float: right; } .block-main { width: 50%; float: left; } .block-side-comment { width: 50%; background-color:#DCDCDC; float: right; } pre.form-field-pre { margin: 10px; background-color: white; } .form-input-table td{ padding-top: 5px; padding-bottom: 5px; } .form-input-table label{ margin-left: 2px; margin-right: 5px; font-weight: normal; } .form-btn-bar { padding-top: 5px; padding-bottom: 5px; } .form-btn-bar button{ margin-top: 5px; margin-right: 5px; } .form-list-btn-bar { font-size: 18; line-height: 3em; } .bold { font-weight: bold; } .italic { font-style: italic; } .red { color: red; }
astamuse/asta4d
162
Java
org.eclipse.core.resources.prefs
text/plain
1,996,917,565,071,300,400
<?xml version="1.0" encoding="UTF-8"?> <web-app version="2.5" xmlns="http://java.sun.com/xml/ns/javaee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"> <!-- standalone without spring --> <servlet> <servlet-name>Asta4D Servlet</servlet-name> <servlet-class>com.astamuse.asta4d.sample.Asta4DSampleServlet</servlet-class> <load-on-startup>1</load-on-startup> </servlet> <!-- integrate with spring --> <!-- <servlet> <servlet-name>Asta4D Servlet</servlet-name> <servlet-class>com.astamuse.asta4d.misc.spring.SpringInitializableServlet</servlet-class> <init-param> <param-name>contextConfigLocation</param-name> <param-value>classpath:spring/configuration.xml</param-value> </init-param> <load-on-startup>1</load-on-startup> </servlet> --> <!-- Disabled this configuration due not to work correctly in wildfly which is our online sample runtime and instead of StaticResourceHanlder in java side. This is still work for jetty/tomcat. --> <!-- <servlet-mapping> <servlet-name>default</servlet-name> <url-pattern>/css/*</url-pattern> </servlet-mapping> --> <servlet-mapping> <servlet-name>Asta4D Servlet</servlet-name> <url-pattern>/</url-pattern> </servlet-mapping> </web-app>
astamuse/asta4d
162
Java
org.eclipse.core.resources.prefs
text/plain
6,029,940,716,622,275,000
// Copyright (C) 2006 Google Inc. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. /** * @fileoverview * some functions for browser-side pretty printing of code contained in html. * * <p> * For a fairly comprehensive set of languages see the * <a href="http://google-code-prettify.googlecode.com/svn/trunk/README.html#langs">README</a> * file that came with this source. At a minimum, the lexer should work on a * number of languages including C and friends, Java, Python, Bash, SQL, HTML, * XML, CSS, Javascript, and Makefiles. It works passably on Ruby, PHP and Awk * and a subset of Perl, but, because of commenting conventions, doesn't work on * Smalltalk, Lisp-like, or CAML-like languages without an explicit lang class. * <p> * Usage: <ol> * <li> include this source file in an html page via * {@code <script type="text/javascript" src="/path/to/prettify.js"></script>} * <li> define style rules. See the example page for examples. * <li> mark the {@code <pre>} and {@code <code>} tags in your source with * {@code class=prettyprint.} * You can also use the (html deprecated) {@code <xmp>} tag, but the pretty * printer needs to do more substantial DOM manipulations to support that, so * some css styles may not be preserved. * </ol> * That's it. I wanted to keep the API as simple as possible, so there's no * need to specify which language the code is in, but if you wish, you can add * another class to the {@code <pre>} or {@code <code>} element to specify the * language, as in {@code <pre class="prettyprint lang-java">}. Any class that * starts with "lang-" followed by a file extension, specifies the file type. * See the "lang-*.js" files in this directory for code that implements * per-language file handlers. * <p> * Change log:<br> * cbeust, 2006/08/22 * <blockquote> * Java annotations (start with "@") are now captured as literals ("lit") * </blockquote> * @requires console */ // JSLint declarations /*global console, document, navigator, setTimeout, window, define */ /** @define {boolean} */ var IN_GLOBAL_SCOPE = true; /** * Split {@code prettyPrint} into multiple timeouts so as not to interfere with * UI events. * If set to {@code false}, {@code prettyPrint()} is synchronous. */ window['PR_SHOULD_USE_CONTINUATION'] = true; /** * Pretty print a chunk of code. * @param {string} sourceCodeHtml The HTML to pretty print. * @param {string} opt_langExtension The language name to use. * Typically, a filename extension like 'cpp' or 'java'. * @param {number|boolean} opt_numberLines True to number lines, * or the 1-indexed number of the first line in sourceCodeHtml. * @return {string} code as html, but prettier */ var prettyPrintOne; /** * Find all the {@code <pre>} and {@code <code>} tags in the DOM with * {@code class=prettyprint} and prettify them. * * @param {Function} opt_whenDone called when prettifying is done. * @param {HTMLElement|HTMLDocument} opt_root an element or document * containing all the elements to pretty print. * Defaults to {@code document.body}. */ var prettyPrint; (function () { var win = window; // Keyword lists for various languages. // We use things that coerce to strings to make them compact when minified // and to defeat aggressive optimizers that fold large string constants. var FLOW_CONTROL_KEYWORDS = ["break,continue,do,else,for,if,return,while"]; var C_KEYWORDS = [FLOW_CONTROL_KEYWORDS,"auto,case,char,const,default," + "double,enum,extern,float,goto,inline,int,long,register,short,signed," + "sizeof,static,struct,switch,typedef,union,unsigned,void,volatile"]; var COMMON_KEYWORDS = [C_KEYWORDS,"catch,class,delete,false,import," + "new,operator,private,protected,public,this,throw,true,try,typeof"]; var CPP_KEYWORDS = [COMMON_KEYWORDS,"alignof,align_union,asm,axiom,bool," + "concept,concept_map,const_cast,constexpr,decltype,delegate," + "dynamic_cast,explicit,export,friend,generic,late_check," + "mutable,namespace,nullptr,property,reinterpret_cast,static_assert," + "static_cast,template,typeid,typename,using,virtual,where"]; var JAVA_KEYWORDS = [COMMON_KEYWORDS, "abstract,assert,boolean,byte,extends,final,finally,implements,import," + "instanceof,interface,null,native,package,strictfp,super,synchronized," + "throws,transient"]; var CSHARP_KEYWORDS = [JAVA_KEYWORDS, "as,base,by,checked,decimal,delegate,descending,dynamic,event," + "fixed,foreach,from,group,implicit,in,internal,into,is,let," + "lock,object,out,override,orderby,params,partial,readonly,ref,sbyte," + "sealed,stackalloc,string,select,uint,ulong,unchecked,unsafe,ushort," + "var,virtual,where"]; var COFFEE_KEYWORDS = "all,and,by,catch,class,else,extends,false,finally," + "for,if,in,is,isnt,loop,new,no,not,null,of,off,on,or,return,super,then," + "throw,true,try,unless,until,when,while,yes"; var JSCRIPT_KEYWORDS = [COMMON_KEYWORDS, "debugger,eval,export,function,get,null,set,undefined,var,with," + "Infinity,NaN"]; var PERL_KEYWORDS = "caller,delete,die,do,dump,elsif,eval,exit,foreach,for," + "goto,if,import,last,local,my,next,no,our,print,package,redo,require," + "sub,undef,unless,until,use,wantarray,while,BEGIN,END"; var PYTHON_KEYWORDS = [FLOW_CONTROL_KEYWORDS, "and,as,assert,class,def,del," + "elif,except,exec,finally,from,global,import,in,is,lambda," + "nonlocal,not,or,pass,print,raise,try,with,yield," + "False,True,None"]; var RUBY_KEYWORDS = [FLOW_CONTROL_KEYWORDS, "alias,and,begin,case,class," + "def,defined,elsif,end,ensure,false,in,module,next,nil,not,or,redo," + "rescue,retry,self,super,then,true,undef,unless,until,when,yield," + "BEGIN,END"]; var RUST_KEYWORDS = [FLOW_CONTROL_KEYWORDS, "as,assert,const,copy,drop," + "enum,extern,fail,false,fn,impl,let,log,loop,match,mod,move,mut,priv," + "pub,pure,ref,self,static,struct,true,trait,type,unsafe,use"]; var SH_KEYWORDS = [FLOW_CONTROL_KEYWORDS, "case,done,elif,esac,eval,fi," + "function,in,local,set,then,until"]; var ALL_KEYWORDS = [ CPP_KEYWORDS, CSHARP_KEYWORDS, JSCRIPT_KEYWORDS, PERL_KEYWORDS, PYTHON_KEYWORDS, RUBY_KEYWORDS, SH_KEYWORDS]; var C_TYPES = /^(DIR|FILE|vector|(de|priority_)?queue|list|stack|(const_)?iterator|(multi)?(set|map)|bitset|u?(int|float)\d*)\b/; // token style names. correspond to css classes /** * token style for a string literal * @const */ var PR_STRING = 'str'; /** * token style for a keyword * @const */ var PR_KEYWORD = 'kwd'; /** * token style for a comment * @const */ var PR_COMMENT = 'com'; /** * token style for a type * @const */ var PR_TYPE = 'typ'; /** * token style for a literal value. e.g. 1, null, true. * @const */ var PR_LITERAL = 'lit'; /** * token style for a punctuation string. * @const */ var PR_PUNCTUATION = 'pun'; /** * token style for plain text. * @const */ var PR_PLAIN = 'pln'; /** * token style for an sgml tag. * @const */ var PR_TAG = 'tag'; /** * token style for a markup declaration such as a DOCTYPE. * @const */ var PR_DECLARATION = 'dec'; /** * token style for embedded source. * @const */ var PR_SOURCE = 'src'; /** * token style for an sgml attribute name. * @const */ var PR_ATTRIB_NAME = 'atn'; /** * token style for an sgml attribute value. * @const */ var PR_ATTRIB_VALUE = 'atv'; /** * A class that indicates a section of markup that is not code, e.g. to allow * embedding of line numbers within code listings. * @const */ var PR_NOCODE = 'nocode'; /** * A set of tokens that can precede a regular expression literal in * javascript * http://web.archive.org/web/20070717142515/http://www.mozilla.org/js/language/js20/rationale/syntax.html * has the full list, but I've removed ones that might be problematic when * seen in languages that don't support regular expression literals. * * <p>Specifically, I've removed any keywords that can't precede a regexp * literal in a syntactically legal javascript program, and I've removed the * "in" keyword since it's not a keyword in many languages, and might be used * as a count of inches. * * <p>The link above does not accurately describe EcmaScript rules since * it fails to distinguish between (a=++/b/i) and (a++/b/i) but it works * very well in practice. * * @private * @const */ var REGEXP_PRECEDER_PATTERN = '(?:^^\\.?|[+-]|[!=]=?=?|\\#|%=?|&&?=?|\\(|\\*=?|[+\\-]=|->|\\/=?|::?|<<?=?|>>?>?=?|,|;|\\?|@|\\[|~|{|\\^\\^?=?|\\|\\|?=?|break|case|continue|delete|do|else|finally|instanceof|return|throw|try|typeof)\\s*'; // CAVEAT: this does not properly handle the case where a regular // expression immediately follows another since a regular expression may // have flags for case-sensitivity and the like. Having regexp tokens // adjacent is not valid in any language I'm aware of, so I'm punting. // TODO: maybe style special characters inside a regexp as punctuation. /** * Given a group of {@link RegExp}s, returns a {@code RegExp} that globally * matches the union of the sets of strings matched by the input RegExp. * Since it matches globally, if the input strings have a start-of-input * anchor (/^.../), it is ignored for the purposes of unioning. * @param {Array.<RegExp>} regexs non multiline, non-global regexs. * @return {RegExp} a global regex. */ function combinePrefixPatterns(regexs) { var capturedGroupIndex = 0; var needToFoldCase = false; var ignoreCase = false; for (var i = 0, n = regexs.length; i < n; ++i) { var regex = regexs[i]; if (regex.ignoreCase) { ignoreCase = true; } else if (/[a-z]/i.test(regex.source.replace( /\\u[0-9a-f]{4}|\\x[0-9a-f]{2}|\\[^ux]/gi, ''))) { needToFoldCase = true; ignoreCase = false; break; } } var escapeCharToCodeUnit = { 'b': 8, 't': 9, 'n': 0xa, 'v': 0xb, 'f': 0xc, 'r': 0xd }; function decodeEscape(charsetPart) { var cc0 = charsetPart.charCodeAt(0); if (cc0 !== 92 /* \\ */) { return cc0; } var c1 = charsetPart.charAt(1); cc0 = escapeCharToCodeUnit[c1]; if (cc0) { return cc0; } else if ('0' <= c1 && c1 <= '7') { return parseInt(charsetPart.substring(1), 8); } else if (c1 === 'u' || c1 === 'x') { return parseInt(charsetPart.substring(2), 16); } else { return charsetPart.charCodeAt(1); } } function encodeEscape(charCode) { if (charCode < 0x20) { return (charCode < 0x10 ? '\\x0' : '\\x') + charCode.toString(16); } var ch = String.fromCharCode(charCode); return (ch === '\\' || ch === '-' || ch === ']' || ch === '^') ? "\\" + ch : ch; } function caseFoldCharset(charSet) { var charsetParts = charSet.substring(1, charSet.length - 1).match( new RegExp( '\\\\u[0-9A-Fa-f]{4}' + '|\\\\x[0-9A-Fa-f]{2}' + '|\\\\[0-3][0-7]{0,2}' + '|\\\\[0-7]{1,2}' + '|\\\\[\\s\\S]' + '|-' + '|[^-\\\\]', 'g')); var ranges = []; var inverse = charsetParts[0] === '^'; var out = ['[']; if (inverse) { out.push('^'); } for (var i = inverse ? 1 : 0, n = charsetParts.length; i < n; ++i) { var p = charsetParts[i]; if (/\\[bdsw]/i.test(p)) { // Don't muck with named groups. out.push(p); } else { var start = decodeEscape(p); var end; if (i + 2 < n && '-' === charsetParts[i + 1]) { end = decodeEscape(charsetParts[i + 2]); i += 2; } else { end = start; } ranges.push([start, end]); // If the range might intersect letters, then expand it. // This case handling is too simplistic. // It does not deal with non-latin case folding. // It works for latin source code identifiers though. if (!(end < 65 || start > 122)) { if (!(end < 65 || start > 90)) { ranges.push([Math.max(65, start) | 32, Math.min(end, 90) | 32]); } if (!(end < 97 || start > 122)) { ranges.push([Math.max(97, start) & ~32, Math.min(end, 122) & ~32]); } } } } // [[1, 10], [3, 4], [8, 12], [14, 14], [16, 16], [17, 17]] // -> [[1, 12], [14, 14], [16, 17]] ranges.sort(function (a, b) { return (a[0] - b[0]) || (b[1] - a[1]); }); var consolidatedRanges = []; var lastRange = []; for (var i = 0; i < ranges.length; ++i) { var range = ranges[i]; if (range[0] <= lastRange[1] + 1) { lastRange[1] = Math.max(lastRange[1], range[1]); } else { consolidatedRanges.push(lastRange = range); } } for (var i = 0; i < consolidatedRanges.length; ++i) { var range = consolidatedRanges[i]; out.push(encodeEscape(range[0])); if (range[1] > range[0]) { if (range[1] + 1 > range[0]) { out.push('-'); } out.push(encodeEscape(range[1])); } } out.push(']'); return out.join(''); } function allowAnywhereFoldCaseAndRenumberGroups(regex) { // Split into character sets, escape sequences, punctuation strings // like ('(', '(?:', ')', '^'), and runs of characters that do not // include any of the above. var parts = regex.source.match( new RegExp( '(?:' + '\\[(?:[^\\x5C\\x5D]|\\\\[\\s\\S])*\\]' // a character set + '|\\\\u[A-Fa-f0-9]{4}' // a unicode escape + '|\\\\x[A-Fa-f0-9]{2}' // a hex escape + '|\\\\[0-9]+' // a back-reference or octal escape + '|\\\\[^ux0-9]' // other escape sequence + '|\\(\\?[:!=]' // start of a non-capturing group + '|[\\(\\)\\^]' // start/end of a group, or line start + '|[^\\x5B\\x5C\\(\\)\\^]+' // run of other characters + ')', 'g')); var n = parts.length; // Maps captured group numbers to the number they will occupy in // the output or to -1 if that has not been determined, or to // undefined if they need not be capturing in the output. var capturedGroups = []; // Walk over and identify back references to build the capturedGroups // mapping. for (var i = 0, groupIndex = 0; i < n; ++i) { var p = parts[i]; if (p === '(') { // groups are 1-indexed, so max group index is count of '(' ++groupIndex; } else if ('\\' === p.charAt(0)) { var decimalValue = +p.substring(1); if (decimalValue) { if (decimalValue <= groupIndex) { capturedGroups[decimalValue] = -1; } else { // Replace with an unambiguous escape sequence so that // an octal escape sequence does not turn into a backreference // to a capturing group from an earlier regex. parts[i] = encodeEscape(decimalValue); } } } } // Renumber groups and reduce capturing groups to non-capturing groups // where possible. for (var i = 1; i < capturedGroups.length; ++i) { if (-1 === capturedGroups[i]) { capturedGroups[i] = ++capturedGroupIndex; } } for (var i = 0, groupIndex = 0; i < n; ++i) { var p = parts[i]; if (p === '(') { ++groupIndex; if (!capturedGroups[groupIndex]) { parts[i] = '(?:'; } } else if ('\\' === p.charAt(0)) { var decimalValue = +p.substring(1); if (decimalValue && decimalValue <= groupIndex) { parts[i] = '\\' + capturedGroups[decimalValue]; } } } // Remove any prefix anchors so that the output will match anywhere. // ^^ really does mean an anchored match though. for (var i = 0; i < n; ++i) { if ('^' === parts[i] && '^' !== parts[i + 1]) { parts[i] = ''; } } // Expand letters to groups to handle mixing of case-sensitive and // case-insensitive patterns if necessary. if (regex.ignoreCase && needToFoldCase) { for (var i = 0; i < n; ++i) { var p = parts[i]; var ch0 = p.charAt(0); if (p.length >= 2 && ch0 === '[') { parts[i] = caseFoldCharset(p); } else if (ch0 !== '\\') { // TODO: handle letters in numeric escapes. parts[i] = p.replace( /[a-zA-Z]/g, function (ch) { var cc = ch.charCodeAt(0); return '[' + String.fromCharCode(cc & ~32, cc | 32) + ']'; }); } } } return parts.join(''); } var rewritten = []; for (var i = 0, n = regexs.length; i < n; ++i) { var regex = regexs[i]; if (regex.global || regex.multiline) { throw new Error('' + regex); } rewritten.push( '(?:' + allowAnywhereFoldCaseAndRenumberGroups(regex) + ')'); } return new RegExp(rewritten.join('|'), ignoreCase ? 'gi' : 'g'); } /** * Split markup into a string of source code and an array mapping ranges in * that string to the text nodes in which they appear. * * <p> * The HTML DOM structure:</p> * <pre> * (Element "p" * (Element "b" * (Text "print ")) ; #1 * (Text "'Hello '") ; #2 * (Element "br") ; #3 * (Text " + 'World';")) ; #4 * </pre> * <p> * corresponds to the HTML * {@code <p><b>print </b>'Hello '<br> + 'World';</p>}.</p> * * <p> * It will produce the output:</p> * <pre> * { * sourceCode: "print 'Hello '\n + 'World';", * // 1 2 * // 012345678901234 5678901234567 * spans: [0, #1, 6, #2, 14, #3, 15, #4] * } * </pre> * <p> * where #1 is a reference to the {@code "print "} text node above, and so * on for the other text nodes. * </p> * * <p> * The {@code} spans array is an array of pairs. Even elements are the start * indices of substrings, and odd elements are the text nodes (or BR elements) * that contain the text for those substrings. * Substrings continue until the next index or the end of the source. * </p> * * @param {Node} node an HTML DOM subtree containing source-code. * @param {boolean} isPreformatted true if white-space in text nodes should * be considered significant. * @return {Object} source code and the text nodes in which they occur. */ function extractSourceSpans(node, isPreformatted) { var nocode = /(?:^|\s)nocode(?:\s|$)/; var chunks = []; var length = 0; var spans = []; var k = 0; function walk(node) { var type = node.nodeType; if (type == 1) { // Element if (nocode.test(node.className)) { return; } for (var child = node.firstChild; child; child = child.nextSibling) { walk(child); } var nodeName = node.nodeName.toLowerCase(); if ('br' === nodeName || 'li' === nodeName) { chunks[k] = '\n'; spans[k << 1] = length++; spans[(k++ << 1) | 1] = node; } } else if (type == 3 || type == 4) { // Text var text = node.nodeValue; if (text.length) { if (!isPreformatted) { text = text.replace(/[ \t\r\n]+/g, ' '); } else { text = text.replace(/\r\n?/g, '\n'); // Normalize newlines. } // TODO: handle tabs here? chunks[k] = text; spans[k << 1] = length; length += text.length; spans[(k++ << 1) | 1] = node; } } } walk(node); return { sourceCode: chunks.join('').replace(/\n$/, ''), spans: spans }; } /** * Apply the given language handler to sourceCode and add the resulting * decorations to out. * @param {number} basePos the index of sourceCode within the chunk of source * whose decorations are already present on out. */ function appendDecorations(basePos, sourceCode, langHandler, out) { if (!sourceCode) { return; } var job = { sourceCode: sourceCode, basePos: basePos }; langHandler(job); out.push.apply(out, job.decorations); } var notWs = /\S/; /** * Given an element, if it contains only one child element and any text nodes * it contains contain only space characters, return the sole child element. * Otherwise returns undefined. * <p> * This is meant to return the CODE element in {@code <pre><code ...>} when * there is a single child element that contains all the non-space textual * content, but not to return anything where there are multiple child elements * as in {@code <pre><code>...</code><code>...</code></pre>} or when there * is textual content. */ function childContentWrapper(element) { var wrapper = undefined; for (var c = element.firstChild; c; c = c.nextSibling) { var type = c.nodeType; wrapper = (type === 1) // Element Node ? (wrapper ? element : c) : (type === 3) // Text Node ? (notWs.test(c.nodeValue) ? element : wrapper) : wrapper; } return wrapper === element ? undefined : wrapper; } /** Given triples of [style, pattern, context] returns a lexing function, * The lexing function interprets the patterns to find token boundaries and * returns a decoration list of the form * [index_0, style_0, index_1, style_1, ..., index_n, style_n] * where index_n is an index into the sourceCode, and style_n is a style * constant like PR_PLAIN. index_n-1 <= index_n, and style_n-1 applies to * all characters in sourceCode[index_n-1:index_n]. * * The stylePatterns is a list whose elements have the form * [style : string, pattern : RegExp, DEPRECATED, shortcut : string]. * * Style is a style constant like PR_PLAIN, or can be a string of the * form 'lang-FOO', where FOO is a language extension describing the * language of the portion of the token in $1 after pattern executes. * E.g., if style is 'lang-lisp', and group 1 contains the text * '(hello (world))', then that portion of the token will be passed to the * registered lisp handler for formatting. * The text before and after group 1 will be restyled using this decorator * so decorators should take care that this doesn't result in infinite * recursion. For example, the HTML lexer rule for SCRIPT elements looks * something like ['lang-js', /<[s]cript>(.+?)<\/script>/]. This may match * '<script>foo()<\/script>', which would cause the current decorator to * be called with '<script>' which would not match the same rule since * group 1 must not be empty, so it would be instead styled as PR_TAG by * the generic tag rule. The handler registered for the 'js' extension would * then be called with 'foo()', and finally, the current decorator would * be called with '<\/script>' which would not match the original rule and * so the generic tag rule would identify it as a tag. * * Pattern must only match prefixes, and if it matches a prefix, then that * match is considered a token with the same style. * * Context is applied to the last non-whitespace, non-comment token * recognized. * * Shortcut is an optional string of characters, any of which, if the first * character, gurantee that this pattern and only this pattern matches. * * @param {Array} shortcutStylePatterns patterns that always start with * a known character. Must have a shortcut string. * @param {Array} fallthroughStylePatterns patterns that will be tried in * order if the shortcut ones fail. May have shortcuts. * * @return {function (Object)} a * function that takes source code and returns a list of decorations. */ function createSimpleLexer(shortcutStylePatterns, fallthroughStylePatterns) { var shortcuts = {}; var tokenizer; (function () { var allPatterns = shortcutStylePatterns.concat(fallthroughStylePatterns); var allRegexs = []; var regexKeys = {}; for (var i = 0, n = allPatterns.length; i < n; ++i) { var patternParts = allPatterns[i]; var shortcutChars = patternParts[3]; if (shortcutChars) { for (var c = shortcutChars.length; --c >= 0;) { shortcuts[shortcutChars.charAt(c)] = patternParts; } } var regex = patternParts[1]; var k = '' + regex; if (!regexKeys.hasOwnProperty(k)) { allRegexs.push(regex); regexKeys[k] = null; } } allRegexs.push(/[\0-\uffff]/); tokenizer = combinePrefixPatterns(allRegexs); })(); var nPatterns = fallthroughStylePatterns.length; /** * Lexes job.sourceCode and produces an output array job.decorations of * style classes preceded by the position at which they start in * job.sourceCode in order. * * @param {Object} job an object like <pre>{ * sourceCode: {string} sourceText plain text, * basePos: {int} position of job.sourceCode in the larger chunk of * sourceCode. * }</pre> */ var decorate = function (job) { var sourceCode = job.sourceCode, basePos = job.basePos; /** Even entries are positions in source in ascending order. Odd enties * are style markers (e.g., PR_COMMENT) that run from that position until * the end. * @type {Array.<number|string>} */ var decorations = [basePos, PR_PLAIN]; var pos = 0; // index into sourceCode var tokens = sourceCode.match(tokenizer) || []; var styleCache = {}; for (var ti = 0, nTokens = tokens.length; ti < nTokens; ++ti) { var token = tokens[ti]; var style = styleCache[token]; var match = void 0; var isEmbedded; if (typeof style === 'string') { isEmbedded = false; } else { var patternParts = shortcuts[token.charAt(0)]; if (patternParts) { match = token.match(patternParts[1]); style = patternParts[0]; } else { for (var i = 0; i < nPatterns; ++i) { patternParts = fallthroughStylePatterns[i]; match = token.match(patternParts[1]); if (match) { style = patternParts[0]; break; } } if (!match) { // make sure that we make progress style = PR_PLAIN; } } isEmbedded = style.length >= 5 && 'lang-' === style.substring(0, 5); if (isEmbedded && !(match && typeof match[1] === 'string')) { isEmbedded = false; style = PR_SOURCE; } if (!isEmbedded) { styleCache[token] = style; } } var tokenStart = pos; pos += token.length; if (!isEmbedded) { decorations.push(basePos + tokenStart, style); } else { // Treat group 1 as an embedded block of source code. var embeddedSource = match[1]; var embeddedSourceStart = token.indexOf(embeddedSource); var embeddedSourceEnd = embeddedSourceStart + embeddedSource.length; if (match[2]) { // If embeddedSource can be blank, then it would match at the // beginning which would cause us to infinitely recurse on the // entire token, so we catch the right context in match[2]. embeddedSourceEnd = token.length - match[2].length; embeddedSourceStart = embeddedSourceEnd - embeddedSource.length; } var lang = style.substring(5); // Decorate the left of the embedded source appendDecorations( basePos + tokenStart, token.substring(0, embeddedSourceStart), decorate, decorations); // Decorate the embedded source appendDecorations( basePos + tokenStart + embeddedSourceStart, embeddedSource, langHandlerForExtension(lang, embeddedSource), decorations); // Decorate the right of the embedded section appendDecorations( basePos + tokenStart + embeddedSourceEnd, token.substring(embeddedSourceEnd), decorate, decorations); } } job.decorations = decorations; }; return decorate; } /** returns a function that produces a list of decorations from source text. * * This code treats ", ', and ` as string delimiters, and \ as a string * escape. It does not recognize perl's qq() style strings. * It has no special handling for double delimiter escapes as in basic, or * the tripled delimiters used in python, but should work on those regardless * although in those cases a single string literal may be broken up into * multiple adjacent string literals. * * It recognizes C, C++, and shell style comments. * * @param {Object} options a set of optional parameters. * @return {function (Object)} a function that examines the source code * in the input job and builds the decoration list. */ function sourceDecorator(options) { var shortcutStylePatterns = [], fallthroughStylePatterns = []; if (options['tripleQuotedStrings']) { // '''multi-line-string''', 'single-line-string', and double-quoted shortcutStylePatterns.push( [PR_STRING, /^(?:\'\'\'(?:[^\'\\]|\\[\s\S]|\'{1,2}(?=[^\']))*(?:\'\'\'|$)|\"\"\"(?:[^\"\\]|\\[\s\S]|\"{1,2}(?=[^\"]))*(?:\"\"\"|$)|\'(?:[^\\\']|\\[\s\S])*(?:\'|$)|\"(?:[^\\\"]|\\[\s\S])*(?:\"|$))/, null, '\'"']); } else if (options['multiLineStrings']) { // 'multi-line-string', "multi-line-string" shortcutStylePatterns.push( [PR_STRING, /^(?:\'(?:[^\\\']|\\[\s\S])*(?:\'|$)|\"(?:[^\\\"]|\\[\s\S])*(?:\"|$)|\`(?:[^\\\`]|\\[\s\S])*(?:\`|$))/, null, '\'"`']); } else { // 'single-line-string', "single-line-string" shortcutStylePatterns.push( [PR_STRING, /^(?:\'(?:[^\\\'\r\n]|\\.)*(?:\'|$)|\"(?:[^\\\"\r\n]|\\.)*(?:\"|$))/, null, '"\'']); } if (options['verbatimStrings']) { // verbatim-string-literal production from the C# grammar. See issue 93. fallthroughStylePatterns.push( [PR_STRING, /^@\"(?:[^\"]|\"\")*(?:\"|$)/, null]); } var hc = options['hashComments']; if (hc) { if (options['cStyleComments']) { if (hc > 1) { // multiline hash comments shortcutStylePatterns.push( [PR_COMMENT, /^#(?:##(?:[^#]|#(?!##))*(?:###|$)|.*)/, null, '#']); } else { // Stop C preprocessor declarations at an unclosed open comment shortcutStylePatterns.push( [PR_COMMENT, /^#(?:(?:define|e(?:l|nd)if|else|error|ifn?def|include|line|pragma|undef|warning)\b|[^\r\n]*)/, null, '#']); } // #include <stdio.h> fallthroughStylePatterns.push( [PR_STRING, /^<(?:(?:(?:\.\.\/)*|\/?)(?:[\w-]+(?:\/[\w-]+)+)?[\w-]+\.h(?:h|pp|\+\+)?|[a-z]\w*)>/, null]); } else { shortcutStylePatterns.push([PR_COMMENT, /^#[^\r\n]*/, null, '#']); } } if (options['cStyleComments']) { fallthroughStylePatterns.push([PR_COMMENT, /^\/\/[^\r\n]*/, null]); fallthroughStylePatterns.push( [PR_COMMENT, /^\/\*[\s\S]*?(?:\*\/|$)/, null]); } var regexLiterals = options['regexLiterals']; if (regexLiterals) { /** * @const */ var regexExcls = regexLiterals > 1 ? '' // Multiline regex literals : '\n\r'; /** * @const */ var regexAny = regexExcls ? '.' : '[\\S\\s]'; /** * @const */ var REGEX_LITERAL = ( // A regular expression literal starts with a slash that is // not followed by * or / so that it is not confused with // comments. '/(?=[^/*' + regexExcls + '])' // and then contains any number of raw characters, + '(?:[^/\\x5B\\x5C' + regexExcls + ']' // escape sequences (\x5C), + '|\\x5C' + regexAny // or non-nesting character sets (\x5B\x5D); + '|\\x5B(?:[^\\x5C\\x5D' + regexExcls + ']' + '|\\x5C' + regexAny + ')*(?:\\x5D|$))+' // finally closed by a /. + '/'); fallthroughStylePatterns.push( ['lang-regex', RegExp('^' + REGEXP_PRECEDER_PATTERN + '(' + REGEX_LITERAL + ')') ]); } var types = options['types']; if (types) { fallthroughStylePatterns.push([PR_TYPE, types]); } var keywords = ("" + options['keywords']).replace(/^ | $/g, ''); if (keywords.length) { fallthroughStylePatterns.push( [PR_KEYWORD, new RegExp('^(?:' + keywords.replace(/[\s,]+/g, '|') + ')\\b'), null]); } shortcutStylePatterns.push([PR_PLAIN, /^\s+/, null, ' \r\n\t\xA0']); var punctuation = // The Bash man page says // A word is a sequence of characters considered as a single // unit by GRUB. Words are separated by metacharacters, // which are the following plus space, tab, and newline: { } // | & $ ; < > // ... // A word beginning with # causes that word and all remaining // characters on that line to be ignored. // which means that only a '#' after /(?:^|[{}|&$;<>\s])/ starts a // comment but empirically // $ echo {#} // {#} // $ echo \$# // $# // $ echo }# // }# // so /(?:^|[|&;<>\s])/ is more appropriate. // http://gcc.gnu.org/onlinedocs/gcc-2.95.3/cpp_1.html#SEC3 // suggests that this definition is compatible with a // default mode that tries to use a single token definition // to recognize both bash/python style comments and C // preprocessor directives. // This definition of punctuation does not include # in the list of // follow-on exclusions, so # will not be broken before if preceeded // by a punctuation character. We could try to exclude # after // [|&;<>] but that doesn't seem to cause many major problems. // If that does turn out to be a problem, we should change the below // when hc is truthy to include # in the run of punctuation characters // only when not followint [|&;<>]. '^.[^\\s\\w.$@\'"`/\\\\]*'; if (options['regexLiterals']) { punctuation += '(?!\s*\/)'; } fallthroughStylePatterns.push( // TODO(mikesamuel): recognize non-latin letters and numerals in idents [PR_LITERAL, /^@[a-z_$][a-z_$@0-9]*/i, null], [PR_TYPE, /^(?:[@_]?[A-Z]+[a-z][A-Za-z_$@0-9]*|\w+_t\b)/, null], [PR_PLAIN, /^[a-z_$][a-z_$@0-9]*/i, null], [PR_LITERAL, new RegExp( '^(?:' // A hex number + '0x[a-f0-9]+' // or an octal or decimal number, + '|(?:\\d(?:_\\d+)*\\d*(?:\\.\\d*)?|\\.\\d\\+)' // possibly in scientific notation + '(?:e[+\\-]?\\d+)?' + ')' // with an optional modifier like UL for unsigned long + '[a-z]*', 'i'), null, '0123456789'], // Don't treat escaped quotes in bash as starting strings. // See issue 144. [PR_PLAIN, /^\\[\s\S]?/, null], [PR_PUNCTUATION, new RegExp(punctuation), null]); return createSimpleLexer(shortcutStylePatterns, fallthroughStylePatterns); } var decorateSource = sourceDecorator({ 'keywords': ALL_KEYWORDS, 'hashComments': true, 'cStyleComments': true, 'multiLineStrings': true, 'regexLiterals': true }); /** * Given a DOM subtree, wraps it in a list, and puts each line into its own * list item. * * @param {Node} node modified in place. Its content is pulled into an * HTMLOListElement, and each line is moved into a separate list item. * This requires cloning elements, so the input might not have unique * IDs after numbering. * @param {boolean} isPreformatted true iff white-space in text nodes should * be treated as significant. */ function numberLines(node, opt_startLineNum, isPreformatted) { var nocode = /(?:^|\s)nocode(?:\s|$)/; var lineBreak = /\r\n?|\n/; var document = node.ownerDocument; var li = document.createElement('li'); while (node.firstChild) { li.appendChild(node.firstChild); } // An array of lines. We split below, so this is initialized to one // un-split line. var listItems = [li]; function walk(node) { var type = node.nodeType; if (type == 1 && !nocode.test(node.className)) { // Element if ('br' === node.nodeName) { breakAfter(node); // Discard the <BR> since it is now flush against a </LI>. if (node.parentNode) { node.parentNode.removeChild(node); } } else { for (var child = node.firstChild; child; child = child.nextSibling) { walk(child); } } } else if ((type == 3 || type == 4) && isPreformatted) { // Text var text = node.nodeValue; var match = text.match(lineBreak); if (match) { var firstLine = text.substring(0, match.index); node.nodeValue = firstLine; var tail = text.substring(match.index + match[0].length); if (tail) { var parent = node.parentNode; parent.insertBefore( document.createTextNode(tail), node.nextSibling); } breakAfter(node); if (!firstLine) { // Don't leave blank text nodes in the DOM. node.parentNode.removeChild(node); } } } } // Split a line after the given node. function breakAfter(lineEndNode) { // If there's nothing to the right, then we can skip ending the line // here, and move root-wards since splitting just before an end-tag // would require us to create a bunch of empty copies. while (!lineEndNode.nextSibling) { lineEndNode = lineEndNode.parentNode; if (!lineEndNode) { return; } } function breakLeftOf(limit, copy) { // Clone shallowly if this node needs to be on both sides of the break. var rightSide = copy ? limit.cloneNode(false) : limit; var parent = limit.parentNode; if (parent) { // We clone the parent chain. // This helps us resurrect important styling elements that cross lines. // E.g. in <i>Foo<br>Bar</i> // should be rewritten to <li><i>Foo</i></li><li><i>Bar</i></li>. var parentClone = breakLeftOf(parent, 1); // Move the clone and everything to the right of the original // onto the cloned parent. var next = limit.nextSibling; parentClone.appendChild(rightSide); for (var sibling = next; sibling; sibling = next) { next = sibling.nextSibling; parentClone.appendChild(sibling); } } return rightSide; } var copiedListItem = breakLeftOf(lineEndNode.nextSibling, 0); // Walk the parent chain until we reach an unattached LI. for (var parent; // Check nodeType since IE invents document fragments. (parent = copiedListItem.parentNode) && parent.nodeType === 1;) { copiedListItem = parent; } // Put it on the list of lines for later processing. listItems.push(copiedListItem); } // Split lines while there are lines left to split. for (var i = 0; // Number of lines that have been split so far. i < listItems.length; // length updated by breakAfter calls. ++i) { walk(listItems[i]); } // Make sure numeric indices show correctly. if (opt_startLineNum === (opt_startLineNum|0)) { listItems[0].setAttribute('value', opt_startLineNum); } var ol = document.createElement('ol'); ol.className = 'linenums'; var offset = Math.max(0, ((opt_startLineNum - 1 /* zero index */)) | 0) || 0; for (var i = 0, n = listItems.length; i < n; ++i) { li = listItems[i]; // Stick a class on the LIs so that stylesheets can // color odd/even rows, or any other row pattern that // is co-prime with 10. li.className = 'L' + ((i + offset) % 10); if (!li.firstChild) { li.appendChild(document.createTextNode('\xA0')); } ol.appendChild(li); } node.appendChild(ol); } /** * Breaks {@code job.sourceCode} around style boundaries in * {@code job.decorations} and modifies {@code job.sourceNode} in place. * @param {Object} job like <pre>{ * sourceCode: {string} source as plain text, * sourceNode: {HTMLElement} the element containing the source, * spans: {Array.<number|Node>} alternating span start indices into source * and the text node or element (e.g. {@code <BR>}) corresponding to that * span. * decorations: {Array.<number|string} an array of style classes preceded * by the position at which they start in job.sourceCode in order * }</pre> * @private */ function recombineTagsAndDecorations(job) { var isIE8OrEarlier = /\bMSIE\s(\d+)/.exec(navigator.userAgent); isIE8OrEarlier = isIE8OrEarlier && +isIE8OrEarlier[1] <= 8; var newlineRe = /\n/g; var source = job.sourceCode; var sourceLength = source.length; // Index into source after the last code-unit recombined. var sourceIndex = 0; var spans = job.spans; var nSpans = spans.length; // Index into spans after the last span which ends at or before sourceIndex. var spanIndex = 0; var decorations = job.decorations; var nDecorations = decorations.length; // Index into decorations after the last decoration which ends at or before // sourceIndex. var decorationIndex = 0; // Remove all zero-length decorations. decorations[nDecorations] = sourceLength; var decPos, i; for (i = decPos = 0; i < nDecorations;) { if (decorations[i] !== decorations[i + 2]) { decorations[decPos++] = decorations[i++]; decorations[decPos++] = decorations[i++]; } else { i += 2; } } nDecorations = decPos; // Simplify decorations. for (i = decPos = 0; i < nDecorations;) { var startPos = decorations[i]; // Conflate all adjacent decorations that use the same style. var startDec = decorations[i + 1]; var end = i + 2; while (end + 2 <= nDecorations && decorations[end + 1] === startDec) { end += 2; } decorations[decPos++] = startPos; decorations[decPos++] = startDec; i = end; } nDecorations = decorations.length = decPos; var sourceNode = job.sourceNode; var oldDisplay; if (sourceNode) { oldDisplay = sourceNode.style.display; sourceNode.style.display = 'none'; } try { var decoration = null; while (spanIndex < nSpans) { var spanStart = spans[spanIndex]; var spanEnd = spans[spanIndex + 2] || sourceLength; var decEnd = decorations[decorationIndex + 2] || sourceLength; var end = Math.min(spanEnd, decEnd); var textNode = spans[spanIndex + 1]; var styledText; if (textNode.nodeType !== 1 // Don't muck with <BR>s or <LI>s // Don't introduce spans around empty text nodes. && (styledText = source.substring(sourceIndex, end))) { // This may seem bizarre, and it is. Emitting LF on IE causes the // code to display with spaces instead of line breaks. // Emitting Windows standard issue linebreaks (CRLF) causes a blank // space to appear at the beginning of every line but the first. // Emitting an old Mac OS 9 line separator makes everything spiffy. if (isIE8OrEarlier) { styledText = styledText.replace(newlineRe, '\r'); } textNode.nodeValue = styledText; var document = textNode.ownerDocument; var span = document.createElement('span'); span.className = decorations[decorationIndex + 1]; var parentNode = textNode.parentNode; parentNode.replaceChild(span, textNode); span.appendChild(textNode); if (sourceIndex < spanEnd) { // Split off a text node. spans[spanIndex + 1] = textNode // TODO: Possibly optimize by using '' if there's no flicker. = document.createTextNode(source.substring(end, spanEnd)); parentNode.insertBefore(textNode, span.nextSibling); } } sourceIndex = end; if (sourceIndex >= spanEnd) { spanIndex += 2; } if (sourceIndex >= decEnd) { decorationIndex += 2; } } } finally { if (sourceNode) { sourceNode.style.display = oldDisplay; } } } /** Maps language-specific file extensions to handlers. */ var langHandlerRegistry = {}; /** Register a language handler for the given file extensions. * @param {function (Object)} handler a function from source code to a list * of decorations. Takes a single argument job which describes the * state of the computation. The single parameter has the form * {@code { * sourceCode: {string} as plain text. * decorations: {Array.<number|string>} an array of style classes * preceded by the position at which they start in * job.sourceCode in order. * The language handler should assigned this field. * basePos: {int} the position of source in the larger source chunk. * All positions in the output decorations array are relative * to the larger source chunk. * } } * @param {Array.<string>} fileExtensions */ function registerLangHandler(handler, fileExtensions) { for (var i = fileExtensions.length; --i >= 0;) { var ext = fileExtensions[i]; if (!langHandlerRegistry.hasOwnProperty(ext)) { langHandlerRegistry[ext] = handler; } else if (win['console']) { console['warn']('cannot override language handler %s', ext); } } } function langHandlerForExtension(extension, source) { if (!(extension && langHandlerRegistry.hasOwnProperty(extension))) { // Treat it as markup if the first non whitespace character is a < and // the last non-whitespace character is a >. extension = /^\s*</.test(source) ? 'default-markup' : 'default-code'; } return langHandlerRegistry[extension]; } registerLangHandler(decorateSource, ['default-code']); registerLangHandler( createSimpleLexer( [], [ [PR_PLAIN, /^[^<?]+/], [PR_DECLARATION, /^<!\w[^>]*(?:>|$)/], [PR_COMMENT, /^<\!--[\s\S]*?(?:-\->|$)/], // Unescaped content in an unknown language ['lang-', /^<\?([\s\S]+?)(?:\?>|$)/], ['lang-', /^<%([\s\S]+?)(?:%>|$)/], [PR_PUNCTUATION, /^(?:<[%?]|[%?]>)/], ['lang-', /^<xmp\b[^>]*>([\s\S]+?)<\/xmp\b[^>]*>/i], // Unescaped content in javascript. (Or possibly vbscript). ['lang-js', /^<script\b[^>]*>([\s\S]*?)(<\/script\b[^>]*>)/i], // Contains unescaped stylesheet content ['lang-css', /^<style\b[^>]*>([\s\S]*?)(<\/style\b[^>]*>)/i], ['lang-in.tag', /^(<\/?[a-z][^<>]*>)/i] ]), ['default-markup', 'htm', 'html', 'mxml', 'xhtml', 'xml', 'xsl']); registerLangHandler( createSimpleLexer( [ [PR_PLAIN, /^[\s]+/, null, ' \t\r\n'], [PR_ATTRIB_VALUE, /^(?:\"[^\"]*\"?|\'[^\']*\'?)/, null, '\"\''] ], [ [PR_TAG, /^^<\/?[a-z](?:[\w.:-]*\w)?|\/?>$/i], [PR_ATTRIB_NAME, /^(?!style[\s=]|on)[a-z](?:[\w:-]*\w)?/i], ['lang-uq.val', /^=\s*([^>\'\"\s]*(?:[^>\'\"\s\/]|\/(?=\s)))/], [PR_PUNCTUATION, /^[=<>\/]+/], ['lang-js', /^on\w+\s*=\s*\"([^\"]+)\"/i], ['lang-js', /^on\w+\s*=\s*\'([^\']+)\'/i], ['lang-js', /^on\w+\s*=\s*([^\"\'>\s]+)/i], ['lang-css', /^style\s*=\s*\"([^\"]+)\"/i], ['lang-css', /^style\s*=\s*\'([^\']+)\'/i], ['lang-css', /^style\s*=\s*([^\"\'>\s]+)/i] ]), ['in.tag']); registerLangHandler( createSimpleLexer([], [[PR_ATTRIB_VALUE, /^[\s\S]+/]]), ['uq.val']); registerLangHandler(sourceDecorator({ 'keywords': CPP_KEYWORDS, 'hashComments': true, 'cStyleComments': true, 'types': C_TYPES }), ['c', 'cc', 'cpp', 'cxx', 'cyc', 'm']); registerLangHandler(sourceDecorator({ 'keywords': 'null,true,false' }), ['json']); registerLangHandler(sourceDecorator({ 'keywords': CSHARP_KEYWORDS, 'hashComments': true, 'cStyleComments': true, 'verbatimStrings': true, 'types': C_TYPES }), ['cs']); registerLangHandler(sourceDecorator({ 'keywords': JAVA_KEYWORDS, 'cStyleComments': true }), ['java']); registerLangHandler(sourceDecorator({ 'keywords': SH_KEYWORDS, 'hashComments': true, 'multiLineStrings': true }), ['bash', 'bsh', 'csh', 'sh']); registerLangHandler(sourceDecorator({ 'keywords': PYTHON_KEYWORDS, 'hashComments': true, 'multiLineStrings': true, 'tripleQuotedStrings': true }), ['cv', 'py', 'python']); registerLangHandler(sourceDecorator({ 'keywords': PERL_KEYWORDS, 'hashComments': true, 'multiLineStrings': true, 'regexLiterals': 2 // multiline regex literals }), ['perl', 'pl', 'pm']); registerLangHandler(sourceDecorator({ 'keywords': RUBY_KEYWORDS, 'hashComments': true, 'multiLineStrings': true, 'regexLiterals': true }), ['rb', 'ruby']); registerLangHandler(sourceDecorator({ 'keywords': JSCRIPT_KEYWORDS, 'cStyleComments': true, 'regexLiterals': true }), ['javascript', 'js']); registerLangHandler(sourceDecorator({ 'keywords': COFFEE_KEYWORDS, 'hashComments': 3, // ### style block comments 'cStyleComments': true, 'multilineStrings': true, 'tripleQuotedStrings': true, 'regexLiterals': true }), ['coffee']); registerLangHandler(sourceDecorator({ 'keywords': RUST_KEYWORDS, 'cStyleComments': true, 'multilineStrings': true }), ['rc', 'rs', 'rust']); registerLangHandler( createSimpleLexer([], [[PR_STRING, /^[\s\S]+/]]), ['regex']); function applyDecorator(job) { var opt_langExtension = job.langExtension; try { // Extract tags, and convert the source code to plain text. var sourceAndSpans = extractSourceSpans(job.sourceNode, job.pre); /** Plain text. @type {string} */ var source = sourceAndSpans.sourceCode; job.sourceCode = source; job.spans = sourceAndSpans.spans; job.basePos = 0; // Apply the appropriate language handler langHandlerForExtension(opt_langExtension, source)(job); // Integrate the decorations and tags back into the source code, // modifying the sourceNode in place. recombineTagsAndDecorations(job); } catch (e) { if (win['console']) { console['log'](e && e['stack'] || e); } } } /** * Pretty print a chunk of code. * @param sourceCodeHtml {string} The HTML to pretty print. * @param opt_langExtension {string} The language name to use. * Typically, a filename extension like 'cpp' or 'java'. * @param opt_numberLines {number|boolean} True to number lines, * or the 1-indexed number of the first line in sourceCodeHtml. */ function $prettyPrintOne(sourceCodeHtml, opt_langExtension, opt_numberLines) { var container = document.createElement('div'); // This could cause images to load and onload listeners to fire. // E.g. <img onerror="alert(1337)" src="nosuchimage.png">. // We assume that the inner HTML is from a trusted source. // The pre-tag is required for IE8 which strips newlines from innerHTML // when it is injected into a <pre> tag. // http://stackoverflow.com/questions/451486/pre-tag-loses-line-breaks-when-setting-innerhtml-in-ie // http://stackoverflow.com/questions/195363/inserting-a-newline-into-a-pre-tag-ie-javascript container.innerHTML = '<pre>' + sourceCodeHtml + '</pre>'; container = container.firstChild; if (opt_numberLines) { numberLines(container, opt_numberLines, true); } var job = { langExtension: opt_langExtension, numberLines: opt_numberLines, sourceNode: container, pre: 1 }; applyDecorator(job); return container.innerHTML; } /** * Find all the {@code <pre>} and {@code <code>} tags in the DOM with * {@code class=prettyprint} and prettify them. * * @param {Function} opt_whenDone called when prettifying is done. * @param {HTMLElement|HTMLDocument} opt_root an element or document * containing all the elements to pretty print. * Defaults to {@code document.body}. */ function $prettyPrint(opt_whenDone, opt_root) { var root = opt_root || document.body; var doc = root.ownerDocument || document; function byTagName(tn) { return root.getElementsByTagName(tn); } // fetch a list of nodes to rewrite var codeSegments = [byTagName('pre'), byTagName('code'), byTagName('xmp')]; var elements = []; for (var i = 0; i < codeSegments.length; ++i) { for (var j = 0, n = codeSegments[i].length; j < n; ++j) { elements.push(codeSegments[i][j]); } } codeSegments = null; var clock = Date; if (!clock['now']) { clock = { 'now': function () { return +(new Date); } }; } // The loop is broken into a series of continuations to make sure that we // don't make the browser unresponsive when rewriting a large page. var k = 0; var prettyPrintingJob; var langExtensionRe = /\blang(?:uage)?-([\w.]+)(?!\S)/; var prettyPrintRe = /\bprettyprint\b/; var prettyPrintedRe = /\bprettyprinted\b/; var preformattedTagNameRe = /pre|xmp/i; var codeRe = /^code$/i; var preCodeXmpRe = /^(?:pre|code|xmp)$/i; var EMPTY = {}; function doWork() { var endTime = (win['PR_SHOULD_USE_CONTINUATION'] ? clock['now']() + 250 /* ms */ : Infinity); for (; k < elements.length && clock['now']() < endTime; k++) { var cs = elements[k]; // Look for a preceding comment like // <?prettify lang="..." linenums="..."?> var attrs = EMPTY; { for (var preceder = cs; (preceder = preceder.previousSibling);) { var nt = preceder.nodeType; // <?foo?> is parsed by HTML 5 to a comment node (8) // like <!--?foo?-->, but in XML is a processing instruction var value = (nt === 7 || nt === 8) && preceder.nodeValue; if (value ? !/^\??prettify\b/.test(value) : (nt !== 3 || /\S/.test(preceder.nodeValue))) { // Skip over white-space text nodes but not others. break; } if (value) { attrs = {}; value.replace( /\b(\w+)=([\w:.%+-]+)/g, function (_, name, value) { attrs[name] = value; }); break; } } } var className = cs.className; if ((attrs !== EMPTY || prettyPrintRe.test(className)) // Don't redo this if we've already done it. // This allows recalling pretty print to just prettyprint elements // that have been added to the page since last call. && !prettyPrintedRe.test(className)) { // make sure this is not nested in an already prettified element var nested = false; for (var p = cs.parentNode; p; p = p.parentNode) { var tn = p.tagName; if (preCodeXmpRe.test(tn) && p.className && prettyPrintRe.test(p.className)) { nested = true; break; } } if (!nested) { // Mark done. If we fail to prettyprint for whatever reason, // we shouldn't try again. cs.className += ' prettyprinted'; // If the classes includes a language extensions, use it. // Language extensions can be specified like // <pre class="prettyprint lang-cpp"> // the language extension "cpp" is used to find a language handler // as passed to PR.registerLangHandler. // HTML5 recommends that a language be specified using "language-" // as the prefix instead. Google Code Prettify supports both. // http://dev.w3.org/html5/spec-author-view/the-code-element.html var langExtension = attrs['lang']; if (!langExtension) { langExtension = className.match(langExtensionRe); // Support <pre class="prettyprint"><code class="language-c"> var wrapper; if (!langExtension && (wrapper = childContentWrapper(cs)) && codeRe.test(wrapper.tagName)) { langExtension = wrapper.className.match(langExtensionRe); } if (langExtension) { langExtension = langExtension[1]; } } var preformatted; if (preformattedTagNameRe.test(cs.tagName)) { preformatted = 1; } else { var currentStyle = cs['currentStyle']; var defaultView = doc.defaultView; var whitespace = ( currentStyle ? currentStyle['whiteSpace'] : (defaultView && defaultView.getComputedStyle) ? defaultView.getComputedStyle(cs, null) .getPropertyValue('white-space') : 0); preformatted = whitespace && 'pre' === whitespace.substring(0, 3); } // Look for a class like linenums or linenums:<n> where <n> is the // 1-indexed number of the first line. var lineNums = attrs['linenums']; if (!(lineNums = lineNums === 'true' || +lineNums)) { lineNums = className.match(/\blinenums\b(?::(\d+))?/); lineNums = lineNums ? lineNums[1] && lineNums[1].length ? +lineNums[1] : true : false; } if (lineNums) { numberLines(cs, lineNums, preformatted); } // do the pretty printing prettyPrintingJob = { langExtension: langExtension, sourceNode: cs, numberLines: lineNums, pre: preformatted }; applyDecorator(prettyPrintingJob); } } } if (k < elements.length) { // finish up in a continuation setTimeout(doWork, 250); } else if ('function' === typeof opt_whenDone) { opt_whenDone(); } } doWork(); } /** * Contains functions for creating and registering new language handlers. * @type {Object} */ var PR = win['PR'] = { 'createSimpleLexer': createSimpleLexer, 'registerLangHandler': registerLangHandler, 'sourceDecorator': sourceDecorator, 'PR_ATTRIB_NAME': PR_ATTRIB_NAME, 'PR_ATTRIB_VALUE': PR_ATTRIB_VALUE, 'PR_COMMENT': PR_COMMENT, 'PR_DECLARATION': PR_DECLARATION, 'PR_KEYWORD': PR_KEYWORD, 'PR_LITERAL': PR_LITERAL, 'PR_NOCODE': PR_NOCODE, 'PR_PLAIN': PR_PLAIN, 'PR_PUNCTUATION': PR_PUNCTUATION, 'PR_SOURCE': PR_SOURCE, 'PR_STRING': PR_STRING, 'PR_TAG': PR_TAG, 'PR_TYPE': PR_TYPE, 'prettyPrintOne': IN_GLOBAL_SCOPE ? (win['prettyPrintOne'] = $prettyPrintOne) : (prettyPrintOne = $prettyPrintOne), 'prettyPrint': prettyPrint = IN_GLOBAL_SCOPE ? (win['prettyPrint'] = $prettyPrint) : (prettyPrint = $prettyPrint) }; // Make PR available via the Asynchronous Module Definition (AMD) API. // Per https://github.com/amdjs/amdjs-api/wiki/AMD: // The Asynchronous Module Definition (AMD) API specifies a // mechanism for defining modules such that the module and its // dependencies can be asynchronously loaded. // ... // To allow a clear indicator that a global define function (as // needed for script src browser loading) conforms to the AMD API, // any global define function SHOULD have a property called "amd" // whose value is an object. This helps avoid conflict with any // other existing JavaScript code that could have defined a define() // function that does not conform to the AMD API. if (typeof define === "function" && define['amd']) { define("google-code-prettify", [], function () { return PR; }); } })();
astamuse/asta4d
162
Java
org.eclipse.core.resources.prefs
text/plain
8,369,713,977,092,266,000
validation.type.name.Integer=integer validation.type.msg={0} is expected but value "{1}" found validation.field.PersonForm.name=expects a string less than 6 characters sample.peoplecount=There are(is) {0} people in the room. sample.weatherreport=Today''s weather is {0}. sample.weatherreport.sunny=good sample.weatherreport.cloudy=not good sample.weatherreport.rain=bad sample.textUrl=Click <a href="http://asta4d.sample.com/">here</a> to contact us. sample.htmlUrl=html:Click <a href="http://asta4d.sample.com/">here</a> to contact us. sample.escapedUrl=text:html:Click <a href="http://asta4d.sample.com/">here</a> to contact us.
astamuse/asta4d
162
Java
org.eclipse.core.resources.prefs
text/plain
-1,360,598,073,190,197,000
validation.type.name.Integer=数字 validation.type.msg={0}を入力してください validation.field.PersonForm.name=六文字以下の文字列を入力してください sample.peoplecount=この部屋に{0}人がいます。 sample.weatherreport=今日の天気は{0}です。 sample.weatherreport.sunny=晴れ sample.weatherreport.cloudy=曇り sample.weatherreport.rain=雨 textUrl=お問い合わせは<a href="http://asta4d.sample.com/">こちら</a>まで。 htmlUrl=html:お問い合わせは<a href="http://asta4d.sample.com/">こちら</a>まで。 escapedUrl=text:html:お問い合わせは<a href="http://asta4d.sample.com/">こちら</a>まで。
astamuse/asta4d
162
Java
org.eclipse.core.resources.prefs
text/plain
3,733,927,631,563,928,600
<?xml version="1.0" encoding="UTF-8"?> <beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:mvc="http://www.springframework.org/schema/mvc" xsi:schemaLocation=" http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-3.0.xsd"> <bean id="asta4dConfiguration" class="com.astamuse.asta4d.web.WebApplicationConfiguration"> <property name="snippetResolver"> <bean class="com.astamuse.asta4d.misc.spring.SpringManagedSnippetResolver"/> </property> <property name="instanceResolverList"> <list> <bean class="com.astamuse.asta4d.misc.spring.SpringManagedInstanceResolver"/> </list> </property> <property name="pageInterceptorList"> <list> <bean class="com.astamuse.asta4d.sample.interceptor.SamplePageInterceptor"/> </list> </property> <property name="snippetInvoker"> <bean id="snippetInvoker" class="com.astamuse.asta4d.snippet.DefaultSnippetInvoker"> <property name="snippetInterceptorList"> <list> <bean class="com.astamuse.asta4d.sample.interceptor.SampleSnippetInterceptor"/> </list> </property> </bean> </property> <property name="urlMappingRuleInitializer"> <bean class="com.astamuse.asta4d.sample.UrlRules"/> </property> </bean> <bean id="ComplicatedSnippet" class="com.astamuse.asta4d.sample.snippet.ComplicatedSnippet" scope="prototype"/> <bean id="FormSnippet" class="com.astamuse.asta4d.sample.snippet.FormSnippet" scope="prototype"/> <bean id="SimpleSnippet" class="com.astamuse.asta4d.sample.snippet.SimpleSnippet" scope="prototype"/> <bean id="ShowCodeSnippet" class="com.astamuse.asta4d.sample.snippet.ShowCodeSnippet" scope="prototype"/> <bean class="com.astamuse.asta4d.sample.handler.LoginHandler"/> </beans>
astamuse/asta4d
162
Java
org.eclipse.core.resources.prefs
text/plain
-7,399,485,811,975,453,000
/* * Copyright 2014 astamuse company,Ltd. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ package com.astamuse.asta4d.sample; import java.util.Locale; import javax.servlet.ServletConfig; import javax.servlet.ServletException; import org.apache.commons.lang3.StringUtils; import com.astamuse.asta4d.sample.interceptor.SamplePageInterceptor; import com.astamuse.asta4d.sample.interceptor.SampleSnippetInterceptor; import com.astamuse.asta4d.snippet.DefaultSnippetInvoker; import com.astamuse.asta4d.util.i18n.LocalizeUtil; import com.astamuse.asta4d.web.WebApplicationConfiguration; import com.astamuse.asta4d.web.WebApplicationContext; import com.astamuse.asta4d.web.servlet.Asta4dServlet; public class Asta4DSampleServlet extends Asta4dServlet { /** * */ private static final long serialVersionUID = 1L; @Override protected WebApplicationConfiguration createConfiguration() { WebApplicationConfiguration conf = super.createConfiguration(); conf.getPageInterceptorList().add(new SamplePageInterceptor()); DefaultSnippetInvoker snippetInvoker = ((DefaultSnippetInvoker) conf.getSnippetInvoker()); snippetInvoker.getSnippetInterceptorList().add(new SampleSnippetInterceptor()); boolean debug = Boolean.getBoolean("asta4d.sample.debug"); if (debug) { conf.setCacheEnable(false); conf.setSaveCallstackInfoOnRendererCreation(true); } return conf; } @Override public void init(ServletConfig config) throws ServletException { // for a international application, we use root as default locale Locale.setDefault(Locale.ROOT); super.init(config); } @Override protected void service() throws Exception { // resolve the locale of current request // for a formal web application, the locale should be resolved from the head sent by client browser, // but as a sample project, we use a simple way to decide the locale to simplify the logic WebApplicationContext context = WebApplicationContext.getCurrentThreadWebApplicationContext(); String locale = context.getRequest().getParameter("locale"); if (StringUtils.isNotEmpty(locale)) { context.setCurrentLocale(LocalizeUtil.getLocale(locale)); } super.service(); } }
astamuse/asta4d
162
Java
org.eclipse.core.resources.prefs
text/plain
-976,328,036,530,319,900
/* * Copyright 2012 astamuse company,Ltd. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ package com.astamuse.asta4d.sample; import static com.astamuse.asta4d.web.dispatch.HttpMethod.GET; import static com.astamuse.asta4d.web.dispatch.HttpMethod.PUT; import com.astamuse.asta4d.sample.forward.LoginFailure; import com.astamuse.asta4d.sample.handler.AddUserHandler; import com.astamuse.asta4d.sample.handler.EchoHandler; import com.astamuse.asta4d.sample.handler.GetUserListHandler; import com.astamuse.asta4d.sample.handler.LoginHandler; import com.astamuse.asta4d.sample.handler.form.cascade.CascadeFormHandler; import com.astamuse.asta4d.sample.handler.form.multiinput.MultiInputFormHandler; import com.astamuse.asta4d.sample.handler.form.multistep.MultiStepFormHandler; import com.astamuse.asta4d.sample.handler.form.singlestep.SingleStepFormHandler; import com.astamuse.asta4d.sample.handler.form.splittedinput.SplittedInputFormHandler; import com.astamuse.asta4d.web.builtin.StaticResourceHandler; import com.astamuse.asta4d.web.dispatch.HttpMethod; import com.astamuse.asta4d.web.dispatch.mapping.UrlMappingRuleInitializer; import com.astamuse.asta4d.web.dispatch.mapping.handy.HandyRuleSet; import com.astamuse.asta4d.web.dispatch.request.RequestHandler; import com.astamuse.asta4d.web.form.flow.classical.ClassicalMultiStepFormFlowHandlerTrait; import com.astamuse.asta4d.web.form.flow.classical.OneStepFormHandlerTrait; public class UrlRules implements UrlMappingRuleInitializer<HandyRuleSet<?, ?>> { @Override public void initUrlMappingRules(HandyRuleSet<?, ?> rules) { // global error handling // @ShowCode:showGlobal404RuleStart rules.addGlobalForward(PageNotFoundException.class, "/templates/errors/404.html", 404); // @ShowCode:showGlobal404RuleEnd // @ShowCode:showGlobalErrorRuleStart rules.addGlobalForward(Throwable.class, "/templates/errors/500.html", 500); // @ShowCode:showGlobalErrorRuleEnd //@formatter:off rules.add("/", "/templates/index.html"); rules.add("/index", "/templates/index.html"); rules.add(GET, "/redirect-to-index").redirect("p:/index"); initSampleRules(rules); //@formatter:on } private void initSampleRules(HandyRuleSet<?, ?> rules) { //@formatter:off rules.add("/js/**/*").handler(new StaticResourceHandler()); rules.add("/css/**/*").handler(new StaticResourceHandler()); rules.add("/snippet", "/templates/snippet.html"); // @ShowCode:showVariableinjectionStart rules.add("/var-injection/{name}/{age}", "/templates/variableinjection.html").priority(1); // @ShowCode:showVariableinjectionEnd rules.add("/attributevalues", "/templates/attributevalues.html"); rules.add("/extend/{target}").handler(new Object(){ @RequestHandler public String handle(String target){ return "/templates/extend/"+target+".html"; } }); rules.add("/embed/main", "/templates/embed/main.html"); rules.add("/ajax/getUserList").handler(GetUserListHandler.class).json(); rules.add(PUT, "/ajax/addUser").handler(AddUserHandler.class).xml(); // @ShowCode:showSuccessStart rules.add("/handler") .handler(LoginHandler.class) .handler(EchoHandler.class) .forward(LoginFailure.class, "/templates/error.html") .forward("/templates/success.html"); // @ShowCode:showSuccessEnd rules.add("/renderertypes", "/templates/renderertypes.html"); rules.add("/passvariables", "/templates/passvariables.html"); rules.add("/dynamicsnippet", "/templates/dynamicsnippet.html"); rules.add("/contextdata", "/templates/contextdata.html"); rules.add("/form", "/templates/form/list.html"); // @ShowCode:showSingleStepStart rules.add((HttpMethod)null, "/form/singlestep") //specify the target template file of input page by path var .var(OneStepFormHandlerTrait.VAR_INPUT_TEMPLATE_FILE, "/templates/form/singlestep/edit.html") .handler(SingleStepFormHandler.class) //specify the exit target .redirect("/form?type=singlestep"); // @ShowCode:showSingleStepEnd // @ShowCode:showMultiStepStart rules.add((HttpMethod)null, "/form/multistep") //specify the base path of target template file by path var .var(ClassicalMultiStepFormFlowHandlerTrait.VAR_TEMPLATE_BASE_PATH, "/templates/form/multistep/") .handler(MultiStepFormHandler.class) //specify the exit target .redirect("/form?type=multistep"); // @ShowCode:showMultiStepEnd // @ShowCode:showCascadeStart rules.add((HttpMethod)null, "/form/cascade/add") //specify the base path of target template file by overriding .handler(new CascadeFormHandler.Add(){ @Override public String getTemplateBasePath() { // TODO Auto-generated method stub return "/templates/form/cascade/"; } }) //specify the exit target .redirect("/form?type=cascade"); rules.add((HttpMethod)null, "/form/cascade/edit") //specify the base path of target template file by path var .var(ClassicalMultiStepFormFlowHandlerTrait.VAR_TEMPLATE_BASE_PATH, "/templates/form/cascade/") .handler(CascadeFormHandler.Edit.class) //specify the exit target .redirect("/form?type=cascade"); // @ShowCode:showCascadeEnd // @ShowCode:showMultiInputStart rules.add((HttpMethod)null, "/form/multiinput/add") //specify the base path of target template file by path var .var(ClassicalMultiStepFormFlowHandlerTrait.VAR_TEMPLATE_BASE_PATH, "/templates/form/multiinput/") .handler(MultiInputFormHandler.Add.class) //specify the exit target .redirect("/form?type=multiinput"); rules.add((HttpMethod)null, "/form/multiinput/edit") //specify the base path of target template file by path var .var(ClassicalMultiStepFormFlowHandlerTrait.VAR_TEMPLATE_BASE_PATH, "/templates/form/multiinput/") .handler(MultiInputFormHandler.Edit.class) //specify the exit target .redirect("/form?type=multiinput"); // @ShowCode:showMultiInputEnd // @ShowCode:showSplittedInputStart rules.add((HttpMethod)null, "/form/splittedinput/add") //specify the base path of target template file by path var .var(ClassicalMultiStepFormFlowHandlerTrait.VAR_TEMPLATE_BASE_PATH, "/templates/form/splittedinput/") .handler(SplittedInputFormHandler.Add.class) //specify the exit target .redirect("/form?type=splittedinput"); rules.add((HttpMethod)null, "/form/splittedinput/edit") //specify the base path of target template file by path var .var(ClassicalMultiStepFormFlowHandlerTrait.VAR_TEMPLATE_BASE_PATH, "/templates/form/splittedinput/") .handler(SplittedInputFormHandler.Edit.class) //specify the exit target .redirect("/form?type=splittedinput"); // @ShowCode:showSplittedInputEnd rules.add("/localize", "/templates/localize.html"); rules.add("/error-sample/handler").handler(new Object(){ @RequestHandler public void handle(){ throw new RuntimeException("error in /error-sample/handler"); } }); rules.add("/error-sample/handler404").handler(new Object(){ @RequestHandler public void handle(){ throw new PageNotFoundException(); } }); rules.add("/error-sample/snippet", "/templates/snippet-error.html"); //@formatter:on } }
astamuse/asta4d
162
Java
org.eclipse.core.resources.prefs
text/plain
965,652,003,775,715,300
/* * Copyright 2014 astamuse company,Ltd. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ package com.astamuse.asta4d.sample; public class PageNotFoundException extends RuntimeException { /** * */ private static final long serialVersionUID = 1L; public PageNotFoundException() { super(); } }
astamuse/asta4d
162
Java
org.eclipse.core.resources.prefs
text/plain
5,559,006,806,561,497,000
/* * Copyright 2012 astamuse company,Ltd. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ package com.astamuse.asta4d.sample.handler; import org.apache.commons.lang3.StringUtils; import com.astamuse.asta4d.sample.forward.LoginFailure; import com.astamuse.asta4d.web.dispatch.request.RequestHandler; //@ShowCode:showSuccessStart public class LoginHandler { @RequestHandler public LoginFailure doLogin(String flag) throws LoginFailure { if (StringUtils.isEmpty(flag)) { return null; } if ("error".equals(flag)) { throw new LoginFailure(); } if (!Boolean.parseBoolean(flag)) { return new LoginFailure(); } return null; } } // @ShowCode:showSuccessEnd
astamuse/asta4d
162
Java
org.eclipse.core.resources.prefs
text/plain
8,970,472,410,015,160,000
/* * Copyright 2012 astamuse company,Ltd. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ package com.astamuse.asta4d.sample.handler; import java.util.Arrays; import java.util.List; import com.astamuse.asta4d.web.dispatch.request.RequestHandler; public class GetUserListHandler { @RequestHandler public List<String> queryUserList() { return Arrays.asList("otani", "ryu", "mizuhara"); } }
astamuse/asta4d
162
Java
org.eclipse.core.resources.prefs
text/plain
3,804,704,139,947,181,000
/* * Copyright 2012 astamuse company,Ltd. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ package com.astamuse.asta4d.sample.handler; import java.util.HashMap; import java.util.Map; import com.astamuse.asta4d.web.dispatch.request.RequestHandler; import com.astamuse.asta4d.web.dispatch.response.provider.RedirectTargetProvider; public class FormCompleteHandler { @RequestHandler public Object complete(String name, String age, String bloodtype, String submit, String cancel) { if (cancel != null) { Map<String, Object> flashScopeData = new HashMap<>(); flashScopeData.put("name", name); flashScopeData.put("age", age); flashScopeData.put("bloodtype", bloodtype); return new RedirectTargetProvider("/app/form/input", flashScopeData); } if (submit != null) { System.out.println("[FormCompleteHandler:complete]" + String.format("name=%s, age=%s, bloodtype=%s", name, age, bloodtype)); return "/templates/form/complete.html"; } throw new IllegalStateException(); } }
astamuse/asta4d
162
Java
org.eclipse.core.resources.prefs
text/plain
6,946,342,859,886,401,000
/* * Copyright 2012 astamuse company,Ltd. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ package com.astamuse.asta4d.sample.handler; import java.util.HashMap; import java.util.Map; import org.apache.commons.lang3.StringUtils; import com.astamuse.asta4d.web.dispatch.request.RequestHandler; import com.astamuse.asta4d.web.dispatch.response.provider.RedirectTargetProvider; //@ShowCode:showFormValidateHandlerStart public class FormValidateHandler { @RequestHandler public Object complete(String name, String age, String bloodtype) { String nameErrMsg = null; String ageErrMsg = null; if (StringUtils.isEmpty(name)) { nameErrMsg = "name is required."; } if (StringUtils.isEmpty(age)) { ageErrMsg = "age is required."; } else { try { Integer.valueOf(age); } catch (NumberFormatException e) { ageErrMsg = "age must be numeric value."; } } if (nameErrMsg == null && ageErrMsg == null) { return "/templates/form/confirm.html"; } else { Map<String, Object> flashScopeData = new HashMap<>(); flashScopeData.put("name", name); flashScopeData.put("age", age); flashScopeData.put("bloodtype", bloodtype); flashScopeData.put("nameErrMsg", nameErrMsg); flashScopeData.put("ageErrMsg", ageErrMsg); return new RedirectTargetProvider("/app/form/input", flashScopeData); } } } // @ShowCode:showFormValidateHandlerEnd
astamuse/asta4d
162
Java
org.eclipse.core.resources.prefs
text/plain
9,040,026,626,200,073,000
/* * Copyright 2012 astamuse company,Ltd. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ package com.astamuse.asta4d.sample.handler; import org.apache.commons.lang3.StringUtils; import com.astamuse.asta4d.web.dispatch.request.RequestHandler; public class EchoHandler { @RequestHandler public void echo(String value) { if (StringUtils.isEmpty(value)) { value = "hello!"; } System.out.println("[EchoHandler:echo]" + value); } }
astamuse/asta4d
162
Java
org.eclipse.core.resources.prefs
text/plain
37,071,052,579,815,944
/* * Copyright 2012 astamuse company,Ltd. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ package com.astamuse.asta4d.sample.handler; import com.astamuse.asta4d.web.dispatch.request.RequestHandler; import com.astamuse.asta4d.web.dispatch.response.provider.HeaderInfoProvider; public class AddUserHandler { @RequestHandler public HeaderInfoProvider doAdd(String newUserName) { // some logic that should add a new user by the given name // ... return new HeaderInfoProvider(200); } }
astamuse/asta4d
162
Java
org.eclipse.core.resources.prefs
text/plain
-7,822,652,259,839,176,000
/* * Copyright 2014 astamuse company,Ltd. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ package com.astamuse.asta4d.sample.handler.form; import java.lang.reflect.InvocationTargetException; import javax.validation.constraints.NotNull; import org.apache.commons.beanutils.BeanUtils; import org.hibernate.validator.constraints.NotEmpty; import com.astamuse.asta4d.sample.util.persondb.Person; import com.astamuse.asta4d.web.form.annotation.Form; import com.astamuse.asta4d.web.form.annotation.renderable.Checkbox; import com.astamuse.asta4d.web.form.annotation.renderable.Hidden; import com.astamuse.asta4d.web.form.annotation.renderable.Input; import com.astamuse.asta4d.web.form.annotation.renderable.Radio; import com.astamuse.asta4d.web.form.annotation.renderable.Select; import com.astamuse.asta4d.web.form.annotation.renderable.Textarea; //@ShowCode:showPersonFormStart //@Form to tell the framework this class can be initialized from context //extend from the entity POJO to annotate form field definitions on getters. @Form public class PersonForm extends Person { public static PersonForm buildFromPerson(Person p) { PersonForm form = new PersonForm(); try { BeanUtils.copyProperties(form, p); } catch (IllegalAccessException | InvocationTargetException e) { throw new RuntimeException(e); } return form; } @Override @Hidden public Integer getId() { return super.getId(); } @Override @Input public String getName() { return super.getName(); } @Override @Input public Integer getAge() { return super.getAge(); } @Override @Select(name = "bloodtype") @NotNull public BloodType getBloodType() { return super.getBloodType(); } // the field name would be displayed as "gender" rather than the original field name "sex" @Override @Radio(nameLabel = "gender") @NotNull public SEX getSex() { return super.getSex(); } @Override @Checkbox @NotEmpty public Language[] getLanguage() { return super.getLanguage(); } @Override @Textarea public String getMemo() { return super.getMemo(); } } // @ShowCode:showPersonFormEnd
astamuse/asta4d
162
Java
org.eclipse.core.resources.prefs
text/plain
-1,924,472,563,594,141,700
/* * Copyright 2014 astamuse company,Ltd. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ package com.astamuse.asta4d.sample.handler.form; import java.lang.reflect.InvocationTargetException; import org.apache.commons.beanutils.BeanUtils; import com.astamuse.asta4d.sample.util.persondb.JobPosition; import com.astamuse.asta4d.web.form.annotation.renderable.Hidden; import com.astamuse.asta4d.web.form.annotation.renderable.Input; //@ShowCode:showJobPositionFormStart public class JobPositionForm extends JobPosition { public static JobPositionForm buildFromJobPosition(JobPosition job) { JobPositionForm form = new JobPositionForm(); try { BeanUtils.copyProperties(form, job); } catch (IllegalAccessException | InvocationTargetException e) { throw new RuntimeException(e); } return form; } // for arrayed form, all the field names must contain a "@" mark which will be rewritten to array index by framework. @Override @Hidden(name = "job-position-id-@-@@") public Integer getId() { return super.getId(); } @Override @Hidden(name = "job-position-job-id-@-@@") public Integer getJobId() { return super.getJobId(); } @Override @Input(name = "job-position-name-@-@@") public String getName() { return super.getName(); } } // @ShowCode:showJobPositionFormEnd
astamuse/asta4d
162
Java
org.eclipse.core.resources.prefs
text/plain
-3,256,466,681,969,965,600
/* * Copyright 2014 astamuse company,Ltd. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ package com.astamuse.asta4d.sample.handler.form; import java.lang.reflect.InvocationTargetException; import javax.validation.Valid; import org.apache.commons.beanutils.BeanUtils; import org.hibernate.validator.constraints.NotEmpty; import com.astamuse.asta4d.sample.util.persondb.JobExperence; import com.astamuse.asta4d.web.form.annotation.CascadeFormField; import com.astamuse.asta4d.web.form.annotation.renderable.AvailableWhenEditOnly; import com.astamuse.asta4d.web.form.annotation.renderable.Hidden; import com.astamuse.asta4d.web.form.annotation.renderable.Input; import com.astamuse.asta4d.web.form.annotation.renderable.Select; //@ShowCode:showJobFormStart public class JobForm extends JobExperence { public static JobForm buildFromJob(JobExperence job) { JobForm form = new JobForm(); try { BeanUtils.copyProperties(form, job); } catch (IllegalAccessException | InvocationTargetException e) { throw new RuntimeException(e); } return form; } public JobForm() { jobPositionForms = new JobPositionForm[0]; jobPositionLength = jobPositionForms.length; } @Hidden(name = "job-position-length-@") private Integer jobPositionLength; // a field with @CascadeFormField with arrayLengthField configured will be treated an array field @CascadeFormField(name = "job-position-@", arrayLengthField = "job-position-length-@", containerSelector = "[cascade-ref=job-position-row-@-@@]") @Valid @NotEmpty private JobPositionForm[] jobPositionForms; // show the add and remove buttons only when edit mode @AvailableWhenEditOnly(selector = "#job-position-add-btn-@") private String positionAddBtn; @AvailableWhenEditOnly(selector = "#job-position-remove-btn-@") private String positionRemoveBtn; // for arrayed form, all the field names must contain a "@" mark which will be rewritten to array index by framework. @Override @Hidden(name = "job-id-@") public Integer getId() { return super.getId(); } @Override @Hidden(name = "job-person-id-@") public Integer getPersonId() { return super.getPersonId(); } @Override @Select(name = "job-year-@") public Integer getYear() { return super.getYear(); } @Override @Input(name = "job-description-@") public String getDescription() { return super.getDescription(); } public Integer getJobPositionLength() { return jobPositionLength; } public void setJobPositionLength(Integer jobPositionLength) { this.jobPositionLength = jobPositionLength; } public JobPositionForm[] getJobPositionForms() { return jobPositionForms; } public void setJobPositionForms(JobPositionForm[] jobPositionForms) { this.jobPositionForms = jobPositionForms; } } // @ShowCode:showJobFormEnd
astamuse/asta4d
162
Java
org.eclipse.core.resources.prefs
text/plain
5,301,975,016,320,023,000
/* * Copyright 2014 astamuse company,Ltd. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ package com.astamuse.asta4d.sample.handler.form.cascade; import java.util.HashSet; import java.util.LinkedList; import java.util.List; import java.util.Set; import com.astamuse.asta4d.sample.util.persondb.Education; import com.astamuse.asta4d.sample.util.persondb.EducationDbManager; import com.astamuse.asta4d.sample.util.persondb.PersonDbManager; import com.astamuse.asta4d.util.collection.ListConvertUtil; import com.astamuse.asta4d.util.collection.RowConvertor; import com.astamuse.asta4d.web.form.flow.classical.ClassicalMultiStepFormFlowHandlerTrait; import com.astamuse.asta4d.web.util.message.DefaultMessageRenderingHelper; //@ShowCode:showCascadeFormHandlerStart public abstract class CascadeFormHandler implements ClassicalMultiStepFormFlowHandlerTrait<PersonFormIncludingCascadeForm> { @Override public Class<PersonFormIncludingCascadeForm> getFormCls() { return PersonFormIncludingCascadeForm.class; } @Override public boolean treatCompleteStepAsExit() { // exit immediately after update without displaying complete page return true; } // intercept the form date construction to rewrite the form data @Override public PersonFormIncludingCascadeForm generateFormInstanceFromContext(String currentStep) { PersonFormIncludingCascadeForm form = ClassicalMultiStepFormFlowHandlerTrait.super.generateFormInstanceFromContext(currentStep); if (firstStepName().equals(currentStep)) { // for the submitting of input step, we need to rewrite the education list to handle deleted items. List<EducationForm> rewriteList = new LinkedList<>(); for (EducationForm eform : form.getEducationForms()) { // we assume all the job forms without person id are removed by client if (eform.getPersonId() != null) { rewriteList.add(eform); } } form.setEducationForms(rewriteList.toArray(new EducationForm[rewriteList.size()])); } return form; } /** * we do add logic by Add handler * */ public static class Add extends CascadeFormHandler { @Override public PersonFormIncludingCascadeForm createInitForm() { PersonFormIncludingCascadeForm form = new PersonFormIncludingCascadeForm(); EducationForm[] eForms = new EducationForm[0]; form.setEducationForms(eForms); form.setEducationLength(eForms.length); return form; } @Override public void updateForm(PersonFormIncludingCascadeForm form) { EducationForm[] eForms = form.getEducationForms(); PersonDbManager.instance().add(form); for (EducationForm e : eForms) { e.setPersonId(form.getId()); EducationDbManager.instance().add(e); } DefaultMessageRenderingHelper.getConfiguredInstance().info("data inserted"); } } /** * we do update logic by Edit handler * */ public static class Edit extends CascadeFormHandler { @Override public PersonFormIncludingCascadeForm createInitForm() throws Exception { PersonFormIncludingCascadeForm superform = super.createInitForm(); PersonFormIncludingCascadeForm form = PersonFormIncludingCascadeForm.buildFromPerson(PersonDbManager.instance().find( superform.getId())); List<Education> educations = EducationDbManager.instance().find("personId", form.getId()); List<EducationForm> eFormList = ListConvertUtil.transform(educations, new RowConvertor<Education, EducationForm>() { @Override public EducationForm convert(int rowIndex, Education e) { return EducationForm.buildFromEducation(e); } }); EducationForm[] eForms = eFormList.toArray(new EducationForm[eFormList.size()]); form.setEducationForms(eForms); form.setEducationLength(eForms.length); return form; } @Override public void updateForm(PersonFormIncludingCascadeForm form) { EducationForm[] eForms = form.getEducationForms(); PersonDbManager.instance().update(form); List<Education> existingEdus = EducationDbManager.instance().find("personId", form.getId()); Set<Integer> validIds = new HashSet<>(); for (EducationForm edu : eForms) { edu.setPersonId(form.getId()); if (edu.getId() == null) { EducationDbManager.instance().add(edu); } else { EducationDbManager.instance().update(edu); } validIds.add(edu.getId()); } for (Education edu : existingEdus) { if (!validIds.contains(edu.getId())) { EducationDbManager.instance().remove(edu); } } DefaultMessageRenderingHelper.getConfiguredInstance().info("update succeed"); } } } // @ShowCode:showCascadeFormHandlerEnd
astamuse/asta4d
162
Java
org.eclipse.core.resources.prefs
text/plain
1,953,076,267,934,561,500
/* * Copyright 2014 astamuse company,Ltd. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ package com.astamuse.asta4d.sample.handler.form.cascade; import java.lang.reflect.InvocationTargetException; import org.apache.commons.beanutils.BeanUtils; import com.astamuse.asta4d.sample.util.persondb.Education; import com.astamuse.asta4d.web.form.annotation.renderable.Hidden; import com.astamuse.asta4d.web.form.annotation.renderable.Input; import com.astamuse.asta4d.web.form.annotation.renderable.Select; //@ShowCode:showEducationFormStart public class EducationForm extends Education { public static EducationForm buildFromEducation(Education education) { EducationForm form = new EducationForm(); try { BeanUtils.copyProperties(form, education); } catch (IllegalAccessException | InvocationTargetException e) { throw new RuntimeException(e); } return form; } // for arrayed form, all the field names must contain a "@" mark which will be rewritten to array index by framework. @Override @Hidden(name = "education-id-@") public Integer getId() { return super.getId(); } @Override @Hidden(name = "education-person-id-@") public Integer getPersonId() { return super.getPersonId(); } @Override @Select(name = "education-year-@") public Integer getYear() { return super.getYear(); } @Override @Input(name = "education-description-@") public String getDescription() { return super.getDescription(); } } // @ShowCode:showEducationFormEnd
astamuse/asta4d
162
Java
org.eclipse.core.resources.prefs
text/plain
1,279,497,045,458,109,000
/* * Copyright 2014 astamuse company,Ltd. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ package com.astamuse.asta4d.sample.handler.form.cascade; import java.lang.reflect.InvocationTargetException; import javax.validation.Valid; import org.apache.commons.beanutils.BeanUtils; import org.hibernate.validator.constraints.NotEmpty; import com.astamuse.asta4d.sample.handler.form.PersonForm; import com.astamuse.asta4d.sample.util.persondb.Person; import com.astamuse.asta4d.web.form.annotation.CascadeFormField; import com.astamuse.asta4d.web.form.annotation.Form; import com.astamuse.asta4d.web.form.annotation.renderable.AvailableWhenEditOnly; import com.astamuse.asta4d.web.form.annotation.renderable.Hidden; // @ShowCode:showPersonFormIncludingCascadeFormStart @Form public class PersonFormIncludingCascadeForm extends PersonForm { // show the input comments only when edit mode @AvailableWhenEditOnly(selector = "#input-comment") private String inputComment; // a field with @CascadeFormField with arrayLengthField configured will be treated an array field @CascadeFormField(name = "education", arrayLengthField = "education-length", containerSelector = "[cascade-ref=education-row-@]") @Valid @NotEmpty private EducationForm[] educationForms; @Hidden(name = "education-length") private Integer educationLength; // show the add and remove buttons only when edit mode @AvailableWhenEditOnly(selector = "#education-add-btn") private String educationAddBtn; @AvailableWhenEditOnly(selector = "#education-remove-btn") private String educationRemoveBtn; // getter/setter public Integer getEducationLength() { return educationLength; } public void setEducationLength(Integer educationLength) { this.educationLength = educationLength; } public EducationForm[] getEducationForms() { return educationForms; } public void setEducationForms(EducationForm[] educationForms) { this.educationForms = educationForms; } // @ShowCode:showPersonFormIncludingCascadeFormEnd public static PersonFormIncludingCascadeForm buildFromPerson(Person p) { PersonFormIncludingCascadeForm form = new PersonFormIncludingCascadeForm(); try { BeanUtils.copyProperties(form, p); } catch (IllegalAccessException | InvocationTargetException e) { throw new RuntimeException(e); } return form; } }
astamuse/asta4d
162
Java
org.eclipse.core.resources.prefs
text/plain
-2,141,569,196,852,803,000
/* * Copyright 2014 astamuse company,Ltd. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ package com.astamuse.asta4d.sample.handler.form.multiinput; import java.util.HashSet; import java.util.LinkedList; import java.util.List; import java.util.Set; import com.astamuse.asta4d.sample.handler.form.JobForm; import com.astamuse.asta4d.sample.handler.form.JobPositionForm; import com.astamuse.asta4d.sample.handler.form.PersonForm; import com.astamuse.asta4d.sample.handler.form.common.Asta4DSamplePrjCommonFormHandler; import com.astamuse.asta4d.sample.util.persondb.JobExperence; import com.astamuse.asta4d.sample.util.persondb.JobExperenceDbManager; import com.astamuse.asta4d.sample.util.persondb.JobPosition; import com.astamuse.asta4d.sample.util.persondb.JobPositionDbManager; import com.astamuse.asta4d.sample.util.persondb.PersonDbManager; import com.astamuse.asta4d.util.collection.ListConvertUtil; import com.astamuse.asta4d.util.collection.RowConvertor; import com.astamuse.asta4d.web.form.flow.ext.MultiInputStepFormFlowHandlerTrait; import com.astamuse.asta4d.web.util.message.DefaultMessageRenderingHelper; //@ShowCode:showSplittedFormHandlerStart public abstract class MultiInputFormHandler extends Asta4DSamplePrjCommonFormHandler<MultiInputForm> implements MultiInputStepFormFlowHandlerTrait<MultiInputForm> { public Class<MultiInputForm> getFormCls() { return MultiInputForm.class; } @Override public String[] getInputSteps() { return new String[] { MultiInputForm.inputStep1, MultiInputForm.inputStep2 }; } @Override public MultiInputForm generateFormInstanceFromContext(String currentStep) { MultiInputForm form = super.generateFormInstanceFromContext(currentStep); if (MultiInputForm.inputStep2.equalsIgnoreCase(currentStep)) { // rewrite the array to handle deleted items CascadeJobForm cjForm = form.getCascadeJobForm(); List<JobForm> rewriteJobList = new LinkedList<>(); for (JobForm jobform : cjForm.getJobForms()) { List<JobPositionForm> rewritePosList = new LinkedList<>(); // remove rows without job id specified for (JobPositionForm posForm : jobform.getJobPositionForms()) { if (posForm.getJobId() != null) { rewritePosList.add(posForm); } } jobform.setJobPositionForms(rewritePosList.toArray(new JobPositionForm[rewritePosList.size()])); jobform.setJobPositionLength(jobform.getJobPositionForms().length); // remove rows without person id specified if (jobform.getPersonId() != null) { rewriteJobList.add(jobform); } } cjForm.setJobForms(rewriteJobList.toArray(new JobForm[rewriteJobList.size()])); cjForm.setJobExperienceLength(cjForm.getJobForms().length); } return form; } /** * we do add logic by Add handler * */ public static class Add extends MultiInputFormHandler { @Override public MultiInputForm createInitForm() { MultiInputForm form = new MultiInputForm(); return form; } @Override public void updateForm(MultiInputForm form) { PersonForm pForm = form.getPersonForm(); PersonDbManager.instance().add(pForm); for (JobForm jobForm : form.getCascadeJobForm().getJobForms()) { jobForm.setPersonId(pForm.getId()); JobExperenceDbManager.instance().add(jobForm); for (JobPositionForm posForm : jobForm.getJobPositionForms()) { posForm.setJobId(jobForm.getId()); JobPositionDbManager.instance().add(posForm); } } DefaultMessageRenderingHelper.getConfiguredInstance().info("data inserted"); } } /** * we do update logic by Edit handler * */ public static class Edit extends MultiInputFormHandler { @Override public MultiInputForm createInitForm() throws Exception { MultiInputForm superform = super.createInitForm(); PersonForm pForm = PersonForm.buildFromPerson(PersonDbManager.instance().find(superform.getPersonForm().getId())); List<JobExperence> jobs = JobExperenceDbManager.instance().find("personId", pForm.getId()); List<JobForm> jobFormList = ListConvertUtil.transform(jobs, new RowConvertor<JobExperence, JobForm>() { @Override public JobForm convert(int rowIndex, JobExperence j) { return JobForm.buildFromJob(j); } }); JobForm[] jobForms = jobFormList.toArray(new JobForm[jobFormList.size()]); for (JobForm jobform : jobForms) { List<JobPosition> posList = JobPositionDbManager.instance().find("jobId", jobform.getId()); List<JobPositionForm> posFormList = ListConvertUtil.transform(posList, new RowConvertor<JobPosition, JobPositionForm>() { @Override public JobPositionForm convert(int rowIndex, JobPosition jp) { return JobPositionForm.buildFromJobPosition(jp); } }); JobPositionForm[] posForms = posFormList.toArray(new JobPositionForm[posFormList.size()]); jobform.setJobPositionForms(posForms); jobform.setJobPositionLength(posForms.length); } CascadeJobForm cjForm = new CascadeJobForm(); cjForm.setJobForms(jobForms); cjForm.setJobExperienceLength(jobForms.length); MultiInputForm form = new MultiInputForm(); form.setPersonForm(pForm); form.setCascadeJobForm(cjForm); return form; } private final boolean isExistingId(Integer id) { if (id == null) { return false; } else { return id > 0; } } @Override public void updateForm(MultiInputForm form) { PersonForm pForm = form.getPersonForm(); PersonDbManager.instance().update(pForm); Set<Integer> validJobIds = new HashSet<>(); Set<Integer> validPosIds = new HashSet<>(); for (JobForm jobForm : form.getCascadeJobForm().getJobForms()) { jobForm.setPersonId(pForm.getId()); if (isExistingId(jobForm.getId())) { JobExperenceDbManager.instance().update(jobForm); } else { JobExperenceDbManager.instance().add(jobForm); } validJobIds.add(jobForm.getId()); for (JobPositionForm posForm : jobForm.getJobPositionForms()) { posForm.setJobId(jobForm.getId()); if (isExistingId(posForm.getId())) { JobPositionDbManager.instance().update(posForm); } else { JobPositionDbManager.instance().add(posForm); } validPosIds.add(posForm.getId()); } } List<JobExperence> jobList = JobExperenceDbManager.instance().find("personId", pForm.getId()); for (JobExperence job : jobList) { List<JobPosition> posList = JobPositionDbManager.instance().find("jobId", job.getId()); for (JobPosition pos : posList) { if (!validPosIds.contains(pos.getId())) { JobPositionDbManager.instance().remove(pos); } } if (!validJobIds.contains(job.getId())) { JobExperenceDbManager.instance().remove(job); } } DefaultMessageRenderingHelper.getConfiguredInstance().info("update succeed"); } } } // @ShowCode:showSplittedFormHandlerEnd
astamuse/asta4d
162
Java
org.eclipse.core.resources.prefs
text/plain
-6,651,866,711,473,313,000
/* * Copyright 2014 astamuse company,Ltd. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ package com.astamuse.asta4d.sample.handler.form.multiinput; import javax.validation.Valid; import com.astamuse.asta4d.sample.handler.form.PersonForm; import com.astamuse.asta4d.web.form.annotation.CascadeFormField; import com.astamuse.asta4d.web.form.annotation.Form; import com.astamuse.asta4d.web.form.annotation.renderable.AvailableWhenEditOnly; import com.astamuse.asta4d.web.form.flow.base.StepAwaredValidationTarget; import com.astamuse.asta4d.web.form.flow.ext.MultiInputStepForm; //@ShowCode:showSplittedFormStart @Form public class MultiInputForm implements MultiInputStepForm { // show the input comments only when edit mode @AvailableWhenEditOnly(selector = "#input-comment") private String inputComment; // a field with @CascadeFormField without arrayLengthField configured will be treated a simple reused form POJO @CascadeFormField @Valid @StepAwaredValidationTarget(inputStep1) private PersonForm personForm; @CascadeFormField @Valid @StepAwaredValidationTarget(inputStep2) private CascadeJobForm cascadeJobForm; public static final String inputStep1 = "input-1"; public static final String inputStep2 = "input-2"; public MultiInputForm() { personForm = new PersonForm(); cascadeJobForm = new CascadeJobForm(); } // getter/setter public PersonForm getPersonForm() { return personForm; } public void setPersonForm(PersonForm personForm) { this.personForm = personForm; } public CascadeJobForm getCascadeJobForm() { return cascadeJobForm; } public void setCascadeJobForm(CascadeJobForm cascadeJobForm) { this.cascadeJobForm = cascadeJobForm; } @Override public void mergeInputDataForConfirm(String step, Object inputForm) { MultiInputForm form = (MultiInputForm) inputForm; switch (step) { case inputStep1: this.personForm = form.personForm; break; case inputStep2: this.cascadeJobForm = form.cascadeJobForm; break; default: // } } } // @ShowCode:showSplittedFormEnd
astamuse/asta4d
162
Java
org.eclipse.core.resources.prefs
text/plain
-2,108,133,808,954,310,100
package com.astamuse.asta4d.sample.handler.form.multiinput; import javax.validation.Valid; import org.hibernate.validator.constraints.NotEmpty; import com.astamuse.asta4d.sample.handler.form.JobForm; import com.astamuse.asta4d.web.form.annotation.CascadeFormField; import com.astamuse.asta4d.web.form.annotation.Form; import com.astamuse.asta4d.web.form.annotation.renderable.AvailableWhenEditOnly; import com.astamuse.asta4d.web.form.annotation.renderable.Hidden; @Form public class CascadeJobForm { // a field with @CascadeFormField with arrayLengthField configured will be treated an array field @CascadeFormField(name = "job-experience", arrayLengthField = "job-experience-length", containerSelector = "[cascade-ref=job-experience-row-@]") @Valid @NotEmpty private JobForm[] jobForms; @Hidden(name = "job-experience-length") private Integer jobExperienceLength; // show the add and remove buttons only when edit mode @AvailableWhenEditOnly(selector = "#job-experience-add-btn") private String jobExperienceAddBtn; @AvailableWhenEditOnly(selector = "#job-experience-remove-btn") private String jobExperienceRemoveBtn; public CascadeJobForm() { jobForms = new JobForm[0]; jobExperienceLength = jobForms.length; } public Integer getJobExperienceLength() { return jobExperienceLength; } public void setJobExperienceLength(Integer jobExperienceLength) { this.jobExperienceLength = jobExperienceLength; } public JobForm[] getJobForms() { return jobForms; } public void setJobForms(JobForm[] jobForms) { this.jobForms = jobForms; } }
astamuse/asta4d
162
Java
org.eclipse.core.resources.prefs
text/plain
-4,998,109,431,658,555,000
/* * Copyright 2014 astamuse company,Ltd. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ package com.astamuse.asta4d.sample.handler.form.common; import javax.validation.Validation; import javax.validation.Validator; import com.astamuse.asta4d.util.i18n.I18nMessageHelperTypeAssistant; import com.astamuse.asta4d.util.i18n.OrderedParamI18nMessageHelper; import com.astamuse.asta4d.web.form.validation.JsrValidator; // @ShowCode:showSamplePrjValueValidatorStart public class SamplePrjValueValidator extends JsrValidator { // since the validator is thread-safe, we cache it as static // all the custom initialization of bean validation can be done here //@formatter:off private static Validator validator = Validation.byDefaultProvider() .configure() .messageInterpolator( new Asta4DIntegratedResourceBundleInterpolator( //supply a customized message file new Asta4DResourceBundleFactoryAdapter("BeanValidationMessages") ) ) .buildValidatorFactory() .getValidator(); //@formatter:on private OrderedParamI18nMessageHelper messageHelper = I18nMessageHelperTypeAssistant.getConfiguredOrderedHelper(); private SamplePrjCommonValidatoinMessageLogics messageLogics; public SamplePrjValueValidator() { this(true); } public SamplePrjValueValidator(boolean addFieldLablePrefixToMessage) { super(validator, addFieldLablePrefixToMessage); messageLogics = new SamplePrjCommonValidatoinMessageLogics(messageHelper, addFieldLablePrefixToMessage); } /** * we override this method to treat the annotated message as a key, and note that the annotated message will be used in priority if * there is one specified by form field annotation */ @SuppressWarnings("rawtypes") @Override protected String createAnnotatedMessage(Class formCls, String fieldName, String fieldLabel, String annotatedMsg) { return messageLogics.createAnnotatedMessage(formCls, fieldName, fieldLabel, annotatedMsg); } } // @ShowCode:showSamplePrjValueValidatorEnd
astamuse/asta4d
162
Java
org.eclipse.core.resources.prefs
text/plain
-8,414,619,779,756,506,000
/* * Copyright 2014 astamuse company,Ltd. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ package com.astamuse.asta4d.sample.handler.form.common; import com.astamuse.asta4d.web.form.flow.classical.ClassicalMultiStepFormFlowHandlerTrait; import com.astamuse.asta4d.web.form.validation.FormValidator; // @ShowCode:showCommonFormHandlerStart /** * A common parent handler to configure the common actions of form flow process in application. <br> * For quick start, an empty class body would be good enough. You only need to do the customization when you really need to do it!!! * */ public abstract class Asta4DSamplePrjCommonFormHandler<T> implements ClassicalMultiStepFormFlowHandlerTrait<T> { // we use a field to store a pre generated instance rather than create it at every time private static SamplePrjTypeUnMatchValidator TypeValidator = new SamplePrjTypeUnMatchValidator(false); // as the same as type validator, we cache the value validator instance here private static SamplePrjValueValidator ValueValidator = new SamplePrjValueValidator(false); @Override public FormValidator getTypeUnMatchValidator() { return TypeValidator; } @Override public FormValidator getValueValidator() { return ValueValidator; } } // @ShowCode:showCommonFormHandlerEnd
astamuse/asta4d
162
Java
org.eclipse.core.resources.prefs
text/plain
-3,079,863,672,291,769,000
/* * Copyright 2014 astamuse company,Ltd. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ package com.astamuse.asta4d.sample.handler.form.common; import com.astamuse.asta4d.util.i18n.I18nMessageHelperTypeAssistant; import com.astamuse.asta4d.util.i18n.OrderedParamI18nMessageHelper; /** * * We use a splitted message logics class to share all the common logics * * @author e-ryu * */ public class SamplePrjCommonValidatoinMessageLogics { protected OrderedParamI18nMessageHelper messageHelper = I18nMessageHelperTypeAssistant.getConfiguredOrderedHelper(); protected boolean addFieldLablePrefixToMessage; public SamplePrjCommonValidatoinMessageLogics(OrderedParamI18nMessageHelper messageHelper, boolean addFieldLablePrefixToMessage) { super(); this.messageHelper = messageHelper; this.addFieldLablePrefixToMessage = addFieldLablePrefixToMessage; } // @ShowCode:showCreateAnnotatedMessageStart /** * we share the annotated message logic here */ @SuppressWarnings("rawtypes") public String createAnnotatedMessage(Class formCls, String fieldName, String fieldLabel, String annotatedMsg) { // treat the annotated message as key String msg = messageHelper.getMessageWithDefault(annotatedMsg, annotatedMsg); if (addFieldLablePrefixToMessage) { return String.format("%s: %s", fieldLabel, msg); } else { return msg; } } // @ShowCode:showCreateAnnotatedMessageEnd }
astamuse/asta4d
162
Java
org.eclipse.core.resources.prefs
text/plain
-5,625,428,173,940,636,000
/* * Copyright 2014 astamuse company,Ltd. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ package com.astamuse.asta4d.sample.handler.form.common; import com.astamuse.asta4d.util.i18n.I18nMessageHelperTypeAssistant; import com.astamuse.asta4d.util.i18n.OrderedParamI18nMessageHelper; import com.astamuse.asta4d.web.form.validation.TypeUnMatchValidator; //@ShowCode:showSamplePrjTypeUnMatchValidatorStart public class SamplePrjTypeUnMatchValidator extends TypeUnMatchValidator { private OrderedParamI18nMessageHelper messageHelper = I18nMessageHelperTypeAssistant.getConfiguredOrderedHelper(); private SamplePrjCommonValidatoinMessageLogics messageLogics; public SamplePrjTypeUnMatchValidator() { this(true); } public SamplePrjTypeUnMatchValidator(boolean addFieldLablePrefixToMessage) { super(addFieldLablePrefixToMessage); messageLogics = new SamplePrjCommonValidatoinMessageLogics(messageHelper, addFieldLablePrefixToMessage); } @Override protected String createMessage(Class formCls, String fieldName, String fieldLabel, String fieldTypeName, String valueString) { // try to retrieve the type name by validation.type.name.[fieldTypeName] String typeName = messageHelper.getMessageWithDefault("validation.type.name." + fieldTypeName, fieldTypeName); // there is a common message for type unmatch error which requires type name and value string String msg = messageHelper.getMessage("validation.type.msg", typeName, valueString); if (addFieldLablePrefixToMessage) { // treat the field label as msg key of field as validation.form.[form class name].[fieldLabel] String formSimpleName = retrieveSimpleFormName(formCls); String fieldDisplayLabel = messageHelper.getMessageWithDefault("validation.form." + formSimpleName + "." + fieldLabel, fieldLabel); msg = fieldDisplayLabel + ": " + msg; } return msg; } @SuppressWarnings("rawtypes") private String retrieveSimpleFormName(Class formCls) { String clsName = formCls.getName(); return clsName.substring("com.astamuse.asta4d.sample.handler.form.".length()); } /** * we override this method to treat the annotated message as a key, and note that the annotated message will be used in priority if * there is one specified by form field annotation */ @SuppressWarnings("rawtypes") @Override protected String createAnnotatedMessage(Class formCls, String fieldName, String fieldLabel, String annotatedMsg) { return messageLogics.createAnnotatedMessage(formCls, fieldName, fieldLabel, annotatedMsg); } } // @ShowCode:showSamplePrjTypeUnMatchValidatorEnd
astamuse/asta4d
162
Java
org.eclipse.core.resources.prefs
text/plain
-5,859,608,652,545,402,000
/* * Copyright 2014 astamuse company,Ltd. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ package com.astamuse.asta4d.sample.handler.form.singlestep; import com.astamuse.asta4d.sample.handler.form.PersonForm; import com.astamuse.asta4d.sample.util.persondb.Person; import com.astamuse.asta4d.sample.util.persondb.PersonDbManager; import com.astamuse.asta4d.web.form.flow.classical.OneStepFormHandlerTrait; import com.astamuse.asta4d.web.util.message.DefaultMessageRenderingHelper; // @ShowCode:showSingleStepFormHandlerStart public class SingleStepFormHandler implements OneStepFormHandlerTrait<PersonForm> { public Class<PersonForm> getFormCls() { return PersonForm.class; } @Override public PersonForm createInitForm() throws Exception { PersonForm form = OneStepFormHandlerTrait.super.createInitForm(); if (form.getId() == null) {// add return form; } else {// update // retrieve the form form db again return PersonForm.buildFromPerson(PersonDbManager.instance().find(form.getId())); } } @Override public void updateForm(PersonForm form) { if (form.getId() == null) {// add PersonDbManager.instance().add(Person.createByForm(form)); // the success message will be shown at the default global message bar DefaultMessageRenderingHelper.getConfiguredInstance().info("data inserted"); } else {// update Person p = Person.createByForm(form); PersonDbManager.instance().update(p); // the success message will be shown at the default global message bar DefaultMessageRenderingHelper.getConfiguredInstance().info("update succeed"); } } } // @ShowCode:showSingleStepFormHandlerEnd
astamuse/asta4d
162
Java
org.eclipse.core.resources.prefs
text/plain
5,745,906,177,566,171,000
/* * Copyright 2014 astamuse company,Ltd. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ package com.astamuse.asta4d.sample.handler.form.splittedinput; import java.util.HashSet; import java.util.LinkedList; import java.util.List; import java.util.Set; import com.astamuse.asta4d.sample.handler.form.JobForm; import com.astamuse.asta4d.sample.handler.form.JobPositionForm; import com.astamuse.asta4d.sample.handler.form.PersonForm; import com.astamuse.asta4d.sample.handler.form.common.Asta4DSamplePrjCommonFormHandler; import com.astamuse.asta4d.sample.handler.form.multiinput.CascadeJobForm; import com.astamuse.asta4d.sample.handler.form.splittedinput.SplittedInputForm.CascadeJobFormStep3; import com.astamuse.asta4d.sample.handler.form.splittedinput.SplittedInputForm.ConfirmStepForm; import com.astamuse.asta4d.sample.util.persondb.JobExperence; import com.astamuse.asta4d.sample.util.persondb.JobExperenceDbManager; import com.astamuse.asta4d.sample.util.persondb.JobPosition; import com.astamuse.asta4d.sample.util.persondb.JobPositionDbManager; import com.astamuse.asta4d.sample.util.persondb.PersonDbManager; import com.astamuse.asta4d.util.collection.ListConvertUtil; import com.astamuse.asta4d.util.collection.RowConvertor; import com.astamuse.asta4d.web.form.flow.ext.MultiInputStepFormFlowHandlerTrait; import com.astamuse.asta4d.web.form.flow.ext.ExcludingFieldRetrievableFormValidationProcessor; import com.astamuse.asta4d.web.util.message.DefaultMessageRenderingHelper; //@ShowCode:showSplittedFormHandlerStart public abstract class SplittedInputFormHandler extends Asta4DSamplePrjCommonFormHandler<SplittedInputForm> implements MultiInputStepFormFlowHandlerTrait<SplittedInputForm>, ExcludingFieldRetrievableFormValidationProcessor { public Class<SplittedInputForm> getFormCls() { return SplittedInputForm.class; } @Override public String[] getInputSteps() { return new String[] { SplittedInputForm.inputStep1, SplittedInputForm.inputStep2, SplittedInputForm.inputStep3 }; } @Override public SplittedInputForm generateFormInstanceFromContext(String currentStep) { SplittedInputForm form = super.generateFormInstanceFromContext(currentStep); if (SplittedInputForm.inputStep3.equalsIgnoreCase(currentStep)) { // rewrite the array to handle deleted items CascadeJobForm cjForm = form.getForms().getCascadeJobForm(); List<JobForm> rewriteJobList = new LinkedList<>(); for (JobForm jobform : cjForm.getJobForms()) { List<JobPositionForm> rewritePosList = new LinkedList<>(); // remove rows without job id specified for (JobPositionForm posForm : jobform.getJobPositionForms()) { if (posForm.getJobId() != null) { rewritePosList.add(posForm); } } jobform.setJobPositionForms(rewritePosList.toArray(new JobPositionForm[rewritePosList.size()])); jobform.setJobPositionLength(jobform.getJobPositionForms().length); // remove rows without person id specified if (jobform.getPersonId() != null) { rewriteJobList.add(jobform); } } cjForm.setJobForms(rewriteJobList.toArray(new JobForm[rewriteJobList.size()])); cjForm.setJobExperienceLength(cjForm.getJobForms().length); } return form; } /** * we do add logic by Add handler * */ public static class Add extends SplittedInputFormHandler { @Override public SplittedInputForm createInitForm() { SplittedInputForm form = new SplittedInputForm(); return form; } @Override public void updateForm(SplittedInputForm form) { ConfirmStepForm allForms = form.getForms(); PersonForm pForm = allForms.getPersonForm(); PersonDbManager.instance().add(pForm); for (JobForm jobForm : allForms.getCascadeJobForm().getJobForms()) { jobForm.setPersonId(pForm.getId()); JobExperenceDbManager.instance().add(jobForm); for (JobPositionForm posForm : jobForm.getJobPositionForms()) { posForm.setJobId(jobForm.getId()); JobPositionDbManager.instance().add(posForm); } } DefaultMessageRenderingHelper.getConfiguredInstance().info("data inserted"); } } /** * we do update logic by Edit handler * */ public static class Edit extends SplittedInputFormHandler { @Override public SplittedInputForm createInitForm() throws Exception { SplittedInputForm superform = super.createInitForm(); PersonForm pForm = PersonForm.buildFromPerson(PersonDbManager.instance().find(superform.getForms().getPersonForm().getId())); List<JobExperence> jobs = JobExperenceDbManager.instance().find("personId", pForm.getId()); List<JobForm> jobFormList = ListConvertUtil.transform(jobs, new RowConvertor<JobExperence, JobForm>() { @Override public JobForm convert(int rowIndex, JobExperence j) { return JobForm.buildFromJob(j); } }); JobForm[] jobForms = jobFormList.toArray(new JobForm[jobFormList.size()]); for (JobForm jobform : jobForms) { List<JobPosition> posList = JobPositionDbManager.instance().find("jobId", jobform.getId()); List<JobPositionForm> posFormList = ListConvertUtil.transform(posList, new RowConvertor<JobPosition, JobPositionForm>() { @Override public JobPositionForm convert(int rowIndex, JobPosition jp) { return JobPositionForm.buildFromJobPosition(jp); } }); JobPositionForm[] posForms = posFormList.toArray(new JobPositionForm[posFormList.size()]); jobform.setJobPositionForms(posForms); jobform.setJobPositionLength(posForms.length); } CascadeJobFormStep3 cjForm = new CascadeJobFormStep3(); cjForm.setJobForms(jobForms); cjForm.setJobExperienceLength(jobForms.length); SplittedInputForm form = new SplittedInputForm(); form.setForms(pForm, cjForm); return form; } private final boolean isExistingId(Integer id) { if (id == null) { return false; } else { return id > 0; } } @Override public void updateForm(SplittedInputForm form) { ConfirmStepForm allForms = form.getForms(); PersonForm pForm = allForms.getPersonForm(); PersonDbManager.instance().update(pForm); Set<Integer> validJobIds = new HashSet<>(); Set<Integer> validPosIds = new HashSet<>(); for (JobForm jobForm : allForms.getCascadeJobForm().getJobForms()) { jobForm.setPersonId(pForm.getId()); if (isExistingId(jobForm.getId())) { JobExperenceDbManager.instance().update(jobForm); } else { JobExperenceDbManager.instance().add(jobForm); } validJobIds.add(jobForm.getId()); for (JobPositionForm posForm : jobForm.getJobPositionForms()) { posForm.setJobId(jobForm.getId()); if (isExistingId(posForm.getId())) { JobPositionDbManager.instance().update(posForm); } else { JobPositionDbManager.instance().add(posForm); } validPosIds.add(posForm.getId()); } } List<JobExperence> jobList = JobExperenceDbManager.instance().find("personId", pForm.getId()); for (JobExperence job : jobList) { List<JobPosition> posList = JobPositionDbManager.instance().find("jobId", job.getId()); for (JobPosition pos : posList) { if (!validPosIds.contains(pos.getId())) { JobPositionDbManager.instance().remove(pos); } } if (!validJobIds.contains(job.getId())) { JobExperenceDbManager.instance().remove(job); } } DefaultMessageRenderingHelper.getConfiguredInstance().info("update succeed"); } } } // @ShowCode:showSplittedFormHandlerEnd
astamuse/asta4d
162
Java
org.eclipse.core.resources.prefs
text/plain
-1,978,603,626,497,741,300
/* * Copyright 2014 astamuse company,Ltd. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ package com.astamuse.asta4d.sample.handler.form.splittedinput; import com.astamuse.asta4d.sample.handler.form.PersonForm; import com.astamuse.asta4d.sample.handler.form.multiinput.CascadeJobForm; import com.astamuse.asta4d.web.form.annotation.CascadeFormField; import com.astamuse.asta4d.web.form.annotation.Form; import com.astamuse.asta4d.web.form.annotation.renderable.AvailableWhenEditOnly; import com.astamuse.asta4d.web.form.flow.base.StepAwaredValidationTarget; import com.astamuse.asta4d.web.form.flow.base.StepRepresentableForm; import com.astamuse.asta4d.web.form.flow.classical.ClassicalFormFlowConstant; import com.astamuse.asta4d.web.form.flow.ext.ExcludingFieldRetrievableForm; import com.astamuse.asta4d.web.form.flow.ext.IncludingFieldRetrievableForm; import com.astamuse.asta4d.web.form.flow.ext.MultiInputStepForm; //@ShowCode:showSplittedFormStart /** * Declares four form instances to represent the steps: input-1, input-2, input-3, confirm(and complete). * * @author e-ryu * */ @Form public class SplittedInputForm implements MultiInputStepForm { /** * Implements {@link ExcludingFieldRetrievableForm} to declare fields to be excluded in validation and rendering. Implements * {@link StepRepresentableForm} to declare whether this form instance should be rendered. * * @author e-ryu * */ @Form public static class PersonFormStep1 extends PersonForm implements ExcludingFieldRetrievableForm, StepRepresentableForm { @Override public String[] retrieveRepresentingSteps() { return new String[] { "input-1" }; } @Override public String[] getExcludeFields() { return new String[] { "language", "memo" }; } } /** * Use {@link IncludingFieldRetrievableForm} instead of {@link ExcludingFieldRetrievableForm} to simplify fields declaration. * * @author e-ryu * */ @Form public static class PersonFormStep2 extends PersonForm implements IncludingFieldRetrievableForm, StepRepresentableForm { @Override public String[] retrieveRepresentingSteps() { return new String[] { "input-2" }; } @Override public String[] getIncludeFields() { return new String[] { "language", "memo" }; } } @Form public static class CascadeJobFormStep3 extends CascadeJobForm implements StepRepresentableForm { @Override public String[] retrieveRepresentingSteps() { return new String[] { "input-3" }; } } @Form public static class ConfirmStepForm implements StepRepresentableForm { @CascadeFormField private PersonForm personForm = new PersonForm(); @CascadeFormField private CascadeJobForm cascadeJobForm = new CascadeJobForm(); @Override public String[] retrieveRepresentingSteps() { return new String[] { ClassicalFormFlowConstant.STEP_CONFIRM, ClassicalFormFlowConstant.STEP_COMPLETE }; } public PersonForm getPersonForm() { return personForm; } public CascadeJobForm getCascadeJobForm() { return cascadeJobForm; } } // private // show the input comments only when edit mode @AvailableWhenEditOnly(selector = "#input-comment") private String inputComment; /** * {@link StepAwaredValidationTarget} to suggest the validation target for certain step. */ @CascadeFormField @StepAwaredValidationTarget(inputStep1) private PersonFormStep1 personFormStep1; @CascadeFormField @StepAwaredValidationTarget(inputStep2) private PersonFormStep2 personFormStep2; @CascadeFormField @StepAwaredValidationTarget(inputStep3) private CascadeJobFormStep3 cascadeJobFormStep3; @CascadeFormField private ConfirmStepForm confirmStepForm; public static final String inputStep1 = "input-1"; public static final String inputStep2 = "input-2"; public static final String inputStep3 = "input-3"; public SplittedInputForm() { this.personFormStep1 = new PersonFormStep1(); this.personFormStep2 = new PersonFormStep2(); this.cascadeJobFormStep3 = new CascadeJobFormStep3(); this.confirmStepForm = new ConfirmStepForm(); } // getter/setter public void setForms(PersonForm personForm, CascadeJobForm cascadeJobForm) { this.personFormStep1.copyPropertiesFrom(personForm); this.personFormStep2.copyPropertiesFrom(personForm); this.cascadeJobFormStep3.copyPropertiesFrom(cascadeJobForm); } public ConfirmStepForm getForms() { return this.confirmStepForm; } @Override public void mergeInputDataForConfirm(String step, Object inputForm) { SplittedInputForm form = (SplittedInputForm) inputForm; switch (step) { case inputStep1: form.personFormStep1.copyIncludingFieldsTo(this.confirmStepForm.personForm); break; case inputStep2: form.personFormStep2.copyIncludingFieldsTo(this.confirmStepForm.personForm); break; case inputStep3: form.cascadeJobFormStep3.copyPropertiesTo(this.confirmStepForm.cascadeJobForm); break; default: // } } } // @ShowCode:showSplittedFormEnd
astamuse/asta4d
162
Java
org.eclipse.core.resources.prefs
text/plain
2,891,186,603,860,571,000
/* * Copyright 2014 astamuse company,Ltd. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ package com.astamuse.asta4d.sample.handler.form.multistep; import java.lang.reflect.InvocationTargetException; import org.apache.commons.beanutils.BeanUtils; import com.astamuse.asta4d.sample.handler.form.PersonForm; import com.astamuse.asta4d.sample.util.persondb.Person; import com.astamuse.asta4d.web.form.annotation.Form; import com.astamuse.asta4d.web.form.annotation.renderable.Input; import com.astamuse.asta4d.web.form.annotation.renderable.Select; @Form public class PersonFormForMultiStep extends PersonForm { public static PersonFormForMultiStep buildFromPerson(Person p) { PersonFormForMultiStep form = new PersonFormForMultiStep(); try { BeanUtils.copyProperties(form, p); } catch (IllegalAccessException | InvocationTargetException e) { throw new RuntimeException(e); } return form; } // @ShowCode:showAnnotatedMessageStart // afford an annotated message to override default generated message @Input(message = "validation.field.PersonForm.name") @Override public String getName() { return super.getName(); } @Override @Select(name = "bloodtype") public BloodType getBloodType() { return super.getBloodType(); } // @ShowCode:showAnnotatedMessageEnd }
astamuse/asta4d
162
Java
org.eclipse.core.resources.prefs
text/plain
1,719,538,441,513,920,300
/* * Copyright 2014 astamuse company,Ltd. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ package com.astamuse.asta4d.sample.handler.form.multistep; import com.astamuse.asta4d.sample.handler.form.common.Asta4DSamplePrjCommonFormHandler; import com.astamuse.asta4d.sample.util.persondb.Person; import com.astamuse.asta4d.sample.util.persondb.PersonDbManager; import com.astamuse.asta4d.web.util.message.DefaultMessageRenderingHelper; //@ShowCode:showMultiStepFormHandlerStart public class MultiStepFormHandler extends Asta4DSamplePrjCommonFormHandler<PersonFormForMultiStep> { @Override public Class<PersonFormForMultiStep> getFormCls() { return PersonFormForMultiStep.class; } @Override public boolean treatCompleteStepAsExit() { // change to true would cause the form flow exit immediately after the form data is updated // false would show a complete page after updated. return false; } @Override public PersonFormForMultiStep createInitForm() throws Exception { PersonFormForMultiStep form = super.createInitForm(); if (form.getId() == null) {// add return form; } else {// update // retrieve the form form db again return PersonFormForMultiStep.buildFromPerson(PersonDbManager.instance().find(form.getId())); } } @Override public void updateForm(PersonFormForMultiStep form) { DefaultMessageRenderingHelper msgHelper = DefaultMessageRenderingHelper.getConfiguredInstance(); String msg = null; if (form.getId() == null) {// add PersonDbManager.instance().add(Person.createByForm(form)); // output the success message to the global message bar msg = "data inserted"; } else {// update Person p = Person.createByForm(form); PersonDbManager.instance().update(p); msg = "update succeed"; } // output the success message to specified DOM rather than the global message bar msgHelper.info(".x-success-msg", msg); } } // @ShowCode:showMultiStepFormHandlerEnd
astamuse/asta4d
162
Java
org.eclipse.core.resources.prefs
text/plain
9,079,074,348,237,308,000
/* * Copyright 2014 astamuse company,Ltd. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ package com.astamuse.asta4d.sample.util.persondb; import java.util.LinkedList; import java.util.List; public class JobExperenceDbManager extends AbstractDbManager<JobExperence> { private static JobExperenceDbManager instance = new JobExperenceDbManager(); private JobExperenceDbManager() { super(); } public static JobExperenceDbManager instance() { return instance; } protected List<JobExperence> initEntityList() { return new LinkedList<>(); } }
astamuse/asta4d
162
Java
org.eclipse.core.resources.prefs
text/plain
-6,280,017,421,908,714,000
/* * Copyright 2014 astamuse company,Ltd. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ package com.astamuse.asta4d.sample.util.persondb; import javax.validation.constraints.Max; import javax.validation.constraints.Min; import javax.validation.constraints.NotNull; import javax.validation.constraints.Size; public class Education implements IdentifiableEntity, Cloneable { private Integer id; private Integer personId; @Min(2000) @Max(2010) private Integer year; private String description; @Override public Integer getId() { return id; } @Override public void setId(Integer id) { this.id = id; } @NotNull public Integer getPersonId() { return personId; } public void setPersonId(Integer personId) { this.personId = personId; } public Integer getYear() { return year; } public void setYear(Integer year) { this.year = year; } @Size(min = 5) public String getDescription() { return description; } public void setDescription(String description) { this.description = description; } @Override public int hashCode() { return id == null ? 0 : id; } @Override public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (getClass() != obj.getClass()) return false; Education other = (Education) obj; if (id != other.id) return false; return true; } @Override public Object clone() throws CloneNotSupportedException { return super.clone(); } }
astamuse/asta4d
162
Java
org.eclipse.core.resources.prefs
text/plain
347,000,614,809,607,500
/* * Copyright 2014 astamuse company,Ltd. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ package com.astamuse.asta4d.sample.util.persondb; public interface IdentifiableEntity extends Cloneable { public Integer getId(); public void setId(Integer id); public Object clone() throws CloneNotSupportedException; }
astamuse/asta4d
162
Java
org.eclipse.core.resources.prefs
text/plain
1,050,014,212,278,327,600
/* * Copyright 2014 astamuse company,Ltd. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ package com.astamuse.asta4d.sample.util.persondb; import java.lang.reflect.InvocationTargetException; import javax.validation.constraints.Max; import javax.validation.constraints.NotNull; import javax.validation.constraints.Size; import org.apache.commons.beanutils.BeanUtils; import org.hibernate.validator.constraints.NotBlank; import com.astamuse.asta4d.sample.handler.form.PersonForm; import com.astamuse.asta4d.util.collection.RowConvertor; import com.astamuse.asta4d.web.form.field.OptionValueMap; import com.astamuse.asta4d.web.form.field.OptionValuePair; public class Person implements IdentifiableEntity, Cloneable { public static enum BloodType { A, B, O, AB; public static final OptionValueMap asOptionValueMap = OptionValueMap.build(BloodType.values(), new RowConvertor<BloodType, OptionValuePair>() { @Override public OptionValuePair convert(int rowIndex, BloodType obj) { return new OptionValuePair(obj.name(), obj.name()); } }); } public static enum SEX { Male, Female; public static final OptionValueMap asOptionValueMap = OptionValueMap.build(SEX.values(), new RowConvertor<SEX, OptionValuePair>() { @Override public OptionValuePair convert(int rowIndex, SEX obj) { return new OptionValuePair(obj.name(), obj.name()); } }); } public static enum Language { English, Japanese, Chinese; public static final OptionValueMap asOptionValueMap = OptionValueMap.build(Language.values(), new RowConvertor<Language, OptionValuePair>() { @Override public OptionValuePair convert(int rowIndex, Language obj) { return new OptionValuePair(obj.name(), obj.name()); } }); } private String name; private Integer age; private BloodType bloodType = BloodType.AB; private SEX sex; private Language[] language; private String memo; // @ShowCode:showValidationAnnotationStart /* * bean validation is annotated on entity POJO * * (it can also be done at the form POJO side, but we think the value * constrains should be considered as a part of the entity POJO's feature) */ @NotBlank @Size(max = 6) public String getName() { return name; } public void setName(String name) { this.name = name; } @Max(45) @NotNull public Integer getAge() { return age; } // @ShowCode:showValidationAnnotationEnd public void setAge(Integer age) { this.age = age; } public BloodType getBloodType() { return bloodType; } public void setBloodType(BloodType bloodType) { this.bloodType = bloodType; } public SEX getSex() { return sex; } public void setSex(SEX sex) { this.sex = sex; } public Language[] getLanguage() { return language; } public void setLanguage(Language[] language) { this.language = language; } private Integer id; public Integer getId() { return id; } public void setId(Integer id) { this.id = id; } public String getMemo() { return memo; } public void setMemo(String memo) { this.memo = memo; } @Override public int hashCode() { return id == null ? 0 : id; } @Override public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (getClass() != obj.getClass()) return false; Person other = (Person) obj; if (id != other.id) return false; return true; } @Override public Object clone() throws CloneNotSupportedException { return super.clone(); } public static Person createByForm(PersonForm form) { Person p = new Person(); try { BeanUtils.copyProperties(p, form); } catch (IllegalAccessException | InvocationTargetException e) { throw new RuntimeException(e); } return p; } }
astamuse/asta4d
162
Java
org.eclipse.core.resources.prefs
text/plain
-6,783,498,302,933,302,000
/* * Copyright 2014 astamuse company,Ltd. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ package com.astamuse.asta4d.sample.util.persondb; import java.lang.reflect.InvocationTargetException; import java.util.ArrayList; import java.util.HashSet; import java.util.List; import java.util.Set; import java.util.concurrent.atomic.AtomicInteger; import org.apache.commons.beanutils.PropertyUtils; import org.apache.commons.collections.CollectionUtils; import org.apache.commons.collections.Predicate; import org.apache.commons.lang3.ObjectUtils; import com.astamuse.asta4d.util.collection.ListConvertUtil; import com.astamuse.asta4d.util.collection.RowConvertor; public abstract class AbstractDbManager<T extends IdentifiableEntity> { private AtomicInteger idGenerator = new AtomicInteger(); private Set<T> entityList = new HashSet<>(); protected AbstractDbManager() { entityList.addAll(initEntityList()); } protected abstract List<T> initEntityList(); protected Integer nextId() { return idGenerator.incrementAndGet(); } public synchronized List<T> findAll() { return new ArrayList<>(entityList); } @SuppressWarnings("unchecked") public synchronized List<T> find(final String field, final Object v) { List<T> list = new ArrayList<>(entityList); CollectionUtils.filter(list, new Predicate() { @Override public boolean evaluate(Object object) { try { return ObjectUtils.equals(v, PropertyUtils.getProperty(object, field)); } catch (IllegalAccessException | InvocationTargetException | NoSuchMethodException e) { throw new RuntimeException(e); } } }); return ListConvertUtil.transform(list, new RowConvertor<T, T>() { @Override public T convert(int rowIndex, T obj) { try { return (T) obj.clone(); } catch (CloneNotSupportedException e) { throw new RuntimeException(e); } } }); } @SuppressWarnings("unchecked") public synchronized T find(final int id) { T entity = (T) CollectionUtils.find(entityList, new Predicate() { @Override public boolean evaluate(Object object) { return ((T) object).getId() == id; } }); try { return (T) entity.clone(); } catch (CloneNotSupportedException e) { throw new RuntimeException(e); } } @SuppressWarnings("unchecked") public synchronized void add(T entity) { if (entityList.size() >= 10) { throw new RuntimeException("too many data"); } entity.setId(nextId()); try { entityList.add((T) entity.clone()); } catch (CloneNotSupportedException e) { throw new RuntimeException(e); } } @SuppressWarnings("unchecked") public synchronized void update(final T entity) { remove(entity); try { entityList.add((T) entity.clone()); } catch (CloneNotSupportedException e) { throw new RuntimeException(e); } } public synchronized void remove(final T entity) { T existingEntity = find(entity.getId()); if (existingEntity == null) { throw new IllegalArgumentException("entity does not exist:" + entity.getId()); } entityList.remove(existingEntity); } }
astamuse/asta4d
162
Java
org.eclipse.core.resources.prefs
text/plain
3,661,329,372,311,289,300
/* * Copyright 2014 astamuse company,Ltd. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ package com.astamuse.asta4d.sample.util.persondb; import javax.validation.constraints.Max; import javax.validation.constraints.Min; import javax.validation.constraints.NotNull; import javax.validation.constraints.Size; public class JobExperence implements IdentifiableEntity, Cloneable { private Integer id; private Integer personId; @Min(2000) @Max(2010) private Integer year; private String description; @Override public Integer getId() { return id; } @Override public void setId(Integer id) { this.id = id; } @NotNull public Integer getPersonId() { return personId; } public void setPersonId(Integer personId) { this.personId = personId; } public Integer getYear() { return year; } public void setYear(Integer year) { this.year = year; } @Size(min = 5) public String getDescription() { return description; } public void setDescription(String description) { this.description = description; } @Override public int hashCode() { return id == null ? 0 : id; } @Override public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (getClass() != obj.getClass()) return false; JobExperence other = (JobExperence) obj; if (id != other.id) return false; return true; } @Override public Object clone() throws CloneNotSupportedException { return super.clone(); } }
astamuse/asta4d
162
Java
org.eclipse.core.resources.prefs
text/plain
-7,485,519,175,579,125,000
/* * Copyright 2014 astamuse company,Ltd. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ package com.astamuse.asta4d.sample.util.persondb; import javax.validation.constraints.NotNull; import org.hibernate.validator.constraints.NotEmpty; public class JobPosition implements IdentifiableEntity, Cloneable { private Integer id; private Integer jobId; private String name; @Override public Integer getId() { return id; } @Override public void setId(Integer id) { this.id = id; } @NotNull public Integer getJobId() { return jobId; } public void setJobId(Integer jobId) { this.jobId = jobId; } @NotEmpty public String getName() { return name; } public void setName(String name) { this.name = name; } @Override public int hashCode() { return id == null ? 0 : id; } @Override public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (getClass() != obj.getClass()) return false; JobPosition other = (JobPosition) obj; if (id != other.id) return false; return true; } @Override public Object clone() throws CloneNotSupportedException { return super.clone(); } }
astamuse/asta4d
162
Java
org.eclipse.core.resources.prefs
text/plain
1,205,941,789,070,075,600
/* * Copyright 2014 astamuse company,Ltd. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ package com.astamuse.asta4d.sample.util.persondb; import java.util.LinkedList; import java.util.List; import com.astamuse.asta4d.sample.handler.form.PersonForm; public class PersonDbManager extends AbstractDbManager<Person> { private static PersonDbManager instance = new PersonDbManager(); private PersonDbManager() { super(); } public static PersonDbManager instance() { return instance; } protected List<Person> initEntityList() { //@formatter:off Object[][] data = new Object[][]{ {nextId(), "Alice", 20, PersonForm.SEX.Female, PersonForm.BloodType.AB, new PersonForm.Language[]{PersonForm.Language.Chinese, PersonForm.Language.English}}, {nextId(), "Bob", 25, PersonForm.SEX.Male, PersonForm.BloodType.O, new PersonForm.Language[]{PersonForm.Language.Japanese, PersonForm.Language.English}}, }; //@formatter:on List<Person> list = new LinkedList<>(); for (Object[] d : data) { int idx = 0; Person p = new Person(); p.setId((Integer) d[idx++]); p.setName((String) d[idx++]); p.setAge((Integer) d[idx++]); p.setSex((Person.SEX) d[idx++]); p.setBloodType((Person.BloodType) d[idx++]); p.setLanguage((Person.Language[]) d[idx++]); list.add(p); } return list; } }
astamuse/asta4d
162
Java
org.eclipse.core.resources.prefs
text/plain
-5,505,846,737,698,207,000
/* * Copyright 2014 astamuse company,Ltd. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ package com.astamuse.asta4d.sample.util.persondb; import java.util.LinkedList; import java.util.List; public class JobPositionDbManager extends AbstractDbManager<JobPosition> { private static JobPositionDbManager instance = new JobPositionDbManager(); private JobPositionDbManager() { super(); } public static JobPositionDbManager instance() { return instance; } protected List<JobPosition> initEntityList() { return new LinkedList<>(); } }
astamuse/asta4d
162
Java
org.eclipse.core.resources.prefs
text/plain
-4,073,600,822,502,422,500
/* * Copyright 2014 astamuse company,Ltd. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ package com.astamuse.asta4d.sample.util.persondb; import java.util.LinkedList; import java.util.List; public class EducationDbManager extends AbstractDbManager<Education> { private static EducationDbManager instance = new EducationDbManager(); private EducationDbManager() { super(); } public static EducationDbManager instance() { return instance; } protected List<Education> initEntityList() { return new LinkedList<>(); } }
astamuse/asta4d
162
Java
org.eclipse.core.resources.prefs
text/plain
6,087,857,103,736,588,000
package com.astamuse.asta4d.sample.customrule; import com.astamuse.asta4d.web.dispatch.mapping.UrlMappingRuleInitializer; public class CustomRuleInitializer implements UrlMappingRuleInitializer<CustomRuleSet> { @Override public void initUrlMappingRules(CustomRuleSet rules) { rules.add("/", "index.html").id("top").group("somegroup"); rules.add("/index.html").reMapTo("top"); rules.add("/gohandler").group("handler-group").handler(new Object() { public void handler() { System.out.println(""); } }).forward("handlerResult.html"); } }
astamuse/asta4d
162
Java
org.eclipse.core.resources.prefs
text/plain
-3,282,138,888,391,231,000
package com.astamuse.asta4d.sample.customrule; import com.astamuse.asta4d.web.dispatch.mapping.handy.HandyRuleSet; @SuppressWarnings({ "unchecked" }) public class CustomRuleSet extends HandyRuleSet<CustomRuleAfterAddSrc, CustomRuleAfterAddSrcAndTarget>implements CustomRuleBuilder { }
astamuse/asta4d
162
Java
org.eclipse.core.resources.prefs
text/plain
-6,149,928,996,312,050,000
package com.astamuse.asta4d.sample.customrule; import com.astamuse.asta4d.web.dispatch.mapping.UrlMappingRule; import com.astamuse.asta4d.web.dispatch.mapping.handy.HandyRuleAfterAddSrcAndTarget; public class CustomRuleAfterAddSrcAndTarget extends HandyRuleAfterAddSrcAndTarget<CustomRuleAfterAddSrcAndTarget> implements CustomRuleGroupConfigurable<CustomRuleAfterAddSrcAndTarget> { public CustomRuleAfterAddSrcAndTarget(UrlMappingRule rule) { super(rule); } }
astamuse/asta4d
162
Java
org.eclipse.core.resources.prefs
text/plain
8,111,047,759,124,855,000
package com.astamuse.asta4d.sample.customrule; import com.astamuse.asta4d.web.dispatch.mapping.UrlMappingRule; import com.astamuse.asta4d.web.dispatch.mapping.handy.HandyRuleBuilder; @SuppressWarnings("unchecked") public interface CustomRuleBuilder extends HandyRuleBuilder { @Override default CustomRuleAfterAddSrc buildHandyRuleAfterAddSrc(UrlMappingRule rule) { return new CustomRuleAfterAddSrc(rule); } @Override default CustomRuleAfterAddSrcAndTarget buildHandyRuleAfterAddSrcAndTarget(UrlMappingRule rule) { return new CustomRuleAfterAddSrcAndTarget(rule); } }
astamuse/asta4d
162
Java
org.eclipse.core.resources.prefs
text/plain
-4,994,938,556,509,228,000
package com.astamuse.asta4d.sample.customrule; import com.astamuse.asta4d.web.dispatch.mapping.UrlMappingRule; import com.astamuse.asta4d.web.dispatch.mapping.handy.HandyRuleAfterAddSrc; import com.astamuse.asta4d.web.dispatch.mapping.handy.HandyRuleAfterAttr; import com.astamuse.asta4d.web.dispatch.mapping.handy.HandyRuleAfterHandler; @SuppressWarnings({ "rawtypes", "unchecked" }) public class CustomRuleAfterAddSrc extends HandyRuleAfterAddSrc<CustomRuleAfterAddSrc, HandyRuleAfterAttr<?, ?>, HandyRuleAfterHandler<?>> implements CustomRuleGroupConfigurable<CustomRuleAfterAddSrc>, CustomRuleBuilder { public CustomRuleAfterAddSrc(UrlMappingRule rule) { super(rule); } }
astamuse/asta4d
162
Java
org.eclipse.core.resources.prefs
text/plain
4,045,097,030,271,837,000
package com.astamuse.asta4d.sample.customrule; import com.astamuse.asta4d.web.dispatch.mapping.handy.base.HandyRuleConfigurable; public interface CustomRuleGroupConfigurable<T> extends HandyRuleConfigurable { default T group(String group) { configureRule(rule -> { rule.getExtraVarMap().put("CustomGroup", group); }); return (T) this; } }
astamuse/asta4d
162
Java
org.eclipse.core.resources.prefs
text/plain
5,776,985,730,571,547,000
/* * Copyright 2012 astamuse company,Ltd. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ package com.astamuse.asta4d.sample.forward; @SuppressWarnings("serial") public class LoginFailure extends Exception { }
astamuse/asta4d
162
Java
org.eclipse.core.resources.prefs
text/plain
-5,226,091,755,262,949,000
/* * Copyright 2012 astamuse company,Ltd. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ package com.astamuse.asta4d.sample.interceptor; import com.astamuse.asta4d.interceptor.PageInterceptor; import com.astamuse.asta4d.render.Renderer; public class SamplePageInterceptor implements PageInterceptor { @Override public void prePageRendering(Renderer renderer) { System.out.println("[SamplePageInterceptor:prePageRendering]"); } @Override public void postPageRendering(Renderer renderer) { System.out.println("[SamplePageInterceptor:postPageRendering]"); } }
astamuse/asta4d
162
Java
org.eclipse.core.resources.prefs
text/plain
-4,681,185,047,870,878,000
/* * Copyright 2012 astamuse company,Ltd. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ package com.astamuse.asta4d.sample.interceptor; import com.astamuse.asta4d.interceptor.base.ExceptionHandler; import com.astamuse.asta4d.snippet.SnippetExecutionHolder; import com.astamuse.asta4d.snippet.interceptor.SnippetInterceptor; public class SampleSnippetInterceptor implements SnippetInterceptor { @Override public boolean beforeProcess(SnippetExecutionHolder executionHolder) throws Exception { System.out.println("[SampleSnippetInterceptor:beforeProcess]" + getSnippetNameMethod(executionHolder)); return true; } public void afterProcess(SnippetExecutionHolder executionHolder, ExceptionHandler exceptionHandler) { System.out.println("[SampleSnippetInterceptor:afterProcess]" + getSnippetNameMethod(executionHolder)); } private String getSnippetNameMethod(SnippetExecutionHolder executionHolder) { return executionHolder.getDeclarationInfo().getSnippetName() + ":" + executionHolder.getMethod().getName(); } }
astamuse/asta4d
162
Java
org.eclipse.core.resources.prefs
text/plain
2,171,130,703,700,243,000
/* * Copyright 2012 astamuse company,Ltd. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ package com.astamuse.asta4d.sample.snippet; import static com.astamuse.asta4d.render.SpecialRenderer.Clear; import java.util.ArrayList; import java.util.Date; import java.util.List; import org.apache.commons.lang3.time.DateFormatUtils; import org.jsoup.nodes.Element; import org.jsoup.parser.Tag; import com.astamuse.asta4d.data.annotation.ContextData; import com.astamuse.asta4d.render.ChildReplacer; import com.astamuse.asta4d.render.GoThroughRenderer; import com.astamuse.asta4d.render.Renderer; import com.astamuse.asta4d.web.WebApplicationContext; import com.astamuse.asta4d.web.annotation.QueryParam; public class ComplicatedSnippet { // @ShowCode:showRenderertypesStart public Renderer render() { // a renderer which does nothing Renderer render = Renderer.create(); // replace all the children nodes of the corresponding node by selector render.add("ul#childreplacer", new ChildReplacer(createElement())); // remove a node render.add("ul#clearnode", Clear); // output the whole html string of current node to log console render.addDebugger("current element"); return render; } private Element createElement() { Element ul = new Element(Tag.valueOf("ul"), ""); ul.appendChild(new Element(Tag.valueOf("li"), "").appendText("This text is created by snippet.(1)")); ul.appendChild(new Element(Tag.valueOf("li"), "").appendText("This text is created by snippet.(2)")); ul.appendChild(new Element(Tag.valueOf("li"), "").appendText("This text is created by snippet.(3)")); return ul; } // @ShowCode:showRenderertypesEnd // @ShowCode:showPassvariablesStart public Renderer outer() { // prepare all necessary data for the inner snippet Renderer render = Renderer.create(); render.add("div#inner", "name", "baz"); render.add("div#inner", "age", "30"); render.add("div#inner", "currenttime", new Date()); List<String> list = new ArrayList<>(); list.add("This text is passed by outer snippet.(1)"); list.add("This text is passed by outer snippet.(2)"); list.add("This text is passed by outer snippet.(3)"); render.add("div#inner", "list", list); return render; } public Renderer inner(String name, int age, Date currenttime, List<String> list) { // receive the parameters by method declaration and then make use of them Renderer render = new GoThroughRenderer(); render.add("p#name span", name); render.add("p#age span", age); render.add("p#currenttime span", DateFormatUtils.format(currenttime, "yyyy/MM/dd HH:mm:ss")); render.add("ul#list li", list); return render; } // @ShowCode:showPassvariablesEnd // @ShowCode:showContextdataStart public Renderer changeName(@ContextData(name = "var") String changedName) { return Renderer.create("dd", changedName); } public Renderer specificScope(@ContextData(scope = WebApplicationContext.SCOPE_QUERYPARAM) String var) { return Renderer.create("dd", var == null ? "" : var); } public Renderer convenientAnnotation(@QueryParam String var) { return Renderer.create("dd", var == null ? "" : var); } // @ShowCode:showContextdataEnd // @ShowCode:showLocalizeStart public Renderer setMsgParam() { Renderer render = Renderer.create(); render.add("#peoplecount", "p0", 15); return render; } // @ShowCode:showLocalizeEnd }
astamuse/asta4d
162
Java
org.eclipse.core.resources.prefs
text/plain
2,982,897,612,065,211,400
/* * Copyright 2012 astamuse company,Ltd. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ package com.astamuse.asta4d.sample.snippet; import static com.astamuse.asta4d.render.SpecialRenderer.Clear; import org.apache.commons.lang3.StringUtils; import org.jsoup.nodes.Element; import com.astamuse.asta4d.render.GoThroughRenderer; import com.astamuse.asta4d.render.Renderer; import com.astamuse.asta4d.util.ElementUtil; public class SimpleSnippet { // @ShowCode:showSnippetStart // @ShowCode:showVariableinjectionStart public Renderer render(String name) { // replace the whole title node if (StringUtils.isEmpty(name)) { name = "Asta4D"; } Element element = ElementUtil.parseAsSingle("<div>Hello " + name + "!</div>"); return Renderer.create(":root", element); } public Renderer setProfileByVariableInjection(String name, int age) { Renderer render = Renderer.create(); render.add("p#name span", name); render.add("p#age span", age); return render; } // @ShowCode:showVariableinjectionEnd public Renderer setProfile() { Renderer render = Renderer.create(); render.add("p#name span", "asta4d"); render.add("p#age span", 20); return render; } // @ShowCode:showSnippetEnd // @ShowCode:showAttributevaluesStart public Renderer manipulateAttrValues() { Renderer render = new GoThroughRenderer(); render.add("input#yes", "checked", "checked"); render.add("button#delete", "disabled", Clear); render.add("li#plus", "+class", "red"); render.add("li#minus", "-class", "bold"); return render; } // @ShowCode:showAttributevaluesEnd public Renderer errorOccurs() { throw new RuntimeException("Error occurs at snippet side"); } }
astamuse/asta4d
162
Java
org.eclipse.core.resources.prefs
text/plain
1,442,589,655,846,230,500
/* * Copyright 2014 astamuse company,Ltd. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ package com.astamuse.asta4d.sample.snippet; import com.astamuse.asta4d.render.Renderer; public class ExtendSnippet { public Renderer renderTabs(String target) { return Renderer.create("#" + target, "+class", "active"); } }
astamuse/asta4d
162
Java
org.eclipse.core.resources.prefs
text/plain
-6,172,632,796,270,840,000
/* * Copyright 2012 astamuse company,Ltd. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ package com.astamuse.asta4d.sample.snippet; import java.util.ArrayList; import java.util.List; import org.apache.commons.lang3.StringUtils; import com.astamuse.asta4d.render.GoThroughRenderer; import com.astamuse.asta4d.render.Renderer; public class FormSnippet { // @ShowCode:showInputStart // @ShowCode:showConfirmStart // @ShowCode:showCompleteStart private enum BloodType { A, B, O, AB; } // @ShowCode:showConfirmEnd // @ShowCode:showCompleteEnd // @ShowCode:showInputEnd // @ShowCode:showInputStart public Renderer setInitValue(String name, String age, String bloodtype, String nameErrMsg, String ageErrMsg) { Renderer renderer = new GoThroughRenderer(); if (!StringUtils.isEmpty(name)) { renderer.add("input#name", "value", name); } if (!StringUtils.isEmpty(age)) { renderer.add("input#age", "value", age); } if (!StringUtils.isEmpty(nameErrMsg)) { renderer.add("span#nameErrMsg", nameErrMsg); } if (!StringUtils.isEmpty(ageErrMsg)) { renderer.add("span#ageErrMsg", ageErrMsg); } List<Renderer> options = new ArrayList<>(); for (BloodType bloodTypeEnum : BloodType.values()) { Renderer type = Renderer.create("option", "value", bloodTypeEnum.name()); type.add("option", bloodTypeEnum.name()); if (bloodTypeEnum.name().equals(bloodtype)) { type.add("option", "selected", "selected"); } options.add(type); } renderer.add("select#bloodtype > option", options); return renderer; } // @ShowCode:showInputEnd // @ShowCode:showConfirmStart // @ShowCode:showCompleteStart public Renderer setInputValue(String name, String age, String bloodtype) { Renderer renderer = new GoThroughRenderer(); renderer.add("dd.name", name); renderer.add("dd.age", age); renderer.add("dd.bloodtype", BloodType.valueOf(bloodtype).name()); return renderer; } // @ShowCode:showCompleteEnd public Renderer setHiddenValue(String name, String age, String bloodtype) { Renderer renderer = new GoThroughRenderer(); renderer.add("input#name", "value", name); renderer.add("input#age", "value", age); renderer.add("input#bloodtype", "value", bloodtype); return renderer; } // @ShowCode:showConfirmEnd }
astamuse/asta4d
162
Java
org.eclipse.core.resources.prefs
text/plain
4,447,435,715,418,720,000
/* * Copyright 2012 astamuse company,Ltd. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ package com.astamuse.asta4d.sample.snippet; import java.io.BufferedReader; import java.io.FileInputStream; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import javax.servlet.ServletContext; import javax.servlet.http.HttpServletRequest; import org.apache.commons.lang3.StringUtils; import org.jsoup.nodes.Element; import org.jsoup.parser.Tag; import com.astamuse.asta4d.render.GoThroughRenderer; import com.astamuse.asta4d.render.Renderer; public class ShowCodeSnippet { private static final String JAVA_PACKAGE = "/com/astamuse/asta4d/sample"; private static final String VM_ARG = "asta4d.sample.source_location"; private static final String SHOW_MARK = "@ShowCode:"; public Renderer showCode(HttpServletRequest request, String file, String startMark, String endMark, String title) { Renderer render = new GoThroughRenderer(); ServletContext servletContext = request.getSession().getServletContext(); String contents = readFileByLines(servletContext, file, SHOW_MARK + startMark, SHOW_MARK + endMark); render.add("div", makeShowHtml(file, title, contents)); return render; } private Element makeShowHtml(String file, String title, String contents) { // create the panel tag Element panel = new Element(Tag.valueOf("div"), ""); panel.addClass("panel"); panel.addClass("panel-default"); Element heading = new Element(Tag.valueOf("div"), ""); heading.addClass("panel-heading"); Element body = new Element(Tag.valueOf("div"), ""); body.addClass("panel-body"); panel.appendChild(heading); panel.appendChild(body); // write title and file path String headStr = StringUtils.isEmpty(title) ? "" : title + ":"; headStr += file; heading.appendText(headStr); // create the pre tag Element pre = new Element(Tag.valueOf("pre"), ""); pre.addClass("prettyprint source"); pre.attr("style", "overflow-x:auto"); if (contents != null) { pre.appendChild(new Element(Tag.valueOf("span"), "").appendText(contents)); } body.appendChild(pre); return panel; } private static String readFileByLines(ServletContext servletContext, String fileName, String startMark, String endMark) { String filePath = ""; InputStream inputStream = null; BufferedReader reader = null; try { // read the file if (fileName.endsWith(".java")) { String source_location = System.getProperty(VM_ARG); if (source_location != null) { filePath = source_location + JAVA_PACKAGE + fileName; inputStream = new FileInputStream(filePath); } else { filePath = "/WEB-INF/src" + JAVA_PACKAGE + fileName; inputStream = servletContext.getResourceAsStream(filePath); } } else { inputStream = servletContext.getResourceAsStream(fileName); } if (inputStream == null) { return null; } // find the line that has the mark reader = new BufferedReader(new InputStreamReader(inputStream, "utf-8")); String line = null; String contents = ""; int markStart = -1; while ((line = reader.readLine()) != null) { if (line.contains(endMark)) { break; } if (markStart >= 0 && !line.contains(SHOW_MARK)) { if (line.length() <= markStart) { line = ""; } else { line = line.substring(markStart); } contents = contents + line + "\n"; } if (line.contains(startMark)) { String trim = line.trim(); markStart = line.indexOf(trim); } } return contents; } catch (IOException e) { return null; // close } finally { if (reader != null) { try { reader.close(); } catch (IOException e1) { } } if (inputStream != null) { try { inputStream.close(); } catch (IOException e1) { } } } } }
astamuse/asta4d
162
Java
org.eclipse.core.resources.prefs
text/plain
8,262,983,917,491,343,000
/* * Copyright 2012 astamuse company,Ltd. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ package com.astamuse.asta4d.sample.snippet.form; import java.util.LinkedList; import java.util.List; import com.astamuse.asta4d.sample.handler.form.PersonForm; import com.astamuse.asta4d.sample.util.persondb.Person.BloodType; import com.astamuse.asta4d.sample.util.persondb.Person.Language; import com.astamuse.asta4d.sample.util.persondb.Person.SEX; import com.astamuse.asta4d.web.form.field.FormFieldPrepareRenderer; import com.astamuse.asta4d.web.form.field.impl.CheckboxPrepareRenderer; import com.astamuse.asta4d.web.form.field.impl.RadioPrepareRenderer; import com.astamuse.asta4d.web.form.field.impl.SelectPrepareRenderer; import com.astamuse.asta4d.web.form.flow.classical.OneStepFormSnippetTrait; //@ShowCode:showSingleStepFormSnippetStart public class SingleStepFormSnippet implements OneStepFormSnippetTrait { /** * override this method to supply the option data for select, radio and checkbox. */ @Override public List<FormFieldPrepareRenderer> retrieveFieldPrepareRenderers(String renderTargetStep, Object form) { List<FormFieldPrepareRenderer> list = new LinkedList<>(); list.add(new SelectPrepareRenderer(PersonForm.class, "bloodtype").setOptionData(BloodType.asOptionValueMap)); list.add(new RadioPrepareRenderer(PersonForm.class, "sex").setOptionData(SEX.asOptionValueMap)); list.add(new CheckboxPrepareRenderer(PersonForm.class, "language").setOptionData(Language.asOptionValueMap)); return list; } } // @ShowCode:showSingleStepFormSnippetEnd
astamuse/asta4d
162
Java
org.eclipse.core.resources.prefs
text/plain
-5,426,760,933,415,605,000
/* * Copyright 2012 astamuse company,Ltd. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ package com.astamuse.asta4d.sample.snippet.form; import com.astamuse.asta4d.sample.snippet.form.common.Asta4DSamplePrjCommonFormSnippet; //@ShowCode:showMultiStepFormSnippetStart public class MultiStepFormSnippet extends Asta4DSamplePrjCommonFormSnippet { // we do not need to do anything here. } // @ShowCode:showMultiStepFormSnippetEnd
astamuse/asta4d
162
Java
org.eclipse.core.resources.prefs
text/plain
-5,722,589,600,747,043,000
/* * Copyright 2012 astamuse company,Ltd. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ package com.astamuse.asta4d.sample.snippet.form; import java.util.ArrayList; import java.util.LinkedList; import java.util.List; import com.astamuse.asta4d.sample.handler.form.PersonForm; import com.astamuse.asta4d.sample.handler.form.cascade.EducationForm; import com.astamuse.asta4d.sample.util.persondb.Person.BloodType; import com.astamuse.asta4d.sample.util.persondb.Person.Language; import com.astamuse.asta4d.sample.util.persondb.Person.SEX; import com.astamuse.asta4d.web.form.field.FormFieldPrepareRenderer; import com.astamuse.asta4d.web.form.field.OptionValueMap; import com.astamuse.asta4d.web.form.field.OptionValuePair; import com.astamuse.asta4d.web.form.field.impl.CheckboxPrepareRenderer; import com.astamuse.asta4d.web.form.field.impl.RadioPrepareRenderer; import com.astamuse.asta4d.web.form.field.impl.SelectPrepareRenderer; import com.astamuse.asta4d.web.form.flow.classical.ClassicalMultiStepFormFlowSnippetTrait; //@ShowCode:showCascadeFormSnippetStart public class CascadeFormSnippet implements ClassicalMultiStepFormFlowSnippetTrait { @Override public List<FormFieldPrepareRenderer> retrieveFieldPrepareRenderers(String renderTargetStep, Object form) { List<FormFieldPrepareRenderer> list = new LinkedList<>(); // since there are cascade forms, so we have to differentiate the option data rendering for different forms if (form instanceof PersonForm) { list.add(new SelectPrepareRenderer(PersonForm.class, "bloodtype").setOptionData(BloodType.asOptionValueMap)); list.add(new RadioPrepareRenderer(PersonForm.class, "sex").setOptionData(SEX.asOptionValueMap)); list.add(new CheckboxPrepareRenderer(PersonForm.class, "language").setOptionData(Language.asOptionValueMap)); } else if (form instanceof EducationForm) { // to render the option data of arrayed form fields, simply use the field name with "@" mark as the same as plain fields list.add(new SelectPrepareRenderer(EducationForm.class, "education-year-@").setOptionData(createYearOptionList())); } return list; } private OptionValueMap createYearOptionList() { List<OptionValuePair> optionList = new ArrayList<>(); for (int y = 2000; y <= 2010; y++) { optionList.add(new OptionValuePair(String.valueOf(y), String.valueOf(y))); } return new OptionValueMap(optionList); } @Override public Object createFormInstanceForCascadeFormArrayTemplate(Class subFormType) throws InstantiationException, IllegalAccessException { Object form = ClassicalMultiStepFormFlowSnippetTrait.super.createFormInstanceForCascadeFormArrayTemplate(subFormType); ((EducationForm) form).setPersonId(-1); return form; } @Override public String clientCascadeUtilJsExportName() { return "$acu"; } } // @ShowCode:showCascadeFormSnippetEnd
astamuse/asta4d
162
Java
org.eclipse.core.resources.prefs
text/plain
7,759,450,769,891,343,000
/* * Copyright 2012 astamuse company,Ltd. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ package com.astamuse.asta4d.sample.snippet.form; import java.util.ArrayList; import java.util.LinkedList; import java.util.List; import com.astamuse.asta4d.sample.handler.form.JobForm; import com.astamuse.asta4d.sample.handler.form.JobPositionForm; import com.astamuse.asta4d.sample.handler.form.PersonForm; import com.astamuse.asta4d.sample.snippet.form.common.Asta4DSamplePrjCommonFormSnippet; import com.astamuse.asta4d.sample.util.persondb.Person.BloodType; import com.astamuse.asta4d.sample.util.persondb.Person.Language; import com.astamuse.asta4d.sample.util.persondb.Person.SEX; import com.astamuse.asta4d.web.form.field.FormFieldPrepareRenderer; import com.astamuse.asta4d.web.form.field.OptionValueMap; import com.astamuse.asta4d.web.form.field.OptionValuePair; import com.astamuse.asta4d.web.form.field.impl.CheckboxPrepareRenderer; import com.astamuse.asta4d.web.form.field.impl.RadioPrepareRenderer; import com.astamuse.asta4d.web.form.field.impl.SelectPrepareRenderer; import com.astamuse.asta4d.web.form.flow.ext.MultiInputStepFormFlowSnippetTrait; //@ShowCode:showSplittedFormSnippetStart public class MultiInputFormSnippet extends Asta4DSamplePrjCommonFormSnippet implements MultiInputStepFormFlowSnippetTrait { @Override public List<FormFieldPrepareRenderer> retrieveFieldPrepareRenderers(String renderTargetStep, Object form) { List<FormFieldPrepareRenderer> list = new LinkedList<>(); // since there are cascade forms, so we have to differentiate the option data rendering for different forms if (form instanceof PersonForm) { list.add(new SelectPrepareRenderer(PersonForm.class, "bloodtype").setOptionData(BloodType.asOptionValueMap)); list.add(new RadioPrepareRenderer(PersonForm.class, "sex").setOptionData(SEX.asOptionValueMap)); list.add(new CheckboxPrepareRenderer(PersonForm.class, "language").setOptionData(Language.asOptionValueMap)); } else if (form instanceof JobForm) { // to render the option data of arrayed form fields, simply use the field name with "@" mark as the same as plain fields list.add(new SelectPrepareRenderer(JobForm.class, "job-year-@").setOptionData(createYearOptionList())); } return list; } private OptionValueMap createYearOptionList() { List<OptionValuePair> optionList = new ArrayList<>(); for (int y = 2000; y <= 2010; y++) { optionList.add(new OptionValuePair(String.valueOf(y), String.valueOf(y))); } return new OptionValueMap(optionList); } @Override public Object createFormInstanceForCascadeFormArrayTemplate(Class subFormType) throws InstantiationException, IllegalAccessException { Object form = super.createFormInstanceForCascadeFormArrayTemplate(subFormType); if (subFormType.equals(JobForm.class)) { ((JobForm) form).setPersonId(-1); } else if (subFormType.equals(JobPositionForm.class)) { ((JobPositionForm) form).setJobId(-1); } return form; } @Override public String clientCascadeUtilJsExportName() { return "$acu"; } } // @ShowCode:showSplittedFormSnippetEnd
astamuse/asta4d
162
Java
org.eclipse.core.resources.prefs
text/plain
-423,156,277,327,645,300
/* * Copyright 2014 astamuse company,Ltd. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ package com.astamuse.asta4d.sample.snippet.form; import static com.astamuse.asta4d.render.SpecialRenderer.Clear; import java.util.Arrays; import java.util.List; import com.astamuse.asta4d.render.Renderer; import com.astamuse.asta4d.sample.util.persondb.Person; import com.astamuse.asta4d.sample.util.persondb.PersonDbManager; import com.astamuse.asta4d.util.SelectorUtil; import com.astamuse.asta4d.web.annotation.QueryParam; public class ListSnippet { public Renderer render() { List<Person> personList = PersonDbManager.instance().findAll(); return Renderer.create(".x-row", personList, (p) -> { Renderer renderer = Renderer.create(); renderer.add(".x-check input", "value", p.getId()); renderer.add(".x-name", p.getName()); renderer.add(".x-age", p.getAge()); renderer.add(".x-sex", p.getSex()); renderer.add(".x-blood", p.getBloodType()); renderer.add(".x-language span", Arrays.asList(p.getLanguage())); return renderer; }); } public Renderer showTabs(@QueryParam String type) { Renderer renderer = Renderer.create(); renderer.add("li", "-class", "active"); String targetLi = SelectorUtil.id("li", type); renderer.add(targetLi, "+class", "active"); renderer.add(targetLi + " a", "href", Clear); String targetBtn = SelectorUtil.id("div", type); renderer.add(targetBtn, "-class", "x-remove"); renderer.add(".x-remove", Clear); return renderer; } }
astamuse/asta4d
162
Java
org.eclipse.core.resources.prefs
text/plain
618,775,758,301,585,300
/* * Copyright 2012 astamuse company,Ltd. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ package com.astamuse.asta4d.sample.snippet.form; import java.util.ArrayList; import java.util.LinkedList; import java.util.List; import com.astamuse.asta4d.sample.handler.form.JobForm; import com.astamuse.asta4d.sample.handler.form.JobPositionForm; import com.astamuse.asta4d.sample.handler.form.PersonForm; import com.astamuse.asta4d.sample.handler.form.splittedinput.SplittedInputForm; import com.astamuse.asta4d.sample.snippet.form.common.Asta4DSamplePrjCommonFormSnippet; import com.astamuse.asta4d.sample.util.persondb.Person.BloodType; import com.astamuse.asta4d.sample.util.persondb.Person.Language; import com.astamuse.asta4d.sample.util.persondb.Person.SEX; import com.astamuse.asta4d.web.form.field.FormFieldPrepareRenderer; import com.astamuse.asta4d.web.form.field.OptionValueMap; import com.astamuse.asta4d.web.form.field.OptionValuePair; import com.astamuse.asta4d.web.form.field.impl.CheckboxPrepareRenderer; import com.astamuse.asta4d.web.form.field.impl.RadioPrepareRenderer; import com.astamuse.asta4d.web.form.field.impl.SelectPrepareRenderer; import com.astamuse.asta4d.web.form.flow.ext.MultiInputStepFormFlowSnippetTrait; import com.astamuse.asta4d.web.form.flow.ext.ExcludingFieldRetrievableFormRenderable; //@ShowCode:showSplittedFormSnippetStart public class SplittedInputFormSnippet extends Asta4DSamplePrjCommonFormSnippet implements MultiInputStepFormFlowSnippetTrait, ExcludingFieldRetrievableFormRenderable { @Override public List<FormFieldPrepareRenderer> retrieveFieldPrepareRenderers(String renderTargetStep, Object form) { List<FormFieldPrepareRenderer> list = new LinkedList<>(); // since there are cascade forms, so we can differentiate the option data rendering for different forms with the concern of // performance if (form instanceof SplittedInputForm.PersonFormStep1 || form instanceof SplittedInputForm.ConfirmStepForm) { list.add(new SelectPrepareRenderer(PersonForm.class, "bloodtype").setOptionData(BloodType.asOptionValueMap)); list.add(new RadioPrepareRenderer(PersonForm.class, "sex").setOptionData(SEX.asOptionValueMap)); } if (form instanceof SplittedInputForm.PersonFormStep2 || form instanceof SplittedInputForm.ConfirmStepForm) { list.add(new CheckboxPrepareRenderer(PersonForm.class, "language").setOptionData(Language.asOptionValueMap)); } if (form instanceof JobForm) { // to render the option data of arrayed form fields, simply use the field name with "@" mark as the same as plain fields list.add(new SelectPrepareRenderer(JobForm.class, "job-year-@").setOptionData(createYearOptionList())); } return list; } private OptionValueMap createYearOptionList() { List<OptionValuePair> optionList = new ArrayList<>(); for (int y = 2000; y <= 2010; y++) { optionList.add(new OptionValuePair(String.valueOf(y), String.valueOf(y))); } return new OptionValueMap(optionList); } @Override public Object createFormInstanceForCascadeFormArrayTemplate(Class subFormType) throws InstantiationException, IllegalAccessException { Object form = super.createFormInstanceForCascadeFormArrayTemplate(subFormType); if (subFormType.equals(JobForm.class)) { ((JobForm) form).setPersonId(-1); } else if (subFormType.equals(JobPositionForm.class)) { ((JobPositionForm) form).setJobId(-1); } return form; } @Override public String clientCascadeUtilJsExportName() { return "$acu"; } } // @ShowCode:showSplittedFormSnippetEnd
astamuse/asta4d
162
Java
org.eclipse.core.resources.prefs
text/plain
-4,693,760,140,119,641,000
/* * Copyright 2014 astamuse company,Ltd. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ package com.astamuse.asta4d.sample.snippet.form.common; import com.astamuse.asta4d.web.form.flow.classical.ClassicalMultiStepFormFlowSnippetTrait; //@ShowCode:showCommonFormSnippetStart /** * This class is used to configure the common action of snippet rendering. For most cases, it could be an empty class body. */ public abstract class Asta4DSamplePrjCommonFormSnippet implements ClassicalMultiStepFormFlowSnippetTrait { } // @ShowCode:showCommonFormSnippetEnd
astamuse/asta4d
162
Java
org.eclipse.core.resources.prefs
text/plain
-6,852,987,606,684,799,000
<?xml version="1.0" encoding="UTF-8"?> <faceted-project> <fixed facet="wst.jsdt.web"/> <installed facet="jst.web" version="2.5"/> <installed facet="wst.jsdt.web" version="1.0"/> <installed facet="java" version="1.8"/> </faceted-project>
astamuse/asta4d
162
Java
org.eclipse.core.resources.prefs
text/plain
7,545,017,720,037,511,000
eclipse.preferences.version=1 encoding//src/main/java=UTF-8 encoding//src/main/resources=UTF-8 encoding//src/main/resources/BeanValidationMessages_ja.properties=UTF-8 encoding//src/main/resources/messages_ja.properties=UTF-8 encoding//src/test/java=UTF-8 encoding/<project>=UTF-8
astamuse/asta4d
162
Java
org.eclipse.core.resources.prefs
text/plain
-7,909,126,198,336,186,000
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> <modelVersion>4.0.0</modelVersion> <groupId>com.asta4d</groupId> <artifactId>asta4d-archetype-prototype</artifactId> <version>1.2.1-SNAPSHOT</version> <packaging>war</packaging> <name>com.asta4d.asta4d-archetype-prototype</name> <description>sample of asta4d framework, shows how to use asta4d</description> <properties> <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding> </properties> <dependencies> <dependency> <groupId>com.astamuse</groupId> <artifactId>asta4d-web</artifactId> <!--asta4dversion--> <version>${project.version}</version> <!--asta4dversion--> </dependency> <dependency> <groupId>org.hibernate</groupId> <artifactId>hibernate-validator</artifactId> <version>5.0.2.Final</version> </dependency> <dependency> <groupId>javax.servlet</groupId> <artifactId>servlet-api</artifactId> <version>2.5</version> <scope>provided</scope> </dependency> </dependencies> <build> <plugins> <plugin> <groupId>org.apache.maven.plugins</groupId> <artifactId>maven-compiler-plugin</artifactId> <version>3.3</version> <configuration> <source>1.8</source> <target>1.8</target> <compilerArgs> <arg>-parameters</arg> </compilerArgs> </configuration> </plugin> <plugin> <groupId>org.eclipse.jetty</groupId> <artifactId>jetty-maven-plugin</artifactId> <version>9.2.8.v20150217</version> <configuration> <webApp> <contextPath>/</contextPath> </webApp> <systemProperties> <systemProperty> <name>asta4d.sample.debug</name> <value>true</value> </systemProperty> <systemProperty> <name>asta4d.sample.source_location</name> <value>${basedir}/src/main/java</value> </systemProperty> </systemProperties> </configuration> </plugin> <!-- archetypePluginRemove --> <!-- Don't remove the above comment which is used for remove redundant declarations for a archetype --> <plugin> <groupId>org.apache.maven.plugins</groupId> <artifactId>maven-deploy-plugin</artifactId> <version>2.7</version> <configuration> <skip>true</skip> </configuration> </plugin> <plugin> <groupId>org.apache.maven.plugins</groupId> <artifactId>maven-archetype-plugin</artifactId> <version>2.2</version> <executions> <execution> <id>archetype-run</id> <phase>package</phase> <goals> <goal>create-from-project</goal> </goals> </execution> </executions> </plugin> <plugin> <artifactId>maven-antrun-plugin</artifactId> <version>1.7</version> <executions> <execution> <phase>package</phase> <goals> <goal>run</goal> </goals> <configuration> <target> <delete dir="../asta4d-archetype/src/main/resources/META-INF"/> <copy todir="../asta4d-archetype/src/main/resources/META-INF"> <fileset dir="target/generated-sources/archetype/src/main/resources/META-INF" includes="**/*" /> </copy> <delete dir="../asta4d-archetype/src/main/resources/archetype-resources/src"/> <copy todir="../asta4d-archetype/src/main/resources/archetype-resources/src"> <fileset dir="target/generated-sources/archetype/src/main/resources/archetype-resources/src" includes="**/*" /> </copy> <copy tofile="../asta4d-archetype/src/main/resources/archetype-resources/pom.xml" file="target/generated-sources/archetype/src/main/resources/archetype-resources/pom.xml" /> <replaceregexp file="../asta4d-archetype/src/main/resources/archetype-resources/pom.xml" match="archetypePluginRemove(.*)archetypePluginRemove" replace="" byline="false" flags="gs" encoding="utf-8" /> <replaceregexp file="../asta4d-archetype/src/main/resources/archetype-resources/pom.xml" match="(asta4dversion.*)(\$\{project\.version\})(.*asta4dversion)" replace="\1${project.version}\3" byline="false" flags="gs" encoding="utf-8" /> </target> </configuration> </execution> </executions> </plugin> <!-- archetypePluginRemove --> </plugins> </build> </project>
astamuse/asta4d
162
Java
org.eclipse.core.resources.prefs
text/plain
-7,569,965,594,163,047,000
<?xml version="1.0" encoding="UTF-8" standalone="no"?> <launchConfiguration type="org.testng.eclipse.launchconfig"> <listAttribute key="com.mountainminds.eclemma.core.SCOPE_IDS"> <listEntry value="=asta4d-core/src\/main\/java"/> </listAttribute> <stringAttribute key="org.eclipse.jdt.launching.CLASSPATH_PROVIDER" value="org.eclipse.m2e.launchconfig.classpathProvider"/> <stringAttribute key="org.eclipse.jdt.launching.MAIN_TYPE" value="org.testng.remote.RemoteTestNG"/> <stringAttribute key="org.eclipse.jdt.launching.PROJECT_ATTR" value="asta4d-core"/> <stringAttribute key="org.eclipse.jdt.launching.SOURCE_PATH_PROVIDER" value="org.eclipse.m2e.launchconfig.sourcepathProvider"/> <mapAttribute key="org.testng.eclipse.ALL_CLASS_METHODS"/> <listAttribute key="org.testng.eclipse.CLASS_TEST_LIST"/> <listAttribute key="org.testng.eclipse.GROUP_LIST"/> <listAttribute key="org.testng.eclipse.GROUP_LIST_CLASS"/> <stringAttribute key="org.testng.eclipse.LOG_LEVEL" value="2"/> <listAttribute key="org.testng.eclipse.PACKAGE_TEST_LIST"> <listEntry value="com.astamuse.asta4d.test.unit"/> <listEntry value="com.astamuse.asta4d.test.render"/> <listEntry value="com.astamuse.asta4d.test.unit"/> <listEntry value="com.astamuse.asta4d.test.unit"/> </listAttribute> <intAttribute key="org.testng.eclipse.TYPE" value="5"/> </launchConfiguration>
astamuse/asta4d
162
Java
org.eclipse.core.resources.prefs
text/plain
5,069,888,070,021,669,000
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> <modelVersion>4.0.0</modelVersion> <parent> <groupId>com.astamuse</groupId> <artifactId>asta4d</artifactId> <version>1.2.1-SNAPSHOT</version> </parent> <groupId>com.astamuse</groupId> <artifactId>asta4d-core</artifactId> <packaging>jar</packaging> <name>com.astamuse.asta4d-core</name> <description>core functionalities of asta4d framework, including template and snippt implemention</description> <dependencies> <dependency> <!-- jsoup HTML parser library @ http://jsoup.org/ --> <groupId>org.jsoup</groupId> <artifactId>jsoup</artifactId> <version>1.8.1</version> </dependency> <dependency> <groupId>org.apache.commons</groupId> <artifactId>commons-lang3</artifactId> <version>3.1</version> </dependency> <dependency> <groupId>org.apache.commons</groupId> <artifactId>commons-collections4</artifactId> <version>4.0</version> </dependency> <dependency> <groupId>com.thoughtworks.paranamer</groupId> <artifactId>paranamer</artifactId> <version>2.7</version> </dependency> <dependency> <groupId>joda-time</groupId> <artifactId>joda-time</artifactId> <version>2.5</version> </dependency> </dependencies> <build> <plugins> <plugin> <groupId>org.codehaus.mojo</groupId> <artifactId>build-helper-maven-plugin</artifactId> <executions> <execution> <phase>generate-sources</phase> <goals> <goal>add-source</goal> </goals> <configuration> <sources> <source>src/main/jsoup</source> </sources> </configuration> </execution> </executions> </plugin> <plugin> <groupId>org.apache.maven.plugins</groupId> <artifactId>maven-jar-plugin</artifactId> <version>2.5</version> <executions> <execution> <goals> <goal>test-jar</goal> </goals> </execution> </executions> </plugin> <plugin> <groupId>org.apache.maven.plugins</groupId> <artifactId>maven-surefire-plugin</artifactId> <version>2.18.1</version> </plugin> <plugin> <groupId>org.apache.maven.plugins</groupId> <artifactId>maven-site-plugin</artifactId> <version>3.3</version> </plugin> <plugin> <groupId>org.codehaus.mojo</groupId> <artifactId>cobertura-maven-plugin</artifactId> <version>2.6</version> <configuration> <instrumentation> <excludes> <exclude>org\jsoup\parser\*</exclude> </excludes> </instrumentation> </configuration> <executions> <execution> <goals> <goal>clean</goal> </goals> </execution> </executions> </plugin> <plugin> <groupId>org.apache.maven.plugins</groupId> <artifactId>maven-surefire-report-plugin</artifactId> <version>2.18.1</version> <executions> <execution> <phase>test</phase> <goals> <goal>report-only</goal> </goals> </execution> </executions> </plugin> </plugins> </build> <reporting> <plugins> <plugin> <groupId>org.codehaus.mojo</groupId> <artifactId>cobertura-maven-plugin</artifactId> <version>2.6</version> </plugin> <plugin> <groupId>org.apache.maven.plugins</groupId> <artifactId>maven-surefire-report-plugin</artifactId> <version>2.18.1</version> <reportSets> <reportSet> <reports> <report>report-only</report> </reports> </reportSet> </reportSets> </plugin> </plugins> </reporting> </project>
astamuse/asta4d
162
Java
org.eclipse.core.resources.prefs
text/plain
-470,456,365,185,271,500
package org.jsoup.parser; import java.util.Iterator; import java.util.LinkedList; import org.apache.commons.lang3.ArrayUtils; import org.jsoup.helper.DescendableLinkedList; import org.jsoup.helper.StringUtil; import org.jsoup.nodes.Attribute; import org.jsoup.nodes.Attributes; import org.jsoup.nodes.Document; import org.jsoup.nodes.DocumentType; import org.jsoup.nodes.Element; import org.jsoup.nodes.Node; import org.jsoup.parser.Token.StartTag; import com.astamuse.asta4d.extnode.ExtNodeConstants; /* * Search "ExtNodeConstants" to locate the customized logic for asta4d tags support * * */ /** * The Tree Builder's current state. Each state embodies the processing for the state, and transitions to other states. */ enum Asta4DTagSupportHtmlTreeBuilderState { Initial { boolean process(Token t, Asta4DTagSupportHtmlTreeBuilder tb) { if (isWhitespace(t)) { return true; // ignore whitespace } else if (t.isComment()) { tb.insert(t.asComment()); } else if (t.isDoctype()) { // todo: parse error check on expected doctypes // todo: quirk state check on doctype ids Token.Doctype d = t.asDoctype(); DocumentType doctype = new DocumentType(d.getName(), d.getPublicIdentifier(), d.getSystemIdentifier(), tb.getBaseUri()); tb.getDocument().appendChild(doctype); if (d.isForceQuirks()) tb.getDocument().quirksMode(Document.QuirksMode.quirks); tb.transition(BeforeHtml); } else { // todo: check not iframe srcdoc tb.transition(BeforeHtml); return tb.process(t); // re-process token } return true; } }, BeforeHtml { boolean process(Token t, Asta4DTagSupportHtmlTreeBuilder tb) { if (t.isDoctype()) { tb.error(this); return false; } else if (t.isComment()) { tb.insert(t.asComment()); } else if (isWhitespace(t)) { return true; // ignore whitespace } else if (t.isStartTag() && t.asStartTag().name().equals("html")) { tb.insert(t.asStartTag()); tb.transition(BeforeHead); } else if (t.isEndTag() && (StringUtil.in(t.asEndTag().name(), "head", "body", "html", "br"))) { return anythingElse(t, tb); } else if (t.isEndTag()) { tb.error(this); return false; } else { return anythingElse(t, tb); } return true; } private boolean anythingElse(Token t, Asta4DTagSupportHtmlTreeBuilder tb) { tb.insert("html"); tb.transition(BeforeHead); return tb.process(t); } }, BeforeHead { boolean process(Token t, Asta4DTagSupportHtmlTreeBuilder tb) { if (isWhitespace(t)) { return true; } else if (t.isComment()) { tb.insert(t.asComment()); } else if (t.isDoctype()) { tb.error(this); return false; } else if (t.isStartTag() && t.asStartTag().name().equals("html")) { return InBody.process(t, tb); // does not transition } else if (t.isStartTag() && t.asStartTag().name().equals("head")) { Element head = tb.insert(t.asStartTag()); tb.setHeadElement(head); tb.transition(InHead); } else if (t.isEndTag() && (StringUtil.in(t.asEndTag().name(), "head", "body", "html", "br"))) { tb.process(new Token.StartTag("head")); return tb.process(t); } else if (t.isEndTag()) { tb.error(this); return false; } else { tb.process(new Token.StartTag("head")); return tb.process(t); } return true; } }, InHead { boolean process(Token t, Asta4DTagSupportHtmlTreeBuilder tb) { if (isWhitespace(t)) { tb.insert(t.asCharacter()); return true; } switch (t.type) { case Comment: tb.insert(t.asComment()); break; case Doctype: tb.error(this); return false; case StartTag: Token.StartTag start = t.asStartTag(); String name = start.name(); if (name.equals("html")) { return InBody.process(t, tb); } else if (StringUtil.in(name, "base", "basefont", "bgsound", "command", "link")) { Element el = tb.insertEmpty(start); // jsoup special: update base the frist time it is seen if (name.equals("base") && el.hasAttr("href")) tb.maybeSetBaseUri(el); } else if (name.equals("meta")) { Element meta = tb.insertEmpty(start); // todo: charset switches } else if (name.equals("title")) { handleRcData(start, tb); } else if (StringUtil.in(name, "noframes", "style")) { handleRawtext(start, tb); } else if (name.equals("noscript")) { // else if noscript && scripting flag = true: rawtext (jsoup doesn't run script, to handle as noscript) tb.insert(start); tb.transition(InHeadNoscript); } else if (name.equals("script")) { // skips some script rules as won't execute them tb.tokeniser.transition(TokeniserState.ScriptData); tb.markInsertionMode(); tb.transition(Text); tb.insert(start); } else if (name.equals("head")) { tb.error(this); return false; // asta4d customization start } else if (ArrayUtils.contains(ExtNodeConstants.ASTA4D_IN_HEAD_NODE_TAGS, name)) { // here, we allow asta4d tags in head tb.insert(start); // asta4d customization end } else { return anythingElse(t, tb); } break; case EndTag: Token.EndTag end = t.asEndTag(); name = end.name(); if (name.equals("head")) { tb.pop(); tb.transition(AfterHead); } else if (StringUtil.in(name, "body", "html", "br")) { return anythingElse(t, tb); // asta4d customization start } else if (ArrayUtils.contains(ExtNodeConstants.ASTA4D_IN_HEAD_NODE_TAGS, name)) { // copy these sources from InBody, I think it works well. if (!tb.inScope(name)) { // nothing to close tb.error(this); return false; } else { tb.generateImpliedEndTags(); if (!tb.currentElement().nodeName().equals(name)) tb.error(this); tb.popStackToClose(name); } // asta4d customization end } else { tb.error(this); return false; } break; // asta4d customization start case Character: tb.insert(t.asCharacter()); break; // asta4d customization end default: return anythingElse(t, tb); } return true; } private boolean anythingElse(Token t, TreeBuilder tb) { tb.process(new Token.EndTag("head")); return tb.process(t); } }, InHeadNoscript { boolean process(Token t, Asta4DTagSupportHtmlTreeBuilder tb) { if (t.isDoctype()) { tb.error(this); } else if (t.isStartTag() && t.asStartTag().name().equals("html")) { return tb.process(t, InBody); } else if (t.isEndTag() && t.asEndTag().name().equals("noscript")) { tb.pop(); tb.transition(InHead); } else if (isWhitespace(t) || t.isComment() || (t.isStartTag() && StringUtil.in(t.asStartTag().name(), "basefont", "bgsound", "link", "meta", "noframes", "style"))) { return tb.process(t, InHead); } else if (t.isEndTag() && t.asEndTag().name().equals("br")) { return anythingElse(t, tb); } else if ((t.isStartTag() && StringUtil.in(t.asStartTag().name(), "head", "noscript")) || t.isEndTag()) { tb.error(this); return false; } else { return anythingElse(t, tb); } return true; } private boolean anythingElse(Token t, Asta4DTagSupportHtmlTreeBuilder tb) { tb.error(this); tb.process(new Token.EndTag("noscript")); return tb.process(t); } }, AfterHead { boolean process(Token t, Asta4DTagSupportHtmlTreeBuilder tb) { if (isWhitespace(t)) { tb.insert(t.asCharacter()); } else if (t.isComment()) { tb.insert(t.asComment()); } else if (t.isDoctype()) { tb.error(this); } else if (t.isStartTag()) { Token.StartTag startTag = t.asStartTag(); String name = startTag.name(); if (name.equals("html")) { return tb.process(t, InBody); } else if (name.equals("body")) { tb.insert(startTag); tb.framesetOk(false); tb.transition(InBody); } else if (name.equals("frameset")) { tb.insert(startTag); tb.transition(InFrameset); } else if (StringUtil.in(name, "base", "basefont", "bgsound", "link", "meta", "noframes", "script", "style", "title")) { tb.error(this); Element head = tb.getHeadElement(); tb.push(head); tb.process(t, InHead); tb.removeFromStack(head); } else if (name.equals("head")) { tb.error(this); return false; } else { anythingElse(t, tb); } } else if (t.isEndTag()) { if (StringUtil.in(t.asEndTag().name(), "body", "html")) { anythingElse(t, tb); } else { tb.error(this); return false; } } else { anythingElse(t, tb); } return true; } private boolean anythingElse(Token t, Asta4DTagSupportHtmlTreeBuilder tb) { StartTag tag = new Token.StartTag("body"); // asta4d customization start tag.appendAttributeName(ExtNodeConstants.ATTR_BODY_ONLY_WITH_NS); tag.finaliseTag(); // asta4d customization end tb.process(tag); tb.framesetOk(true); return tb.process(t); } }, InBody { boolean process(Token t, Asta4DTagSupportHtmlTreeBuilder tb) { switch (t.type) { case Character: { Token.Character c = t.asCharacter(); if (c.getData().equals(nullString)) { // todo confirm that check tb.error(this); return false; } else if (tb.framesetOk() && isWhitespace(c)) { // don't check if whitespace if frames already closed tb.reconstructFormattingElements(); tb.insert(c); } else { tb.reconstructFormattingElements(); tb.insert(c); tb.framesetOk(false); } break; } case Comment: { tb.insert(t.asComment()); break; } case Doctype: { tb.error(this); return false; } case StartTag: Token.StartTag startTag = t.asStartTag(); String name = startTag.name(); if (name.equals("html")) { tb.error(this); // merge attributes onto real html Element html = tb.getStack().getFirst(); for (Attribute attribute : startTag.getAttributes()) { if (!html.hasAttr(attribute.getKey())) html.attributes().put(attribute); } } else if (StringUtil.in(name, Constants.InBodyStartToHead)) { return tb.process(t, InHead); } else if (name.equals("body")) { tb.error(this); LinkedList<Element> stack = tb.getStack(); if (stack.size() == 1 || (stack.size() > 2 && !stack.get(1).nodeName().equals("body"))) { // only in fragment case return false; // ignore } else { tb.framesetOk(false); Element body = stack.get(1); for (Attribute attribute : startTag.getAttributes()) { if (!body.hasAttr(attribute.getKey())) body.attributes().put(attribute); } } } else if (name.equals("frameset")) { tb.error(this); LinkedList<Element> stack = tb.getStack(); if (stack.size() == 1 || (stack.size() > 2 && !stack.get(1).nodeName().equals("body"))) { // only in fragment case return false; // ignore } else if (!tb.framesetOk()) { return false; // ignore frameset } else { Element second = stack.get(1); if (second.parent() != null) second.remove(); // pop up to html element while (stack.size() > 1) stack.removeLast(); tb.insert(startTag); tb.transition(InFrameset); } } else if (StringUtil.in(name, Constants.InBodyStartPClosers)) { if (tb.inButtonScope("p")) { tb.process(new Token.EndTag("p")); } tb.insert(startTag); } else if (StringUtil.in(name, Constants.Headings)) { if (tb.inButtonScope("p")) { tb.process(new Token.EndTag("p")); } if (StringUtil.in(tb.currentElement().nodeName(), Constants.Headings)) { tb.error(this); tb.pop(); } tb.insert(startTag); } else if (StringUtil.in(name, Constants.InBodyStartPreListing)) { if (tb.inButtonScope("p")) { tb.process(new Token.EndTag("p")); } tb.insert(startTag); // todo: ignore LF if next token tb.framesetOk(false); } else if (name.equals("form")) { if (tb.getFormElement() != null) { tb.error(this); return false; } if (tb.inButtonScope("p")) { tb.process(new Token.EndTag("p")); } tb.insertForm(startTag, true); } else if (name.equals("li")) { tb.framesetOk(false); LinkedList<Element> stack = tb.getStack(); for (int i = stack.size() - 1; i > 0; i--) { Element el = stack.get(i); if (el.nodeName().equals("li")) { tb.process(new Token.EndTag("li")); break; } if (tb.isSpecial(el) && !StringUtil.in(el.nodeName(), Constants.InBodyStartLiBreakers)) break; } if (tb.inButtonScope("p")) { tb.process(new Token.EndTag("p")); } tb.insert(startTag); } else if (StringUtil.in(name, Constants.DdDt)) { tb.framesetOk(false); LinkedList<Element> stack = tb.getStack(); for (int i = stack.size() - 1; i > 0; i--) { Element el = stack.get(i); if (StringUtil.in(el.nodeName(), Constants.DdDt)) { tb.process(new Token.EndTag(el.nodeName())); break; } if (tb.isSpecial(el) && !StringUtil.in(el.nodeName(), Constants.InBodyStartLiBreakers)) break; } if (tb.inButtonScope("p")) { tb.process(new Token.EndTag("p")); } tb.insert(startTag); } else if (name.equals("plaintext")) { if (tb.inButtonScope("p")) { tb.process(new Token.EndTag("p")); } tb.insert(startTag); tb.tokeniser.transition(TokeniserState.PLAINTEXT); // once in, never gets out } else if (name.equals("button")) { if (tb.inButtonScope("button")) { // close and reprocess tb.error(this); tb.process(new Token.EndTag("button")); tb.process(startTag); } else { tb.reconstructFormattingElements(); tb.insert(startTag); tb.framesetOk(false); } } else if (name.equals("a")) { if (tb.getActiveFormattingElement("a") != null) { tb.error(this); tb.process(new Token.EndTag("a")); // still on stack? Element remainingA = tb.getFromStack("a"); if (remainingA != null) { tb.removeFromActiveFormattingElements(remainingA); tb.removeFromStack(remainingA); } } tb.reconstructFormattingElements(); Element a = tb.insert(startTag); tb.pushActiveFormattingElements(a); } else if (StringUtil.in(name, Constants.Formatters)) { tb.reconstructFormattingElements(); Element el = tb.insert(startTag); tb.pushActiveFormattingElements(el); } else if (name.equals("nobr")) { tb.reconstructFormattingElements(); if (tb.inScope("nobr")) { tb.error(this); tb.process(new Token.EndTag("nobr")); tb.reconstructFormattingElements(); } Element el = tb.insert(startTag); tb.pushActiveFormattingElements(el); } else if (StringUtil.in(name, Constants.InBodyStartApplets)) { tb.reconstructFormattingElements(); tb.insert(startTag); tb.insertMarkerToFormattingElements(); tb.framesetOk(false); } else if (name.equals("table")) { if (tb.getDocument().quirksMode() != Document.QuirksMode.quirks && tb.inButtonScope("p")) { tb.process(new Token.EndTag("p")); } tb.insert(startTag); tb.framesetOk(false); tb.transition(InTable); } else if (StringUtil.in(name, Constants.InBodyStartEmptyFormatters)) { tb.reconstructFormattingElements(); tb.insertEmpty(startTag); tb.framesetOk(false); } else if (name.equals("input")) { tb.reconstructFormattingElements(); Element el = tb.insertEmpty(startTag); if (!el.attr("type").equalsIgnoreCase("hidden")) tb.framesetOk(false); } else if (StringUtil.in(name, Constants.InBodyStartMedia)) { tb.insertEmpty(startTag); } else if (name.equals("hr")) { if (tb.inButtonScope("p")) { tb.process(new Token.EndTag("p")); } tb.insertEmpty(startTag); tb.framesetOk(false); } else if (name.equals("image")) { if (tb.getFromStack("svg") == null) return tb.process(startTag.name("img")); // change <image> to <img>, unless in svg else tb.insert(startTag); } else if (name.equals("isindex")) { // how much do we care about the early 90s? tb.error(this); if (tb.getFormElement() != null) return false; tb.tokeniser.acknowledgeSelfClosingFlag(); tb.process(new Token.StartTag("form")); if (startTag.attributes.hasKey("action")) { Element form = tb.getFormElement(); form.attr("action", startTag.attributes.get("action")); } tb.process(new Token.StartTag("hr")); tb.process(new Token.StartTag("label")); // hope you like english. String prompt = startTag.attributes.hasKey("prompt") ? startTag.attributes.get("prompt") : "This is a searchable index. Enter search keywords: "; tb.process(new Token.Character(prompt)); // input Attributes inputAttribs = new Attributes(); for (Attribute attr : startTag.attributes) { if (!StringUtil.in(attr.getKey(), Constants.InBodyStartInputAttribs)) inputAttribs.put(attr); } inputAttribs.put("name", "isindex"); tb.process(new Token.StartTag("input", inputAttribs)); tb.process(new Token.EndTag("label")); tb.process(new Token.StartTag("hr")); tb.process(new Token.EndTag("form")); } else if (name.equals("textarea")) { tb.insert(startTag); // todo: If the next token is a U+000A LINE FEED (LF) character token, then ignore that token and move on to the next // one. (Newlines at the start of textarea elements are ignored as an authoring convenience.) tb.tokeniser.transition(TokeniserState.Rcdata); tb.markInsertionMode(); tb.framesetOk(false); tb.transition(Text); } else if (name.equals("xmp")) { if (tb.inButtonScope("p")) { tb.process(new Token.EndTag("p")); } tb.reconstructFormattingElements(); tb.framesetOk(false); handleRawtext(startTag, tb); } else if (name.equals("iframe")) { tb.framesetOk(false); handleRawtext(startTag, tb); } else if (name.equals("noembed")) { // also handle noscript if script enabled handleRawtext(startTag, tb); } else if (name.equals("select")) { tb.reconstructFormattingElements(); tb.insert(startTag); tb.framesetOk(false); Asta4DTagSupportHtmlTreeBuilderState state = tb.state(); if (state.equals(InTable) || state.equals(InCaption) || state.equals(InTableBody) || state.equals(InRow) || state.equals(InCell)) tb.transition(InSelectInTable); else tb.transition(InSelect); } else if (StringUtil.in(name, Constants.InBodyStartOptions)) { if (tb.currentElement().nodeName().equals("option")) tb.process(new Token.EndTag("option")); tb.reconstructFormattingElements(); tb.insert(startTag); } else if (StringUtil.in(name, Constants.InBodyStartRuby)) { if (tb.inScope("ruby")) { tb.generateImpliedEndTags(); if (!tb.currentElement().nodeName().equals("ruby")) { tb.error(this); tb.popStackToBefore("ruby"); // i.e. close up to but not include name } tb.insert(startTag); } } else if (name.equals("math")) { tb.reconstructFormattingElements(); // todo: handle A start tag whose tag name is "math" (i.e. foreign, mathml) tb.insert(startTag); tb.tokeniser.acknowledgeSelfClosingFlag(); } else if (name.equals("svg")) { tb.reconstructFormattingElements(); // todo: handle A start tag whose tag name is "svg" (xlink, svg) tb.insert(startTag); tb.tokeniser.acknowledgeSelfClosingFlag(); } else if (StringUtil.in(name, Constants.InBodyStartDrop)) { tb.error(this); return false; } else { tb.reconstructFormattingElements(); tb.insert(startTag); } break; case EndTag: Token.EndTag endTag = t.asEndTag(); name = endTag.name(); if (name.equals("body")) { if (!tb.inScope("body")) { tb.error(this); return false; } else { // todo: error if stack contains something not dd, dt, li, optgroup, option, p, rp, rt, tbody, td, tfoot, th, thead, // tr, body, html tb.transition(AfterBody); } } else if (name.equals("html")) { boolean notIgnored = tb.process(new Token.EndTag("body")); if (notIgnored) return tb.process(endTag); } else if (StringUtil.in(name, Constants.InBodyEndClosers)) { if (!tb.inScope(name)) { // nothing to close tb.error(this); return false; } else { tb.generateImpliedEndTags(); if (!tb.currentElement().nodeName().equals(name)) tb.error(this); tb.popStackToClose(name); } } else if (name.equals("form")) { Element currentForm = tb.getFormElement(); tb.setFormElement(null); if (currentForm == null || !tb.inScope(name)) { tb.error(this); return false; } else { tb.generateImpliedEndTags(); if (!tb.currentElement().nodeName().equals(name)) tb.error(this); // remove currentForm from stack. will shift anything under up. tb.removeFromStack(currentForm); } } else if (name.equals("p")) { if (!tb.inButtonScope(name)) { tb.error(this); tb.process(new Token.StartTag(name)); // if no p to close, creates an empty <p></p> return tb.process(endTag); } else { tb.generateImpliedEndTags(name); if (!tb.currentElement().nodeName().equals(name)) tb.error(this); tb.popStackToClose(name); } } else if (name.equals("li")) { if (!tb.inListItemScope(name)) { tb.error(this); return false; } else { tb.generateImpliedEndTags(name); if (!tb.currentElement().nodeName().equals(name)) tb.error(this); tb.popStackToClose(name); } } else if (StringUtil.in(name, Constants.DdDt)) { if (!tb.inScope(name)) { tb.error(this); return false; } else { tb.generateImpliedEndTags(name); if (!tb.currentElement().nodeName().equals(name)) tb.error(this); tb.popStackToClose(name); } } else if (StringUtil.in(name, Constants.Headings)) { if (!tb.inScope(Constants.Headings)) { tb.error(this); return false; } else { tb.generateImpliedEndTags(name); if (!tb.currentElement().nodeName().equals(name)) tb.error(this); tb.popStackToClose(Constants.Headings); } } else if (name.equals("sarcasm")) { // *sigh* return anyOtherEndTag(t, tb); } else if (StringUtil.in(name, Constants.InBodyEndAdoptionFormatters)) { // Adoption Agency Algorithm. OUTER: for (int i = 0; i < 8; i++) { Element formatEl = tb.getActiveFormattingElement(name); if (formatEl == null) return anyOtherEndTag(t, tb); else if (!tb.onStack(formatEl)) { tb.error(this); tb.removeFromActiveFormattingElements(formatEl); return true; } else if (!tb.inScope(formatEl.nodeName())) { tb.error(this); return false; } else if (tb.currentElement() != formatEl) tb.error(this); Element furthestBlock = null; Element commonAncestor = null; boolean seenFormattingElement = false; LinkedList<Element> stack = tb.getStack(); // the spec doesn't limit to < 64, but in degenerate cases (9000+ stack depth) this prevents // run-aways final int stackSize = stack.size(); for (int si = 0; si < stackSize && si < 64; si++) { Element el = stack.get(si); if (el == formatEl) { commonAncestor = stack.get(si - 1); seenFormattingElement = true; } else if (seenFormattingElement && tb.isSpecial(el)) { furthestBlock = el; break; } } if (furthestBlock == null) { tb.popStackToClose(formatEl.nodeName()); tb.removeFromActiveFormattingElements(formatEl); return true; } // todo: Let a bookmark note the position of the formatting element in the list of active formatting elements // relative to the elements on either side of it in the list. // does that mean: int pos of format el in list? Element node = furthestBlock; Element lastNode = furthestBlock; INNER: for (int j = 0; j < 3; j++) { if (tb.onStack(node)) node = tb.aboveOnStack(node); if (!tb.isInActiveFormattingElements(node)) { // note no bookmark check tb.removeFromStack(node); continue INNER; } else if (node == formatEl) break INNER; Element replacement = new Element(Tag.valueOf(node.nodeName()), tb.getBaseUri()); tb.replaceActiveFormattingElement(node, replacement); tb.replaceOnStack(node, replacement); node = replacement; if (lastNode == furthestBlock) { // todo: move the aforementioned bookmark to be immediately after the new node in the list of active // formatting elements. // not getting how this bookmark both straddles the element above, but is inbetween here... } if (lastNode.parent() != null) lastNode.remove(); node.appendChild(lastNode); lastNode = node; } if (StringUtil.in(commonAncestor.nodeName(), Constants.InBodyEndTableFosters)) { if (lastNode.parent() != null) lastNode.remove(); tb.insertInFosterParent(lastNode); } else { if (lastNode.parent() != null) lastNode.remove(); commonAncestor.appendChild(lastNode); } Element adopter = new Element(formatEl.tag(), tb.getBaseUri()); adopter.attributes().addAll(formatEl.attributes()); Node[] childNodes = furthestBlock.childNodes().toArray(new Node[furthestBlock.childNodeSize()]); for (Node childNode : childNodes) { adopter.appendChild(childNode); // append will reparent. thus the clone to avoid concurrent mod. } furthestBlock.appendChild(adopter); tb.removeFromActiveFormattingElements(formatEl); // todo: insert the new element into the list of active formatting elements at the position of the aforementioned // bookmark. tb.removeFromStack(formatEl); tb.insertOnStackAfter(furthestBlock, adopter); } } else if (StringUtil.in(name, Constants.InBodyStartApplets)) { if (!tb.inScope("name")) { if (!tb.inScope(name)) { tb.error(this); return false; } tb.generateImpliedEndTags(); if (!tb.currentElement().nodeName().equals(name)) tb.error(this); tb.popStackToClose(name); tb.clearFormattingElementsToLastMarker(); } } else if (name.equals("br")) { tb.error(this); tb.process(new Token.StartTag("br")); return false; } else { return anyOtherEndTag(t, tb); } break; case EOF: // todo: error if stack contains something not dd, dt, li, p, tbody, td, tfoot, th, thead, tr, body, html // stop parsing break; } return true; } boolean anyOtherEndTag(Token t, Asta4DTagSupportHtmlTreeBuilder tb) { String name = t.asEndTag().name(); DescendableLinkedList<Element> stack = tb.getStack(); Iterator<Element> it = stack.descendingIterator(); while (it.hasNext()) { Element node = it.next(); if (node.nodeName().equals(name)) { tb.generateImpliedEndTags(name); if (!name.equals(tb.currentElement().nodeName())) tb.error(this); tb.popStackToClose(name); break; } else { if (tb.isSpecial(node)) { tb.error(this); return false; } } } return true; } }, Text { // in script, style etc. normally treated as data tags boolean process(Token t, Asta4DTagSupportHtmlTreeBuilder tb) { if (t.isCharacter()) { tb.insert(t.asCharacter()); } else if (t.isEOF()) { tb.error(this); // if current node is script: already started tb.pop(); tb.transition(tb.originalState()); return tb.process(t); } else if (t.isEndTag()) { // if: An end tag whose tag name is "script" -- scripting nesting level, if evaluating scripts tb.pop(); tb.transition(tb.originalState()); } return true; } }, InTable { boolean process(Token t, Asta4DTagSupportHtmlTreeBuilder tb) { if (t.isCharacter()) { tb.newPendingTableCharacters(); tb.markInsertionMode(); tb.transition(InTableText); return tb.process(t); } else if (t.isComment()) { tb.insert(t.asComment()); return true; } else if (t.isDoctype()) { tb.error(this); return false; } else if (t.isStartTag()) { Token.StartTag startTag = t.asStartTag(); String name = startTag.name(); if (name.equals("caption")) { tb.clearStackToTableContext(); tb.insertMarkerToFormattingElements(); tb.insert(startTag); tb.transition(InCaption); } else if (name.equals("colgroup")) { tb.clearStackToTableContext(); tb.insert(startTag); tb.transition(InColumnGroup); } else if (name.equals("col")) { tb.process(new Token.StartTag("colgroup")); return tb.process(t); } else if (StringUtil.in(name, "tbody", "tfoot", "thead")) { tb.clearStackToTableContext(); tb.insert(startTag); tb.transition(InTableBody); } else if (StringUtil.in(name, "td", "th", "tr")) { tb.process(new Token.StartTag("tbody")); return tb.process(t); } else if (name.equals("table")) { tb.error(this); boolean processed = tb.process(new Token.EndTag("table")); if (processed) // only ignored if in fragment return tb.process(t); } else if (StringUtil.in(name, "style", "script")) { return tb.process(t, InHead); } else if (name.equals("input")) { if (!startTag.attributes.get("type").equalsIgnoreCase("hidden")) { return anythingElse(t, tb); } else { tb.insertEmpty(startTag); } } else if (name.equals("form")) { tb.error(this); if (tb.getFormElement() != null) return false; else { tb.insertForm(startTag, false); } } else { return anythingElse(t, tb); } return true; // todo: check if should return processed // http://www.whatwg.org/specs/web-apps/current-work/multipage/tree-construction.html#parsing-main-intable } else if (t.isEndTag()) { Token.EndTag endTag = t.asEndTag(); String name = endTag.name(); if (name.equals("table")) { if (!tb.inTableScope(name)) { tb.error(this); return false; } else { tb.popStackToClose("table"); } tb.resetInsertionMode(); } else if (StringUtil.in(name, "body", "caption", "col", "colgroup", "html", "tbody", "td", "tfoot", "th", "thead", "tr")) { tb.error(this); return false; } else { return anythingElse(t, tb); } return true; // todo: as above todo } else if (t.isEOF()) { if (tb.currentElement().nodeName().equals("html")) tb.error(this); return true; // stops parsing } return anythingElse(t, tb); } boolean anythingElse(Token t, Asta4DTagSupportHtmlTreeBuilder tb) { tb.error(this); boolean processed = true; if (StringUtil.in(tb.currentElement().nodeName(), "table", "tbody", "tfoot", "thead", "tr")) { tb.setFosterInserts(true); processed = tb.process(t, InBody); tb.setFosterInserts(false); } else { processed = tb.process(t, InBody); } return processed; } }, InTableText { boolean process(Token t, Asta4DTagSupportHtmlTreeBuilder tb) { switch (t.type) { case Character: Token.Character c = t.asCharacter(); if (c.getData().equals(nullString)) { tb.error(this); return false; } else { tb.getPendingTableCharacters().add(c); } break; default: if (tb.getPendingTableCharacters().size() > 0) { for (Token.Character character : tb.getPendingTableCharacters()) { if (!isWhitespace(character)) { // InTable anything else section: tb.error(this); if (StringUtil.in(tb.currentElement().nodeName(), "table", "tbody", "tfoot", "thead", "tr")) { tb.setFosterInserts(true); tb.process(character, InBody); tb.setFosterInserts(false); } else { tb.process(character, InBody); } } else tb.insert(character); } tb.newPendingTableCharacters(); } tb.transition(tb.originalState()); return tb.process(t); } return true; } }, InCaption { boolean process(Token t, Asta4DTagSupportHtmlTreeBuilder tb) { if (t.isEndTag() && t.asEndTag().name().equals("caption")) { Token.EndTag endTag = t.asEndTag(); String name = endTag.name(); if (!tb.inTableScope(name)) { tb.error(this); return false; } else { tb.generateImpliedEndTags(); if (!tb.currentElement().nodeName().equals("caption")) tb.error(this); tb.popStackToClose("caption"); tb.clearFormattingElementsToLastMarker(); tb.transition(InTable); } } else if ((t.isStartTag() && StringUtil.in(t.asStartTag().name(), "caption", "col", "colgroup", "tbody", "td", "tfoot", "th", "thead", "tr") || t.isEndTag() && t.asEndTag().name().equals("table"))) { tb.error(this); boolean processed = tb.process(new Token.EndTag("caption")); if (processed) return tb.process(t); } else if (t.isEndTag() && StringUtil.in(t.asEndTag().name(), "body", "col", "colgroup", "html", "tbody", "td", "tfoot", "th", "thead", "tr")) { tb.error(this); return false; } else { return tb.process(t, InBody); } return true; } }, InColumnGroup { boolean process(Token t, Asta4DTagSupportHtmlTreeBuilder tb) { if (isWhitespace(t)) { tb.insert(t.asCharacter()); return true; } switch (t.type) { case Comment: tb.insert(t.asComment()); break; case Doctype: tb.error(this); break; case StartTag: Token.StartTag startTag = t.asStartTag(); String name = startTag.name(); if (name.equals("html")) return tb.process(t, InBody); else if (name.equals("col")) tb.insertEmpty(startTag); else return anythingElse(t, tb); break; case EndTag: Token.EndTag endTag = t.asEndTag(); name = endTag.name(); if (name.equals("colgroup")) { if (tb.currentElement().nodeName().equals("html")) { // frag case tb.error(this); return false; } else { tb.pop(); tb.transition(InTable); } } else return anythingElse(t, tb); break; case EOF: if (tb.currentElement().nodeName().equals("html")) return true; // stop parsing; frag case else return anythingElse(t, tb); default: return anythingElse(t, tb); } return true; } private boolean anythingElse(Token t, TreeBuilder tb) { boolean processed = tb.process(new Token.EndTag("colgroup")); if (processed) // only ignored in frag case return tb.process(t); return true; } }, InTableBody { boolean process(Token t, Asta4DTagSupportHtmlTreeBuilder tb) { switch (t.type) { case StartTag: Token.StartTag startTag = t.asStartTag(); String name = startTag.name(); if (name.equals("tr")) { tb.clearStackToTableBodyContext(); tb.insert(startTag); tb.transition(InRow); } else if (StringUtil.in(name, "th", "td")) { tb.error(this); tb.process(new Token.StartTag("tr")); return tb.process(startTag); } else if (StringUtil.in(name, "caption", "col", "colgroup", "tbody", "tfoot", "thead")) { return exitTableBody(t, tb); } else return anythingElse(t, tb); break; case EndTag: Token.EndTag endTag = t.asEndTag(); name = endTag.name(); if (StringUtil.in(name, "tbody", "tfoot", "thead")) { if (!tb.inTableScope(name)) { tb.error(this); return false; } else { tb.clearStackToTableBodyContext(); tb.pop(); tb.transition(InTable); } } else if (name.equals("table")) { return exitTableBody(t, tb); } else if (StringUtil.in(name, "body", "caption", "col", "colgroup", "html", "td", "th", "tr")) { tb.error(this); return false; } else return anythingElse(t, tb); break; default: return anythingElse(t, tb); } return true; } private boolean exitTableBody(Token t, Asta4DTagSupportHtmlTreeBuilder tb) { if (!(tb.inTableScope("tbody") || tb.inTableScope("thead") || tb.inScope("tfoot"))) { // frag case tb.error(this); return false; } tb.clearStackToTableBodyContext(); tb.process(new Token.EndTag(tb.currentElement().nodeName())); // tbody, tfoot, thead return tb.process(t); } private boolean anythingElse(Token t, Asta4DTagSupportHtmlTreeBuilder tb) { return tb.process(t, InTable); } }, InRow { boolean process(Token t, Asta4DTagSupportHtmlTreeBuilder tb) { if (t.isStartTag()) { Token.StartTag startTag = t.asStartTag(); String name = startTag.name(); if (StringUtil.in(name, "th", "td")) { tb.clearStackToTableRowContext(); tb.insert(startTag); tb.transition(InCell); tb.insertMarkerToFormattingElements(); } else if (StringUtil.in(name, "caption", "col", "colgroup", "tbody", "tfoot", "thead", "tr")) { return handleMissingTr(t, tb); } else { return anythingElse(t, tb); } } else if (t.isEndTag()) { Token.EndTag endTag = t.asEndTag(); String name = endTag.name(); if (name.equals("tr")) { if (!tb.inTableScope(name)) { tb.error(this); // frag return false; } tb.clearStackToTableRowContext(); tb.pop(); // tr tb.transition(InTableBody); } else if (name.equals("table")) { return handleMissingTr(t, tb); } else if (StringUtil.in(name, "tbody", "tfoot", "thead")) { if (!tb.inTableScope(name)) { tb.error(this); return false; } tb.process(new Token.EndTag("tr")); return tb.process(t); } else if (StringUtil.in(name, "body", "caption", "col", "colgroup", "html", "td", "th")) { tb.error(this); return false; } else { return anythingElse(t, tb); } } else { return anythingElse(t, tb); } return true; } private boolean anythingElse(Token t, Asta4DTagSupportHtmlTreeBuilder tb) { return tb.process(t, InTable); } private boolean handleMissingTr(Token t, TreeBuilder tb) { boolean processed = tb.process(new Token.EndTag("tr")); if (processed) return tb.process(t); else return false; } }, InCell { boolean process(Token t, Asta4DTagSupportHtmlTreeBuilder tb) { if (t.isEndTag()) { Token.EndTag endTag = t.asEndTag(); String name = endTag.name(); if (StringUtil.in(name, "td", "th")) { if (!tb.inTableScope(name)) { tb.error(this); tb.transition(InRow); // might not be in scope if empty: <td /> and processing fake end tag return false; } tb.generateImpliedEndTags(); if (!tb.currentElement().nodeName().equals(name)) tb.error(this); tb.popStackToClose(name); tb.clearFormattingElementsToLastMarker(); tb.transition(InRow); } else if (StringUtil.in(name, "body", "caption", "col", "colgroup", "html")) { tb.error(this); return false; } else if (StringUtil.in(name, "table", "tbody", "tfoot", "thead", "tr")) { if (!tb.inTableScope(name)) { tb.error(this); return false; } closeCell(tb); return tb.process(t); } else { return anythingElse(t, tb); } } else if (t.isStartTag() && StringUtil.in(t.asStartTag().name(), "caption", "col", "colgroup", "tbody", "td", "tfoot", "th", "thead", "tr")) { if (!(tb.inTableScope("td") || tb.inTableScope("th"))) { tb.error(this); return false; } closeCell(tb); return tb.process(t); } else { return anythingElse(t, tb); } return true; } private boolean anythingElse(Token t, Asta4DTagSupportHtmlTreeBuilder tb) { return tb.process(t, InBody); } private void closeCell(Asta4DTagSupportHtmlTreeBuilder tb) { if (tb.inTableScope("td")) tb.process(new Token.EndTag("td")); else tb.process(new Token.EndTag("th")); // only here if th or td in scope } }, InSelect { boolean process(Token t, Asta4DTagSupportHtmlTreeBuilder tb) { switch (t.type) { case Character: Token.Character c = t.asCharacter(); if (c.getData().equals(nullString)) { tb.error(this); return false; } else { tb.insert(c); } break; case Comment: tb.insert(t.asComment()); break; case Doctype: tb.error(this); return false; case StartTag: Token.StartTag start = t.asStartTag(); String name = start.name(); if (name.equals("html")) return tb.process(start, InBody); else if (name.equals("option")) { tb.process(new Token.EndTag("option")); tb.insert(start); } else if (name.equals("optgroup")) { if (tb.currentElement().nodeName().equals("option")) tb.process(new Token.EndTag("option")); else if (tb.currentElement().nodeName().equals("optgroup")) tb.process(new Token.EndTag("optgroup")); tb.insert(start); } else if (name.equals("select")) { tb.error(this); return tb.process(new Token.EndTag("select")); } else if (StringUtil.in(name, "input", "keygen", "textarea")) { tb.error(this); if (!tb.inSelectScope("select")) return false; // frag tb.process(new Token.EndTag("select")); return tb.process(start); } else if (name.equals("script")) { return tb.process(t, InHead); } else { return anythingElse(t, tb); } break; case EndTag: Token.EndTag end = t.asEndTag(); name = end.name(); if (name.equals("optgroup")) { if (tb.currentElement().nodeName().equals("option") && tb.aboveOnStack(tb.currentElement()) != null && tb.aboveOnStack(tb.currentElement()).nodeName().equals("optgroup")) tb.process(new Token.EndTag("option")); if (tb.currentElement().nodeName().equals("optgroup")) tb.pop(); else tb.error(this); } else if (name.equals("option")) { if (tb.currentElement().nodeName().equals("option")) tb.pop(); else tb.error(this); } else if (name.equals("select")) { if (!tb.inSelectScope(name)) { tb.error(this); return false; } else { tb.popStackToClose(name); tb.resetInsertionMode(); } } else return anythingElse(t, tb); break; case EOF: if (!tb.currentElement().nodeName().equals("html")) tb.error(this); break; default: return anythingElse(t, tb); } return true; } private boolean anythingElse(Token t, Asta4DTagSupportHtmlTreeBuilder tb) { tb.error(this); return false; } }, InSelectInTable { boolean process(Token t, Asta4DTagSupportHtmlTreeBuilder tb) { if (t.isStartTag() && StringUtil.in(t.asStartTag().name(), "caption", "table", "tbody", "tfoot", "thead", "tr", "td", "th")) { tb.error(this); tb.process(new Token.EndTag("select")); return tb.process(t); } else if (t.isEndTag() && StringUtil.in(t.asEndTag().name(), "caption", "table", "tbody", "tfoot", "thead", "tr", "td", "th")) { tb.error(this); if (tb.inTableScope(t.asEndTag().name())) { tb.process(new Token.EndTag("select")); return (tb.process(t)); } else return false; } else { return tb.process(t, InSelect); } } }, AfterBody { boolean process(Token t, Asta4DTagSupportHtmlTreeBuilder tb) { if (isWhitespace(t)) { return tb.process(t, InBody); } else if (t.isComment()) { tb.insert(t.asComment()); // into html node } else if (t.isDoctype()) { tb.error(this); return false; } else if (t.isStartTag() && t.asStartTag().name().equals("html")) { return tb.process(t, InBody); } else if (t.isEndTag() && t.asEndTag().name().equals("html")) { if (tb.isFragmentParsing()) { tb.error(this); return false; } else { tb.transition(AfterAfterBody); } } else if (t.isEOF()) { // chillax! we're done } else { tb.error(this); tb.transition(InBody); return tb.process(t); } return true; } }, InFrameset { boolean process(Token t, Asta4DTagSupportHtmlTreeBuilder tb) { if (isWhitespace(t)) { tb.insert(t.asCharacter()); } else if (t.isComment()) { tb.insert(t.asComment()); } else if (t.isDoctype()) { tb.error(this); return false; } else if (t.isStartTag()) { Token.StartTag start = t.asStartTag(); String name = start.name(); if (name.equals("html")) { return tb.process(start, InBody); } else if (name.equals("frameset")) { tb.insert(start); } else if (name.equals("frame")) { tb.insertEmpty(start); } else if (name.equals("noframes")) { return tb.process(start, InHead); } else { tb.error(this); return false; } } else if (t.isEndTag() && t.asEndTag().name().equals("frameset")) { if (tb.currentElement().nodeName().equals("html")) { // frag tb.error(this); return false; } else { tb.pop(); if (!tb.isFragmentParsing() && !tb.currentElement().nodeName().equals("frameset")) { tb.transition(AfterFrameset); } } } else if (t.isEOF()) { if (!tb.currentElement().nodeName().equals("html")) { tb.error(this); return true; } } else { tb.error(this); return false; } return true; } }, AfterFrameset { boolean process(Token t, Asta4DTagSupportHtmlTreeBuilder tb) { if (isWhitespace(t)) { tb.insert(t.asCharacter()); } else if (t.isComment()) { tb.insert(t.asComment()); } else if (t.isDoctype()) { tb.error(this); return false; } else if (t.isStartTag() && t.asStartTag().name().equals("html")) { return tb.process(t, InBody); } else if (t.isEndTag() && t.asEndTag().name().equals("html")) { tb.transition(AfterAfterFrameset); } else if (t.isStartTag() && t.asStartTag().name().equals("noframes")) { return tb.process(t, InHead); } else if (t.isEOF()) { // cool your heels, we're complete } else { tb.error(this); return false; } return true; } }, AfterAfterBody { boolean process(Token t, Asta4DTagSupportHtmlTreeBuilder tb) { if (t.isComment()) { tb.insert(t.asComment()); } else if (t.isDoctype() || isWhitespace(t) || (t.isStartTag() && t.asStartTag().name().equals("html"))) { return tb.process(t, InBody); } else if (t.isEOF()) { // nice work chuck } else { tb.error(this); tb.transition(InBody); return tb.process(t); } return true; } }, AfterAfterFrameset { boolean process(Token t, Asta4DTagSupportHtmlTreeBuilder tb) { if (t.isComment()) { tb.insert(t.asComment()); } else if (t.isDoctype() || isWhitespace(t) || (t.isStartTag() && t.asStartTag().name().equals("html"))) { return tb.process(t, InBody); } else if (t.isEOF()) { // nice work chuck } else if (t.isStartTag() && t.asStartTag().name().equals("noframes")) { return tb.process(t, InHead); } else { tb.error(this); return false; } return true; } }, ForeignContent { boolean process(Token t, Asta4DTagSupportHtmlTreeBuilder tb) { return true; // todo: implement. Also; how do we get here? } }; private static String nullString = String.valueOf('\u0000'); abstract boolean process(Token t, Asta4DTagSupportHtmlTreeBuilder tb); private static boolean isWhitespace(Token t) { if (t.isCharacter()) { String data = t.asCharacter().getData(); // todo: this checks more than spec - "\t", "\n", "\f", "\r", " " for (int i = 0; i < data.length(); i++) { char c = data.charAt(i); if (!StringUtil.isWhitespace(c)) return false; } return true; } return false; } private static void handleRcData(Token.StartTag startTag, Asta4DTagSupportHtmlTreeBuilder tb) { tb.insert(startTag); tb.tokeniser.transition(TokeniserState.Rcdata); tb.markInsertionMode(); tb.transition(Text); } private static void handleRawtext(Token.StartTag startTag, Asta4DTagSupportHtmlTreeBuilder tb) { tb.insert(startTag); tb.tokeniser.transition(TokeniserState.Rawtext); tb.markInsertionMode(); tb.transition(Text); } // lists of tags to search through. A little harder to read here, but causes less GC than dynamic varargs. // was contributing around 10% of parse GC load. private static final class Constants { private static final String[] InBodyStartToHead = new String[] { "base", "basefont", "bgsound", "command", "link", "meta", "noframes", "script", "style", "title" }; private static final String[] InBodyStartPClosers = new String[] { "address", "article", "aside", "blockquote", "center", "details", "dir", "div", "dl", "fieldset", "figcaption", "figure", "footer", "header", "hgroup", "menu", "nav", "ol", "p", "section", "summary", "ul" }; private static final String[] Headings = new String[] { "h1", "h2", "h3", "h4", "h5", "h6" }; private static final String[] InBodyStartPreListing = new String[] { "pre", "listing" }; private static final String[] InBodyStartLiBreakers = new String[] { "address", "div", "p" }; private static final String[] DdDt = new String[] { "dd", "dt" }; private static final String[] Formatters = new String[] { "b", "big", "code", "em", "font", "i", "s", "small", "strike", "strong", "tt", "u" }; private static final String[] InBodyStartApplets = new String[] { "applet", "marquee", "object" }; private static final String[] InBodyStartEmptyFormatters = new String[] { "area", "br", "embed", "img", "keygen", "wbr" }; private static final String[] InBodyStartMedia = new String[] { "param", "source", "track" }; private static final String[] InBodyStartInputAttribs = new String[] { "name", "action", "prompt" }; private static final String[] InBodyStartOptions = new String[] { "optgroup", "option" }; private static final String[] InBodyStartRuby = new String[] { "rp", "rt" }; private static final String[] InBodyStartDrop = new String[] { "caption", "col", "colgroup", "frame", "head", "tbody", "td", "tfoot", "th", "thead", "tr" }; private static final String[] InBodyEndClosers = new String[] { "address", "article", "aside", "blockquote", "button", "center", "details", "dir", "div", "dl", "fieldset", "figcaption", "figure", "footer", "header", "hgroup", "listing", "menu", "nav", "ol", "pre", "section", "summary", "ul" }; private static final String[] InBodyEndAdoptionFormatters = new String[] { "a", "b", "big", "code", "em", "font", "i", "nobr", "s", "small", "strike", "strong", "tt", "u" }; private static final String[] InBodyEndTableFosters = new String[] { "table", "tbody", "tfoot", "thead", "tr" }; } }
astamuse/asta4d
162
Java
org.eclipse.core.resources.prefs
text/plain
-8,186,320,509,843,742,000
package org.jsoup.parser; import java.util.ArrayList; import java.util.Iterator; import java.util.LinkedList; import java.util.List; import org.jsoup.helper.DescendableLinkedList; import org.jsoup.helper.StringUtil; import org.jsoup.helper.Validate; import org.jsoup.nodes.Comment; import org.jsoup.nodes.DataNode; import org.jsoup.nodes.Document; import org.jsoup.nodes.Element; import org.jsoup.nodes.FormElement; import org.jsoup.nodes.Node; import org.jsoup.nodes.TextNode; import org.jsoup.select.Elements; /* * No thing is different from the original version HtmlTreeBuilder of jsoup except use Asta4DTagSupportHtmlTreeBuilderState rather than * the original HtmlTreeBuilderState */ /** * HTML Tree Builder; creates a DOM from Tokens. */ public class Asta4DTagSupportHtmlTreeBuilder extends TreeBuilder { // tag searches private static final String[] TagsScriptStyle = new String[] { "script", "style" }; public static final String[] TagsSearchInScope = new String[] { "applet", "caption", "html", "table", "td", "th", "marquee", "object" }; private static final String[] TagSearchList = new String[] { "ol", "ul" }; private static final String[] TagSearchButton = new String[] { "button" }; private static final String[] TagSearchTableScope = new String[] { "html", "table" }; private static final String[] TagSearchSelectScope = new String[] { "optgroup", "option" }; private static final String[] TagSearchEndTags = new String[] { "dd", "dt", "li", "option", "optgroup", "p", "rp", "rt" }; private static final String[] TagSearchSpecial = new String[] { "address", "applet", "area", "article", "aside", "base", "basefont", "bgsound", "blockquote", "body", "br", "button", "caption", "center", "col", "colgroup", "command", "dd", "details", "dir", "div", "dl", "dt", "embed", "fieldset", "figcaption", "figure", "footer", "form", "frame", "frameset", "h1", "h2", "h3", "h4", "h5", "h6", "head", "header", "hgroup", "hr", "html", "iframe", "img", "input", "isindex", "li", "link", "listing", "marquee", "menu", "meta", "nav", "noembed", "noframes", "noscript", "object", "ol", "p", "param", "plaintext", "pre", "script", "section", "select", "style", "summary", "table", "tbody", "td", "textarea", "tfoot", "th", "thead", "title", "tr", "ul", "wbr", "xmp" }; private Asta4DTagSupportHtmlTreeBuilderState state; // the current state private Asta4DTagSupportHtmlTreeBuilderState originalState; // original / marked state private boolean baseUriSetFromDoc = false; private Element headElement; // the current head element private FormElement formElement; // the current form element private Element contextElement; // fragment parse context -- could be null even if fragment parsing private DescendableLinkedList<Element> formattingElements = new DescendableLinkedList<Element>(); // active (open) formatting elements private List<Token.Character> pendingTableCharacters = new ArrayList<Token.Character>(); // chars in table to be shifted out private boolean framesetOk = true; // if ok to go into frameset private boolean fosterInserts = false; // if next inserts should be fostered private boolean fragmentParsing = false; // if parsing a fragment of html public Asta4DTagSupportHtmlTreeBuilder() { } @Override Document parse(String input, String baseUri, ParseErrorList errors) { state = Asta4DTagSupportHtmlTreeBuilderState.Initial; baseUriSetFromDoc = false; return super.parse(input, baseUri, errors); } List<Node> parseFragment(String inputFragment, Element context, String baseUri, ParseErrorList errors) { // context may be null state = Asta4DTagSupportHtmlTreeBuilderState.Initial; initialiseParse(inputFragment, baseUri, errors); contextElement = context; fragmentParsing = true; Element root = null; if (context != null) { if (context.ownerDocument() != null) // quirks setup: doc.quirksMode(context.ownerDocument().quirksMode()); // initialise the tokeniser state: String contextTag = context.tagName(); if (StringUtil.in(contextTag, "title", "textarea")) tokeniser.transition(TokeniserState.Rcdata); else if (StringUtil.in(contextTag, "iframe", "noembed", "noframes", "style", "xmp")) tokeniser.transition(TokeniserState.Rawtext); else if (contextTag.equals("script")) tokeniser.transition(TokeniserState.ScriptData); else if (contextTag.equals(("noscript"))) tokeniser.transition(TokeniserState.Data); // if scripting enabled, rawtext else if (contextTag.equals("plaintext")) tokeniser.transition(TokeniserState.Data); else tokeniser.transition(TokeniserState.Data); // default root = new Element(Tag.valueOf("html"), baseUri); doc.appendChild(root); stack.push(root); resetInsertionMode(); // setup form element to nearest form on context (up ancestor chain). ensures form controls are associated // with form correctly Elements contextChain = context.parents(); contextChain.add(0, context); for (Element parent : contextChain) { if (parent instanceof FormElement) { formElement = (FormElement) parent; break; } } } runParser(); if (context != null) return root.childNodes(); else return doc.childNodes(); } @Override protected boolean process(Token token) { currentToken = token; return this.state.process(token, this); } boolean process(Token token, Asta4DTagSupportHtmlTreeBuilderState state) { currentToken = token; return state.process(token, this); } void transition(Asta4DTagSupportHtmlTreeBuilderState state) { this.state = state; } Asta4DTagSupportHtmlTreeBuilderState state() { return state; } void markInsertionMode() { originalState = state; } Asta4DTagSupportHtmlTreeBuilderState originalState() { return originalState; } void framesetOk(boolean framesetOk) { this.framesetOk = framesetOk; } boolean framesetOk() { return framesetOk; } Document getDocument() { return doc; } String getBaseUri() { return baseUri; } void maybeSetBaseUri(Element base) { if (baseUriSetFromDoc) // only listen to the first <base href> in parse return; String href = base.absUrl("href"); if (href.length() != 0) { // ignore <base target> etc baseUri = href; baseUriSetFromDoc = true; doc.setBaseUri(href); // set on the doc so doc.createElement(Tag) will get updated base, and to update all descendants } } boolean isFragmentParsing() { return fragmentParsing; } void error(Asta4DTagSupportHtmlTreeBuilderState state) { if (errors.canAddError()) errors.add(new ParseError(reader.pos(), "Unexpected token [%s] when in state [%s]", currentToken.tokenType(), state)); } Element insert(Token.StartTag startTag) { // handle empty unknown tags // when the spec expects an empty tag, will directly hit insertEmpty, so won't generate this fake end tag. if (startTag.isSelfClosing()) { Element el = insertEmpty(startTag); stack.add(el); tokeniser.transition(TokeniserState.Data); // handles <script />, otherwise needs breakout steps from script data tokeniser.emit(new Token.EndTag(el.tagName())); // ensure we get out of whatever state we are in. emitted for yielded processing return el; } Element el = new Element(Tag.valueOf(startTag.name()), baseUri, startTag.attributes); insert(el); return el; } Element insert(String startTagName) { Element el = new Element(Tag.valueOf(startTagName), baseUri); insert(el); return el; } void insert(Element el) { insertNode(el); stack.add(el); } Element insertEmpty(Token.StartTag startTag) { Tag tag = Tag.valueOf(startTag.name()); Element el = new Element(tag, baseUri, startTag.attributes); insertNode(el); if (startTag.isSelfClosing()) { if (tag.isKnownTag()) { if (tag.isSelfClosing()) tokeniser.acknowledgeSelfClosingFlag(); // if not acked, promulagates error } else { // unknown tag, remember this is self closing for output tag.setSelfClosing(); tokeniser.acknowledgeSelfClosingFlag(); // not an distinct error } } return el; } FormElement insertForm(Token.StartTag startTag, boolean onStack) { Tag tag = Tag.valueOf(startTag.name()); FormElement el = new FormElement(tag, baseUri, startTag.attributes); setFormElement(el); insertNode(el); if (onStack) stack.add(el); return el; } void insert(Token.Comment commentToken) { Comment comment = new Comment(commentToken.getData(), baseUri); insertNode(comment); } void insert(Token.Character characterToken) { Node node; // characters in script and style go in as datanodes, not text nodes String tagName = currentElement().tagName(); if (tagName.equals("script") || tagName.equals("style")) node = new DataNode(characterToken.getData(), baseUri); else node = new TextNode(characterToken.getData(), baseUri); currentElement().appendChild(node); // doesn't use insertNode, because we don't foster these; and will always have a stack. } private void insertNode(Node node) { // if the stack hasn't been set up yet, elements (doctype, comments) go into the doc if (stack.size() == 0) doc.appendChild(node); else if (isFosterInserts()) insertInFosterParent(node); else currentElement().appendChild(node); // connect form controls to their form element if (node instanceof Element && ((Element) node).tag().isFormListed()) { if (formElement != null) formElement.addElement((Element) node); } } Element pop() { // todo - dev, remove validation check if (stack.peekLast().nodeName().equals("td") && !state.name().equals("InCell")) Validate.isFalse(true, "pop td not in cell"); if (stack.peekLast().nodeName().equals("html")) Validate.isFalse(true, "popping html!"); return stack.pollLast(); } void push(Element element) { stack.add(element); } DescendableLinkedList<Element> getStack() { return stack; } boolean onStack(Element el) { return isElementInQueue(stack, el); } private boolean isElementInQueue(DescendableLinkedList<Element> queue, Element element) { Iterator<Element> it = queue.descendingIterator(); while (it.hasNext()) { Element next = it.next(); if (next == element) { return true; } } return false; } Element getFromStack(String elName) { Iterator<Element> it = stack.descendingIterator(); while (it.hasNext()) { Element next = it.next(); if (next.nodeName().equals(elName)) { return next; } } return null; } boolean removeFromStack(Element el) { Iterator<Element> it = stack.descendingIterator(); while (it.hasNext()) { Element next = it.next(); if (next == el) { it.remove(); return true; } } return false; } void popStackToClose(String elName) { Iterator<Element> it = stack.descendingIterator(); while (it.hasNext()) { Element next = it.next(); if (next.nodeName().equals(elName)) { it.remove(); break; } else { it.remove(); } } } void popStackToClose(String... elNames) { Iterator<Element> it = stack.descendingIterator(); while (it.hasNext()) { Element next = it.next(); if (StringUtil.in(next.nodeName(), elNames)) { it.remove(); break; } else { it.remove(); } } } void popStackToBefore(String elName) { Iterator<Element> it = stack.descendingIterator(); while (it.hasNext()) { Element next = it.next(); if (next.nodeName().equals(elName)) { break; } else { it.remove(); } } } void clearStackToTableContext() { clearStackToContext("table"); } void clearStackToTableBodyContext() { clearStackToContext("tbody", "tfoot", "thead"); } void clearStackToTableRowContext() { clearStackToContext("tr"); } private void clearStackToContext(String... nodeNames) { Iterator<Element> it = stack.descendingIterator(); while (it.hasNext()) { Element next = it.next(); if (StringUtil.in(next.nodeName(), nodeNames) || next.nodeName().equals("html")) break; else it.remove(); } } Element aboveOnStack(Element el) { assert onStack(el); Iterator<Element> it = stack.descendingIterator(); while (it.hasNext()) { Element next = it.next(); if (next == el) { return it.next(); } } return null; } void insertOnStackAfter(Element after, Element in) { int i = stack.lastIndexOf(after); Validate.isTrue(i != -1); stack.add(i + 1, in); } void replaceOnStack(Element out, Element in) { replaceInQueue(stack, out, in); } private void replaceInQueue(LinkedList<Element> queue, Element out, Element in) { int i = queue.lastIndexOf(out); Validate.isTrue(i != -1); queue.remove(i); queue.add(i, in); } void resetInsertionMode() { boolean last = false; Iterator<Element> it = stack.descendingIterator(); while (it.hasNext()) { Element node = it.next(); if (!it.hasNext()) { last = true; node = contextElement; } String name = node.nodeName(); if ("select".equals(name)) { transition(Asta4DTagSupportHtmlTreeBuilderState.InSelect); break; // frag } else if (("td".equals(name) || "td".equals(name) && !last)) { transition(Asta4DTagSupportHtmlTreeBuilderState.InCell); break; } else if ("tr".equals(name)) { transition(Asta4DTagSupportHtmlTreeBuilderState.InRow); break; } else if ("tbody".equals(name) || "thead".equals(name) || "tfoot".equals(name)) { transition(Asta4DTagSupportHtmlTreeBuilderState.InTableBody); break; } else if ("caption".equals(name)) { transition(Asta4DTagSupportHtmlTreeBuilderState.InCaption); break; } else if ("colgroup".equals(name)) { transition(Asta4DTagSupportHtmlTreeBuilderState.InColumnGroup); break; // frag } else if ("table".equals(name)) { transition(Asta4DTagSupportHtmlTreeBuilderState.InTable); break; } else if ("head".equals(name)) { transition(Asta4DTagSupportHtmlTreeBuilderState.InBody); break; // frag } else if ("body".equals(name)) { transition(Asta4DTagSupportHtmlTreeBuilderState.InBody); break; } else if ("frameset".equals(name)) { transition(Asta4DTagSupportHtmlTreeBuilderState.InFrameset); break; // frag } else if ("html".equals(name)) { transition(Asta4DTagSupportHtmlTreeBuilderState.BeforeHead); break; // frag } else if (last) { transition(Asta4DTagSupportHtmlTreeBuilderState.InBody); break; // frag } } } // todo: tidy up in specific scope methods private boolean inSpecificScope(String targetName, String[] baseTypes, String[] extraTypes) { return inSpecificScope(new String[] { targetName }, baseTypes, extraTypes); } private boolean inSpecificScope(String[] targetNames, String[] baseTypes, String[] extraTypes) { Iterator<Element> it = stack.descendingIterator(); while (it.hasNext()) { Element el = it.next(); String elName = el.nodeName(); if (StringUtil.in(elName, targetNames)) return true; if (StringUtil.in(elName, baseTypes)) return false; if (extraTypes != null && StringUtil.in(elName, extraTypes)) return false; } Validate.fail("Should not be reachable"); return false; } boolean inScope(String[] targetNames) { return inSpecificScope(targetNames, TagsSearchInScope, null); } boolean inScope(String targetName) { return inScope(targetName, null); } boolean inScope(String targetName, String[] extras) { return inSpecificScope(targetName, TagsSearchInScope, extras); // todo: in mathml namespace: mi, mo, mn, ms, mtext annotation-xml // todo: in svg namespace: forignOjbect, desc, title } boolean inListItemScope(String targetName) { return inScope(targetName, TagSearchList); } boolean inButtonScope(String targetName) { return inScope(targetName, TagSearchButton); } boolean inTableScope(String targetName) { return inSpecificScope(targetName, TagSearchTableScope, null); } boolean inSelectScope(String targetName) { Iterator<Element> it = stack.descendingIterator(); while (it.hasNext()) { Element el = it.next(); String elName = el.nodeName(); if (elName.equals(targetName)) return true; if (!StringUtil.in(elName, TagSearchSelectScope)) // all elements except return false; } Validate.fail("Should not be reachable"); return false; } void setHeadElement(Element headElement) { this.headElement = headElement; } Element getHeadElement() { return headElement; } boolean isFosterInserts() { return fosterInserts; } void setFosterInserts(boolean fosterInserts) { this.fosterInserts = fosterInserts; } FormElement getFormElement() { return formElement; } void setFormElement(FormElement formElement) { this.formElement = formElement; } void newPendingTableCharacters() { pendingTableCharacters = new ArrayList<Token.Character>(); } List<Token.Character> getPendingTableCharacters() { return pendingTableCharacters; } void setPendingTableCharacters(List<Token.Character> pendingTableCharacters) { this.pendingTableCharacters = pendingTableCharacters; } /** * 11.2.5.2 Closing elements that have implied end tags * <p/> * When the steps below require the UA to generate implied end tags, then, while the current node is a dd element, a dt element, an li * element, an option element, an optgroup element, a p element, an rp element, or an rt element, the UA must pop the current node off * the stack of open elements. * * @param excludeTag * If a step requires the UA to generate implied end tags but lists an element to exclude from the process, then the UA must * perform the above steps as if that element was not in the above list. */ void generateImpliedEndTags(String excludeTag) { while ((excludeTag != null && !currentElement().nodeName().equals(excludeTag)) && StringUtil.in(currentElement().nodeName(), TagSearchEndTags)) pop(); } void generateImpliedEndTags() { generateImpliedEndTags(null); } boolean isSpecial(Element el) { // todo: mathml's mi, mo, mn // todo: svg's foreigObject, desc, title String name = el.nodeName(); return StringUtil.in(name, TagSearchSpecial); } // active formatting elements void pushActiveFormattingElements(Element in) { int numSeen = 0; Iterator<Element> iter = formattingElements.descendingIterator(); while (iter.hasNext()) { Element el = iter.next(); if (el == null) // marker break; if (isSameFormattingElement(in, el)) numSeen++; if (numSeen == 3) { iter.remove(); break; } } formattingElements.add(in); } private boolean isSameFormattingElement(Element a, Element b) { // same if: same namespace, tag, and attributes. Element.equals only checks tag, might in future check children return a.nodeName().equals(b.nodeName()) && // a.namespace().equals(b.namespace()) && a.attributes().equals(b.attributes()); // todo: namespaces } void reconstructFormattingElements() { int size = formattingElements.size(); if (size == 0 || formattingElements.getLast() == null || onStack(formattingElements.getLast())) return; Element entry = formattingElements.getLast(); int pos = size - 1; boolean skip = false; while (true) { if (pos == 0) { // step 4. if none before, skip to 8 skip = true; break; } entry = formattingElements.get(--pos); // step 5. one earlier than entry if (entry == null || onStack(entry)) // step 6 - neither marker nor on stack break; // jump to 8, else continue back to 4 } while (true) { if (!skip) // step 7: on later than entry entry = formattingElements.get(++pos); Validate.notNull(entry); // should not occur, as we break at last element // 8. create new element from element, 9 insert into current node, onto stack skip = false; // can only skip increment from 4. Element newEl = insert(entry.nodeName()); // todo: avoid fostering here? // newEl.namespace(entry.namespace()); // todo: namespaces newEl.attributes().addAll(entry.attributes()); // 10. replace entry with new entry formattingElements.add(pos, newEl); formattingElements.remove(pos + 1); // 11 if (pos == size - 1) // if not last entry in list, jump to 7 break; } } void clearFormattingElementsToLastMarker() { while (!formattingElements.isEmpty()) { Element el = formattingElements.peekLast(); formattingElements.removeLast(); if (el == null) break; } } void removeFromActiveFormattingElements(Element el) { Iterator<Element> it = formattingElements.descendingIterator(); while (it.hasNext()) { Element next = it.next(); if (next == el) { it.remove(); break; } } } boolean isInActiveFormattingElements(Element el) { return isElementInQueue(formattingElements, el); } Element getActiveFormattingElement(String nodeName) { Iterator<Element> it = formattingElements.descendingIterator(); while (it.hasNext()) { Element next = it.next(); if (next == null) // scope marker break; else if (next.nodeName().equals(nodeName)) return next; } return null; } void replaceActiveFormattingElement(Element out, Element in) { replaceInQueue(formattingElements, out, in); } void insertMarkerToFormattingElements() { formattingElements.add(null); } void insertInFosterParent(Node in) { Element fosterParent = null; Element lastTable = getFromStack("table"); boolean isLastTableParent = false; if (lastTable != null) { if (lastTable.parent() != null) { fosterParent = lastTable.parent(); isLastTableParent = true; } else fosterParent = aboveOnStack(lastTable); } else { // no table == frag fosterParent = stack.get(0); } if (isLastTableParent) { Validate.notNull(lastTable); // last table cannot be null by this point. lastTable.before(in); } else fosterParent.appendChild(in); } @Override public String toString() { return "TreeBuilder{" + "currentToken=" + currentToken + ", state=" + state + ", currentElement=" + currentElement() + '}'; } }
astamuse/asta4d
162
Java
org.eclipse.core.resources.prefs
text/plain
-990,356,784,746,540,500
/* * Copyright 2012 astamuse company,Ltd. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ package com.astamuse.asta4d; import java.io.OutputStream; import java.nio.charset.StandardCharsets; import java.util.ArrayList; import java.util.List; import org.jsoup.nodes.Document; import org.jsoup.select.Elements; import com.astamuse.asta4d.extnode.ExtNodeConstants; import com.astamuse.asta4d.interceptor.PageInterceptor; import com.astamuse.asta4d.interceptor.base.ExceptionHandler; import com.astamuse.asta4d.interceptor.base.Executor; import com.astamuse.asta4d.interceptor.base.GenericInterceptor; import com.astamuse.asta4d.interceptor.base.InterceptorUtil; import com.astamuse.asta4d.render.GoThroughRenderer; import com.astamuse.asta4d.render.RenderUtil; import com.astamuse.asta4d.render.Renderer; import com.astamuse.asta4d.template.Template; import com.astamuse.asta4d.template.TemplateResolver; import com.astamuse.asta4d.util.SelectorUtil; public class Page { private static class PageInterceptorWrapper implements GenericInterceptor<Document> { private PageInterceptor interceptor; public PageInterceptorWrapper(PageInterceptor interceptor) { this.interceptor = interceptor; } @Override public boolean beforeProcess(Document doc) throws Exception { Renderer renderer = new GoThroughRenderer(); interceptor.prePageRendering(renderer); RenderUtil.apply(doc, renderer); return true; } @Override public void afterProcess(Document doc, ExceptionHandler exceptionHandler) { if (exceptionHandler.getException() != null) { return; } Renderer renderer = new GoThroughRenderer(); interceptor.postPageRendering(renderer); RenderUtil.apply(doc, renderer); } public final static List<PageInterceptorWrapper> buildList(List<PageInterceptor> interceptorList) { List<PageInterceptorWrapper> list = new ArrayList<>(); if (interceptorList != null) { for (PageInterceptor interceptor : interceptorList) { list.add(new PageInterceptorWrapper(interceptor)); } } return list; } } private final static List<PageInterceptorWrapper> WrapperPageInterceptorList = PageInterceptorWrapper .buildList(Configuration.getConfiguration().getPageInterceptorList()); protected final static String DEFAULT_CONTENT_TYPE = "text/html; charset=UTF-8"; private Document renderedDocument; public Page(Template template) throws Exception { renderedDocument = renderTemplate(template); } public final static Page buildFromPath(String path) throws Exception { Configuration conf = Configuration.getConfiguration(); TemplateResolver templateResolver = conf.getTemplateResolver(); Template template = templateResolver.findTemplate(path); return new Page(template); } protected Document renderTemplate(Template template) throws Exception { Configuration conf = Configuration.getConfiguration(); Document doc = template.getDocumentClone(); doc.outputSettings().prettyPrint(conf.isOutputAsPrettyPrint()); InterceptorUtil.executeWithInterceptors(doc, WrapperPageInterceptorList, new Executor<Document>() { @Override public void execute(Document doc) throws Exception { RenderUtil.applySnippets(doc); RenderUtil.applyMessages(doc); RenderUtil.applyClearAction(doc, true); } }); // clear after page interceptors was executed RenderUtil.applyClearAction(doc, true); return doc; } protected Document getRenderedDocument() { return renderedDocument; } public String getContentType() { Elements elems = renderedDocument.select("meta[http-equiv=Content-Type]"); if (elems.size() == 0) { return DEFAULT_CONTENT_TYPE; } else { return elems.get(0).attr("content"); } } public void output(OutputStream out) throws Exception { out.write(output().getBytes(StandardCharsets.UTF_8)); } public String output() { // body only attr on body if (renderedDocument.body().hasAttr(ExtNodeConstants.ATTR_BODY_ONLY_WITH_NS)) { return renderedDocument.body().html(); } // body only meta Elements bodyonlyMeta = renderedDocument.head().select(SelectorUtil.attr("meta", ExtNodeConstants.ATTR_BODY_ONLY_WITH_NS, null)); if (bodyonlyMeta.size() > 0) { return renderedDocument.body().html(); } // full page return renderedDocument.outerHtml(); } /** * This method is for back forward compatibility in framework internal implementation, client developers should never use it. * * @param out * @throws Exception */ @Deprecated public void outputBodyOnly(OutputStream out) throws Exception { out.write(renderedDocument.body().html().getBytes(StandardCharsets.UTF_8)); } }
astamuse/asta4d
162
Java
org.eclipse.core.resources.prefs
text/plain
-3,378,501,306,288,659,500
/* * Copyright 2012 astamuse company,Ltd. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ package com.astamuse.asta4d; import java.util.HashMap; import java.util.Locale; import java.util.Map; import java.util.Map.Entry; import java.util.Set; import java.util.concurrent.Callable; import org.jsoup.nodes.Element; import com.astamuse.asta4d.data.ContextBindData; import com.astamuse.asta4d.data.ContextDataHolder; import com.astamuse.asta4d.data.InjectUtil; import com.astamuse.asta4d.extnode.ExtNodeConstants; import com.astamuse.asta4d.snippet.interceptor.SnippetInitializeInterceptor; import com.astamuse.asta4d.util.DelegatedContextMap; public class Context { public final static String SCOPE_GLOBAL = "global"; public final static String SCOPE_DEFAULT = "default"; public final static String SCOPE_ATTR = "attr"; public final static String SCOPE_EXT_ATTR = "ext_attr"; private final static String KEY_CURRENT_LOCALE = "current_locale"; private final static String KEY_CURRENT_RENDERING_ELEMENT = "current_rendering_element"; private final static ThreadLocal<Context> instanceHolder = new ThreadLocal<>(); private final static ContextMap globalMap = DelegatedContextMap.createBySingletonConcurrentHashMap(); // this map is not thought to be used in multi threads since the instance of // Context is thread single. private Map<String, ContextMap> scopeMap = new HashMap<>(); // private List @SuppressWarnings("unchecked") public final static <T extends Context> T getCurrentThreadContext() { return (T) instanceHolder.get(); } public final static void setCurrentThreadContext(Context context) { instanceHolder.set(context); } public void setCurrentRenderingElement(Element elem) { setData(KEY_CURRENT_RENDERING_ELEMENT, elem); } public Element getCurrentRenderingElement() { return getData(KEY_CURRENT_RENDERING_ELEMENT); } public void setData(String key, Object data) { setData(SCOPE_DEFAULT, key, data); } public void setData(String scope, String key, Object data) { ContextMap dataMap = acquireMapForScope(scope); dataMap.put(key, data); } public <T> T getData(String key) { return getData(SCOPE_DEFAULT, key); } @SuppressWarnings("unchecked") public <T> T getData(String scope, String key) { if (scope.equals(SCOPE_ATTR)) { return (T) retrieveElementAttr(key); } else { ContextMap dataMap = acquireMapForScope(scope); return (T) dataMap.get(key); } } public <T> ContextDataHolder<T> getDataHolder(String key) { return getDataHolder(SCOPE_DEFAULT, key); } @SuppressWarnings("unchecked") public <T> ContextDataHolder<T> getDataHolder(String scope, String key) { Object v = getData(scope, key); if (v == null) { return null; } else { ContextDataHolder<T> holder = new ContextDataHolder<T>(key, scope, (T) v); return holder; } } public Locale getCurrentLocale() { Locale currentLocale = getData(KEY_CURRENT_LOCALE); if (currentLocale != null) { return currentLocale; } return Locale.getDefault(); } public void setCurrentLocale(Locale locale) { setData(KEY_CURRENT_LOCALE, locale); } private Object retrieveElementAttr(String key) { String dataRef = ExtNodeConstants.ATTR_DATAREF_PREFIX_WITH_NS + key; Element elem = getCurrentRenderingElement(); Object value = null; while (value == null && elem != null) { // for a faked snippet node, we will just jump over it if (elem.tagName().equals(ExtNodeConstants.SNIPPET_NODE_TAG)) { String type = elem.attr(ExtNodeConstants.SNIPPET_NODE_ATTR_TYPE); if (type.equals(ExtNodeConstants.SNIPPET_NODE_ATTR_TYPE_FAKE)) { elem = elem.parent(); continue; } } if (elem.hasAttr(dataRef)) { String id = elem.attr(dataRef); value = getData(SCOPE_EXT_ATTR, id); } else if (elem.hasAttr(key)) { value = elem.attr(key); } elem = elem.parent(); } return value; } protected final ContextMap acquireMapForScope(String scope) { ContextMap dataMap = scopeMap.get(scope); if (dataMap == null) { dataMap = createMapForScope(scope); if (dataMap == null) { dataMap = DelegatedContextMap.createByNonThreadSafeHashMap(); } scopeMap.put(scope, dataMap); } return dataMap; } /** * sub class can override this method for custom scope map instance * * @param scope * @return */ protected ContextMap createMapForScope(String scope) { ContextMap map = null; switch (scope) { case SCOPE_GLOBAL: map = globalMap; break; case SCOPE_EXT_ATTR: map = DelegatedContextMap.createBySingletonConcurrentHashMap(); break; default: map = DelegatedContextMap.createByNonThreadSafeHashMap(); } return map; } public void init() { clear(); ContextBindData.initConext(this); InjectUtil.initContext(this); SnippetInitializeInterceptor.initContext(this); } public void clear() { scopeMap.clear(); } public Context clone() { Context newCtx = new Context(); copyScopesTo(newCtx); return newCtx; } protected void copyScopesTo(Context newCtx) { Set<Entry<String, ContextMap>> entrys = scopeMap.entrySet(); for (Entry<String, ContextMap> entry : entrys) { newCtx.scopeMap.put(entry.getKey(), entry.getValue().createClone()); } } public final static void with(Context context, Runnable runner) { Context oldContext = Context.getCurrentThreadContext(); try { Context.setCurrentThreadContext(context); runner.run(); } finally { Context.setCurrentThreadContext(oldContext); } } public final static <T> T with(Context context, Callable<T> caller) throws Exception { Context oldContext = Context.getCurrentThreadContext(); try { Context.setCurrentThreadContext(context); return caller.call(); } finally { Context.setCurrentThreadContext(oldContext); } } public void with(String varName, Object varValue, Runnable runner) { Object orinialData = null; try { orinialData = this.getData(varName); this.setData(varName, varValue); runner.run(); } finally { // revive the scene this.setData(varName, orinialData); } } public <T> T with(String varName, Object varValue, Callable<T> caller) throws Exception { Object orinialData = null; try { orinialData = this.getData(varName); this.setData(varName, varValue); return caller.call(); } finally { // revive the scene this.setData(varName, orinialData); } } }
astamuse/asta4d
162
Java
org.eclipse.core.resources.prefs
text/plain
7,179,052,360,571,065,000
/* * Copyright 2012 astamuse company,Ltd. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ package com.astamuse.asta4d; import java.util.ArrayList; import java.util.List; import org.jsoup.nodes.Document; import org.jsoup.nodes.Element; import org.jsoup.nodes.Node; import com.astamuse.asta4d.extnode.GroupNode; import com.astamuse.asta4d.render.AttributeSetter; import com.astamuse.asta4d.render.RenderUtil; import com.astamuse.asta4d.template.Template; import com.astamuse.asta4d.template.TemplateResolver; public class Component { public static abstract class AttributesRequire { private List<AttributeSetter> attrList = new ArrayList<>(); public AttributesRequire() { this.prepareAttributes(); } protected void add(String attr, Object value) { attrList.add(new AttributeSetter(attr, value)); } List<AttributeSetter> getAttrList() { return attrList; } protected abstract void prepareAttributes(); } private Element renderedElement; public Component(Element elem, AttributesRequire attrs) throws Exception { Document doc = new Document(""); doc.appendElement("body"); doc.body().appendChild(elem); renderedElement = renderTemplate(doc, attrs); } public Component(Element elem) throws Exception { this(elem, null); } public Component(String path, AttributesRequire attrs) throws Exception { Configuration conf = Configuration.getConfiguration(); TemplateResolver templateResolver = conf.getTemplateResolver(); Template template = templateResolver.findTemplate(path); renderedElement = renderTemplate(template.getDocumentClone(), attrs); } public Component(String path) throws Exception { this(path, null); } protected Element renderTemplate(Document doc, AttributesRequire attrs) throws Exception { if (attrs != null) { List<AttributeSetter> attrList = attrs.getAttrList(); Element body = doc.body(); for (AttributeSetter attributeSetter : attrList) { attributeSetter.set(body); } } RenderUtil.applySnippets(doc); Element grp = new GroupNode(); List<Node> children = new ArrayList<>(doc.body().childNodes()); for (Node node : children) { node.remove(); grp.appendChild(node); } return grp; } public Element toElement() { return renderedElement.clone(); } public String toHtml() { Document doc = new Document(""); doc.appendChild(toElement()); RenderUtil.applyMessages(doc); RenderUtil.applyClearAction(doc, true); return doc.html(); } public String toString() { return toHtml(); } }
astamuse/asta4d
162
Java
org.eclipse.core.resources.prefs
text/plain
-1,727,920,631,247,995,600
/* * Copyright 2014 astamuse company,Ltd. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ package com.astamuse.asta4d; public interface ContextMap { public void put(String key, Object data); public <T> T get(String key); public ContextMap createClone(); }
astamuse/asta4d
162
Java
org.eclipse.core.resources.prefs
text/plain
-558,893,079,779,515,840
/* * Copyright 2012 astamuse company,Ltd. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ package com.astamuse.asta4d; import java.util.ArrayList; import java.util.LinkedList; import java.util.List; import com.astamuse.asta4d.data.ContextDataFinder; import com.astamuse.asta4d.data.DataTypeTransformer; import com.astamuse.asta4d.data.DefaultContextDataFinder; import com.astamuse.asta4d.data.DefaultDataTypeTransformer; import com.astamuse.asta4d.interceptor.PageInterceptor; import com.astamuse.asta4d.snippet.DefaultSnippetInvoker; import com.astamuse.asta4d.snippet.SnippetInvoker; import com.astamuse.asta4d.snippet.extract.DefaultSnippetExtractor; import com.astamuse.asta4d.snippet.extract.SnippetExtractor; import com.astamuse.asta4d.snippet.resolve.DefaultSnippetResolver; import com.astamuse.asta4d.snippet.resolve.SnippetResolver; import com.astamuse.asta4d.template.FileTemplateResolver; import com.astamuse.asta4d.template.TemplateResolver; import com.astamuse.asta4d.util.collection.ParallelRecursivePolicy; import com.astamuse.asta4d.util.concurrent.DefaultExecutorServiceFactory; import com.astamuse.asta4d.util.concurrent.ExecutorServiceFactory; import com.astamuse.asta4d.util.i18n.I18nMessageHelper; import com.astamuse.asta4d.util.i18n.OrderedParamI18nMessageHelper; public class Configuration { private TemplateResolver templateResolver = new FileTemplateResolver(); private SnippetInvoker snippetInvoker = new DefaultSnippetInvoker(); private SnippetResolver snippetResolver = new DefaultSnippetResolver(); private SnippetExtractor snippetExtractor = new DefaultSnippetExtractor(); private List<PageInterceptor> pageInterceptorList = new ArrayList<>(); private ContextDataFinder contextDataFinder = new DefaultContextDataFinder(); private DataTypeTransformer dataTypeTransformer = new DefaultDataTypeTransformer(); private I18nMessageHelper i18nMessageHelper = new OrderedParamI18nMessageHelper(); private boolean cacheEnable = true; private boolean skipSnippetExecution = false; private boolean outputAsPrettyPrint = false; private ExecutorServiceFactory snippetExecutorFactory = new DefaultExecutorServiceFactory("asta4d-snippet", 200); private ExecutorServiceFactory parallelListConvertingExecutorFactory = new DefaultExecutorServiceFactory("asta4d-parallel-list", 600); private boolean blockParallelListRendering = false; private ParallelRecursivePolicy recursivePolicyForParallelListConverting = ParallelRecursivePolicy.EXCEPTION; private int numberLimitOfParallelListConverting = 50; private List<String> clearNodeClasses = new ArrayList<>(); private String tagNameSpace = "afd"; private boolean saveCallstackInfoOnRendererCreation = false; /** * application should retrieve this list and invoke all the hookers when shutdown. */ private List<Runnable> shutdownHookers = new LinkedList<>(); private static Configuration instance; public final static Configuration getConfiguration() { return instance; } public final static void setConfiguration(Configuration configuration) { instance = configuration; } public TemplateResolver getTemplateResolver() { return templateResolver; } public void setTemplateResolver(TemplateResolver templateResolver) { this.templateResolver = templateResolver; } public SnippetInvoker getSnippetInvoker() { return snippetInvoker; } public void setSnippetInvoker(SnippetInvoker snippetInvoker) { this.snippetInvoker = snippetInvoker; } public SnippetResolver getSnippetResolver() { return snippetResolver; } public void setSnippetResolver(SnippetResolver snippetResolver) { this.snippetResolver = snippetResolver; } public SnippetExtractor getSnippetExtractor() { return snippetExtractor; } public void setSnippetExtractor(SnippetExtractor snippetExtractor) { this.snippetExtractor = snippetExtractor; } public List<PageInterceptor> getPageInterceptorList() { return pageInterceptorList; } public void setPageInterceptorList(List<PageInterceptor> pageInterceptorList) { this.pageInterceptorList = pageInterceptorList; } public ContextDataFinder getContextDataFinder() { return contextDataFinder; } public void setContextDataFinder(ContextDataFinder contextDataFinder) { this.contextDataFinder = contextDataFinder; } public DataTypeTransformer getDataTypeTransformer() { return dataTypeTransformer; } public void setDataTypeTransformer(DataTypeTransformer dataTypeTransformer) { this.dataTypeTransformer = dataTypeTransformer; } public I18nMessageHelper getI18nMessageHelper() { return i18nMessageHelper; } public void setI18nMessageHelper(I18nMessageHelper i18nMessageHelper) { this.i18nMessageHelper = i18nMessageHelper; } public boolean isCacheEnable() { return cacheEnable; } public void setCacheEnable(boolean cacheEnable) { this.cacheEnable = cacheEnable; } public boolean isSkipSnippetExecution() { return skipSnippetExecution; } public void setSkipSnippetExecution(boolean skipSnippetExecution) { this.skipSnippetExecution = skipSnippetExecution; } public ExecutorServiceFactory getSnippetExecutorFactory() { return snippetExecutorFactory; } public void setSnippetExecutorFactory(ExecutorServiceFactory snippetExecutorFactory) { this.snippetExecutorFactory = snippetExecutorFactory; } public ExecutorServiceFactory getParallelListConvertingExecutorFactory() { return parallelListConvertingExecutorFactory; } public void setParallelListConvertingExecutorFactory(ExecutorServiceFactory parallelListConvertingExecutorFactory) { this.parallelListConvertingExecutorFactory = parallelListConvertingExecutorFactory; } public ParallelRecursivePolicy getRecursivePolicyForParallelConverting() { return recursivePolicyForParallelListConverting; } public void setRecursivePolicyForParallelListConverting(ParallelRecursivePolicy recursivePolicyForParallelListConverting) { this.recursivePolicyForParallelListConverting = recursivePolicyForParallelListConverting; } public boolean isOutputAsPrettyPrint() { return outputAsPrettyPrint; } public void setOutputAsPrettyPrint(boolean outputAsPrettyPrint) { this.outputAsPrettyPrint = outputAsPrettyPrint; } public boolean isBlockParallelListRendering() { return blockParallelListRendering; } public void setBlockParallelListRendering(boolean blockParallelListRendering) { this.blockParallelListRendering = blockParallelListRendering; } public List<String> getClearNodeClasses() { return clearNodeClasses; } public void setClearNodeClasses(List<String> clearNodeClasses) { this.clearNodeClasses = clearNodeClasses; } public String getTagNameSpace() { return tagNameSpace; } public void setTagNameSpace(String tagNameSpace) { this.tagNameSpace = tagNameSpace; } public boolean isSaveCallstackInfoOnRendererCreation() { return saveCallstackInfoOnRendererCreation; } public void setSaveCallstackInfoOnRendererCreation(boolean saveCallstackInfoOnRendererCreation) { this.saveCallstackInfoOnRendererCreation = saveCallstackInfoOnRendererCreation; } public int getNumberLimitOfParallelListConverting() { return numberLimitOfParallelListConverting; } public void setNumberLimitOfParallelListConverting(int numberLimitOfParallelListConverting) { this.numberLimitOfParallelListConverting = numberLimitOfParallelListConverting; } public List<Runnable> getShutdownHookers() { return new ArrayList<>(shutdownHookers); } public void addShutdownHookers(Runnable runnable) { shutdownHookers.add(runnable); } }
astamuse/asta4d
162
Java
org.eclipse.core.resources.prefs
text/plain
1,442,164,106,548,778,000
/* * Copyright 2012 astamuse company,Ltd. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ package com.astamuse.asta4d.util; public class Asta4DWarningException extends RuntimeException { /** * */ private static final long serialVersionUID = -2603684529937435896L; public Asta4DWarningException(String message, Throwable cause) { super(message, cause); } public Asta4DWarningException(String message) { super(message); } }
astamuse/asta4d
162
Java
org.eclipse.core.resources.prefs
text/plain
-7,665,924,373,417,999,000
/* * Copyright 2014 astamuse company,Ltd. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ package com.astamuse.asta4d.util; import com.astamuse.asta4d.ContextMap; public class UnmodifiableContextMap implements ContextMap { private ContextMap map; public UnmodifiableContextMap(ContextMap map) { super(); this.map = map; } public void put(String key, Object data) { throw new UnsupportedOperationException("Put operation is forbidden on this class:" + this.getClass().getName()); } public <T> T get(String key) { return map.get(key); } public ContextMap createClone() { return this; } }
astamuse/asta4d
162
Java
org.eclipse.core.resources.prefs
text/plain
3,729,478,271,768,756,000
package com.astamuse.asta4d.util; public class ClosureReference<T> { /** * This ref is not volatile, which means you should avoid to use it in crossing threads sharing.<br> * For cross thread sharing, use {@link SyncClosureReference} instead. */ public T ref = null; }
astamuse/asta4d
162
Java
org.eclipse.core.resources.prefs
text/plain
4,924,036,931,148,842,000
package com.astamuse.asta4d.util; public class SyncClosureReference<T> { /** * This ref is volatile, which is necessary for make sure all threads can retrieve the reference after it has been assigned. Further, * since we will write it once and read it many times in most situations, the cost is payable. */ public volatile T ref = null; }
astamuse/asta4d
162
Java
org.eclipse.core.resources.prefs
text/plain
1,665,806,975,943,825,000
package com.astamuse.asta4d.util; import java.lang.reflect.AccessibleObject; import com.thoughtworks.paranamer.BytecodeReadingParanamer; import com.thoughtworks.paranamer.Paranamer; public class Java8ParanamerBytecodeScanWrapper extends BytecodeReadingParanamer { public Java8ParanamerBytecodeScanWrapper() { super(); } @Override public String[] lookupParameterNames(AccessibleObject methodOrConstructor) { return lookupParameterNames(methodOrConstructor, true); } @Override public String[] lookupParameterNames(AccessibleObject methodOrConstructor, boolean throwExceptionIfMissing) { try { return super.lookupParameterNames(methodOrConstructor, throwExceptionIfMissing); } catch (Exception ex) { return Paranamer.EMPTY_NAMES; } } }
astamuse/asta4d
162
Java
org.eclipse.core.resources.prefs
text/plain
1,356,884,493,128,891,400
package com.astamuse.asta4d.util; import java.lang.reflect.AccessibleObject; import java.lang.reflect.Constructor; import java.lang.reflect.Method; import java.lang.reflect.Parameter; import java.util.Arrays; import com.thoughtworks.paranamer.Paranamer; public class Java8Paranamer implements Paranamer { @Override public String[] lookupParameterNames(AccessibleObject methodOrConstructor) { return lookupParameterNames(methodOrConstructor, true); } @Override public String[] lookupParameterNames(AccessibleObject methodOrConstructor, boolean throwExceptionIfMissing) { Parameter[] parameters = getParameters(methodOrConstructor); return Arrays.stream(parameters).map(p -> { return p.getName(); }).toArray(String[]::new); } private Parameter[] getParameters(AccessibleObject methodOrConstructor) { if (methodOrConstructor instanceof Method) { Method method = (Method) methodOrConstructor; return method.getParameters(); } else { Constructor<?> constructor = (Constructor<?>) methodOrConstructor; return constructor.getParameters(); } } }
astamuse/asta4d
162
Java
org.eclipse.core.resources.prefs
text/plain
3,350,377,467,292,165,600
/* * Copyright 2012 astamuse company,Ltd. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ package com.astamuse.asta4d.util; public class SelectorUtil { public final static String not(String not) { return not(null, not); } public final static String not(String prefix, String not) { StringBuilder sb = new StringBuilder(); sb.append(prefix == null ? "*" : prefix); sb.append(":not(").append(not).append(")"); return sb.toString(); } public final static String attr(String attr) { return attr(attr, null); } public final static String attr(String attr, String value) { return attr(null, attr, value); } public final static String attr(String prefix, String attr, String value) { StringBuilder sb = new StringBuilder(); if (prefix != null) { sb.append(prefix); } sb.append("[").append(attr); if (value != null) { sb.append("=").append(value); } sb.append("]"); return sb.toString(); } public final static String id(String id) { return id(null, id); } public final static String id(String prefix, String id) { StringBuilder sb = new StringBuilder(); if (prefix != null) { sb.append(prefix); } sb.append("#").append(id); return sb.toString(); } public final static String tag(String tag) { return tag.replace(':', '|'); } }
astamuse/asta4d
162
Java
org.eclipse.core.resources.prefs
text/plain
-8,021,044,183,155,626,000
package com.astamuse.asta4d.util; import java.time.LocalDateTime; import java.time.ZoneId; import java.time.ZoneOffset; import java.time.ZonedDateTime; public class Java8TimeUtil { private static final ZoneOffset _defaultZoneOffset; static { LocalDateTime ldt = LocalDateTime.now(); ZonedDateTime zdt = ldt.atZone(ZoneId.systemDefault()); _defaultZoneOffset = zdt.getOffset(); } public static final ZoneOffset defaultZoneOffset() { return _defaultZoneOffset; } }
astamuse/asta4d
162
Java
org.eclipse.core.resources.prefs
text/plain
-8,714,042,238,975,581,000
/* * Copyright 2014 astamuse company,Ltd. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ package com.astamuse.asta4d.util; import java.lang.ref.SoftReference; import java.util.Map; import java.util.concurrent.ConcurrentHashMap; /** * We want to cache the result of not found resources but a potential DDOS attack can be performed against this wish. Thus we cache the not * found results in a SoftRreferenced map. * * @author e-ryu * * @param <K> * @param <V> */ public class MemorySafeResourceCache<K, V> { public static class ResouceHolder<T> { private T resource; ResouceHolder(T _res) { resource = _res; } public T get() { return resource; } public boolean exists() { return resource != null; } } private Map<K, ResouceHolder<V>> existingResourceMap; private SoftReference<Map<K, ResouceHolder<V>>> notExistingResourceMapRef = null; private final ResouceHolder<V> notExistingHolder = new ResouceHolder<>(null); public MemorySafeResourceCache() { // a copy on write map would be better existingResourceMap = new ConcurrentHashMap<>(); } /** * * @param key * throw NullPointerException when key is null * @param resource * null means the resource of the given key is not existing */ public void put(K key, V resource) { if (key == null) { throw new NullPointerException(); } if (resource == null) { getNotExistingResourceMap().put(key, notExistingHolder); } else { existingResourceMap.put(key, new ResouceHolder<>(resource)); } } private Map<K, ResouceHolder<V>> getNotExistingResourceMap() { Map<K, ResouceHolder<V>> map = null; if (notExistingResourceMapRef == null) { map = new ConcurrentHashMap<>(); notExistingResourceMapRef = new SoftReference<>(map); } else { map = notExistingResourceMapRef.get(); if (map == null) { map = new ConcurrentHashMap<>(); notExistingResourceMapRef = new SoftReference<>(map); } } return map; } public ResouceHolder<V> get(K key) { ResouceHolder<V> holder = existingResourceMap.get(key); if (holder == null) { holder = getNotExistingResourceMap().get(key); } return holder; } }
astamuse/asta4d
162
Java
org.eclipse.core.resources.prefs
text/plain
4,895,129,472,620,524,000
/* * Copyright 2012 astamuse company,Ltd. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ package com.astamuse.asta4d.util; import java.util.ArrayList; import java.util.Iterator; import java.util.List; import org.jsoup.Jsoup; import org.jsoup.nodes.Element; import org.jsoup.nodes.Node; import org.jsoup.nodes.TextNode; import org.jsoup.select.Elements; import com.astamuse.asta4d.extnode.GroupNode; public class ElementUtil { public ElementUtil() { } public final static Element text(String text) { TextNode node = new TextNode(text, ""); Element wrap = new GroupNode(); wrap.appendChild(node); return wrap; } /** * parse given html source to a single Element * <p> * <b>ATTENTION</b>: this method will cause a potential XSS problem, so be sure that you have escaped the passed html string if * necessary. * * @param html * the html source * @return a Element object which contains the dom tree created from passed html source */ public final static Element parseAsSingle(String html) { Element body = Jsoup.parseBodyFragment(html).body(); List<Node> children = body.childNodes(); return wrapElementsToSingleNode(children); } public final static Element wrapElementsToSingleNode(List<Node> elements) { Element groupNode = new GroupNode(); List<Node> list = new ArrayList<Node>(elements); for (Node node : list) { node.remove(); groupNode.appendChild(node); } return groupNode; } public final static void removeNodesBySelector(Element target, String selector, boolean pullupChildren) { Elements removeNodes = target.select(selector); Iterator<Element> it = removeNodes.iterator(); Element rm; while (it.hasNext()) { rm = it.next(); if (target == rm) { continue; } if (rm.ownerDocument() == null) { continue; } if (pullupChildren) { pullupChildren(rm); } rm.remove(); } } public final static void pullupChildren(Element elem) { List<Node> childrenNodes = new ArrayList<>(elem.childNodes()); for (Node node : childrenNodes) { node.remove(); elem.before(node); } } }
astamuse/asta4d
162
Java
org.eclipse.core.resources.prefs
text/plain
1,478,673,290,963,328,500
/* * Copyright 2012 astamuse company,Ltd. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ package com.astamuse.asta4d.util; import java.util.ArrayList; import java.util.List; import org.slf4j.Logger; import org.slf4j.LoggerFactory; public abstract class MultiSearchPathResourceLoader<T> { private Logger logger = LoggerFactory.getLogger(this.getClass()); private String[] searchPathList = new String[0]; public MultiSearchPathResourceLoader() { } public T searchResource(String pathSeparator, String... names) { if (names == null || names.length < 1) { throw new IllegalArgumentException("must specify one or more names"); } return searchResource(pathSeparator, -1, names); } private T searchResource(String pathSeparator, int index, String... names) { List<String> searchNames = new ArrayList<>(); for (String name : names) { String searchName; if (index < 0) { searchName = name; } else if (index >= searchPathList.length) { logger.debug("Did not find any associated resource for name {}", name); return null; } else { String searchPath = searchPathList[index]; boolean pathWithSeparator = searchPath.endsWith(pathSeparator); boolean nameWithSeparator = name.startsWith(pathSeparator); if (pathWithSeparator && nameWithSeparator) { searchName = searchPath + name.substring(1); } else if (pathWithSeparator || nameWithSeparator) { searchName = searchPath + name; } else { // nether has searchName = searchPath + pathSeparator + name; } } logger.debug("try load resource for {}", searchName); T result = loadResource(searchName); if (result != null) { return result; } searchNames.add(searchName); } logger.debug("load resource for {} failed", searchNames.toString()); return searchResource(pathSeparator, index + 1, names); } protected abstract T loadResource(String name); public String[] getSearchPathList() { return searchPathList.clone(); } public void setSearchPathList(String... searchPathList) { this.searchPathList = searchPathList.clone(); } }
astamuse/asta4d
162
Java
org.eclipse.core.resources.prefs
text/plain
1,787,800,248,302,061,000
/* * Copyright 2014 astamuse company,Ltd. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ package com.astamuse.asta4d.util; import java.lang.reflect.Field; import java.util.Arrays; import java.util.LinkedList; import java.util.List; public class ClassUtil { @SuppressWarnings("rawtypes") public static final List<Field> retrieveAllFieldsIncludeAllSuperClasses(Class cls) { Class c = cls; List<Field> resultList = new LinkedList<Field>(); while (!c.getName().equals("java.lang.Object")) { resultList.addAll(Arrays.asList(c.getDeclaredFields())); c = c.getSuperclass(); } return resultList; } }
astamuse/asta4d
162
Java
org.eclipse.core.resources.prefs
text/plain
7,898,314,407,043,568,000
/* * Copyright 2012 astamuse company,Ltd. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ package com.astamuse.asta4d.util; import java.nio.ByteBuffer; import java.security.SecureRandom; import java.util.Base64; import java.util.Base64.Encoder; public class IdGenerator { private static Encoder b64Encoder = Base64.getUrlEncoder(); // this seed must by 5 bytes due to avoid base64 padding later private final static byte[] randomSeed; static { // use the last 32 bit of current time as the seed ByteBuffer bb = ByteBuffer.allocate(64); bb.putLong(System.currentTimeMillis()); byte[] bytes = bb.array(); byte[] seed = new byte[4]; System.arraycopy(bytes, 4, seed, 0, 4); SecureRandom sr = new SecureRandom(seed); int s = Math.abs(sr.nextInt()); ByteBuffer seedBuffer = ByteBuffer.allocate(5); seedBuffer.putInt(s); seedBuffer.put(seed[3]); randomSeed = seedBuffer.array(); } private final static class IdHolder { // must be times of 3 to avoid padding, 8 + 8 + 5 = 21 private ByteBuffer buffer = ByteBuffer.allocate(21); private long threadId; private long lastTime = Long.MIN_VALUE; public IdHolder(long threadId) { this.threadId = threadId; this.buffer.mark(); } public long getThreadId() { return this.threadId; } long newTime() { // since the current milliseconds is less than 40 bit, we think this // operation is safe long cur = System.currentTimeMillis() << 7; if (cur > lastTime) { lastTime = cur; } else { lastTime++; cur = lastTime; } return cur; } public byte[] newId() { buffer.reset(); buffer.putLong(newTime());// 8 buffer.putLong(threadId);// 8 buffer.put(randomSeed);// 5 byte[] bs = new byte[21]; System.arraycopy(buffer.array(), 0, bs, 0, 21); return bs; } } private final static ThreadLocal<IdHolder> idHolderCache = new ThreadLocal<IdHolder>() { @Override protected IdHolder initialValue() { return new IdHolder(Thread.currentThread().getId()); } }; /** * a unique id with thread id embedded and a process unique(random) number, as string. * * @return */ public final static String createId() { IdHolder idHolder = idHolderCache.get(); return b64Encoder.encodeToString(idHolder.newId()); } /** * a unique id with thread id embedded and a process unique(random) number, as byte array * * @return */ public final static byte[] createIdBytes() { IdHolder idHolder = idHolderCache.get(); return idHolder.newId(); } }
astamuse/asta4d
162
Java
org.eclipse.core.resources.prefs
text/plain
-6,911,352,327,101,968,000
/* * Copyright 2014 astamuse company,Ltd. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ package com.astamuse.asta4d.util; import java.util.HashMap; import java.util.Map; import java.util.concurrent.ConcurrentHashMap; import com.astamuse.asta4d.ContextMap; @SuppressWarnings({ "rawtypes", "unchecked" }) public class DelegatedContextMap implements ContextMap { private Class<? extends Map> mapCls; private Map map; private boolean copyOnClone; public DelegatedContextMap(Class<? extends Map> mapCls, boolean copyOnClone) { try { this.mapCls = mapCls; this.map = mapCls.newInstance(); this.copyOnClone = copyOnClone; } catch (Exception e) { throw new RuntimeException(e); } } public final static DelegatedContextMap createBySingletonConcurrentHashMap() { return new DelegatedContextMap(ConcurrentHashMap.class, false); } public final static DelegatedContextMap createByNonThreadSafeHashMap() { return new DelegatedContextMap(HashMap.class, true); } @Override public void put(String key, Object data) { if (data == null) { map.remove(key); } else { map.put(key, data); } } @Override public <T> T get(String key) { return (T) map.get(key); } @Override public ContextMap createClone() { if (copyOnClone) { DelegatedContextMap newMap = new DelegatedContextMap(mapCls, copyOnClone); newMap.map.putAll(map); return newMap; } else { return this; } } }
astamuse/asta4d
162
Java
org.eclipse.core.resources.prefs
text/plain
6,115,007,111,317,251,000
/* * Copyright 2012 astamuse company,Ltd. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ package com.astamuse.asta4d.util; import java.io.PrintStream; import java.io.PrintWriter; import java.util.Arrays; import java.util.LinkedList; import java.util.List; /** * we use this Exception to combine multiple exceptions to a single one * * @author e-ryu * */ public class GroupedException extends RuntimeException { /** * */ private static final long serialVersionUID = 1L; private List<Exception> exceptionList = null; public void setExceptionList(List<Exception> exceptionList) { this.exceptionList = exceptionList; } @Override public String getMessage() { StringBuffer sb = new StringBuffer("There are multiple exceptions ocurred. Please check them one by one.\n"); for (Exception ex : exceptionList) { sb.append(ex.getClass().getName()).append(":").append(ex.getMessage()).append("\n"); } return sb.toString(); } @Override public String getLocalizedMessage() { StringBuffer sb = new StringBuffer("There are multiple exceptions ocurred. Please check them one by one.\n"); for (Exception ex : exceptionList) { sb.append(ex.getClass().getName()).append(":").append(ex.getLocalizedMessage()).append("\n"); } return sb.toString(); } @Override public void printStackTrace() { for (Exception ex : exceptionList) { System.err.println(ex.getClass().getName() + ":"); ex.printStackTrace(); } System.err.println(); } @Override public void printStackTrace(PrintStream s) { for (Exception ex : exceptionList) { s.println(ex.getClass().getName() + ":"); ex.printStackTrace(s); } s.println(); } @Override public void printStackTrace(PrintWriter s) { for (Exception ex : exceptionList) { s.println(ex.getClass().getName() + ":"); ex.printStackTrace(s); } s.println(); } @Override public StackTraceElement[] getStackTrace() { List<StackTraceElement> list = new LinkedList<>(); for (Exception ex : exceptionList) { list.addAll(Arrays.asList(ex.getStackTrace())); } return list.toArray(new StackTraceElement[list.size()]); } }
astamuse/asta4d
162
Java
org.eclipse.core.resources.prefs
text/plain
8,226,583,533,279,220,000
/* * Copyright 2014 astamuse company,Ltd. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ package com.astamuse.asta4d.util.annotation; import java.lang.annotation.Annotation; import java.lang.reflect.Field; import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; import java.util.ArrayList; import java.util.Collections; import java.util.HashSet; import java.util.Iterator; import java.util.LinkedList; import java.util.List; import java.util.Map; import java.util.Set; import java.util.concurrent.ConcurrentHashMap; import java.util.stream.Collectors; import org.apache.commons.collections4.CollectionUtils; import org.apache.commons.lang3.StringUtils; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import com.astamuse.asta4d.Configuration; import com.astamuse.asta4d.util.ClassUtil; public class AnnotatedPropertyUtil { private static class ReadOnlyAnnotatedPropertyInfo extends AnnotatedPropertyInfo { private AnnotatedPropertyInfo info; ReadOnlyAnnotatedPropertyInfo(AnnotatedPropertyInfo info) { this.info = info; } public String getName() { return info.getName(); } public void setName(String name) { throw new UnsupportedOperationException(); } public String getBeanPropertyName() { return info.getBeanPropertyName(); } public void setBeanPropertyName(String beanPropertyName) { throw new UnsupportedOperationException(); } public Field getField() { return info.getField(); } public void setField(Field field) { throw new UnsupportedOperationException(); } public Method getGetter() { return info.getGetter(); } public void setGetter(Method getter) { throw new UnsupportedOperationException(); } public Method getSetter() { return info.getSetter(); } public void setSetter(Method setter) { throw new UnsupportedOperationException(); } @SuppressWarnings("rawtypes") public Class getType() { return info.getType(); } @SuppressWarnings("rawtypes") public void setType(Class type) { throw new UnsupportedOperationException(); } public <A extends Annotation> A getAnnotation(Class<A> annotationCls) { return info.getAnnotation(annotationCls); } public void setAnnotations(List<Annotation> annotationList) { throw new UnsupportedOperationException(); } public void assignValue(Object instance, Object value) throws IllegalAccessException, IllegalArgumentException, InvocationTargetException { info.assignValue(instance, value); } public Object retrieveValue(Object instance) throws IllegalAccessException, IllegalArgumentException, InvocationTargetException { return info.retrieveValue(instance); } public int hashCode() { return info.hashCode(); } public boolean equals(Object obj) { return info.equals(obj); } public String toString() { return info.toString(); } } private static class AnnotatedPropertyInfoMap { Map<String, List<AnnotatedPropertyInfo>> nameMap; Map<String, List<AnnotatedPropertyInfo>> beanNameMap; List<AnnotatedPropertyInfo> list; AnnotatedPropertyInfoMap(List<AnnotatedPropertyInfo> infoList) { list = infoList.stream().map(info -> new ReadOnlyAnnotatedPropertyInfo(info)).collect(Collectors.toList()); list = Collections.unmodifiableList(list); nameMap = list.stream().collect(Collectors.groupingBy(info -> info.getName())); makeListUnmodifiable(nameMap); nameMap = Collections.unmodifiableMap(nameMap); beanNameMap = list.stream().collect(Collectors.groupingBy(info -> info.getBeanPropertyName())); makeListUnmodifiable(beanNameMap); beanNameMap = Collections.unmodifiableMap(beanNameMap); } void makeListUnmodifiable(Map<String, List<AnnotatedPropertyInfo>> map) { for (String key : map.keySet()) { map.put(key, Collections.unmodifiableList(map.get(key))); } } } private static final Logger logger = LoggerFactory.getLogger(AnnotatedPropertyUtil.class); private static final ConcurrentHashMap<String, AnnotatedPropertyInfoMap> propertiesMapCache = new ConcurrentHashMap<>(); // TODO allow method property to override field property to avoid duplicated properties @SuppressWarnings({ "rawtypes", "unchecked" }) private static AnnotatedPropertyInfoMap retrievePropertiesMap(Class cls) { String cacheKey = cls.getName(); AnnotatedPropertyInfoMap map = propertiesMapCache.get(cacheKey); if (map == null) { List<AnnotatedPropertyInfo> infoList = new LinkedList<>(); Set<String> beanPropertyNameSet = new HashSet<>(); Method[] mtds = cls.getMethods(); for (Method method : mtds) { List<Annotation> annoList = ConvertableAnnotationRetriever.retrieveAnnotationHierarchyList(AnnotatedProperty.class, method.getAnnotations()); if (CollectionUtils.isEmpty(annoList)) { continue; } AnnotatedPropertyInfo info = new AnnotatedPropertyInfo(); info.setAnnotations(annoList); boolean isGet = false; boolean isSet = false; String propertySuffixe = method.getName(); if (propertySuffixe.startsWith("set")) { propertySuffixe = propertySuffixe.substring(3); isSet = true; } else if (propertySuffixe.startsWith("get")) { propertySuffixe = propertySuffixe.substring(3); isGet = true; } else if (propertySuffixe.startsWith("is")) { propertySuffixe = propertySuffixe.substring(2); isSet = true; } else { String msg = String.format("Method [%s]:[%s] can not be treated as a getter or setter method.", cls.getName(), method.toGenericString()); throw new RuntimeException(msg); } char[] cs = propertySuffixe.toCharArray(); cs[0] = Character.toLowerCase(cs[0]); info.setBeanPropertyName(new String(cs)); AnnotatedProperty ap = (AnnotatedProperty) annoList.get(0);// must by String name = ap.name(); if (StringUtils.isEmpty(name)) { name = info.getBeanPropertyName(); } info.setName(name); if (isGet) { info.setGetter(method); info.setType(method.getReturnType()); String setterName = "set" + propertySuffixe; Method setter = null; try { setter = cls.getMethod(setterName, method.getReturnType()); } catch (NoSuchMethodException | SecurityException e) { String msg = "Could not find setter method:[{}({})] in class[{}] for annotated getter:[{}]"; logger.warn(msg, new Object[] { setterName, method.getReturnType().getName(), cls.getName(), method.getName() }); } info.setSetter(setter); } if (isSet) { info.setSetter(method); info.setType(method.getParameterTypes()[0]); String getterName = "get" + propertySuffixe; Method getter = null; try { getter = cls.getMethod(getterName); } catch (NoSuchMethodException | SecurityException e) { String msg = "Could not find getter method:[{}:{}] in class[{}] for annotated setter:[{}]"; logger.warn(msg, new Object[] { getterName, method.getReturnType().getName(), cls.getName(), method.getName() }); } info.setGetter(getter); } infoList.add(info); beanPropertyNameSet.add(info.getBeanPropertyName()); } List<Field> list = new ArrayList<>(ClassUtil.retrieveAllFieldsIncludeAllSuperClasses(cls)); Iterator<Field> it = list.iterator(); while (it.hasNext()) { Field f = it.next(); List<Annotation> annoList = ConvertableAnnotationRetriever.retrieveAnnotationHierarchyList(AnnotatedProperty.class, f.getAnnotations()); if (CollectionUtils.isNotEmpty(annoList)) { AnnotatedProperty ap = (AnnotatedProperty) annoList.get(0);// must by String beanPropertyName = f.getName(); if (beanPropertyNameSet.contains(beanPropertyName)) { continue; } String name = ap.name(); if (StringUtils.isEmpty(name)) { name = f.getName(); } AnnotatedPropertyInfo info = new AnnotatedPropertyInfo(); info.setAnnotations(annoList); info.setBeanPropertyName(beanPropertyName); info.setName(name); info.setField(f); info.setGetter(null); info.setSetter(null); info.setType(f.getType()); infoList.add(info); } } map = new AnnotatedPropertyInfoMap(infoList); if (Configuration.getConfiguration().isCacheEnable()) { propertiesMapCache.put(cacheKey, map); } } return map; } @SuppressWarnings("rawtypes") public static List<AnnotatedPropertyInfo> retrieveProperties(Class cls) { AnnotatedPropertyInfoMap map = retrievePropertiesMap(cls); return map.list; } @SuppressWarnings("rawtypes") public static List<AnnotatedPropertyInfo> retrievePropertyByName(Class cls, final String name) { AnnotatedPropertyInfoMap map = retrievePropertiesMap(cls); return map.nameMap.get(name); } @SuppressWarnings("rawtypes") public static List<AnnotatedPropertyInfo> retrievePropertyByBeanPropertyName(Class cls, final String name) { AnnotatedPropertyInfoMap map = retrievePropertiesMap(cls); return map.beanNameMap.get(name); } public static void assignValueByName(Object instance, String name, Object value) throws IllegalAccessException, IllegalArgumentException, InvocationTargetException { List<AnnotatedPropertyInfo> list = retrievePropertyByName(instance.getClass(), name); assignValue(list, instance, value); } public static void assignValueByBeanPropertyName(Object instance, String name, Object value) throws IllegalAccessException, IllegalArgumentException, InvocationTargetException { List<AnnotatedPropertyInfo> list = retrievePropertyByBeanPropertyName(instance.getClass(), name); assignValue(list, instance, value); } public static void assignValue(List<AnnotatedPropertyInfo> list, Object instance, Object value) throws IllegalAccessException, IllegalArgumentException, InvocationTargetException { for (AnnotatedPropertyInfo p : list) { p.assignValue(instance, value); } } }
astamuse/asta4d
162
Java
org.eclipse.core.resources.prefs
text/plain
3,333,883,807,959,497,000
/* * Copyright 2014 astamuse company,Ltd. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ package com.astamuse.asta4d.util.annotation; import java.lang.annotation.ElementType; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target; @Retention(RetentionPolicy.RUNTIME) @Target(ElementType.ANNOTATION_TYPE) public @interface ConvertableAnnotation { public Class<? extends AnnotationConvertor<?, ?>> value(); }
astamuse/asta4d
162
Java
org.eclipse.core.resources.prefs
text/plain
3,312,279,690,762,724,400
/* * Copyright 2014 astamuse company,Ltd. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ package com.astamuse.asta4d.util.annotation; import java.lang.annotation.Annotation; public interface AnnotationConvertor<S extends Annotation, T extends Annotation> { public T convert(S originalAnnotation); }
astamuse/asta4d
162
Java
org.eclipse.core.resources.prefs
text/plain
-6,559,399,805,697,832,000
/* * Copyright 2014 astamuse company,Ltd. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ package com.astamuse.asta4d.util.annotation; import java.lang.annotation.Annotation; import java.util.Collections; import java.util.LinkedList; import java.util.List; public class ConvertableAnnotationRetriever { @SuppressWarnings({ "unchecked", "rawtypes" }) public static final <T extends Annotation> T retrieveAnnotation(Class<T> targetAnnotation, Annotation... annotations) { try { String targetName = targetAnnotation.getName(); T found = null; ConvertableAnnotation ca; for (Annotation annotation : annotations) { while (true) { if (annotation.annotationType().getName().equals(targetName)) { found = (T) annotation; break; } ca = annotation.annotationType().getAnnotation(ConvertableAnnotation.class); if (ca == null) { break; } else { AnnotationConvertor ac = ca.value().newInstance(); annotation = ac.convert(annotation); } } if (found != null) { break; } } return found; } catch (InstantiationException | IllegalAccessException e) { throw new RuntimeException(e); } } /** * * * @param targetAnnotation * @param annotations * @return The first element in the returned list is the target annotation specified by parameter and the next is which the previous one * be converted from */ @SuppressWarnings({ "unchecked", "rawtypes" }) public static final List<Annotation> retrieveAnnotationHierarchyList(Class<? extends Annotation> targetAnnotation, Annotation... annotations) { try { String targetName = targetAnnotation.getName(); ConvertableAnnotation ca; List<Annotation> list = new LinkedList<>(); for (Annotation annotation : annotations) { list.clear(); while (true) { list.add(annotation); if (annotation.annotationType().getName().equals(targetName)) { // found break; } ca = annotation.annotationType().getAnnotation(ConvertableAnnotation.class); if (ca == null) { // not found list.clear(); break; } else { AnnotationConvertor ac = ca.value().newInstance(); annotation = ac.convert(annotation); } }// end of while if (!list.isEmpty()) { break; } } Collections.reverse(list); return list; } catch (InstantiationException | IllegalAccessException e) { throw new RuntimeException(e); } } }
astamuse/asta4d
162
Java
org.eclipse.core.resources.prefs
text/plain
-8,823,217,214,265,632,000
/* * Copyright 2014 astamuse company,Ltd. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ package com.astamuse.asta4d.util.annotation; import java.lang.annotation.Annotation; import java.lang.reflect.Field; import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; import java.util.List; import org.apache.commons.lang3.reflect.FieldUtils; public class AnnotatedPropertyInfo { private String name; private String beanPropertyName; private Field field; private Method getter; private Method setter; private Class type; private List<Annotation> annotationList; public String getName() { return name; } public void setName(String name) { this.name = name; } public String getBeanPropertyName() { return beanPropertyName; } public void setBeanPropertyName(String beanPropertyName) { this.beanPropertyName = beanPropertyName; } public Field getField() { return field; } public void setField(Field field) { this.field = field; } public Method getGetter() { return getter; } public void setGetter(Method getter) { this.getter = getter; } public Method getSetter() { return setter; } public void setSetter(Method setter) { this.setter = setter; } @SuppressWarnings("rawtypes") public Class getType() { return type; } @SuppressWarnings("rawtypes") public void setType(Class type) { this.type = type; } @SuppressWarnings("unchecked") public <A extends Annotation> A getAnnotation(Class<A> annotationCls) { for (Annotation anno : annotationList) { if (annotationCls.isAssignableFrom(anno.getClass())) { return (A) anno; } } return null; } public void setAnnotations(List<Annotation> annotationList) { this.annotationList = annotationList; } public void assignValue(Object instance, Object value) throws IllegalAccessException, IllegalArgumentException, InvocationTargetException { if (this.field == null) { setter.invoke(instance, value); } else { FieldUtils.writeField(field, instance, value, true); } } public Object retrieveValue(Object instance) throws IllegalAccessException, IllegalArgumentException, InvocationTargetException { if (this.field == null) { return getter.invoke(instance); } else { return FieldUtils.readField(field, instance, true); } } @Override public int hashCode() { return (name == null) ? 0 : name.hashCode(); } @Override public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (getClass() != obj.getClass()) return false; AnnotatedPropertyInfo other = (AnnotatedPropertyInfo) obj; if (annotationList == null) { if (other.annotationList != null) return false; } else if (!annotationList.equals(other.annotationList)) return false; if (field == null) { if (other.field != null) return false; } else if (!field.equals(other.field)) return false; if (getter == null) { if (other.getter != null) return false; } else if (!getter.equals(other.getter)) return false; if (name == null) { if (other.name != null) return false; } else if (!name.equals(other.name)) return false; if (setter == null) { if (other.setter != null) return false; } else if (!setter.equals(other.setter)) return false; if (type == null) { if (other.type != null) return false; } else if (!type.equals(other.type)) return false; return true; } @Override public String toString() { return "AnnotatedPropertyInfo [name=" + name + "]"; } }
astamuse/asta4d
162
Java
org.eclipse.core.resources.prefs
text/plain
-878,013,568,378,929,900
/* * Copyright 2014 astamuse company,Ltd. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ package com.astamuse.asta4d.util.annotation; public @interface AnnotatedProperty { String name() default ""; }
astamuse/asta4d
162
Java
org.eclipse.core.resources.prefs
text/plain
-3,231,973,383,591,208,400
/* * Copyright 2014 astamuse company,Ltd. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ package com.astamuse.asta4d.util.concurrent; import java.util.concurrent.ExecutorService; import com.astamuse.asta4d.Configuration; public class SnippetExecutorServiceUtil { private final static ExecutorService snippetExecutorService; static { Configuration conf = Configuration.getConfiguration(); snippetExecutorService = conf.getSnippetExecutorFactory().createExecutorService(); } public final static ExecutorService getExecutorService() { return snippetExecutorService; } }
astamuse/asta4d
162
Java
org.eclipse.core.resources.prefs
text/plain
-4,170,071,932,528,388,000
/* * Copyright 2012 astamuse company,Ltd. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ package com.astamuse.asta4d.util.concurrent; import java.util.concurrent.ExecutorService; public interface ExecutorServiceFactory { public ExecutorService createExecutorService(); }
astamuse/asta4d
162
Java
org.eclipse.core.resources.prefs
text/plain
-6,630,156,623,624,594,000
/* * Copyright 2012 astamuse company,Ltd. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ package com.astamuse.asta4d.util.concurrent; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import java.util.concurrent.ThreadFactory; import java.util.concurrent.atomic.AtomicInteger; import com.astamuse.asta4d.Configuration; public class DefaultExecutorServiceFactory implements ExecutorServiceFactory { private final static AtomicInteger instanceCounter = new AtomicInteger(); private AtomicInteger counter = new AtomicInteger(); private String threadName; private int poolSize; public DefaultExecutorServiceFactory() { this(200); } public DefaultExecutorServiceFactory(int poolSize) { this("asta4d", poolSize); } public DefaultExecutorServiceFactory(String threadName, int poolSize) { this.threadName = threadName; this.poolSize = poolSize; } public String getThreadName() { return threadName; } public void setThreadName(String threadName) { this.threadName = threadName; } public int getPoolSize() { return poolSize; } public void setPoolSize(int poolSize) { this.poolSize = poolSize; } @Override public ExecutorService createExecutorService() { final int instanceId = instanceCounter.incrementAndGet(); ExecutorService es = Executors.newFixedThreadPool(poolSize, new ThreadFactory() { @Override public Thread newThread(Runnable r) { String name = threadName + "-" + instanceId + "-t-" + counter.incrementAndGet(); return new Thread(r, name); } }); Configuration.getConfiguration().addShutdownHookers(() -> { es.shutdown(); }); return es; } }
astamuse/asta4d
162
Java
org.eclipse.core.resources.prefs
text/plain
4,417,526,226,879,618,000