signature:
public class EMail { /** * Send an email */
public static Future < Boolean > send ( Email email ) { } }

implementation: try { email = buildMessage ( email ) ; if ( GojaConfig . getProperty ( "mail.smtp" , StringPool . EMPTY ) . equals ( "mock" ) && GojaConfig . getApplicationMode ( ) . isDev ( ) ) { Mock . send ( email ) ; return new Future < Boolean > ( ) { @ Override public boolean cancel ( boolean mayInterruptIfRunning ) { return false ; } @ Override public boolean isCancelled ( ) { return false ; } @ Override public boolean isDone ( ) { return true ; } @ Override public Boolean get ( ) throws InterruptedException , ExecutionException { return true ; } @ Override public Boolean get ( long timeout , final TimeUnit unit ) throws InterruptedException , ExecutionException , TimeoutException { return true ; } } ; } email . setMailSession ( getSession ( ) ) ; return sendMessage ( email ) ; } catch ( EmailException ex ) { throw new MailException ( "Cannot send email" , ex ) ; }


signature:
public class EMail { /** * Send a JavaMail message
 * @ param msg An Email message */
public static Future < Boolean > sendMessage ( final Email msg ) { } }

implementation: if ( asynchronousSend ) { return executor . submit ( new Callable < Boolean > ( ) { public Boolean call ( ) { try { msg . setSentDate ( new Date ( ) ) ; msg . send ( ) ; return true ; } catch ( Throwable e ) { MailException me = new MailException ( "Error while sending email" , e ) ; logger . error ( "The email has not been sent" , me ) ; return false ; } } } ) ; } else { final StringBuffer result = new StringBuffer ( ) ; try { msg . setSentDate ( new Date ( ) ) ; msg . send ( ) ; } catch ( Throwable e ) { MailException me = new MailException ( "Error while sending email" , e ) ; logger . error ( "The email has not been sent" , me ) ; result . append ( "oops" ) ; } return new Future < Boolean > ( ) { public boolean cancel ( boolean mayInterruptIfRunning ) { return false ; } public boolean isCancelled ( ) { return false ; } public boolean isDone ( ) { return true ; } public Boolean get ( ) throws InterruptedException , ExecutionException { return result . length ( ) == 0 ; } public Boolean get ( long timeout , TimeUnit unit ) throws InterruptedException , ExecutionException , TimeoutException { return result . length ( ) == 0 ; } } ; }


signature:
public class ApplicationRouter { /** * Specify a handler that will be called for all HTTP methods
 * @ param pattern The simple pattern
 * @ param handler The handler to call */
public void bind ( final RouteBinding handler ) { } }

implementation: final Method method = handler . getMethod ( ) ; logger . info ( "Using appId: {} and default version: {}" , appAcceptId , defaultVersion ) ; List < String > versions = handler . getVersions ( ) ; if ( versions == null || versions . isEmpty ( ) ) { versions = Collections . singletonList ( defaultVersion ) ; } for ( final String version : versions ) { final Set < Method > methods = new HashSet < > ( ) ; if ( method == Method . ANY ) { for ( final Method m : Method . values ( ) ) { methods . add ( m ) ; } } else { methods . add ( method ) ; } for ( final Method m : methods ) { final BindingKey key = new BindingKey ( m , version ) ; List < PatternRouteBinding > b = routeBindings . get ( key ) ; if ( b == null ) { b = new ArrayList < > ( ) ; routeBindings . put ( key , b ) ; } logger . info ( "ADD: {}, Pattern: {}, Route: {}\n" , key , handler . getPath ( ) , handler ) ; addPattern ( handler , b ) ; } }


signature:
public class ApplicationRouter { /** * Specify a filter handler that will be used to wrap route executions
 * @ param pattern The simple pattern
 * @ param handler The handler to call */
public void bind ( final FilterBinding handler ) { } }

implementation: final Method method = handler . getMethod ( ) ; final String path = handler . getPath ( ) ; logger . info ( "Using appId: {} and default version: {}" , appAcceptId , defaultVersion ) ; List < String > versions = handler . getVersions ( ) ; if ( versions == null || versions . isEmpty ( ) ) { versions = Collections . singletonList ( defaultVersion ) ; } for ( final String version : versions ) { final Set < Method > methods = new HashSet < > ( ) ; if ( method == Method . ANY ) { for ( final Method m : Method . values ( ) ) { methods . add ( m ) ; } } else { methods . add ( method ) ; } for ( final Method m : methods ) { final BindingKey key = new BindingKey ( m , version ) ; logger . info ( "ADD: {}, Pattern: {}, Filter: {}\n" , key , path , handler ) ; List < PatternFilterBinding > allFilterBindings = this . filterBindings . get ( key ) ; if ( allFilterBindings == null ) { allFilterBindings = new ArrayList < > ( ) ; this . filterBindings . put ( key , allFilterBindings ) ; } boolean found = false ; for ( final PatternFilterBinding binding : allFilterBindings ) { if ( binding . getPattern ( ) . pattern ( ) . equals ( handler . getPath ( ) ) ) { binding . addFilter ( handler ) ; found = true ; break ; } } if ( ! found ) { final PatternFilterBinding binding = new PatternFilterBinding ( handler . getPath ( ) , handler ) ; allFilterBindings . add ( binding ) ; } } }


signature:
public class Servlets { /** * 根据浏览器If - Modified - Since Header , 计算文件是否已被修改 . < p / > 如果无修改 , checkIfModify返回false , 设置304 not modify
 * status .
 * @ param lastModified 内容的最后修改时间 . */
public static boolean checkIfModifiedSince ( HttpServletRequest request , HttpServletResponse response , long lastModified ) { } }

implementation: long ifModifiedSince = request . getDateHeader ( HttpHeaders . IF_MODIFIED_SINCE ) ; if ( ( ifModifiedSince != - 1 ) && ( lastModified < ( ifModifiedSince + 1000 ) ) ) { response . setStatus ( HttpServletResponse . SC_NOT_MODIFIED ) ; return false ; } return true ;


signature:
public class Servlets { /** * 根据浏览器 If - None - Match Header , 计算Etag是否已无效 . < p / > 如果Etag有效 , checkIfNoneMatch返回false , 设置304 not
 * modify status .
 * @ param etag 内容的ETag . */
public static boolean checkIfNoneMatchEtag ( HttpServletRequest request , HttpServletResponse response , String etag ) { } }

implementation: String headerValue = request . getHeader ( HttpHeaders . IF_NONE_MATCH ) ; if ( headerValue != null ) { boolean conditionSatisfied = false ; if ( ! StringPool . ASTERISK . equals ( headerValue ) ) { StringTokenizer commaTokenizer = new StringTokenizer ( headerValue , StringPool . COMMA ) ; while ( ! conditionSatisfied && commaTokenizer . hasMoreTokens ( ) ) { String currentToken = commaTokenizer . nextToken ( ) ; if ( currentToken . trim ( ) . equals ( etag ) ) { conditionSatisfied = true ; } } } else { conditionSatisfied = true ; } if ( conditionSatisfied ) { response . setStatus ( HttpServletResponse . SC_NOT_MODIFIED ) ; response . setHeader ( HttpHeaders . ETAG , etag ) ; return false ; } } return true ;


signature:
public class Servlets { /** * 设置让浏览器弹出下载对话框的Header .
 * @ param fileName 下载后的文件名 . */
public static void setFileDownloadHeader ( HttpServletResponse response , String fileName ) { } }

implementation:
try { // 中文文件名支持
String encodedfileName = new String ( fileName . getBytes ( ) , "ISO8859-1" ) ; response . setHeader ( HttpHeaders . CONTENT_DISPOSITION , "attachment; filename=\"" + encodedfileName + StringPool . QUOTE ) ; } catch ( UnsupportedEncodingException ignored ) { }


signature:
public class Servlets { /** * 取得带相同前缀的Request Parameters , copy from spring WebUtils . < p / > 返回的结果的Parameter名已去除前缀 . */
public static Map < String , Object > getParametersStartingWith ( ServletRequest request , String prefix ) { } }

implementation:
Validate . notNull ( request , "Request must not be null" ) ; Enumeration paramNames = request . getParameterNames ( ) ; Map < String , Object > params = new TreeMap < String , Object > ( ) ; if ( prefix == null ) { prefix = "" ; } while ( ( paramNames != null ) && paramNames . hasMoreElements ( ) ) { String paramName = ( String ) paramNames . nextElement ( ) ; if ( "" . equals ( prefix ) || paramName . startsWith ( prefix ) ) { String unprefixed = paramName . substring ( prefix . length ( ) ) ; String [ ] values = request . getParameterValues ( paramName ) ; if ( ( values == null ) || ( values . length == 0 ) ) { // Do nothing , no values found at all .
} else if ( values . length > 1 ) { params . put ( unprefixed , values ) ; } else { params . put ( unprefixed , values [ 0 ] ) ; } } } return params ;


signature:
public class Servlets { /** * 组合Parameters生成Query String的Parameter部分 , 并在paramter name上加上prefix .
 * @ see # getParametersStartingWith */
public static String encodeParameterStringWithPrefix ( Map < String , Object > params , String prefix ) { } }

implementation: if ( ( params == null ) || ( params . size ( ) == 0 ) ) { return "" ; } if ( prefix == null ) { prefix = "" ; } StringBuilder queryStringBuilder = new StringBuilder ( ) ; Iterator < Map . Entry < String , Object > > it = params . entrySet ( ) . iterator ( ) ; while ( it . hasNext ( ) ) { Map . Entry < String , Object > entry = it . next ( ) ; queryStringBuilder . append ( prefix ) . append ( entry . getKey ( ) ) . append ( '=' ) . append ( entry . getValue ( ) ) ; if ( it . hasNext ( ) ) { queryStringBuilder . append ( '&' ) ; } } return queryStringBuilder . toString ( ) ;


signature:
public class Servlets { /** * 客户端对Http Basic验证的 Header进行编码 . */
public static String encodeHttpBasic ( String userName , String password ) { } }

implementation: String encode = userName + StringPool . COLON + password ; return "Basic " + EncodeKit . encodeBase64 ( encode . getBytes ( ) ) ;


signature:
public class HasAnyRolesTag { /** * Delimeter that separates role names in tag attribute */
@ Override protected boolean showTagBody ( String roleName ) { } }

implementation:
boolean hasAnyRole = false ; Subject subject = getSubject ( ) ; if ( subject != null ) { // Iterate through roles and check to see if the user has one of the roles
for ( String role : roleName . split ( StringPool . COMMA ) ) { if ( subject . hasRole ( role . trim ( ) ) ) { hasAnyRole = true ; break ; } } } return hasAnyRole ;


signature:
public class Freemarkers { /** * appConfig配置所有参数 重写freemarker中的 reader方法 , 读取该配置文件
 * @ return config */
private static Configuration getAppConfiguration ( ) { } }

implementation:
if ( appConfig == null ) { // 从freemarker 视图中获取所有配置
appConfig = ( Configuration ) FreeMarkerRender . getConfiguration ( ) . clone ( ) ; try { // 设置模板路径
appConfig . setDirectoryForTemplateLoading ( new File ( PathKit . getWebRootPath ( ) + Goja . viewPath ) ) ; appConfig . setObjectWrapper ( new BeansWrapperBuilder ( Configuration . VERSION_2_3_21 ) . build ( ) ) ; } catch ( IOException e ) { logger . error ( "The Freemarkers has error!" , e ) ; } } return appConfig ;


signature:
public class Freemarkers { /** * 渲染模版为字符串 , 并制定参数
 * @ param tpl 模版
 * @ param renderParams 参数信息
 * @ return 渲染后的字符串 */
public static String processString ( String tpl , Map < String , Object > renderParams ) { } }

implementation: if ( appConfig == null ) { getAppConfiguration ( ) ; } StringWriter result = new StringWriter ( ) ; try { Template template = appConfig . getTemplate ( tpl ) ; template . process ( renderParams , result ) ; } catch ( IOException e ) { throw new RenderException ( e ) ; } catch ( TemplateException e ) { throw new RenderException ( e ) ; } return result . toString ( ) ;


signature:
public class Freemarkers { /** * 将Freemakrer的字符串模版 , 渲染参数为字符串形式的结果 。
 * @ param strTemplat 字符串模版 , 而不是文件模版
 * @ param renderParams 渲染参数
 * @ return 字符串形式的渲染结果 */
public static String renderStrTemplate ( String strTemplat , Map < String , Object > renderParams ) { } }

implementation: stringLoader . putTemplate ( UPDATE_RESPONSE_TEMPLATE , strTemplat ) ; stringConfig . setTemplateLoader ( stringLoader ) ; Writer out = new StringWriter ( 2048 ) ; try { Template tpl = stringConfig . getTemplate ( UPDATE_RESPONSE_TEMPLATE , StringPool . UTF_8 ) ; tpl . process ( renderParams , out ) ; } catch ( IOException e ) { Logger . error ( "Get update response template occurs error." , e ) ; } catch ( TemplateException e ) { Logger . error ( "Process template occurs error.template content is:\n {}" , e , strTemplat ) ; throw new IllegalArgumentException ( "Error update response template." , e ) ; } return out . toString ( ) ;


signature:
public class Freemarkers { /** * 生成HTML
 * @ param tlDirectory tl模板目录
 * @ param tlName ftl模板
 * @ param paramMap 参数map
 * @ param htmlPath 生成HTML存放路径 */
public static void makeHtml ( String tlDirectory , String tlName , Map < String , Object > paramMap , String htmlPath ) { } }

