signature:
public class Strings { /** * 如果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 ( Strings . isEmpty ( str ) || c != str . charAt ( 0 ) ) ? str : str . substring ( 1 ) ;


signature:
public class Strings { /** * 检查一个字符串是否为合法的电子邮件地址
 * @ param input
 * 需要检查的字符串
 * @ return true 如果是有效的邮箱地址 */
public static final boolean isEmail ( CharSequence input ) { } }

implementation: if ( Strings . isBlank ( input ) ) return false ; try { new Email ( input . toString ( ) ) ; return true ; } catch ( Exception e ) { } return false ;


signature:
public class Strings { /** * 将一个字符串由驼峰式命名变成分割符分隔单词
 * < pre >
 * lowerWord ( " helloWorld " , ' - ' ) = > " hello - world "
 * < / pre >
 * @ param cs
 * 字符串
 * @ param c
 * 分隔符
 * @ return 转换后字符串 */
public static String lowerWord ( CharSequence cs , char c ) { } }

implementation: StringBuilder sb = new StringBuilder ( ) ; int len = cs . length ( ) ; for ( int i = 0 ; i < len ; i ++ ) { char ch = cs . charAt ( i ) ; if ( Character . isUpperCase ( ch ) ) { if ( i > 0 ) sb . append ( c ) ; sb . append ( Character . toLowerCase ( ch ) ) ; } else { sb . append ( ch ) ; } } return sb . toString ( ) ;


signature:
public class Strings { /** * 将一个字符串某一个字符后面的字母变成大写 , 比如
 * < pre >
 * upperWord ( " hello - world " , ' - ' ) = > " helloWorld "
 * < / pre >
 * @ param cs
 * 字符串
 * @ param c
 * 分隔符
 * @ return 转换后字符串 */
public static String upperWord ( CharSequence cs , char c ) { } }

implementation: StringBuilder sb = new StringBuilder ( ) ; int len = cs . length ( ) ; for ( int i = 0 ; i < len ; i ++ ) { char ch = cs . charAt ( i ) ; if ( ch == c ) { do { i ++ ; if ( i >= len ) return sb . toString ( ) ; ch = cs . charAt ( i ) ; } while ( ch == c ) ; sb . append ( Character . toUpperCase ( ch ) ) ; } else { sb . append ( ch ) ; } } return sb . toString ( ) ;


signature:
public class Strings { /** * 根据一个给定的 Map , 来替换一段字符串 。
 * 以替换 HTML 为例 , 这个 Map 可以是
 * < pre >
 * / / 值为 Null 表示不变
 * " & copy ; " : null ,
 * " & # \ \ d { 3 , } ; " : null , / / 也可以用正则表达式
 * " & ( amp | lt | gt | quot | qpos ) ; " : null ,
 * / / 有值的 , 就要替换了
 * " & " : " & amp ; " , / / 键不支持正则表达式
 * " < " : " & lt ; " ,
 * " > " : " & gt ; " ,
 * < / pre >
 * 实际上 , 本函数会根据 Map 生成一个正则表达式 , 然后进行替换 , 效率应该还不错 ^ _ ^
 * < b > ! ! ! 注意 < / b > 有值的组 , 键值不支持正则表达式
 * @ param str
 * 原始字符串
 * @ param map
 * 如何替换的方式
 * @ return 新字符串 */
public static String replaceBy ( CharSequence cs , Map < String , Object > map ) { } }

implementation:
if ( null == cs ) return null ; String str = cs . toString ( ) ; if ( str . length ( ) == 0 ) return str ; if ( null == map || map . isEmpty ( ) ) return str ; // 准备两个分组
List < String > keys1 = new ArrayList < String > ( map . size ( ) ) ; List < String > keys2 = new ArrayList < String > ( map . size ( ) ) ; for ( Map . Entry < String , Object > en : map . entrySet ( ) ) { String key = en . getKey ( ) ; // 没值 , 分作第一组
if ( null == en . getValue ( ) ) { keys1 . add ( key ) ; } // 有值 , 作为第二组
else { keys2 . add ( key ) ; } } // 准备模式 : 0 : 一组null , 1 : 一组val , 2 : 两组
int mode = - 1 ; // 准备正则表达式
StringBuilder regex = new StringBuilder ( ) ; if ( keys1 . size ( ) > 0 ) { regex . append ( "(" + Strings . join ( "|" , keys1 ) + ")" ) ; mode = 0 ; } if ( keys2 . size ( ) > 0 ) { if ( mode < 0 ) { mode = 1 ; } else { mode = 2 ; regex . append ( '|' ) ; } regex . append ( "(" + Strings . join ( "|" , keys2 ) + ")" ) ; } // mode 1,2 的时候才有必要转换吧
if ( mode <= 0 ) return str ; // 编译正则表达式
Pattern p = Pattern . compile ( regex . toString ( ) ) ; // 准备返回值
StringBuilder sb = new StringBuilder ( ) ; int pos = 0 ; // 匹配字符串
Matcher m = p . matcher ( str ) ; while ( m . find ( ) ) { // 1 : 一组val
if ( 1 == mode ) { // 截取前面的字符串
if ( m . start ( ) > pos ) { sb . append ( str . substring ( pos , m . start ( ) ) ) ; } // 得到 Key , 并替换
String key = m . group ( 1 ) ; sb . append ( map . get ( key ) ) ; } // 2 : 两组
else { // 如果落到 Null 组了 , 那么直接 copy
if ( null != m . group ( 1 ) ) { sb . append ( str . substring ( pos , m . end ( ) ) ) ; } // 否则
else { // 截取前面的字符串
if ( m . start ( ) > pos ) { sb . append ( str . substring ( pos , m . start ( ) ) ) ; } // 得到 Key , 并替换
String key = m . group ( m . groupCount ( ) ) ; sb . append ( map . get ( key ) ) ; } } // 最后记录一下 pos
pos = m . end ( ) ; } // 木有匹配 , 直接返回
if ( pos == 0 ) return str ; if ( pos < str . length ( ) ) sb . append ( str . substring ( pos ) ) ; // 拼上最后一截并返回
return sb . toString ( ) ;


signature:
public class Strings { /** * 使用 UTF - 8 编码将字符串编码为 byte 序列 , 并将结果存储到新的 byte 数组
 * @ param cs
 * 字符串
 * @ return UTF - 8编码后的 byte 数组 */
public static byte [ ] getBytesUTF8 ( CharSequence cs ) { } }

implementation: try { return cs . toString ( ) . getBytes ( Encoding . UTF8 ) ; } catch ( UnsupportedEncodingException e ) { throw Lang . wrapThrow ( e ) ; }


signature:
public class Strings { /** * 将数字转为十六进制字符串 , 默认要使用2个字符 ( 暂时没考虑负数 )
 * @ param n
 * 数字
 * @ return 十六进制字符串 */
public static String num2hex ( int n ) { } }

implementation: String s = Integer . toHexString ( n ) ; return n <= 15 ? "0" + s : s ;


signature:
public class Strings { /** * 使用给定的分隔符 , 将一个数组拼接成字符串
 * @ param sp
 * 分隔符
 * @ param array
 * 要拼接的数组
 * @ return 拼接好的字符串 */
public static < T > String join2 ( String sp , T [ ] array ) { } }

implementation: return Lang . concat ( sp , array ) . toString ( ) ;


signature:
public class Strings { /** * 使用给定的分隔符 , 将一个数组拼接成字符串
 * @ param sp
 * 分隔符
 * @ param array
 * 要拼接的数组
 * @ return 拼接好的字符串 */
public static < T > String join ( String sp , T ... array ) { } }


signature:
public class Strings { /** * 使用给定的分隔符 , 将一个集合拼接成字符串
 * @ param sp
 * 分隔符
 * @ param coll
 * 要拼接的集合
 * @ return 拼接好的字符串 */
public static < T > String join ( String sp , Collection < T > coll ) { } }

implementation: return Lang . concat ( sp , coll ) . toString ( ) ;


signature:
public class Strings { /** * 改变字符编码集
 * @ param cs
 * 原字符串
 * @ param newCharset
 * 指定的新编码集
 * @ return 新字符集编码的字符串 */
public static String changeCharset ( CharSequence cs , Charset newCharset ) { } }

implementation: if ( cs != null ) { byte [ ] bs = cs . toString ( ) . getBytes ( ) ; return new String ( bs , newCharset ) ; } return null ;


signature:
public class Strings { /** * 将字符串根据转移字符转移
 * @ param str
 * 字符串
 * @ return 转移后的字符串 */
public static String evalEscape ( String str ) { } }

implementation:
StringBuilder sb = new StringBuilder ( ) ; char [ ] cs = str . toCharArray ( ) ; for ( int i = 0 ; i < cs . length ; i ++ ) { char c = cs [ i ] ; // 如果是转义字符
if ( c == '\\' ) { c = cs [ ++ i ] ; switch ( c ) { case 'n' : sb . append ( '\n' ) ; break ; case 'r' : sb . append ( '\r' ) ; break ; case 't' : sb . append ( '\t' ) ; break ; case 'b' : sb . append ( '\b' ) ; break ; case '\'' : case '"' : case '\\' : sb . append ( c ) ; break ; default : throw Lang . makeThrow ( "evalEscape invalid char[%d] '%c'  : %s" , i , c , str ) ; } } // 否则添加
else { sb . append ( c ) ; } } return sb . toString ( ) ;


signature:
public class Strings { /** * 将字符串按照某个或几个分隔符拆分 。 其中 , 遇到字符串 " . . . " 或者 ' . . . ' 并不拆分
 * @ param str
 * 要被拆分的字符串
 * @ param keepQuote
 * 是否保持引号
 * @ param seps
 * 分隔符
 * @ return 拆分后的数组 */
public static String [ ] split ( String str , boolean keepQuote , boolean keepBlank , char ... seps ) { } }

implementation:
List < String > list = new LinkedList < String > ( ) ; char [ ] cs = str . toCharArray ( ) ; StringBuilder sb = new StringBuilder ( ) ; for ( int i = 0 ; i < cs . length ; i ++ ) { char c = cs [ i ] ; // 遇到分隔符号
if ( Nums . isin ( seps , c ) ) { if ( keepBlank || ! Strings . isBlank ( sb ) ) { String s2 = sb . toString ( ) ; if ( ! keepQuote ) s2 = evalEscape ( s2 ) ; list . add ( s2 ) ; sb = new StringBuilder ( ) ; } } // 如果是转义字符
else if ( c == '\\' ) { i ++ ; if ( keepQuote ) sb . append ( c ) ; if ( i < cs . length ) { c = cs [ i ] ; sb . append ( c ) ; } else { break ; } } // 字符串
else if ( c == '\'' || c == '"' || c == '`' ) { if ( keepQuote ) sb . append ( c ) ; while ( ++ i < cs . length ) { char c2 = cs [ i ] ; // 如果是转义字符
if ( c2 == '\\' ) { sb . append ( '\\' ) ; i ++ ; if ( i < cs . length ) { c2 = cs [ i ] ; sb . append ( c2 ) ; } else { break ; } } // 退出字符串
else if ( c2 == c ) { if ( keepQuote ) sb . append ( c2 ) ; break ; } // 其他附加
else { sb . append ( c2 ) ; } } } // 其他 , 计入
else { sb . append ( c ) ; } } // 添加最后一个
if ( keepBlank || ! Strings . isBlank ( sb ) ) { String s2 = sb . toString ( ) ; if ( ! keepQuote ) s2 = evalEscape ( s2 ) ; list . add ( s2 ) ; } // 返回拆分后的数组
return list . toArray ( new String [ list . size ( ) ] ) ;


signature:
public class Strings { /** * 按长度截取字符串 ( 尾部补足 )
 * @ param length
 * 长度
 * @ param s
 * 字符串内容
 * @ param supply
 * 补足内容
 * @ return 截断后的字符串 */
public static String cutStr ( int length , String s , String supply ) { } }

implementation: if ( Lang . isEmpty ( length ) || Lang . isEmpty ( s ) ) return null ; else if ( s . length ( ) <= length ) return s ; else return s . substring ( 0 , length - 1 ) + supply ;


signature:
public class Strings { /** * 判断字符串是否为URL
 * @ param s
 * 字符串内容
 * @ return 判断结果 */
public static boolean isUrl ( String s ) { } }

implementation: try { new java . net . URL ( s ) ; } catch ( MalformedURLException e ) { return false ; } return true ;


signature:
public class Strings { /** * 给定内容是否匹配正则
 * @ param pattern
 * 模式
 * @ param content
 * 内容
 * @ return 正则为null或者 " " 则不检查 , 返回true , 内容为null返回false */
public static boolean isMatch ( Pattern pattern , String content ) { } }

implementation:
if ( content == null || pattern == null ) // 提供null的字符串为不匹配
return false ; return pattern . matcher ( content ) . matches ( ) ;


signature:
public class Strings { /** * 截去最后一个字符
 * 比如 :
 * < ul >
 * < li > removeLast ( " 12345 " ) = > 1234
 * < li > removeLast ( " A " ) = > " "
 * < / ul >
 * @ param str
 * 字符串
 * @ return 新字符串 */
public static String removeLast ( CharSequence str ) { } }

implementation: if ( str == null ) return null ; if ( str . length ( ) > 1 ) return str . subSequence ( 0 , str . length ( ) - 1 ) . toString ( ) ; return "" ;


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

implementation: return ( Strings . isEmpty ( str ) || ! str . endsWith ( c + "" ) ) ? str : str . subSequence ( 0 , str . length ( ) - 1 ) . toString ( ) ;


signature:
public class ClassTools { /** * 从输入流中读取Class的名字 , 输入流必须是Class文件格式 */
public static String getClassName ( InputStream in ) { } }

