signature:
public class ClassKit { /** * Determine the name of the package of the given fully - qualified class name ,
 * e . g . " java . lang " for the { @ code java . lang . String } class name .
 * @ param fqClassName the fully - qualified class name
 * @ return the package name , or the empty String if the class
 * is defined in the default package */
public static String getPackageName ( String fqClassName ) { } }

implementation: Preconditions . checkNotNull ( fqClassName , "Class name must not be null" ) ; int lastDotIndex = fqClassName . lastIndexOf ( PACKAGE_SEPARATOR ) ; return ( lastDotIndex != - 1 ? fqClassName . substring ( 0 , lastDotIndex ) : "" ) ;


signature:
public class ClassKit { /** * Return the qualified name of the given class : usually simply
 * the class name , but component type class name + " [ ] " for arrays .
 * @ param clazz the class
 * @ return the qualified name of the class */
public static String getQualifiedName ( Class < ? > clazz ) { } }

implementation: Preconditions . checkNotNull ( clazz , "Class must not be null" ) ; if ( clazz . isArray ( ) ) { return getQualifiedNameForArray ( clazz ) ; } else { return clazz . getName ( ) ; }


signature:
public class ClassKit { /** * Return the qualified name of the given method , consisting of
 * fully qualified interface / class name + " . " + method name .
 * @ param method the method
 * @ return the qualified name of the method */
public static String getQualifiedMethodName ( Method method ) { } }

implementation: Preconditions . checkNotNull ( method , "Method must not be null" ) ; return method . getDeclaringClass ( ) . getName ( ) + "." + method . getName ( ) ;


signature:
public class ClassKit { /** * Determine whether the given class has a public constructor with the given signature ,
 * and return it if available ( else return { @ code null } ) .
 * < p > Essentially translates { @ code NoSuchMethodException } to { @ code null } .
 * @ param clazz the clazz to analyze
 * @ param paramTypes the parameter types of the method
 * @ return the constructor , or { @ code null } if not found
 * @ see Class # getConstructor */
public static < T > Constructor < T > getConstructorIfAvailable ( Class < T > clazz , Class < ? > ... paramTypes ) { } }

implementation: Preconditions . checkNotNull ( clazz , "Class must not be null" ) ; try { return clazz . getConstructor ( paramTypes ) ; } catch ( NoSuchMethodException ex ) { return null ; }


signature:
public class ClassKit { /** * Return the number of methods with a given name ( with any argument types ) ,
 * for the given class and / or its superclasses . Includes non - public methods .
 * @ param clazz the clazz to check
 * @ param methodName the name of the method
 * @ return the number of methods with the given name */
public static int getMethodCountForName ( Class < ? > clazz , String methodName ) { } }

implementation: Preconditions . checkNotNull ( clazz , "Class must not be null" ) ; Preconditions . checkNotNull ( methodName , "Method name must not be null" ) ; int count = 0 ; Method [ ] declaredMethods = clazz . getDeclaredMethods ( ) ; for ( Method method : declaredMethods ) { if ( methodName . equals ( method . getName ( ) ) ) { count ++ ; } } Class < ? > [ ] ifcs = clazz . getInterfaces ( ) ; for ( Class < ? > ifc : ifcs ) { count += getMethodCountForName ( ifc , methodName ) ; } if ( clazz . getSuperclass ( ) != null ) { count += getMethodCountForName ( clazz . getSuperclass ( ) , methodName ) ; } return count ;


signature:
public class ClassKit { /** * Determine whether the given method is declared by the user or at least pointing to
 * a user - declared method .
 * < p > Checks { @ link Method # isSynthetic ( ) } ( for implementation methods ) as well as the
 * { @ code GroovyObject } interface ( for interface methods ; on an implementation class ,
 * implementations of the { @ code GroovyObject } methods will be marked as synthetic anyway ) .
 * Note that , despite being synthetic , bridge methods ( { @ link Method # isBridge ( ) } ) are considered
 * as user - level methods since they are eventually pointing to a user - declared generic method .
 * @ param method the method to check
 * @ return { @ code true } if the method can be considered as user - declared ; [ @ code false } otherwise */
public static boolean isUserLevelMethod ( Method method ) { } }

implementation: Preconditions . checkNotNull ( method , "Method must not be null" ) ; return ( method . isBridge ( ) || ( ! method . isSynthetic ( ) && ! isGroovyObjectMethod ( method ) ) ) ;


signature:
public class ClassKit { /** * Check if the given class represents a primitive ( i . e . boolean , byte ,
 * char , short , int , long , float , or double ) or a primitive wrapper
 * ( i . e . Boolean , Byte , Character , Short , Integer , Long , Float , or Double ) .
 * @ param clazz the class to check
 * @ return whether the given class is a primitive or primitive wrapper class */
public static boolean isPrimitiveOrWrapper ( Class < ? > clazz ) { } }

implementation: Preconditions . checkNotNull ( clazz , "Class must not be null" ) ; return ( clazz . isPrimitive ( ) || isPrimitiveWrapper ( clazz ) ) ;


signature:
public class ClassKit { /** * Check if the given class represents an array of primitives ,
 * i . e . boolean , byte , char , short , int , long , float , or double .
 * @ param clazz the class to check
 * @ return whether the given class is a primitive array class */
public static boolean isPrimitiveArray ( Class < ? > clazz ) { } }

implementation: Preconditions . checkNotNull ( clazz , "Class must not be null" ) ; return ( clazz . isArray ( ) && clazz . getComponentType ( ) . isPrimitive ( ) ) ;


signature:
public class ClassKit { /** * Check if the given class represents an array of primitive wrappers ,
 * i . e . Boolean , Byte , Character , Short , Integer , Long , Float , or Double .
 * @ param clazz the class to check
 * @ return whether the given class is a primitive wrapper array class */
public static boolean isPrimitiveWrapperArray ( Class < ? > clazz ) { } }

implementation: Preconditions . checkNotNull ( clazz , "Class must not be null" ) ; return ( clazz . isArray ( ) && isPrimitiveWrapper ( clazz . getComponentType ( ) ) ) ;


signature:
public class ClassKit { /** * Resolve the given class if it is a primitive class ,
 * returning the corresponding primitive wrapper type instead .
 * @ param clazz the class to check
 * @ return the original class , or a primitive wrapper for the original primitive type */
public static Class < ? > resolvePrimitiveIfNecessary ( Class < ? > clazz ) { } }

implementation: Preconditions . checkNotNull ( clazz , "Class must not be null" ) ; return ( clazz . isPrimitive ( ) && clazz != void . class ? primitiveTypeToWrapperMap . get ( clazz ) : clazz ) ;


signature:
public class ClassKit { /** * Check if the right - hand side type may be assigned to the left - hand side
 * type , assuming setting by reflection . Considers primitive wrapper
 * classes as assignable to the corresponding primitive types .
 * @ param lhsType the target type
 * @ param rhsType the value type that should be assigned to the target type
 * @ return if the target type is assignable from the value type */
public static boolean isAssignable ( Class < ? > lhsType , Class < ? > rhsType ) { } }

implementation: Preconditions . checkNotNull ( lhsType , "Left-hand side type must not be null" ) ; Preconditions . checkNotNull ( rhsType , "Right-hand side type must not be null" ) ; if ( lhsType . isAssignableFrom ( rhsType ) ) { return true ; } if ( lhsType . isPrimitive ( ) ) { Class < ? > resolvedPrimitive = primitiveWrapperTypeMap . get ( rhsType ) ; if ( resolvedPrimitive != null && lhsType . equals ( resolvedPrimitive ) ) { return true ; } } else { Class < ? > resolvedWrapper = primitiveTypeToWrapperMap . get ( rhsType ) ; if ( resolvedWrapper != null && lhsType . isAssignableFrom ( resolvedWrapper ) ) { return true ; } } return false ;


signature:
public class ClassKit { /** * Determine if the given type is assignable from the given value ,
 * assuming setting by reflection . Considers primitive wrapper classes
 * as assignable to the corresponding primitive types .
 * @ param type the target type
 * @ param value the value that should be assigned to the type
 * @ return if the type is assignable from the value */
public static boolean isAssignableValue ( Class < ? > type , Object value ) { } }

implementation: Preconditions . checkNotNull ( type , "Type must not be null" ) ; return ( value != null ? isAssignable ( type , value . getClass ( ) ) : ! type . isPrimitive ( ) ) ;


signature:
public class ClassKit { /** * Convert a " / " - based resource path to a " . " - based fully qualified class name .
 * @ param resourcePath the resource path pointing to a class
 * @ return the corresponding fully qualified class name */
public static String convertResourcePathToClassName ( String resourcePath ) { } }

implementation: Preconditions . checkNotNull ( resourcePath , "Resource path must not be null" ) ; return resourcePath . replace ( PATH_SEPARATOR , PACKAGE_SEPARATOR ) ;


signature:
public class ClassKit { /** * Convert a " . " - based fully qualified class name to a " / " - based resource path .
 * @ param className the fully qualified class name
 * @ return the corresponding resource path , pointing to the class */
public static String convertClassNameToResourcePath ( String className ) { } }

implementation: Preconditions . checkNotNull ( className , "Class name must not be null" ) ; return className . replace ( PACKAGE_SEPARATOR , PATH_SEPARATOR ) ;


signature:
public class ClassKit { /** * Return a path suitable for use with { @ code ClassLoader . getResource }
 * ( also suitable for use with { @ code Class . getResource } by prepending a
 * slash ( ' / ' ) to the return value ) . Built by taking the package of the specified
 * class file , converting all dots ( ' . ' ) to slashes ( ' / ' ) , adding a trailing slash
 * if necessary , and concatenating the specified resource name to this .
 * @ param clazz the Class whose package will be used as the base
 * @ param resourceName the resource name to append . A leading slash is optional .
 * @ return the built - up resource path
 * @ see ClassLoader # getResource
 * @ see Class # getResource */
public static String addResourcePathToPackagePath ( Class < ? > clazz , String resourceName ) { } }

implementation: Preconditions . checkNotNull ( resourceName , "Resource name must not be null" ) ; if ( ! resourceName . startsWith ( "/" ) ) { return classPackageAsResourcePath ( clazz ) + "/" + resourceName ; } return classPackageAsResourcePath ( clazz ) + resourceName ;


signature:
public class ClassKit { /** * Return all interfaces that the given instance implements as array ,
 * including ones implemented by superclasses .
 * @ param instance the instance to analyze for interfaces
 * @ return all interfaces that the given instance implements as array */
public static Class < ? > [ ] getAllInterfaces ( Object instance ) { } }

implementation: Preconditions . checkNotNull ( instance , "Instance must not be null" ) ; return getAllInterfacesForClass ( instance . getClass ( ) ) ;


signature:
public class ClassKit { /** * Return all interfaces that the given instance implements as Set ,
 * including ones implemented by superclasses .
 * @ param instance the instance to analyze for interfaces
 * @ return all interfaces that the given instance implements as Set */
public static Set < Class < ? > > getAllInterfacesAsSet ( Object instance ) { } }

implementation: Preconditions . checkNotNull ( instance , "Instance must not be null" ) ; return getAllInterfacesForClassAsSet ( instance . getClass ( ) ) ;


signature:
public class ClassKit { /** * Return all interfaces that the given class implements as Set ,
 * including ones implemented by superclasses .
 * < p > If the class itself is an interface , it gets returned as sole interface .
 * @ param clazz the class to analyze for interfaces
 * @ param classLoader the ClassLoader that the interfaces need to be visible in
 * ( may be { @ code null } when accepting all declared interfaces )
 * @ return all interfaces that the given object implements as Set */
public static Set < Class < ? > > getAllInterfacesForClassAsSet ( Class < ? > clazz , ClassLoader classLoader ) { } }

implementation: Preconditions . checkNotNull ( clazz , "Class must not be null" ) ; if ( clazz . isInterface ( ) && isVisible ( clazz , classLoader ) ) { return Collections . < Class < ? > > singleton ( clazz ) ; } Set < Class < ? > > interfaces = new LinkedHashSet < Class < ? > > ( ) ; while ( clazz != null ) { Class < ? > [ ] ifcs = clazz . getInterfaces ( ) ; for ( Class < ? > ifc : ifcs ) { interfaces . addAll ( getAllInterfacesForClassAsSet ( ifc , classLoader ) ) ; } clazz = clazz . getSuperclass ( ) ; } return interfaces ;


signature:
public class ClassKit { /** * Create a composite interface Class for the given interfaces ,
 * implementing the given interfaces in one single Class .
 * < p > This implementation builds a JDK proxy class for the given interfaces .
 * @ param interfaces the interfaces to merge
 * @ param classLoader the ClassLoader to create the composite Class in
 * @ return the merged interface as Class
 * @ see java . lang . reflect . Proxy # getProxyClass */
public static Class < ? > createCompositeInterface ( Class < ? > [ ] interfaces , ClassLoader classLoader ) { } }

