signature:
public class Controller { /** * 渲染DataGrid的表格展示 , 支持排序和搜索
 * @ param sqlGroupName 指定SQL管理的GroupName */
protected void renderEasyUIDataGrid ( String sqlGroupName , List < Object > params ) { } }

implementation: Preconditions . checkNotNull ( sqlGroupName , "sql Group Name 不能为空" ) ; final Optional < DataGridReq > reqOptional = EuiDataGrid . req ( getRequest ( ) ) ; if ( reqOptional . isPresent ( ) ) { renderJson ( EuiDataGrid . rsp ( reqOptional . get ( ) , sqlGroupName , params ) ) ; } else { renderJson ( EuiDataGrid . EMPTY_DATAGRID ) ; }


signature:
public class Controller { /** * For information on the logged in user . < p / > This access is through the way the Cookie and
 * Sessionw
 * @ param < M > Generic parameter .
 * @ return user model . */
protected < M extends Model > Optional < M > getLogin ( ) { } }

implementation: final HttpServletRequest request = getRequest ( ) ; if ( SecurityKit . isLogin ( request ) ) { final M user = SecurityKit . getLoginUser ( request ) ; return Optional . of ( user ) ; } else { return Optional . absent ( ) ; }


signature:
public class Controller { /** * The current Shiro login user . < p / > If it opens the secruity function can call this method to
 * obtain the logged in user .
 * @ param < U > Generic parameter .
 * @ return Shiro login user . */
protected < U extends Model > Optional < AppUser < U > > getPrincipal ( ) { } }

implementation: if ( Securitys . isLogin ( ) ) { final AppUser < U > appUser = Securitys . getLogin ( ) ; return Optional . of ( appUser ) ; } return Optional . absent ( ) ;


signature:
public class Controller { /** * JodaTime time request
 * @ param name param . the datetime format : yyyy - MM - dd
 * @ param defaultValue the default value .
 * @ return datetime . */
protected DateTime getDate ( String name , DateTime defaultValue ) { } }

implementation: String value = getRequest ( ) . getParameter ( name ) ; if ( Strings . isNullOrEmpty ( value ) ) { return defaultValue ; } return DateKit . parseDashYMDDateTime ( value ) ;


signature:
public class Controller { /** * JodaTime time request
 * @ param name param . the datetime format : yyyy - MM - dd HH : mm : ss
 * @ param defaultValue the default value .
 * @ return datetime . */
protected DateTime getDateTime ( String name , DateTime defaultValue ) { } }

implementation: String value = getRequest ( ) . getParameter ( name ) ; if ( Strings . isNullOrEmpty ( value ) ) { return defaultValue ; } return DateKit . parseDashYMDHMSDateTime ( value ) ;


signature:
public class ComboBoxEditingSupport { /** * Sets the input items to the underlying ComboBoxCellEditor .
 * @ param items
 * a < code > null < / code > value is converted to an empty list . */
public void setItems ( List < V > items ) { } }

implementation: final List < V > its = items == null ? ImmutableList . of ( ) : items ; this . items = its ; getComboBoxCellEditor ( ) . setInput ( items ) ;


signature:
public class Redirect { /** * Writes this HTTP response to the specified Web context .
 * @ param context Web context . */
public void to ( WebContext context ) { } }

implementation: HttpServletResponse response = context . response ( ) ; if ( ! mediaType . isEmpty ( ) ) { response . setHeader ( "Content-Type" , mediaType ) ; } if ( status > 0 ) { response . setStatus ( status ) ; } try { response . sendRedirect ( response . encodeRedirectURL ( url ) ) ; } catch ( IOException e ) { throw new UncheckedException ( e ) ; }


signature:
public class Send { /** * Sends Web endpoint invocation result to the client as HTTP response .
 * This method processes the response as the following steps :
 * < ol >
 * < li > If the Web endpoint invocation result is instance of { @ code Response } ,
 * sends the HTTP response to the client by invoking { @ code Response # to ( WebContext ) }
 * method with the current Web context . < / li >
 * < li > ( If it does not so , ) If the Web endpoint method is qualified by
 * { @ code @ Generates } annotation , this class determines the { @ code Response }
 * type from the specified MIME media type by invoking
 * { @ code Configuration # responseType ( String ) } . < / li >
 * < li > If the Web endpoint method is qualified by { @ code @ Negotiated }
 * annotation , this class determines the { @ code Response } type from the MIME
 * media type specified on " Accept " HTTP request header by invoking
 * { @ code Configuration # responseType ( String ) } . < / li >
 * < li > ( If it does not so , ) If the Web endpoint method is qualified neither
 * by { @ code @ Generates } nor { @ code @ Negotiated } annotation , this class
 * determines the { @ code Response } type by invoking
 * { @ code Configuration # responseType ( String ) } with empty string . < / li >
 * < li > Constructs { @ code Response } instance and sets the MIME media type and
 * Web endpoint invocation result , then sends the HTTP response to the
 * client by invoking { @ code Response # to ( WebContext ) } method with the
 * current Web context . < / li >
 * < / ol >
 * @ param context HTTP request processing context . */
public boolean apply ( WebContext context ) { } }

implementation:
Object result = context . result ( ) ; if ( result instanceof Response ) { Response response = ( Response ) result ; response . to ( context ) ; return true ; } try { Method method = context . method ( ) ; String contentType = "" ; Generates generates = method . getAnnotation ( Generates . class ) ; Negotiated negotiated = method . getAnnotation ( Negotiated . class ) ; if ( generates != null ) { logger . debug ( "Web endpoint [" + method . getDeclaringClass ( ) . getName ( ) + "#" + method . getName ( ) + "] is qualified by [" + generates + "]" ) ; contentType = generates . value ( ) ; } else if ( negotiated != null ) { logger . debug ( "Web endpoint [" + method . getDeclaringClass ( ) . getName ( ) + "#" + method . getName ( ) + "] is qualified by [" + negotiated + "]" ) ; String header = context . request ( ) . getHeader ( "Accept" ) ; if ( header != null ) { // TODO : Parse .
contentType = header ; } } logger . debug ( "MIME media type is [" + contentType + "]" ) ; Class < ? extends Response > responseType = context . configuration ( ) . responseTypes ( ) . get ( contentType ) ; if ( responseType == null ) { throw new CannotSendResponseException ( HttpServletResponse . SC_UNSUPPORTED_MEDIA_TYPE , "Configuration [" + context . configuration ( ) . getClass ( ) . getName ( ) + "] does not provide a response type corresponding to [" + contentType + "] media type" ) ; } Response response = responseType . newInstance ( ) ; response . mediaType ( contentType ) ; response . entity ( result ) ; response . to ( context ) ; return true ; } catch ( CannotSendResponseException exception ) { logger . warn ( "Failed to send HTTP response" , exception ) ; try { context . response ( ) . sendError ( exception . status ( ) ) ; return false ; } catch ( IOException e ) { throw new UncheckedException ( e ) ; } } catch ( Exception e ) { throw new UncheckedException ( e ) ; }


signature:
public class StandardWebApplicationContextInitializer { /** * Encapsulates the logic for associating property source with a given servlet .
 * @ param servletInitializer A callback that encapsulates the call to the container specific way to set init parameter
 * @ param source Property source , that needs to be registered and later available to the spring context
 * @ return A closeable instance that should be closed to perform cleanup once server is stopped */
@ Nonnull public static AutoCloseable register ( @ Nonnull ServletInitializer servletInitializer , @ Nonnull PropertySource < ? > source ) { } }

implementation:
final BigInteger bigInteger = new BigInteger ( 64 , ThreadLocalRandom . current ( ) ) ; final String key = bigInteger . toString ( 16 ) ; if ( PROPERTIES . containsKey ( key ) ) { return register ( servletInitializer , source ) ; // shouldn ' t happen
} // associate this key with the context parameter
servletInitializer . setInitParameter ( PROPERTY_SOURCE_SERVLET_CONFIG_KEY , key ) ; // . . . and put it to the globally visible properties map
PROPERTIES . put ( key , source ) ; return new AutoCloseable ( ) { @ Override public void close ( ) { PROPERTIES . remove ( key ) ; } } ;


signature:
public class EncodeKit { /** * Hex解码 . */
public static byte [ ] decodeHex ( String input ) { } }

implementation: try { return Hex . decodeHex ( input . toCharArray ( ) ) ; } catch ( DecoderException e ) { throw ExceptionKit . unchecked ( e ) ; }


signature:
public class EncodeKit { /** * Base62编码 。 */
public static String encodeBase62 ( byte [ ] input ) { } }

implementation: char [ ] chars = new char [ input . length ] ; for ( int i = 0 ; i < input . length ; i ++ ) { chars [ i ] = BASE62 [ ( ( input [ i ] & 0xFF ) % BASE62 . length ) ] ; } return new String ( chars ) ;


signature:
public class EncodeKit { /** * URL 编码 , Encode默认为UTF - 8. */
public static String urlEncode ( String part ) { } }

implementation: try { return URLEncoder . encode ( part , StringPool . UTF_8 ) ; } catch ( UnsupportedEncodingException e ) { throw ExceptionKit . unchecked ( e ) ; }


signature:
public class EncodeKit { /** * URL 解码 , Encode默认为UTF - 8. */
public static String urlDecode ( String part ) { } }

implementation: try { return URLDecoder . decode ( part , StringPool . UTF_8 ) ; } catch ( UnsupportedEncodingException e ) { throw ExceptionKit . unchecked ( e ) ; }


signature:
public class ExtensionList { /** * Returns all the extension implementations in the specified injector . */
public List < T > list ( Injector injector ) { } }

implementation: List < T > r = new ArrayList < T > ( ) ; for ( Injector i = injector ; i != null ; i = i . getParent ( ) ) { for ( Entry < Key < ? > , Binding < ? > > e : i . getBindings ( ) . entrySet ( ) ) { if ( e . getKey ( ) . getTypeLiteral ( ) . equals ( type ) ) r . add ( ( T ) e . getValue ( ) . getProvider ( ) . get ( ) ) ; } } return r ;


signature:
public class RuntimeKit { /** * Returns current method signature . */
public static String currentMethod ( ) { } }

implementation: StackTraceElement [ ] ste = new Exception ( ) . getStackTrace ( ) ; int ndx = ( ste . length > 1 ) ? 1 : 0 ; return new Exception ( ) . getStackTrace ( ) [ ndx ] . toString ( ) ;


signature:
public class RuntimeKit { /** * Compacts memory as much as possible by allocating huge memory block
 * and then forcing garbage collection . */
public static void compactMemory ( ) { } }

implementation: try { final byte [ ] [ ] unused = new byte [ 128 ] [ ] ; for ( int i = unused . length ; i -- != 0 ; ) { unused [ i ] = new byte [ 2000000000 ] ; } } catch ( OutOfMemoryError ignore ) { } System . gc ( ) ;


signature:
public class LogUtil { /** * Propagates metrics entry to the local metrics collection or ( if unavailable ) logs immediately
 * @ param metrics Metrics object to log
 * @ param log Target logger to use if local metrics collection is not available */
public static void propagateOrLogInfo ( Metrics metrics , Logger log ) { } }

implementation: final MetricsCollection metricsCollection = propagate ( metrics ) ; if ( metricsCollection == null ) { logInfo ( metrics , log ) ; }


signature:
public class LogUtil { /** * Propagates metrics entry to the thread local metrics collection , does nothing if local metrics collection
 * is missing .
 * @ param metrics Metrics to capture
 * @ return Local metrics collection or null */
@ Nullable public static MetricsCollection propagate ( Metrics metrics ) { } }

implementation: final MetricsCollection metricsCollection = getLocalMetricsCollection ( ) ; if ( metricsCollection != null ) { metricsCollection . add ( metrics ) ; } return metricsCollection ;


signature:
public class LogUtil { /** * Validates , that passed request vector is valid . This function is used to prevent the potential attacker to send
 * garbage request vectors into the service .
 * If passed request vector is invalid , it should be discarded .
 * @ param requestVector Request vector to validate
 * @ return True , if passed request vector is valid , false otherwise . */
public static boolean isValidRequestVector ( @ Nullable String requestVector ) { } }

implementation:
if ( requestVector == null || requestVector . isEmpty ( ) || requestVector . length ( ) > MAX_REQUEST_VECTOR_LENGTH ) { return false ; } // verify , that each character is within the allowed bounds
for ( int i = 0 ; i < requestVector . length ( ) ; ++ i ) { final char ch = requestVector . charAt ( i ) ; if ( ch <= 32 || ch >= 127 ) { return false ; } } return true ;


signature:
public class LogUtil { /** * Encodes a value , so that it won ' t contain spaces , commas and equal signs .
 * @ param value Value to be encoded
 * @ return Encoded value or same value if passed argument does not contain whitespace , comma or equals sign */
public static String encodeString ( String value ) { } }