implementation:
try { DataInputStream dis = new DataInputStream ( new BufferedInputStream ( in ) ) ; Map < Integer , String > strs = new HashMap < Integer , String > ( ) ; Map < Integer , Integer > classes = new HashMap < Integer , Integer > ( ) ; dis . skipBytes ( 4 ) ; // Magic
dis . skipBytes ( 2 ) ; // 副版本号
dis . skipBytes ( 2 ) ; // 主版本号
// 读取常量池
int constant_pool_count = dis . readUnsignedShort ( ) ; for ( int i = 0 ; i < ( constant_pool_count - 1 ) ; i ++ ) { byte flag = dis . readByte ( ) ; switch ( flag ) { case 7 : // CONSTANT _ Class :
int index = dis . readUnsignedShort ( ) ; classes . put ( i + 1 , index ) ; break ; case 9 : // CONSTANT _ Fieldref :
case 10 : // CONSTANT _ Methodref :
case 11 : // CONSTANT _ InterfaceMethodref :
dis . skipBytes ( 2 ) ; dis . skipBytes ( 2 ) ; break ; case 8 : // CONSTANT _ String :
dis . skipBytes ( 2 ) ; break ; case 3 : // CONSTANT _ Integer :
case 4 : // CONSTANT _ Float :
dis . skipBytes ( 4 ) ; break ; case 5 : // CONSTANT _ Long :
case 6 : // CONSTANT _ Double :
dis . skipBytes ( 8 ) ; i ++ ; // 必须跳过一个 , 这是class文件设计的一个缺陷 , 历史遗留问题
break ; case 12 : // CONSTANT _ NameAndType :
dis . skipBytes ( 2 ) ; dis . skipBytes ( 2 ) ; break ; case 1 : // CONSTANT _ Utf8:
int len = dis . readUnsignedShort ( ) ; byte [ ] data = new byte [ len ] ; dis . readFully ( data ) ; strs . put ( i + 1 , new String ( data , Encoding . UTF8 ) ) ; // 必然是UTF8的
break ; case 15 : // CONSTANT _ MethodHandle :
dis . skipBytes ( 1 ) ; dis . skipBytes ( 2 ) ; break ; case 16 : // CONSTANT _ MethodType :
dis . skipBytes ( 2 ) ; break ; case 18 : // CONSTANT _ InvokeDynamic :
dis . skipBytes ( 2 ) ; dis . skipBytes ( 2 ) ; break ; default : throw new RuntimeException ( "Impossible!! flag=" + flag ) ; } } dis . skipBytes ( 2 ) ; // 版本控制符
int pos = dis . readUnsignedShort ( ) ; String name = strs . get ( classes . get ( pos ) ) ; if ( name != null ) name = name . replace ( '/' , '.' ) ; dis . close ( ) ; return name ; } catch ( Throwable e ) { if ( log . isInfoEnabled ( ) ) log . info ( "Fail to read ClassName from class InputStream" , e ) ; } return null ;


signature:
public class NutFilePool { /** * 获取指定路径下的FilePool , 如果没有就新建一个
 * @ param path 临时文件夹
 * @ param limit 最大文件数量
 * @ return 已有或新建的FilePool同步实例 */
public static FilePool getOrCreatePool ( String path , long limit ) { } }

implementation: FilePool pool = pools . get ( path ) ; if ( pool == null ) { pool = new NutFilePool ( path , limit ) ; pool = new SynchronizedFilePool ( pool ) ; pools . put ( path , pool ) ; } return pool ;


signature:
public class StringGenerator { /** * 根据设置的max和min的长度 , 生成随机字符串 .
 * 若max或min小于0 , 则返回null
 * @ return 生成的字符串 */
public String next ( ) { } }

implementation: if ( maxLen <= 0 || minLen <= 0 || minLen > maxLen ) return null ; char [ ] buf = new char [ R . random ( minLen , maxLen ) ] ; for ( int i = 0 ; i < buf . length ; i ++ ) buf [ i ] = CharGenerator . next ( ) ; return new String ( buf ) ;


signature:
public class StringOutputStream { /** * 完成本方法后 , 确认字符串已经完成写入后 , 务必调用flash方法 ! */
@ Override public void write ( int b ) throws IOException { } }

implementation: if ( null == baos ) throw new IOException ( "Stream is closed" ) ; baos . write ( b ) ;


signature:
public class StringOutputStream { /** * 使用StringBuilder前 , 务必调用 */
@ Override public void flush ( ) throws IOException { } }

implementation: if ( null != baos ) { baos . flush ( ) ; if ( baos . size ( ) > 0 ) { if ( charset == null ) sb . append ( new String ( baos . toByteArray ( ) ) ) ; else sb . append ( new String ( baos . toByteArray ( ) , charset ) ) ; baos . reset ( ) ; } }


signature:
public class AbstractMethodInterceptor { /** * 拦截方法调用 , 将拦截器的行为 , 分成 : 之前 , 之后 , 抛异常 , 抛错误 - - 4种拦截点 */
public void filter ( InterceptorChain chain ) throws Throwable { } }

implementation: try { if ( beforeInvoke ( chain . getCallingObj ( ) , chain . getCallingMethod ( ) , chain . getArgs ( ) ) ) chain . doChain ( ) ; Object obj = afterInvoke ( chain . getCallingObj ( ) , chain . getReturn ( ) , chain . getCallingMethod ( ) , chain . getArgs ( ) ) ; chain . setReturnValue ( obj ) ; } catch ( Exception e ) { if ( whenException ( e , chain . getCallingObj ( ) , chain . getCallingMethod ( ) , chain . getArgs ( ) ) ) throw e ; } catch ( Throwable e ) { if ( whenError ( e , chain . getCallingObj ( ) , chain . getCallingMethod ( ) , chain . getArgs ( ) ) ) throw e ; }


signature:
public class AbstractMethodInterceptor { /** * 在方法执行后拦截
 * @ param obj 被拦截的对象
 * @ param returnObj 被拦截的方法的返回值的对象
 * @ param method 被拦截的方法
 * @ param args 被拦截方法的参数
 * @ return 将会替代原方法返回值的值 */
public Object afterInvoke ( Object obj , Object returnObj , Method method , Object ... args ) { } }

implementation: return returnObj ;


signature:
public class AbstractMethodInterceptor { /** * 抛出Exception的时候拦截
 * @ param e 异常对象
 * @ param obj 被拦截的对象
 * @ param method 被拦截的方法
 * @ param args 被拦截方法的返回值
 * @ return 是否继续抛出异常 */
public boolean whenException ( Exception e , Object obj , Method method , Object ... args ) { } }

implementation: return true ;


signature:
public class AbstractMethodInterceptor { /** * 抛出Throwable的时候拦截
 * @ param e 异常对象
 * @ param obj 被拦截的对象
 * @ param method 被拦截的方法
 * @ param args 被拦截方法的返回值
 * @ return 是否继续抛出异常 */
public boolean whenError ( Throwable e , Object obj , Method method , Object ... args ) { } }


signature:
public class Chain { /** * 由当前的值链生成一个可被实体化的 Map 。 即有 ' . table ' 属性
 * @ param tableName
 * 表名
 * @ return 可被实体化的 Map */
public Map < String , Object > toEntityMap ( String tableName ) { } }

implementation: Map < String , Object > map = toMap ( ) ; map . put ( ".table" , tableName ) ; return map ;


signature:
public class Chain { /** * 根据一个对象的字段 生成一个 Chain 对象
 * 这个对象可以是一个 POJO 或者是一个 Map 。
 * 支持 FieldMatcher , 即你可以通过 FieldMatcher 来指定你需要哪些字段加入 Chain
 * @ param obj
 * 对象 , 可以是一个 POJO 或者是一个 Map
 * @ param fm
 * 指明可用字段 , null 表示全部字段可用
 * @ return Chain 对象 , null 表示对象中没有可用字段
 * @ see org . nutz . dao . FieldMatcher */
public static Chain from ( Object obj , FieldMatcher fm ) { } }

implementation:
if ( null == obj ) return null ; Chain c = null ; /* * Is Map */
if ( obj instanceof Map < ? , ? > ) { for ( Map . Entry < ? , ? > en : ( ( Map < ? , ? > ) obj ) . entrySet ( ) ) { Object key = en . getKey ( ) ; if ( null == key ) continue ; String name = key . toString ( ) ; if ( null != fm && ! fm . match ( name ) ) continue ; Object v = en . getValue ( ) ; if ( null != fm ) { if ( null == v ) { if ( fm . isIgnoreNull ( ) ) continue ; } else if ( fm . isIgnoreBlankStr ( ) && v instanceof String && Strings . isBlank ( ( String ) v ) ) { continue ; } } if ( c == null ) { c = Chain . make ( name , v ) ; } else { c = c . add ( name , v ) ; } } } /* * Is POJO */
else { Mirror < ? > mirror = Mirror . me ( obj . getClass ( ) ) ; for ( Field f : mirror . getFields ( ) ) { if ( null != fm && ! fm . match ( f . getName ( ) ) ) continue ; Object v = mirror . getValue ( obj , f . getName ( ) ) ; if ( null == v ) { if ( fm != null && fm . isIgnoreNull ( ) ) continue ; } else if ( fm != null && fm . isIgnoreBlankStr ( ) && v instanceof String && Strings . isBlank ( ( String ) v ) ) { continue ; } if ( c == null ) { c = Chain . make ( f . getName ( ) , v ) ; } else { c = c . add ( f . getName ( ) , v ) ; } } } return c ;


signature:
public class Dumps { /** * 显示 Matcher 的详细信息
 * @ param m
 * Matcher 对象 , 必须执行过 find
 * @ return 信息 */
public static String matcherFound ( Matcher m ) { } }

implementation: StringBuilder sb = new StringBuilder ( ) ; sb . append ( String . format ( "%d/%d  Regin:%d/%d\n" , m . start ( ) , m . end ( ) , m . regionStart ( ) , m . regionEnd ( ) ) ) ; for ( int i = 0 ; i <= m . groupCount ( ) ; i ++ ) sb . append ( String . format ( "%2d:[%3d,%3d) %s\n" , i , m . start ( i ) , m . end ( i ) , m . group ( i ) ) ) ; return sb . toString ( ) ;


signature:
public class Dumps { /** * 显示一个对象所有个 getter 函数返回 , 以及 public 的 Field 的值
 * @ param obj
 * 对象
 * @ return 信息 */
public static String obj ( Object obj ) { } }

implementation: if ( null == obj ) return "null" ; StringBuilder sb = new StringBuilder ( obj . getClass ( ) . getName ( ) + "\n\n[Fields:]" ) ; Mirror < ? > mirror = Mirror . me ( obj . getClass ( ) ) ; for ( Field f : mirror . getType ( ) . getFields ( ) ) if ( Modifier . isPublic ( f . getModifiers ( ) ) ) try { sb . append ( String . format ( "\n\t%10s : %s" , f . getName ( ) , f . get ( obj ) ) ) ; } catch ( Exception e1 ) { sb . append ( String . format ( "\n\t%10s : %s" , f . getName ( ) , e1 . getMessage ( ) ) ) ; } sb . append ( "\n\n[Methods:]" ) ; for ( Method m : mirror . getType ( ) . getMethods ( ) ) if ( Modifier . isPublic ( m . getModifiers ( ) ) ) if ( m . getName ( ) . startsWith ( "get" ) ) if ( m . getParameterTypes ( ) . length == 0 ) try { sb . append ( String . format ( "\n\t%10s : %s" , m . getName ( ) , m . invoke ( obj ) ) ) ; } catch ( Exception e ) { sb . append ( String . format ( "\n\t%10s : %s" , m . getName ( ) , e . getMessage ( ) ) ) ; } return sb . toString ( ) ;


signature:
public class GeneratorAdapter { /** * Generates the instruction to push the given value on the stack .
 * @ param value
 * the value to be pushed on the stack . */
public void push ( final int value ) { } }

implementation: if ( value >= - 1 && value <= 5 ) { mv . visitInsn ( Opcodes . ICONST_0 + value ) ; } else if ( value >= Byte . MIN_VALUE && value <= Byte . MAX_VALUE ) { mv . visitIntInsn ( Opcodes . BIPUSH , value ) ; } else if ( value >= Short . MIN_VALUE && value <= Short . MAX_VALUE ) { mv . visitIntInsn ( Opcodes . SIPUSH , value ) ; } else { mv . visitLdcInsn ( value ) ; }


signature:
public class GeneratorAdapter { /** * Generates the instruction to push the given value on the stack .
 * @ param value
 * the value to be pushed on the stack . */
public void push ( final long value ) { } }

implementation: if ( value == 0L || value == 1L ) { mv . visitInsn ( Opcodes . LCONST_0 + ( int ) value ) ; } else { mv . visitLdcInsn ( value ) ; }


signature:
public class GeneratorAdapter { /** * Generates the instruction to push the given value on the stack .
 * @ param value
 * the value to be pushed on the stack . */
public void push ( final float value ) { } }

implementation:
int bits = Float . floatToIntBits ( value ) ; if ( bits == 0L || bits == 0x3f800000 || bits == 0x40000000 ) { // 0 . . 2
mv . visitInsn ( Opcodes . FCONST_0 + ( int ) value ) ; } else { mv . visitLdcInsn ( value ) ; }


signature:
public class GeneratorAdapter { /** * Generates the instruction to push the given value on the stack .
 * @ param value
 * the value to be pushed on the stack . */
public void push ( final double value ) { } }

implementation:
long bits = Double . doubleToLongBits ( value ) ; if ( bits == 0L || bits == 0x3ff0000000000000L ) { // + 0.0d and 1.0d
mv . visitInsn ( Opcodes . DCONST_0 + ( int ) value ) ; } else { mv . visitLdcInsn ( value ) ; }


signature:
public class GeneratorAdapter { /** * Generates the instruction to push the given value on the stack .
 * @ param value
 * the value to be pushed on the stack . May be < tt > null < / tt > . */
public void push ( final String value ) { } }

implementation: if ( value == null ) { mv . visitInsn ( Opcodes . ACONST_NULL ) ; } else { mv . visitLdcInsn ( value ) ; }


signature:
public class GeneratorAdapter { /** * Generates the instruction to push the given value on the stack .
 * @ param value
 * the value to be pushed on the stack . */
public void push ( final Type value ) { } }

implementation: if ( value == null ) { mv . visitInsn ( Opcodes . ACONST_NULL ) ; } else { switch ( value . getSort ( ) ) { case Type . BOOLEAN : mv . visitFieldInsn ( Opcodes . GETSTATIC , "java/lang/Boolean" , "TYPE" , CLDESC ) ; break ; case Type . CHAR : mv . visitFieldInsn ( Opcodes . GETSTATIC , "java/lang/Character" , "TYPE" , CLDESC ) ; break ; case Type . BYTE : mv . visitFieldInsn ( Opcodes . GETSTATIC , "java/lang/Byte" , "TYPE" , CLDESC ) ; break ; case Type . SHORT : mv . visitFieldInsn ( Opcodes . GETSTATIC , "java/lang/Short" , "TYPE" , CLDESC ) ; break ; case Type . INT : mv . visitFieldInsn ( Opcodes . GETSTATIC , "java/lang/Integer" , "TYPE" , CLDESC ) ; break ; case Type . FLOAT : mv . visitFieldInsn ( Opcodes . GETSTATIC , "java/lang/Float" , "TYPE" , CLDESC ) ; break ; case Type . LONG : mv . visitFieldInsn ( Opcodes . GETSTATIC , "java/lang/Long" , "TYPE" , CLDESC ) ; break ; case Type . DOUBLE : mv . visitFieldInsn ( Opcodes . GETSTATIC , "java/lang/Double" , "TYPE" , CLDESC ) ; break ; default : mv . visitLdcInsn ( value ) ; } }


signature:
public class GeneratorAdapter { /** * Returns the index of the given method argument in the frame ' s local
 * variables array .
 * @ param arg
 * the index of a method argument .
 * @ return the index of the given method argument in the frame ' s local
 * variables array . */
private int getArgIndex ( final int arg ) { } }

implementation: int index = ( access & Opcodes . ACC_STATIC ) == 0 ? 1 : 0 ; for ( int i = 0 ; i < arg ; i ++ ) { index += argumentTypes [ i ] . getSize ( ) ; } return index ;


signature:
public class GeneratorAdapter { /** * Generates the instruction to push a local variable on the stack .
 * @ param type
 * the type of the local variable to be loaded .
 * @ param index
 * an index in the frame ' s local variables array . */
private void loadInsn ( final Type type , final int index ) { } }