implementation: Preconditions . checkNotNull ( interfaces , "Interfaces must not be empty" ) ; Preconditions . checkNotNull ( classLoader , "ClassLoader must not be null" ) ; return Proxy . getProxyClass ( classLoader , interfaces ) ;


signature:
public class StandardLauncher { /** * This method initializes servlet filters .
 * Default implementation adds request vector filter by default .
 * Overrides of this method can also do things like enforcing UTF - 8 encoding .
 * Here is an example of how it can be done :
 * < code >
 * final FilterHolder encFilterHolder = contextHandler . addFilter ( CharacterEncodingFilter . class , " / * " , EnumSet . allOf ( DispatcherType . class ) ) ;
 * encFilterHolder . setInitParameter ( " encoding " , " UTF - 8 " ) ;
 * encFilterHolder . setInitParameter ( " forceEncoding " , " true " ) ; / / this line instructs filter to add encoding
 * < / code >
 * However this is usually not something
 * @ param contextHandler Servlet context handler */
protected void initContextFilters ( @ Nonnull ServletContextHandler contextHandler ) { } }

implementation: if ( springSecurityEnabled ) { initSpringSecurity ( contextHandler ) ; } if ( requestVectorOperationsEnabled ) { initRequestVectorOperations ( contextHandler ) ; }


signature:
public class TempConfiguration { /** * Writes properties to the temporary file that will be deleted on process exit and returns file URL as a result .
 * @ return File URL
 * @ throws IOException On I / O error */
public URL writeToTempFile ( ) throws IOException { } }

implementation:
final File tempConfigFile = File . createTempFile ( "brikar-tempconfig-" , ".properties" ) ; tempConfigFile . deleteOnExit ( ) ; // store properties
final Properties props = new Properties ( ) ; props . putAll ( properties ) ; try ( final FileOutputStream fileOutputStream = new FileOutputStream ( tempConfigFile ) ) { props . store ( fileOutputStream , "[brikar-maintenance] TempConfiguration - Autogenerated properties" ) ; } return tempConfigFile . toURI ( ) . toURL ( ) ;


signature:
public class MongoQuery { /** * 数组 */
public void add ( String key , Object value ) { } }

implementation: list . add ( new BasicDBObject ( key , value ) ) ;


signature:
public class Route { /** * Identifies Web endpoint method to be invoked from the HTTP request ' s URI .
 * This method processes the request as the following steps :
 * < ol >
 * < li > Gets Web endpoint classes from the { @ code ServletContext } . If they
 * have not been set on the { @ code ServletContext } , this method loads them
 * by invoking { @ code Loader # load ( ) } on the loader that the
 * { @ code Configuration } returns . < / li >
 * < li > Determines if the requested URI is ignored by { @ link Routing } . If the
 * requested URI is matched to the pattern specified by { @ code Routing # ignore ( String . . . ) } ,
 * the request is forwarded to the next filter chain . < / li >
 * < li > Determines if the requested URI is matched to the URI template
 * specified by { @ code Routing # add ( String , Class , String ) } . If the requested
 * URI is matched to the URI template , the corresponding Web endpoint method
 * is set to the current HTTP request processing context . < / li >
 * < li > If the requested URI is not matched to any URI template , identifies
 * Web endpoint class and method according to the default URI convention
 * ( URI ends with / . . . / & lt ; simple - name - of - the - endpoint - class & gt ; / & lt ; endpoint - method & gt ; ) .
 * < / li >
 * < li > If any Web endpoint method is not identified , the request is
 * forwarded to the next filter chain . < / li >
 * < / ol >
 * @ param context HTTP request processing context . */
public boolean apply ( WebContext context ) { } }

implementation: Configuration configuration = context . configuration ( ) ; if ( endpoints == null ) { synchronized ( lock ) { if ( endpoints == null ) { endpoints = new HashMap < String , Class < ? > > ( ) ; for ( Class < ? > endpoint : configuration . endpoints ( ) ) { String name = endpoint . getSimpleName ( ) . toLowerCase ( ) ; if ( endpoints . containsKey ( name ) ) { logger . warn ( "Web endpoint class name is duplicated: [" + endpoints . get ( name ) + "] is overwritten by [" + endpoint + "]" ) ; } endpoints . put ( name , endpoint ) ; } } } } if ( routing == null ) { synchronized ( lock ) { if ( routing == null ) { routing = configuration . routing ( ) ; } } } HttpServletRequest request = context . request ( ) ; String uri = request . getRequestURI ( ) . substring ( ( request . getContextPath ( ) ) . length ( ) ) ; try { if ( routing . ignores ( uri ) ) { logger . debug ( "URI [" + request . getRequestURI ( ) + "] is ignored by routing configuration" ) ; context . chain ( ) . doFilter ( request , context . response ( ) ) ; return false ; } Verb verb = null ; try { verb = Verb . valueOf ( request . getMethod ( ) ) ; } catch ( Exception e ) { logger . warn ( "HTTP verb [" + request . getMethod ( ) + "] is not supported" ) ; } List < Entry < URITemplate , Map < Verb , Method > > > route = routing . route ( uri ) ; for ( Entry < URITemplate , Map < Verb , Method > > r : route ) { Method method = r . getValue ( ) . get ( verb ) ; if ( method == null ) { method = r . getValue ( ) . get ( null ) ; } if ( method != null ) { context . method ( method ) ; request . setAttribute ( Request . PATH , r . getKey ( ) . variables ( uri ) ) ; logger . debug ( "Web endpoint method is [" + method . getDeclaringClass ( ) . getName ( ) + "#" + method . getName ( ) + "]" ) ; return true ; } } if ( uri . endsWith ( "/" ) ) { logger . debug ( "URI [" + request . getRequestURI ( ) + "] is not correlated with any Web endpoint" ) ; context . chain ( ) . doFilter ( request , context . response ( ) ) ; return false ; } String [ ] segments = uri . split ( "/" ) ; if ( segments . length < 2 ) { logger . debug ( "URI [" + request . getRequestURI ( ) + "] is not correlated with any Web endpoint" ) ; logger . debug ( "The requested URI pattern must end with " + "[/.../<simple-name-of-the-endpoint-class>/<endpoint-method>] or " + "correlated with any Web endpoint in the routing configuration" ) ; context . chain ( ) . doFilter ( request , context . response ( ) ) ; return false ; } Class < ? > endpoint = endpoints . get ( segments [ segments . length - 2 ] . toLowerCase ( ) ) ; if ( endpoint == null ) { logger . warn ( "Web endpoint class is not found: Simple class name [" + segments [ segments . length - 2 ] + "]" ) ; context . chain ( ) . doFilter ( request , context . response ( ) ) ; return false ; } for ( Method method : endpoint . getMethods ( ) ) { if ( method . getName ( ) . compareToIgnoreCase ( segments [ segments . length - 1 ] ) == 0 ) { context . method ( method ) ; logger . debug ( "Web endpoint method is [" + method . getDeclaringClass ( ) . getName ( ) + "#" + method . getName ( ) + "]" ) ; return true ; } } logger . warn ( "Web endpoint method is not found: Method name [" + segments [ segments . length - 1 ] + "]" ) ; context . chain ( ) . doFilter ( request , context . response ( ) ) ; return false ; } catch ( Exception e ) { throw new UncheckedException ( e ) ; }


signature:
public class JVMKit { /** * 得到当时进程PID , 如果没有得到 , 返回 - 1
 * @ return 进程PID */
public static int getPid ( ) { } }

implementation: String name = ManagementFactory . getRuntimeMXBean ( ) . getName ( ) ; int indexOf = name . indexOf ( StringPool . AT ) ; if ( indexOf > 0 ) { return Integer . parseInt ( name . substring ( 0 , indexOf ) ) ; } else { return - 1 ; }


signature:
public class JVMKit { /** * 锁定一个临时文件 , 以便实现一台服务器只能启动一个进程
 * @ param lockName 临时文件名称 , 不要带目录名称 */
public static void lockFileForOnlyProcess ( String lockName ) { } }

implementation: File file = new File ( System . getProperty ( "java.io.tmpdir" ) , lockName + ".lock" ) ; try { FileOutputStream output = new FileOutputStream ( file ) ; FileLock fileLock = output . getChannel ( ) . tryLock ( ) ; if ( fileLock == null ) { logger . warn ( "文件:'" + file + "'已经被lock,进程已经启动,系统将退出" ) ; System . exit ( 1 ) ; } PrintStream printStream = new PrintStream ( output ) ; printStream . println ( getPid ( ) ) ; printStream . flush ( ) ; jvmFile . add ( fileLock ) ; logger . info ( "成功lock文件:'" + file + "',用以避免程序被多次启动,pid:" + getPid ( ) ) ; } catch ( IOException e ) { logger . warn ( "获得文件lock时异常:'" + file + "',系统退出" , e ) ; System . exit ( 2 ) ; }


signature:
public class URITemplate { /** * Returns template variable name and value pairs extracted from the
 * specified actual URI .
 * @ param uri The actual URI to be parsed .
 * @ return The template variable name and value pairs extracted from the
 * specified actual URI . */
public Map < String , String > variables ( String uri ) { } }

implementation: Map < String , String > variables = new HashMap < String , String > ( ) ; Matcher matcher = pattern . matcher ( uri ) ; if ( matcher . matches ( ) ) { for ( int i = 0 ; i < matcher . groupCount ( ) ; i ++ ) { variables . put ( this . variables . get ( i ) , matcher . group ( i + 1 ) ) ; } } return variables ;


signature:
public class URITemplate { /** * Compares this URI template to the specified one .
 * Returns < code > & lt ; 0 < / code > if this URI template ' s segment ( split by ' / ' )
 * count is < b > greater < / b > than the specified one , < code > & gt ; 0 < / code > if
 * this URI template ' s segment count is < b > less < / b > than the specified one
 * or this URI template ' s segment count is equivalent to the specified one .
 * This method is used for sorting URI templates according to the priority
 * { @ code URITemplate # matches ( String ) } method is tested by { @ link Routing }
 * class , so a stricter template ( which has more segments ) is prior to a
 * less one .
 * @ param o URI template to be compared .
 * @ return < code > & lt ; 0 < / code > if this URI template ' s segment ( split by ' / ' )
 * count is < b > greater < / b > than the specified one , < code > & gt ; 0 < / code > if
 * this URI template ' s segment count is < b > less < / b > than the specified one
 * or this URI template ' s segment count is equivalent to the specified one .
 * @ see Routing */
public int compareTo ( URITemplate o ) { } }

implementation: if ( template . equals ( o . template ) ) { return 0 ; } int difference = template . split ( "/" ) . length - o . template . split ( "/" ) . length ; return ( difference == 0 ) ? 1 : difference * - 1 ;


signature:
public class PermBean { /** * Add permission and message one by one .
 * @ param permission { @ link Permission } to be asked .
 * @ param message String rationale message . */
public PermBean put ( Permission permission , String message ) { } }

implementation: if ( permission == null ) throw new IllegalArgumentException ( "Permission can't be null" ) ; mPermissions . put ( permission , message ) ; return this ;


signature:
public class Reflect { /** * Determines if first class match the destination and simulates kind of < code > instanceof < / code > .
 * All subclasses and interface of first class are examined against second class . Method is not
 * symmetric . */
public static boolean isSubclass ( Class thisClass , Class target ) { } }

implementation: if ( target . isInterface ( ) ) { return isInterfaceImpl ( thisClass , target ) ; } for ( Class x = thisClass ; x != null ; x = x . getSuperclass ( ) ) { if ( x == target ) { return true ; } } return false ;


signature:
public class Reflect { /** * Returns < code > true < / code > if provided class is interface implementation . */
public static boolean isInterfaceImpl ( Class thisClass , Class targetInterface ) { } }

implementation: for ( Class x = thisClass ; x != null ; x = x . getSuperclass ( ) ) { Class [ ] interfaces = x . getInterfaces ( ) ; for ( Class i : interfaces ) { if ( i == targetInterface ) { return true ; } if ( isInterfaceImpl ( i , targetInterface ) ) { return true ; } } } return false ;


signature:
public class Reflect { /** * Get a Map containing field names and wrapped values for the fields ' values . < p / > If the wrapped
 * object is a { @ link Class } , then this will return static fields . If the wrapped object is any
 * other { @ link Object } , then this will return instance fields . < p / >
 * These two calls are equivalent < code > < pre >
 * on ( object ) . field ( " myField " ) ;
 * on ( object ) . fields ( ) . get ( " myField " ) ;
 * < / pre > < / code >
 * @ return A map containing field names and wrapped values . */
public Map < String , Reflect > fields ( ) { } }

implementation: Map < String , Reflect > result = Maps . newLinkedHashMap ( ) ; for ( Field field : type ( ) . getFields ( ) ) { if ( ! isClass ^ Modifier . isStatic ( field . getModifiers ( ) ) ) { String name = field . getName ( ) ; result . put ( name , field ( name ) ) ; } } return result ;


signature:
public class DruidDbIntializer { /** * The configuration database , specify the name of the database .
 * @ param dbProp 数据库配置 */
public static DruidPlugin druidPlugin ( Properties dbProp ) { } }