implementation:
int estimatedSize = 0 ; final int len = value . length ( ) ; // estimate output string size to find out whether encoding is required and avoid reallocations in string builder
for ( int i = 0 ; i < len ; ++ i ) { final char ch = value . charAt ( i ) ; if ( ch <= ' ' || ch == ',' ) { estimatedSize += 3 ; continue ; } ++ estimatedSize ; } if ( value . length ( ) == estimatedSize ) { return value ; // return value as is - it does not contain any special characters
} final StringBuilder builder = new StringBuilder ( estimatedSize ) ; for ( int i = 0 ; i < len ; ++ i ) { final char ch = value . charAt ( i ) ; if ( ch <= ' ' ) { builder . append ( "%20" ) ; continue ; } if ( ch == ',' ) { builder . append ( "%2c" ) ; continue ; } builder . append ( ch ) ; } return builder . toString ( ) ;


signature:
public class ExceptionKit { /** * 将CheckedException转换为UncheckedException . */
public static RuntimeException unchecked ( Exception e ) { } }

implementation: if ( e instanceof RuntimeException ) { return ( RuntimeException ) e ; } else { return new RuntimeException ( e ) ; }


signature:
public class ExceptionKit { /** * 将ErrorStack转化为String . */
public static String getStackTraceAsString ( Exception e ) { } }

implementation: StringWriter stringWriter = new StringWriter ( ) ; e . printStackTrace ( new PrintWriter ( stringWriter ) ) ; return stringWriter . toString ( ) ;


signature:
public class ExceptionKit { /** * 判断异常是否由某些底层的异常引起 . */
public static boolean isCausedBy ( Exception ex , Class < ? extends Exception > ... causeExceptionClasses ) { } }

implementation: Throwable cause = ex . getCause ( ) ; while ( cause != null ) { for ( Class < ? extends Exception > causeClass : causeExceptionClasses ) { if ( causeClass . isInstance ( cause ) ) { return true ; } } cause = cause . getCause ( ) ; } return false ;


signature:
public class DTDao { /** * Paging retrieve , default sorted by id , you need to specify the datatables request parameters .
 * @ param model _ name sql - conf sqlgroup name .
 * @ param criterias required parameter
 * @ return Paging data . */
public static Page < Record > paginate ( String model_name , DTCriterias criterias ) { } }

implementation: return paginate ( model_name , criterias , Lists . newArrayListWithCapacity ( 1 ) ) ;


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

implementation: SqlNode sqlNode = SqlKit . sqlNode ( sqlPaginatePrefix + ".paginate" ) ; Preconditions . checkNotNull ( sqlNode , "[" + sqlPaginatePrefix + ".paginate]分页Sql不存在,无法执行分页" ) ; return DTDao . paginate ( sqlNode , criterias , params ) ;


signature:
public class DTDao { /** * Paging retrieve , default sorted by id , you need to specify the datatables request parameters .
 * @ param where FROM WHERE SQL .
 * @ param sql _ columns SELECT column sql .
 * @ param criterias required parameter
 * @ return Paging data . */
public static Page < Record > paginate ( String where , String sql_columns , DTCriterias criterias , List < Object > params ) { } }

implementation: int pageSize = criterias . getLength ( ) ; int start = criterias . getStart ( ) / pageSize + 1 ; StringBuilder where_sql = new StringBuilder ( where ) ; final List < Triple < String , Condition , Object > > custom_params = criterias . getParams ( ) ; if ( ! custom_params . isEmpty ( ) ) { boolean append_and = StringUtils . containsIgnoreCase ( where , "WHERE" ) ; if ( ! append_and ) { where_sql . append ( SQL_WHERE ) ; } itemCustomParamSql ( params , where_sql , custom_params , append_and ) ; } final List < DTOrder > order = criterias . getOrder ( ) ; if ( order != null && ! order . isEmpty ( ) ) { StringBuilder orderBy = new StringBuilder ( ) ; for ( DTOrder _order : order ) orderBy . append ( _order . getColumn ( ) ) . append ( StringPool . SPACE ) . append ( _order . getDir ( ) ) ; final String byColumns = orderBy . toString ( ) ; if ( ! Strings . isNullOrEmpty ( byColumns ) ) { where_sql . append ( " ORDER BY " ) . append ( byColumns ) ; } } if ( params == null || params . isEmpty ( ) ) { return Db . paginate ( start , pageSize , sql_columns , where_sql . toString ( ) ) ; } else { return Db . paginate ( start , pageSize , sql_columns , where_sql . toString ( ) , params . toArray ( ) ) ; }


signature:
public class DTDao { /** * 分页检索 , 默认按照id进行排序 , 需要指定datatables的请求参数 。
 * @ param model 实体
 * @ param criterias 请求参数
 * @ return 分页数据 */
public static Page < Record > paginate ( Class < ? extends Model > model , DTCriterias criterias ) { } }

implementation:
int pageSize = criterias . getLength ( ) ; int start = criterias . getStart ( ) / pageSize + 1 ; final Table table = TableMapping . me ( ) . getTable ( model ) ; final String tableName = table . getName ( ) ; final List < DTColumn > columns = criterias . getColumns ( ) ; String sql_columns = null ; if ( ! ( columns == null || columns . isEmpty ( ) ) ) { StringBuilder sql_builder = new StringBuilder ( "SELECT " ) ; boolean first = false ; for ( DTColumn column : columns ) { if ( column != null ) { if ( first ) { sql_builder . append ( COMMA ) . append ( SPACE ) . append ( column . getData ( ) ) ; } else { sql_builder . append ( column . getData ( ) ) ; first = true ; } } } sql_columns = sql_builder . toString ( ) ; } StringBuilder where = new StringBuilder ( " FROM " ) ; where . append ( tableName ) . append ( SPACE ) ; // final DTSearch search = criterias . getSearch ( ) ;
final List < Triple < String , Condition , Object > > custom_params = criterias . getParams ( ) ; final List < Object > params = Lists . newArrayList ( ) ; appendWhereSql ( params , where , custom_params ) ; final List < DTOrder > order = criterias . getOrder ( ) ; if ( ! ( order == null || order . isEmpty ( ) ) ) { StringBuilder orderBy = new StringBuilder ( ) ; for ( DTOrder _order : order ) orderBy . append ( _order . getColumn ( ) ) . append ( SPACE ) . append ( _order . getDir ( ) ) ; final String byColumns = orderBy . toString ( ) ; if ( ! Strings . isNullOrEmpty ( byColumns ) ) { where . append ( " ORDER BY " ) . append ( byColumns ) ; } } return Db . paginate ( start , pageSize , sql_columns , where . toString ( ) , params . toArray ( ) ) ;


signature:
public class FileEncodingKit { /** * Get coding format file .
 * @ param file the file .
 * @ return File encoding format . */
public static Optional < Charset > charset ( File file ) { } }

implementation:
if ( ! file . exists ( ) ) { logger . error ( "The file [ {} ] is not exist." , file . getAbsolutePath ( ) ) ; return Optional . absent ( ) ; } FileInputStream fileInputStream = null ; BufferedInputStream bin = null ; try { fileInputStream = new FileInputStream ( file ) ; bin = new BufferedInputStream ( fileInputStream ) ; int p = ( bin . read ( ) << 8 ) + bin . read ( ) ; Optional < Charset > charset ; // 其中的 0xefbb 、 0xfffe 、 0xfeff 、 0x5c75这些都是这个文件的前面两个字节的16进制数
switch ( p ) { case 0xefbb : charset = Optional . of ( Charsets . UTF_8 ) ; break ; case 0xfffe : charset = Optional . of ( Charset . forName ( "Unicode" ) ) ; break ; case 0xfeff : charset = Optional . of ( Charsets . UTF_16BE ) ; break ; case 0x5c75 : charset = Optional . of ( Charsets . US_ASCII ) ; break ; default : charset = Optional . of ( Charset . forName ( "GBK" ) ) ; } return charset ; } catch ( FileNotFoundException e ) { logger . error ( "The file [ {} ] is not exist." , file . getAbsolutePath ( ) , e ) ; } catch ( IOException e ) { logger . error ( "Read file has error, {}." , file . getAbsolutePath ( ) , e ) ; } finally { IOUtils . closeQuietly ( fileInputStream ) ; IOUtils . closeQuietly ( bin ) ; } return Optional . absent ( ) ;


signature:
public class MongoKit { /** * 根据ID查找 */
public static List < DBObject > findById ( String collectionName , String id ) { } }

implementation: DBCollection c = MongoKit . getCollection ( collectionName ) ; return c . find ( new BasicDBObject ( "_id" , new ObjectId ( id ) ) ) . toArray ( ) ;


signature:
public class MongoKit { /** * 根据条件对象查找 */
public static List < DBObject > findByQuery ( String collectionName , MongoQuery query ) { } }

implementation: DBCollection c = MongoKit . getCollection ( collectionName ) ; return c . find ( query . get ( ) ) . toArray ( ) ;


signature:
public class MongoKit { /** * 根据条件对象查找并删除 */
public static DBObject findAndRemove ( String collectionName , MongoQuery query ) { } }

implementation: DBCollection c = MongoKit . getCollection ( collectionName ) ; return c . findAndRemove ( query . get ( ) ) ;


signature:
public class StreamUtil { /** * Closes an output stream and releases any system resources associated with
 * this stream . No exception will be thrown if an I / O error occurs . */
public static void close ( OutputStream out ) { } }

implementation:
if ( out != null ) { try { out . flush ( ) ; } catch ( IOException ioex ) { // ignore
} try { out . close ( ) ; } catch ( IOException ioex ) { // ignore
} }


signature:
public class StreamUtil { /** * Closes a character - output stream and releases any system resources
 * associated with this stream . No exception will be thrown if an I / O error
 * occurs . */
public static void close ( Writer out ) { } }


signature:
public class StreamUtil { /** * Copies input stream to output stream using buffer . Streams don ' t have
 * to be wrapped to buffered , since copying is already optimized . */
public static int copy ( InputStream input , OutputStream output ) throws IOException { } }

implementation: byte [ ] buffer = new byte [ ioBufferSize ] ; int count = 0 ; int read ; while ( true ) { read = input . read ( buffer , 0 , ioBufferSize ) ; if ( read == - 1 ) { break ; } output . write ( buffer , 0 , read ) ; count += read ; } return count ;


signature:
public class StreamUtil { /** * Copies specified number of bytes from input stream to output stream using buffer . */
public static int copy ( InputStream input , OutputStream output , int byteCount ) throws IOException { } }

implementation: byte buffer [ ] = new byte [ ioBufferSize ] ; int count = 0 ; int read ; while ( byteCount > 0 ) { if ( byteCount < ioBufferSize ) { read = input . read ( buffer , 0 , byteCount ) ; } else { read = input . read ( buffer , 0 , ioBufferSize ) ; } if ( read == - 1 ) { break ; } byteCount -= read ; count += read ; output . write ( buffer , 0 , read ) ; } return count ;


signature:
public class StreamUtil { /** * Copies input stream to writer using buffer . */
public static void copy ( InputStream input , Writer output ) throws IOException { } }

implementation: copy ( input , output , Const . DEFAULT_ENCODING ) ;


signature:
public class StreamUtil { /** * Copies reader to writer using buffer .
 * Streams don ' t have to be wrapped to buffered , since copying is already optimized . */
public static int copy ( Reader input , Writer output ) throws IOException { } }

implementation: char [ ] buffer = new char [ ioBufferSize ] ; int count = 0 ; int read ; while ( ( read = input . read ( buffer , 0 , ioBufferSize ) ) >= 0 ) { output . write ( buffer , 0 , read ) ; count += read ; } output . flush ( ) ; return count ;


signature:
public class StreamUtil { /** * Copies specified number of characters from reader to writer using buffer . */
public static int copy ( Reader input , Writer output , int charCount ) throws IOException { } }

implementation: char buffer [ ] = new char [ ioBufferSize ] ; int count = 0 ; int read ; while ( charCount > 0 ) { if ( charCount < ioBufferSize ) { read = input . read ( buffer , 0 , charCount ) ; } else { read = input . read ( buffer , 0 , ioBufferSize ) ; } if ( read == - 1 ) { break ; } charCount -= read ; count += read ; output . write ( buffer , 0 , read ) ; } return count ;


signature:
public class StreamUtil { /** * Copies reader to output stream using buffer . */
public static void copy ( Reader input , OutputStream output ) throws IOException { } }


signature:
public class StreamUtil { /** * Copies reader to output stream using buffer and specified encoding . */
public static void copy ( Reader input , OutputStream output , String encoding ) throws IOException { } }

implementation: Writer out = new OutputStreamWriter ( output , encoding ) ; copy ( input , out ) ; out . flush ( ) ;