implementation: mv . visitVarInsn ( type . getOpcode ( Opcodes . ILOAD ) , index ) ;


signature:
public class GeneratorAdapter { /** * Generates the instruction to store the top stack value in a local
 * variable .
 * @ param type
 * the type of the local variable to be stored .
 * @ param index
 * an index in the frame ' s local variables array . */
private void storeInsn ( final Type type , final int index ) { } }

implementation: mv . visitVarInsn ( type . getOpcode ( Opcodes . ISTORE ) , index ) ;


signature:
public class GeneratorAdapter { /** * Generates the instructions to load the given method arguments on the
 * stack .
 * @ param arg
 * the index of the first method argument to be loaded .
 * @ param count
 * the number of method arguments to be loaded . */
public void loadArgs ( final int arg , final int count ) { } }

implementation: int index = getArgIndex ( arg ) ; for ( int i = 0 ; i < count ; ++ i ) { Type t = argumentTypes [ arg + i ] ; loadInsn ( t , index ) ; index += t . getSize ( ) ; }


signature:
public class GeneratorAdapter { /** * Generates the instructions to load all the method arguments on the stack ,
 * as a single object array . */
public void loadArgArray ( ) { } }

implementation: push ( argumentTypes . length ) ; newArray ( OBJECT_TYPE ) ; for ( int i = 0 ; i < argumentTypes . length ; i ++ ) { dup ( ) ; push ( i ) ; loadArg ( i ) ; box ( argumentTypes [ i ] ) ; arrayStore ( OBJECT_TYPE ) ; }


signature:
public class GeneratorAdapter { /** * Generates the instruction to load the given local variable on the stack .
 * @ param local
 * a local variable identifier , as returned by
 * { @ link LocalVariablesSorter # newLocal ( Type ) newLocal ( ) } .
 * @ param type
 * the type of this local variable . */
public void loadLocal ( final int local , final Type type ) { } }

implementation: setLocalType ( local , type ) ; loadInsn ( type , local ) ;


signature:
public class GeneratorAdapter { /** * Generates the instruction to store the top stack value in the given local
 * variable .
 * @ param local
 * a local variable identifier , as returned by
 * { @ link LocalVariablesSorter # newLocal ( Type ) newLocal ( ) } .
 * @ param type
 * the type of this local variable . */
public void storeLocal ( final int local , final Type type ) { } }

implementation: setLocalType ( local , type ) ; storeInsn ( type , local ) ;


signature:
public class GeneratorAdapter { /** * Generates the instructions to swap the top two stack values .
 * @ param prev
 * type of the top - 1 stack value .
 * @ param type
 * type of the top stack value . */
public void swap ( final Type prev , final Type type ) { } }

implementation:
if ( type . getSize ( ) == 1 ) { if ( prev . getSize ( ) == 1 ) { swap ( ) ; // same as dupX1 ( ) , pop ( ) ;
} else { dupX2 ( ) ; pop ( ) ; } } else { if ( prev . getSize ( ) == 1 ) { dup2X1 ( ) ; pop2 ( ) ; } else { dup2X2 ( ) ; pop2 ( ) ; } }


signature: public class GeneratorAdapter { private static Type getBoxedType ( final Type type ) { } }

implementation: switch ( type . getSort ( ) ) { case Type . BYTE : return BYTE_TYPE ; case Type . BOOLEAN : return BOOLEAN_TYPE ; case Type . SHORT : return SHORT_TYPE ; case Type . CHAR : return CHARACTER_TYPE ; case Type . INT : return INTEGER_TYPE ; case Type . FLOAT : return FLOAT_TYPE ; case Type . LONG : return LONG_TYPE ; case Type . DOUBLE : return DOUBLE_TYPE ; } return type ;


signature:
public class GeneratorAdapter { /** * Generates the instructions to box the top stack value . This value is
 * replaced by its boxed equivalent on top of the stack .
 * @ param type
 * the type of the top stack value . */
public void box ( final Type type ) { } }

implementation:
if ( type . getSort ( ) == Type . OBJECT || type . getSort ( ) == Type . ARRAY ) { return ; } if ( type == Type . VOID_TYPE ) { push ( ( String ) null ) ; } else { Type boxed = getBoxedType ( type ) ; newInstance ( boxed ) ; if ( type . getSize ( ) == 2 ) { // Pp - > Ppo - > oPpo - > ooPpo - > ooPp - > o
dupX2 ( ) ; dupX2 ( ) ; pop ( ) ; } else { // p - > po - > opo - > oop - > o
dupX1 ( ) ; swap ( ) ; } invokeConstructor ( boxed , new Method ( "<init>" , Type . VOID_TYPE , new Type [ ] { type } ) ) ; }


signature:
public class GeneratorAdapter { /** * Generates the instructions to box the top stack value using Java 5 ' s
 * valueOf ( ) method . This value is replaced by its boxed equivalent on top
 * of the stack .
 * @ param type
 * the type of the top stack value . */
public void valueOf ( final Type type ) { } }

implementation: if ( type . getSort ( ) == Type . OBJECT || type . getSort ( ) == Type . ARRAY ) { return ; } if ( type == Type . VOID_TYPE ) { push ( ( String ) null ) ; } else { Type boxed = getBoxedType ( type ) ; invokeStatic ( boxed , new Method ( "valueOf" , boxed , new Type [ ] { type } ) ) ; }


signature:
public class GeneratorAdapter { /** * Generates the instructions to unbox the top stack value . This value is
 * replaced by its unboxed equivalent on top of the stack .
 * @ param type
 * the type of the top stack value . */
public void unbox ( final Type type ) { } }

implementation: Type t = NUMBER_TYPE ; Method sig = null ; switch ( type . getSort ( ) ) { case Type . VOID : return ; case Type . CHAR : t = CHARACTER_TYPE ; sig = CHAR_VALUE ; break ; case Type . BOOLEAN : t = BOOLEAN_TYPE ; sig = BOOLEAN_VALUE ; break ; case Type . DOUBLE : sig = DOUBLE_VALUE ; break ; case Type . FLOAT : sig = FLOAT_VALUE ; break ; case Type . LONG : sig = LONG_VALUE ; break ; case Type . INT : case Type . SHORT : case Type . BYTE : sig = INT_VALUE ; } if ( sig == null ) { checkCast ( type ) ; } else { checkCast ( t ) ; invokeVirtual ( t , sig ) ; }


signature:
public class GeneratorAdapter { /** * Generates the instructions to jump to a label based on the comparison of
 * the top two stack values .
 * @ param type
 * the type of the top two stack values .
 * @ param mode
 * how these values must be compared . One of EQ , NE , LT , GE , GT ,
 * LE .
 * @ param label
 * where to jump if the comparison result is < tt > true < / tt > . */
public void ifCmp ( final Type type , final int mode , final Label label ) { } }

implementation: switch ( type . getSort ( ) ) { case Type . LONG : mv . visitInsn ( Opcodes . LCMP ) ; break ; case Type . DOUBLE : mv . visitInsn ( mode == GE || mode == GT ? Opcodes . DCMPL : Opcodes . DCMPG ) ; break ; case Type . FLOAT : mv . visitInsn ( mode == GE || mode == GT ? Opcodes . FCMPL : Opcodes . FCMPG ) ; break ; case Type . ARRAY : case Type . OBJECT : switch ( mode ) { case EQ : mv . visitJumpInsn ( Opcodes . IF_ACMPEQ , label ) ; return ; case NE : mv . visitJumpInsn ( Opcodes . IF_ACMPNE , label ) ; return ; } throw new IllegalArgumentException ( "Bad comparison for type " + type ) ; default : int intOp = - 1 ; switch ( mode ) { case EQ : intOp = Opcodes . IF_ICMPEQ ; break ; case NE : intOp = Opcodes . IF_ICMPNE ; break ; case GE : intOp = Opcodes . IF_ICMPGE ; break ; case LT : intOp = Opcodes . IF_ICMPLT ; break ; case LE : intOp = Opcodes . IF_ICMPLE ; break ; case GT : intOp = Opcodes . IF_ICMPGT ; break ; } mv . visitJumpInsn ( intOp , label ) ; return ; } mv . visitJumpInsn ( mode , label ) ;


signature:
public class GeneratorAdapter { /** * Generates the instructions for a switch statement .
 * @ param keys
 * the switch case keys .
 * @ param generator
 * a generator to generate the code for the switch cases . */
public void tableSwitch ( final int [ ] keys , final TableSwitchGenerator generator ) { } }

implementation: float density ; if ( keys . length == 0 ) { density = 0 ; } else { density = ( float ) keys . length / ( keys [ keys . length - 1 ] - keys [ 0 ] + 1 ) ; } tableSwitch ( keys , generator , density >= 0.5f ) ;


signature:
public class GeneratorAdapter { /** * Generates the instructions for a switch statement .
 * @ param keys
 * the switch case keys .
 * @ param generator
 * a generator to generate the code for the switch cases .
 * @ param useTable
 * < tt > true < / tt > to use a TABLESWITCH instruction , or
 * < tt > false < / tt > to use a LOOKUPSWITCH instruction . */
public void tableSwitch ( final int [ ] keys , final TableSwitchGenerator generator , final boolean useTable ) { } }

implementation: for ( int i = 1 ; i < keys . length ; ++ i ) { if ( keys [ i ] < keys [ i - 1 ] ) { throw new IllegalArgumentException ( "keys must be sorted ascending" ) ; } } Label def = newLabel ( ) ; Label end = newLabel ( ) ; if ( keys . length > 0 ) { int len = keys . length ; int min = keys [ 0 ] ; int max = keys [ len - 1 ] ; int range = max - min + 1 ; if ( useTable ) { Label [ ] labels = new Label [ range ] ; Arrays . fill ( labels , def ) ; for ( int i = 0 ; i < len ; ++ i ) { labels [ keys [ i ] - min ] = newLabel ( ) ; } mv . visitTableSwitchInsn ( min , max , def , labels ) ; for ( int i = 0 ; i < range ; ++ i ) { Label label = labels [ i ] ; if ( label != def ) { mark ( label ) ; generator . generateCase ( i + min , end ) ; } } } else { Label [ ] labels = new Label [ len ] ; for ( int i = 0 ; i < len ; ++ i ) { labels [ i ] = newLabel ( ) ; } mv . visitLookupSwitchInsn ( def , keys , labels ) ; for ( int i = 0 ; i < len ; ++ i ) { mark ( labels [ i ] ) ; generator . generateCase ( keys [ i ] , end ) ; } } } mark ( def ) ; generator . generateDefault ( ) ; mark ( end ) ;


signature:
public class GeneratorAdapter { /** * Generates a get field or set field instruction .
 * @ param opcode
 * the instruction ' s opcode .
 * @ param ownerType
 * the class in which the field is defined .
 * @ param name
 * the name of the field .
 * @ param fieldType
 * the type of the field . */
private void fieldInsn ( final int opcode , final Type ownerType , final String name , final Type fieldType ) { } }

implementation: mv . visitFieldInsn ( opcode , ownerType . getInternalName ( ) , name , fieldType . getDescriptor ( ) ) ;


signature:
public class GeneratorAdapter { /** * Generates the instruction to push the value of a static field on the
 * stack .
 * @ param owner
 * the class in which the field is defined .
 * @ param name
 * the name of the field .
 * @ param type
 * the type of the field . */
public void getStatic ( final Type owner , final String name , final Type type ) { } }

implementation: fieldInsn ( Opcodes . GETSTATIC , owner , name , type ) ;


signature:
public class GeneratorAdapter { /** * Generates the instruction to store the top stack value in a static field .
 * @ param owner
 * the class in which the field is defined .
 * @ param name
 * the name of the field .
 * @ param type
 * the type of the field . */
public void putStatic ( final Type owner , final String name , final Type type ) { } }

implementation: fieldInsn ( Opcodes . PUTSTATIC , owner , name , type ) ;


signature:
public class GeneratorAdapter { /** * Generates the instruction to push the value of a non static field on the
 * stack .
 * @ param owner
 * the class in which the field is defined .
 * @ param name
 * the name of the field .
 * @ param type
 * the type of the field . */
public void getField ( final Type owner , final String name , final Type type ) { } }

implementation: fieldInsn ( Opcodes . GETFIELD , owner , name , type ) ;


signature:
public class GeneratorAdapter { /** * Generates the instruction to store the top stack value in a non static
 * field .
 * @ param owner
 * the class in which the field is defined .
 * @ param name
 * the name of the field .
 * @ param type
 * the type of the field . */
public void putField ( final Type owner , final String name , final Type type ) { } }

implementation: fieldInsn ( Opcodes . PUTFIELD , owner , name , type ) ;


signature:
public class GeneratorAdapter { /** * Generates an invoke method instruction .
 * @ param opcode
 * the instruction ' s opcode .
 * @ param type
 * the class in which the method is defined .
 * @ param method
 * the method to be invoked . */
private void invokeInsn ( final int opcode , final Type type , final Method method , final boolean itf ) { } }

implementation: String owner = type . getSort ( ) == Type . ARRAY ? type . getDescriptor ( ) : type . getInternalName ( ) ; mv . visitMethodInsn ( opcode , owner , method . getName ( ) , method . getDescriptor ( ) , itf ) ;


signature:
public class GeneratorAdapter { /** * Generates the instruction to invoke a normal method .
 * @ param owner
 * the class in which the method is defined .
 * @ param method
 * the method to be invoked . */
public void invokeVirtual ( final Type owner , final Method method ) { } }

implementation: invokeInsn ( Opcodes . INVOKEVIRTUAL , owner , method , false ) ;


signature:
public class GeneratorAdapter { /** * Generates the instruction to invoke a constructor .
 * @ param type
 * the class in which the constructor is defined .
 * @ param method
 * the constructor to be invoked . */
public void invokeConstructor ( final Type type , final Method method ) { } }

implementation: invokeInsn ( Opcodes . INVOKESPECIAL , type , method , false ) ;


signature:
public class GeneratorAdapter { /** * Generates the instruction to invoke a static method .
 * @ param owner
 * the class in which the method is defined .
 * @ param method
 * the method to be invoked . */
public void invokeStatic ( final Type owner , final Method method ) { } }

implementation: invokeInsn ( Opcodes . INVOKESTATIC , owner , method , false ) ;


signature:
public class GeneratorAdapter { /** * Generates the instruction to invoke an interface method .
 * @ param owner
 * the class in which the method is defined .
 * @ param method
 * the method to be invoked . */
public void invokeInterface ( final Type owner , final Method method ) { } }

implementation: invokeInsn ( Opcodes . INVOKEINTERFACE , owner , method , true ) ;


signature:
public class GeneratorAdapter { /** * Generates the instructions to create and throw an exception . The
 * exception class must have a constructor with a single String argument .
 * @ param type
 * the class of the exception to be thrown .
 * @ param msg
 * the detailed message of the exception . */
public void throwException ( final Type type , final String msg ) { } }

implementation: newInstance ( type ) ; dup ( ) ; push ( msg ) ; invokeConstructor ( type , Method . getMethod ( "void <init> (String)" ) ) ; throwException ( ) ;