implementation:
String dbUrl = dbProp . getProperty ( GojaPropConst . DBURL ) , username = dbProp . getProperty ( GojaPropConst . DBUSERNAME ) , password = dbProp . getProperty ( GojaPropConst . DBPASSWORD ) ; if ( ! Strings . isNullOrEmpty ( dbUrl ) ) { String dbtype = JdbcUtils . getDbType ( dbUrl , StringUtils . EMPTY ) ; String driverClassName ; try { driverClassName = JdbcUtils . getDriverClassName ( dbUrl ) ; } catch ( SQLException e ) { throw new DatabaseException ( e . getMessage ( ) , e ) ; } final DruidPlugin druidPlugin = new DruidPlugin ( dbUrl , username , password , driverClassName ) ; // set validator
setValidatorQuery ( dbtype , druidPlugin ) ; druidPlugin . addFilter ( new StatFilter ( ) ) ; final String initialSize = dbProp . getProperty ( GojaPropConst . DB_INITIAL_SIZE ) ; if ( ! Strings . isNullOrEmpty ( initialSize ) ) { druidPlugin . setInitialSize ( MoreObjects . firstNonNull ( Ints . tryParse ( initialSize ) , 6 ) ) ; } final String initial_minidle = dbProp . getProperty ( GojaPropConst . DB_INITIAL_MINIDLE ) ; if ( ! Strings . isNullOrEmpty ( initial_minidle ) ) { druidPlugin . setMinIdle ( MoreObjects . firstNonNull ( Ints . tryParse ( initial_minidle ) , 5 ) ) ; } final String initial_maxwait = dbProp . getProperty ( GojaPropConst . DB_INITIAL_MAXWAIT ) ; if ( ! Strings . isNullOrEmpty ( initial_maxwait ) ) { druidPlugin . setMaxWait ( MoreObjects . firstNonNull ( Ints . tryParse ( initial_maxwait ) , 5 ) ) ; } final String initial_active = dbProp . getProperty ( GojaPropConst . DB_INITIAL_ACTIVE ) ; if ( ! Strings . isNullOrEmpty ( initial_active ) ) { druidPlugin . setMaxActive ( MoreObjects . firstNonNull ( Ints . tryParse ( initial_active ) , 5 ) ) ; } final String timeBetweenEvictionRunsMillis = dbProp . getProperty ( GojaPropConst . DB_TIME_BETWEEN_EVICTION_RUNS_MILLIS ) ; if ( ! Strings . isNullOrEmpty ( timeBetweenEvictionRunsMillis ) ) { final Integer millis = MoreObjects . firstNonNull ( Ints . tryParse ( timeBetweenEvictionRunsMillis ) , 10000 ) ; druidPlugin . setTimeBetweenEvictionRunsMillis ( millis ) ; } final String minEvictableIdleTimeMillis = dbProp . getProperty ( GojaPropConst . DB_MIN_EVICTABLE_IDLE_TIME_MILLIS ) ; if ( ! Strings . isNullOrEmpty ( minEvictableIdleTimeMillis ) ) { final Integer idleTimeMillis = MoreObjects . firstNonNull ( Ints . tryParse ( minEvictableIdleTimeMillis ) , 10000 ) ; druidPlugin . setMinEvictableIdleTimeMillis ( idleTimeMillis ) ; } final WallFilter wall = new WallFilter ( ) ; wall . setDbType ( dbtype ) ; druidPlugin . addFilter ( wall ) ; if ( GojaConfig . getPropertyToBoolean ( GojaPropConst . DBLOGFILE , false ) ) { // 增加 LogFilter 输出JDBC执行的日志
druidPlugin . addFilter ( new Slf4jLogFilter ( ) ) ; } return druidPlugin ; } return null ;


signature:
public class ExtensionFinder { /** * Allows the subtype to be selective about what to bind . */
protected < T > void bind ( Class < ? extends T > impl , Class < T > extensionPoint ) { } }

implementation: ExtensionLoaderModule < T > lm = createLoaderModule ( extensionPoint ) ; lm . init ( impl , extensionPoint ) ; install ( lm ) ;


signature:
public class ExtensionFinder { /** * Creates a new instance of { @ link ExtensionLoaderModule } to be used to
 * load the extension of the given type . */
protected < T > ExtensionLoaderModule < T > createLoaderModule ( Class < T > extensionPoint ) { } }

implementation: ExtensionPoint ep = extensionPoint . getAnnotation ( ExtensionPoint . class ) ; if ( ep != null ) { if ( ep . loader ( ) != ExtensionLoaderModule . Default . class ) { try { return ( ExtensionLoaderModule ) ep . loader ( ) . newInstance ( ) ; } catch ( InstantiationException e ) { throw ( Error ) new InstantiationError ( ) . initCause ( e ) ; } catch ( IllegalAccessException e ) { throw ( Error ) new IllegalAccessError ( ) . initCause ( e ) ; } } } return new ExtensionLoaderModule . Default < T > ( ) ;


signature:
public class ExtensionFinder { /** * Finds all the supertypes that are annotated with { @ link ExtensionPoint } . */
private Set < Class > listExtensionPoint ( Class e , Set < Class > result ) { } }

implementation: if ( e . isAnnotationPresent ( ExtensionPoint . class ) ) result . add ( e ) ; Class s = e . getSuperclass ( ) ; if ( s != null ) listExtensionPoint ( s , result ) ; for ( Class c : e . getInterfaces ( ) ) { listExtensionPoint ( c , result ) ; } return result ;


signature:
public class AbstractRequest { /** * Constructs Web endpoint parameter from the specified source list or type .
 * This method is invoked for every Web endpoint method parameter by
 * { @ link Receive } . This method processes according to the following steps :
 * < ol >
 * < li > If the specified type is an array type , returns < code > null < / code > . An
 * array type is not supported in this class . < / li >
 * < li > If the specified type is built - in type ( See { @ link Types # isBuiltinType ( Type ) } ) ,
 * returns the built - in instance . < / li >
 * < li > Constructs the value as the specified type from the specified sources
 * and names . If the Web endpoint parameter is declared without any source
 * annotation except built - in type , this method always returns < code > null < / code > .
 * < / li >
 * < li > If the construction result is not < code > null < / code > , returns the
 * result to the client . < / li >
 * < li > If the result is < code > null < / code > of primitive type , returns the
 * default value of each primitive type to the client . < / li >
 * < li > If the result is < code > null < / code > of supported collection type ( See
 * { @ link Types # isSupportedCollection ( Type ) } ) , returns the empty collection
 * of the specified type to the client . < / li >
 * < li > Otherwise , returns < code > null < / code > . < / li >
 * < / ol >
 * @ param type The type of Web endpoint parameter .
 * @ param sources The source list from which Web endpoint parameter is
 * constructed .
 * @ return Web endpoint method parameter . */
public Object get ( Type type , List < Annotation > sources ) { } }

implementation: if ( Types . isArray ( type ) ) { logger . warn ( "Array type is not supported in [" + getClass ( ) + "]" ) ; return null ; } else if ( Types . isBuiltinType ( type ) ) { return builtin ( type ) ; } for ( Annotation source : sources ) { Object parameter = null ; if ( source instanceof Query ) { Query query = ( Query ) source ; parameter = query ( type , query . value ( ) ) ; } else if ( source instanceof Body ) { Body body = ( Body ) source ; parameter = body ( type , body . value ( ) ) ; } else if ( source instanceof Header ) { Header header = ( Header ) source ; parameter = header ( type , header . value ( ) ) ; } else if ( source instanceof org . eiichiro . bootleg . annotation . Cookie ) { org . eiichiro . bootleg . annotation . Cookie cookie = ( org . eiichiro . bootleg . annotation . Cookie ) source ; parameter = cookie ( type , cookie . value ( ) ) ; } else if ( source instanceof Session ) { Session session = ( Session ) source ; parameter = session ( type , session . value ( ) ) ; } else if ( source instanceof Application ) { Application application = ( Application ) source ; parameter = application ( type , application . value ( ) ) ; } else if ( source instanceof Path ) { Path path = ( Path ) source ; parameter = path ( type , path . value ( ) ) ; } else { logger . warn ( "Unknown source [" + source + "]" ) ; } if ( parameter != null ) { return parameter ; } } if ( Types . isPrimitive ( type ) ) { logger . debug ( "Cannot construct [" + type + "] primitive; Returns the default value" ) ; return primitive ( type ) ; } else if ( Types . isCollection ( type ) ) { if ( Types . isSupportedCollection ( type ) ) { logger . debug ( "Cannot construct [" + type + "] collection; Returns the empty colleciton" ) ; return Types . getEmptyCollection ( type ) ; } else { logger . warn ( "Collection type " + type + " is not supported in [" + getClass ( ) + "]" ) ; return null ; } } StringBuilder builder = new StringBuilder ( ) ; for ( Annotation source : sources ) { builder . append ( source + " " ) ; } logger . debug ( "Cannot construct Web endpoint method parameter [" + builder + type + "]" ) ; return null ;


signature:
public class AbstractRequest { /** * Returns the value of built - in type .
 * @ param type The parameter type .
 * @ return The value of built - in type . */
protected Object builtin ( Type type ) { } }

implementation:
Class < ? > rawType = Types . getRawType ( type ) ; if ( rawType . equals ( WebContext . class ) ) { return context ; } else if ( rawType . equals ( HttpServletRequest . class ) ) { return context . request ( ) ; } else if ( rawType . equals ( HttpServletResponse . class ) ) { return context . response ( ) ; } else if ( rawType . equals ( HttpSession . class ) ) { return context . session ( ) ; } else if ( rawType . equals ( ServletContext . class ) ) { return context . application ( ) ; } else { // org . eiichiro . bootleg . Request .
return this ; }


signature:
public class AbstractRequest { /** * Returns the default value of the specified primitive type .
 * @ param type The primitive type .
 * @ return The default value of the specified primitive type . */
protected Object primitive ( Type type ) { } }

implementation:
Class < ? > rawType = Types . getRawType ( type ) ; if ( rawType . equals ( Boolean . TYPE ) ) { return ( boolean ) false ; } else if ( rawType . equals ( Character . TYPE ) ) { return ( char ) 0 ; } else if ( rawType . equals ( Byte . TYPE ) ) { return ( byte ) 0 ; } else if ( rawType . equals ( Double . TYPE ) ) { return ( double ) 0.0 ; } else if ( rawType . equals ( Float . TYPE ) ) { return ( float ) 0.0 ; } else if ( rawType . equals ( Integer . TYPE ) ) { return ( int ) 0 ; } else { // short .
return ( short ) 0 ; }


signature:
public class AbstractRequest { /** * Constructs the value of Web endpoint parameter .
 * Web endpoint parameter declaration falls into the several patterns and
 * each pattern has the own construction logic as below :
 * < ol >
 * < li > Named array type - Unsupported . Always returns < code > null < / code > . < / li >
 * < li > Named collection of core value type - Supported . The collection
 * instance is constructed according to the default implementation type
 * ( See { @ code Types # getDefaultImplementationType ( Type ) } ) . If the collection
 * type is not supported ( See { @ code Types # isSupportedCollection ( Type ) } ) ,
 * this method returns < code > null < / code > . Each of the collection elements is
 * constructed from the values that { @ code values } has returned as the same
 * way of the following core value type . If the constructed collection has
 * no element , this method returns < code > null < / code > . < / li >
 * < li > Named collection of user - defined value type - Supported . The
 * collection instance is constructed according to the default
 * implementation type ( as the same as collection of core value type ) . Each
 * of the collection elements is constructed from the values that
 * { @ code values } has returned as the same way of following user - defined
 * value type .
 * < / li >
 * < li > Named collection of user - defined object type - Unsupported . Always
 * returns < code > null < / code > . < / li >
 * < li > Named core value type - Supported . The value that { @ code value } has
 * returned is converted to the core value type . If the conversion
 * failed , returns < code > null < / code > < / li >
 * < li > Named user - defined value type - Supported . If the value that
 * { @ code value } has returned is assignable to the user - defined value type ,
 * returns it . If the value that { @ code value } has returned is
 * { @ code String . class } , this method constructs the user - defined value type
 * with public constructor that takes one String . class parameter or public
 * static < code > valueOf ( String . class ) < / code > method . If the conversion
 * failed , returns < code > null < / code > .
 * < / li >
 * < li > Named user - defined object type - Partially supported . If the value
 * that { @ code value } method has returned is assignable to the user - defined
 * object type , returns it . Otherwise , returns < code > null < / code > ( does not
 * any type conversion ) . < / li >
 * < li > Not named array type - Unsupported . Always returns < code > null < / code > .
 * < / li >
 * < li > Not named collection of core value type - Unsupported . Always returns
 * < code > null < / code > . < / li >
 * < li > Not named collection of user - defined value type - Unsupported . Always
 * returns < code > null < / code > . < / li >
 * < li > Not named collection of user - defined object type - Unsupported .
 * Always returns < code > null < / code > . < / li >
 * < li > Not named core value type - Unsupported . Always returns
 * < code > null < / code > . < / li >
 * < li > Not named user - defined value type - Unsupported . Always returns
 * < code > null < / code > . < / li >
 * < li > Not named user - defined object type - Supported . First , this method
 * instantiates the user - defined object instance form public default
 * constructor , and then constructs each of the instances ' fields value
 * according to the named type construction described above ( by invoking
 * { @ code # newParameter ( WebContext , Type , String ) } with the field
 * type and field name ) . If the instantiation is failed , returns < code > null
 * < / code > .
 * < / li >
 * < / ol >
 * This method is overridable . You can provide your own value construction
 * to Web endpoint parameter by overriding this method .
 * @ param type The parameter type .
 * @ param name The parameter name .
 * @ param value The { @ code Function } that returns the value corresponding to
 * the specified name from its own source .
 * The returned value is converted to appropriate parameter type .
 * @ param values The { @ code Function } that returns the value corresponding
 * to the specified name from its own source , as { @ code Collection } view .
 * @ return The value of Web endpoint parameter . */
@ SuppressWarnings ( "unchecked" ) protected Object parameter ( Type type , String name , Function < String , Object > value , Function < String , Collection < Object > > values ) { } }