signature:
public class StreamUtil { /** * Reads all available bytes from InputStream as a byte array .
 * Uses < code > in . available ( ) < / code > to determine the size of input stream .
 * This is the fastest method for reading input stream to byte array , but
 * depends on stream implementation of < code > available ( ) < / code > .
 * Buffered internally . */
public static byte [ ] readAvailableBytes ( InputStream in ) throws IOException { } }

implementation: int l = in . available ( ) ; byte byteArray [ ] = new byte [ l ] ; int i = 0 , j ; while ( ( i < l ) && ( j = in . read ( byteArray , i , l - i ) ) >= 0 ) { i += j ; } if ( i < l ) { throw new IOException ( "Failed to completely read input stream" ) ; } return byteArray ;


signature:
public class StreamUtil { /** * Compares the content of two byte streams .
 * @ return < code > true < / code > if the content of the first stream is equal
 * to the content of the second stream . */
public static boolean compare ( InputStream input1 , InputStream input2 ) throws IOException { } }

implementation: if ( ! ( input1 instanceof BufferedInputStream ) ) { input1 = new BufferedInputStream ( input1 ) ; } if ( ! ( input2 instanceof BufferedInputStream ) ) { input2 = new BufferedInputStream ( input2 ) ; } int ch = input1 . read ( ) ; while ( ch != - 1 ) { int ch2 = input2 . read ( ) ; if ( ch != ch2 ) { return false ; } ch = input1 . read ( ) ; } int ch2 = input2 . read ( ) ; return ( ch2 == - 1 ) ;


signature:
public class StreamUtil { /** * Compares the content of two character streams .
 * @ return < code > true < / code > if the content of the first stream is equal
 * to the content of the second stream . */
public static boolean compare ( Reader input1 , Reader input2 ) throws IOException { } }

implementation: if ( ! ( input1 instanceof BufferedReader ) ) { input1 = new BufferedReader ( input1 ) ; } if ( ! ( input2 instanceof BufferedReader ) ) { input2 = new BufferedReader ( input2 ) ; } int ch = input1 . read ( ) ; while ( ch != - 1 ) { int ch2 = input2 . read ( ) ; if ( ch != ch2 ) { return false ; } ch = input1 . read ( ) ; } int ch2 = input2 . read ( ) ; return ( ch2 == - 1 ) ;


signature:
public class Pipeline { /** * Starts pipeline with the specified stream object that flows through this
 * pipeline .
 * @ param io The stream object that flows through this pipeline . */
@ SuppressWarnings ( "unchecked" ) public T apply ( T io ) { } }

implementation: logger . debug ( "Pipeline began" ) ; try { for ( int i = 0 ; i < stages . size ( ) ; i ++ ) { Object stage = stages . get ( i ) ; String name = names . get ( stage ) ; logger . debug ( "Stage-" + i + ( ( name != null && ! name . isEmpty ( ) ) ? " [" + name + "] " : " " ) + "processing" ) ; if ( stage instanceof Function ) { if ( ( io = ( ( Function < T , T > ) stage ) . apply ( io ) ) == null ) { return io ; } } else if ( stage instanceof Predicate ) { if ( ! ( ( Predicate < T > ) stage ) . apply ( io ) ) { return io ; } } } return io ; } finally { logger . debug ( "Pipeline ended" ) ; }


signature:
public class Pipeline { /** * Sets the specified { @ code Function } to the next processing stage with the
 * class name of the { @ code Function } as the stage name .
 * @ param function The { @ code Function } set to the next processing stage .
 * @ return This { @ code Pipeline } instance . */
public Pipeline < T > set ( Function < T , T > function ) { } }

implementation: return set ( stages . size ( ) , function . getClass ( ) . getName ( ) , function ) ;


signature:
public class Pipeline { /** * Sets the specified { @ code Function } to the next processing stage with the
 * specified index and the class name of the { @ code Function } as the stage
 * name .
 * @ param index The index the specified { @ code Function } to be set .
 * @ param function The { @ code Function } set to the next processing stage .
 * @ return This { @ code Pipeline } instance . */
public Pipeline < T > set ( int index , Function < T , T > function ) { } }

implementation: return set ( index , function . getClass ( ) . getName ( ) , function ) ;


signature:
public class Pipeline { /** * Sets the specified { @ code Function } to the next processing stage with the
 * specified stage name .
 * @ param name The stage name .
 * @ param function The { @ code Function } set to the next processing stage .
 * @ return This { @ code Pipeline } instance . */
public Pipeline < T > set ( String name , Function < T , T > function ) { } }

implementation: return set ( stages . size ( ) , name , function ) ;


signature:
public class Pipeline { /** * Sets the specified { @ code Function } to the next processing stage with the
 * specified index and stage name .
 * @ param index The index the specified { @ code Function } to be set .
 * @ param name The stage name .
 * @ param function The { @ code Function } set to the next processing stage .
 * @ return This { @ code Pipeline } instance . */
public Pipeline < T > set ( int index , String name , Function < T , T > function ) { } }

implementation: Preconditions . checkArgument ( function != null , "Parameter 'function' must not be [" + function + "]" ) ; stages . add ( index , function ) ; names . put ( function , name ) ; return this ;


signature:
public class Pipeline { /** * Sets the specified { @ code Predicate } to the next processing stage with
 * the class name of the { @ code Predicate } as the stage name .
 * @ param predicate The { @ code Predicate } set to the next processing stage .
 * @ return This { @ code Pipeline } instance . */
public Pipeline < T > set ( Predicate < T > predicate ) { } }

implementation: return set ( stages . size ( ) , predicate . getClass ( ) . getName ( ) , predicate ) ;


signature:
public class Pipeline { /** * Sets the specified { @ code Predicate } to the next processing stage with
 * the specified index and the class name of the { @ code Predicate } as the
 * stage name .
 * @ param index The index the specified { @ code Predicate } to be set .
 * @ param predicate The { @ code Predicate } set to the next processing stage .
 * @ return This { @ code Pipeline } instance . */
public Pipeline < T > set ( int index , Predicate < T > predicate ) { } }

implementation: return set ( index , predicate . getClass ( ) . getName ( ) , predicate ) ;


signature:
public class Pipeline { /** * Sets the specified { @ code Predicate } to the next processing stage with
 * the specified stage name .
 * @ param name The stage name .
 * @ param predicate The { @ code Predicate } set to the next processing stage .
 * @ return This { @ code Pipeline } instance . */
public Pipeline < T > set ( String name , Predicate < T > predicate ) { } }

implementation: return set ( stages . size ( ) , name , predicate ) ;


signature:
public class Pipeline { /** * Sets the specified { @ code Predicate } to the next processing stage with
 * the specified index and stage name .
 * @ param index The index the specified { @ code Predicate } to be set .
 * @ param name The stage name .
 * @ param predicate The { @ code Function } set to the next processing stage .
 * @ return This { @ code Pipeline } instance . */
public Pipeline < T > set ( int index , String name , Predicate < T > predicate ) { } }

implementation: Preconditions . checkArgument ( predicate != null , "Parameter 'predicate' must not be [" + predicate + "]" ) ; stages . add ( index , predicate ) ; names . put ( predicate , name ) ; return this ;


signature:
public class Pipeline { /** * Removes { @ code Function } or { @ code Predicate } at the specified index .
 * @ param index The index the specified { @ code Function } or { @ code Predicate } to be removed .
 * @ return This { @ code Pipeline } instance . */
public Pipeline < T > remove ( int index ) { } }

implementation: Object object = stages . remove ( index ) ; names . remove ( object ) ; return this ;


signature:
public class SqlKit { /** * To obtain a configuration of SQL .
 * @ param groupNameAndsqlId SQL id .
 * @ return sql script . */
public static String sql ( String groupNameAndsqlId ) { } }

implementation: final SqlNode sqlNode = SQL_MAP . get ( groupNameAndsqlId ) ; return sqlNode == null ? StringPool . EMPTY : sqlNode . sql ;


signature:
public class JaxbKit { /** * string - > object */
@ SuppressWarnings ( "unchecked" ) public static < T > T unmarshal ( String src , Class < T > clazz ) { } }

implementation: T result = null ; try { Unmarshaller avm = JAXBContext . newInstance ( clazz ) . createUnmarshaller ( ) ; result = ( T ) avm . unmarshal ( new StringReader ( src ) ) ; } catch ( JAXBException e ) { Throwables . propagate ( e ) ; } return result ;


signature:
public class Receive { /** * Validates HTTP request and constructs Web endpoint method parameters .
 * This method processes the request as the following steps :
 * < ol >
 * < li > Checks the requested HTTP method is allowable . If the Web endpoint
 * method is qualified by { @ code @ Allows } , this class allows only the
 * HTTP methods qualified in it . < / li >
 * < li > Checks the requested MIME media type is acceptable . If the Web
 * endpoint method is qualified by { @ code @ Accepts } , this class accepts only
 * the qualified MIME media types . < / li >
 * < li > Determines { @ code Request } type from the content type on HTTP request
 * header by invoking { @ code Configuration # requestType ( String ) } method with the
 * content type . < / li >
 * < li > Constructs Web endpoint method parameters by invoking { @ code Request # get ( ) }
 * methods and sets them to the current HTTP request processing context . < / li >
 * < / ol >
 * @ param context HTTP request processing context . */
public boolean apply ( WebContext context ) { } }

implementation:
Method method = context . method ( ) ; try { Verb verb = null ; try { verb = Verb . valueOf ( context . request ( ) . getMethod ( ) ) ; } catch ( Exception e ) { throw new CannotAcceptRequestException ( HttpServletResponse . SC_METHOD_NOT_ALLOWED , "HTTP verb [" + context . request ( ) . getMethod ( ) + "] is not supported" ) ; } // Is the HTTP method allowable ?
if ( method . isAnnotationPresent ( Allows . class ) ) { Allows allows = method . getAnnotation ( Allows . class ) ; List < Verb > verbs = Arrays . asList ( allows . value ( ) ) ; if ( ! verbs . contains ( verb ) ) { throw new CannotAcceptRequestException ( HttpServletResponse . SC_METHOD_NOT_ALLOWED , "Endpoint method [" + method . getDeclaringClass ( ) . getName ( ) + "#" + method . getName ( ) + "] is not capable of accepting [" + verb + "] method" ) ; } } // Is the MIME media type of the request acceptable ?
Accepts accepts = method . getAnnotation ( Accepts . class ) ; String type = context . request ( ) . getContentType ( ) ; if ( accepts != null ) { boolean acceptable = false ; for ( String value : accepts . value ( ) ) { if ( type . startsWith ( value ) ) { acceptable = true ; break ; } } if ( ! acceptable ) { throw new CannotAcceptRequestException ( HttpServletResponse . SC_UNSUPPORTED_MEDIA_TYPE , "Endpoint method [" + method . getDeclaringClass ( ) . getName ( ) + "#" + method . getName ( ) + "] is not capable of accepting [" + type + "] media type" ) ; } } Class < ? extends Request > requestType = context . configuration ( ) . requestTypes ( ) . get ( type ) ; if ( requestType == null ) { throw new CannotAcceptRequestException ( HttpServletResponse . SC_UNSUPPORTED_MEDIA_TYPE , "Configuration [" + context . configuration ( ) . getClass ( ) . getName ( ) + "] does not provide a request type corresponding to [" + type + "] media type" ) ; } Request request = requestType . newInstance ( ) ; request . from ( context ) ; // Parameter construction .
List < Object > parameters = new ArrayList < Object > ( ) ; Annotation [ ] [ ] parameterAnnotations = method . getParameterAnnotations ( ) ; Type [ ] parameterTypes = method . getGenericParameterTypes ( ) ; for ( int i = 0 ; i < parameterTypes . length ; i ++ ) { List < Annotation > sources = new ArrayList < Annotation > ( ) ; for ( Annotation annotation : parameterAnnotations [ i ] ) { if ( annotation . annotationType ( ) . isAnnotationPresent ( Source . class ) ) { sources . add ( annotation ) ; } } parameters . add ( request . get ( parameterTypes [ i ] , sources ) ) ; } context . parameters ( parameters ) ; return true ; } catch ( CannotAcceptRequestException exception ) { logger . warn ( "Failed to accept HTTP request" , exception ) ; try { context . response ( ) . sendError ( exception . status ( ) ) ; return false ; } catch ( IOException e ) { throw new UncheckedException ( e ) ; } } catch ( Exception e ) { throw new UncheckedException ( e ) ; }