signature:
public class GeneratorAdapter { /** * Generates the instruction to check that the top stack value is of the
 * given type .
 * @ param type
 * a class or interface type . */
public void checkCast ( final Type type ) { } }

implementation: if ( ! type . equals ( OBJECT_TYPE ) ) { typeInsn ( Opcodes . CHECKCAST , type ) ; }


signature:
public class FieldMatcher { /** * 构建一个字段匹配器 .
 * @ param actived 需要保留的字段 , 必须是合法的正则表达式 , 可以为null
 * @ param locked 需要忽略的字段 , 必须是合法的正则表达式 , 可以为null
 * @ param ignoreNull 是否忽略空值
 * @ return 字段 / 属性匹配器 */
public static FieldMatcher make ( String actived , String locked , boolean ignoreNull ) { } }

implementation: FieldMatcher fm = new FieldMatcher ( ) ; fm . ignoreNull = ignoreNull ; if ( ! Strings . isBlank ( actived ) ) fm . actived = Regex . getPattern ( actived ) ; if ( ! Strings . isBlank ( locked ) ) fm . locked = Regex . getPattern ( locked ) ; return fm ;


signature:
public class FieldMatcher { /** * 仅配置是否忽略 @ Id标注的属性 , 然后生成实例
 * @ param ignoreId 是否忽略 @ Id标注的属性
 * @ return 字段匹配器实例 */
public static FieldMatcher create ( boolean ignoreId ) { } }

implementation: FieldMatcher fm = new FieldMatcher ( ) ; fm . ignoreId = ignoreId ; return fm ;


signature:
public class FieldMatcher { /** * 构建一个字段匹配器 .
 * @ param actived 需要保留的字段 , 必须是合法的正则表达式 , 可以为null
 * @ param locked 需要忽略的字段 , 必须是合法的正则表达式 , 可以为null
 * @ param ignoreNull 是否忽略空值
 * @ param ignoreZero 是否忽略零值 , 仅针对数值类型
 * @ param ignoreDate 是否忽略java . util . Date及其子类的属性
 * @ param ignoreId 是否忽略 @ Id标注的属性
 * @ param ignoreName 是否忽略 @ Name标注的属性
 * @ param ignorePk 是否忽略 @ Pk引用的属性
 * @ return 字段 / 属性匹配器 */
public static FieldMatcher make ( String actived , String locked , boolean ignoreNull , boolean ignoreZero , boolean ignoreDate , boolean ignoreId , boolean ignoreName , boolean ignorePk , boolean ignoreBlankStr ) { } }

implementation: FieldMatcher fm = make ( actived , locked , ignoreNull ) ; fm . ignoreZero = ignoreZero ; fm . ignoreDate = ignoreDate ; fm . ignoreId = ignoreId ; fm . ignoreName = ignoreName ; fm . ignorePk = ignorePk ; fm . ignoreBlankStr = ignoreBlankStr ; return fm ;


signature:
public class FieldMatcher { /** * 匹配顺序 locked - - actived - - ignoreNull
 * @ param str 需要匹配的字段名称
 * @ return true , 如果可用 */
public boolean match ( String str ) { } }

implementation: if ( null != locked && locked . matcher ( str ) . find ( ) ) { return false ; } if ( null != actived && ! actived . matcher ( str ) . find ( ) ) { return false ; } return true ;


signature:
public class FieldMatcher { /** * 设置过滤可用字段 / 属性的正则表达式
 * @ param actived 正则表达式
 * @ return 原对象 , 用于链式调用 */
public FieldMatcher setActived ( String actived ) { } }

implementation: if ( actived != null ) this . actived = Regex . getPattern ( actived ) ; else this . actived = null ; return this ;


signature:
public class FieldMatcher { /** * 设置过滤不可用字段 / 属性的正则表达式
 * @ param locked 正则表达式
 * @ return 原对象 , 用于链式调用 */
public FieldMatcher setLocked ( String locked ) { } }

implementation: if ( locked != null ) this . locked = Regex . getPattern ( locked ) ; else this . locked = null ; return this ;


signature:
public class Sockets { /** * 向某主机发送一些字节内容 , 并将返回写入输出流
 * @ param host
 * 主机
 * @ param port
 * 端口
 * @ param ins
 * 发送的内容
 * @ param ops
 * 主机返回的输入流 */
public static void send ( String host , int port , InputStream ins , OutputStream ops , int timeout ) { } }

implementation:
Socket socket = null ; try { socket = new Socket ( ) ; socket . connect ( new InetSocketAddress ( host , port ) , timeout ) ; // 发送关闭命令
OutputStream sOut = socket . getOutputStream ( ) ; Streams . write ( sOut , ins ) ; sOut . flush ( ) ; // 接收服务器的反馈
if ( ! socket . isClosed ( ) ) { InputStream sReturn = socket . getInputStream ( ) ; Streams . write ( ops , sReturn ) ; } } catch ( IOException e ) { throw Lang . wrapThrow ( e ) ; } finally { Streams . safeClose ( ins ) ; Streams . safeClose ( ops ) ; safeClose ( socket ) ; }


signature:
public class Sockets { /** * 向某主机发送一段文本 , 并将主机的返回作为文本返回
 * @ param host
 * 主机
 * @ param port
 * 端口
 * @ param text
 * 发送的内容
 * @ return 主机返回的文本 */
public static String sendText ( String host , int port , String text ) { } }

implementation: StringBuilder sb = new StringBuilder ( ) ; send ( host , port , Lang . ins ( text ) , Lang . ops ( sb ) ) ; return sb . toString ( ) ;


signature:
public class Sockets { /** * 监听本地某一个端口 , 仅仅收到某一个特殊命令时 , 才会开始一个动作 。
 * 并且原生的 , 它支持输入 " close | stop | bye | exit " 来结束本地监听
 * @ param port
 * 要监听的端口
 * @ param line
 * 命令名称
 * @ param action
 * 动作执行类 */
public static void localListenOneAndStop ( int port , String line , SocketAction action ) { } }

implementation: Map < String , SocketAction > actions = createActions ( ) ; actions . put ( line , action ) ; actions . put ( "$:^(close|stop|bye|exit)$" , doClose ( ) ) ; localListenByLine ( port , actions ) ;


signature:
public class Sockets { /** * 监听本地某一个端口 , 仅仅收到某一个特殊命令时 , 才会开始一个动作 。
 * @ param port
 * 要监听的端口
 * @ param line
 * 命令名称
 * @ param action
 * 动作执行类 */
public static void localListenOne ( int port , String line , SocketAction action ) { } }

implementation: Map < String , SocketAction > actions = createActions ( ) ; actions . put ( line , action ) ; localListenByLine ( port , actions ) ;


signature:
public class Sockets { /** * 简化了一个参数 , 采用默认线程数
 * @ see org . nutz . lang . socket . Sockets # localListenByLine ( int , Map , int ) */
public static void localListenByLine ( int port , Map < String , SocketAction > actions ) { } }

implementation: Sockets . localListenByLine ( port , actions , DEFAULT_POOL_SIZE ) ;


signature:
public class Sockets { /** * 监听本地某一个端口 , 根据用户输入的命令的不同 , 执行不同的操作
 * 当然 , 你如果想让一个过程处理多种命令 , 请给的 key 前用 " REGEX : " 作为前缀 , 后面用一个正则表达式 来表示你的你要的匹配的命令 < br >
 * " REGEX : ! " 开头的 , 表示后面的正则表达式是一个命令过滤 , 所有没有匹配上的命令都会被处理
 * @ param port
 * 要监听的端口
 * @ param actions
 * 动作执行类映射表
 * @ param poolSize
 * 针对一个 CPU 你打算启动几个处理线程
 * @ see org . nutz . lang . socket . Sockets # localListenByLine ( int , Map ,
 * ExecutorService ) */
public static void localListenByLine ( int port , Map < String , SocketAction > actions , int poolSize ) { } }

implementation: Sockets . localListenByLine ( port , actions , Executors . newFixedThreadPool ( Runtime . getRuntime ( ) . availableProcessors ( ) * poolSize ) ) ;


signature:
public class Sockets { /** * 监听本地某一个端口 , 根据用户输入的命令的不同 , 执行不同的操作
 * 当然 , 你如果想让一个过程处理多种命令 , 请给的 key 前用 " REGEX : " 作为前缀 , 后面用一个正则表达式 来表示你的你要的匹配的命令 < br >
 * " REGEX : ! " 开头的 , 表示后面的正则表达式是一个命令过滤 , 所有没有匹配上的命令都会被处理
 * @ param port
 * 要监听的端口
 * @ param actions
 * 动作执行类映射表
 * @ param service
 * 线程池的实现类 */
public static void localListenByLine ( int port , Map < String , SocketAction > actions , ExecutorService service ) { } }

implementation: localListen ( port , actions , service , SocketAtom . class ) ;


signature:
public class Sockets { /** * 监听本地某一个端口 , 根据用户输入的命令的不同 , 执行不同的操作
 * 当然 , 你如果想让一个过程处理多种命令 , 请给的 key 前用 " REGEX : " 作为前缀 , 后面用一个正则表达式 来表示你的你要的匹配的命令 < br >
 * " REGEX : ! " 开头的 , 表示后面的正则表达式是一个命令过滤 , 所有没有匹配上的命令都会被处理
 * @ param port
 * 要监听的端口
 * @ param actions
 * 动作执行类映射表
 * @ param service
 * 线程池的实现类 */
@ SuppressWarnings ( "rawtypes" ) public static void localListen ( int port , Map < String , SocketAction > actions , ExecutorService service , Class < ? extends SocketAtom > klass ) { } }

implementation:
try { // 建立动作映射表
SocketActionTable saTable = new SocketActionTable ( actions ) ; // 初始化 socket 接口
final ServerSocket server ; try { server = new ServerSocket ( port ) ; } catch ( IOException e1 ) { throw Lang . wrapThrow ( e1 ) ; } if ( log . isInfoEnabled ( ) ) log . infof ( "Local socket is up at :%d with %d action ready" , port , actions . size ( ) ) ; final Context context = Lang . context ( ) ; context . set ( "stop" , false ) ; /* * 启动一个守护线程 , 判断是否该关闭 socket 服务 */
( new Thread ( ) { @ Override public void run ( ) { setName ( "Nutz.Sockets monitor thread" ) ; while ( true ) { try { Thread . sleep ( 1000 ) ; if ( context . getBoolean ( "stop" ) ) { try { server . close ( ) ; } catch ( Throwable e ) { } return ; } } catch ( Throwable e ) { } } } } ) . start ( ) ; /* * 准备 SocketAtom 的生成器 */
Borning borning = Mirror . me ( klass ) . getBorningByArgTypes ( Context . class , Socket . class , SocketActionTable . class ) ; if ( borning == null ) { log . error ( "boring == null !!!!" ) ; return ; } /* * 进入监听循环 */
while ( ! context . getBoolean ( "stop" ) ) { try { if ( log . isDebugEnabled ( ) ) log . debug ( "Waiting for new socket" ) ; Socket socket = server . accept ( ) ; if ( context . getBoolean ( "stop" ) ) { Sockets . safeClose ( socket ) ; break ; // 监护线程也许还是睡觉 , 还没来得及关掉哦 , 所以自己检查一下
} if ( log . isDebugEnabled ( ) ) log . debug ( "accept a new socket, create new SocketAtom to handle it ..." ) ; Runnable runnable = ( Runnable ) borning . born ( new Object [ ] { context , socket , saTable } ) ; service . execute ( runnable ) ; } catch ( Throwable e ) { log . info ( "Throwable catched!! maybe ask to exit" , e ) ; } } if ( ! server . isClosed ( ) ) { try { server . close ( ) ; } catch ( Throwable e ) { } } log . info ( "Seem stop signal was got, wait 15 for all running thread" ) ; try { service . shutdown ( ) ; service . awaitTermination ( 15 , TimeUnit . SECONDS ) ; } catch ( InterruptedException e ) { } try { service . shutdownNow ( ) ; } catch ( Throwable e2 ) { } } catch ( RuntimeException e ) { throw e ; } finally { if ( log . isInfoEnabled ( ) ) log . info ( "Stop services ..." ) ; service . shutdown ( ) ; } if ( log . isInfoEnabled ( ) ) log . infof ( "Local socket is down for :%d" , port ) ;


signature:
public class Sockets { /** * 安全关闭套接层 , 容忍 null
 * @ param socket
 * 套接层
 * @ return 一定会返回 null */
public static Socket safeClose ( Socket socket ) { } }

implementation: if ( null != socket ) try { socket . close ( ) ; socket = null ; } catch ( IOException e ) { throw Lang . wrapThrow ( e ) ; } return null ;


signature:
public class DaoSupport { /** * 设置一个新的 Sql 管理接口实例
 * @ param sqls
 * Sql 管理接口实例 */
public void setSqlManager ( SqlManager sqls ) { } }

implementation: this . sqlManager = sqls ; if ( sqls != null ) { int count = sqls . count ( ) ; log . debug ( "SqlManager Sql count=" + count ) ; }


signature:
public class DaoSupport { /** * 设置一个新的 Dao 运行器
 * @ param runner
 * 运行器对象 */
public void setRunner ( DaoRunner runner ) { } }

implementation: this . runner = runner ; if ( runner instanceof NutDaoRunner ) { ( ( NutDaoRunner ) runner ) . setMeta ( meta ) ; }


signature:
public class DaoSupport { /** * 设置一个新的 Dao 语句执行器
 * @ param executor
 * Dao 语句执行器对象 */
public void setExecutor ( DaoExecutor executor ) { } }

implementation: this . executor = executor ; if ( executor instanceof NutDaoExecutor ) { ( ( NutDaoExecutor ) executor ) . setMeta ( meta ) ; ( ( NutDaoExecutor ) executor ) . setExpert ( expert ) ; }


signature:
public class AbstractSqlManager { /** * 执行根据字符流来加载sql内容的操作
 * @ param reader
 * @ throws IOException */
protected void loadSQL ( Reader reader ) throws IOException { } }

implementation: BufferedReader bufferedReader = null ; try { if ( reader instanceof BufferedReader ) bufferedReader = ( BufferedReader ) reader ; else bufferedReader = new BufferedReader ( reader ) ; SqlFileBuilder p = new SqlFileBuilder ( bufferedReader ) ; _sql_keys = new ArrayList < String > ( p . map . size ( ) ) ; for ( Entry < String , String > en : p . entrySet ( ) ) { addSql ( en . getKey ( ) , Strings . trim ( en . getValue ( ) ) ) ; } } finally { Streams . safeClose ( bufferedReader ) ; }


signature:
public class EntityService { /** * 设置新的实体类型 , 极少调用
 * @ param classOfT */
@ SuppressWarnings ( "unchecked" ) public < C extends T > void setEntityType ( Class < C > classOfT ) { } }

implementation: mirror = ( Mirror < T > ) Mirror . me ( classOfT ) ;


signature:
public class EntityService { /** * 根据条件分页查询
 * @ param cnd
 * 查询条件
 * @ param pager
 * 分页
 * @ return 查询结果 */
public List < T > query ( Condition cnd , Pager pager ) { } }