implementation:
if ( name != null && ! name . isEmpty ( ) ) { // Named parameter construction .
if ( Types . isArray ( type ) ) { // Named array type .
logger . debug ( "Array type [" + type + "] is not supported in [" + getClass ( ) + "]" ) ; } else if ( Types . isCollection ( type ) ) { // Named collection type .
if ( Types . isSupportedCollection ( type ) ) { Collection < Object > objects = values . apply ( name ) ; if ( objects == null ) { logger . debug ( "Collection named [" + name + "] not found" ) ; } else { Class < ? > elementType = Types . getElementType ( type ) ; boolean coreValueType = Types . isCoreValueType ( elementType ) ; if ( ! coreValueType && ! Types . isUserDefinedValueType ( elementType ) ) { // Named collection of user - defined object .
logger . debug ( "Collection element type [" + elementType + "] is not supported in [" + getClass ( ) + "]" ) ; } else { try { Class < ? > implementationType = Types . getDefaultImplementationType ( type ) ; Collection < Object > collection = ( Collection < Object > ) implementationType . newInstance ( ) ; for ( Object object : objects ) { // Named collection of core value type .
// Named collection of user - defined value type .
Object convert = ( coreValueType ) ? convert ( object , elementType ) : convertUserDefinedValueType ( object , elementType ) ; if ( convert != null && ClassUtils . primitiveToWrapper ( elementType ) . isAssignableFrom ( convert . getClass ( ) ) ) { collection . add ( convert ) ; } else { logger . debug ( "Parameter [" + convert + "] cannot be converted to [" + elementType + "]" ) ; } } return ( ! collection . isEmpty ( ) ) ? collection : null ; } catch ( Exception e ) { logger . debug ( "Cannot instantiate [" + Types . getDefaultImplementationType ( type ) + "] (Default implementation type of [" + type + "])" , e ) ; } } } } else { logger . debug ( "Parameter type [" + type + "] is not supported in [" + getClass ( ) + "]" ) ; } } else if ( Types . isCoreValueType ( type ) ) { // Named core value type .
Class < ? > rawType = Types . getRawType ( type ) ; Object object = value . apply ( name ) ; if ( object == null ) { logger . debug ( "Value named [" + name + "] not found" ) ; } else { Object convert = convert ( object , rawType ) ; if ( convert != null && ClassUtils . primitiveToWrapper ( rawType ) . isAssignableFrom ( convert . getClass ( ) ) ) { return convert ; } else { logger . warn ( "Parameter [" + convert + "] cannot be converted to [" + type + "]" ) ; } } } else if ( Types . isUserDefinedValueType ( type ) ) { // Named user - defined value type .
Object object = value . apply ( name ) ; Class < ? > rawType = Types . getRawType ( type ) ; if ( object == null ) { logger . debug ( "Value named [" + name + "] not found" ) ; } else { Object userDefinedValueType = convertUserDefinedValueType ( object , rawType ) ; if ( userDefinedValueType == null ) { logger . warn ( "Parameter [" + object + "] cannot be converted to [" + type + "]" ) ; } return userDefinedValueType ; } } else { // Named user - defined object type .
Object object = value . apply ( name ) ; if ( object == null ) { logger . debug ( "Value named [" + name + "] not found" ) ; } else if ( Types . getRawType ( type ) . isAssignableFrom ( object . getClass ( ) ) ) { return object ; } else { logger . warn ( "Parameter [" + object + "] cannot be converted to [" + type + "]" ) ; } } } else { // Non - named parameter construction .
if ( Types . isArray ( type ) || Types . isCollection ( type ) || Types . isCoreValueType ( type ) || Types . isUserDefinedValueType ( type ) ) { // Not named array type .
// Not named collection ( of core value type or user - defined object type ) .
// Not named core value type .
// Not named user - defined value type .
logger . debug ( "Non-named parameter type [" + type + "] is not supported in [" + getClass ( ) + "]" ) ; } else { // Not named user - defined object type .
Class < ? > rawType = Types . getRawType ( type ) ; try { Object instance = rawType . newInstance ( ) ; for ( Field field : rawType . getDeclaredFields ( ) ) { Object object = parameter ( field . getGenericType ( ) , field . getName ( ) , value , values ) ; if ( object != null ) { field . setAccessible ( true ) ; field . set ( instance , object ) ; } } return instance ; } catch ( Exception e ) { logger . warn ( "Cannot instantiate [" + type + "]" , e ) ; } } } return null ;


signature:
public class AbstractRequest { /** * Converts the specified object to the specified type .
 * This method is overridable . You can provide your own conversion to the
 * parameter construction by overriding this method .
 * @ param object The object to be converted
 * @ param type The type to which the specified object be converted .
 * @ return The converted object . */
protected Object convert ( Object object , Class < ? > type ) { } }

implementation: try { return ConvertUtils . convert ( object , type ) ; } catch ( Exception e ) { logger . warn ( "Cannot convert [" + object + "] to [" + type + "]" , e ) ; return null ; }


signature:
public class AbstractRequest { /** * Converts the specified object to the specified user - defined value type .
 * This method is overridable . You can provide your own conversion to the
 * parameter construction by overriding this method .
 * @ param object The object to be converted .
 * @ param type The type to which the specified object be converted .
 * @ return The converted object . */
protected Object convertUserDefinedValueType ( Object object , Class < ? > type ) { } }

implementation: if ( type . isAssignableFrom ( object . getClass ( ) ) ) { return object ; } else if ( object instanceof String ) { try { Constructor < ? > constructor = type . getConstructor ( String . class ) ; return constructor . newInstance ( object ) ; } catch ( Exception e ) { logger . debug ( "Cannot invoke [public " + type . getName ( ) + "(String.class)] constrcutor on [" + type + "]" , e ) ; } try { return type . getMethod ( "valueOf" , String . class ) . invoke ( null , object ) ; } catch ( Exception e1 ) { logger . debug ( "Cannot invoke [public static " + type . getName ( ) + ".valueOf(String.class)]" + "method on [" + type + "]" , e1 ) ; } } else { logger . warn ( "Parameter [" + object + "] cannot be converted to [" + type + "]" ) ; } return null ;


signature:
public class AbstractRequest { /** * Returns the Web endpoint method parameter from query string .
 * @ param type The parameter type .
 * @ param name The parameter name .
 * @ return The Web endpoint method parameter from the HTTP request ' s query
 * string . */
protected Object query ( Type type , String name ) { } }

implementation: return parameter ( type , name , new Function < String , Object > ( ) { public Object apply ( String name ) { return context . request ( ) . getParameter ( name ) ; } } , new Function < String , Collection < Object > > ( ) { @ SuppressWarnings ( "unchecked" ) public Collection < Object > apply ( String name ) { HttpServletRequest request = context . request ( ) ; Map < String , Object > map = new TreeMap < String , Object > ( ) ; for ( Object object : Collections . list ( request . getParameterNames ( ) ) ) { String key = ( String ) object ; if ( key . startsWith ( name + "[" ) ) { map . put ( key , request . getParameter ( key ) ) ; } } return ( map . isEmpty ( ) ) ? null : map . values ( ) ; } } ) ;


signature:
public class AbstractRequest { /** * Returns the Web endpoint method parameter from cookie in the HTTP request .
 * @ param type The parameter type .
 * @ param name The parameter name .
 * @ return The Web endpoint method parameter from cookie in the HTTP request . */
protected Object cookie ( Type type , String name ) { } }

implementation: return parameter ( type , name , new Function < String , Object > ( ) { public Object apply ( String name ) { Cookie [ ] cookies = context . request ( ) . getCookies ( ) ; if ( cookies != null ) { for ( Cookie cookie : cookies ) { if ( cookie . getName ( ) . equals ( name ) ) { return cookie . getValue ( ) ; } } } return null ; } } , new Function < String , Collection < Object > > ( ) { public Collection < Object > apply ( String name ) { HttpServletRequest request = context . request ( ) ; Map < String , Object > map = new TreeMap < String , Object > ( ) ; Cookie [ ] cookies = request . getCookies ( ) ; if ( cookies != null ) { for ( Cookie cookie : cookies ) { String key = cookie . getName ( ) ; if ( key . startsWith ( name + "[" ) ) { map . put ( key , cookie . getValue ( ) ) ; } } } return ( map . isEmpty ( ) ) ? null : map . values ( ) ; } } ) ;


signature:
public class AbstractRequest { /** * Returns the Web endpoint method parameter from HTTP session .
 * @ param type The parameter type .
 * @ param name The parameter name .
 * @ return The Web endpoint method parameter from HTTP session . */
protected Object session ( Type type , String name ) { } }

implementation: return parameter ( type , name , new Function < String , Object > ( ) { public Object apply ( String name ) { return context . session ( ) . getAttribute ( name ) ; } } , new Function < String , Collection < Object > > ( ) { @ SuppressWarnings ( "unchecked" ) public Collection < Object > apply ( String name ) { HttpSession session = context . session ( ) ; Object attribute = session . getAttribute ( name ) ; if ( attribute instanceof Collection < ? > ) { return ( Collection < Object > ) attribute ; } Map < String , Object > map = new TreeMap < String , Object > ( ) ; for ( Object object : Collections . list ( session . getAttributeNames ( ) ) ) { String key = ( String ) object ; if ( key . startsWith ( name + "[" ) ) { map . put ( key , session . getAttribute ( key ) ) ; } } return ( map . isEmpty ( ) ) ? null : map . values ( ) ; } } ) ;


signature:
public class DigestsKit { /** * 对字符串进行散列 , 支持md5与sha1算法 . */
private static byte [ ] digest ( byte [ ] input , String algorithm , byte [ ] salt , int iterations ) { } }

implementation: try { MessageDigest digest = MessageDigest . getInstance ( algorithm ) ; if ( salt != null ) { digest . update ( salt ) ; } byte [ ] result = digest . digest ( input ) ; for ( int i = 1 ; i < iterations ; i ++ ) { digest . reset ( ) ; result = digest . digest ( result ) ; } return result ; } catch ( GeneralSecurityException e ) { throw ExceptionKit . unchecked ( e ) ; }


signature:
public class Goja { /** * init databases .
 * @ param plugins plugin . */
private void initDataSource ( final Plugins plugins ) { } }

implementation: final Map < String , Properties > dbConfig = GojaConfig . loadDBConfig ( GojaConfig . getConfigProps ( ) ) ; for ( String db_config : dbConfig . keySet ( ) ) { final Properties db_props = dbConfig . get ( db_config ) ; if ( db_props != null && ! db_props . isEmpty ( ) ) { DruidDbIntializer . init ( db_config , plugins , db_props ) ; } } if ( GojaConfig . getPropertyToBoolean ( GojaPropConst . DB_SQLINXML , true ) ) { plugins . add ( new SqlInXmlPlugin ( ) ) ; }


signature:
public class Goja { /** * set freemarker variable . */
private void setFtlSharedVariable ( ) { } }

implementation:
// custmer variable
final Configuration config = FreeMarkerRender . getConfiguration ( ) ; config . setSharedVariable ( "block" , new BlockDirective ( ) ) ; config . setSharedVariable ( "extends" , new ExtendsDirective ( ) ) ; config . setSharedVariable ( "override" , new OverrideDirective ( ) ) ; config . setSharedVariable ( "super" , new SuperDirective ( ) ) ; // 增加日期美化指令 ( 类似 几分钟前 )
config . setSharedVariable ( "prettytime" , new PrettyTimeDirective ( ) ) ; if ( GojaConfig . isSecurity ( ) ) { config . setSharedVariable ( "shiro" , new ShiroTags ( config . getObjectWrapper ( ) ) ) ; }


signature:
public class DTCriterias { /** * Adding custom query condition and value
 * @ param field query condition
 * @ param condition condition
 * @ param value query condition If it is a LIKE query , then you need to pass an array of objects ,
 * the size of 2. */
public void setParam ( String field , Condition condition , Object value ) { } }