signature:
public class ResourceKit { /** * Resolve the given resource location to a { @ code java . io . File } , i . e . to a file in the file
 * system . < p > Does not check whether the file actually exists ; simply returns the File that the
 * given location would correspond to .
 * @ param resourceLocation the resource location to resolve : either a " classpath : " pseudo URL , a
 * " file : " URL , or a plain file path
 * @ return a corresponding File object
 * @ throws FileNotFoundException if the resource cannot be resolved to a file in the file
 * system */
public static File getFile ( String resourceLocation ) throws FileNotFoundException { } }

implementation:
Preconditions . checkNotNull ( resourceLocation , "Resource location must not be null" ) ; if ( resourceLocation . startsWith ( CLASSPATH_URL_PREFIX ) ) { String path = resourceLocation . substring ( CLASSPATH_URL_PREFIX . length ( ) ) ; String description = "class path resource [" + path + "]" ; URL url = ClassKit . getDefaultClassLoader ( ) . getResource ( path ) ; if ( url == null ) { throw new FileNotFoundException ( description + " cannot be resolved to absolute file path " + "because it does not reside in the file system" ) ; } return getFile ( url , description ) ; } try { // try URL
return getFile ( new URL ( resourceLocation ) ) ; } catch ( MalformedURLException ex ) { // no URL - > treat as file path
return new File ( resourceLocation ) ; }


signature:
public class ResourceKit { /** * Determine whether the given URL points to a resource in a jar file , that is , has protocol
 * " jar " , " zip " , " wsjar " or " code - source " . < p > " zip " and " wsjar " are used by WebLogic Server and
 * WebSphere , respectively , but can be treated like jar files .
 * @ param url the URL to check
 * @ return whether the URL has been identified as a JAR URL */
public static boolean isJarURL ( URL url ) { } }

implementation: String up = url . getProtocol ( ) ; return ( URL_PROTOCOL_JAR . equals ( up ) || URL_PROTOCOL_ZIP . equals ( up ) || URL_PROTOCOL_WSJAR . equals ( up ) ) ;


signature:
public class DefaultConfiguration { /** * Returns the default HTTP request processing pipeline .
 * HTTP request processing pipeline consists of [ Route ] - & gt ; [ Receive ]
 * - & gt ; [ Invoke ] - & gt ; [ Send ] by default .
 * @ return HTTP request processing pipeline .
 * @ see Route
 * @ see Receive
 * @ see Invoke
 * @ see Send */
public Pipeline < WebContext > pipeline ( ) { } }

implementation: return new Pipeline < WebContext > ( ) . set ( Route . class . getSimpleName ( ) , new Route ( ) ) . set ( Receive . class . getSimpleName ( ) , new Receive ( ) ) . set ( Invoke . class . getSimpleName ( ) , new Invoke ( ) ) . set ( Send . class . getSimpleName ( ) , new Send ( ) ) ;


signature:
public class ZipKit { /** * Zips a file or a folder . If adding a folder , all its content will be added . */
public static void zip ( File file ) throws IOException { } }

implementation: String zipFile = file . getAbsolutePath ( ) + ZIP_EXT ; ZipOutputStream zos = null ; try { zos = createZip ( zipFile ) ; addToZip ( zos ) . file ( file ) . recursive ( ) . add ( ) ; } finally { StreamUtil . close ( zos ) ; }


signature:
public class ZipKit { /** * Extracts zip file to the target directory . If patterns are provided only matched paths are
 * extracted .
 * @ param zipFile zip file
 * @ param destDir destination directory
 * @ param patterns optional wildcard patterns of files to extract , may be < code > null < / code > */
public static void unzip ( File zipFile , File destDir , String ... patterns ) throws IOException { } }

implementation: ZipFile zip = new ZipFile ( zipFile ) ; Enumeration zipEntries = zip . entries ( ) ; while ( zipEntries . hasMoreElements ( ) ) { ZipEntry entry = ( ZipEntry ) zipEntries . nextElement ( ) ; String entryName = entry . getName ( ) ; if ( patterns != null && patterns . length > 0 ) { if ( Wildcard . matchPathOne ( entryName , patterns ) == - 1 ) { continue ; } } File file = ( destDir != null ) ? new File ( destDir , entryName ) : new File ( entryName ) ; if ( entry . isDirectory ( ) ) { if ( ! file . mkdirs ( ) ) { if ( ! file . isDirectory ( ) ) { throw new IOException ( "Failed to create directory: " + file ) ; } } } else { File parent = file . getParentFile ( ) ; if ( parent != null && ! parent . exists ( ) ) { if ( ! parent . mkdirs ( ) ) { if ( ! file . isDirectory ( ) ) { throw new IOException ( "Failed to create directory: " + parent ) ; } } } InputStream in = zip . getInputStream ( entry ) ; OutputStream out = null ; try { out = new FileOutputStream ( file ) ; StreamUtil . copy ( in , out ) ; } finally { StreamUtil . close ( out ) ; StreamUtil . close ( in ) ; } } } close ( zip ) ;


signature:
public class GenericResponse { /** * Writes HTTP response representation to output stream .
 * This method determines the response form as the following convention :
 * < ul >
 * < li >
 * If the MIME media type ( { @ code # mediaType } ) is not empty , set it to
 * ' Content - Type ' HTTP response header .
 * < / li >
 * < li >
 * If the status ( { @ code # status } ) is greater than 0 , set it to HTTP
 * response code .
 * < / li >
 * < li >
 * If { @ code # entity } is an instance of { @ code String } , this method writes
 * it to the HTTP response directly . If MIME media type has not been
 * specified , ' text / plain ' is used .
 * < / li >
 * < li >
 * If { @ code # entity } is an instance of { @ code Externalizable } , this method
 * writes it to the HTTP response as { @ code ObjectOutputStream } by invoking
 * { @ code Externalizable # writeExternal ( java . io . ObjectOutput ) } .
 * < / li >
 * < li >
 * If { @ code # entity } is an instance of { @ code Serializable } , this method
 * writes it to the HTTP response as { @ code ObjectOutputStream } .
 * < / li >
 * < li >
 * The other , this method write it to the HTTP response as plain text by
 * invoking { @ code # value # toString ( ) } . If MIME media type has not been
 * specified , ' text / plain ' is used .
 * < / li >
 * < / ul >
 * UTF - 8 is used for the character encoding ( MIME charset ) at any time .
 * @ param context HTTP request processing context . */
public void to ( WebContext context ) { } }

implementation: HttpServletResponse response = context . response ( ) ; if ( ! mediaType . isEmpty ( ) ) { response . setHeader ( "Content-Type" , mediaType ) ; } if ( status > 0 ) { response . setStatus ( status ) ; } if ( entity == null ) { return ; } try { if ( entity instanceof String ) { if ( mediaType . isEmpty ( ) ) { response . setHeader ( "Content-Type" , MediaType . TEXT_PLAIN ) ; } response . setCharacterEncoding ( "UTF-8" ) ; response . getWriter ( ) . write ( ( String ) entity ) ; } else if ( entity instanceof Serializable ) { new ObjectOutputStream ( response . getOutputStream ( ) ) . writeObject ( entity ) ; } else { if ( mediaType . isEmpty ( ) ) { response . setHeader ( "Content-Type" , MediaType . TEXT_PLAIN ) ; } response . setCharacterEncoding ( "UTF-8" ) ; response . getWriter ( ) . write ( entity . toString ( ) ) ; } } catch ( IOException e ) { throw new UncheckedException ( e ) ; }


signature:
public class LoggerInit { /** * 日志控件初始化 */
public static void init ( ) { } }

implementation: URL slf4jConf = LoggerInit . class . getResource ( slf4jPath ) ; final String app_name = GojaConfig . getAppName ( ) ; final String app_version = GojaConfig . getVersion ( ) ; if ( slf4jConf == null ) { LoggerContext lc = ( LoggerContext ) LoggerFactory . getILoggerFactory ( ) ; lc . reset ( ) ; AppLogConfigurator . configure ( lc ) ; Logger . slf4j = LoggerFactory . getLogger ( app_name + StringPool . AT + app_version ) ; } else if ( Logger . slf4j == null ) { if ( slf4jConf . getFile ( ) . indexOf ( PathKit . getWebRootPath ( ) ) == 0 ) { Logger . configuredManually = true ; } Logger . slf4j = LoggerFactory . getLogger ( app_name + StringPool . AT + app_version ) ; }


signature:
public class PermissionDialogFragment { /** * A static dialog fragment instance creator method .
 * @ param bean { @ link PermBean }
 * @ param requestCode any 16 bit { @ link Integer } value .
 * @ return new prepared instance of PermissionDialogFragment . */
public static PermissionDialogFragment getInstance ( PermBean bean , int requestCode ) { } }

implementation:
if ( bean == null ) throw new NullPointerException ( "Permission Beans cannot be null !" ) ; Bundle extras = new Bundle ( 3 ) ; // convert map to two arrays .
HashMap < Permission , String > map = ( HashMap < Permission , String > ) bean . getPermissions ( ) ; // put arrays in extras .
extras . putSerializable ( PERMISSION , map ) ; extras . putInt ( REQUEST , requestCode ) ; // set extras in fragment and return .
PermissionDialogFragment fragment = new PermissionDialogFragment ( ) ; fragment . setArguments ( extras ) ; return fragment ;


signature:
public class PermissionDialogFragment { /** * Work around for dialog not to dismiss on back button press . */
@ Override public void onResume ( ) { } }

implementation: super . onResume ( ) ; getDialog ( ) . setOnKeyListener ( new DialogInterface . OnKeyListener ( ) { @ Override public boolean onKey ( DialogInterface dialog , int keyCode , KeyEvent keyEvent ) { return keyCode != KeyEvent . ACTION_DOWN ; } } ) ;


signature:
public class Wildcard { /** * Checks if two strings are equals or if they { @ link # match ( String , String ) } .
 * Useful for cases when matching a lot of equal strings and speed is important . */
public static boolean equalsOrMatch ( String string , String pattern ) { } }

implementation: return string . equals ( pattern ) || match ( string , pattern , 0 , 0 ) ;


signature:
public class Types { /** * Returns < code > true < / code > if the specified < code > type < / code > is a
 * built - in type .
 * @ param type The type to be tested .
 * @ return < code > true < / code > if the specified < code > type < / code > is a
 * built - in type . */
public static boolean isBuiltinType ( Type type ) { } }

implementation: Class < ? > rawType = getRawType ( type ) ; return ( rawType == null ) ? false : builtins . contains ( rawType ) ;


signature:
public class Types { /** * Returns < code > true < / code > if the specified < code > type < / code > is an
 * instance of { @ code Collection } .
 * @ param type The type to be tested .
 * @ return < code > true < / code > if the specified < code > type < / code > is an
 * instance of { @ code Collection } . */
public static boolean isCollection ( Type type ) { } }

implementation: Class < ? > rawType = getRawType ( type ) ; return ( rawType == null ) ? false : ( rawType . equals ( Collection . class ) || ClassUtils . getAllInterfaces ( rawType ) . contains ( Collection . class ) ) ;


signature:
public class Types { /** * Returns < code > true < / code > if the specified < code > type < / code > is an
 * instance of supported { @ code Collection } . < br >
 * < br >
 * Supported collections are :
 * < pre >
 * java . util . Collection
 * java . util . List
 * java . util . Set
 * java . util . SortedSet
 * java . util . NavigableSet
 * java . util . Queue
 * java . util . Deque
 * java . util . ArrayList
 * java . util . LinkedList
 * java . util . concurrent . CopyOnWriteArrayList
 * java . util . Stack
 * java . util . Vector
 * java . util . HashSet
 * java . util . LinkedHashSet
 * java . util . concurrent . CopyOnWriteArraySet
 * java . util . TreeSet
 * java . util . concurrent . ConcurrentSkipListSet
 * java . util . PriorityQueue
 * java . util . concurrent . ConcurrentLinkedQueue
 * java . util . concurrent . PriorityBlockingQueue
 * java . util . concurrent . DelayQueue
 * java . util . concurrent . LinkedBlockingQueue
 * java . util . concurrent . PriorityBlockingQueue
 * java . util . ArrayDeque
 * java . util . concurrent . LinkedBlockingDeque
 * java . util . concurrent . SynchronousQueue
 * < / pre >
 * @ param type The type to be tested .
 * @ return < code > true < / code > if the specified < code > type < / code > is an
 * instance of supported { @ code Collection } . < br > */
public static boolean isSupportedCollection ( Type type ) { } }

implementation: Class < ? > rawType = getRawType ( type ) ; return ( rawType == null ) ? false : collections . contains ( rawType ) ;


signature:
public class Types { /** * Returns < code > true < / code > if the specified < code > type < / code > is an array
 * type .
 * @ param type The type to be tested .
 * @ return < code > true < / code > if the specified < code > type < / code > is an array
 * type . */
public static boolean isArray ( Type type ) { } }