implementation:
FileOutputStream fileOutputStream = null ; OutputStreamWriter outputStreamWriter = null ; try { Configuration configuration = new Configuration ( Configuration . VERSION_2_3_22 ) ; File file = new File ( tlDirectory ) ; // . ftl模板目录
configuration . setDirectoryForTemplateLoading ( file ) ; configuration . setObjectWrapper ( new DefaultObjectWrapper ( Configuration . VERSION_2_3_22 ) ) ; Template template = configuration . getTemplate ( tlName , StringPool . UTF_8 ) ; File file2 = new File ( htmlPath ) ; // 生成html目录
fileOutputStream = new FileOutputStream ( file2 ) ; outputStreamWriter = new OutputStreamWriter ( fileOutputStream , StringPool . UTF_8 ) ; BufferedWriter bufferedWriter = new BufferedWriter ( outputStreamWriter ) ; template . process ( paramMap , bufferedWriter ) ; bufferedWriter . flush ( ) ; outputStreamWriter . close ( ) ; fileOutputStream . close ( ) ; } catch ( IOException e ) { e . printStackTrace ( ) ; } catch ( TemplateException e ) { e . printStackTrace ( ) ; } finally { if ( null != fileOutputStream ) { try { fileOutputStream . close ( ) ; } catch ( IOException e ) { e . printStackTrace ( ) ; } } if ( null != outputStreamWriter ) { try { outputStreamWriter . close ( ) ; } catch ( IOException e ) { e . printStackTrace ( ) ; } } }


signature:
public class DataKit { /** * Converts packing Long Int
 * @ param l the object representation
 * @ return the primitive representation */
public static int getInt ( Long l ) { } }

implementation: return ( l == null || l > Integer . MAX_VALUE ) ? 0 : l . intValue ( ) ;


signature:
public class Strs { /** * Extract the filename from the given path ,
 * e . g . " mypath / myfile . txt " - > " myfile . txt " .
 * @ param path the file path ( may be { @ code null } )
 * @ return the extracted filename , or { @ code null } if none */
public static String getFilename ( String path ) { } }

implementation: if ( path == null ) { return null ; } int separatorIndex = path . lastIndexOf ( StringPool . SLASH ) ; return ( separatorIndex != - 1 ? path . substring ( separatorIndex + 1 ) : path ) ;


signature:
public class Strs { /** * Extract the filename extension from the given path ,
 * e . g . " mypath / myfile . txt " - > " txt " .
 * @ param path the file path ( may be { @ code null } )
 * @ return the extracted filename extension , or { @ code null } if none */
public static String getFilenameExtension ( String path ) { } }

implementation: if ( path == null ) { return null ; } int extIndex = path . lastIndexOf ( EXTENSION_SEPARATOR ) ; if ( extIndex == - 1 ) { return null ; } int folderIndex = path . lastIndexOf ( StringPool . SLASH ) ; if ( folderIndex > extIndex ) { return null ; } return path . substring ( extIndex + 1 ) ;


signature:
public class Strs { /** * Apply the given relative path to the given path ,
 * assuming standard Java folder separation ( i . e . " / " separators ) .
 * @ param path the path to start from ( usually a full file path )
 * @ param relativePath the relative path to apply
 * ( relative to the full file path above )
 * @ return the full file path that results from applying the relative path */
public static String applyRelativePath ( String path , String relativePath ) { } }

implementation: int separatorIndex = path . lastIndexOf ( StringPool . SLASH ) ; if ( separatorIndex != - 1 ) { String newPath = path . substring ( 0 , separatorIndex ) ; if ( ! relativePath . startsWith ( StringPool . SLASH ) ) { newPath += StringPool . SLASH ; } return newPath + relativePath ; } else { return relativePath ; }


signature:
public class Strs { /** * Normalize the path by suppressing sequences like " path / . . " and
 * inner simple dots .
 * < p > The result is convenient for path comparison . For other uses ,
 * notice that Windows separators ( " \ " ) are replaced by simple slashes .
 * @ param path the original path
 * @ return the normalized path */
public static String cleanPath ( String path ) { } }

implementation:
if ( path == null ) { return null ; } String pathToUse = replace ( path , StringPool . BACK_SLASH , StringPool . SLASH ) ; // Strip prefix from path to analyze , to not treat it as part of the
// first path element . This is necessary to correctly parse paths like
// " file : core / . . / core / io / Resource . class " , where the " . . " should just
// strip the first " core " directory while keeping the " file : " prefix .
int prefixIndex = pathToUse . indexOf ( ":" ) ; String prefix = "" ; if ( prefixIndex != - 1 ) { prefix = pathToUse . substring ( 0 , prefixIndex + 1 ) ; if ( prefix . contains ( "/" ) ) { prefix = "" ; } else { pathToUse = pathToUse . substring ( prefixIndex + 1 ) ; } } if ( pathToUse . startsWith ( StringPool . SLASH ) ) { prefix = prefix + StringPool . SLASH ; pathToUse = pathToUse . substring ( 1 ) ; } String [ ] pathArray = delimitedListToStringArray ( pathToUse , StringPool . SLASH ) ; List < String > pathElements = new LinkedList < String > ( ) ; int tops = 0 ; for ( int i = pathArray . length - 1 ; i >= 0 ; i -- ) { String element = pathArray [ i ] ; // if ( StringPool . DOT . equals ( element ) ) {
// Points to current directory - drop it .
/* else */
if ( StringPool . DOTDOT . equals ( element ) ) { // Registering top path found .
tops ++ ; } else { if ( tops > 0 ) { // Merging path element with element corresponding to top path .
tops -- ; } else { // Normal path element found .
pathElements . add ( 0 , element ) ; } } } // Remaining top paths need to be retained .
for ( int i = 0 ; i < tops ; i ++ ) { pathElements . add ( 0 , StringPool . DOTDOT ) ; } return prefix + collectionToDelimitedString ( pathElements , StringPool . SLASH ) ;


signature:
public class Strs { /** * Trim the elements of the given String array ,
 * calling { @ code String . trim ( ) } on each of them .
 * @ param array the original String array
 * @ return the resulting array ( of the same size ) with trimmed elements */
public static String [ ] trimArrayElements ( String [ ] array ) { } }

implementation: if ( ObjectKit . isEmpty ( array ) ) { return new String [ 0 ] ; } String [ ] result = new String [ array . length ] ; for ( int i = 0 ; i < array . length ; i ++ ) { String element = array [ i ] ; result [ i ] = ( element != null ? element . trim ( ) : null ) ; } return result ;


signature:
public class Strs { /** * Remove duplicate Strings from the given array .
 * Also sorts the array , as it uses a TreeSet .
 * @ param array the String array
 * @ return an array without duplicates , in natural sort order */
public static String [ ] removeDuplicateStrings ( String [ ] array ) { } }

implementation: if ( ObjectKit . isEmpty ( array ) ) { return array ; } Set < String > set = new TreeSet < String > ( ) ; for ( String element : array ) { set . add ( element ) ; } return toStringArray ( set ) ;


signature:
public class Strs { /** * Take an array Strings and split each element based on the given delimiter .
 * A { @ code Properties } instance is then generated , with the left of the
 * delimiter providing the key , and the right of the delimiter providing the value .
 * < p > Will trim both the key and value before adding them to the
 * { @ code Properties } instance .
 * @ param array the array to process
 * @ param delimiter to split each element using ( typically the equals symbol )
 * @ param charsToDelete one or more characters to remove from each element
 * prior to attempting the split operation ( typically the quotation mark
 * symbol ) , or { @ code null } if no removal should occur
 * @ return a { @ code Properties } instance representing the array contents ,
 * or { @ code null } if the array to process was { @ code null } or empty */
public static Properties splitArrayElementsIntoProperties ( String [ ] array , String delimiter , String charsToDelete ) { } }

implementation: if ( ObjectKit . isEmpty ( array ) ) { return null ; } Properties result = new Properties ( ) ; for ( String element : array ) { if ( charsToDelete != null ) { element = deleteAny ( element , charsToDelete ) ; } String [ ] splittedElement = split ( element , delimiter ) ; if ( splittedElement == null ) { continue ; } result . setProperty ( splittedElement [ 0 ] . trim ( ) , splittedElement [ 1 ] . trim ( ) ) ; } return result ;


signature:
public class Strs { /** * Convenience method to return a Collection as a delimited ( e . g . CSV )
 * String . E . g . useful for { @ code toString ( ) } implementations .
 * @ param coll the Collection to display
 * @ param delim the delimiter to use ( probably a " , " )
 * @ param prefix the String to start each element with
 * @ param suffix the String to end each element with
 * @ return the delimited String */
public static String collectionToDelimitedString ( Collection < ? > coll , String delim , String prefix , String suffix ) { } }

implementation: if ( CollectionKit . isEmpty ( coll ) ) { return "" ; } StringBuilder sb = new StringBuilder ( ) ; Iterator < ? > it = coll . iterator ( ) ; while ( it . hasNext ( ) ) { sb . append ( prefix ) . append ( it . next ( ) ) . append ( suffix ) ; if ( it . hasNext ( ) ) { sb . append ( delim ) ; } } return sb . toString ( ) ;


signature:
public class Strs { /** * 将一个整数转换成最小长度为某一固定数值的十进制形式字符串
 * @ param d 整数
 * @ param width 宽度
 * @ return 新字符串 */
public static String fillDigit ( int d , int width ) { } }

implementation: return Strs . alignRight ( String . valueOf ( d ) , width , '0' ) ;


signature:
public class Strs { /** * 将一个整数转换成最小长度为某一固定数值的十六进制形式字符串
 * @ param d 整数
 * @ param width 宽度
 * @ return 新字符串 */
public static String fillHex ( int d , int width ) { } }

implementation: return Strs . alignRight ( Integer . toHexString ( d ) , width , '0' ) ;


signature:
public class Strs { /** * 将一个整数转换成最小长度为某一固定数值的二进制形式字符串
 * @ param d 整数
 * @ param width 宽度
 * @ return 新字符串 */
public static String fillBinary ( int d , int width ) { } }

implementation: return Strs . alignRight ( Integer . toBinaryString ( d ) , width , '0' ) ;


signature:
public class Strs { /** * 将一个整数转换成固定长度的十进制形式字符串
 * @ param d 整数
 * @ param width 宽度
 * @ return 新字符串 */
public static String toDigit ( int d , int width ) { } }

implementation: return Strs . cutRight ( String . valueOf ( d ) , width , '0' ) ;


signature:
public class Strs { /** * 将一个整数转换成固定长度的十六进制形式字符串
 * @ param d 整数
 * @ param width 宽度
 * @ return 新字符串 */
public static String toHex ( int d , int width ) { } }

implementation: return Strs . cutRight ( Integer . toHexString ( d ) , width , '0' ) ;


signature:
public class Strs { /** * 将一个整数转换成固定长度的二进制形式字符串
 * @ param d 整数
 * @ param width 宽度
 * @ return 新字符串 */
public static String toBinary ( int d , int width ) { } }

implementation: return Strs . cutRight ( Integer . toBinaryString ( d ) , width , '0' ) ;


signature:
public class Strs { /** * 保证字符串为一固定长度 。 超过长度 , 切除右侧字符 , 否则右侧填补字符 。
 * @ param s 字符串
 * @ param width 长度
 * @ param c 补字符
 * @ return 修饰后的字符串 */
public static String cutLeft ( String s , int width , char c ) { } }

implementation: if ( null == s ) return null ; int len = s . length ( ) ; if ( len == width ) return s ; if ( len < width ) return s + Strs . dup ( c , width - len ) ; return s . substring ( 0 , width ) ;


signature:
public class Strs { /** * 如果str中第一个字符和 c一致 , 则删除 , 否则返回 str
 * 比如 :
 * < ul >
 * < li > removeFirst ( " 12345 " , 1 ) = > " 2345"
 * < li > removeFirst ( " ABC " , ' B ' ) = > " ABC "
 * < li > removeFirst ( " A " , ' B ' ) = > " A "
 * < li > removeFirst ( " A " , ' A ' ) = > " "
 * < / ul >
 * @ param str 字符串
 * @ param c 第一个个要被截取的字符
 * @ return 新字符串 */
public static String removeFirst ( String str , char c ) { } }

implementation: return ( Strs . isEmpty ( str ) || c != str . charAt ( 0 ) ) ? str : str . substring ( 1 ) ;


signature:
public class Strs { /** * 判断一个字符串数组是否包括某一字符串
 * @ param ss 字符串数组
 * @ param s 字符串
 * @ return 是否包含 */
public static boolean isin ( String [ ] ss , String s ) { } }

implementation: if ( null == ss || ss . length == 0 || Strs . isBlank ( s ) ) return false ; for ( String w : ss ) if ( s . equals ( w ) ) return true ; return false ;


signature:
public class Strs { /** * 将一个字符串出现的HMTL元素进行转义 , 比如
 * < pre >
 * escapeHtml ( " & lt ; script & gt ; alert ( " hello world " ) ; & lt ; / script & gt ; " ) = > " & amp ; lt ; script & amp ; gt ; alert ( & amp ; quot ; hello world & amp ; quot ; ) ; & amp ; lt ; / script & amp ; gt ; "
 * < / pre >
 * 转义字符对应如下
 * < ul >
 * < li > & = > & amp ; amp ;
 * < li > < = > & amp ; lt ;
 * < li > > = > & amp ; gt ;
 * < li > ' = > & amp ; # x27;
 * < li > " = > & amp ; quot ;
 * < / ul >
 * @ param cs 字符串
 * @ return 转换后字符串 */
public static String escapeHtml ( CharSequence cs ) { } }