implementation: this . params . add ( Triple . of ( field , condition , value ) ) ;


signature:
public class DTCriterias { /** * Adding custom query equal value .
 * @ param field query condition
 * @ param value query condition */
public void setParam ( String field , Object value ) { } }

implementation: this . setParam ( field , Condition . EQ , value ) ;


signature:
public class DTCriterias { /** * Support for a single entity with the integration of Datatables plugin 。
 * @ param model The DB model .
 * @ return response . */
public DTResponse response ( Class < ? extends Model > model ) { } }

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


signature:
public class Responses { /** * Creates generic { @ code Response } that has the specified entity as message
 * body .
 * @ param value The object to be sent to the client .
 * @ return Generic { @ code Response } that has the specified entity as message
 * body . */
public static Response response ( Object value ) { } }

implementation: GenericResponse response = new GenericResponse ( ) ; response . entity ( value ) ; return response ;


signature:
public class Responses { /** * Creates { @ code JSONResponse } to send the specified entity to the client
 * as JSON format response .
 * @ param value The object to be sent to the client .
 * @ return { @ code JSONResponse } . */
public static JSONResponse json ( Object value ) { } }

implementation: JSONResponse response = new JSONResponse ( ) ; response . entity ( value ) ; return response ;


signature:
public class Responses { /** * Creates { @ code XMLResponse } to send the specified entity to the client as
 * XML format response .
 * @ param value The object to be sent to the client .
 * @ return { @ code XMLResponse } . */
public static XMLResponse xml ( Object value ) { } }

implementation: XMLResponse response = new XMLResponse ( ) ; response . entity ( value ) ; return response ;


signature:
public class IdCardKit { /** * 将15位身份证号码转换为18位
 * @ param idCard 15位身份编码
 * @ return 18位身份编码 */
public static String conver15CardTo18 ( String idCard ) { } }

implementation:
String idCard18 ; if ( idCard . length ( ) != CHINA_ID_MIN_LENGTH ) { return null ; } if ( isNum ( idCard ) ) { // 获取出生年月日
String birthday = idCard . substring ( 6 , 12 ) ; Date birthDate = null ; try { birthDate = new SimpleDateFormat ( "yyMMdd" ) . parse ( birthday ) ; } catch ( ParseException e ) { e . printStackTrace ( ) ; } Calendar cal = Calendar . getInstance ( ) ; if ( birthDate != null ) { cal . setTime ( birthDate ) ; } // 获取出生年 ( 完全表现形式 , 如 : 2010)
String sYear = String . valueOf ( cal . get ( Calendar . YEAR ) ) ; idCard18 = idCard . substring ( 0 , 6 ) + sYear + idCard . substring ( 8 ) ; // 转换字符数组
char [ ] cArr = idCard18 . toCharArray ( ) ; int [ ] iCard = converCharToInt ( cArr ) ; int iSum17 = getPowerSum ( iCard ) ; // 获取校验位
String sVal = getCheckCode18 ( iSum17 ) ; if ( sVal . length ( ) > 0 ) { idCard18 += sVal ; } else { return null ; } } else { return null ; } return idCard18 ;


signature:
public class IdCardKit { /** * 验证身份证是否合法 */
public static boolean validateCard ( String idCard ) { } }

implementation: String card = idCard . trim ( ) ; if ( validateIdCard18 ( card ) ) { return true ; } if ( validateIdCard15 ( card ) ) { return true ; } String [ ] cardval = validateIdCard10 ( card ) ; if ( cardval != null ) { if ( cardval [ 2 ] . equals ( "true" ) ) { return true ; } } return false ;


signature:
public class IdCardKit { /** * 验证18位身份编码是否合法
 * @ param idCard 身份编码
 * @ return 是否合法 */
public static boolean validateIdCard18 ( String idCard ) { } }

implementation:
boolean bTrue = false ; if ( idCard . length ( ) == CHINA_ID_MAX_LENGTH ) { // 前17位
String code17 = idCard . substring ( 0 , 17 ) ; // 第18位
String code18 = idCard . substring ( 17 , CHINA_ID_MAX_LENGTH ) ; if ( isNum ( code17 ) ) { char [ ] cArr = code17 . toCharArray ( ) ; int [ ] iCard = converCharToInt ( cArr ) ; int iSum17 = getPowerSum ( iCard ) ; // 获取校验位
String val = getCheckCode18 ( iSum17 ) ; if ( val . length ( ) > 0 ) { if ( val . equalsIgnoreCase ( code18 ) ) { bTrue = true ; } } } } return bTrue ;


signature:
public class IdCardKit { /** * 验证15位身份编码是否合法
 * @ param idCard 身份编码
 * @ return 是否合法 */
public static boolean validateIdCard15 ( String idCard ) { } }

implementation: if ( idCard . length ( ) != CHINA_ID_MIN_LENGTH ) { return false ; } if ( isNum ( idCard ) ) { String proCode = idCard . substring ( 0 , 2 ) ; if ( cityCodes . get ( proCode ) == null ) { return false ; } String birthCode = idCard . substring ( 6 , 12 ) ; Date birthDate = null ; try { birthDate = new SimpleDateFormat ( "yy" ) . parse ( birthCode . substring ( 0 , 2 ) ) ; } catch ( ParseException e ) { e . printStackTrace ( ) ; } Calendar cal = Calendar . getInstance ( ) ; if ( birthDate != null ) { cal . setTime ( birthDate ) ; } if ( ! valiDate ( cal . get ( Calendar . YEAR ) , Integer . valueOf ( birthCode . substring ( 2 , 4 ) ) , Integer . valueOf ( birthCode . substring ( 4 , 6 ) ) ) ) { return false ; } } else { return false ; } return true ;


signature:
public class IdCardKit { /** * 验证10位身份编码是否合法
 * @ param idCard 身份编码
 * @ return 身份证信息数组 < p > [ 0 ] - 台湾 、 澳门 、 香港 [ 1 ] - 性别 ( 男M , 女F , 未知N ) [ 2 ] - 是否合法 ( 合法true , 不合法false )
 * 若不是身份证件号码则返回null < / p > */
public static String [ ] validateIdCard10 ( String idCard ) { } }

implementation:
String [ ] info = new String [ 3 ] ; String card = idCard . replaceAll ( "[\\(|\\)]" , "" ) ; if ( card . length ( ) != 8 && card . length ( ) != 9 && idCard . length ( ) != 10 ) { return null ; } if ( idCard . matches ( "^[a-zA-Z][0-9]{9}$" ) ) { // 台湾
info [ 0 ] = "台湾" ; System . out . println ( "11111" ) ; String char2 = idCard . substring ( 1 , 2 ) ; if ( char2 . equals ( "1" ) ) { info [ 1 ] = "M" ; System . out . println ( "MMMMMMM" ) ; } else if ( char2 . equals ( "2" ) ) { info [ 1 ] = "F" ; System . out . println ( "FFFFFFF" ) ; } else { info [ 1 ] = "N" ; info [ 2 ] = "false" ; System . out . println ( "NNNN" ) ; return info ; } info [ 2 ] = validateTWCard ( idCard ) ? "true" : "false" ; } else if ( idCard . matches ( "^[1|5|7][0-9]{6}\\(?[0-9A-Z]\\)?$" ) ) { // 澳门
info [ 0 ] = "澳门" ; info [ 1 ] = "N" ; // TODO
} else if ( idCard . matches ( "^[A-Z]{1,2}[0-9]{6}\\(?[0-9A]\\)?$" ) ) { // 香港
info [ 0 ] = "香港" ; info [ 1 ] = "N" ; info [ 2 ] = validateHKCard ( idCard ) ? "true" : "false" ; } else { return null ; } return info ;


signature:
public class IdCardKit { /** * 验证台湾身份证号码
 * @ param idCard 身份证号码
 * @ return 验证码是否符合 */
public static boolean validateTWCard ( String idCard ) { } }

implementation: String start = idCard . substring ( 0 , 1 ) ; String mid = idCard . substring ( 1 , 9 ) ; String end = idCard . substring ( 9 , 10 ) ; Integer iStart = twFirstCode . get ( start ) ; Integer sum = iStart / 10 + ( iStart % 10 ) * 9 ; char [ ] chars = mid . toCharArray ( ) ; Integer iflag = 8 ; for ( char c : chars ) { sum = sum + Integer . valueOf ( c + "" ) * iflag ; iflag -- ; } return ( sum % 10 == 0 ? 0 : ( 10 - sum % 10 ) ) == Integer . valueOf ( end ) ;


signature:
public class IdCardKit { /** * 验证香港身份证号码 ( 存在Bug , 部份特殊身份证无法检查 ) < p > 身份证前2位为英文字符 , 如果只出现一个英文字符则表示第一位是空格 , 对应数字58 前2位英文字符A - Z分别对应数字10-35
 * 最后一位校验码为0-9的数字加上字符 " A " , " A " 代表10 < / p > < p > 将身份证号码全部转换为数字 , 分别对应乘9-1相加的总和 , 整除11则证件号码有效 < / p >
 * @ param idCard 身份证号码
 * @ return 验证码是否符合 */
public static boolean validateHKCard ( String idCard ) { } }

implementation: String card = idCard . replaceAll ( "[\\(|\\)]" , "" ) ; Integer sum ; if ( card . length ( ) == 9 ) { sum = ( ( int ) card . substring ( 0 , 1 ) . toUpperCase ( ) . toCharArray ( ) [ 0 ] - 55 ) * 9 + ( ( int ) card . substring ( 1 , 2 ) . toUpperCase ( ) . toCharArray ( ) [ 0 ] - 55 ) * 8 ; card = card . substring ( 1 , 9 ) ; } else { sum = 522 + ( ( int ) card . substring ( 0 , 1 ) . toUpperCase ( ) . toCharArray ( ) [ 0 ] - 55 ) * 8 ; } String mid = card . substring ( 1 , 7 ) ; String end = card . substring ( 7 , 8 ) ; char [ ] chars = mid . toCharArray ( ) ; Integer iflag = 7 ; for ( char c : chars ) { sum = sum + Integer . valueOf ( c + "" ) * iflag ; iflag -- ; } if ( end . toUpperCase ( ) . equals ( "A" ) ) { sum = sum + 10 ; } else { sum = sum + Integer . valueOf ( end ) ; } return ( sum % 11 == 0 ) ;


signature:
public class IdCardKit { /** * 将字符数组转换成数字数组
 * @ param ca 字符数组
 * @ return 数字数组 */
public static int [ ] converCharToInt ( char [ ] ca ) { } }

implementation: int len = ca . length ; int [ ] iArr = new int [ len ] ; try { for ( int i = 0 ; i < len ; i ++ ) { iArr [ i ] = Integer . parseInt ( String . valueOf ( ca [ i ] ) ) ; } } catch ( NumberFormatException e ) { e . printStackTrace ( ) ; } return iArr ;


signature:
public class IdCardKit { /** * 将身份证的每位和对应位的加权因子相乘之后 , 再得到和值
 * @ param iArr 身份证的数值表示
 * @ return 身份证编码 。 */
public static int getPowerSum ( int [ ] iArr ) { } }

implementation: int iSum = 0 ; if ( power . length == iArr . length ) { for ( int i = 0 ; i < iArr . length ; i ++ ) { for ( int j = 0 ; j < power . length ; j ++ ) { if ( i == j ) { iSum = iSum + iArr [ i ] * power [ j ] ; } } } } return iSum ;


signature:
public class IdCardKit { /** * 将power和值与11取模获得余数进行校验码判断
 * @ param iSum pow 余数比较
 * @ return 校验位 */
public static String getCheckCode18 ( int iSum ) { } }

implementation: String sCode = "" ; switch ( iSum % 11 ) { case 10 : sCode = "2" ; break ; case 9 : sCode = "3" ; break ; case 8 : sCode = "4" ; break ; case 7 : sCode = "5" ; break ; case 6 : sCode = "6" ; break ; case 5 : sCode = "7" ; break ; case 4 : sCode = "8" ; break ; case 3 : sCode = "9" ; break ; case 2 : sCode = "x" ; break ; case 1 : sCode = "0" ; break ; case 0 : sCode = "1" ; break ; } return sCode ;


signature:
public class IdCardKit { /** * 根据身份编号获取年龄
 * @ param idCard 身份编号
 * @ return 年龄 */
public static int getAgeByIdCard ( String idCard ) { } }

implementation: int iAge ; if ( idCard . length ( ) == CHINA_ID_MIN_LENGTH ) { idCard = conver15CardTo18 ( idCard ) ; } String year = idCard . substring ( 6 , 10 ) ; Calendar cal = Calendar . getInstance ( ) ; int iCurrYear = cal . get ( Calendar . YEAR ) ; iAge = iCurrYear - Integer . valueOf ( year ) ; return iAge ;


signature:
public class IdCardKit { /** * 根据身份编号获取生日
 * @ param idCard 身份编号
 * @ return 生日 ( yyyyMMdd ) */
public static String getBirthByIdCard ( String idCard ) { } }