implementation: if ( type instanceof GenericArrayType ) { return true ; } else if ( type instanceof Class < ? > ) { return ( ( Class < ? > ) type ) . isArray ( ) ; } else { return false ; }


signature:
public class Types { /** * Returns the element type of the specified collection type .
 * The specified type must be collection or array . To make it sure , use
 * { @ code # isCollection ( Type ) } method or { @ code # isArray ( Type ) } method .
 * @ param type Collection or array type .
 * @ return The element type of the specified collection or array .
 * @ throws IllegalArgumentException If the specified ' type ' is not a
 * collection or array . */
public static Class < ? > getElementType ( Type type ) { } }

implementation: if ( isCollection ( type ) ) { if ( type instanceof ParameterizedType ) { ParameterizedType parameterizedType = ( ParameterizedType ) type ; return ( Class < ? > ) parameterizedType . getActualTypeArguments ( ) [ 0 ] ; } else { return Object . class ; } } else if ( isArray ( type ) ) { if ( type instanceof GenericArrayType ) { GenericArrayType genericArrayType = ( GenericArrayType ) type ; return ( Class < ? > ) genericArrayType . getGenericComponentType ( ) ; } else { Class < ? > clazz = ( Class < ? > ) type ; return clazz . getComponentType ( ) ; } } else { throw new IllegalArgumentException ( "'type' must be a collection or array" ) ; }


signature:
public class Types { /** * Returns the default implementation type of the specified collection
 * interface type .
 * The specified type must be an supported collection . To make it sure , use
 * { @ code # isSupportedCollection ( Type ) } . If the specified collection type is
 * < b > not < / b > an interface , this method returns the specified implementation
 * type directly . < br >
 * < br >
 * The default implementations are :
 * < pre >
 * java . util . Collection - > java . util . ArrayList
 * java . util . List - > java . util . ArrayList
 * java . util . Set - > java . util . HashSet
 * java . util . SortedSet - > java . util . TreeSet
 * java . util . NavigableSet - > java . util . TreeSet
 * java . util . Queue - > java . util . PriorityQueue
 * java . util . Deque - > java . util . ArrayDeque
 * < / pre >
 * @ param type Collection type ( must be supported type ) .
 * @ return The default implementation type of the specified collection
 * interface type . */
public static Class < ? > getDefaultImplementationType ( Type type ) { } }

implementation: Class < ? > clazz = getRawType ( type ) ; return ( clazz . isInterface ( ) ) ? implementations . get ( clazz ) : clazz ;


signature:
public class Types { /** * Returns < code > true < / code > if the specified < code > type < / code > is a
 * supported core value type . < br >
 * < br >
 * Supported core value types are :
 * < pre >
 * boolean
 * byte
 * char
 * double
 * float
 * int
 * long
 * short
 * java . math . BigDecimal
 * java . math . BigInteger
 * Boolean
 * Byte
 * Character
 * Double
 * Float
 * Integer
 * Long
 * Short
 * String
 * Class
 * java . util . Date
 * java . util . Calendar
 * java . io . File
 * java . sql . Date
 * java . sql . Time
 * java . sql . Timestamp
 * java . net . URL
 * Object
 * < / pre >
 * @ param type The type to be tested .
 * @ return < code > true < / code > if the specified type is supported core value
 * type . */
public static boolean isCoreValueType ( Type type ) { } }

implementation: Class < ? > rawType = getRawType ( type ) ; return ( rawType == null ) ? false : values . contains ( rawType ) ;


signature:
public class Types { /** * Returns < code > true < / code > if the specified type is an user define value
 * type .
 * User defined value type must satisfy either of the following condition .
 * < ol >
 * < li > ( The class ) has a public constructor that takes one String . class parameter . < / li >
 * < li > Has a public static factory method that named ' valueOf ' and takes one
 * String . class parameter . < / li >
 * < / ol >
 * @ param type The type to be tested .
 * @ return < code > true < / code > if the specified type is an user define value
 * type . */
public static boolean isUserDefinedValueType ( Type type ) { } }

implementation: Class < ? > rawType = getRawType ( type ) ; if ( rawType == null ) { return false ; } for ( Constructor < ? > constructor : rawType . getConstructors ( ) ) { Class < ? > [ ] parameterTypes = constructor . getParameterTypes ( ) ; if ( parameterTypes . length == 1 && parameterTypes [ 0 ] . equals ( String . class ) ) { return true ; } } for ( Method method : rawType . getMethods ( ) ) { if ( method . getName ( ) . equals ( "valueOf" ) && Modifier . isStatic ( method . getModifiers ( ) ) ) { return true ; } } return false ;


signature:
public class Types { /** * Adds supported core value type .
 * @ param clazz The core value type .
 * @ param converter Converter for the specified core value type . */
public static void addCoreValueType ( Class < ? > clazz , Converter converter ) { } }

implementation: ConvertUtils . register ( converter , clazz ) ; values . add ( clazz ) ;


signature:
public class Types { /** * Returns the raw type of the specified type .
 * This method supports { @ code ParameterizedType } or raw { @ code Class }
 * ( just returns it directly ) . The other types such as array type are not
 * supported . If the specified ' type ' is not supported , this method returns
 * < code > null < / code > .
 * @ param type The type to be tested .
 * @ return The raw type of the specified type . */
public static Class < ? > getRawType ( Type type ) { } }

implementation: if ( type instanceof ParameterizedType ) { ParameterizedType parameterizedType = ( ParameterizedType ) type ; return ( Class < ? > ) parameterizedType . getRawType ( ) ; } else if ( type instanceof Class < ? > ) { Class < ? > clazz = ( Class < ? > ) type ; return ( clazz . isArray ( ) ) ? null : clazz ; } else { return null ; }


signature:
public class Validator { /** * Matches the regular expression
 * @ param regex regex
 * @ param value value
 * @ return boolean */
public static boolean match ( String regex , String value ) { } }

implementation: Pattern pattern = Pattern . compile ( regex ) ; return pattern . matcher ( value ) . find ( ) ;


signature:
public class Validator { /** * Email validation
 * @ param value value
 * @ return boolean */
public static boolean isEmail ( String value ) { } }

implementation: String check = "^([a-z0-9A-Z]+[-|\\.]?)+[a-z0-9A-Z]@([a-z0-9A-Z]+(-[a-z0-9A-Z]+)?\\.)+[a-zA-Z]{2,}$" ; return match ( check , Pattern . CASE_INSENSITIVE , value ) ;


signature:
public class Validator { /** * Phone number verification
 * @ param value value
 * @ return boolean */
public static boolean isMobile ( String value ) { } }


signature:
public class Validator { /** * Phone verification
 * @ param value value
 * @ return boolean */
public static boolean isTel ( String value ) { } }

implementation: String check = "^\\d{3,4}-?\\d{7,9}$" ; return match ( check , Pattern . CASE_INSENSITIVE , value ) ;


signature:
public class Validator { /** * Telephone number , including mobile phones and landlines
 * @ param value value
 * @ return boolean */
public static boolean isPhone ( String value ) { } }

implementation: String telcheck = "^\\d{3,4}-?\\d{7,9}$" ; String mobilecheck = "^(((13[0-9]{1})|(15[0-9]{1})|(18[0-9]{1}))+\\d{8})$" ; return match ( telcheck , Pattern . CASE_INSENSITIVE , value ) || match ( mobilecheck , Pattern . CASE_INSENSITIVE , value ) ;


signature:
public class Validator { /** * Judge whether it is birthday
 * @ param value value
 * @ return boolean */
public static boolean isBirthDay ( String value ) { } }

implementation: String check = "(\\d{4})(/|-|\\.)(\\d{1,2})(/|-|\\.)(\\d{1,2})$" ; if ( match ( check , Pattern . CASE_INSENSITIVE , value ) ) { int year = Integer . parseInt ( value . substring ( 0 , 4 ) ) ; int month = Integer . parseInt ( value . substring ( 5 , 7 ) ) ; int day = Integer . parseInt ( value . substring ( 8 , 10 ) ) ; if ( month < 1 || month > 12 ) { return false ; } if ( day < 1 || day > 31 ) { return false ; } if ( ( month == 4 || month == 6 || month == 9 || month == 11 ) && day == 31 ) { return false ; } if ( month == 2 ) { boolean isleap = ( year % 4 == 0 && ( year % 100 != 0 || year % 400 == 0 ) ) ; if ( day > 29 || ( day == 29 && ! isleap ) ) { return false ; } } return true ; } else { return false ; }


signature:
public class Validator { /** * Identity verification
 * @ param value value
 * @ return boolean */
public static boolean isIdentityCard ( String value ) { } }

implementation: String check = "(^\\d{15}$)|(^\\d{17}([0-9]|X)$)" ; return match ( check , Pattern . CASE_INSENSITIVE , value ) ;


signature:
public class Validator { /** * Postal Code
 * @ param value value
 * @ return boolean */
public static boolean isZipCode ( String value ) { } }

implementation: String check = "^[0-9]{6}$" ; return match ( check , Pattern . CASE_INSENSITIVE , value ) ;


signature:
public class Validator { /** * Currency validation
 * @ param value value
 * @ return boolean */
public static boolean isCurrency ( String value ) { } }

implementation: String check = "^(\\d+(?:\\.\\d{1,2})?)$" ; return match ( check , Pattern . CASE_INSENSITIVE , value ) ;


signature:
public class Validator { /** * Chinese
 * @ param value value
 * @ return boolean */
public static boolean isChinese ( String value ) { } }

implementation: String check = "^[\\u2E80-\\u9FFF]+$" ; return match ( check , Pattern . CASE_INSENSITIVE , value ) ;


signature:
public class Validator { /** * Matches are linked
 * @ param value value
 * @ return boolean */
public static boolean isUrl ( String value ) { } }


signature:
public class Validator { /** * Tell the time
 * @ param value value
 * @ return boolean */
public static boolean isDateTime ( String value ) { } }


signature:
public class Validator { /** * Blank
 * @ param value value
 * @ return boolean */
public static boolean isBlank ( Object value ) { } }

implementation: if ( value instanceof Collection ) { return ( ( Collection ) value ) . isEmpty ( ) ; } else if ( value instanceof String ) { return "" . equals ( value . toString ( ) . trim ( ) ) ; } else { return value == null ; }


signature:
public class QRCode { /** * 使用指定的 「 QRCode 生成器格式 」 来创建一个 QRCode 处理器 。
 * @ param content 所要生成 QRCode 的内容
 * @ param format QRCode 生成器格式
 * @ return QRCode 处理器 */
public static QRCode create ( final String content , QRCodeFormat format ) { } }

implementation: QRCode qrcode = new QRCode ( ) ; qrcode . format = format ; qrcode . qrcodeImage = toQRCode ( content , format ) ; return qrcode ;


signature:
public class QRCode { /** * 使用指定的 「 QRCode生成器格式 」 , 把指定的内容生成为一个 QRCode 的图像对象 。
 * @ param content 所需生成 QRCode 的内容
 * @ return QRCode 的图像对象 */
public static BufferedImage toQRCode ( String content , QRCodeFormat format ) { } }

implementation: if ( format == null ) { format = QRCodeFormat . NEW ( ) ; } content = new String ( content . getBytes ( Charset . forName ( format . getEncode ( ) ) ) ) ; BitMatrix matrix ; try { matrix = new QRCodeWriter ( ) . encode ( content , BarcodeFormat . QR_CODE , format . getSize ( ) , format . getSize ( ) , format . getHints ( ) ) ; } catch ( WriterException e ) { throw new RuntimeException ( e ) ; } int width = matrix . getWidth ( ) ; int height = matrix . getHeight ( ) ; int fgColor = format . getForeGroundColor ( ) . getRGB ( ) ; int bgColor = format . getBackGroundColor ( ) . getRGB ( ) ; BufferedImage image = new BufferedImage ( width , height , ColorSpace . TYPE_RGB ) ; for ( int x = 0 ; x < width ; x ++ ) { for ( int y = 0 ; y < height ; y ++ ) { image . setRGB ( x , y , matrix . get ( x , y ) ? fgColor : bgColor ) ; } } return image ;


signature:
public class QRCode { /** * 从指定的 QRCode 图片文件中解析出其内容 。
 * @ param qrcodeFile QRCode 文件
 * @ return QRCode 中的内容 */
public static String from ( String qrcodeFile ) { } }

implementation: if ( qrcodeFile . startsWith ( "http://" ) || qrcodeFile . startsWith ( "https://" ) ) { try { return from ( new URL ( qrcodeFile ) ) ; } catch ( MalformedURLException e ) { throw new RuntimeException ( e ) ; } } else { return from ( new File ( qrcodeFile ) ) ; }


signature:
public class QRCode { /** * 从指定的 QRCode 图片文件中解析出其内容 。
 * @ param qrcodeFile QRCode 图片文件
 * @ return QRCode 中的内容 */
public static String from ( File qrcodeFile ) { } }