implementation: if ( null == cs ) return null ; char [ ] cas = cs . toString ( ) . toCharArray ( ) ; StringBuilder sb = new StringBuilder ( ) ; for ( char c : cas ) { switch ( c ) { case '&' : sb . append ( "&" ) ; break ; case '<' : sb . append ( "<" ) ; break ; case '>' : sb . append ( ">" ) ; break ; case '\'' : sb . append ( "'" ) ; break ; case '"' : sb . append ( """ ) ; break ; default : sb . append ( c ) ; } } return sb . toString ( ) ;


signature:
public class Strs { /** * 将一个字节数变成人类容易识别的显示字符串 , 比如 1.5M 等
 * @ param size 字节数
 * @ param SZU 千的单位 , 可能为 1024 或者 1000
 * @ return 人类容易阅读的字符串 */
private static String _formatSizeForRead ( long size , double SZU ) { } }

implementation: if ( size < SZU ) { return String . format ( "%d bytes" , size ) ; } double n = ( double ) size / SZU ; if ( n < SZU ) { return String . format ( "%5.2f KB" , n ) ; } n = n / SZU ; if ( n < SZU ) { return String . format ( "%5.2f MB" , n ) ; } n = n / SZU ; return String . format ( "%5.2f GB" , n ) ;


signature:
public class Strs { /** * Stitching LIKE SQL percent .
 * @ param value value
 * @ return SQL LIKE expression . */
public static String like ( String value ) { } }

implementation: return StringPool . PERCENT + Strings . nullToEmpty ( value ) + StringPool . PERCENT ;


signature:
public class PeriodicService { /** * Run from the web interface .
 * @ throws Exception */
public void doRun ( ) throws Exception { } }

implementation: if ( inProgress . compareAndSet ( false , true ) ) { try { run ( ) ; } finally { inProgress . set ( false ) ; } } else { throw new IllegalStateException ( "Another run is already in progress" ) ; }


signature:
public class MultiState { /** * 该方法调用无效果 */
@ Override public void putInfo ( String name , String val ) { } }

implementation: this . infoMap . put ( name , val ) ;


signature:
public class SecurityKit { /** * Check the user ' s password , and execute the login request
 * @ param user user .
 * @ param password password .
 * @ param remember has remember .
 * @ param request request .
 * @ param response http response .
 * @ param < T > User type .
 * @ return True login Success . */
public static < T extends Model > boolean login ( T user , String password , boolean remember , HttpServletRequest request , HttpServletResponse response ) { } }

implementation: boolean matcher = SecurityKit . checkPassword ( user . getStr ( "salt" ) , user . getStr ( "password" ) , password ) ; if ( matcher ) { SecurityKit . setLoginMember ( request , response , user , remember ) ; } return matcher ;


signature:
public class SecurityKit { /** * logout
 * @ param req http request
 * @ param response http response */
public static < T extends Model > void logout ( HttpServletRequest req , HttpServletResponse response ) { } }

implementation:
CookieUser cookie_user = getUserFromCookie ( req ) ; Requests . deleteCookie ( req , response , COOKIE_LOGIN , true ) ; // 清理Cache
if ( cookie_user != null ) { CacheKit . remove ( LOGIN_CACHE_SESSION , LOGIN_CACHE_SESSION + cookie_user . getId ( ) ) ; } else { T user = getLoginUser ( req ) ; if ( user != null ) { CacheKit . remove ( LOGIN_CACHE_SESSION , LOGIN_CACHE_SESSION + user . getNumber ( StringPool . PK_COLUMN ) ) ; } } // 清除session
Enumeration < String > em = req . getSession ( ) . getAttributeNames ( ) ; while ( em . hasMoreElements ( ) ) { final String key = em . nextElement ( ) ; req . getSession ( ) . removeAttribute ( key ) ; } req . getSession ( ) . invalidate ( ) ;


signature:
public class SecurityKit { /** * Get user login information , if the session does not exist , then try to obtain from the
 * Cookie , if cookie exists , then decrypt obtain user information .
 * @ param req requeset
 * @ param response http response
 * @ param function call function .
 * @ return user login information . */
public static < T extends Model > T getLoginWithDb ( HttpServletRequest req , HttpServletResponse response , Function < Long , T > function ) { } }

implementation:
T loginUser = getLoginUser ( req ) ; if ( loginUser == null ) { // 从Cookie中解析出用户id
CookieUser cookie_user = getUserFromCookie ( req ) ; if ( cookie_user == null ) return null ; T user = CacheKit . get ( LOGIN_CACHE_SESSION , LOGIN_CACHE_SESSION + cookie_user . getId ( ) ) ; if ( user == null ) { user = function . apply ( cookie_user . getId ( ) ) ; CacheKit . put ( LOGIN_CACHE_SESSION , LOGIN_CACHE_SESSION + cookie_user . getId ( ) , user ) ; } // 用户密码和cookie中存储的密码一致
if ( user != null && StringUtils . equalsIgnoreCase ( user . getStr ( "password" ) , cookie_user . getPassword ( ) ) ) { setLoginMember ( req , response , user , true ) ; return user ; } else { return null ; } } else { return loginUser ; }


signature:
public class SecurityKit { /** * Obtain user information from the Session
 * @ param req request
 * @ return user infomation . */
public static < T extends Model > T getLoginUser ( HttpServletRequest req ) { } }

implementation: return ( T ) req . getSession ( ) . getAttribute ( LOGIN_SESSION_KEY ) ;


signature:
public class SecurityKit { /** * Sign settings
 * @ param request request .
 * @ param response response
 * @ param user The logged user .
 * @ param remember is remember . */
private static < T extends Model > void setLoginMember ( HttpServletRequest request , HttpServletResponse response , T user , boolean remember ) { } }

implementation: request . getSession ( ) . setAttribute ( LOGIN_SESSION_KEY , user ) ; request . getSession ( ) . setAttribute ( LOGIN_MEMBER_ID , user . getNumber ( StringPool . PK_COLUMN ) ) ; saveMemberInCookie ( user , remember , request , response ) ;


signature:
public class SecurityKit { /** * Check Password , salt , password , planpassword .
 * @ param salt salt
 * @ param password password .
 * @ param plainPassword plain password .
 * @ return true , in user . */
public static boolean checkPassword ( String salt , String password , String plainPassword ) { } }

implementation: byte [ ] saltHex = EncodeKit . decodeHex ( salt ) ; byte [ ] hashPassword = DigestsKit . sha1 ( plainPassword . getBytes ( ) , saltHex , EncodeKit . HASH_INTERATIONS ) ; return StringUtils . equals ( EncodeKit . encodeHex ( hashPassword ) , password ) ;


signature:
public class SecurityKit { /** * Store user information in a cookie logged in .
 * @ param user The user has logged on .
 * @ param save has save .
 * @ param request request
 * @ param response http response */
public static < T extends Model > void saveMemberInCookie ( T user , boolean save , HttpServletRequest request , HttpServletResponse response ) { } }

implementation: String new_value = getLoginKey ( user , Requests . remoteIP ( request ) , request . getHeader ( "user-agent" ) ) ; int max_age = save ? MAX_AGE : - 1 ; Requests . deleteCookie ( request , response , COOKIE_LOGIN , true ) ; Requests . setCookie ( request , response , COOKIE_LOGIN , new_value , max_age , true ) ;


signature:
public class SecurityKit { /** * Generating system user login ID string .
 * @ param user The user has logged on .
 * @ param ip The login ip .
 * @ param user _ agent http agent .
 * @ return User login identification string */
private static < T extends Model > String getLoginKey ( T user , String ip , String user_agent ) { } }

implementation: return encrypt ( String . valueOf ( user . getNumber ( StringPool . PK_COLUMN ) ) + '|' + user . getStr ( "password" ) + '|' + ip + '|' + ( ( user_agent == null ) ? 0 : user_agent . hashCode ( ) ) + '|' + System . currentTimeMillis ( ) ) ;


signature:
public class SecurityKit { /** * 从cookie中读取保存的用户信息
 * @ param req requeset 请求
 * @ return 用户信息 */
private static CookieUser getUserFromCookie ( HttpServletRequest req ) { } }

implementation: try { Cookie cookie = Requests . getCookie ( req , COOKIE_LOGIN ) ; if ( cookie != null && StringUtils . isNotBlank ( cookie . getValue ( ) ) ) { return userForCookie ( cookie . getValue ( ) , req ) ; } } catch ( Exception ignored ) { } return null ;


signature:
public class SecurityKit { /** * encrypt
 * @ param value encry string
 * @ return ciphertext . */
private static String encrypt ( String value ) { } }

implementation: byte [ ] data = encrypt ( value . getBytes ( ) , E_KEY ) ; try { return URLEncoder . encode ( new String ( Base64 . encodeBase64 ( data ) ) , StringPool . UTF_8 ) ; } catch ( UnsupportedEncodingException e ) { return null ; }


signature:
public class SecurityKit { /** * Obtain user information from the Cookie
 * @ param uuid ciphertext .
 * @ param request request .
 * @ return cookie user . */
private static CookieUser userForCookie ( String uuid , HttpServletRequest request ) { } }

implementation: if ( StringUtils . isBlank ( uuid ) ) { return null ; } String ck = decrypt ( uuid ) ; final String [ ] items = StringUtils . split ( ck , '|' ) ; if ( items . length == 5 ) { String ua = request . getHeader ( "user-agent" ) ; int ua_code = ( ua == null ) ? 0 : ua . hashCode ( ) ; int old_ua_code = Integer . parseInt ( items [ 3 ] ) ; if ( ua_code == old_ua_code ) { return new CookieUser ( NumberUtils . toLong ( items [ 0 ] , - 1L ) , items [ 1 ] , false ) ; } } return null ;


signature:
public class SecurityKit { /** * decrypt
 * @ param value ciphertext
 * @ return Plaintext . */
private static String decrypt ( String value ) { } }

implementation: try { value = URLDecoder . decode ( value , StringPool . UTF_8 ) ; if ( StringUtils . isBlank ( value ) ) return null ; byte [ ] data = Base64 . decodeBase64 ( value . getBytes ( ) ) ; return new String ( decrypt ( data , E_KEY ) ) ; } catch ( UnsupportedEncodingException excp ) { return null ; }


signature:
public class SecurityKit { /** * decrypt
 * @ param src ciphertext
 * @ param key Key .
 * @ return Plaintext
 * @ throws RuntimeException cuowu */
private static byte [ ] decrypt ( byte [ ] src , byte [ ] key ) throws RuntimeException { } }

implementation:
try { // DES算法要求有一个可信任的随机数源
SecureRandom sr = new SecureRandom ( ) ; // 从原始密匙数据创建一个DESKeySpec对象
DESKeySpec dks = new DESKeySpec ( key ) ; // 创建一个密匙工厂 , 然后用它把DESKeySpec对象转换成
// 一个SecretKey对象
SecretKeyFactory keyFactory = SecretKeyFactory . getInstance ( DES ) ; SecretKey securekey = keyFactory . generateSecret ( dks ) ; // Cipher对象实际完成解密操作
Cipher cipher = Cipher . getInstance ( DES ) ; // 用密匙初始化Cipher对象
cipher . init ( Cipher . DECRYPT_MODE , securekey , sr ) ; // 现在 , 获取数据并解密
// 正式执行解密操作
return cipher . doFinal ( src ) ; } catch ( Exception e ) { throw new RuntimeException ( e ) ; }


signature:
public class AjaxMessage { /** * 返回处理正常的消息内容
 * @ param message Toast
 * @ param data 消息数据
 * @ param < E > 数据泛型类型
 * @ return message content */
public static < E > AjaxMessage ok ( String message , E data ) { } }

implementation: return new AjaxMessage < E > ( data , message , MessageStatus . OK ) ;


signature:
public class AjaxMessage { /** * 返回没有数据的消息内容
 * @ param data 消息数据
 * @ param < E > 数据泛型类型
 * @ return message content */
public static < E > AjaxMessage nodata ( E data ) { } }

implementation: return new AjaxMessage < E > ( data , EMPTY , MessageStatus . NODATA ) ;


signature:
public class AjaxMessage { /** * 返回没有数据的消息内容
 * @ param data 消息数据
 * @ param < E > 数据泛型类型
 * @ return message content */
public static < E > AjaxMessage nodata ( String message , E data ) { } }

implementation: return new AjaxMessage < E > ( data , message , MessageStatus . NODATA ) ;


signature:
public class AjaxMessage { /** * 返回没有登录时消息内容
 * @ param data 消息数据
 * @ param < E > 数据泛型类型
 * @ return message content */
public static < E > AjaxMessage nologin ( E data ) { } }

implementation: return new AjaxMessage < E > ( data , EMPTY , MessageStatus . NOLOGIN ) ;


signature:
public class AjaxMessage { /** * 返回禁止访问消息内容
 * @ param data 消息数据
 * @ param < E > 数据泛型类型
 * @ return message content */
public static < E > AjaxMessage forbidden ( E data ) { } }

implementation: return new AjaxMessage < E > ( data , EMPTY , MessageStatus . FORBIDDEN ) ;


signature:
public class AjaxMessage { /** * 返回禁止访问消息内容
 * @ param data 消息数据
 * @ param < E > 数据泛型类型
 * @ return message content */
public static < E > AjaxMessage forbidden ( String message , E data ) { } }

implementation: return new AjaxMessage < E > ( data , message , MessageStatus . FORBIDDEN ) ;


signature:
public class AjaxMessage { /** * 返回处理错误的消息内容
 * @ param message Toast
 * @ param exception exception
 * @ return message content */
public static AjaxMessage error ( String message , Exception exception ) { } }

implementation: return error ( message , null , exception ) ;


signature:
public class AjaxMessage { /** * 返回处理错误的消息内容
 * @ param message Toast
 * @ param exception exception
 * @ param data 数据
 * @ return message content */
public static < E > AjaxMessage error ( String message , E data , Exception exception ) { } }

implementation: return new AjaxMessage < E > ( data , message , MessageStatus . ERROR , exception ) ;


signature:
public class AjaxMessage { /** * 返回处理失败的消息内容
 * @ param message Toast
 * @ param exception exception
 * @ return message content */
public static AjaxMessage failure ( String message , Exception exception ) { } }

implementation: return failure ( message , null , exception ) ;


signature:
public class AjaxMessage { /** * 返回处理失败的消息内容
 * @ param message Toast
 * @ param exception exception
 * @ param data 数据
 * @ return message content */
public static < E > AjaxMessage failure ( String message , E data , Exception exception ) { } }

implementation: return new AjaxMessage < E > ( data , message , MessageStatus . FAILURE , exception ) ;


signature:
public class KeyCodeKit { /** * 产品序列号前10位 + KEY前5位 + 5位随机数字和字符 ( 大小写 ) + 时间戳 MD5 加密
 * @ param productSerialNo 产品序列号
 * @ param codeKey 产品代码
 * @ return 授权码 */
public static String generateKeyCode ( String productSerialNo , String codeKey ) { } }

implementation: return digestPassword ( StringUtils . leftPad ( productSerialNo , 10 , StringPool . ZERO ) + StringUtils . leftPad ( codeKey , 5 , StringPool . ZERO ) + RandomStringUtils . randomAlphanumeric ( 5 ) + DateTime . now ( ) . getMillis ( ) ) ;


signature:
public class KeyCodeKit { /** * 加密
 * @ param password 需要加密的字符串 */
private static String digestPassword ( String password ) { } }

implementation: try { SecureRandom random = new SecureRandom ( ) ; byte [ ] salt = new byte [ EncodeKit . SALT_SIZE ] ; random . nextBytes ( salt ) ; MessageDigest md = MessageDigest . getInstance ( "MD5" ) ; md . update ( salt ) ; md . update ( password . getBytes ( ) ) ; byte [ ] digest = md . digest ( ) ; BASE64Encoder encoder = new BASE64Encoder ( ) ; return encoder . encode ( salt ) + encoder . encode ( digest ) ; } catch ( NoSuchAlgorithmException ne ) { System . err . println ( ne . toString ( ) ) ; return null ; } catch ( Exception e ) { System . err . println ( e . toString ( ) ) ; return null ; }


signature:
public class ShiroPlugin { /** * 启动插件 */
@ Override public boolean start ( ) { } }

implementation:
Set < String > excludedMethodName = buildExcludedMethodName ( ) ; ConcurrentMap < String , AuthzHandler > authzMaps = Maps . newConcurrentMap ( ) ; // 逐个访问所有注册的Controller , 解析Controller及action上的所有Shiro注解 。
// 并依据这些注解 , actionKey提前构建好权限检查处理器 。
final List < Routes . Route > routeItemList = routes . getRouteItemList ( ) ; for ( Routes . Route route : routeItemList ) { final Class < ? extends Controller > controllerClass = route . getControllerClass ( ) ; String controllerKey = route . getControllerKey ( ) ; // 获取Controller的所有Shiro注解 。
List < Annotation > controllerAnnotations = getAuthzAnnotations ( controllerClass ) ; // 逐个遍历方法 。
Method [ ] methods = controllerClass . getMethods ( ) ; for ( Method method : methods ) { // 排除掉Controller基类的所有方法 , 并且只关注没有参数的Action方法 。
if ( ! excludedMethodName . contains ( method . getName ( ) ) && method . getParameterTypes ( ) . length == 0 ) { // 若该方法上存在ClearShiro注解 , 则对该action不进行访问控制检查 。
if ( isClearShiroAnnotationPresent ( method ) ) { continue ; } // 获取方法的所有Shiro注解 。
List < Annotation > methodAnnotations = getAuthzAnnotations ( method ) ; // 依据Controller的注解和方法的注解来生成访问控制处理器 。
AuthzHandler authzHandler = createAuthzHandler ( controllerAnnotations , methodAnnotations ) ; // 生成访问控制处理器成功 。
if ( authzHandler != null ) { // 构建ActionKey , 参考ActionMapping中实现
String actionKey = createActionKey ( controllerClass , method , controllerKey ) ; // 添加映射
authzMaps . put ( actionKey , authzHandler ) ; } } } } // 注入到ShiroKit类中 。 ShiroKit类以单例模式运行 。
ShiroKit . init ( authzMaps ) ; return true ;


signature:
public class ShiroPlugin { /** * 从Controller方法中构建出需要排除的方法列表
 * @ return 排除的方法列表 */
private Set < String > buildExcludedMethodName ( ) { } }

implementation: Set < String > excludedMethodName = new HashSet < > ( ) ; Method [ ] methods = Controller . class . getMethods ( ) ; for ( Method m : methods ) { if ( m . getParameterTypes ( ) . length == 0 ) { excludedMethodName . add ( m . getName ( ) ) ; } } return excludedMethodName ;


signature:
public class ShiroPlugin { /** * 依据Controller的注解和方法的注解来生成访问控制处理器 。
 * @ param controllerAnnotations Controller的注解
 * @ param methodAnnotations 方法的注解
 * @ return 访问控制处理器 */
private AuthzHandler createAuthzHandler ( List < Annotation > controllerAnnotations , List < Annotation > methodAnnotations ) { } }

implementation:
// 没有注解
if ( controllerAnnotations . size ( ) == 0 && methodAnnotations . size ( ) == 0 ) { return null ; } // 至少有一个注解
List < AuthzHandler > authzHandlers = Lists . newArrayListWithCapacity ( 5 ) ; for ( int index = 0 ; index < 5 ; index ++ ) { authzHandlers . add ( null ) ; } // 逐个扫描注解 , 若是相应的注解则在相应的位置赋值 。
scanAnnotation ( authzHandlers , controllerAnnotations ) ; // 逐个扫描注解 , 若是相应的注解则在相应的位置赋值 。 函数的注解优先级高于Controller
scanAnnotation ( authzHandlers , methodAnnotations ) ; // 去除空值
List < AuthzHandler > finalAuthzHandlers = Lists . newArrayList ( ) ; for ( AuthzHandler a : authzHandlers ) { if ( a != null ) { finalAuthzHandlers . add ( a ) ; } } authzHandlers = null ; // 存在多个 , 则构建组合AuthzHandler
if ( finalAuthzHandlers . size ( ) > 1 ) { return new CompositeAuthzHandler ( finalAuthzHandlers ) ; } // 一个的话直接返回
return finalAuthzHandlers . get ( 0 ) ;


signature:
public class ShiroPlugin { /** * 逐个扫描注解 , 若是相应的注解则在相应的位置赋值 。 注解的处理是有顺序的 , 依次为RequiresRoles , RequiresPermissions ,
 * RequiresAuthentication , RequiresUser , RequiresGuest */
private void scanAnnotation ( List < AuthzHandler > authzArray , List < Annotation > annotations ) { } }

implementation: if ( null == annotations || 0 == annotations . size ( ) ) { return ; } for ( Annotation a : annotations ) { if ( a instanceof RequiresRoles ) { authzArray . set ( 0 , new RoleAuthzHandler ( a ) ) ; } else if ( a instanceof RequiresPermissions ) { authzArray . set ( 1 , new PermissionAuthzHandler ( a ) ) ; } else if ( a instanceof RequiresAuthentication ) { authzArray . set ( 2 , AuthenticatedAuthzHandler . me ( ) ) ; } else if ( a instanceof RequiresUser ) { authzArray . set ( 3 , UserAuthzHandler . me ( ) ) ; } else if ( a instanceof RequiresGuest ) { authzArray . set ( 4 , GuestAuthzHandler . me ( ) ) ; } }


signature:
public class ShiroPlugin { /** * 构建actionkey , 参考ActionMapping中的实现 。 */
private String createActionKey ( Class < ? extends Controller > controllerClass , Method method , String controllerKey ) { } }

implementation: String methodName = method . getName ( ) ; String actionKey ; ActionKey ak = method . getAnnotation ( ActionKey . class ) ; if ( ak != null ) { actionKey = ak . value ( ) . trim ( ) ; if ( Strings . isNullOrEmpty ( actionKey ) ) { throw new IllegalArgumentException ( controllerClass . getName ( ) + "." + methodName + "(): The argument of ActionKey can not be blank." ) ; } if ( ! actionKey . startsWith ( SLASH ) ) { actionKey = SLASH + actionKey ; } } else if ( methodName . equals ( "index" ) ) { actionKey = controllerKey ; } else { actionKey = controllerKey . equals ( SLASH ) ? SLASH + methodName : controllerKey + SLASH + methodName ; } return actionKey ;


signature:
public class ShiroPlugin { /** * 返回该方法的所有访问控制注解 */
private List < Annotation > getAuthzAnnotations ( Method method ) { } }

implementation: List < Annotation > annotations = Lists . newArrayList ( ) ; for ( Class < ? extends Annotation > annClass : AUTHZ_ANNOTATION_CLASSES ) { Annotation a = method . getAnnotation ( annClass ) ; if ( a != null ) { annotations . add ( a ) ; } } return annotations ;


signature:
public class ShiroPlugin { /** * 返回该Controller的所有访问控制注解 */
private List < Annotation > getAuthzAnnotations ( Class < ? extends Controller > targetClass ) { } }

implementation: List < Annotation > annotations = Lists . newArrayList ( ) ; for ( Class < ? extends Annotation > annClass : AUTHZ_ANNOTATION_CLASSES ) { Annotation a = targetClass . getAnnotation ( annClass ) ; if ( a != null ) { annotations . add ( a ) ; } } return annotations ;


signature:
public class ShiroPlugin { /** * 该方法上是否有ClearShiro注解 */
private boolean isClearShiroAnnotationPresent ( Method method ) { } }

implementation: Annotation a = method . getAnnotation ( ClearShiro . class ) ; return a != null ;


signature:
public class LoginActionKit { /** * 触发Shiro的登录请求 .
 * @ param username 用户名称
 * @ param password 登录密码
 * @ param rememberMe 是否记住我
 * @ throws AuthenticationException 授权失败的异常 */
public static void login ( String username , String password , boolean rememberMe ) throws AuthenticationException { } }

implementation: UsernamePasswordToken token = new UsernamePasswordToken ( username , password , rememberMe ) ; final Subject subject = SecurityUtils . getSubject ( ) ; subject . login ( token ) ;


signature:
public class LoginActionKit { /** * 触发Shiro的登录请求 . 默认的不记住我 .
 * @ param username 用户名称
 * @ param password 登录密码
 * @ throws AuthenticationException 授权失败的异常 */
public static void login ( String username , String password ) throws AuthenticationException { } }

implementation: login ( username , password , false ) ;


signature:
public class Forward { /** * Forwards HTTP request to the specified path .
 * @ param context HTTP request processing context . */
public void to ( WebContext context ) { } }

implementation: HttpServletRequest request = context . request ( ) ; HttpServletResponse response = context . response ( ) ; try { request . getRequestDispatcher ( path ) . forward ( request , response ) ; } catch ( ServletException e ) { throw new UncheckedException ( e ) ; } catch ( IOException e ) { throw new UncheckedException ( e ) ; }


signature:
public class FileRenamePolicyWrapper { /** * Add File Separator */
public String appendFileSeparator ( String path ) { } }

implementation:
if ( null == path ) { return File . separator ; } // add " / " prefix
if ( ! path . startsWith ( StringPool . SLASH ) && ! path . startsWith ( StringPool . BACK_SLASH ) ) { path = File . separator + path ; } // add " / " postfix
if ( ! path . endsWith ( StringPool . SLASH ) && ! path . endsWith ( StringPool . BACK_SLASH ) ) { path = path + File . separator ; } return path ;


signature:
public class Requests { /** * 获取客户端浏览器信息
 * @ return string */
public static String browserInfo ( HttpServletRequest req ) { } }

implementation: String browserInfo = "other" ; String ua = req . getHeader ( "User-Agent" ) . toLowerCase ( ) ; String s ; String version ; String msieP = "msie ([\\d.]+)" ; String ieheighP = "rv:([\\d.]+)" ; String firefoxP = "firefox\\/([\\d.]+)" ; String chromeP = "chrome\\/([\\d.]+)" ; String operaP = "opr.([\\d.]+)" ; String safariP = "version\\/([\\d.]+).*safari" ; Pattern pattern = Pattern . compile ( msieP ) ; Matcher mat = pattern . matcher ( ua ) ; if ( mat . find ( ) ) { s = mat . group ( ) ; if ( s != null ) { version = s . split ( " " ) [ 1 ] ; browserInfo = "ie " + version . substring ( 0 , version . indexOf ( "." ) ) ; return browserInfo ; } } pattern = Pattern . compile ( firefoxP ) ; mat = pattern . matcher ( ua ) ; if ( mat . find ( ) ) { s = mat . group ( ) ; if ( s != null ) { version = s . split ( "/" ) [ 1 ] ; browserInfo = "firefox " + version . substring ( 0 , version . indexOf ( "." ) ) ; return browserInfo ; } } pattern = Pattern . compile ( ieheighP ) ; mat = pattern . matcher ( ua ) ; if ( mat . find ( ) ) { s = mat . group ( ) ; if ( s != null ) { version = s . split ( ":" ) [ 1 ] ; browserInfo = "ie " + version . substring ( 0 , version . indexOf ( "." ) ) ; return browserInfo ; } } pattern = Pattern . compile ( operaP ) ; mat = pattern . matcher ( ua ) ; if ( mat . find ( ) ) { s = mat . group ( ) ; if ( s != null ) { version = s . split ( "/" ) [ 1 ] ; browserInfo = "opera " + version . substring ( 0 , version . indexOf ( "." ) ) ; return browserInfo ; } } pattern = Pattern . compile ( chromeP ) ; mat = pattern . matcher ( ua ) ; if ( mat . find ( ) ) { s = mat . group ( ) ; if ( s != null ) { version = s . split ( "/" ) [ 1 ] ; browserInfo = "chrome " + version . substring ( 0 , version . indexOf ( "." ) ) ; return browserInfo ; } } pattern = Pattern . compile ( safariP ) ; mat = pattern . matcher ( ua ) ; if ( mat . find ( ) ) { s = mat . group ( ) ; if ( s != null ) { version = s . split ( "/" ) [ 1 ] . split ( " " ) [ 0 ] ; browserInfo = "safari " + version . substring ( 0 , version . indexOf ( "." ) ) ; return browserInfo ; } } return browserInfo ;


signature:
public class Requests { /** * 获取客户端操作系统信息
 * @ param req http request .
 * @ return string */
public static String clientOS ( HttpServletRequest req ) { } }

implementation: String userAgent = req . getHeader ( "User-Agent" ) ; String cos = "unknow os" ; Pattern p = Pattern . compile ( ".*(Windows NT 6\\.2).*" ) ; Matcher m = p . matcher ( userAgent ) ; if ( m . find ( ) ) { cos = "Win 8" ; return cos ; } p = Pattern . compile ( ".*(Windows NT 6\\.1).*" ) ; m = p . matcher ( userAgent ) ; if ( m . find ( ) ) { cos = "Win 7" ; return cos ; } p = Pattern . compile ( ".*(Windows NT 5\\.1|Windows XP).*" ) ; m = p . matcher ( userAgent ) ; if ( m . find ( ) ) { cos = "WinXP" ; return cos ; } p = Pattern . compile ( ".*(Windows NT 5\\.2).*" ) ; m = p . matcher ( userAgent ) ; if ( m . find ( ) ) { cos = "Win2003" ; return cos ; } p = Pattern . compile ( ".*(Win2000|Windows 2000|Windows NT 5\\.0).*" ) ; m = p . matcher ( userAgent ) ; if ( m . find ( ) ) { cos = "Win2000" ; return cos ; } p = Pattern . compile ( ".*(Mac|apple|MacOS8).*" ) ; m = p . matcher ( userAgent ) ; if ( m . find ( ) ) { cos = "MAC" ; return cos ; } p = Pattern . compile ( ".*(WinNT|Windows NT).*" ) ; m = p . matcher ( userAgent ) ; if ( m . find ( ) ) { cos = "WinNT" ; return cos ; } p = Pattern . compile ( ".*Linux.*" ) ; m = p . matcher ( userAgent ) ; if ( m . find ( ) ) { cos = "Linux" ; return cos ; } p = Pattern . compile ( ".*(68k|68000).*" ) ; m = p . matcher ( userAgent ) ; if ( m . find ( ) ) { cos = "Mac68k" ; return cos ; } p = Pattern . compile ( ".*(9x 4.90|Win9(5|8)|Windows 9(5|8)|95/NT|Win32|32bit).*" ) ; m = p . matcher ( userAgent ) ; if ( m . find ( ) ) { cos = "Win9x" ; return cos ; } return cos ;


signature:
public class Requests { /** * 获取客户端IP地址 , 此方法用在proxy环境中
 * @ param request 当前请求
 * @ return 客户端ip , 如果获取失败 , 则返回 127.0.0.1 */
public static String remoteIP ( HttpServletRequest request ) { } }

implementation: String ipAddress ; ipAddress = request . getHeader ( "x-forwarded-for" ) ; if ( ( ipAddress == null ) || ( ipAddress . length ( ) == 0 ) || ( "unknown" . equalsIgnoreCase ( ipAddress ) ) ) { ipAddress = request . getHeader ( "Proxy-Client-IP" ) ; } if ( ( ipAddress == null ) || ( ipAddress . length ( ) == 0 ) || ( "unknown" . equalsIgnoreCase ( ipAddress ) ) ) { ipAddress = request . getHeader ( "WL-Proxy-Client-IP" ) ; } if ( ( ipAddress == null ) || ( ipAddress . length ( ) == 0 ) || ( "unknown" . equalsIgnoreCase ( ipAddress ) ) ) { ipAddress = request . getRemoteAddr ( ) ; if ( ipAddress . equals ( "127.0.0.1" ) ) { InetAddress inet ; try { inet = InetAddress . getLocalHost ( ) ; ipAddress = inet . getHostAddress ( ) ; } catch ( UnknownHostException e ) { e . printStackTrace ( ) ; } } } if ( ( ipAddress != null ) && ( ipAddress . length ( ) > 15 ) ) { if ( ipAddress . indexOf ( "," ) > 0 ) { ipAddress = ipAddress . substring ( 0 , ipAddress . indexOf ( "," ) ) ; } } return ipAddress ;


signature:
public class Requests { /** * 判断是否为搜索引擎
 * @ param request 当前请求
 * @ return true 表示当前请求为搜索引擎发过来的请求 。 */
public static boolean robot ( HttpServletRequest request ) { } }

implementation: String ua = request . getHeader ( "user-agent" ) ; return ! StringUtils . isBlank ( ua ) && ( ( ua . contains ( "Baiduspider" ) || ua . contains ( "Googlebot" ) || ua . contains ( "sogou" ) || ua . contains ( "sina" ) || ua . contains ( "iaskspider" ) || ua . contains ( "ia_archiver" ) || ua . contains ( "Sosospider" ) || ua . contains ( "YoudaoBot" ) || ua . contains ( "yahoo" ) || ua . contains ( "yodao" ) || ua . contains ( "MSNBot" ) || ua . contains ( "spider" ) || ua . contains ( "Twiceler" ) || ua . contains ( "Sosoimagespider" ) || ua . contains ( "naver.com/robots" ) || ua . contains ( "Nutch" ) || ua . contains ( "spider" ) ) ) ;


signature:
public class Requests { /** * 获取COOKIE
 * @ param name cookie 名称
 * @ param request 当前请求
 * @ return cookie 信息 */
public static Cookie getCookie ( HttpServletRequest request , String name ) { } }

implementation: Cookie [ ] cookies = request . getCookies ( ) ; if ( cookies == null ) return null ; for ( Cookie ck : cookies ) { if ( StringUtils . equalsIgnoreCase ( name , ck . getName ( ) ) ) { return ck ; } } return null ;


signature:
public class Requests { /** * 设置COOKIE
 * @ param name cookie ' s name .
 * @ param value cooke value .
 * @ param maxAge age time . */
public static void setCookie ( HttpServletRequest request , HttpServletResponse response , String name , String value , int maxAge , boolean all_sub_domain ) { } }

implementation: Cookie cookie = new Cookie ( name , value ) ; cookie . setMaxAge ( maxAge ) ; if ( all_sub_domain ) { String serverName = request . getServerName ( ) ; String domain = domainOfServerName ( serverName ) ; if ( domain != null && domain . indexOf ( '.' ) != - 1 ) { cookie . setDomain ( '.' + domain ) ; } } cookie . setPath ( StringPool . SLASH ) ; response . addCookie ( cookie ) ;


signature:
public class Requests { /** * 获取用户访问URL中的根域名 例如 : www . dlog . cn - > dlog . cn
 * @ param host 访问地址
 * @ return 根域名 */
public static String domainOfServerName ( String host ) { } }

implementation: if ( isIPAddr ( host ) ) { return null ; } String [ ] names = StringUtils . split ( host , '.' ) ; if ( names == null ) return null ; int len = names . length ; if ( len == 1 ) return null ; if ( len == 3 ) { return makeup ( names [ len - 2 ] , names [ len - 1 ] ) ; } if ( len > 3 ) { String dp = names [ len - 2 ] ; if ( dp . equalsIgnoreCase ( "com" ) || dp . equalsIgnoreCase ( "gov" ) || dp . equalsIgnoreCase ( "net" ) || dp . equalsIgnoreCase ( "edu" ) || dp . equalsIgnoreCase ( "org" ) ) { return makeup ( names [ len - 3 ] , names [ len - 2 ] , names [ len - 1 ] ) ; } else { return makeup ( names [ len - 2 ] , names [ len - 1 ] ) ; } } return host ;


signature:
public class Requests { /** * 判断字符串是否是一个IP地址
 * @ param addr 字符串
 * @ return true 表示ip地址 , 否则反之 */
public static boolean isIPAddr ( String addr ) { } }

implementation: if ( StringUtils . isEmpty ( addr ) ) { return false ; } String [ ] ips = StringUtils . split ( addr , '.' ) ; if ( ips == null || ips . length != 4 ) { return false ; } try { int ipa = Integer . parseInt ( ips [ 0 ] ) ; int ipb = Integer . parseInt ( ips [ 1 ] ) ; int ipc = Integer . parseInt ( ips [ 2 ] ) ; int ipd = Integer . parseInt ( ips [ 3 ] ) ; return ipa >= 0 && ipa <= 255 && ipb >= 0 && ipb <= 255 && ipc >= 0 && ipc <= 255 && ipd >= 0 && ipd <= 255 ; } catch ( Exception ignored ) { } return false ;


signature:
public class Requests { /** * 获取HTTP端口
 * @ param request 当前请求
 * @ return http端口 */
public static int httpPort ( HttpServletRequest request ) { } }

implementation: try { return new URL ( request . getRequestURL ( ) . toString ( ) ) . getPort ( ) ; } catch ( MalformedURLException excp ) { return 80 ; }


signature:
public class Requests { /** * 获取浏览器提交的整形参数
 * @ param request 当前请求
 * @ param param 参数
 * @ param defaultValue 默认值
 * @ return 值 */
public static int param ( HttpServletRequest request , String param , int defaultValue ) { } }

implementation: return NumberUtils . toInt ( request . getParameter ( param ) , defaultValue ) ;


signature:
public class Requests { /** * 获取浏览器提交的字符串参
 * @ param request 当前请求
 * @ param param 参数
 * @ param defaultValue 默认值
 * @ return 值 */
public static String param ( HttpServletRequest request , String param , String defaultValue ) { } }

implementation: String value = request . getParameter ( param ) ; return ( StringUtils . isEmpty ( value ) ) ? defaultValue : value ;


signature:
public class Requests { /** * Get shaping parameters submitted by the browser
 * @ param request Request
 * @ param param Param
 * @ param defaultValue Default Value
 * @ return Param Values . */
public static long param ( HttpServletRequest request , String param , long defaultValue ) { } }

implementation: return NumberUtils . toLong ( request . getParameter ( param ) , defaultValue ) ;


signature:
public class Requests { /** * 判断当前Request是否位Ajax请求 , 通过消息头来进行判断 .
 * @ param request 当前请求对象
 * @ return 如果返回 < code > true < / code > 则 , 表示当前的Request是由Ajax请求 , 否则反之 */
public static boolean ajax ( HttpServletRequest request ) { } }

implementation: String x_requested = request . getHeader ( "x-requested-with" ) ; return ! Strings . isNullOrEmpty ( x_requested ) && "XMLHttpRequest" . equals ( x_requested ) ;


signature:
public class Requests { /** * 去html
 * @ param src HTMl
 * @ return 去掉HTML后的字符串 */
public static String replaceTagHTML ( String src ) { } }

implementation: String regex = "\\<(.+?)\\>" ; return StringUtils . isNotEmpty ( src ) ? src . replaceAll ( regex , "" ) : "" ;


signature:
public class Logger { /** * Log with DEBUG level
 * @ param message The message pattern
 * @ param args Pattern arguments */
public static void debug ( String message , Object ... args ) { } }

implementation: if ( recordCaller ) { LoggerFactory . getLogger ( getCallerClassName ( ) ) . debug ( message , args ) ; } else { slf4j . debug ( message , args ) ; }


signature:
public class Logger { /** * Examine stack trace to get caller
 * @ param level method stack depth
 * @ return who called the logger */
static CallInfo getCallerInformations ( int level ) { } }

implementation: StackTraceElement [ ] callStack = Thread . currentThread ( ) . getStackTrace ( ) ; StackTraceElement caller = callStack [ level ] ; return new CallInfo ( caller . getClassName ( ) , caller . getMethodName ( ) ) ;


signature:
public class QRCodeFormat { /** * 设置错误修正等级 。 其定义如下
 * < ul > < li > L : 有 7 % 的内容可被修正 < / li > < li > M : 有15 % 的内容可被修正 < / li > < li > Q : 有 25 % 的内容可被修正 < / li > < li > H : 有 30%
 * 的内容可被修正 < / li > < / ul >
 * @ param errorCorrectionLevel 错误修正等级
 * @ return QRCode生成器的格式 */
public QRCodeFormat setErrorCorrectionLevel ( char errorCorrectionLevel ) { } }

implementation: switch ( Character . toUpperCase ( errorCorrectionLevel ) ) { case 'L' : this . errorCorrectionLevel = ErrorCorrectionLevel . L ; break ; case 'M' : this . errorCorrectionLevel = ErrorCorrectionLevel . M ; break ; case 'Q' : this . errorCorrectionLevel = ErrorCorrectionLevel . Q ; break ; case 'H' : this . errorCorrectionLevel = ErrorCorrectionLevel . H ; break ; default : this . errorCorrectionLevel = ErrorCorrectionLevel . M ; } return this ;


signature:
public class QRCodeFormat { /** * 设置前景色 。 值为十六进制的颜色值 ( 与 CSS 定义颜色的值相同 , 不支持简写 ) , 可以忽略 「 # 」 符号 。
 * @ param foreGroundColor 前景色的值
 * @ return QRCode生成器的格式 */
public QRCodeFormat setForeGroundColor ( String foreGroundColor ) { } }

implementation: try { this . foreGroundColor = getColor ( foreGroundColor ) ; } catch ( NumberFormatException e ) { this . foreGroundColor = Color . BLACK ; } return this ;


signature:
public class QRCodeFormat { /** * 设置背景色 。 值为十六进制的颜色值 ( 与 CSS 定义颜色的值相同 , 不支持简写 ) , 可以忽略 「 # 」 符号 。
 * @ param backGroundColor 前景色的值
 * @ return QRCode生成器的格式 */
public QRCodeFormat setBackGroundColor ( String backGroundColor ) { } }

implementation: try { this . backGroundColor = getColor ( backGroundColor ) ; } catch ( NumberFormatException e ) { this . backGroundColor = Color . WHITE ; } return this ;


signature:
public class QRCodeFormat { /** * 返回提供给编码器额外的参数 。
 * @ return 提供给编码器额外的参数 */
public Hashtable < EncodeHintType , ? > getHints ( ) { } }

implementation: hints . clear ( ) ; hints . put ( EncodeHintType . ERROR_CORRECTION , getErrorCorrectionLevel ( ) ) ; hints . put ( EncodeHintType . CHARACTER_SET , getEncode ( ) ) ; hints . put ( EncodeHintType . MARGIN , getMargin ( ) ) ; return hints ;


signature:
public class JSONResponse { /** * Writes { @ code JSONResponse } to the current { @ code WebContext } .
 * @ param context The current { @ code WebContext } . */
public void to ( WebContext context ) { } }

implementation:
if ( entity == null ) { return ; } HttpServletResponse response = context . response ( ) ; try { response . setCharacterEncoding ( "UTF-8" ) ; response . setHeader ( "Content-Type" , mediaType ) ; if ( status > 0 ) { response . setStatus ( status ) ; } if ( entity instanceof String ) { response . getWriter ( ) . write ( ( String ) entity ) ; return ; } GsonBuilder builder = new GsonBuilder ( ) ; Set < Class < ? > > classes = new HashSet < Class < ? > > ( ) ; parse ( entity . getClass ( ) , classes ) ; for ( Class < ? > clazz : classes ) { builder . registerTypeAdapter ( clazz , new ValueTypeJsonSerializer < Object > ( ) ) ; } // XXX : Any options ?
Gson gson = builder . create ( ) ; response . getWriter ( ) . write ( gson . toJson ( entity ) ) ; } catch ( IOException e ) { throw new UncheckedException ( e ) ; }


signature:
public class IntEditingSupport { /** * Sets the input validator for this cell editor .
 * The validator is given the ( integer ) value to be validated , and must return a
 * string indicating whether the given value is valid ; < code > null < / code > means
 * valid , and non - < code > null < / code > means invalid , with the result being the
 * error message to display to the end user .
 * This is simply a better - typed version of { @ link # setValidator ( Function ) } .
 * @ param valueToErrorMessage
 * the input validator , or < code > null < / code > if none */
public void setIntegerValidator ( Function < Integer , String > valueToErrorMessage ) { } }

implementation: setValidator ( valueToErrorMessage . compose ( v -> Integer . valueOf ( v ) ) ) ;


signature:
public class CsvUtil { /** * 将文本头与数据共同转成csv字符串
 * @ param headers 列属性
 * @ param data 数据
 * @ param columns 需要显示列的key值
 * @ return csv字符串 */
@ SuppressWarnings ( { } }

implementation:
"unchecked" , "rawtypes" } ) public static String createCSV ( List headers , List data , List columns ) { StringBuffer strOut = new StringBuffer ( "" ) ; if ( null != headers && ! headers . isEmpty ( ) ) { // 如果文本不为空则添加到csv字符串中
listToCSV ( strOut , headers ) ; } if ( null == data || data . isEmpty ( ) ) { return strOut . toString ( ) ; } Iterator itr = data . iterator ( ) ; while ( itr . hasNext ( ) ) { Object obj = itr . next ( ) ; // 将数据添加到csv字符串
Class cls = obj . getClass ( ) ; if ( cls != null && cls . isArray ( ) ) { Object [ ] objs = ( Object [ ] ) obj ; for ( Object obj1 : objs ) { createCol ( strOut , obj1 ) ; strOut . append ( COMMA ) ; } strOut = strOut . deleteCharAt ( strOut . length ( ) - 1 ) ; // 去点多余逗号
strOut . append ( NEWLINE ) ; } else if ( obj instanceof List ) { List objlist = ( List ) obj ; if ( null == columns || columns . isEmpty ( ) ) { // 如果没有限制 , 默认全部显示
listToCSV ( strOut , objlist ) ; } else { for ( Object column : columns ) { createCol ( strOut , objlist . get ( ( Integer ) column ) ) ; strOut . append ( COMMA ) ; } strOut = strOut . deleteCharAt ( strOut . length ( ) - 1 ) ; strOut . append ( NEWLINE ) ; } } else if ( obj instanceof Map ) { Map objmap = ( Map ) obj ; if ( null == columns || columns . isEmpty ( ) ) { // 如果没有限制 , 默认全部显示
Set keyset = objmap . keySet ( ) ; for ( Object key : keyset ) { createCol ( strOut , objmap . get ( key ) ) ; strOut . append ( COMMA ) ; } strOut = strOut . deleteCharAt ( strOut . length ( ) - 1 ) ; strOut . append ( NEWLINE ) ; } else { for ( Object column : columns ) { createCol ( strOut , objmap . get ( column ) ) ; strOut . append ( COMMA ) ; } strOut = strOut . deleteCharAt ( strOut . length ( ) - 1 ) ; strOut . append ( NEWLINE ) ; } } else if ( obj instanceof Model ) { Model objmodel = ( Model ) obj ; if ( null == columns || columns . isEmpty ( ) ) { // 如果没有限制 , 默认全部显示
Set < Entry < String , Object > > entries = objmodel . _getAttrsEntrySet ( ) ; for ( Entry entry : entries ) { createCol ( strOut , entry . getValue ( ) ) ; strOut . append ( COMMA ) ; } strOut = strOut . deleteCharAt ( strOut . length ( ) - 1 ) ; strOut . append ( NEWLINE ) ; } else { for ( Object column : columns ) { createCol ( strOut , objmodel . get ( column + EMPTY ) ) ; strOut . append ( COMMA ) ; } strOut = strOut . deleteCharAt ( strOut . length ( ) - 1 ) ; strOut . append ( NEWLINE ) ; } } else if ( obj instanceof Record ) { Record objrecord = ( Record ) obj ; Map < String , Object > map = objrecord . getColumns ( ) ; if ( null == columns || columns . isEmpty ( ) ) { // 如果没有限制 , 默认全部显示
Set < String > keys = map . keySet ( ) ; for ( String key : keys ) { createCol ( strOut , objrecord . get ( key ) ) ; strOut . append ( COMMA ) ; } strOut = strOut . deleteCharAt ( strOut . length ( ) - 1 ) ; strOut . append ( NEWLINE ) ; } else { for ( Object column : columns ) { createCol ( strOut , objrecord . get ( column + EMPTY ) ) ; strOut . append ( COMMA ) ; } strOut = strOut . deleteCharAt ( strOut . length ( ) - 1 ) ; strOut . append ( NEWLINE ) ; } } else { while ( itr . hasNext ( ) ) { Object objs = itr . next ( ) ; if ( objs != null ) { createCol ( strOut , objs ) ; strOut . append ( NEWLINE ) ; } } } obj = null ; } return strOut . toString ( ) ;


signature:
public class CsvUtil { /** * 把单纯的集合转化成csv字符串
 * @ param strOut StringBuffer
 * @ param list 数据 */
public static void listToCSV ( StringBuffer strOut , List < ? > list ) { } }

implementation:
if ( null != list && ! list . isEmpty ( ) ) { // 如果文本不为空则添加到csv字符串中
for ( Object aList : list ) { createCol ( strOut , aList ) ; strOut . append ( COMMA ) ; } strOut = strOut . deleteCharAt ( strOut . length ( ) - 1 ) ; strOut . append ( NEWLINE ) ; }


signature:
public class CsvUtil { /** * 把单个元素转化 */
public static void createCol ( StringBuffer strOut , Object obj ) { } }

implementation: if ( obj != null ) { strOut . append ( QUOTE ) ; String content ; if ( obj instanceof Boolean ) { content = obj . toString ( ) ; } else if ( obj instanceof Calendar ) { content = obj . toString ( ) ; } else if ( obj instanceof Timestamp ) { content = DP_YYYY_MM_DD_HH_MM . format ( new Date ( ( ( Timestamp ) obj ) . getTime ( ) ) ) ; } else if ( obj instanceof Date ) { content = DP_YYYY_MM_DD_HH_MM . format ( ( Date ) obj ) ; } else { content = write ( String . valueOf ( obj ) ) ; } strOut . append ( content ) ; strOut . append ( QUOTE ) ; } else { strOut . append ( "\" \" " ) ; }


signature:
public class CsvUtil { /** * 特殊字符的转换 " \ t " - > " \ \ t " */
public static String replace ( String original , String pattern , String replace ) { } }

implementation: final int len = pattern . length ( ) ; int found = original . indexOf ( pattern ) ; if ( found > - 1 ) { StringBuilder sb = new StringBuilder ( ) ; int start = 0 ; while ( found != - 1 ) { sb . append ( original . substring ( start , found ) ) ; sb . append ( replace ) ; start = found + len ; found = original . indexOf ( pattern , start ) ; } sb . append ( original . substring ( start ) ) ; return sb . toString ( ) ; } else { return original ; }


signature:
public class CharKit { /** * Converts char array into byte array by stripping the high byte of each character . */
public static byte [ ] toSimpleByteArray ( char [ ] carr ) { } }

implementation: byte [ ] barr = new byte [ carr . length ] ; for ( int i = 0 ; i < carr . length ; i ++ ) { barr [ i ] = ( byte ) carr [ i ] ; } return barr ;


signature:
public class CharKit { /** * Converts char sequence into byte array .
 * @ see # toSimpleByteArray ( char [ ] ) */
public static byte [ ] toSimpleByteArray ( CharSequence charSequence ) { } }

implementation: byte [ ] barr = new byte [ charSequence . length ( ) ] ; for ( int i = 0 ; i < barr . length ; i ++ ) { barr [ i ] = ( byte ) charSequence . charAt ( i ) ; } return barr ;


signature:
public class CharKit { /** * Converts byte array to char array by simply extending bytes to chars . */
public static char [ ] toSimpleCharArray ( byte [ ] barr ) { } }

implementation: char [ ] carr = new char [ barr . length ] ; for ( int i = 0 ; i < barr . length ; i ++ ) { carr [ i ] = ( char ) ( barr [ i ] & 0xFF ) ; } return carr ;


signature:
public class CharKit { /** * Converts char array into { @ link # toAscii ( char ) ASCII } array . */
public static byte [ ] toAsciiByteArray ( char [ ] carr ) { } }

implementation: byte [ ] barr = new byte [ carr . length ] ; for ( int i = 0 ; i < carr . length ; i ++ ) { barr [ i ] = ( byte ) ( ( int ) ( carr [ i ] <= 0xFF ? carr [ i ] : 0x3F ) ) ; } return barr ;


signature:
public class CharKit { /** * Converts char sequence into ASCII byte array . */
public static byte [ ] toAsciiByteArray ( CharSequence charSequence ) { } }

implementation: byte [ ] barr = new byte [ charSequence . length ( ) ] ; for ( int i = 0 ; i < barr . length ; i ++ ) { char c = charSequence . charAt ( i ) ; barr [ i ] = ( byte ) ( ( int ) ( c <= 0xFF ? c : 0x3F ) ) ; } return barr ;


signature:
public class CharKit { /** * Indicates whether the given character is in the < i > sub - delims < / i > set .
 * @ see < a href = " http : / / www . ietf . org / rfc / rfc3986 . txt " > RFC 3986 , appendix A < / a > */
protected static boolean isSubDelimiter ( int c ) { } }


signature:
public class CharKit { /** * Indicates whether the given character is in the < i > unreserved < / i > set .
 * @ see < a href = " http : / / www . ietf . org / rfc / rfc3986 . txt " > RFC 3986 , appendix A < / a > */
protected static boolean isUnreserved ( char c ) { } }


signature:
public class CharKit { /** * Returns the very first index of any char from provided string , starting from specified index offset .
 * Returns index of founded char , or < code > - 1 < / code > if nothing found . */
public static int indexOfChars ( String string , String chars , int startindex ) { } }

implementation: int stringLen = string . length ( ) ; int charsLen = chars . length ( ) ; if ( startindex < 0 ) { startindex = 0 ; } for ( int i = startindex ; i < stringLen ; i ++ ) { char c = string . charAt ( i ) ; for ( int j = 0 ; j < charsLen ; j ++ ) { if ( c == chars . charAt ( j ) ) { return i ; } } } return - 1 ;


signature:
public class CharKit { /** * Returns the very first index of any char from provided string , starting from specified index offset .
 * Returns index of founded char , or < code > - 1 < / code > if nothing found . */
public static int indexOfChars ( String string , char [ ] chars , int startindex ) { } }

implementation: int stringLen = string . length ( ) ; for ( int i = startindex ; i < stringLen ; i ++ ) { char c = string . charAt ( i ) ; for ( char aChar : chars ) { if ( c == aChar ) { return i ; } } } return - 1 ;


signature:
public class CharKit { /** * Returns < code > true < / code > if string { @ link # containsOnlyDigits ( String ) contains only digits }
 * or signs plus or minus . */
public static boolean containsOnlyDigitsAndSigns ( String string ) { } }

implementation: int size = string . length ( ) ; for ( int i = 0 ; i < size ; i ++ ) { char c = string . charAt ( i ) ; if ( ( ! CharKit . isDigit ( c ) ) && ( c != '-' ) && ( c != '+' ) ) { return false ; } } return true ;


signature:
public class CharKit { /** * Splits a string in several parts ( tokens ) that are separated by delimiter
 * characters . Delimiter may contains any number of character and it is
 * always surrounded by two strings .
 * @ param src source to examine
 * @ param d string with delimiter characters
 * @ return array of tokens */
public static String [ ] splitc ( String src , String d ) { } }

implementation:
if ( ( d . length ( ) == 0 ) || ( src . length ( ) == 0 ) ) { return new String [ ] { src } ; } char [ ] delimiters = d . toCharArray ( ) ; char [ ] srcc = src . toCharArray ( ) ; int maxparts = srcc . length + 1 ; int [ ] start = new int [ maxparts ] ; int [ ] end = new int [ maxparts ] ; int count = 0 ; start [ 0 ] = 0 ; int s = 0 , e ; if ( CharKit . equalsOne ( srcc [ 0 ] , delimiters ) ) { // string starts with delimiter
end [ 0 ] = 0 ; count ++ ; s = CharKit . findFirstDiff ( srcc , 1 , delimiters ) ; if ( s == - 1 ) { // nothing after delimiters
return new String [ ] { StringUtils . EMPTY , StringUtils . EMPTY } ; } start [ 1 ] = s ; // new start
} while ( true ) { // find new end
e = CharKit . findFirstEqual ( srcc , s , delimiters ) ; if ( e == - 1 ) { end [ count ] = srcc . length ; break ; } end [ count ] = e ; // find new start
count ++ ; s = CharKit . findFirstDiff ( srcc , e , delimiters ) ; if ( s == - 1 ) { start [ count ] = end [ count ] = srcc . length ; break ; } start [ count ] = s ; } count ++ ; String [ ] result = new String [ count ] ; for ( int i = 0 ; i < count ; i ++ ) { result [ i ] = src . substring ( start [ i ] , end [ i ] ) ; } return result ;


signature:
public class LocaleKit { /** * Lookups for locale data and creates new if it doesn ' t exist . */
protected static LocaleData lookupLocaleData ( String code ) { } }

implementation: LocaleData localeData = locales . get ( code ) ; if ( localeData == null ) { String [ ] data = decodeLocaleCode ( code ) ; localeData = new LocaleData ( new Locale ( data [ 0 ] , data [ 1 ] , data [ 2 ] ) ) ; locales . put ( code , localeData ) ; } return localeData ;


signature:
public class LocaleKit { /** * Returns Locale from cache . */
public static Locale getLocale ( String language , String country , String variant ) { } }

implementation: LocaleData localeData = lookupLocaleData ( resolveLocaleCode ( language , country , variant ) ) ; return localeData . locale ;


signature:
public class LocaleKit { /** * Returns Locale from cache where Locale may be specified also using language code .
 * Converts a locale string like " en " , " en _ US " or " en _ US _ win " to < b > new < / b > Java locale object . */
public static Locale getLocale ( String languageCode ) { } }

implementation: LocaleData localeData = lookupLocaleData ( languageCode ) ; return localeData . locale ;


signature:
public class LocaleKit { /** * Transforms locale data to locale code . < code > null < / code > values are allowed . */
public static String resolveLocaleCode ( String lang , String country , String variant ) { } }

implementation: StringBuilder code = new StringBuilder ( lang ) ; if ( ! StringUtils . isEmpty ( country ) ) { code . append ( '_' ) . append ( country ) ; if ( ! StringUtils . isEmpty ( variant ) ) { code . append ( '_' ) . append ( variant ) ; } } return code . toString ( ) ;


signature:
public class LocaleKit { /** * Decodes locale code in string array that can be used for < code > Locale < / code > constructor . */
public static String [ ] decodeLocaleCode ( String localeCode ) { } }

implementation: String result [ ] = new String [ 3 ] ; String [ ] data = CharKit . splitc ( localeCode , '_' ) ; result [ 0 ] = data [ 0 ] ; result [ 1 ] = result [ 2 ] = StringPool . EMPTY ; if ( data . length >= 2 ) { result [ 1 ] = data [ 1 ] ; if ( data . length >= 3 ) { result [ 2 ] = data [ 2 ] ; } } return result ;


signature:
public class LocaleKit { /** * Returns cached < code > NumberFormat < / code > instance for specified locale . */
public static NumberFormat getNumberFormat ( Locale locale ) { } }

implementation: LocaleData localeData = lookupLocaleData ( locale ) ; NumberFormat nf = localeData . numberFormat ; if ( nf == null ) { nf = NumberFormat . getInstance ( locale ) ; localeData . numberFormat = nf ; } return nf ;


signature:
public class XMLResponse { /** * Writes { @ code XMLResponse } to the current { @ code WebContext } .
 * @ param context The current { @ code WebContext } . */
public void to ( WebContext context ) { } }

implementation: if ( entity == null ) { return ; } HttpServletResponse response = context . response ( ) ; try { response . setCharacterEncoding ( "UTF-8" ) ; response . setHeader ( "Content-Type" , mediaType ) ; if ( status > 0 ) { response . setStatus ( status ) ; } if ( entity instanceof String ) { response . getWriter ( ) . write ( ( String ) entity ) ; return ; } Marshaller marshaller = JAXBContext . newInstance ( entity . getClass ( ) ) . createMarshaller ( ) ; marshaller . setAdapter ( new ValueTypeXmlAdapter < Object > ( ) ) ; marshaller . marshal ( entity , response . getWriter ( ) ) ; } catch ( Exception e ) { throw new UncheckedException ( e ) ; }


signature:
public class ExtensionLoaderModule { /** * Called by { @ link ExtensionFinder } to initialize this module . */
public void init ( Class < ? extends T > impl , Class < T > extensionPoint ) { } }

implementation: this . impl = impl ; this . extensionPoint = extensionPoint ;


signature:
public class Freemarkers { /** * 渲染模板 */
public static String render ( String templateContent , Map < String , Object > paramMap ) { } }

implementation: StringWriter writer = new StringWriter ( ) ; try { Configuration cfg = new Configuration ( Configuration . VERSION_2_3_22 ) ; cfg . setTemplateLoader ( new StringTemplateLoader ( templateContent ) ) ; cfg . setDefaultEncoding ( "UTF-8" ) ; Template template = cfg . getTemplate ( "" ) ; template . process ( paramMap , writer ) ; } catch ( IOException e ) { e . printStackTrace ( ) ; log . error ( e . getMessage ( ) ) ; } catch ( TemplateException e ) { e . printStackTrace ( ) ; log . error ( e . getMessage ( ) ) ; } return writer . toString ( ) ;


signature:
public class Job { /** * Start this job now ( well ASAP )
 * @ return the job completion */
public Promise < V > now ( ) { } }

implementation: final Promise < V > smartFuture = new Promise < V > ( ) ; JobsPlugin . executor . submit ( getJobCallingCallable ( smartFuture ) ) ; return smartFuture ;


signature:
public class Job { /** * Start this job in several seconds
 * @ return the job completion */
public Promise < V > in ( int seconds ) { } }

implementation: final Promise < V > smartFuture = new Promise < V > ( ) ; JobsPlugin . executor . schedule ( getJobCallingCallable ( smartFuture ) , seconds , TimeUnit . SECONDS ) ; return smartFuture ;


signature:
public class Job { /** * Customize Invocation */
@ Override public void onException ( Throwable e ) { } }

implementation: wasError = true ; lastException = e ; try { super . onException ( e ) ; } catch ( Throwable ex ) { logger . error ( "Error during job execution (%s)" , this , ex ) ; }


signature:
public class JettyResourceUtil { /** * hidden */
public static Resource createResource ( String resourcePath ) throws IOException { } }

implementation:
if ( resourcePath . startsWith ( ResourceUtils . CLASSPATH_URL_PREFIX ) ) { return Resource . newClassPathResource ( resourcePath . substring ( ResourceUtils . CLASSPATH_URL_PREFIX . length ( ) ) ) ; } else if ( resourcePath . startsWith ( ResourceUtils . FILE_URL_PREFIX ) ) { return Resource . newResource ( new File ( resourcePath . substring ( ResourceUtils . FILE_URL_PREFIX . length ( ) ) ) ) ; } else if ( resourcePath . startsWith ( "/" ) ) { return Resource . newResource ( new File ( resourcePath ) ) ; } try { if ( Files . exists ( Paths . get ( resourcePath ) ) ) { return Resource . newResource ( new File ( resourcePath ) ) ; } // path seem to be valid but nothing exists there
throw new IOException ( "Missing file at resourcePath=" + resourcePath ) ; } catch ( InvalidPathException e ) { throw new IOException ( "Invalid path or unknown protocol in resourcePath=" + resourcePath , e ) ; }


signature:
public class AbstractServletRpcBinding { /** * VisibleForTesting */
static MediaType getMediaType ( HttpServletRequest request , String headerName ) { } }

implementation: final String mediaTypeName = request . getHeader ( headerName ) ; if ( mediaTypeName == null ) { return null ; } try { return MediaType . valueOf ( mediaTypeName ) ; } catch ( InvalidMediaTypeException ignored ) { return null ; }


signature:
public class Images { /** * Resize an image
 * @ param originalImage The image file
 * @ param to The destination file
 * @ param w The new width ( or - 1 to proportionally resize )
 * @ param h The new height ( or - 1 to proportionally resize ) */
public static void resize ( File originalImage , File to , int w , int h ) { } }

implementation: resize ( originalImage , to , w , h , false ) ;


signature:
public class Images { /** * Resize an image
 * @ param originalImage The image file
 * @ param to The destination file
 * @ param w The new width ( or - 1 to proportionally resize ) or the maxWidth if keepRatio is true
 * @ param h The new height ( or - 1 to proportionally resize ) or the maxHeight if keepRatio is true
 * @ param keepRatio : if true , resize will keep the original image ratio and use w and h as max
 * dimensions */
public static void resize ( File originalImage , File to , int w , int h , boolean keepRatio ) { } }

implementation:
try { BufferedImage source = ImageIO . read ( originalImage ) ; int owidth = source . getWidth ( ) ; int oheight = source . getHeight ( ) ; double ratio = ( double ) owidth / oheight ; int maxWidth = w ; int maxHeight = h ; if ( w < 0 && h < 0 ) { w = owidth ; h = oheight ; } if ( w < 0 && h > 0 ) { w = ( int ) ( h * ratio ) ; } if ( w > 0 && h < 0 ) { h = ( int ) ( w / ratio ) ; } if ( keepRatio ) { h = ( int ) ( w / ratio ) ; if ( h > maxHeight ) { h = maxHeight ; w = ( int ) ( h * ratio ) ; } if ( w > maxWidth ) { w = maxWidth ; h = ( int ) ( w / ratio ) ; } } String mimeType = "image/jpeg" ; if ( to . getName ( ) . endsWith ( ".png" ) ) { mimeType = "image/png" ; } if ( to . getName ( ) . endsWith ( ".gif" ) ) { mimeType = "image/gif" ; } // out
BufferedImage dest = new BufferedImage ( w , h , BufferedImage . TYPE_INT_RGB ) ; Image srcSized = source . getScaledInstance ( w , h , Image . SCALE_SMOOTH ) ; Graphics graphics = dest . getGraphics ( ) ; graphics . setColor ( Color . WHITE ) ; graphics . fillRect ( 0 , 0 , w , h ) ; graphics . drawImage ( srcSized , 0 , 0 , null ) ; ImageWriter writer = ImageIO . getImageWritersByMIMEType ( mimeType ) . next ( ) ; ImageWriteParam params = writer . getDefaultWriteParam ( ) ; FileImageOutputStream toFs = new FileImageOutputStream ( to ) ; writer . setOutput ( toFs ) ; IIOImage image = new IIOImage ( dest , null , null ) ; writer . write ( null , image , params ) ; toFs . flush ( ) ; toFs . close ( ) ; writer . dispose ( ) ; } catch ( Exception e ) { throw new RuntimeException ( e ) ; }


signature:
public class Images { /** * Crop an image
 * @ param originalImage The image file
 * @ param to The destination file
 * @ param x1 The new x origin
 * @ param y1 The new y origin
 * @ param x2 The new x end
 * @ param y2 The new y end */
public static void crop ( File originalImage , File to , int x1 , int y1 , int x2 , int y2 ) { } }

implementation:
try { BufferedImage source = ImageIO . read ( originalImage ) ; String mimeType = "image/jpeg" ; if ( to . getName ( ) . endsWith ( ".png" ) ) { mimeType = "image/png" ; } if ( to . getName ( ) . endsWith ( ".gif" ) ) { mimeType = "image/gif" ; } int width = x2 - x1 ; int height = y2 - y1 ; // out
BufferedImage dest = new BufferedImage ( width , height , BufferedImage . TYPE_INT_RGB ) ; Image croppedImage = source . getSubimage ( x1 , y1 , width , height ) ; Graphics graphics = dest . getGraphics ( ) ; graphics . setColor ( Color . WHITE ) ; graphics . fillRect ( 0 , 0 , width , height ) ; graphics . drawImage ( croppedImage , 0 , 0 , null ) ; ImageWriter writer = ImageIO . getImageWritersByMIMEType ( mimeType ) . next ( ) ; ImageWriteParam params = writer . getDefaultWriteParam ( ) ; writer . setOutput ( new FileImageOutputStream ( to ) ) ; IIOImage image = new IIOImage ( dest , null , null ) ; writer . write ( null , image , params ) ; writer . dispose ( ) ; } catch ( Exception e ) { throw new RuntimeException ( e ) ; }


signature:
public class Images { /** * Encode an image to base64 using a data : URI
 * @ param image The image file
 * @ return The base64 encoded value */
public static String toBase64 ( File image ) throws IOException { } }

implementation: return "data:" + MimeTypes . getMimeType ( image . getName ( ) ) + ";base64," + Codec . encodeBASE64 ( IO . readContent ( image ) ) ;


signature:
public class Images { /** * 将指定的图片加入到当前图片中的指定位置 . 即向图片中打水印 .
 * @ param file 要添加的图片文件 。
 * @ param position 要添加的图片在当前图片中的位置 . < br / > 其取值范围为1-9之间的整数 ( 默认为9 ) 。 分别代表 : 左上 、 上中 、 右上 、 左中 、 正中 、 右中 、 左下 、 中下 、 右下 */
public void add ( File dest , File file , int position ) { } }

implementation: if ( dest . exists ( ) && ! dest . isDirectory ( ) ) { String fn = file . getName ( ) . toLowerCase ( ) ; int opacityType = fn . endsWith ( ".png" ) || fn . endsWith ( "gif" ) ? BufferedImage . TYPE_INT_ARGB : BufferedImage . TYPE_INT_RGB ; Image destImg ; try { destImg = ImageIO . read ( dest ) ; } catch ( IllegalArgumentException e ) { throw new RuntimeException ( e ) ; } catch ( IOException e ) { throw new RuntimeException ( e ) ; } int width = destImg . getWidth ( null ) ; int height = destImg . getHeight ( null ) ; final BufferedImage image = new BufferedImage ( width , height , opacityType ) ; Image src ; try { src = ImageIO . read ( file ) ; } catch ( IllegalArgumentException e ) { throw new RuntimeException ( e ) ; } catch ( IOException e ) { throw new RuntimeException ( e ) ; } int ww = src . getWidth ( null ) ; int hh = src . getHeight ( null ) ; int WW , HH ; switch ( position ) { case 1 : WW = 0 ; HH = 0 ; break ; case 2 : WW = ( width - ww ) / 2 ; HH = 0 ; break ; case 3 : WW = width - ww ; HH = 0 ; break ; case 4 : WW = 0 ; HH = ( height - hh ) / 2 ; break ; case 5 : WW = ( width - ww ) / 2 ; HH = ( height - hh ) / 2 ; break ; case 6 : WW = width - ww ; HH = ( height - hh ) / 2 ; break ; case 7 : WW = 0 ; HH = height - hh ; break ; case 8 : WW = ( width - ww ) / 2 ; HH = height - hh ; break ; default : WW = width - ww ; HH = height - hh ; } Graphics g = image . createGraphics ( ) ; g . drawImage ( src , WW , HH , ww , hh , null ) ; g . dispose ( ) ; }


signature:
public class StrTemplateKit { /** * Creates commonly used { @ link StrTemplateKit . MacroResolver } that resolved macros in the
 * provided map . */
public static MacroResolver createMapMacroResolver ( final Map map ) { } }

implementation: return new MacroResolver ( ) { @ Override public String resolve ( String macroName ) { Object value = map . get ( macroName ) ; if ( value == null ) { return null ; } return value . toString ( ) ; } } ;


signature:
public class StrTemplateKit { /** * Parses string template and replaces macros with resolved values . */
public String parse ( String template , MacroResolver macroResolver ) { } }

implementation:
StringBuilder result = new StringBuilder ( template . length ( ) ) ; int i = 0 ; int len = template . length ( ) ; int startLen = macroStart . length ( ) ; int endLen = macroEnd . length ( ) ; while ( i < len ) { int ndx = template . indexOf ( macroStart , i ) ; if ( ndx == - 1 ) { result . append ( i == 0 ? template : template . substring ( i ) ) ; break ; } // check escaped
int j = ndx - 1 ; boolean escape = false ; int count = 0 ; while ( ( j >= 0 ) && ( template . charAt ( j ) == escapeChar ) ) { escape = ! escape ; if ( escape ) { count ++ ; } j -- ; } if ( resolveEscapes ) { result . append ( template . substring ( i , ndx - count ) ) ; } else { result . append ( template . substring ( i , ndx ) ) ; } if ( escape ) { result . append ( macroStart ) ; i = ndx + startLen ; continue ; } // find macros end
ndx += startLen ; int ndx2 = template . indexOf ( macroEnd , ndx ) ; if ( ndx2 == - 1 ) { throw new IllegalArgumentException ( "Invalid template, unclosed macro at: " + ( ndx - startLen ) ) ; } // detect inner macros , there is no escaping
int ndx1 = ndx ; while ( ndx1 < ndx2 ) { int n = indexOf ( template , macroStart , ndx1 , ndx2 ) ; if ( n == - 1 ) { break ; } ndx1 = n + startLen ; } String name = template . substring ( ndx1 , ndx2 ) ; // find value and append
Object value ; if ( missingKeyReplacement != null || ! replaceMissingKey ) { try { value = macroResolver . resolve ( name ) ; } catch ( Exception ignore ) { value = null ; } if ( value == null ) { if ( replaceMissingKey ) { value = missingKeyReplacement ; } else { value = template . substring ( ndx1 - startLen , ndx2 + 1 ) ; } } } else { value = macroResolver . resolve ( name ) ; if ( value == null ) { value = StringPool . EMPTY ; } } if ( ndx == ndx1 ) { String stringValue = value . toString ( ) ; if ( parseValues ) { if ( stringValue . contains ( macroStart ) ) { stringValue = parse ( stringValue , macroResolver ) ; } } result . append ( stringValue ) ; i = ndx2 + endLen ; } else { // inner macro
template = template . substring ( 0 , ndx1 - startLen ) + value . toString ( ) + template . substring ( ndx2 + endLen ) ; len = template . length ( ) ; i = ndx - startLen ; } } return result . toString ( ) ;


signature:
public class Invoker { /** * Run the code in a new thread after a delay
 * @ param invocation The code to run
 * @ param millis The time to wait before , in milliseconds
 * @ return The future object , to know when the task is completed */
public static Future < ? > invoke ( final Invocation invocation , long millis ) { } }

implementation: return executor . schedule ( invocation , millis , TimeUnit . MILLISECONDS ) ;


signature:
public class Invoker { /** * Run the code in the same thread than caller .
 * @ param invocation The code to run */
public static void invokeInThread ( DirectInvocation invocation ) { } }

implementation: boolean retry = true ; while ( retry ) { invocation . run ( ) ; if ( invocation . retry == null ) { retry = false ; } else { try { if ( invocation . retry . task != null ) { invocation . retry . task . get ( ) ; } else { Thread . sleep ( invocation . retry . timeout ) ; } } catch ( Exception e ) { throw new UnexpectedException ( e ) ; } retry = true ; } }


signature:
public class RestOperationsFactory { /** * Sets credentials for use when accessing service APIs .
 * Note , that multiple calls to this method override previously set credentials .
 * @ param credentials Credential list to use */
public void setCredentials ( @ Nonnull List < ServiceClientCredentials > credentials ) { } }

implementation: credentialsProvider . clear ( ) ; for ( final ServiceClientCredentials cred : credentials ) { final URI uri = cred . getBaseUri ( ) ; credentialsProvider . setCredentials ( new AuthScope ( new HttpHost ( uri . getHost ( ) , uri . getPort ( ) , uri . getScheme ( ) ) ) , new UsernamePasswordCredentials ( cred . getUsername ( ) , cred . getPassword ( ) . toString ( ) ) ) ; }


signature:
public class RestOperationsFactory { /** * Returns rest operations object , suitable for use with the specified credentials
 * @ return New instance of { @ link RestOperations } with all the connection settings provided prior to calling this */
@ Nonnull public RestOperations getRestOperations ( ) { } }

implementation: final HttpClientBuilder builder = HttpClientBuilder . create ( ) ; initDefaultHttpClientBuilder ( builder ) ; httpRequestFactory = new HttpComponentsClientHttpRequestFactory ( builder . build ( ) ) ; final RestTemplate restTemplate = new RestTemplate ( messageConverters ) ; restTemplate . setRequestFactory ( httpRequestFactory ) ; return restTemplate ;


signature:
public class Controller { /** * Rendering errors information , in Json format .
 * @ param error errors information .
 * @ param e exception . */
protected void renderAjaxError ( String error , Exception e ) { } }

implementation: renderJson ( AjaxMessage . error ( error , e ) ) ;


signature:
public class Controller { /** * In the form of JSON rendering forbidden information .
 * @ param message the forbidden message .
 * @ param data the forbidden data .
 * @ param < T > Generic parameter . */
protected < T > void renderAjaxForbidden ( String message , T data ) { } }

implementation: renderJson ( AjaxMessage . forbidden ( message , data ) ) ;


signature:
public class Controller { /** * Render view as a string
 * @ param view view
 * @ return render string . */
protected String template ( String view ) { } }

implementation: final Enumeration < String > attrs = getAttrNames ( ) ; final Map < String , Object > root = Maps . newHashMap ( ) ; while ( attrs . hasMoreElements ( ) ) { String attrName = attrs . nextElement ( ) ; root . put ( attrName , getAttr ( attrName ) ) ; } return Freemarkers . processString ( view , root ) ;


signature:
public class Controller { /** * Based on the current path structure is going to jump full Action of the path
 * @ param currentActionPath The current path , similar to / sau / index
 * @ param url The next path , similar to / au / login , the detail ? The admin / detail .
 * @ return An Action under the full path . */
protected String parsePath ( String currentActionPath , String url ) { } }

implementation:
if ( url . startsWith ( SLASH ) ) { return url . split ( "\\?" ) [ 0 ] ; } else if ( ! url . contains ( SLASH ) ) { return SLASH + currentActionPath . split ( SLASH ) [ 1 ] + SLASH + url . split ( "\\?" ) [ 0 ] ; } else if ( url . contains ( "http:" ) || url . contains ( "https:" ) ) { return null ; } // / abc / def " , " bcd / efg ? abc
return currentActionPath + SLASH + url . split ( "\\?" ) [ 0 ] ;


signature:
public class Controller { /** * According to the request information of jquery . Datatables , the results of the query and
 * returns the JSON data to the client . < p / > The specified query set the data .
 * @ param datas The data .
 * @ param criterias datatable criterias .
 * @ param < E > Generic parameter . */
protected < E > void renderDataTables ( DTCriterias criterias , Page < E > datas ) { } }

implementation: Preconditions . checkNotNull ( criterias , "datatable criterias is must be not null." ) ; DTResponse < E > response = DTResponse . build ( criterias , datas . getList ( ) , datas . getTotalRow ( ) , datas . getTotalPage ( ) ) ; renderJson ( response ) ;


signature:
public class Controller { /** * According to the request information of jquery . Datatables , the results of the query and
 * returns the JSON data to the client . < p / > According to the SQL configuration file , in
 * accordance with the Convention model _ name . coloumns \ model _ name . where \ model _ name . order
 * configured SQL to query and returns the results to the client .
 * @ param model _ name The Model name .
 * @ param criterias datatable criterias . */
protected void renderDataTables ( DTCriterias criterias , String model_name ) { } }

implementation: Preconditions . checkNotNull ( criterias , "datatable criterias is must be not null." ) ; final Page < Record > datas = DTDao . paginate ( model_name , criterias ) ; DTResponse response = DTResponse . build ( criterias , datas . getList ( ) , datas . getTotalRow ( ) , datas . getTotalRow ( ) ) ; renderJson ( response ) ;


signature:
public class Controller { /** * According to the request information of jquery . Datatables , the results of the query and
 * returns the JSON data to the client . < p / > According to the SQL configuration file , in
 * accordance with the Convention model _ name . coloumns \ model _ name . where \ model _ name . order
 * configured SQL to query and specify the parameters and return results to the client .
 * @ param criterias datatable criterias .
 * @ param sqlGroupName The Model name .
 * @ param params Query parameters */
protected void renderDataTables ( DTCriterias criterias , String sqlGroupName , List < Object > params ) { } }

implementation: Preconditions . checkNotNull ( criterias , "datatable criterias is must be not null." ) ; final Page < Record > datas = DTDao . paginate ( sqlGroupName , criterias , params ) ; DTResponse response = DTResponse . build ( criterias , datas . getList ( ) , datas . getTotalRow ( ) , datas . getTotalRow ( ) ) ; renderJson ( response ) ;


signature:
public class Controller { /** * The source of data for rendering the jQuery Datatables
 * @ param m _ cls The Model class . */
protected void renderDataTables ( Class < ? extends Model > m_cls ) { } }

implementation: DTCriterias criterias = getCriterias ( ) ; Preconditions . checkNotNull ( criterias , "datatable criterias is must be not null." ) ; DTResponse response = criterias . response ( m_cls ) ; renderJson ( response ) ;


signature:
public class Controller { /** * rendering the empty datasource .
 * @ param criterias datatable criterias . */
protected void renderEmptyDataTables ( DTCriterias criterias ) { } }

implementation: Preconditions . checkNotNull ( criterias , "datatable criterias is must be not null." ) ; DTResponse response = DTResponse . build ( criterias , Collections . EMPTY_LIST , 0 , 0 ) ; renderJson ( response ) ;


signature:
public class Controller { /** * 渲染DataGrid的表格展示 , 支持排序和搜索
 * @ param modelClass 指定类 */
protected void renderEasyUIDataGrid ( Class < ? extends Model > modelClass ) { } }

implementation: final Optional < DataGridReq > reqOptional = EuiDataGrid . req ( getRequest ( ) ) ; if ( reqOptional . isPresent ( ) ) { renderJson ( EuiDataGrid . rsp ( reqOptional . get ( ) , modelClass ) ) ; } else { renderJson ( EuiDataGrid . EMPTY_DATAGRID ) ; }


signature:
public class Controller { /** * 渲染DataGrid的表格展示 , 支持排序和搜索
 * @ param gridReq 请求参数
 * @ param sqlGroupName 指定SQL管理的GroupName */
protected void renderEasyUIDataGrid ( DataGridReq gridReq , String sqlGroupName ) { } }

implementation: Preconditions . checkNotNull ( gridReq , "参数不能为空" ) ; renderJson ( EuiDataGrid . rsp ( gridReq , sqlGroupName ) ) ;


signature:
public class Controller { /** * 渲染DataGrid的表格展示 , 支持排序和搜索 */
protected void renderEasyUIDataGrid ( final Page < Record > paginate ) { } }

implementation: Preconditions . checkNotNull ( paginate , "参数不能为空" ) ; renderJson ( EuiDataGrid . rsp ( paginate ) ) ;