implementation: Integer len = idCard . length ( ) ; if ( len < CHINA_ID_MIN_LENGTH ) { return null ; } else if ( len == CHINA_ID_MIN_LENGTH ) { idCard = conver15CardTo18 ( idCard ) ; } return idCard . substring ( 6 , 14 ) ;


signature:
public class IdCardKit { /** * 根据身份编号获取生日年
 * @ param idCard 身份编号
 * @ return 生日 ( yyyy ) */
public static Short getYearByIdCard ( String idCard ) { } }

implementation: Integer len = idCard . length ( ) ; if ( len < CHINA_ID_MIN_LENGTH ) { return null ; } else if ( len == CHINA_ID_MIN_LENGTH ) { idCard = conver15CardTo18 ( idCard ) ; } return Short . valueOf ( idCard . substring ( 6 , 10 ) ) ;


signature:
public class IdCardKit { /** * 根据身份编号获取性别
 * @ param idCard 身份编号
 * @ return 性别 ( M男 , F女 , N未知 ) */
public static String getGenderByIdCard ( String idCard ) { } }

implementation: String sGender = "N" ; if ( idCard . length ( ) == CHINA_ID_MIN_LENGTH ) { idCard = conver15CardTo18 ( idCard ) ; } String sCardNum = idCard . substring ( 16 , 17 ) ; if ( Integer . parseInt ( sCardNum ) % 2 != 0 ) { sGender = "M" ; } else { sGender = "F" ; } return sGender ;


signature:
public class IdCardKit { /** * 根据身份编号获取户籍省份
 * @ param idCard 身份编码
 * @ return 省级编码 。 */
public static String getProvinceByIdCard ( String idCard ) { } }

implementation: int len = idCard . length ( ) ; String sProvince ; String sProvinNum = "" ; if ( len == CHINA_ID_MIN_LENGTH || len == CHINA_ID_MAX_LENGTH ) { sProvinNum = idCard . substring ( 0 , 2 ) ; } sProvince = cityCodes . get ( sProvinNum ) ; return sProvince ;


signature:
public class IdCardKit { /** * 验证小于当前日期 是否有效
 * @ param iYear 待验证日期 ( 年 )
 * @ param iMonth 待验证日期 ( 月 1-12)
 * @ param iDate 待验证日期 ( 日 )
 * @ return 是否有效 */
private static boolean valiDate ( int iYear , int iMonth , int iDate ) { } }

implementation: Calendar cal = Calendar . getInstance ( ) ; int year = cal . get ( Calendar . YEAR ) ; int datePerMonth ; if ( iYear < MIN || iYear >= year ) { return false ; } if ( iMonth < 1 || iMonth > 12 ) { return false ; } switch ( iMonth ) { case 4 : case 6 : case 9 : case 11 : datePerMonth = 30 ; break ; case 2 : boolean dm = ( ( iYear % 4 == 0 && iYear % 100 != 0 ) || ( iYear % 400 == 0 ) ) && ( iYear > MIN && iYear < year ) ; datePerMonth = dm ? 29 : 28 ; break ; default : datePerMonth = 31 ; } return ( iDate >= 1 ) && ( iDate <= datePerMonth ) ;


signature:
public class DirectiveKit { /** * 取得参数 < code > params < / code > 中必须存在的指定Key的值 , 如果不存在 , 抛出异常
 * @ param params 参数Map
 * @ param key 必须存在的Key
 * @ return 对应key的值
 * @ throws freemarker . template . TemplateException 异常 , 如果key不存在params中则会出现异常 */
@ SuppressWarnings ( "rawtypes" ) public static String getRequiredParam ( Map params , String key ) throws TemplateException { } }

implementation: Object value = params . get ( key ) ; if ( value == null || StringUtils . isEmpty ( value . toString ( ) ) ) { throw new TemplateModelException ( "not found required parameter:" + key + " for directive" ) ; } return value . toString ( ) ;


signature:
public class DirectiveKit { /** * 取得 < code > params < / code > 中指定Key的值 , 如果不存在返回默认信息
 * @ param params 参数Map
 * @ param key key信息
 * @ param defaultValue 默认值
 * @ return 对应Key的值 , 不存在返回默认 */
@ SuppressWarnings ( "rawtypes" ) public static String getParam ( Map params , String key , String defaultValue ) { } }

implementation: Object value = params . get ( key ) ; return value == null ? defaultValue : value . toString ( ) ;


signature:
public class DirectiveKit { /** * 从Freemarker的运行环境中 , 取得指定名称的覆盖内容渲染器
 * @ param env 运行环境
 * @ param name 指定名称
 * @ return 覆盖内容渲染器
 * @ throws freemarker . template . TemplateModelException 模板模型异常 */
public static TemplateDirectiveBodyOverrideWraper getOverrideBody ( Environment env , String name ) throws TemplateModelException { } }

implementation: return ( TemplateDirectiveBodyOverrideWraper ) env . getVariable ( DirectiveKit . getOverrideVariableName ( name ) ) ;


signature:
public class DirectiveKit { /** * 对指定的Body的渲染器 , 指定其父亲的内容区域
 * @ param topBody 内容渲染器
 * @ param overrideBody 需要覆盖的内容渲染器 */
public static void setTopBodyForParentBody ( TemplateDirectiveBodyOverrideWraper topBody , TemplateDirectiveBodyOverrideWraper overrideBody ) { } }

implementation: TemplateDirectiveBodyOverrideWraper parent = overrideBody ; while ( parent . parentBody != null ) { parent = parent . parentBody ; } parent . parentBody = topBody ;


signature:
public class Invoke { /** * Invokes Web endpoint method .
 * This method processes the request as the following steps :
 * < ol >
 * < li > Gets Web endpoint class by invoking { @ code Method # getDeclaringClass ( ) }
 * of the Web endpoint method set on the current HTTP request processing
 * context and instantiates it with the { @ link Instantiator } that the
 * { @ link Configuration # instantiator ( ) } returns . < / li >
 * < li > Invokes Web endpoint method on the constructed instance with the
 * parameters set on the current HTTP request processing context and sets
 * the invocation result to the current HTTP request processing context . < / li >
 * < li > If the invocation is failed with { @ code WebException } , this method
 * sends HTTP response with the status code the exception has . < / li >
 * < li > If the invocation is failed for any reasons , this method sends HTTP
 * response with the status code 500 ( INTERNAL _ SERVER _ ERROR ) . < / li >
 * < / ol >
 * @ param context HTTP request processing context . */
public boolean apply ( WebContext context ) { } }

implementation: WebException e = null ; try { context . result ( new MethodInvocation < Object > ( context . method ( ) , instantiate ( context . method ( ) . getDeclaringClass ( ) ) , context . parameters ( ) . toArray ( ) ) . proceed ( ) ) ; return true ; } catch ( WebException exception ) { e = exception ; } catch ( Throwable throwable ) { e = new EndpointInvocationFailedException ( HttpServletResponse . SC_INTERNAL_SERVER_ERROR , throwable ) ; } logger . warn ( "Failed to invoke Web endpoint" , e ) ; try { context . response ( ) . sendError ( e . status ( ) ) ; return false ; } catch ( IOException exception ) { throw new UncheckedException ( exception ) ; }


signature:
public class RequestPermission { /** * Set a permission and message wrapper class { @ link PermBean }
 * with desired permission / s and respective messages .
 * @ param permBean A wrapper class containing
 * permissions to be asked and
 * respective message to be shown .
 * @ return modified object of RequestPermission containing
 * permissions to be asked and respective messages to be shown . */
public RequestPermission with ( PermBean permBean ) { } }

implementation: if ( permBean . getPermissions ( ) . isEmpty ( ) ) { throw new NullPointerException ( "Permission and Message collection cannot be null !" ) ; } RequestPermission . permBean = permBean ; return this ;


signature:
public class RequestPermission { /** * < p > Execute request for all provided permissions . It checks if permissions
 * are already granted or required to grant . < / p >
 * < p > Only if only API is greater than 23 ( i . e . Marshmallows or later ) . < / p > */
public void request ( ) { } }

implementation:
mLog . i ( TAG , "Requesting........." ) ; resultMap = new LinkedHashMap < > ( permBean . size ( ) ) ; if ( Build . VERSION . SDK_INT >= Build . VERSION_CODES . M && isPermissionRequired ( permBean ) ) { // if result target is not set use activity as default .
if ( RequestPermission . mBase == null ) { RequestPermission . mBase = mActivity ; } mLog . i ( TAG , "On permission result " + mBase . getClass ( ) . getSimpleName ( ) + " class methods will be executed." ) ; PermBean bean = new PermBean ( ) ; Map < Permission , String > map = permBean . getPermissions ( ) ; for ( Map . Entry < Permission , String > m : map . entrySet ( ) ) { if ( mActivity . checkSelfPermission ( m . getKey ( ) . toString ( ) ) != PackageManager . PERMISSION_GRANTED ) { bean . put ( m . getKey ( ) , m . getValue ( ) ) ; mLog . i ( TAG , m . getKey ( ) . name ( ) + " requires permission" ) ; } else { resultMap . put ( m . getKey ( ) , Result . GRANTED ) ; } } // ask permissions for granted methods .
if ( bean . size ( ) > 0 ) { showDialog ( bean ) ; } } else { for ( Map . Entry < Permission , String > m : permBean . getPermissions ( ) . entrySet ( ) ) { resultMap . put ( m . getKey ( ) , Result . GRANTED ) ; } try { invokeAnnotatedMethods ( resultMap ) ; } catch ( InvocationTargetException e ) { mLog . e ( TAG , e . getMessage ( ) , e ) ; } catch ( IllegalAccessException e ) { mLog . e ( TAG , e . getMessage ( ) , e ) ; } mLog . i ( TAG , "request: Redundant" ) ; }


signature:
public class RequestPermission { /** * < p > Check weather single or multiple permissions requires grant . < / p >
 * Use instead { @ link RequestPermission # request ( ) } directly .
 * @ param permBean { @ link PermBean } wrapper class .
 * @ return boolean value if any one of permission requires to be asked . */
private static boolean isPermissionRequired ( PermBean permBean ) { } }

implementation: if ( Build . VERSION . SDK_INT < Build . VERSION_CODES . M ) { return false ; } if ( permBean . size ( ) > 0 ) { Map < Permission , String > map = permBean . getPermissions ( ) ; for ( Permission permission : map . keySet ( ) ) { int status = mActivity . checkSelfPermission ( permission . toString ( ) ) ; if ( status != PackageManager . PERMISSION_GRANTED ) return true ; } } return false ;


signature:
public class RequestPermission { /** * Show dialog fragment to show dialogs before asking permission .
 * Or you can set to show dialogs only when user denied permission earlier .
 * @ param permBean { @ link PermBean } wrapper class
 * with Permission and respective messages . */
private void showDialog ( PermBean permBean ) { } }

implementation: PermissionDialogFragment fragment = PermissionDialogFragment . getInstance ( permBean , requestCode ) ; fragment . show ( mActivity . getSupportFragmentManager ( ) , TAG ) ;


signature:
public class RequestPermission { /** * Get on Request Permissions Results , invoke annotated methods and send a local broadcast of results .
 * @ param requestCode Auto Generated request code .
 * @ param permissions Permissions asked .
 * @ param grantResults Result of permissions asked . */
public static void onResult ( int requestCode , @ NonNull String [ ] permissions , @ NonNull int [ ] grantResults ) { } }

implementation:
if ( RequestPermission . requestCode == requestCode ) { /* Sort granted and denied permissions in array list */
int count = permissions . length ; List < String > granted = new ArrayList < > ( count ) ; List < String > denied = new ArrayList < > ( count ) ; for ( int k = 0 ; k < count ; k ++ ) { resultMap . put ( Permission . get ( permissions [ k ] ) , Result . get ( grantResults [ k ] ) ) ; if ( grantResults [ k ] == PackageManager . PERMISSION_GRANTED ) { granted . add ( permissions [ k ] ) ; } else if ( grantResults [ k ] == PackageManager . PERMISSION_DENIED ) { denied . add ( permissions [ k ] ) ; } } String [ ] grantedArray = granted . toArray ( new String [ granted . size ( ) ] ) ; String [ ] deniedArray = denied . toArray ( new String [ denied . size ( ) ] ) ; // forward to invoke annotated methods .
try { invokeAnnotatedMethods ( resultMap ) ; } catch ( IllegalAccessException e ) { mLog . e ( TAG , e . getMessage ( ) , e ) ; } catch ( InvocationTargetException e ) { mLog . e ( TAG , e . getMessage ( ) , e ) ; } /* Send local broadcast on permissions result . */
Intent intent = new Intent ( PERMISSION_RESULT_BROADCAST ) ; intent . putExtra ( GRANTED , grantedArray ) ; intent . putExtra ( DENIED , deniedArray ) ; LocalBroadcastManager . getInstance ( mActivity ) . sendBroadcast ( intent ) ; }