implementation: if ( ! qrcodeFile . exists ( ) ) { return null ; } try { BufferedImage image = ImageIO . read ( qrcodeFile ) ; return from ( image ) ; } catch ( IOException e ) { throw new RuntimeException ( e ) ; }


signature:
public class QRCode { /** * 从指定的 QRCode 图片链接中解析出其内容 。
 * @ param qrcodeUrl QRCode 图片链接
 * @ return QRCode 中的内容 */
public static String from ( URL qrcodeUrl ) { } }

implementation: try { BufferedImage image = ImageIO . read ( qrcodeUrl ) ; return from ( image ) ; } catch ( IOException e ) { throw new RuntimeException ( e ) ; }


signature:
public class QRCode { /** * 从指定的 QRCode 图像对象中解析出其内容 。
 * @ param qrcodeImage QRCode 图像对象
 * @ return QRCode 中的内容 */
public static String from ( BufferedImage qrcodeImage ) { } }

implementation: final LuminanceSource source = new BufferedImageLuminanceSource ( qrcodeImage ) ; final BinaryBitmap bitmap = new BinaryBitmap ( new HybridBinarizer ( source ) ) ; String content ; try { Result result = new QRCodeReader ( ) . decode ( bitmap ) ; content = result . getText ( ) ; } catch ( NotFoundException e ) { throw new RuntimeException ( e ) ; } catch ( ChecksumException e ) { throw new RuntimeException ( e ) ; } catch ( FormatException e ) { throw new RuntimeException ( e ) ; } return content ;


signature:
public class QRCode { /** * 把指定的内容生成为一个 QRCode 的图片 , 之后保存到指定的文件中 。
 * @ param qrcodeFile 指定的文件
 * @ return QRCode 处理器 */
public QRCode toFile ( File qrcodeFile ) { } }

implementation: try { if ( ! qrcodeFile . exists ( ) ) { Files . createParentDirs ( qrcodeFile ) ; qrcodeFile . createNewFile ( ) ; } if ( ! ImageIO . write ( this . qrcodeImage , getSuffixName ( qrcodeFile ) , qrcodeFile ) ) { throw new RuntimeException ( ) ; } } catch ( IOException e ) { throw new RuntimeException ( e ) ; } this . qrcodeFile = qrcodeFile ; return this ;


signature:
public class QRCode { /** * 把指定的内容生成为一个 QRCode 的图片 , 并在该图片中间添加上指定的图片 ; 之后保存到指定的文件内 。
 * @ param qrcodeFile QRCode 图片生成的指定的文件
 * @ param appendFile 需要添加的图片
 * @ return QRCode 处理器 */
public QRCode toFile ( String qrcodeFile , String appendFile ) { } }

implementation: return toFile ( new File ( qrcodeFile ) , new File ( appendFile ) ) ;


signature:
public class QRCode { /** * 把指定的内容生成为一个 QRCode 的图片 , 并在该图片中间添加上指定的图片 ; 之后保存到指定的文件内 。
 * @ param qrcodeFile QRCode 图片生成的指定的文件
 * @ param appendFile 需要添加的图片
 * @ return QRCode 处理器 */
public QRCode toFile ( File qrcodeFile , File appendFile ) { } }

implementation: try { if ( ! qrcodeFile . exists ( ) ) { Files . createParentDirs ( qrcodeFile ) ; qrcodeFile . createNewFile ( ) ; } appendImage ( this . qrcodeImage , ImageIO . read ( appendFile ) , this . format ) ; if ( ! ImageIO . write ( this . qrcodeImage , getSuffixName ( qrcodeFile ) , qrcodeFile ) ) { throw new RuntimeException ( "Unexpected error writing image" ) ; } } catch ( IOException e ) { throw new RuntimeException ( e ) ; } this . qrcodeFile = qrcodeFile ; return this ;


signature:
public class JSONRequest { /** * Constructs a new { @ code JSONRequest } from the current { @ code WebContext } .
 * @ param context The current { @ code WebContext } . */
public void from ( WebContext context ) { } }

implementation: try { element = new JsonParser ( ) . parse ( context . request ( ) . getReader ( ) ) ; } catch ( Exception e ) { logger . warn ( "Cannot parse JSON string into a parse tree" , e ) ; throw new UncheckedException ( e ) ; } super . from ( context ) ;


signature:
public class JSONRequest { /** * Returns the Web endpoint method parameter value from the current HTTP
 * request body sent as JSON format .
 * This method supports the following parameter declaration independently .
 * Other than them are the same as { @ link AbstractRequest } .
 * < ol >
 * < li > Named collection of user - defined object type < / li >
 * < li > Named user - defined object type < / li >
 * < li > No - named collection of core value type < / li >
 * < li > No - named collection of user - defined value type < / li >
 * < li > No - named collection of user - defined object type < / li >
 * < / ol >
 * @ param type Web endpoint method parameter type .
 * @ param name Web endpoint method parameter name .
 * @ return Web endpoint method parameter value . */
@ Override protected Object body ( Type type , String name ) { } }

implementation: return body ( type , name , element ) ;


signature:
public class JSONRequest { /** * Converts the specified object to the specified user - defined value type .
 * The object to be converted must be a { @ code JsonPrimitive } , or this
 * method return < code > null < / code > .
 * @ param object The object to be converted
 * @ param type The user - defined value type to which the specified object be
 * converted .
 * @ return The converted object . */
@ Override protected Object convertUserDefinedValueType ( Object object , Class < ? > type ) { } }

implementation: if ( object instanceof JsonPrimitive ) { JsonPrimitive primitive = ( JsonPrimitive ) object ; return super . convertUserDefinedValueType ( primitive . getAsString ( ) , type ) ; } else { logger . warn ( "Parameter [" + object + "] cannot be converted to [" + type + "]; Converted 'object' must be a [" + JsonPrimitive . class + "]" ) ; return null ; }


signature:
public class BootlegFilter { /** * Initializes this filter with the specified configuration .
 * Constructs the { @ code Configuration } and sets up the HTTP request processing
 * pipeline . If the custom configuration class has not been specified ,
 * { @ link DefaultConfiguration } is used by default .
 * @ param filterConfig Servlet filter configuration . */
public void init ( FilterConfig filterConfig ) throws ServletException { } }

implementation: logger . info ( "Starting Bootleg on the Servlet [" + filterConfig . getServletContext ( ) . getMajorVersion ( ) + "." + filterConfig . getServletContext ( ) . getMinorVersion ( ) + "] environment" ) ; Configuration configuration = configuration ( filterConfig ) ; if ( configuration == null ) { configuration = new DefaultConfiguration ( ) ; configuration . init ( filterConfig . getServletContext ( ) ) ; logger . info ( "Default configuration [" + DefaultConfiguration . class + "] loaded" ) ; } Pipeline < WebContext > pipeline = configuration . pipeline ( ) ; if ( pipeline == null ) { throw new ServletException ( "Pipeline must not be [" + pipeline + "]: Configuration [" + configuration + "]" ) ; } else { logger . debug ( "HTTP request processing pipeline " + pipeline + " constructed" ) ; } this . configuration = configuration ; this . pipeline = pipeline ;


signature:
public class BootlegFilter { /** * Processes the Web request in Bootleg .
 * @ param request HTTP request .
 * @ param response HTTP response .
 * @ throws IOException If any I / O error has occurred .
 * @ throws ServletException If any exception has occurred in processing the
 * request . */
public void doFilter ( ServletRequest request , ServletResponse response , FilterChain chain ) throws IOException , ServletException { } }

implementation: try { pipeline . apply ( new WebContext ( configuration , ( HttpServletRequest ) request , ( HttpServletResponse ) response , chain ) ) ; } catch ( Exception e ) { logger . warn ( "Failed to process HTTP request" , e ) ; ( ( HttpServletResponse ) response ) . sendError ( HttpServletResponse . SC_INTERNAL_SERVER_ERROR ) ; }


signature:
public class BootlegFilter { /** * Constructs the { @ code Configuration } .
 * This method attempts to get custom configuration class from { @ code ServletContext }
 * init parameter and instantiate and initialize it . If the custom configuration
 * class has not been specified as the { @ code ServletContext } init parameter ,
 * this method returns < code > null < / code > .
 * @ param config Servlet filter configuration .
 * @ return { @ code Configuration } constructed .
 * @ throws ServletException If the custom configuration loading is failed . */
protected Configuration configuration ( FilterConfig config ) throws ServletException { } }

implementation: ServletContext context = config . getServletContext ( ) ; String clazz = context . getInitParameter ( CONFIGURATION ) ; Configuration configuration = null ; if ( clazz != null ) { try { configuration = ( Configuration ) Class . forName ( clazz ) . newInstance ( ) ; configuration . init ( config . getServletContext ( ) ) ; logger . info ( "Custom configuration [" + clazz + "] loaded" ) ; } catch ( Exception e ) { logger . error ( "Failed to load custom configuration [" + clazz + "]" , e ) ; throw new ServletException ( "Failed to load custom configuration [" + clazz + "]" , e ) ; } } return configuration ;


signature:
public class GojaBootVersion { /** * Return the full version string of the present Goja Boot codebase , or { @ code null }
 * if it cannot be determined .
 * @ return the version of Goja Boot or { @ code null }
 * @ see Package # getImplementationVersion ( ) */
public static String getVersion ( ) { } }

implementation: Package pkg = GojaBootVersion . class . getPackage ( ) ; return ( pkg != null ? pkg . getImplementationVersion ( ) : null ) ;


signature:
public class ExtendsDirective { /** * 取得模板路径的地址
 * @ param env Freemarker的运行环境
 * @ return 模板路径地址 */
private String getTemplatePath ( Environment env ) { } }

implementation: String templateName = env . getTemplate ( ) . getName ( ) ; return templateName . lastIndexOf ( '/' ) == - 1 ? "" : templateName . substring ( 0 , templateName . lastIndexOf ( '/' ) + 1 ) ;


signature:
public class Codec { /** * Encode a String to base64
 * @ param value The plain String
 * @ return The base64 encoded String */
public static String encodeBASE64 ( String value ) { } }

implementation: try { return new String ( Base64 . encodeBase64 ( value . getBytes ( StringPool . UTF_8 ) ) ) ; } catch ( UnsupportedEncodingException ex ) { throw new UnexpectedException ( ex ) ; }


signature:
public class Codec { /** * Decode a base64 value
 * @ param value The base64 encoded String
 * @ return decoded binary data */
public static byte [ ] decodeBASE64 ( String value ) { } }

implementation: try { return Base64 . decodeBase64 ( value . getBytes ( StringPool . UTF_8 ) ) ; } catch ( UnsupportedEncodingException ex ) { throw new UnexpectedException ( ex ) ; }


signature:
public class Codec { /** * Transform an hexadecimal String to a byte array . */
public static byte [ ] hexStringToByte ( String hexString ) { } }

implementation: try { return Hex . decodeHex ( hexString . toCharArray ( ) ) ; } catch ( DecoderException e ) { throw new UnexpectedException ( e ) ; }


signature:
public class IO { /** * Read a properties file with the utf - 8 encoding
 * @ param is Stream to properties file
 * @ return The Properties object */
public static Properties readUtf8Properties ( InputStream is ) { } }

implementation: Properties properties = new OrderSafeProperties ( ) ; try { properties . load ( is ) ; is . close ( ) ; } catch ( Exception e ) { throw new RuntimeException ( e ) ; } return properties ;


signature:
public class IO { /** * Read the Stream content as a string
 * @ param is The stream to read
 * @ return The String content */
public static String readContentAsString ( InputStream is , String encoding ) { } }

implementation: String res = null ; try { res = IOUtils . toString ( is , encoding ) ; } catch ( Exception e ) { throw new RuntimeException ( e ) ; } finally { try { is . close ( ) ; } catch ( Exception e ) { } } return res ;


signature:
public class IO { /** * Read file content to a String
 * @ param file The file to read
 * @ return The String content */
public static String readContentAsString ( File file , String encoding ) { } }

implementation: InputStream is = null ; try { is = new FileInputStream ( file ) ; StringWriter result = new StringWriter ( ) ; PrintWriter out = new PrintWriter ( result ) ; BufferedReader reader = new BufferedReader ( new InputStreamReader ( is , encoding ) ) ; String line = null ; while ( ( line = reader . readLine ( ) ) != null ) { out . println ( line ) ; } return result . toString ( ) ; } catch ( IOException e ) { throw new UnexpectedException ( e ) ; } finally { if ( is != null ) { try { is . close ( ) ; } catch ( Exception e ) { } } }


signature:
public class IO { /** * Read binary content of a file ( warning does not use on large file ! )
 * @ param file The file te read
 * @ return The binary data */
public static byte [ ] readContent ( File file ) { } }