implementation: return ( List < T > ) dao ( ) . query ( getEntityClass ( ) , cnd , pager ) ;


signature:
public class EntityService { /** * 批量更新
 * @ param chain
 * 设置值的键值对
 * @ param cnd
 * 需要更新的条件语句 */
public int update ( Chain chain , Condition cnd ) { } }

implementation: return dao ( ) . update ( getEntityClass ( ) , chain , cnd ) ;


signature:
public class EntityService { /** * 更新 @ ManyMany关联表中的数据
 * @ param regex
 * 关联字段的匹配正则表达式 , 如果为null则代表全部
 * @ param chain
 * 键值对
 * @ param cnd
 * 条件语句 */
public int updateRelation ( String regex , Chain chain , Condition cnd ) { } }

implementation: return dao ( ) . updateRelation ( getEntityClass ( ) , regex , chain , cnd ) ;


signature:
public class EntityService { /** * 对一组对象进行迭代 , 这个接口函数非常适用于很大的数据量的集合 , 因为你不可能把他们都读到内存里
 * @ param cnd
 * WHERE 条件 。 如果为 null , 将获取全部数据 , 顺序为数据库原生顺序
 * @ param callback
 * 处理回调
 * @ return 一共迭代的数量 */
public int each ( Condition cnd , Each < T > callback ) { } }

implementation: return dao ( ) . each ( getEntityClass ( ) , cnd , callback ) ;


signature:
public class EntityService { /** * 对某一个对象字段 , 进行计算 。
 * @ param funcName
 * 计算函数名 , 请确保你的数据库是支持这个函数的
 * @ param fieldName
 * 对象 java 字段名
 * @ return 计算结果 */
public int func ( String funcName , String fieldName ) { } }

implementation: return dao ( ) . func ( getEntityClass ( ) , funcName , fieldName ) ;


signature:
public class EntityService { /** * 对某一个对象字段 , 进行计算 。
 * @ param funcName
 * 计算函数名 , 请确保你的数据库是支持这个函数的
 * @ param fieldName
 * 对象 java 字段名
 * @ param cnd
 * 过滤条件
 * @ return 计算结果 */
public int func ( String funcName , String fieldName , Condition cnd ) { } }

implementation: return dao ( ) . func ( getEntityClass ( ) , funcName , fieldName , cnd ) ;


signature:
public class EntityService { /** * 从一个 ResultSet 中获取一个对象 。
 * 因为 Dao 接口可以知道一个 POJO 的映射细节 , 这个函数可以帮你节省一点体力 。
 * @ param rs
 * 结果集
 * @ param fm
 * 字段过滤器
 * @ return 对象 */
public T getObject ( ResultSet rs , FieldMatcher fm ) { } }

implementation: return dao ( ) . getObject ( getEntityClass ( ) , rs , fm ) ;


signature:
public class Nums { /** * 计算尺寸
 * @ param v
 * 要计算的尺寸值的类型可以是
 * < ul >
 * < li > 500 - 整数 , 直接返回
 * < li > . 12 - 浮点 , 相当于一个百分比 , 可以大于 1.0
 * < li > " 12 % " - 百分比 , 相当于 . 12
 * < / ul >
 * @ param base
 * 百分比的基数
 * @ return 根据基数计算后的数值 */
public static double dimension ( String v , double base ) { } }

implementation:
// 试试整型
try { Integer nb = Integer . valueOf ( v ) ; return nb . intValue ( ) ; } catch ( NumberFormatException e ) { } // 试试浮点
try { Double nb = Double . valueOf ( v ) ; return nb . doubleValue ( ) * base ; } catch ( NumberFormatException e ) { } // 百分比
Pattern p = Regex . getPattern ( "^([0-9.]{1,})%$" ) ; Matcher m = p . matcher ( v ) ; if ( m . find ( ) ) { Double nb = Double . valueOf ( m . group ( 1 ) ) ; return ( nb . doubleValue ( ) / 100 ) * base ; } // 靠不知道是啥
throw Lang . makeThrow ( "fail to dimension : " + v ) ;


signature:
public class Nums { /** * @ param str
 * 数字的字符串
 * @ return 字符串的进制
 * @ see org . nutz . lang . Nums . Radix */
public static Radix evalRadix ( String str ) { } }

implementation: if ( str . startsWith ( "0x" ) ) return new Radix ( str . substring ( 2 ) , 16 ) ; if ( str . startsWith ( "0" ) && str . length ( ) > 1 ) return new Radix ( str . substring ( 1 ) , 8 ) ; if ( str . startsWith ( "0b" ) ) return new Radix ( str . substring ( 2 ) , 2 ) ; return new Radix ( str , 10 ) ;


signature:
public class Nums { /** * 将一个字符串变成一个整型数组 , 如果字符串不符合规则 , 对应的元素为 - 1 < br >
 * 比如 :
 * < pre >
 * " 3,4,9 " = > [ 3 , 4 , 9 ]
 * " a , 9,100 " = > [ - 1 , 9 , 100 ]
 * < / pre >
 * @ param str
 * 半角逗号分隔的数字字符串
 * @ return 数组 */
public static int [ ] splitInt ( String str ) { } }

implementation: String [ ] ss = Strings . splitIgnoreBlank ( str ) ; if ( null == ss ) return null ; int [ ] ns = new int [ ss . length ] ; for ( int i = 0 ; i < ns . length ; i ++ ) { try { ns [ i ] = Integer . parseInt ( ss [ i ] ) ; } catch ( NumberFormatException e ) { ns [ i ] = - 1 ; } } return ns ;


signature:
public class Nums { /** * 将一个字符串变成一个浮点数数组 , 如果字符串不符合规则 , 对应的元素为 0.0 < br >
 * 比如 :
 * < pre >
 * " 3,4,9 " = > [ 3.0f , 4.0f , 9.0f ]
 * " a , 9.8,100 " = > [ 0.0f , 9.0f , 100.0f ]
 * < / pre >
 * @ param str
 * 半角逗号分隔的数字字符串
 * @ return 数组 */
public static float [ ] splitFloat ( String str ) { } }

implementation: String [ ] ss = Strings . splitIgnoreBlank ( str ) ; if ( null == ss ) return null ; float [ ] ns = new float [ ss . length ] ; for ( int i = 0 ; i < ns . length ; i ++ ) { try { ns [ i ] = Float . parseFloat ( ss [ i ] ) ; } catch ( NumberFormatException e ) { ns [ i ] = 0.0f ; } } return ns ;


signature:
public class Nums { /** * 整合两个整数数组为一个数组 < b > 这个方法在JDK5不可用 ! ! < b / >
 * @ param arr
 * 整数数组
 * @ param is
 * 变参
 * @ return 新的整合过的数组 */
public static int [ ] join ( int [ ] arr , int ... is ) { } }

implementation: if ( null == arr ) return is ; int length = arr . length + is . length ; int [ ] re = new int [ length ] ; System . arraycopy ( arr , 0 , re , 0 , arr . length ) ; int i = arr . length ; for ( int num : is ) re [ i ++ ] = num ; return re ;


signature:
public class DaoUp { /** * 主动设置Dao实例
 * @ param dao Dao实例 */
public void setDao ( Dao dao ) { } }

implementation: if ( this . dao != null ) log . infof ( "override old Dao=%s by new Dao=%s" , this . dao , dao ) ; this . dao = dao ;


signature:
public class DaoUp { /** * 从一个流读取数据库配置
 * @ param in 输入流 , 包含配置信息
 * @ throws IOException 读取失败是抛出异常 */
public void init ( InputStream in ) throws IOException { } }

implementation: Properties props = new Properties ( ) ; try { props . load ( in ) ; init ( props ) ; } finally { Streams . safeClose ( in ) ; }


signature:
public class DaoUp { /** * 给定一个Properties配置 , 不能为null ! ! ! ! 最起码要包含一个叫url的参数 ! ! !
 * @ param props 配置信息 */
public void init ( Properties props ) { } }

implementation: if ( dao != null ) { throw new IllegalArgumentException ( "DaoUp is inited!!" ) ; } if ( props . size ( ) == 0 ) { throw new IllegalArgumentException ( "DaoUp props size=0!!!" ) ; } DataSource ds = buildDataSource ( props ) ; setDataSource ( ds ) ;


signature:
public class DaoUp { /** * 构建DataSource , 子类可覆盖 . 如果存在Druid , 则使用之 , 否则使用内置的SimpleDataSource
 * @ param props 配置信息
 * @ return 目标DataSource */
protected DataSource buildDataSource ( Properties props ) { } }

implementation: if ( druidFactoryClass != null ) { log . debug ( "build DruidDataSource by props" ) ; Mirror < ? > mirror = Mirror . me ( druidFactoryClass ) ; DataSource ds = ( DataSource ) mirror . invoke ( null , "createDataSource" , props ) ; if ( ! props . containsKey ( "maxWait" ) ) Mirror . me ( ds ) . setValue ( ds , "maxWait" , 15 * 1000 ) ; return ds ; } log . debug ( "build SimpleteDataSource by props" ) ; return SimpleDataSource . createDataSource ( props ) ;


signature:
public class DaoUp { /** * 关闭本DaoUp , 将关闭DataSource并将dao和dataSource置为null ! ! ! < p / >
 * < b > 只能在程序关闭时调用 , 严禁在每次Dao操作后调用 ! ! < / b > */
public synchronized void close ( ) { } }

implementation: if ( dao == null ) return ; log . infof ( "shutdown DaoUp(name=%s)" , name ) ; try { Mirror . me ( dataSource ) . invoke ( dataSource , "close" ) ; } catch ( Throwable e ) { } this . dataSource = null ; this . dao = null ;


signature:
public class AbstractPathView { /** * 为一次 HTTP 请求 , 创建一个可以被表达式引擎接受的上下文对象
 * @ param req
 * HTTP 请求对象
 * @ param obj
 * 入口函数的返回值
 * @ return 上下文对象 */
public static Context createContext ( HttpServletRequest req , Object obj ) { } }

implementation:
Context context = Lang . context ( ) ; // 复制全局的上下文对象
Object globalContext = Mvcs . getServletContext ( ) . getAttribute ( Loading . CONTEXT_NAME ) ; if ( globalContext != null ) { context . putAll ( ( Context ) globalContext ) ; } // 请求对象的属性列表
Map < String , Object > req_attr = new HashMap < String , Object > ( ) ; for ( Enumeration < String > en = req . getAttributeNames ( ) ; en . hasMoreElements ( ) ; ) { String tem = en . nextElement ( ) ; if ( ! tem . startsWith ( "$" ) ) req_attr . put ( tem , req . getAttribute ( tem ) ) ; } context . set ( "a" , req_attr ) ; // 兼容最初的写法
context . set ( "req_attr" , req_attr ) ; ActionContext ac = Mvcs . getActionContext ( ) ; if ( ac != null ) context . set ( "pathargs" , Mvcs . getActionContext ( ) . getPathArgs ( ) ) ; try { HttpSession session = Mvcs . getHttpSession ( false ) ; if ( session != null ) { Map < String , Object > session_attr = new HashMap < String , Object > ( ) ; for ( Enumeration < String > en = session . getAttributeNames ( ) ; en . hasMoreElements ( ) ; ) { String tem = en . nextElement ( ) ; session_attr . put ( tem , session . getAttribute ( tem ) ) ; } context . set ( "session_attr" , session_attr ) ; } } catch ( Throwable e ) { // noop
} // 请求的参数表 , 需要兼容之前的p . 参数 , Fix issue 418
Map < String , String > p = new HashMap < String , String > ( ) ; for ( Object o : Lang . enum2collection ( req . getParameterNames ( ) , new ArrayList < String > ( ) ) ) { String key = ( String ) o ; String value = req . getParameter ( key ) ; p . put ( key , value ) ; context . set ( key , value ) ; // 以支持直接获取请求参数
} context . set ( "p" , p ) ; Map < String , String > u = new HashMap < String , String > ( ) ; AtMap at = Mvcs . getAtMap ( ) ; if ( at != null ) { for ( Object o : at . keys ( ) ) { String key = ( String ) o ; u . put ( key , at . get ( key ) ) ; } context . set ( "u" , u ) ; } // 加入返回对象
if ( null != obj ) context . set ( ViewProcessor . DEFAULT_ATTRIBUTE , obj ) ; return context ;


signature: public class Mvcs { public static Map < String , Object > getLocaleMessage ( String key ) { } }

implementation: Map < String , Map < String , Object > > msgss = getMessageSet ( ) ; if ( null != msgss ) return msgss . get ( key ) ; return null ;


signature:
public class Mvcs { /** * 获取当前请求对象的字符串表
 * @ param req
 * 请求对象
 * @ return 字符串表 */
@ SuppressWarnings ( "unchecked" ) public static Map < String , String > getMessages ( ServletRequest req ) { } }

implementation: return ( Map < String , String > ) req . getAttribute ( MSG ) ;


signature:
public class Mvcs { /** * 获取当前请求对象的字符串表中的某一个字符串
 * @ param req
 * 请求对象
 * @ param key
 * 字符串键值
 * @ return 字符串内容 */
public static String getMessage ( ServletRequest req , String key ) { } }

implementation: Map < String , String > map = getMessages ( req ) ; if ( null != map ) return map . get ( key ) ; return null ;


signature:
public class Mvcs { /** * 设置本地化字符串的键值
 * 如果你用的是 Nutz . Mvc 默认的本地化机制 , 那么你的本地字符串键值 , 相当于一个你目录名 。 < br >
 * 比如 " zh _ CN " 等
 * @ param key
 * 键值
 * @ return 是否设置成功 */
public static boolean setLocalizationKey ( String key ) { } }

implementation: HttpSession sess = getHttpSession ( ) ; if ( null == sess ) return false ; sess . setAttribute ( LOCALE_KEY , key ) ; return true ;


signature:
public class Mvcs { /** * 返回当前加载了的本地化字符串的键值
 * @ return 当前都加载了哪些种字符串的 KEY */
public static Set < String > getLocalizationKeySet ( ) { } }

implementation: Map < String , Map < String , Object > > msgss = getMessageSet ( ) ; if ( null == msgss ) return new HashSet < String > ( ) ; return msgss . keySet ( ) ;


signature:
public class Mvcs { /** * 为当前的 HTTP 请求对象设置一些必要的属性 。 包括 :
 * < ul >
 * < li > 本地化子字符串 = > $ { msg }
 * < li > 应用的路径名 = > $ { base }
 * < / ul >
 * @ param req
 * HTTP 请求对象 */
public static void updateRequestAttributes ( HttpServletRequest req ) { } }