signature:
public class RequestPermission { /** * Invoke annotated methods in provided class .
 * @ param resultMap prepared Map of Permissions and respective results .
 * @ throws InvocationTargetException
 * @ throws IllegalAccessException */
private static void invokeAnnotatedMethods ( HashMap < Permission , Result > resultMap ) throws InvocationTargetException , IllegalAccessException { } }

implementation:
Method [ ] methods = getBase ( ) . getClass ( ) . getDeclaredMethods ( ) ; // check all methods from provided class or by default provided activity .
for ( Method method : methods ) { if ( method != null && method . isAnnotationPresent ( GrantedPermission . class ) ) { GrantedPermission granted = method . getAnnotation ( GrantedPermission . class ) ; if ( granted != null ) { /* Check single value annotations */
if ( ! granted . permission ( ) . equals ( "" ) || granted . value ( ) != Permission . NONE ) { for ( Map . Entry < Permission , Result > permResult : resultMap . entrySet ( ) ) { // invoke method if String permission is annotated .
if ( ( granted . permission ( ) . equals ( permResult . getKey ( ) . toString ( ) ) || granted . value ( ) == permResult . getKey ( ) ) && Result . GRANTED == permResult . getValue ( ) ) { method . invoke ( getBase ( ) ) ; mLog . i ( TAG , "invoking grant method: " + method . getName ( ) ) ; } } continue ; } /* Check array fields in annotations */
if ( granted . values ( ) . length > 0 ) { if ( allValuesGranted ( granted . values ( ) , resultMap ) ) { method . invoke ( getBase ( ) ) ; mLog . i ( TAG , "invoking grant method: " + method . getName ( ) ) ; } continue ; } if ( granted . permissions ( ) . length > 0 ) { if ( allValuesGranted ( granted . permissions ( ) , resultMap ) ) { method . invoke ( getBase ( ) ) ; mLog . i ( TAG , "invoking grant method: " + method . getName ( ) ) ; } } } } else if ( method != null && method . isAnnotationPresent ( DeniedPermission . class ) ) { DeniedPermission denied = method . getAnnotation ( DeniedPermission . class ) ; if ( denied != null ) { /* Check single value annotations */
if ( ! denied . permission ( ) . equals ( "" ) || denied . value ( ) != Permission . NONE ) { for ( Map . Entry < Permission , Result > permResult : resultMap . entrySet ( ) ) { // invoke method if String permission is annotated .
if ( ( denied . permission ( ) . equals ( permResult . getKey ( ) . toString ( ) ) || denied . value ( ) == permResult . getKey ( ) ) && Result . DENIED == permResult . getValue ( ) ) { method . invoke ( getBase ( ) ) ; mLog . i ( TAG , "invoking denied method: " + method . getName ( ) ) ; } } continue ; } /* Check array fields in annotations */
if ( denied . values ( ) . length > 0 ) { if ( anyValueDenied ( denied . values ( ) , resultMap ) ) { method . invoke ( getBase ( ) ) ; mLog . i ( TAG , "invoking denied method: " + method . getName ( ) ) ; } continue ; } if ( denied . permissions ( ) . length > 0 ) { if ( anyValueDenied ( denied . permissions ( ) , resultMap ) ) { mLog . i ( TAG , "invoking denied method: " + method . getName ( ) ) ; method . invoke ( getBase ( ) ) ; } } } } else if ( method != null && method . isAnnotationPresent ( OPermission . class ) ) { OPermission oPermission = method . getAnnotation ( OPermission . class ) ; final Annotation [ ] [ ] paramAnnotations = method . getParameterAnnotations ( ) ; final Class [ ] paramTypes = method . getParameterTypes ( ) ; if ( oPermission != null && paramAnnotations [ 0 ] [ 0 ] instanceof co . omkar . utility . opermission . annotation . Result && ( paramTypes [ 0 ] == boolean . class || paramTypes [ 0 ] == Boolean . class ) ) { /* Check single value annotations */
for ( Map . Entry < Permission , Result > permResult : resultMap . entrySet ( ) ) { // invoke method if String permission is annotated .
if ( oPermission . permission ( ) . equals ( permResult . getKey ( ) . toString ( ) ) || oPermission . value ( ) . equals ( permResult . getKey ( ) ) ) { switch ( permResult . getValue ( ) ) { // Permission is granted .
case GRANTED : method . invoke ( getBase ( ) , true ) ; mLog . i ( TAG , "invoking method: " + method . getName ( ) ) ; break ; // Permission is denied .
case DENIED : method . invoke ( getBase ( ) , false ) ; mLog . i ( TAG , "invoking method: " + method . getName ( ) ) ; break ; } } } /* Check array fields in annotations */
if ( oPermission . values ( ) . length > 0 ) { if ( allValuesGranted ( oPermission . values ( ) , resultMap ) ) { method . invoke ( getBase ( ) , true ) ; mLog . i ( TAG , "invoking as granted method: " + method . getName ( ) ) ; } else { method . invoke ( getBase ( ) , false ) ; mLog . i ( TAG , "invoking as denied method: " + method . getName ( ) ) ; } continue ; } if ( oPermission . permissions ( ) . length > 0 ) { if ( allValuesGranted ( oPermission . permissions ( ) , resultMap ) ) { method . invoke ( getBase ( ) , true ) ; mLog . i ( TAG , "invoking as granted method: " + method . getName ( ) ) ; } else { method . invoke ( getBase ( ) , false ) ; mLog . i ( TAG , "invoking as denied method: " + method . getName ( ) ) ; } } } } }


signature:
public class RequestPermission { /** * Check if annotated result permissions contains all values from annotated array .
 * Then it also check if all permissions in annotated method value array are granted .
 * @ param values Annotated value ( { @ link Permission } ) array .
 * @ param resultMap Permission and respective result map .
 * @ return false if any of above condition fails . */
private static boolean allValuesGranted ( Object [ ] values , HashMap < Permission , Result > resultMap ) { } }

implementation: if ( values instanceof Permission [ ] ) { Set < Permission > valueSet = new HashSet < > ( Arrays . asList ( ( Permission [ ] ) values ) ) ; if ( resultMap . keySet ( ) . containsAll ( valueSet ) ) { for ( Object value : values ) { if ( Result . GRANTED != resultMap . get ( ( Permission ) value ) ) { mLog . i ( TAG , "denied - " + value . toString ( ) ) ; return false ; } } return true ; } } else if ( values instanceof String [ ] ) { Set < String > valueSet = new HashSet < > ( Arrays . asList ( ( String [ ] ) values ) ) ; Set < String > permission = new HashSet < > ( ) ; for ( Permission perm : resultMap . keySet ( ) ) { permission . add ( perm . toString ( ) ) ; } if ( permission . containsAll ( valueSet ) ) { for ( Object value : values ) { if ( Result . GRANTED != resultMap . get ( Permission . get ( String . valueOf ( value ) ) ) ) { mLog . i ( TAG , "denied - " + value ) ; return false ; } } return true ; } } return false ;


signature:
public class RequestPermission { /** * Check if annotated result permissions contains all values from annotated array .
 * Then it also check if any permission in annotated method value array is denied .
 * @ param values ( { @ link Permission } or { @ link String } ) array .
 * @ param resultMap Permission and respective result map .
 * @ return false if first statement is not satisfied else true if both are satisfied . */
private static boolean anyValueDenied ( Object [ ] values , HashMap < Permission , Result > resultMap ) { } }

implementation: if ( values instanceof Permission [ ] ) { Set < Permission > valueSet = new LinkedHashSet < > ( Arrays . asList ( ( Permission [ ] ) values ) ) ; if ( resultMap . keySet ( ) . containsAll ( valueSet ) ) { for ( Object value : values ) { if ( Result . DENIED == resultMap . get ( ( Permission ) value ) ) { mLog . i ( TAG , "denied - " + value . toString ( ) ) ; return true ; } } } } else if ( values instanceof String [ ] ) { Set < String > valueSet = new HashSet < > ( Arrays . asList ( ( String [ ] ) values ) ) ; Set < String > permissionSet = new HashSet < > ( ) ; for ( Permission perm : resultMap . keySet ( ) ) { permissionSet . add ( perm . toString ( ) ) ; } if ( permissionSet . containsAll ( valueSet ) ) { for ( Object value : values ) { if ( Result . DENIED == resultMap . get ( Permission . get ( ( String ) value ) ) ) { mLog . i ( TAG , "denied - " + value ) ; return true ; } } } } return false ;


signature:
public class StandardRestServiceBinder { /** * Creates an instance of an interface which is supposed to handle method calls in the proxy . */
@ Nonnull private MethodInvocationHandler getMethodInvocationHandler ( @ Nonnull Method method , @ Nonnull final Class < ? > clazz , @ Nonnull String serviceBaseUrl ) { } }

implementation:
// toString + hashCode + equals
if ( method . getName ( ) . equals ( "toString" ) && method . getParameterTypes ( ) . length == 0 ) { return ( proxy , method1 , args ) -> clazz . getSimpleName ( ) ; } else if ( method . getName ( ) . equals ( "hashCode" ) && method . getParameterTypes ( ) . length == 0 ) { return new MethodInvocationHandler ( ) { @ Override public Object invoke ( Object proxy , Method method , Object [ ] args ) throws Throwable { return this . hashCode ( ) ; } } ; } else if ( method . getName ( ) . equals ( "equals" ) && method . getParameterTypes ( ) . length == 1 && method . getParameterTypes ( ) [ 0 ] == Object . class ) { return ( proxy , method12 , args ) -> proxy == args [ 0 ] ; } return createRequestMappingHandler ( method , serviceBaseUrl ) ;


signature:
public class Dao { /** * 获取SQL , 动态SQL
 * @ param sqlId xml文件中的sql id
 * @ param param xml sql中的变量map
 * @ return 返回处理对象 , key为 sql , value为参数 */
public static Pair < String , List < Object > > dynamicSql ( String sqlId , Map < String , Object > param ) { } }

implementation: String sqlTemplete = SqlKit . sql ( sqlId ) ; if ( null == sqlTemplete || sqlTemplete . isEmpty ( ) ) { logger . error ( "sql语句不存在：sql id是" + sqlId ) ; return null ; } if ( param == null ) { param = Maps . newHashMap ( ) ; } String sql = Freemarkers . render ( sqlTemplete , param ) ; List < Object > params = Lists . newArrayList ( ) ; Set < String > keySet = param . keySet ( ) ; for ( String key : keySet ) { if ( param . get ( key ) == null ) { break ; } Object paramValue = param . get ( key ) ; final String placeChar = StringPool . HASH + key + StringPool . HASH ; if ( StringUtils . containsIgnoreCase ( sql , placeChar ) ) { sql = StringUtils . replace ( sql , placeChar , StringPool . QUESTION_MARK ) ; params . add ( paramValue ) ; } } return Pair . of ( sql . replaceAll ( "[\\s]{2,}" , " " ) , params ) ;


signature:
public class Dao { /** * According to the default primary key < code > id < / code > is for the new data and entity .
 * @ param m model
 * @ param < M > Generic entity references
 * @ return If for the new form of return true . */
public static < M extends Model > boolean isNew ( M m ) { } }

implementation: final Table table = TableMapping . me ( ) . getTable ( m . getClass ( ) ) ; final String [ ] pks = table . getPrimaryKey ( ) ; return isNew ( m , pks [ 0 ] ) ;


signature:
public class Dao { /** * Query the database record set .
 * @ param sqlSelect SqlNode Select
 * @ return query result .
 * @ see SqlSelect
 * @ see FindBy */
public static List < Record > findBy ( SqlSelect sqlSelect ) { } }

implementation: Preconditions . checkNotNull ( sqlSelect , "The Query SqlNode is must be not null." ) ; return Db . find ( sqlSelect . toString ( ) , sqlSelect . getParams ( ) . toArray ( ) ) ;


signature:
public class Dao { /** * Query a data record .
 * @ param sqlSelect SqlNode Select
 * @ return query result .
 * @ see SqlSelect
 * @ see FindBy */
public static Record findOne ( SqlSelect sqlSelect ) { } }

implementation: Preconditions . checkNotNull ( sqlSelect , "The Query SqlNode is must be not null." ) ; return Db . findFirst ( sqlSelect . toString ( ) , sqlSelect . getParams ( ) . toArray ( ) ) ;


signature:
public class Dao { /** * 根据多个数据通过主键批量删除数据
 * @ param ids 要删除的数据值数组
 * @ param modelClass 对应的Model的Class
 * @ return 是否删除成功 */
public static < M extends Model > boolean deleteByIds ( Serializable [ ] ids , Class < M > modelClass ) { } }

implementation:
final Table table = TableMapping . me ( ) . getTable ( modelClass ) ; final String [ ] primaryKey = table . getPrimaryKey ( ) ; if ( primaryKey == null || primaryKey . length < 1 || ids == null ) { throw new IllegalArgumentException ( "需要删除的表数据主键不存在，无法删除!" ) ; } // 暂时支持单主键的 , 多主键的后续在说吧 。
final String question_mark = StringUtils . repeat ( StringPool . QUESTION_MARK , StringPool . COMMA , ids . length ) ; String deleteSql = "DELETE FROM " + table . getName ( ) + " WHERE " + primaryKey [ 0 ] + " IN (" + question_mark + ")" ; return Db . update ( deleteSql , ids ) >= 0 ;