implementation: InputStream is = null ; try { is = new FileInputStream ( file ) ; byte [ ] result = new byte [ ( int ) file . length ( ) ] ; is . read ( result ) ; return result ; } catch ( IOException e ) { throw new UnexpectedException ( e ) ; } finally { if ( is != null ) { try { is . close ( ) ; } catch ( Exception e ) { } } }


signature:
public class IO { /** * Read binary content of a stream ( warning does not use on large file ! )
 * @ param is The stream to read
 * @ return The binary data */
public static byte [ ] readContent ( InputStream is ) { } }

implementation: try { ByteArrayOutputStream baos = new ByteArrayOutputStream ( ) ; int read = 0 ; byte [ ] buffer = new byte [ 8096 ] ; while ( ( read = is . read ( buffer ) ) > 0 ) { baos . write ( buffer , 0 , read ) ; } return baos . toByteArray ( ) ; } catch ( IOException e ) { throw new UnexpectedException ( e ) ; }


signature:
public class IO { /** * Write binay data to a file
 * @ param data The binary data to write
 * @ param file The file to write */
public static void write ( byte [ ] data , File file ) { } }

implementation: OutputStream os = null ; try { os = new FileOutputStream ( file ) ; os . write ( data ) ; os . flush ( ) ; } catch ( IOException e ) { throw new UnexpectedException ( e ) ; } finally { try { if ( os != null ) os . close ( ) ; } catch ( Exception e ) { } }


signature:
public class IO { /** * Copy an stream to another one . */
public static void write ( InputStream is , OutputStream os ) { } }

implementation: try { int read = 0 ; byte [ ] buffer = new byte [ 8096 ] ; while ( ( read = is . read ( buffer ) ) > 0 ) { os . write ( buffer , 0 , read ) ; } } catch ( IOException e ) { throw new UnexpectedException ( e ) ; } finally { try { is . close ( ) ; } catch ( Exception e ) { } try { os . close ( ) ; } catch ( Exception e ) { } }


signature:
public class IO { /** * Copy an stream to another one . */
public static void write ( InputStream is , File f ) { } }

implementation: OutputStream os = null ; try { os = new FileOutputStream ( f ) ; int read = 0 ; byte [ ] buffer = new byte [ 8096 ] ; while ( ( read = is . read ( buffer ) ) > 0 ) { os . write ( buffer , 0 , read ) ; } } catch ( IOException e ) { throw new UnexpectedException ( e ) ; } finally { try { is . close ( ) ; } catch ( Exception e ) { } try { if ( os != null ) os . close ( ) ; } catch ( Exception e ) { } }


signature:
public class IO { /** * If targetLocation does not exist , it will be created . */
public static void copyDirectory ( File source , File target ) { } }

implementation: if ( source . isDirectory ( ) ) { if ( ! target . exists ( ) ) { target . mkdir ( ) ; } for ( String child : source . list ( ) ) { copyDirectory ( new File ( source , child ) , new File ( target , child ) ) ; } } else { try { write ( new FileInputStream ( source ) , new FileOutputStream ( target ) ) ; } catch ( IOException e ) { throw new UnexpectedException ( e ) ; } }


signature:
public class ExampleActivity { /** * < p > Executes this method on permission result .
 * Get boolean result as method parameter .
 * Granted = True & & Denied = False . < / p >
 * @ param isGranted boolean on permission result . */
@ OPermission ( value = Permission . WRITE_EXTERNAL_STORAGE ) void onStoragePermission ( @ Result boolean isGranted ) { } }

implementation: if ( isGranted ) { updateView ( "\n Write Storage Granted" ) ; } else { updateView ( "\n Write Storage Denied" ) ; }