implementation:
// 初始化本次请求的多国语言字符串
Map < String , Map < String , Object > > msgss = getMessageSet ( ) ; if ( msgss == null && ! ctx ( ) . localizations . isEmpty ( ) ) msgss = ctx ( ) . localizations . values ( ) . iterator ( ) . next ( ) ; if ( null != msgss ) { Map < String , Object > msgs = null ; String lKey = Strings . sBlank ( Mvcs . getLocalizationKey ( ) , getDefaultLocalizationKey ( ) ) ; if ( ! Strings . isBlank ( lKey ) ) msgs = msgss . get ( lKey ) ; // 没有设定特殊的 Local 名字 , 随便取一个
if ( null == msgs ) { if ( msgss . size ( ) > 0 ) msgs = msgss . values ( ) . iterator ( ) . next ( ) ; } // 记录到请求中
req . setAttribute ( MSG , msgs ) ; } // 记录一些数据到请求对象中
req . setAttribute ( "base" , req . getContextPath ( ) ) ; req . setAttribute ( "$request" , req ) ;


signature:
public class Mvcs { /** * 获取当前请求的路径 , 并去掉后缀
 * @ param req
 * HTTP 请求对象 */
public static RequestPath getRequestPathObject ( HttpServletRequest req ) { } }

implementation: String url = req . getPathInfo ( ) ; if ( null == url ) url = req . getServletPath ( ) ; return getRequestPathObject ( url ) ;


signature:
public class Mvcs { /** * 获取当前请求的路径 , 并去掉后缀
 * @ param url
 * 请求路径的URL */
public static RequestPath getRequestPathObject ( String url ) { } }

implementation: RequestPath rr = new RequestPath ( ) ; rr . setUrl ( url ) ; if ( null != url ) { int lio = 0 ; if ( ! url . endsWith ( "/" ) ) { int ll = url . lastIndexOf ( '/' ) ; lio = url . lastIndexOf ( '.' ) ; if ( lio < ll ) lio = - 1 ; } if ( lio > 0 ) { rr . setPath ( url . substring ( 0 , lio ) ) ; rr . setSuffix ( url . substring ( lio + 1 ) ) ; } else { rr . setPath ( url ) ; rr . setSuffix ( "" ) ; } } else { rr . setPath ( "" ) ; rr . setSuffix ( "" ) ; } return rr ;


signature:
public class Mvcs { /** * 它将对象序列化成 JSON 字符串 , 并写入 HTTP 响应
 * @ param resp
 * 响应对象
 * @ param obj
 * 数据对象
 * @ param format
 * JSON 的格式化方式
 * @ throws IOException
 * 写入失败 */
public static void write ( HttpServletResponse resp , Object obj , JsonFormat format ) throws IOException { } }

implementation: write ( resp , resp . getWriter ( ) , obj , format ) ;


signature:
public class Mvcs { /** * 设置 Servlet 执行的上下文
 * @ param servletContext
 * Servlet 执行的上下文 */
public static void setServletContext ( ServletContext servletContext ) { } }

implementation: if ( servletContext == null ) { Mvcs . servletContext . remove ( ) ; } if ( def_servletContext == null ) def_servletContext = servletContext ; Mvcs . servletContext . set ( servletContext ) ;


signature:
public class Mvcs { /** * 获取 Servlet 执行的上下文
 * @ return Servlet 执行的上下文 */
public static ServletContext getServletContext ( ) { } }

implementation: ServletContext cnt = servletContext . get ( ) ; if ( cnt != null ) return cnt ; return def_servletContext ;


signature:
public class Mvcs { /** * 重置当前线程所持有的对象 */
public static Context resetALL ( ) { } }

implementation: Context context = reqt ( ) ; NAME . set ( null ) ; ctx ( ) . removeReqCtx ( ) ; return context ;


signature:
public class JsonEntityField { /** * 根据名称获取字段实体 , 默认以set优先 */
public static JsonEntityField eval ( Mirror < ? > mirror , String name , Method getter , Method setter ) { } }

implementation: JsonEntityField jef = new JsonEntityField ( ) ; jef . declaringClass = mirror . getType ( ) ; jef . setGenericType ( getter . getGenericReturnType ( ) ) ; jef . name = name ; jef . ejecting = new EjectByGetter ( getter ) ; jef . injecting = new InjectBySetter ( setter ) ; jef . mirror = Mirror . me ( getter . getReturnType ( ) ) ; return jef ;


signature:
public class ValueEscaper { /** * 设定逃逸方式
 * @ param c
 * 要逃逸的字符
 * @ param s
 * 如何逃逸
 * @ return 自身 */
public ValueEscaper add ( char c , String s ) { } }

implementation: charStack . push ( c ) ; escapeStack . push ( s ) ; return this ;


signature:
public class ValueEscaper { /** * 根据逃逸的设置 , 对传入的字符串进行逃逸
 * @ param cs
 * 字符序列
 * @ return 逃逸后的字符序列 */
public CharSequence escape ( CharSequence cs ) { } }

implementation: StringBuilder sb = new StringBuilder ( ) ; boolean find ; for ( int i = 0 ; i < cs . length ( ) ; i ++ ) { char c = cs . charAt ( i ) ; find = false ; for ( int x = 0 ; x < chars . length ; x ++ ) { if ( c == chars [ x ] ) { sb . append ( escapes [ x ] ) ; find = true ; break ; } } if ( ! find ) sb . append ( c ) ; } return sb ;


signature:
public class ReflectTool { /** * 泛型类clazz , field字段的真实class对象 .
 * @ param clazz 泛型class
 * @ param field 字段
 * @ return */
public static Class < ? > getGenericFieldType ( Class < ? > clazz , Field field ) { } }

implementation: Type fieldType = field . getGenericType ( ) ; return getRealGenericClass ( clazz , fieldType ) ;


signature:
public class ReflectTool { /** * 获取泛型类参数的实际类型 . 例如 Map < String , E > , 获取E实际的类型 .
 * @ param clazz 泛型基类 .
 * @ param type 泛型基类中的某个type
 * @ return */
public static Class < ? > getParameterRealGenericClass ( Class < ? > clazz , Type type , int index ) { } }

implementation: if ( type instanceof ParameterizedType ) { Type [ ] actualTypeArguments = ( ( ParameterizedType ) type ) . getActualTypeArguments ( ) ; return getRealGenericClass ( clazz , actualTypeArguments [ index ] ) ; } return Object . class ;


signature:
public class ReflectTool { /** * 获取泛型类中type变量对应的真实class
 * @ param clazz 泛型基类 .
 * @ param type 泛型基类中的某个type
 * @ return */
public static Class < ? > getRealGenericClass ( Class < ? > clazz , Type type ) { } }

implementation: if ( type instanceof TypeVariable ) { TypeVariable < ? > tv = ( TypeVariable < ? > ) type ; Type genericFieldType = getInheritGenericType ( clazz , tv ) ; if ( genericFieldType != null ) { return Lang . getTypeClass ( genericFieldType ) ; } } return Lang . getTypeClass ( type ) ;


signature:
public class ReflectTool { /** * 获取泛型类中type对应的真实Type
 * @ param clazz
 * @ param type
 * @ return */
public static Type getInheritGenericType ( Class < ? > clazz , Type type ) { } }

implementation: if ( type instanceof TypeVariable ) { TypeVariable < ? > tv = ( TypeVariable < ? > ) type ; return getInheritGenericType ( clazz , tv ) ; } else { return type ; }


signature:
public class ReflectTool { /** * 获取泛型类clazz中某个TypeVariable对应的真实Type .
 * @ param clazz
 * @ param tv
 * @ return */
public static Type getInheritGenericType ( Class < ? > clazz , TypeVariable < ? > tv ) { } }

implementation: Type type = null ; GenericDeclaration gd = tv . getGenericDeclaration ( ) ; do { type = clazz . getGenericSuperclass ( ) ; if ( type == null ) { return null ; } if ( type instanceof ParameterizedType ) { ParameterizedType ptype = ( ParameterizedType ) type ; Type rawType = ptype . getRawType ( ) ; boolean eq = gd . equals ( rawType ) || ( gd instanceof Class && rawType instanceof Class && ( ( Class ) gd ) . isAssignableFrom ( ( Class ) rawType ) ) ; if ( eq ) { TypeVariable < ? > [ ] tvs = gd . getTypeParameters ( ) ; Type [ ] types = ptype . getActualTypeArguments ( ) ; for ( int i = 0 ; i < tvs . length ; i ++ ) { if ( tv . equals ( tvs [ i ] ) ) { return types [ i ] ; } } return null ; } } clazz = Lang . getTypeClass ( type ) ; } while ( type != null ) ; return null ;


signature:
public class Response { /** * 根据Http头的Content - Type获取网页的编码类型 , 如果没有设的话则返回null */
public String getEncodeType ( ) { } }

implementation: String contentType = header . get ( "Content-Type" ) ; if ( null != contentType ) { for ( String tmp : contentType . split ( ";" ) ) { if ( tmp == null ) continue ; tmp = tmp . trim ( ) ; if ( tmp . startsWith ( "charset=" ) ) { tmp = Strings . trim ( tmp . substring ( 8 ) ) . trim ( ) ; if ( tmp . contains ( "," ) ) tmp = tmp . substring ( 0 , tmp . indexOf ( ',' ) ) . trim ( ) ; return tmp ; } } } return Encoding . UTF8 ;


signature:
public class Segments { /** * 根据一个对象填充所有片段的占位符
 * @ param seg
 * 片段
 * @ param obj
 * 对象
 * @ return 填充后的片段对象 */
public static Segment fill ( Segment seg , Object obj ) { } }

implementation: if ( null == obj || null == seg ) return seg ; return seg . setBy ( obj ) ;


signature:
public class Segments { /** * 根据一个文件生成一个代码片段
 * @ param f
 * 文件
 * @ return 片段对象 */
public static Segment read ( File f ) { } }

implementation: String txt = Files . read ( f ) ; return new CharSegment ( txt ) ;


signature:
public class Segments { /** * 根据字符串片段 , 将上下文对象替换对应占位符 。 未赋值的占位符维持原样
 * 比如 :
 * @ param seg
 * 片段对象
 * @ param context
 * 上下文对象
 * @ return 替换后的字符串 */
public static String replace ( Segment seg , Context context ) { } }

implementation:
if ( null == seg ) return null ; // 增加缺失的占位符号
for ( String key : seg . keys ( ) ) if ( ! context . has ( key ) ) context . set ( key , "${" + key + "}" ) ; return seg . render ( context ) . toString ( ) ;


signature:
public class Segments { /** * 根据字符串片段 , 将上下文对象替换对应占位符 。 未赋值的占位符维持原样
 * @ param pattern
 * 字符串片段
 * @ param context
 * 上下文对象
 * @ return 替换后的字符串 */
public static String replace ( String pattern , Context context ) { } }

implementation: if ( null == pattern ) return null ; if ( null == context ) return pattern ; return replace ( new CharSegment ( pattern ) , context ) ;


signature:
public class _Infos { /** * 根据 getter / setter 函数获取一个实体字段信息对象
 * @ param pk
 * 复合主键
 * @ param method
 * 方法 : 可能是 getter 或者是 setter
 * @ return 字段信息对象 */
public static MappingInfo createMapingInfo ( PK pk , Method method ) { } }

implementation: MappingInfo info = create ( MappingInfo . class , method ) ; info . annPK = pk ; info . annColumn = method . getAnnotation ( Column . class ) ; info . annDefine = method . getAnnotation ( ColDefine . class ) ; info . annDefault = method . getAnnotation ( Default . class ) ; info . annId = method . getAnnotation ( Id . class ) ; info . annName = method . getAnnotation ( Name . class ) ; info . annNext = method . getAnnotation ( Next . class ) ; info . annPrev = method . getAnnotation ( Prev . class ) ; info . annReadonly = method . getAnnotation ( Readonly . class ) ; return info ;


signature:
public class _Infos { /** * 根据 Java 字段创建一个实体字段信息对象
 * @ param pk
 * 复合主键
 * @ param field
 * Java 字段
 * @ return 字段信息对象 */
public static MappingInfo createMappingInfo ( PK pk , Field field ) { } }

implementation:
MappingInfo info = create ( MappingInfo . class , field ) ; info . annPK = pk ; info . annColumn = field . getAnnotation ( Column . class ) ; info . annDefine = field . getAnnotation ( ColDefine . class ) ; info . annDefault = field . getAnnotation ( Default . class ) ; info . annId = field . getAnnotation ( Id . class ) ; info . annName = field . getAnnotation ( Name . class ) ; info . annNext = field . getAnnotation ( Next . class ) ; info . annPrev = field . getAnnotation ( Prev . class ) ; info . annReadonly = field . getAnnotation ( Readonly . class ) ; info . columnComment = field . getAnnotation ( Comment . class ) ; // 检查 @ Id和 @ Name的属性类型
if ( info . annId != null ) { if ( ! Mirror . me ( field . getType ( ) ) . isIntLike ( ) ) throw Lang . makeThrow ( DaoException . class , "Field(%s) annotation @Id , but not Number type!!" , field ) ; } if ( info . annName != null ) if ( ! Mirror . me ( field . getType ( ) ) . isStringLike ( ) ) throw Lang . makeThrow ( DaoException . class , "Field(%s) annotation @Name , but not String type!!" , field ) ; // 检查 @ Version属性类型 , 必须是int 、 long 、 short
if ( info . annColumn != null && info . annColumn . version ( ) ) { Mirror < ? > mirror = Mirror . me ( field . getType ( ) ) ; if ( ! mirror . isInt ( ) && ! mirror . isShort ( ) && ! mirror . isLong ( ) ) throw Lang . makeThrow ( DaoException . class , "Field(%s) define version=true , but not  int\\long\\short type!" , field ) ; } return info ;


signature:
public class Castors { /** * 填充 map . < br >
 * 在map中使用hash值来做为key来进行存储
 * @ param klass
 * @ param settingMap
 * @ param replace
 * @ throws InstantiationException
 * @ throws IllegalAccessException
 * @ throws IllegalArgumentException
 * @ throws InvocationTargetException */
private void fillMap ( Class < ? > klass , HashMap < Class < ? > , Method > settingMap , boolean replace ) throws InstantiationException , IllegalAccessException , IllegalArgumentException , InvocationTargetException { } }

implementation: Castor < ? , ? > castor = ( Castor < ? , ? > ) klass . newInstance ( ) ; String key = castor . toString ( ) ; if ( ! map . containsKey ( key ) || replace ) { map . put ( key , castor ) ; } else { castor = map . get ( key ) ; } Method m = settingMap . get ( castor . getClass ( ) ) ; if ( null == m ) { for ( Entry < Class < ? > , Method > entry : settingMap . entrySet ( ) ) { Class < ? > cc = entry . getKey ( ) ; if ( cc . isAssignableFrom ( klass ) ) { m = settingMap . get ( cc ) ; break ; } } } if ( null != m ) m . invoke ( setting , castor ) ;