signature:
public class Dao { /** * According to the primary key and entity determine whether for the new entity .
 * @ param m Database model .
 * @ param pk _ column PK Column .
 * @ param < M > Generic entity references .
 * @ return If for the new form of return true . */
public static < M extends Model > boolean isNew ( M m , String pk_column ) { } }

implementation: final Object val = m . get ( pk_column ) ; return val == null || val instanceof Number && ( ( Number ) val ) . intValue ( ) <= 0 ;


signature:
public class Dao { /** * Paging retrieve , default sorted by id , you need to specify the datatables request parameters .
 * @ param sqlPaginatePrefix 分页搜索前缀
 * @ param pageDto required parameter .
 * @ return Paging data . */
public static Page < Record > paginate ( String sqlPaginatePrefix , PageDto pageDto ) { } }

implementation: SqlNode sqlNode = SqlKit . sqlNode ( sqlPaginatePrefix + ".paginate" ) ; Preconditions . checkNotNull ( sqlNode , "[" + sqlPaginatePrefix + ".paginate]分页Sql不存在,无法执行分页" ) ; String where = sqlNode . whereSql ; int pageSize = pageDto . pageSize ; int p = pageDto . page ; int start = ( ( p - 1 ) * pageSize ) + 1 ; final List < RequestParam > params = pageDto . params ; final List < Object > query_params = pageDto . query_params ; if ( ( params . isEmpty ( ) ) && ( query_params . isEmpty ( ) ) ) { return Db . paginate ( start , pageSize , sqlNode . selectSql , where ) ; } else { if ( ! params . isEmpty ( ) ) { where += ( sqlNode . condition ? StringPool . SPACE : " WHERE 1=1 " ) ; } for ( RequestParam param : pageDto . params ) { where += param . toSql ( ) ; } return Db . paginate ( start , pageSize , sqlNode . selectSql , where , query_params . toArray ( ) ) ; }


signature:
public class GojaConfig { /** * 取得系统的运行模式
 * @ return 运行模式 */
private static ApplicationMode getApplicationModel ( ) { } }

implementation: final String mode = getProperty ( GojaPropConst . APPMODE , "dev" ) . toUpperCase ( ) ; return ApplicationMode . valueOf ( mode ) ;


signature:
public class ReflectionKit { /** * Determine whether the given method explicitly declares the given
 * exception or one of its superclasses , which means that an exception of
 * that type can be propagated as - is within a reflective invocation .
 * @ param method the declaring method
 * @ param exceptionType the exception to throw
 * @ return { @ code true } if the exception can be thrown as - is ;
 * { @ code false } if it needs to be wrapped */
public static boolean declaresException ( Method method , Class < ? > exceptionType ) { } }

implementation: Preconditions . checkNotNull ( method , "Method must not be null" ) ; Class < ? > [ ] declaredExceptions = method . getExceptionTypes ( ) ; for ( Class < ? > declaredException : declaredExceptions ) { if ( declaredException . isAssignableFrom ( exceptionType ) ) { return true ; } } return false ;


signature:
public class ConcurrentSoftHashMap { /** * Traverses the ReferenceQueue and removes garbage - collected SoftValue objects from the backing map
 * by looking them up using the SoftValue . key data member . */
private void processQueue ( ) { } }

implementation:
SoftValue < ? , ? > sv ; while ( ( sv = ( SoftValue < ? , ? > ) queue . poll ( ) ) != null ) { // noinspection SuspiciousMethodCalls
map . remove ( sv . key ) ; // we can access private data !
}


signature:
public class ConcurrentSoftHashMap { /** * Creates a new entry , but wraps the value in a SoftValue instance to enable auto garbage collection . */
@ Override public V put ( K key , V value ) { } }

implementation:
processQueue ( ) ; // throw out garbage collected values first
SoftValue < V , K > sv = new SoftValue < V , K > ( value , key , queue ) ; SoftValue < V , K > previous = map . put ( key , sv ) ; addToStrongReferences ( value ) ; return previous != null ? previous . get ( ) : null ;


signature:
public class Util { /** * Create a { @ code LoginException } with a cause .
 * @ param message the detail message ( which is saved for later retrieval by the
 * { @ link java . lang . Exception # getMessage ( ) } method ) .
 * @ param cause the cause ( which is saved for later retrieval by the { @ link java . lang . Exception # getCause ( ) }
 * method ) . ( A < tt > null < / tt > value is permitted , and indicates that the cause is nonexistent or
 * unknown . )
 * @ return a new { @ code LoginException }
 * @ throws NullPointerException When the { @ code message } or { @ code cause } are { @ code null }
 * @ throws IllegalArgumentException When { @ code message } is empty
 * @ see Exception # Exception ( String , Throwable ) */
public static LoginException newLoginException ( final String message , final Throwable cause ) { } }

implementation: Validate . notBlank ( message , "The validated character sequence 'message' is null or empty" ) ; Validate . notNull ( cause , "The validated object 'cause' is null" ) ; final LoginException loginException = new LoginException ( message ) ; loginException . initCause ( cause ) ; return loginException ;


signature:
public class ParameterInfo { /** * 使用 ASM 获取参数名称 */
private static void receiveParameterNames ( final KlassInfo declaringklass ) { } }

implementation:
if ( declaringklass . getType ( ) . getClassLoader ( ) == null ) { // We can not find parameter name for class which is in JDK
return ; } ClassReader cr = null ; try { InputStream stream = ClassLoaderUtils . getClassAsStream ( declaringklass . getType ( ) ) ; cr = new ClassReader ( stream ) ; } catch ( IOException e ) { throw new RuntimeException ( e ) ; } cr . accept ( new ClassVisitor ( Opcodes . ASM5 ) { @ Override public MethodVisitor visitMethod ( final int access , final String name , final String desc , final String signature , final String [ ] exceptions ) { final MethodInfo method = searchMethod ( declaringklass , name , desc ) ; if ( method == null ) { return super . visitMethod ( access , name , desc , signature , exceptions ) ; } MethodVisitor mv = super . visitMethod ( access , name , desc , signature , exceptions ) ; return new MethodVisitor ( Opcodes . ASM5 , mv ) { List < ParameterInfo > parameters = method . getParameters ( ) ; boolean isStatic = method . isStatic ( ) ; @ Override public void visitLocalVariable ( String name , String desc , String signature , Label start , Label end , int index ) { int offset = isStatic ? index : index - 1 ; if ( offset >= 0 && offset < parameters . size ( ) ) { parameters . get ( offset ) . name = name ; } super . visitLocalVariable ( name , desc , signature , start , end , index ) ; } int visitParameterIndex = 0 ; // JDK8 parameter name 是按照循序存储的 , 这里需要一个计数器
@ Override public void visitParameter ( String name , int access ) { parameters . get ( visitParameterIndex ++ ) . name = name ; super . visitParameter ( name , access ) ; } } ; } private MethodInfo searchMethod ( KlassInfo declaringklass , String name , String desc ) { if ( "<cinit>" . equals ( name ) ) return null ; if ( "<init>" . equals ( name ) ) return null ; jetbrick . asm . Type [ ] argumentTypes = jetbrick . asm . Type . getArgumentTypes ( desc ) ; for ( MethodInfo method : declaringklass . getDeclaredMethods ( ) ) { if ( method . getName ( ) . equals ( name ) && argumentTypes . length == method . getParameterCount ( ) ) { Class < ? > [ ] types = method . getParameterTypes ( ) ; boolean matched = true ; for ( int i = 0 ; i < argumentTypes . length ; i ++ ) { if ( ! jetbrick . asm . Type . getType ( types [ i ] ) . equals ( argumentTypes [ i ] ) ) { matched = false ; break ; } } if ( matched ) { return method ; } } } return null ; } } , ClassReader . SKIP_FRAMES ) ;


signature:
public class PrepareDbAfterGetCopy { /** * < p > It prepares database after import . < / p >
 * @ param pAddParams additional params
 * @ throws Exception - an exception */
@ Override public final void make ( final Map < String , Object > pAddParams ) throws Exception { } }

implementation: this . factoryAppBeans . releaseBeans ( ) ; Writer htmlWriter = ( Writer ) pAddParams . get ( "htmlWriter" ) ; if ( htmlWriter != null ) { htmlWriter . write ( "<h4>" + new Date ( ) . toString ( ) + ", " + PrepareDbAfterGetCopy . class . getSimpleName ( ) + ", app-factory beans has released" + "</h4>" ) ; } this . logger . info ( null , PrepareDbAfterGetCopy . class , "app-factory beans has released" ) ;


signature:
public class WildcharUtils { /** * Checks whether a string matches a given wildcard pattern .
 * @ param string input string
 * @ param pattern pattern to match
 * @ return < code > true < / code > if string matches the pattern , otherwise < code > false < / code > */
public static boolean match ( String string , String pattern ) { } }

implementation:
if ( string . equals ( pattern ) ) { // speed - up
return true ; } return match ( string , pattern , 0 , 0 ) ;


signature:
public class JBackup { /** * Constructor . */
public void init ( String title ) { } }

implementation: super . init ( title ) ; Container contentPane = this . getContentPane ( ) ; contentPane . setLayout ( new BorderLayout ( ) ) ; m_properties = AppUtilities . readProperties ( m_strFileName = System . getProperty ( PROPERTY_FILENAME_PARAM , DEFAULT_PROPERTY_FILENAME ) ) ; JPanel panel = this . getPropertyView ( m_properties ) ; contentPane . add ( panel , BorderLayout . CENTER ) ; JPanel panelButtons = new JPanel ( ) ; contentPane . add ( panelButtons , BorderLayout . SOUTH ) ; panelButtons . setLayout ( new BorderLayout ( ) ) ; panelButtons . add ( m_buttonGo = new JButton ( "GO!" ) , BorderLayout . EAST ) ; m_buttonGo . addActionListener ( this ) ; panelButtons . add ( progressBar = new JProgressBar ( 0 , 1 ) , BorderLayout . CENTER ) ; panelButtons . add ( m_buttonSave = new JButton ( "Save" ) , BorderLayout . WEST ) ; m_buttonSave . addActionListener ( this ) ;


signature:
public class JBackup { /** * Main method . */
public static void main ( String [ ] args ) { } }

implementation: try { JBackup applet = new JBackup ( "JBackup" ) ; if ( ! Boolean . TRUE . toString ( ) . equalsIgnoreCase ( System . getProperty ( PROPERTY_QUIET_PARAM ) ) ) { JFrame frame = applet . addAppToFrame ( ) ; frame . setVisible ( true ) ; } else { Scanner scanner = new Scanner ( applet . m_properties ) ; scanner . run ( ) ; AppUtilities . writeProperties ( applet . m_strFileName , applet . m_properties ) ; System . exit ( 0 ) ; } } catch ( Throwable t ) { System . out . println ( "uncaught exception: " + t ) ; t . printStackTrace ( ) ; } // + System . exit ( 0 ) ;


signature:
public class JBackup { /** * User pressed a button . */
public void actionPerformed ( ActionEvent e ) { } }

implementation:
if ( e . getSource ( ) == m_buttonGo ) { Scanner scanner = new Scanner ( m_properties ) ; // Fit them on floppys
progressBar . setIndeterminate ( true ) ; // For now
scanner . run ( ) ; progressBar . setIndeterminate ( false ) ; AppUtilities . writeProperties ( m_strFileName , m_properties ) ; } if ( e . getSource ( ) == m_buttonSave ) { AppUtilities . writeProperties ( m_strFileName , m_properties ) ; }


signature:
public class TypeCastResolver { /** * - - - - - register / lookup - - - - - */
@ SuppressWarnings ( "rawtypes" ) public < T > void register ( Class < ? > type , Convertor < ? > convertor ) { } }

implementation: pool . put ( type , convertor ) ; if ( type . isPrimitive ( ) ) { primitiveArrayPool . put ( type , new PrimitiveArrayConvertor ( type ) ) ; } else { objectArrayPool . put ( type , new ArrayConvertor ( type , convertor ) ) ; listPool . put ( type , new ListConvertor ( type , convertor ) ) ; }


signature:
public class TypeCastResolver { /** * - - - - - convert string - - - - - */
public < T > T convert ( String value , Class < T > type ) { } }

implementation:
// fast - path
if ( value == null ) { return null ; } if ( type == String . class ) { return ( T ) value ; } // normal - path
Convertor < T > c = ( Convertor < T > ) pool . get ( type ) ; if ( c != null ) { return c . convert ( value ) ; } if ( type . isArray ( ) ) { return ( T ) convertToArray ( value , type . getComponentType ( ) ) ; } throw new IllegalStateException ( "Unsupported cast class: " + type . getName ( ) ) ;