signature:
public class ExampleActivity { /** * < p > Executes this method on permission results .
 * Get boolean result as method parameter . < / p >
 * @ param isGranted True only if all permissions are granted else False . */
@ OPermission ( values = { } }

implementation: Permission . ACCESS_COARSE_LOCATION , Permission . ACCESS_FINE_LOCATION } ) void onLocationPermission ( @ Result boolean isGranted ) { if ( isGranted ) { updateView ( "\n Location status Granted" ) ; } else { updateView ( "\n Location status Denied" ) ; }


signature:
public class MoneyKit { /** * 货币比较 。 < p / > < p / > 比较本货币对象与另一货币对象的大小 。 如果待比较的两个货币对象的币种不同 , 则抛出 < code > java . lang . IllegalArgumentException < / code > 。
 * 如果本货币对象的金额少于待比较货币对象 , 则返回 - 1 。 如果本货币对象的金额等于待比较货币对象 , 则返回0 。 如果本货币对象的金额大于待比较货币对象 , 则返回1。
 * @ param other 另一对象 。
 * @ return - 1表示小于 , 0表示等于 , 1表示大于 。
 * @ throws IllegalArgumentException 待比较货币对象与本货币对象的币种不同 。 */
public int compareTo ( MoneyKit other ) { } }

implementation: assertSameCurrencyAs ( other ) ; if ( cent < other . cent ) { return - 1 ; } else if ( cent == other . cent ) { return 0 ; } else { return 1 ; }


signature:
public class MoneyKit { /** * 货币加法 。 < p / > < p / > 如果两货币币种相同 , 则返回一个新的相同币种的货币对象 , 其金额为 两货币对象金额之和 , 本货币对象的值不变 。
 * 如果两货币对象币种不同 , 抛出 < code > java . lang . IllegalArgumentException < / code > 。
 * @ param other 作为加数的货币对象 。
 * @ return 相加后的结果 。
 * @ throws IllegalArgumentException 如果本货币对象与另一货币对象币种不同 。 */
public MoneyKit add ( MoneyKit other ) { } }

implementation: assertSameCurrencyAs ( other ) ; return newMoneyWithSameCurrency ( cent + other . cent ) ;


signature:
public class MoneyKit { /** * 货币减法 。 < p / > < p / > 如果两货币币种相同 , 则返回一个新的相同币种的货币对象 , 其金额为 本货币对象的金额减去参数货币对象的金额 。 本货币对象的值不变 。
 * 如果两货币币种不同 , 抛出 < code > java . lang . IllegalArgumentException < / code > 。
 * @ param other 作为减数的货币对象 。
 * @ return 相减后的结果 。
 * @ throws IllegalArgumentException 如果本货币对象与另一货币对象币种不同 。 */
public MoneyKit subtract ( MoneyKit other ) { } }

implementation: assertSameCurrencyAs ( other ) ; return newMoneyWithSameCurrency ( cent - other . cent ) ;


signature:
public class MoneyKit { /** * 货币乘法 。 < p / > < p / > 返回一个新的货币对象 , 币种与本货币对象相同 , 金额为本货币对象的金额乘以乘数 。 本货币对象的值不变 。 如果相乘后的金额不能转换为整数分 , 使用指定的取整方式
 * < code > roundingMode < / code > 进行取整 。
 * @ param val 乘数
 * @ param roundingMode 取整方式
 * @ return 相乘后的结果 。 */
public MoneyKit multiply ( BigDecimal val , int roundingMode ) { } }

implementation: BigDecimal newCent = BigDecimal . valueOf ( cent ) . multiply ( val ) ; return newMoneyWithSameCurrency ( rounding ( newCent , roundingMode ) ) ;


signature:
public class MoneyKit { /** * 货币除法 。 < p / > < p / > 返回一个新的货币对象 , 币种与本货币对象相同 , 金额为本货币对象的金额除以除数 。 本货币对象的值不变 。 如果相除后的金额不能转换为整数分 , 使用指定的取整模式
 * < code > roundingMode < / code > 进行取整 。
 * @ param val 除数
 * @ param roundingMode 取整
 * @ return 相除后的结果 。 */
public MoneyKit divide ( BigDecimal val , int roundingMode ) { } }

implementation: BigDecimal newCent = BigDecimal . valueOf ( cent ) . divide ( val , roundingMode ) ; return newMoneyWithSameCurrency ( newCent . longValue ( ) ) ;


signature:
public class MoneyKit { /** * 货币分配 。 < p / > < p / > 将本货币对象尽可能平均分配成 < code > targets < / code > 份 。 如果不能平均分配尽 , 则将零头放到开始的若干份中 。 分配
 * 运算能够确保不会丢失金额零头 。
 * @ param targets 待分配的份数
 * @ return 货币对象数组 , 数组的长度与分配份数相同 , 数组元素 从大到小排列 , 所有货币对象的金额最多只相差1分 。 */
public MoneyKit [ ] allocate ( int targets ) { } }

implementation: MoneyKit [ ] results = new MoneyKit [ targets ] ; MoneyKit lowResult = newMoneyWithSameCurrency ( cent / targets ) ; MoneyKit highResult = newMoneyWithSameCurrency ( lowResult . cent + 1 ) ; int remainder = ( int ) cent % targets ; for ( int i = 0 ; i < remainder ; i ++ ) { results [ i ] = highResult ; } for ( int i = remainder ; i < targets ; i ++ ) { results [ i ] = lowResult ; } return results ;


signature:
public class MoneyKit { /** * 货币分配 。 < p / > < p / > 将本货币对象按照规定的比例分配成若干份 。 分配所剩的零头 从第一份开始顺序分配 。 分配运算确保不会丢失金额零头 。
 * @ param ratios 分配比例数组 , 每一个比例是一个长整型 , 代表 相对于总数的相对数 。
 * @ return 货币对象数组 , 数组的长度与分配比例数组的长度相同 。 */
public MoneyKit [ ] allocate ( long [ ] ratios ) { } }

implementation: MoneyKit [ ] results = new MoneyKit [ ratios . length ] ; long total = 0 ; for ( long ratio : ratios ) { total += ratio ; } long remainder = cent ; for ( int i = 0 ; i < results . length ; i ++ ) { results [ i ] = newMoneyWithSameCurrency ( ( cent * ratios [ i ] ) / total ) ; remainder -= results [ i ] . cent ; } for ( int i = 0 ; i < remainder ; i ++ ) { results [ i ] . cent ++ ; } return results ;


signature:
public class MoneyKit { /** * 创建一个币种相同 , 具有指定金额的货币对象 。
 * @ param cent 金额 , 以分为单位
 * @ return 一个新建的币种相同 , 具有指定金额的货币对象 */
protected MoneyKit newMoneyWithSameCurrency ( long cent ) { } }

implementation: MoneyKit money = new MoneyKit ( 0 , currency ) ; money . cent = cent ; return money ;


signature:
public class SimpleAuthenticatorUtil { /** * Creates a handler for jetty server with the given list of users .
 * The list of users can be conveniently loaded by using the other method in
 * this utility class : { @ link # loadUsers ( PropertySource , String ) } .
 * @ param users List of user entries
 * @ return Jetty security handler */
public static SecurityHandler newSecurityHandler ( List < SimpleServiceUser > users ) { } }

implementation: final HashLoginService loginService = new HashLoginService ( ) ; final Set < String > roles = new HashSet < > ( ) ; for ( final SimpleServiceUser user : users ) { final List < String > authorities = user . getAuthorities ( ) ; loginService . putUser ( user . getUsername ( ) , Credential . getCredential ( user . getPassword ( ) ) , authorities . toArray ( new String [ authorities . size ( ) ] ) ) ; roles . addAll ( authorities ) ; } loginService . setName ( DEFAULT_REALM ) ; final Constraint constraint = new Constraint ( ) ; constraint . setName ( Constraint . __BASIC_AUTH ) ; constraint . setRoles ( roles . toArray ( new String [ roles . size ( ) ] ) ) ; constraint . setAuthenticate ( true ) ; final ConstraintMapping constraintMapping = new ConstraintMapping ( ) ; constraintMapping . setConstraint ( constraint ) ; constraintMapping . setPathSpec ( "/*" ) ; final ConstraintSecurityHandler csh = new ConstraintSecurityHandler ( ) ; csh . setAuthenticator ( new BasicAuthenticator ( ) ) ; csh . setRealmName ( DEFAULT_REALM_NAME ) ; csh . addConstraintMapping ( constraintMapping ) ; csh . setLoginService ( loginService ) ; return csh ;


signature:
public class SimpleAuthenticatorUtil { /** * Loads user records from a given reader .
 * The text stream produced by reader should contain records in java properties format ( see also { @ link Properties } ) .
 * Each property related to authorization entries should be prefixed . This prefix should be passed as
 * a second parameter to this method , { @ code authPropertiesPrefix } .
 * Example of property file :
 * < code >
 * myService . auth . 1 . username = alice
 * myService . auth . 1 . password = test
 * myService . auth . 1 . roles = USER , ADMIN
 * myService . auth . 1 . username = bob
 * myService . auth . 1 . password = password
 * < / code >
 * Sample call that would read { @ code alice } and { @ code bob } user entries from a sample property file given above :
 * < code >
 * users = loadUsers ( propertySource , " myService . auth " ) ;
 * < / code >
 * Note : if { @ code . roles } property entry is missing for a user , the default value will be used , which is a list
 * of single element which is { @ code USER } .
 * See also { @ link SimpleServiceUser } .
 * @ param propertySource Property source , to read auth properties from
 * @ param authPropertiesPrefix Prefix for properties in a given reader , that should be treated as user record entries
 * @ return List of the parsed user entries */
public static List < SimpleServiceUser > loadUsers ( PropertySource < ? > propertySource , String authPropertiesPrefix ) { } }

implementation: if ( propertySource instanceof EnumerablePropertySource ) { final EnumerablePropertySource < ? > enumPropSource = ( EnumerablePropertySource ) propertySource ; final String [ ] propertyNames = enumPropSource . getPropertyNames ( ) ; final PropertyEntrySink sink = new PropertyEntrySink ( authPropertiesPrefix ) ; for ( final String propertyName : propertyNames ) { final Object value = propertySource . getProperty ( propertyName ) ; if ( value instanceof String ) { sink . putEntry ( propertyName , value . toString ( ) ) ; } } return sink . getUserList ( ) ; } LoggerFactory . getLogger ( SimpleAuthenticatorUtil . class ) . warn ( "propertySource={} is not of type EnumerablePropertySource" , propertySource ) ; return Collections . emptyList ( ) ;


signature:
public class XML { /** * Serialize to XML String
 * @ param document The DOM document
 * @ return The XML String */
public static String serialize ( Document document ) { } }

implementation: StringWriter writer = new StringWriter ( ) ; try { TransformerFactory factory = TransformerFactory . newInstance ( ) ; Transformer transformer = factory . newTransformer ( ) ; DOMSource domSource = new DOMSource ( document ) ; StreamResult streamResult = new StreamResult ( writer ) ; transformer . transform ( domSource , streamResult ) ; } catch ( TransformerException e ) { throw new RuntimeException ( "Error when serializing XML document." , e ) ; } return writer . toString ( ) ;


signature:
public class XML { /** * Parse an XML file to DOM
 * @ return null if an error occurs during parsing . */
public static Document getDocument ( File file ) { } }

implementation: try { return newDocumentBuilder ( ) . parse ( file ) ; } catch ( SAXException e ) { logger . warn ( "Parsing error when building Document object from xml file '" + file + "'." , e ) ; } catch ( IOException e ) { logger . warn ( "Reading error when building Document object from xml file '" + file + "'." , e ) ; } return null ;


signature:
public class XML { /** * Parse an XML string content to DOM
 * @ return null if an error occurs during parsing . */
public static Document getDocument ( String xml ) { } }

implementation: InputSource source = new InputSource ( new StringReader ( xml ) ) ; try { return newDocumentBuilder ( ) . parse ( source ) ; } catch ( SAXException e ) { logger . warn ( "Parsing error when building Document object from xml data." , e ) ; } catch ( IOException e ) { logger . warn ( "Reading error when building Document object from xml data." , e ) ; } return null ;


signature:
public class XML { /** * Parse an XML coming from an input stream to DOM
 * @ return null if an error occurs during parsing . */
public static Document getDocument ( InputStream stream ) { } }

implementation: try { return newDocumentBuilder ( ) . parse ( stream ) ; } catch ( SAXException e ) { logger . warn ( "Parsing error when building Document object from xml data." , e ) ; } catch ( IOException e ) { logger . warn ( "Reading error when building Document object from xml data." , e ) ; } return null ;


signature:
public class XML { /** * Check the xmldsig signature of the XML document .
 * @ param document the document to test
 * @ param publicKey the public key corresponding to the key pair the document was signed with
 * @ return true if a correct signature is present , false otherwise */
public static boolean validSignature ( Document document , Key publicKey ) { } }

implementation: Node signatureNode = document . getElementsByTagNameNS ( XMLSignature . XMLNS , "Signature" ) . item ( 0 ) ; KeySelector keySelector = KeySelector . singletonKeySelector ( publicKey ) ; try { String providerName = System . getProperty ( "jsr105Provider" , "org.jcp.xml.dsig.internal.dom.XMLDSigRI" ) ; XMLSignatureFactory fac = XMLSignatureFactory . getInstance ( "DOM" , ( Provider ) Class . forName ( providerName ) . newInstance ( ) ) ; DOMValidateContext valContext = new DOMValidateContext ( keySelector , signatureNode ) ; XMLSignature signature = fac . unmarshalXMLSignature ( valContext ) ; return signature . validate ( valContext ) ; } catch ( Exception e ) { logger . warn ( "Error validating an XML signature." , e ) ; return false ; }


signature:
public class XML { /** * Sign the XML document using xmldsig .
 * @ param document the document to sign ; it will be modified by the method .
 * @ param publicKey the public key from the key pair to sign the document .
 * @ param privateKey the private key from the key pair to sign the document .
 * @ return the signed document for chaining . */
public static Document sign ( Document document , RSAPublicKey publicKey , RSAPrivateKey privateKey ) { } }

implementation: XMLSignatureFactory fac = XMLSignatureFactory . getInstance ( "DOM" ) ; KeyInfoFactory keyInfoFactory = fac . getKeyInfoFactory ( ) ; try { Reference ref = fac . newReference ( "" , fac . newDigestMethod ( DigestMethod . SHA1 , null ) , Collections . singletonList ( fac . newTransform ( Transform . ENVELOPED , ( TransformParameterSpec ) null ) ) , null , null ) ; SignedInfo si = fac . newSignedInfo ( fac . newCanonicalizationMethod ( CanonicalizationMethod . INCLUSIVE , ( C14NMethodParameterSpec ) null ) , fac . newSignatureMethod ( SignatureMethod . RSA_SHA1 , null ) , Collections . singletonList ( ref ) ) ; DOMSignContext dsc = new DOMSignContext ( privateKey , document . getDocumentElement ( ) ) ; KeyValue keyValue = keyInfoFactory . newKeyValue ( publicKey ) ; KeyInfo ki = keyInfoFactory . newKeyInfo ( Collections . singletonList ( keyValue ) ) ; XMLSignature signature = fac . newXMLSignature ( si , ki ) ; signature . sign ( dsc ) ; } catch ( Exception e ) { logger . warn ( "Error while signing an XML document." , e ) ; } return document ;


signature:
public class ClassKit { /** * Return the default ClassLoader to use : typically the thread context
 * ClassLoader , if available ; the ClassLoader that loaded the ClassUtils
 * class will be used as fallback .
 * < p > Call this method if you intend to use the thread context ClassLoader
 * in a scenario where you clearly prefer a non - null ClassLoader reference :
 * for example , for class path resource loading ( but not necessarily for
 * { @ code Class . forName } , which accepts a { @ code null } ClassLoader
 * reference as well ) .
 * @ return the default ClassLoader ( only { @ code null } if even the system
 * ClassLoader isn ' t accessible )
 * @ see Thread # getContextClassLoader ( )
 * @ see ClassLoader # getSystemClassLoader ( ) */
public static ClassLoader getDefaultClassLoader ( ) { } }

implementation:
ClassLoader cl = null ; try { cl = Thread . currentThread ( ) . getContextClassLoader ( ) ; } catch ( Throwable ex ) { // Cannot access thread context ClassLoader - falling back . . .
} if ( cl == null ) { // No thread context class loader - > use class loader of this class .
cl = ClassKit . class . getClassLoader ( ) ; if ( cl == null ) { // getClassLoader ( ) returning null indicates the bootstrap ClassLoader
try { cl = ClassLoader . getSystemClassLoader ( ) ; } catch ( Throwable ex ) { // Cannot access system ClassLoader - oh well , maybe the caller can live with null . . .
} } } return cl ;


signature:
public class ClassKit { /** * Replacement for { @ code Class . forName ( ) } that also returns Class instances
 * for primitives ( e . g . " int " ) and array class names ( e . g . " String [ ] " ) .
 * Furthermore , it is also capable of resolving inner class names in Java source
 * style ( e . g . " java . lang . Thread . State " instead of " java . lang . Thread $ State " ) .
 * @ param name the name of the Class
 * @ param classLoader the class loader to use
 * ( may be { @ code null } , which indicates the default class loader )
 * @ return Class instance for the supplied name
 * @ throws ClassNotFoundException if the class was not found
 * @ throws LinkageError if the class file could not be loaded
 * @ see Class # forName ( String , boolean , ClassLoader ) */
public static Class < ? > forName ( String name , ClassLoader classLoader ) throws ClassNotFoundException , LinkageError { } }

implementation:
Preconditions . checkNotNull ( name , "Name must not be null" ) ; Class < ? > clazz = resolvePrimitiveClassName ( name ) ; if ( clazz == null ) { clazz = commonClassCache . get ( name ) ; } if ( clazz != null ) { return clazz ; } // " java . lang . String [ ] " style arrays
if ( name . endsWith ( ARRAY_SUFFIX ) ) { String elementClassName = name . substring ( 0 , name . length ( ) - ARRAY_SUFFIX . length ( ) ) ; Class < ? > elementClass = forName ( elementClassName , classLoader ) ; return Array . newInstance ( elementClass , 0 ) . getClass ( ) ; } // " [ Ljava . lang . String ; " style arrays
if ( name . startsWith ( NON_PRIMITIVE_ARRAY_PREFIX ) && name . endsWith ( ";" ) ) { String elementName = name . substring ( NON_PRIMITIVE_ARRAY_PREFIX . length ( ) , name . length ( ) - 1 ) ; Class < ? > elementClass = forName ( elementName , classLoader ) ; return Array . newInstance ( elementClass , 0 ) . getClass ( ) ; } // " [ [ I " or " [ [ Ljava . lang . String ; " style arrays
if ( name . startsWith ( INTERNAL_ARRAY_PREFIX ) ) { String elementName = name . substring ( INTERNAL_ARRAY_PREFIX . length ( ) ) ; Class < ? > elementClass = forName ( elementName , classLoader ) ; return Array . newInstance ( elementClass , 0 ) . getClass ( ) ; } ClassLoader clToUse = classLoader ; if ( clToUse == null ) { clToUse = getDefaultClassLoader ( ) ; } try { return ( clToUse != null ? clToUse . loadClass ( name ) : Class . forName ( name ) ) ; } catch ( ClassNotFoundException ex ) { int lastDotIndex = name . lastIndexOf ( PACKAGE_SEPARATOR ) ; if ( lastDotIndex != - 1 ) { String innerClassName = name . substring ( 0 , lastDotIndex ) + INNER_CLASS_SEPARATOR + name . substring ( lastDotIndex + 1 ) ; try { return ( clToUse != null ? clToUse . loadClass ( innerClassName ) : Class . forName ( innerClassName ) ) ; } catch ( ClassNotFoundException ex2 ) { // Swallow - let original exception get through
} } throw ex ; }


signature:
public class ClassKit { /** * Return the user - defined class for the given instance : usually simply
 * the class of the given instance , but the original class in case of a
 * CGLIB - generated subclass .
 * @ param instance the instance to check
 * @ return the user - defined class */
public static Class < ? > getUserClass ( Object instance ) { } }

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


signature:
public class ClassKit { /** * Check whether the given class is cache - safe in the given context ,
 * i . e . whether it is loaded by the given ClassLoader or a parent of it .
 * @ param clazz the class to analyze
 * @ param classLoader the ClassLoader to potentially cache metadata in */
public static boolean isCacheSafe ( Class < ? > clazz , ClassLoader classLoader ) { } }

implementation:
Preconditions . checkNotNull ( clazz , "Class must not be null" ) ; try { ClassLoader target = clazz . getClassLoader ( ) ; if ( target == null ) { return true ; } ClassLoader cur = classLoader ; if ( cur == target ) { return true ; } while ( cur != null ) { cur = cur . getParent ( ) ; if ( cur == target ) { return true ; } } return false ; } catch ( SecurityException ex ) { // Probably from the system ClassLoader - let ' s consider it safe .
return true ; }


signature:
public class ClassKit { /** * Determine the name of the class file , relative to the containing
 * package : e . g . " String . class "
 * @ param clazz the class
 * @ return the file name of the " . class " file */
public static String getClassFileName ( Class < ? > clazz ) { } }

implementation: Preconditions . checkNotNull ( clazz , "Class must not be null" ) ; String className = clazz . getName ( ) ; int lastDotIndex = className . lastIndexOf ( PACKAGE_SEPARATOR ) ; return className . substring ( lastDotIndex + 1 ) + CLASS_FILE_SUFFIX ;


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

implementation: Preconditions . checkNotNull ( clazz , "Class must not be null" ) ; return getPackageName ( clazz . getName ( ) ) ;