signature:
public class Castors { /** * 转换一个 POJO 从一个指定的类型到另外的类型
 * @ param src
 * 源对象
 * @ param fromType
 * 源对象类型
 * @ param toType
 * 目标类型
 * @ param args
 * 转换时参数 。 有些 Castor 可能需要这个参数 , 比如 Array2Map
 * @ return 目标对象
 * @ throws FailToCastObjectException
 * 如果没有找到转换器 , 或者转换失败 */
@ SuppressWarnings ( { } }

implementation:
"unchecked" , "rawtypes" } ) public < F , T > T cast ( Object src , Class < F > fromType , Class < T > toType , String ... args ) throws FailToCastObjectException { if ( null == src ) { // 原生数据的默认值
if ( toType . isPrimitive ( ) ) { if ( toType == int . class ) return ( T ) Integer . valueOf ( 0 ) ; else if ( toType == long . class ) return ( T ) Long . valueOf ( 0L ) ; else if ( toType == byte . class ) return ( T ) Byte . valueOf ( ( byte ) 0 ) ; else if ( toType == short . class ) return ( T ) Short . valueOf ( ( short ) 0 ) ; else if ( toType == float . class ) return ( T ) Float . valueOf ( .0f ) ; else if ( toType == double . class ) return ( T ) Double . valueOf ( .0 ) ; else if ( toType == boolean . class ) return ( T ) Boolean . FALSE ; else if ( toType == char . class ) return ( T ) Character . valueOf ( ' ' ) ; throw Lang . impossible ( ) ; } // 是对象 , 直接返回 null
return null ; } if ( fromType == toType || toType == null || fromType == null ) return ( T ) src ; Class < ? > componentType = toType . getComponentType ( ) ; if ( null != componentType && fromType != String . class && componentType . isAssignableFrom ( fromType ) ) { Object array = Array . newInstance ( componentType , 1 ) ; Array . set ( array , 0 , src ) ; return ( T ) array ; } if ( fromType . getName ( ) . equals ( toType . getName ( ) ) ) return ( T ) src ; if ( toType . isAssignableFrom ( fromType ) ) return ( T ) src ; Mirror < ? > from = Mirror . me ( fromType , extractor ) ; Castor c = find ( from , toType ) ; if ( null == c ) throw new FailToCastObjectException ( String . format ( "Can not find castor for '%s'=>'%s' in (%d) because:\n%s" , fromType . getName ( ) , toType . getName ( ) , map . size ( ) , "Fail to find matched castor" ) ) ; if ( Object2Object . class . getName ( ) . equals ( c . getClass ( ) . getName ( ) ) && from . canCastToDirectly ( toType ) ) { // Use language built - in cases
return ( T ) src ; } try { return ( T ) c . cast ( src , toType , args ) ; } catch ( FailToCastObjectException e ) { throw e ; } catch ( Exception e ) { throw new FailToCastObjectException ( String . format ( "Fail to cast from <%s> to <%s> for {%s}" , fromType . getName ( ) , toType . getName ( ) , src ) , Lang . unwrapThrow ( e ) ) ; }


signature:
public class Castors { /** * 获取一个转换器
 * @ param from
 * 源类型
 * @ param to
 * 目标类型
 * @ return 转换器 */
public < F , T > Castor < F , T > find ( Class < F > from , Class < T > to ) { } }

implementation: return find ( Mirror . me ( from ) , to ) ;


signature:
public class Castors { /** * 转换一个 POJO 到另外的类型
 * @ param src
 * 源对象
 * @ param toType
 * 目标类型
 * @ return 目标对象
 * @ throws FailToCastObjectException
 * 如果没有找到转换器 , 或者转换失败 */
public < T > T castTo ( Object src , Class < T > toType ) throws FailToCastObjectException { } }

implementation: return cast ( src , null == src ? null : src . getClass ( ) , toType ) ;


signature:
public class Castors { /** * 判断一个类型是否可以被转换成另外一个类型
 * 判断的依据就是看是否可以直接被转型 , 以及能不能找到一个专有的转换器
 * @ param fromType
 * 起始类型
 * @ param toType
 * 目标类型
 * @ return 是否可以转换 */
public boolean canCast ( Class < ? > fromType , Class < ? > toType ) { } }

implementation: if ( Mirror . me ( fromType ) . canCastToDirectly ( toType ) ) return true ; if ( toType . isArray ( ) && toType . getComponentType ( ) . isAssignableFrom ( fromType ) ) { return true ; } Castor < ? , ? > castor = this . find ( fromType , toType ) ; return ! ( castor instanceof Object2Object ) ;


signature:
public class Castors { /** * 将一个 POJO 转换成字符串
 * @ param src
 * 源对象
 * @ return 字符串 */
public String castToString ( Object src ) { } }

implementation: try { return castTo ( src , String . class ) ; } catch ( FailToCastObjectException e ) { return String . valueOf ( src ) ; }


signature:
public class Jdbcs { /** * 针对一个数据源 , 返回其专属的 JdbcExpert
 * @ param ds
 * 数据源
 * @ return 该数据库的特殊驱动封装类
 * @ see org . nutz . dao . jdbc . Jdbcs # getExpert ( String , String ) */
public static JdbcExpert getExpert ( DataSource ds ) { } }

implementation: log . info ( "Get Connection from DataSource for JdbcExpert, if you lock at here, check your database server and configure" ) ; Connection conn = null ; try { conn = Trans . getConnectionAuto ( ds ) ; DatabaseMetaData meta = conn . getMetaData ( ) ; String pnm = meta . getDatabaseProductName ( ) ; String ver = meta . getDatabaseProductVersion ( ) ; return getExpert ( pnm , ver ) ; } catch ( Throwable e ) { throw Lang . wrapThrow ( e ) ; } finally { Trans . closeConnectionAuto ( conn ) ; }


signature:
public class Jdbcs { /** * 根据数据库的产品名称 , 获取其专属的 Expert
 * 映射的规则存放在 JSON 文件 " nutz _ jdbc _ experts . js " 中 , 你可以通过建立这个文件修改 Nutz 的默认映射规则
 * 比如下面的文件 , 将支持两种数据库
 * < pre >
 * experts : {
 * " postgresql . * " : " org . nutz . dao . impl . jdbc . psql . PostgresqlExpert " ,
 * " mysql . * " : " org . nutz . dao . impl . jdbc . mysql . MysqlExpert "
 * config : {
 * " temp - home " : " ~ / . nutz / tmp / dao / " ,
 * " temp - max " : 2000
 * < / pre >
 * 本函数传入的两个参数将会被 :
 * < pre >
 * String . format ( & quot ; % s : : NUTZ _ JDBC : : % s & quot ; , productName , version ) ;
 * < / pre >
 * 并被你声明的正则表达式 ( expert 段下的键值 ) 依次匹配 , 如果匹配上了 , 就会用相应的类当作驱动封装类
 * @ param productName
 * 数据库产品名称
 * @ param version
 * 数据库版本号
 * @ return 该数据库的特殊驱动封装类
 * @ see java . sql . Connection # getMetaData ( )
 * @ see java . sql . DatabaseMetaData # getDatabaseProductName ( ) */
public static JdbcExpert getExpert ( String productName , String version ) { } }

implementation: String dbName = String . format ( "%s::NUTZ_JDBC::%s" , productName , version ) . toLowerCase ( ) ; JdbcExpert re = conf . matchExpert ( dbName ) ; if ( null == re ) { log . warnf ( "unknow database type '%s %s', fallback to MySql 5" , productName , version ) ; re = conf . matchExpert ( "mysql 5" ) ; } return re ;


signature:
public class Jdbcs { /** * 注册一个自定义ValueAdaptor , 若adaptor为null , 则取消注册
 * @ param className 类名
 * @ param adaptor 值适配器实例 , 若为null , 则取消注册
 * @ return 原有的值适配器 */
public static ValueAdaptor register ( String className , ValueAdaptor adaptor ) { } }

implementation: if ( adaptor == null ) return customValueAdaptorMap . remove ( className ) ; return customValueAdaptorMap . put ( className , adaptor ) ;


signature:
public class Jdbcs { /** * 根据字段现有的信息 , 尽可能猜测一下字段的数据库类型
 * @ param ef
 * 映射字段 */
public static void guessEntityFieldColumnType ( NutMappingField ef ) { } }

implementation:
Mirror < ? > mirror = ef . getTypeMirror ( ) ; // 整型
if ( mirror . isInt ( ) ) { ef . setColumnType ( ColType . INT ) ; ef . setWidth ( 8 ) ; } // 字符串
else if ( mirror . isStringLike ( ) || mirror . is ( Email . class ) ) { ef . setColumnType ( ColType . VARCHAR ) ; ef . setWidth ( Daos . DEFAULT_VARCHAR_WIDTH ) ; } // 长整型
else if ( mirror . isLong ( ) ) { ef . setColumnType ( ColType . INT ) ; ef . setWidth ( 16 ) ; } // 枚举
else if ( mirror . isEnum ( ) ) { ef . setColumnType ( ColType . VARCHAR ) ; ef . setWidth ( 20 ) ; } // 时间戳
else if ( mirror . is ( Timestamp . class ) ) { ef . setColumnType ( ColType . TIMESTAMP ) ; } // 布尔
else if ( mirror . isBoolean ( ) ) { ef . setColumnType ( ColType . BOOLEAN ) ; ef . setWidth ( 1 ) ; } // 字符
else if ( mirror . isChar ( ) ) { ef . setColumnType ( ColType . CHAR ) ; ef . setWidth ( 4 ) ; } // 日期
else if ( mirror . is ( java . sql . Date . class ) ) { ef . setColumnType ( ColType . DATE ) ; } // 时间
else if ( mirror . is ( java . sql . Time . class ) ) { ef . setColumnType ( ColType . TIME ) ; } // 日期时间
else if ( mirror . isOf ( Calendar . class ) || mirror . is ( java . util . Date . class ) || mirror . isLocalDateTimeLike ( ) ) { ef . setColumnType ( ColType . DATETIME ) ; } // 大数
else if ( mirror . is ( BigDecimal . class ) ) { ef . setColumnType ( ColType . INT ) ; ef . setWidth ( 32 ) ; } // 短整型
else if ( mirror . isShort ( ) ) { ef . setColumnType ( ColType . INT ) ; ef . setWidth ( 4 ) ; } // 字节
else if ( mirror . isByte ( ) ) { ef . setColumnType ( ColType . INT ) ; ef . setWidth ( 2 ) ; } // 浮点
else if ( mirror . isFloat ( ) ) { ef . setColumnType ( ColType . FLOAT ) ; } // 双精度浮点
else if ( mirror . isDouble ( ) ) { ef . setColumnType ( ColType . FLOAT ) ; } // 文本流
else if ( mirror . isOf ( Reader . class ) || mirror . isOf ( Clob . class ) ) { ef . setColumnType ( ColType . TEXT ) ; } // 二进制流
else if ( mirror . isOf ( InputStream . class ) || mirror . is ( byte [ ] . class ) || mirror . isOf ( Blob . class ) ) { ef . setColumnType ( ColType . BINARY ) ; } /* * 上面的都不是 ? 那就当作字符串好了 , 反正可以 toString */
else { if ( log . isDebugEnabled ( ) && ef . getEntity ( ) != null && ef . getEntity ( ) . getType ( ) != null ) log . debugf ( "take field '%s(%s)'(%s) as VARCHAR(%d)" , ef . getName ( ) , Lang . getTypeClass ( ef . getType ( ) ) . getName ( ) , ef . getEntity ( ) . getType ( ) . getName ( ) , Daos . DEFAULT_VARCHAR_WIDTH ) ; ef . setColumnType ( ColType . VARCHAR ) ; ef . setWidth ( Daos . DEFAULT_VARCHAR_WIDTH ) ; }


signature:
public class NutMvcListener { /** * 首先 , 载入需要的配置信息 , 分别从nutz . properties和ServletContext的上下文获取 .
 * 子类可以覆盖这个方法实现从任意方式加载配置 */
protected void findConfig ( ) { } }

implementation:
String propLocation = sc . getInitParameter ( PROP_LOCATION ) ; if ( Strings . isBlank ( propLocation ) ) { propLocation = "nutz.properties" ; } PropertiesProxy pp = new PropertiesProxy ( ) ; Enumeration < String > params = sc . getInitParameterNames ( ) ; while ( params . hasMoreElements ( ) ) { String name = ( String ) params . nextElement ( ) ; if ( name . startsWith ( "nutz-" ) ) { pp . put ( name , sc . getInitParameter ( name ) . trim ( ) ) ; } } // 先找找classpath
InputStream in = getClass ( ) . getClassLoader ( ) . getResourceAsStream ( "/" + propLocation ) ; if ( in == null ) { in = sc . getResourceAsStream ( "/WEB-INF/" + propLocation ) ; } if ( in == null ) { log . debug ( propLocation + " not found" ) ; } else { pp = new PropertiesProxy ( in ) ; Streams . safeClose ( in ) ; } this . pp = pp ;


signature:
public class NutMvcListener { /** * 初始化Ioc容器 , 使用ComboIocLoader作为配置方式 */
protected void initIoc ( ) { } }

implementation: String key = "nutz-" + IOCBY ; String iocby = pp . get ( key ) ; if ( Strings . isBlank ( iocby ) ) { throw new RuntimeException ( key + " not found nutz.ini or context-param !!" ) ; } String [ ] args = Strings . splitIgnoreBlank ( iocby ) ; for ( int i = 0 ; i < args . length ; i ++ ) { args [ i ] = args [ i ] . trim ( ) ; } log . info ( "init Ioc by args=" + Arrays . toString ( args ) ) ; try { ioc = new NutIoc ( new ComboIocLoader ( args ) ) ; } catch ( ClassNotFoundException e ) { throw new RuntimeException ( e ) ; }


signature:
public class NutMvcListener { /** * 容器销毁时 , 检查Ioc是否已经关闭 , 没有的话就关闭之 . */
public void contextDestroyed ( ServletContextEvent event ) { } }

implementation: if ( ioc ( ) != null ) { Ioc ioc = ioc ( ) ; if ( ioc instanceof NutIoc ) { boolean deposed = ( Boolean ) Mirror . me ( ioc ) . getValue ( ioc , "deposed" ) ; if ( ! deposed ) ioc . depose ( ) ; } }


signature:
public class NutMvcListener { /** * 这里与IocBy结合起来 . 注意 , 这个实现会忽略IocBy的args参数 . */
public Ioc create ( NutConfig config , String [ ] args ) { } }

implementation: if ( args != null && args . length > 0 ) { if ( log != null ) log . warn ( "args ignore : " + Arrays . toString ( args ) ) ; } return ioc ( ) ;


signature:
public class NutIoc { /** * 暴露IocMaking的创建过程 */
public IocMaking makeIocMaking ( IocContext context , String name ) { } }

implementation:
// 连接上下文
IocContext cntx ; if ( null == context || context == this . context ) cntx = this . context ; else { if ( log . isTraceEnabled ( ) ) log . trace ( "Link contexts" ) ; cntx = new ComboContext ( context , this . context ) ; } return new IocMaking ( this , mirrors , cntx , maker , vpms , name ) ;


signature:
public class Region { /** * 根据左边开闭区间的情况返回一个正确的左边比较的运算符
 * @ param gt
 * 大于的运算符 , 开区间时采用
 * @ param gte
 * 大于等于的运算符 , 闭区间时采用
 * @ return 运算符 */
public String leftOpt ( String gt , String gte ) { } }

implementation: if ( null == left ) return null ; return leftOpen ? gt : gte ;


signature:
public class Region { /** * 根据右边开闭区间的情况返回一个正确的右边比较的运算符
 * @ param lt
 * 小于的运算符 , 开区间时采用
 * @ param lte
 * 小于等于的运算符 , 闭区间时采用
 * @ return 运算符 */
public String rightOpt ( String lt , String lte ) { } }

implementation: if ( null == right ) return null ; return rightOpen ? lt : lte ;


signature:
public class Region { /** * 解析
 * @ param str
 * 字符串
 * @ return 自身 */
public Region < T > valueOf ( String str ) { } }

implementation:
String s2 = Strings . trim ( str . substring ( 1 , str . length ( ) - 1 ) ) ; leftOpen = str . charAt ( 0 ) == '(' ; rightOpen = str . charAt ( str . length ( ) - 1 ) == ')' ; // 只有左值
if ( s2 . endsWith ( "," ) ) { left = fromString ( Strings . trim ( s2 . substring ( 0 , s2 . length ( ) - 1 ) ) ) ; right = null ; } // 只有右值
else if ( s2 . startsWith ( "," ) ) { left = null ; right = fromString ( Strings . trim ( s2 . substring ( 1 ) ) ) ; } // 两侧都有值
else { String [ ] ss = Strings . splitIgnoreBlank ( s2 , "," ) ; // 精确的值
if ( 1 == ss . length ) { left = fromString ( ss [ 0 ] ) ; right = left ; } // 一个区间
else { left = fromString ( ss [ 0 ] ) ; right = fromString ( ss [ 1 ] ) ; // 看看是否需要交换交换 . . .
if ( null != left && null != right && left . compareTo ( right ) > 0 ) { T o = right ; right = left ; left = o ; } } } return this ;


signature:
public class MaplEach { /** * 转换对象
 * @ param obj */
protected void each ( Object obj ) { } }

implementation: if ( obj instanceof Map ) { convertMap ( ( Map < ? , ? > ) obj ) ; } else if ( obj instanceof List ) { convertList ( ( List < ? > ) obj ) ; }


signature:
public class MaplEach { /** * 转换map
 * @ param obj */
private void convertMap ( Map < ? , ? > obj ) { } }

implementation: for ( Object key : obj . keySet ( ) ) { paths . addLast ( key . toString ( ) ) ; DLR ( fetchPath ( ) , obj . get ( key ) ) ; each ( obj . get ( key ) ) ; LRD ( fetchPath ( ) , obj . get ( key ) ) ; paths . removeLast ( ) ; }


signature:
public class MaplEach { /** * 提取路径
 * @ return */
private String fetchPath ( ) { } }

implementation: StringBuffer sb = new StringBuffer ( ) ; boolean first = true ; for ( String path : paths ) { if ( ! first ) { sb . append ( "." ) ; } sb . append ( path ) ; first = false ; } return sb . toString ( ) ;


signature:
public class MaplEach { /** * 转换LIST
 * @ param val */
private void convertList ( List < ? > val ) { } }

implementation: if ( paths . size ( ) <= 0 ) { paths . add ( "[]" ) ; } else { paths . addLast ( paths . removeLast ( ) + "[]" ) ; } for ( int i = 0 ; i < val . size ( ) ; i ++ ) { arrayIndex . addLast ( i ) ; each ( val . get ( i ) ) ; arrayIndex . removeLast ( ) ; }


signature:
public class NutTxDao { /** * 开启事务
 * @ param transLevel
 * 事务级别
 * @ see java . sql . Connection
 * @ return 原对象
 * @ throws DaoException
 * 如果已经开启过事务 */
public NutTxDao begin ( int transLevel ) throws DaoException { } }

implementation: if ( this . conn != null ) throw new DaoException ( "NutTxDao has been begined!!" ) ; id = R . UU32 ( ) ; if ( debug ) log . debugf ( "begin level=%d id=%s" , transLevel , id ) ; try { this . conn = dataSource . getConnection ( ) ; this . conn . setTransactionIsolation ( transLevel ) ; if ( this . conn . getAutoCommit ( ) == true ) { this . conn . setAutoCommit ( false ) ; _autoCommit = true ; } setSavepoint ( id ) ; } catch ( SQLException e ) { throw new DaoException ( e ) ; } return this ;


signature:
public class NutTxDao { /** * 提交事务
 * @ return 原对象 */
public NutTxDao commit ( ) { } }

implementation: if ( debug ) log . debugf ( "commit id=%s" , id ) ; try { conn . commit ( ) ; } catch ( SQLException e ) { throw new DaoException ( e ) ; } return this ;


signature:
public class NutTxDao { /** * 回滚事务
 * @ param id
 * 回滚点
 * @ return 原对象 */
public NutTxDao rollback ( String id ) { } }

implementation: if ( debug ) log . debugf ( "rollback id=%s" , id ) ; try { Savepoint sp = sps . getAs ( id , Savepoint . class ) ; if ( sp != null ) conn . rollback ( sp ) ; else log . debug ( "Null Savepoint found, skip, id=" + id ) ; } catch ( Throwable e ) { } return this ;


signature:
public class NutTxDao { /** * 关闭事务及连接 */
public void close ( ) { } }

implementation: if ( debug ) log . debugf ( "close id=%s" , id ) ; try { if ( conn == null ) return ; if ( _autoCommit ) conn . setAutoCommit ( true ) ; conn . close ( ) ; conn = null ; } catch ( Throwable e ) { }


signature:
public class ManyManyLinkField { /** * 返回关联两个实体的主键 Java 字段名数组
 * 数组的第一个元素是宿主主键的字段名 , 第二个元素是映射实体的主键字段名
 * @ return 关联两个实体的主键 Java 字段名数组 */
public String [ ] getLinkedPkNames ( ) { } }

implementation: String [ ] re = new String [ 2 ] ; re [ 0 ] = hostField . getName ( ) ; re [ 1 ] = linkedField . getName ( ) ; return re ;


signature:
public class Files { /** * 读取文件全部字节 , 并关闭文件
 * @ param path
 * 文件路径
 * @ return 文件的字节内容 */
public static byte [ ] readBytes ( String path ) { } }

implementation: File f = Files . findFile ( path ) ; if ( null == f ) throw Lang . makeThrow ( "Can not find file '%s'" , path ) ; return readBytes ( f ) ;


signature:
public class Files { /** * 读取文件全部字节 , 并关闭文件
 * @ param f
 * 文件
 * @ return 文件的字节内容 */
public static byte [ ] readBytes ( File f ) { } }

implementation: return Streams . readBytesAndClose ( Streams . buff ( Streams . fileIn ( f ) ) ) ;


signature:
public class Files { /** * 将内容写到一个文件内 , 内容对象可以是 :
 * < ul >
 * < li > InputStream - 按二进制方式写入
 * < li > byte [ ] - 按二进制方式写入
 * < li > Reader - 按 UTF - 8 方式写入
 * < li > 其他对象被 toString ( ) 后按照 UTF - 8 方式写入
 * < / ul >
 * @ param path
 * 文件路径 , 如果不存在 , 则创建
 * @ param obj
 * 内容对象 */
public static void write ( String path , Object obj ) { } }

implementation: if ( null == path || null == obj ) return ; try { write ( Files . createFileIfNoExists ( path ) , obj ) ; } catch ( IOException e ) { throw Lang . wrapThrow ( e ) ; }


signature:
public class Files { /** * 将文件后缀改名 , 从而生成一个新的文件对象 。 但是并不在磁盘上创建它
 * @ param f
 * 文件
 * @ param suffix
 * 新后缀 , 比如 " . gif " 或者 " . jpg "
 * @ return 新文件对象 */
public static File renameSuffix ( File f , String suffix ) { } }

implementation: if ( null == f || null == suffix || suffix . length ( ) == 0 ) return f ; return new File ( renameSuffix ( f . getAbsolutePath ( ) , suffix ) ) ;


signature:
public class Files { /** * 将文件路径后缀改名 , 从而生成一个新的文件路径 。
 * @ param path
 * 文件路径
 * @ param suffix
 * 新后缀 , 比如 " . gif " 或者 " . jpg "
 * @ return 新文件后缀 */
public static String renameSuffix ( String path , String suffix ) { } }

implementation: int pos = path . length ( ) ; for ( -- pos ; pos > 0 ; pos -- ) { if ( path . charAt ( pos ) == '.' ) break ; if ( path . charAt ( pos ) == '/' || path . charAt ( pos ) == '\\' ) { pos = - 1 ; break ; } } if ( 0 >= pos ) return path + suffix ; return path . substring ( 0 , pos ) + suffix ;


signature:
public class Files { /** * 获取文件主名 。 即去掉后缀的名称
 * @ param path
 * 文件路径
 * @ return 文件主名 */
public static String getMajorName ( String path ) { } }

implementation: int len = path . length ( ) ; int l = 0 ; int r = len ; for ( int i = r - 1 ; i > 0 ; i -- ) { if ( r == len ) if ( path . charAt ( i ) == '.' ) { r = i ; } if ( path . charAt ( i ) == '/' || path . charAt ( i ) == '\\' ) { l = i + 1 ; break ; } } return path . substring ( l , r ) ;


signature:
public class Files { /** * 获取文件后缀名 , 不包括 ' . ' , 如 ' abc . gif ' , ' , 则返回 ' gif '
 * @ param path
 * 文件路径
 * @ return 文件后缀名 */
public static String getSuffixName ( String path ) { } }

implementation: if ( null == path ) return null ; int p0 = path . lastIndexOf ( '.' ) ; int p1 = path . lastIndexOf ( '/' ) ; if ( - 1 == p0 || p0 < p1 ) return "" ; return path . substring ( p0 + 1 ) ;


signature:
public class Files { /** * 获取文件后缀名 , 包括 ' . ' , 如 ' abc . gif ' , ' , 则返回 ' . gif '
 * @ param path
 * 文件路径
 * @ return 文件后缀 */
public static String getSuffix ( String path ) { } }

implementation: if ( null == path ) return null ; int p0 = path . lastIndexOf ( '.' ) ; int p1 = path . lastIndexOf ( '/' ) ; if ( - 1 == p0 || p0 < p1 ) return "" ; return path . substring ( p0 ) ;


signature:
public class Files { /** * 根据正则式 , 从压缩文件中获取文件
 * @ param zip
 * 压缩文件
 * @ param regex
 * 正则式 , 用来匹配文件名
 * @ return 数组 */
public static ZipEntry [ ] findEntryInZip ( ZipFile zip , String regex ) { } }

implementation: List < ZipEntry > list = new LinkedList < ZipEntry > ( ) ; Enumeration < ? extends ZipEntry > en = zip . entries ( ) ; while ( en . hasMoreElements ( ) ) { ZipEntry ze = en . nextElement ( ) ; if ( null == regex || Regex . match ( regex , ze . getName ( ) ) ) list . add ( ze ) ; } return list . toArray ( new ZipEntry [ list . size ( ) ] ) ;


signature:
public class Files { /** * 试图生成一个文件对象 , 如果文件不存在则创建它 。 如果给出的 PATH 是相对路径 则会在 CLASSPATH
 * 中寻找 , 如果未找到 , 则会在用户主目录中创建这个文件
 * @ param path
 * 文件路径 , 可以以 ~ 开头 , 也可以是 CLASSPATH 下面的路径
 * @ return 文件对象
 * @ throws IOException
 * 创建失败 */
public static File createFileIfNoExists ( String path ) throws IOException { } }

implementation: String thePath = Disks . absolute ( path ) ; if ( null == thePath ) thePath = Disks . normalize ( path ) ; File f = new File ( thePath ) ; if ( ! f . exists ( ) ) Files . createNewFile ( f ) ; if ( ! f . isFile ( ) ) throw Lang . makeThrow ( "'%s' should be a file!" , path ) ; return f ;


signature:
public class Files { /** * 如果文件对象不存在 , 则创建它
 * @ param f
 * 文件对象
 * @ return 传入的文件对象 , 以便为调用者省略一行代码 */
public static File createFileIfNoExists ( File f ) { } }

implementation: if ( null == f ) return f ; if ( ! f . exists ( ) ) try { Files . createNewFile ( f ) ; } catch ( IOException e ) { throw Lang . wrapThrow ( e ) ; } if ( ! f . isFile ( ) ) throw Lang . makeThrow ( "'%s' should be a file!" , f ) ; return f ;


signature:
public class Files { /** * 试图生成一个目录对象 , 如果文件不存在则创建它 。 如果给出的 PATH 是相对路径 则会在 CLASSPATH
 * 中寻找 , 如果未找到 , 则会在用户主目录中创建这个目录
 * @ param path
 * 文件路径 , 可以以 ~ 开头 , 也可以是 CLASSPATH 下面的路径
 * @ return 文件对象 */
public static File createDirIfNoExists ( String path ) { } }

implementation: String thePath = Disks . absolute ( path ) ; if ( null == thePath ) thePath = Disks . normalize ( path ) ; File f = new File ( thePath ) ; if ( ! f . exists ( ) ) { boolean flag = Files . makeDir ( f ) ; if ( ! flag ) { Logs . get ( ) . warnf ( "create filepool dir(%s) fail!!" , f . getPath ( ) ) ; } } if ( ! f . isDirectory ( ) ) throw Lang . makeThrow ( "'%s' should be a directory or don't have permission to create it!" , path ) ; return f ;


signature:
public class Files { /** * 传入一个目录对象 , 如果目录不存在 , 则创建目录
 * @ param d
 * 文件目录对象
 * @ return 文件目录对象 , 以便调用者省略一行代码 */
public static File createDirIfNoExists ( File d ) { } }

implementation: if ( null == d ) return d ; if ( ! d . exists ( ) ) { if ( ! Files . makeDir ( d ) ) { throw Lang . makeThrow ( "fail to create '%s', permission deny?" , d . getAbsolutePath ( ) ) ; } } if ( ! d . isDirectory ( ) ) throw Lang . makeThrow ( "'%s' should be a directory!" , d ) ; return d ;


signature:
public class Files { /** * 从 CLASSPATH 下或从指定的本机器路径下寻找一个文件
 * @ param path
 * 文件路径
 * @ param klassLoader
 * 参考 ClassLoader
 * @ param enc
 * 文件路径编码
 * @ return 文件对象 , 如果不存在 , 则为 null */
public static File findFile ( String path , ClassLoader klassLoader , String enc ) { } }

implementation: path = Disks . absolute ( path , klassLoader , enc ) ; if ( null == path ) return null ; return new File ( path ) ;


signature:
public class Files { /** * 从 CLASSPATH 下或从指定的本机器路径下寻找一个文件
 * @ param path
 * 文件路径
 * @ param enc
 * 文件路径编码
 * @ return 文件对象 , 如果不存在 , 则为 null */
public static File findFile ( String path , String enc ) { } }

implementation: return findFile ( path , ClassTools . getClassLoader ( ) , enc ) ;


signature:
public class Files { /** * 从 CLASSPATH 下或从指定的本机器路径下寻找一个文件
 * @ param path
 * 文件路径
 * @ param klassLoader
 * 使用该 ClassLoader进行查找
 * @ return 文件对象 , 如果不存在 , 则为 null */
public static File findFile ( String path , ClassLoader klassLoader ) { } }

implementation: return findFile ( path , klassLoader , Encoding . defaultEncoding ( ) ) ;