signature:
public class OneWayMessageDigestCodec { /** * This creates a well known instance . . the difference with the constructor
 * is that all exceptions are caught and rethrown as RuntimeExcpetion
 * because they should not happen .
 * @ param algorithm
 * @ param password
 * @ param codec
 * @ return the codec */
private static OneWayMessageDigestCodec createWellKnownInstance ( String algorithm , String password , OneWayCodec codec ) { } }

implementation: try { return new OneWayMessageDigestCodec ( algorithm , password , codec ) ; } catch ( NoSuchAlgorithmException e ) { throw new RuntimeException ( e ) ; } catch ( CloneNotSupportedException e ) { throw new RuntimeException ( e ) ; }


signature:
public class RAMResourceProvider { /** * If the path denotes a directory , then it will return all resources that are contained in the
 * directory .
 * @ param path the path to the resource
 * @ param filter the filter to include only some resources in the result
 * @ return < code > true < / code > if it was a directory , < code > false < / code > otherwise
 * @ throws IOException if there is an error accessing the resource */
@ Override public boolean doList ( String path , ResourceFilter filter ) { } }

implementation: if ( _root == null ) return false ; RAMEntry entry = _root . getEntryByPath ( path ) ; if ( entry instanceof RAMDirectory ) { RAMDirectory ramDirectory = ( RAMDirectory ) entry ; for ( RAMEntry ramEntry : ramDirectory . ls ( ) ) { String resourcePath = PathUtils . addPaths ( path , ramEntry . name ( ) ) ; filter . accept ( new RAMResource ( this , getFullPath ( resourcePath ) , resourcePath ) ) ; } return true ; } else return false ;


signature:
public class URLBuilder { /** * Appends the given path . The path is conditionaly escaped .
 * After this call , < code > newpath = oldpath + / + path < / code > .
 * As a consequence , this method cannot be used to set a relative path .
 * @ param path the path to append
 * @ param encodePath < code > true < / code > to encode the path */
public void appendPath ( String path , boolean encodePath ) { } }

implementation: if ( path == null ) return ; if ( encodePath ) path = urlEncode ( path ) ; if ( path . startsWith ( "/" ) ) path = path . substring ( 1 ) ; if ( _path == null || "" . equals ( _path ) ) { StringBuilder sb = new StringBuilder ( "/" ) ; sb . append ( path ) ; _path = sb . toString ( ) ; } else { StringBuilder sb = new StringBuilder ( _path ) ; if ( _path . endsWith ( "/" ) ) sb . append ( path ) ; else sb . append ( '/' ) . append ( path ) ; _path = sb . toString ( ) ; }


signature:
public class URLBuilder { /** * Adds the query parameter
 * @ param name
 * @ param value
 * @ return this object for chaining */
public URLBuilder addQueryParameter ( String name , String value ) { } }

implementation: if ( value == null ) throw new IllegalArgumentException ( "value is null for " + name ) ; _query . addParameter ( name , value ) ; return this ;


signature:
public class URLBuilder { /** * Adds the query parameter
 * @ param name
 * @ param values
 * @ return this object for chaining */
public URLBuilder addQueryParameter ( String name , int [ ] values ) { } }

implementation: String [ ] params = new String [ values . length ] ; int idx = 0 ; if ( values . length > 0 ) { for ( int value : values ) { params [ idx ++ ] = String . valueOf ( value ) ; } _query . addParameters ( name , params ) ; } return this ;


signature:
public class URLBuilder { /** * Adds the query parameter
 * @ param name
 * @ param values
 * @ return this object for chaining */
public URLBuilder addQueryParameter ( String name , String [ ] values ) { } }

implementation: if ( values != null && values . length > 0 ) { _query . addParameters ( name , values ) ; } return this ;


signature:
public class URLBuilder { /** * Remove parameter with given name and
 * return its previous value .
 * @ param name parameter to remove
 * @ return previous value or null if parameter doesn ' t exist */
public String [ ] replaceQueryParameter ( String name , String value ) { } }

implementation: return _query . replaceParameter ( name , value ) ;


signature:
public class URLBuilder { /** * Call this method when you want to reset the internal string to start
 * from scratch again */
public void reset ( ) { } }

implementation: _scheme = null ; _userInfo = null ; _host = null ; _port = - 1 ; _path = null ; _query = new QueryBuilder ( ) ; _fragment = null ; _escapeFragment = true ;


signature:
public class URLBuilder { /** * Encapsulates the call to encoding a URL
 * @ param original the string to encode
 * @ param encoding the encoding to use
 * @ return the encoded url */
public static String urlEncode ( String original , String encoding ) throws UnsupportedEncodingException { } }

implementation: return new URLCodec ( true , encoding ) . urlEncode ( original ) ;


signature:
public class URLBuilder { /** * Encapsulates the call to decoding a URL so that we don ' t have to deal
 * with the encoding .
 * @ param original the string to decode
 * @ param encoding the encoding to use
 * @ return the encoded url */
public static String urlDecode ( String original , String encoding ) throws UnsupportedEncodingException { } }

implementation: return new URLCodec ( true , encoding ) . urlDecode ( original ) ;


signature:
public class URLBuilder { /** * Factory method from a path
 * @ param path the path ( will be url encoded ! )
 * @ return the builder */
public static URLBuilder createFromPath ( String path ) { } }

implementation: URLBuilder res = new URLBuilder ( ) ; res . setPath ( path ) ; return res ;


signature:
public class URLBuilder { /** * Factory method from a url
 * @ param url the url
 * @ return the builder
 * @ throws URISyntaxException if the url is invalid */
public static URLBuilder createFromURL ( String url ) throws URISyntaxException { } }

implementation:
if ( url == null ) { return null ; } else { url = url . trim ( ) ; } URI uri = new URI ( url ) ; if ( uri . isOpaque ( ) ) throw new URISyntaxException ( url , "opaque uris not supported" ) ; URLBuilder res = new URLBuilder ( ) ; res . setScheme ( uri . getScheme ( ) ) ; res . setUserInfo ( uri . getUserInfo ( ) ) ; // CA - 1599 - - Java ' s URI fails to parse the hostname if it has underscores in it .
// this is because _ is not a valid char in hostnames , yet there are systems out there
// that have it . Java ' s URL , however , handles it fine .
if ( uri . getHost ( ) == null && res . getHasScheme ( ) ) { try { java . net . URL u = new java . net . URL ( url ) ; res . setHost ( u . getHost ( ) ) ; res . setPort ( u . getPort ( ) ) ; } catch ( java . net . MalformedURLException e ) { URISyntaxException uex = new URISyntaxException ( url , e . getMessage ( ) ) ; uex . initCause ( e ) ; // keep the original exception
throw uex ; } } else { res . setHost ( uri . getHost ( ) ) ; res . setPort ( uri . getPort ( ) ) ; } res . setPath ( uri . getRawPath ( ) ) ; res . setFragment ( uri . getFragment ( ) ) ; res . addQuery ( uri ) ; return res ;


signature:
public class URLBuilder { /** * Factory method from a url
 * @ param url the url
 * @ return the builder */
public static URLBuilder createFromURL ( URL url ) { } }

implementation:
if ( url == null ) return null ; // fast implementation
if ( url instanceof URLBuilder ) { URLBuilder urlBuilder = ( URLBuilder ) url ; return urlBuilder . deepClone ( ) ; } try { return createFromURL ( url . getURL ( ) ) ; } catch ( URISyntaxException e ) { throw new RuntimeException ( "bad url!" + url . getURL ( ) ) ; }


signature:
public class URLBuilder { /** * Convenient call which adds a query parameter to the give url .
 * @ param url the original URL : will stay unchanged
 * @ param name the name of the query parameter
 * @ param value the value of the query parameter
 * @ return the new URL */
public static URL addQueryParameter ( URL url , String name , String value ) { } }

implementation: URLBuilder ub = createFromURL ( url ) ; ub . addQueryParameter ( name , value ) ; return ub ;


signature:
public class URLBuilder { /** * Returns an array of the ' / ' delimited components for a URL path , starting
 * just after the servlet path . For example , if requestURI is leo / a / b / c / d /
 * and servletPath is / a , then the array returned will be { b , c , d } . The path
 * components are returned decoded ( not htmlified )
 * @ param requestURI request URI ( obtained via request . getRequestURI ( ) )
 * @ param servletPath servlet path ( obtained via request . getServletPath ( ) )
 * @ return an array of the components in the URI , starting just after the
 * specified servletPath . */
public static String [ ] getPathComponents ( String requestURI , String servletPath ) { } }

implementation: ArrayList < String > tokens = new ArrayList < String > ( ) ; if ( requestURI != null && servletPath != null && servletPath . length ( ) > 0 ) { int servletPathStartPos = requestURI . indexOf ( servletPath ) ; if ( servletPathStartPos != - 1 ) { String components = requestURI . substring ( servletPathStartPos + servletPath . length ( ) ) ; StringTokenizer st = new StringTokenizer ( components , "/" ) ; while ( st . hasMoreTokens ( ) ) { tokens . add ( urlDecode ( st . nextToken ( ) ) ) ; } } } return tokens . toArray ( new String [ tokens . size ( ) ] ) ;


signature:
public class URIResourceFactoryImpl { /** * Based on the URI returns the right resource
 * @ param uri
 * @ return the resource
 * @ throws UnsupportedURIException if the uri is not supported by this factory */
@ Override public Resource createResource ( URI uri ) throws UnsupportedURIException { } }

implementation: if ( uri . getScheme ( ) == null ) return FileResource . createFromRoot ( new File ( uri . getPath ( ) ) ) ; SchemeURIResourceFactory factory = _factories . get ( uri . getScheme ( ) ) ; if ( factory == null ) throw new UnsupportedURIException ( "unsupported scheme " + uri . getScheme ( ) ) ; return factory . createResource ( uri , this ) ;


signature:
public class QueryBuilder { /** * Get the first parameter given its name
 * @ param name the name of the parameter
 * @ return the first parameter */
@ Override public String getParameter ( String name ) { } }

implementation: String [ ] params = getParameterValues ( name ) ; if ( params == null ) return null ; return params [ 0 ] ;


signature:
public class QueryBuilder { /** * Add query parameter to query string .
 * @ param name
 * @ param value */
private void addQueryParameter ( String name , String value ) { } }

implementation: if ( _query . length ( ) > 0 ) _query . append ( '&' ) ; _query . append ( encode ( name ) ) ; _query . append ( '=' ) ; _query . append ( encode ( value ) ) ;


signature:
public class QueryBuilder { /** * Adds the query parameter
 * @ param name
 * @ param value */
public void addParameter ( String name , String value ) { } }

implementation: addQueryParameter ( name , value ) ; if ( _queryParameters != null ) addParameterToMap ( name , value ) ;


signature:
public class QueryBuilder { /** * Adds the query parameter
 * @ param name
 * @ param value */
private void addParameterToMap ( String name , String value ) { } }

implementation: String [ ] params = getParameterValues ( name ) ; if ( params == null ) { params = new String [ 1 ] ; params [ 0 ] = value ; _queryParameters . put ( name , params ) ; } else { int len = params . length ; String [ ] newParams = new String [ len + 1 ] ; System . arraycopy ( params , 0 , newParams , 0 , len ) ; newParams [ len ] = value ; _queryParameters . put ( name , newParams ) ; }


signature:
public class QueryBuilder { /** * Adds the query parameter
 * @ param name
 * @ param values */
public void addParameters ( String name , String [ ] values ) { } }

implementation: if ( _query . length ( ) > 0 ) _query . append ( '&' ) ; String encodedName = encode ( name ) ; for ( int i = 0 ; i < values . length ; i ++ ) { if ( i > 0 ) _query . append ( '&' ) ; _query . append ( encodedName ) ; _query . append ( '=' ) ; _query . append ( encode ( values [ i ] ) ) ; } if ( _queryParameters != null ) addParametersToMap ( name , values ) ;


signature:
public class QueryBuilder { /** * Adds the map of parameters
 * @ param parameters */
public void addParameters ( Map < String , String [ ] > parameters ) { } }

implementation: for ( Map . Entry < String , String [ ] > entry : parameters . entrySet ( ) ) { addParameters ( entry . getKey ( ) , entry . getValue ( ) ) ; }


signature:
public class QueryBuilder { /** * Adds the query parameter
 * @ param name
 * @ param values */
private void addParametersToMap ( String name , String [ ] values ) { } }

implementation: String [ ] params = getParameterValues ( name ) ; if ( params == null ) { _queryParameters . put ( name , values ) ; } else { int len = params . length ; String [ ] newParams = new String [ len + values . length ] ; System . arraycopy ( params , 0 , newParams , 0 , len ) ; System . arraycopy ( values , 0 , newParams , len , values . length ) ; _queryParameters . put ( name , newParams ) ; }


signature:
public class QueryBuilder { /** * Adds a parameter that comes from an array at the provided index ( can have multiple dimensions ! )
 * @ param name the name of the parameter
 * @ param value the value
 * @ param indices the indices in the array ( multiple dimensions ) */
public void addIndexedParameter ( String name , String value , int ... indices ) { } }

implementation: addParameter ( getIndexedParamName ( name , indices ) , value ) ;


signature:
public class QueryBuilder { /** * Adds a parameter that comes from an array at the provided index
 * @ param name the name of the parameter
 * @ param value the value
 * @ param index the index in the array */
public void addIndexedParameter ( String name , int value , int index ) { } }

implementation: addParameter ( getIndexedParamName ( name , index ) , value ) ;


signature:
public class QueryBuilder { /** * Adds the query extracted from the URI . No Exception is thrown because the
 * uri could not be built if it was not correct .
 * @ param uri */
public void addQuery ( URI uri ) { } }

implementation:
try { addQuery ( uri . getRawQuery ( ) , false ) ; } catch ( URISyntaxException e ) { // should not happen !
throw new RuntimeException ( e ) ; }


signature:
public class QueryBuilder { /** * Simply adds the query provided . It is assumed that the query is properly
 * encoded for url !
 * @ param query the properly url encoded query ( < code > null < / code > is ok )
 * @ param validate < code > true < / code > true for validating ( should be called
 * with < code > false < / code > only when sure that it is valid . . ) */
private void addQuery ( String query , boolean validate ) throws URISyntaxException { } }

implementation: if ( query == null ) return ; if ( "" . equals ( query ) ) return ; if ( validate ) validateQuery ( query ) ; if ( _query . length ( ) > 0 ) _query . append ( '&' ) ; _query . append ( query ) ; if ( _queryParameters != null ) addQueryToMap ( query ) ;


signature:
public class QueryBuilder { /** * Internal method in charge of validating the query provided . Exception
 * when query is not valid .
 * @ param query the query to validate
 * @ throws URISyntaxException if query invalid */
private void validateQuery ( String query ) throws URISyntaxException { } }

implementation: if ( query . length ( ) == 0 ) return ; Iterator < String > iter = SS . splitToIterator ( query ) ; while ( iter . hasNext ( ) ) { String s = iter . next ( ) ; if ( s . length ( ) > 0 ) { int idx = s . indexOf ( '=' ) ; if ( idx == - 1 ) throw new URISyntaxException ( query , "missing equal sign in " + s ) ; if ( s . lastIndexOf ( '=' ) != idx ) throw new URISyntaxException ( query , "extra equal sign in " + s ) ; } }


signature:
public class QueryBuilder { /** * Simply adds the query provided . It is assumed that the query is properly
 * encoded for url !
 * @ param query the properly url encoded query */
private void addQueryToMap ( String query ) { } }

implementation: String [ ] params = SS . split ( query ) ; for ( int i = 0 ; i < params . length ; i ++ ) { String param = params [ i ] ; if ( param . length ( ) == 0 ) continue ; int idx = param . indexOf ( '=' ) ; if ( idx == - 1 ) addParameterToMap ( decode ( param ) , null ) ; else addParameterToMap ( decode ( param . substring ( 0 , idx ) ) , decode ( param . substring ( idx + 1 ) ) ) ; }


signature:
public class QueryBuilder { /** * Simply adds the query provided .
 * @ param query the query ( < code > null < / code > is ok ) */
public void addQuery ( Query query ) { } }

implementation:
if ( query == null ) return ; try { if ( ! query . getEncoding ( ) . equals ( getEncoding ( ) ) ) throw new RuntimeException ( "TODO" ) ; addQuery ( query . getQuery ( ) , false ) ; } catch ( URISyntaxException e ) { // shouldn ' t happen since a query is already properly formatted
throw new RuntimeException ( e ) ; }


signature:
public class QueryBuilder { /** * Internal call that will return the map . If < code > null < / code > then first
 * populate it
 * @ return the map */
private Map < String , String [ ] > getMap ( ) { } }

implementation: if ( _queryParameters != null ) return _queryParameters ; _queryParameters = new LinkedHashMap < String , String [ ] > ( ) ; addQueryToMap ( _query . toString ( ) ) ; return _queryParameters ;


signature:
public class QueryBuilder { /** * Returns the name of the param that represent an entry in an array . This is the method
 * used by < code > addIndexed * < / code > methods .
 * @ param paramPrefix the prefix for the param
 * @ param indices the indices in the array ( multiple dimensions )
 * @ return the name of the param that represent an entry in an array */
public static String getIndexedParamName ( String paramPrefix , int ... indices ) { } }

implementation: StringBuilder sb = new StringBuilder ( paramPrefix ) ; for ( int index : indices ) { sb . append ( '_' ) . append ( index ) ; } return sb . toString ( ) ;


signature:
public class QueryBuilder { /** * Rebuild query instance with values in the map . */
private void rebuildQuery ( ) { } }

implementation:
Map < String , String [ ] > map = getMap ( ) ; // reset query instance and re - populate it again
_query . setLength ( 0 ) ; for ( String key : map . keySet ( ) ) { String [ ] parameters = map . get ( key ) ; for ( String param : parameters ) { addQueryParameter ( key , param ) ; } }


signature:
public class QueryBuilder { /** * Remove parameter with given name and
 * return its previous value .
 * @ param parameterNames */
public void removeParameters ( String ... parameterNames ) { } }

implementation: Map < String , String [ ] > map = getMap ( ) ; boolean needsRebuild = false ; for ( String name : parameterNames ) { if ( map . remove ( name ) != null ) needsRebuild = true ; } if ( needsRebuild ) rebuildQuery ( ) ;


signature:
public class QueryBuilder { /** * Remove parameter with given name and
 * return its previous value .
 * @ param name parameter to remove
 * @ return previous value or null if parameter doesn ' t exist */
public String [ ] removeParameter ( String name ) { } }

implementation: Map < String , String [ ] > map = getMap ( ) ; String [ ] v = map . remove ( name ) ; if ( v != null ) rebuildQuery ( ) ; return v ;


signature:
public class QueryBuilder { /** * Replace existing or add new parameter with given
 * value . Any existing parameter values are
 * deleted prior to adding the new value .
 * @ param name parameter to replace
 * @ return previous values or null if parameter doesn ' t exist */
public String [ ] replaceParameter ( String name , String value ) { } }

implementation: Map < String , String [ ] > map = getMap ( ) ; String [ ] v = map . put ( name , new String [ ] { value } ) ; rebuildQuery ( ) ; return v ;


signature:
public class URLResourceProvider { /** * Creates a new resource provider given the new path .
 * @ param rootPath
 * @ return the new resource provider */
@ Override public InternalResourceProvider doCreateResourceProvider ( String rootPath ) { } }

implementation: try { return new URLResourceProvider ( _baseURL , getFullPath ( rootPath ) ) ; } catch ( UnsupportedURIException e ) { throw new RuntimeException ( e ) ; } catch ( URISyntaxException e ) { throw new RuntimeException ( e ) ; }


signature:
public class URLResourceProvider { /** * Builds a resource given a path . Only subclasses know how to do that .
 * @ param path the path to the new resource ( always starts with / )
 * @ return the resource */
@ Override public InternalResource doBuildResource ( String path ) { } }

implementation:
try { URI uri = _baseURL . toURI ( ) ; URI newURI = new URI ( uri . getScheme ( ) , uri . getUserInfo ( ) , uri . getHost ( ) , uri . getPort ( ) , getFullPath ( path ) , null , null ) ; return new URLResource ( this , path , newURI . toURL ( ) , _connectTimeout , _readTimeout ) ; } catch ( URISyntaxException e ) { // should not happen
throw new RuntimeException ( e ) ; } catch ( MalformedURLException e ) { // should not happen
throw new RuntimeException ( e ) ; }


signature:
public class JarResourceProvider { /** * Builds a resource given a path . Only subclasses know how to do that .
 * @ param path the path to the new resource ( always starts with / )
 * @ return the resource */
@ Override public InternalResource doBuildResource ( String path ) { } }

implementation: return new JarResource ( this , path , _jarResource , getFullPath ( path ) ) ;


signature:
public class JarResourceProvider { /** * If the path denotes a directory , then it will return all resources that are contained in the
 * directory .
 * @ param path the path to the resource ( it already ends with / )
 * @ param filter the filter to include only some resources in the result
 * @ return < code > true < / code > if it was a directory , < code > false < / code > otherwise */
@ Override public boolean doList ( String path , ResourceFilter filter ) { } }

implementation: try { JarFile jarFile = new JarFile ( _jarResource . getFile ( ) ) ; try { return doList ( path , filter , jarFile ) ; } finally { jarFile . close ( ) ; } } catch ( IOException e ) { if ( log . isDebugEnabled ( ) ) log . debug ( "exception (ignored) while listing path " + path , e ) ; return false ; }


signature:
public class ShutdownProxy { /** * Method from the interface . Checks for shutdown then dispatches the call
 * @ param o
 * @ param method
 * @ param objects
 * @ return object
 * @ throws Throwable */
@ Override public Object invoke ( Object o , Method method , Object [ ] objects ) throws Throwable { } }

implementation:
// throws ShutdownRequestedException when in shutdown mode
_shutdown . startCall ( ) ; try { return method . invoke ( _object , objects ) ; } catch ( InvocationTargetException e ) { Throwable th = e . getTargetException ( ) ; try { throw th ; } catch ( Exception ex ) { throw ex ; } catch ( Throwable throwable ) { log . error ( method . toString ( ) , throwable ) ; throw throwable ; } } finally { _shutdown . endCall ( ) ; }


signature:
public class ShutdownProxy { /** * Creates the proxy to check for shutdown . Uses all interfaces defined by
 * this object ( and recursively ) .
 * @ param o
 * @ param shutdown
 * @ return the proxy */
public static Object createShutdownProxy ( Object o , Shutdown shutdown ) { } }

implementation: return createShutdownProxy ( o , null , shutdown ) ;


signature:
public class ShutdownProxy { /** * Creates the proxy to check for shutdown .
 * @ param o
 * @ param interfaces restriction on which interface to apply the proxy on
 * @ param shutdown
 * @ return the proxy */
public static Object createShutdownProxy ( Object o , Class [ ] interfaces , Shutdown shutdown ) { } }

implementation: if ( interfaces == null ) interfaces = ReflectUtils . extractAllInterfaces ( o ) ; return Proxy . newProxyInstance ( o . getClass ( ) . getClassLoader ( ) , interfaces , new ShutdownProxy ( o , shutdown ) ) ;


signature:
public class LangUtils { /** * This method compares 2 dates . It is mainly written to account for a bug
 * in jdk15 which throws a ClassCastException when calling d1 . compareTo ( d2 ) .
 * It also adds handling of < code > null < / code > values .
 * @ param d1
 * @ param d2
 * @ return 0 if equal , & lt ; 0 if d1 & lt ; d2 and & gt ; 0 if d1 & gt ; d2 */
public static int compareTo ( Date d1 , Date d2 ) { } }

implementation:
if ( d1 == null ) { if ( d2 == null ) return 0 ; else return - 1 ; } if ( d2 == null ) { // here d1 is not null ( already tested . . )
return 1 ; } // here d1 and d2 are not null
long delta = d1 . getTime ( ) - d2 . getTime ( ) ; if ( delta > 0 ) { return 1 ; } else if ( delta < 0 ) { return - 1 ; } else { return 0 ; }


signature:
public class LangUtils { /** * Clone by serializing / deserializing . . . only works if the object is actually serializable ! */
@ SuppressWarnings ( "unchecked" ) public static < T extends Serializable > T deepClone ( T serializable , ClassLoader classLoader ) { } }

implementation: if ( serializable == null ) return null ; try { return ( T ) IOUtils . deserialize ( IOUtils . serialize ( serializable ) , classLoader ) ; } catch ( IOException e ) { throw new InternalException ( e ) ; } catch ( ClassNotFoundException e ) { throw new InternalException ( e ) ; }


signature:
public class LangUtils { /** * Converts the object into a boolean value .
 * @ param o the object to convert
 * @ return a < code > boolean < / code > */
public static boolean convertToBoolean ( Object o ) { } }

implementation: if ( o == null ) return false ; if ( o instanceof Boolean ) { return ( Boolean ) o ; } return convertToBoolean ( o . toString ( ) ) ;


signature:
public class LangUtils { /** * Converts the string into a boolean value . < code > true < / code > or
 * < code > yes < / code > are considered to be < code > true < / code > . < code > false < / code >
 * or < code > no < / code > are < code > false < / code > .
 * @ param s the string to convert
 * @ return a < code > boolean < / code > */
public static boolean convertToBoolean ( String s ) { } }

implementation:
if ( s == null ) return false ; if ( s . equals ( "false" ) || s . equals ( "no" ) || s . equals ( "off" ) ) return false ; // if ( s . equals ( " true " ) | | s . equals ( " yes " ) | | s . equals ( " on " ) )
// return true ;
return true ;


signature:
public class LangUtils { /** * Returns the stack trace of the throwable as a string
 * @ param th the throwable
 * @ return the stack trace as a string */
public static String getStackTrace ( Throwable th ) { } }

implementation: StringWriter sw = new StringWriter ( ) ; PrintWriter pw = new PrintWriter ( sw ) ; th . printStackTrace ( pw ) ; return sw . toString ( ) ;


signature:
public class PathUtils { /** * Adds 2 paths taking into consideration the /
 * @ param path1
 * @ param path2
 * @ return path1 + path2 */
public static String addPaths ( String path1 , String path2 ) { } }

implementation: if ( path1 . endsWith ( "/" ) ) { if ( path2 . startsWith ( "/" ) ) return path1 . substring ( 0 , path1 . length ( ) - 1 ) + path2 ; else return path1 + path2 ; } else { if ( path2 . startsWith ( "/" ) ) return path1 + path2 ; else return path1 + "/" + path2 ; }


signature:
public class PathUtils { /** * Removes a trailing slash if exists
 * @ param path
 * @ return the path without a trailing / */
public static String removeTrailingSlash ( String path ) { } }

implementation: if ( path . endsWith ( "/" ) ) return path . substring ( 0 , path . length ( ) - 1 ) ; else return path ;


signature:
public class StringSplitter { /** * Splits the string into an array of strings using the delimiter
 * provided in the constructor .
 * @ param s the string to split
 * @ return the splitted string ( < code > null < / code > if < code > s < / code > is
 * < code > null < / code > ) */
public String [ ] split ( String s ) { } }

implementation: List < String > ss = splitAsList ( s ) ; if ( ss == null ) return null ; return ss . toArray ( new String [ ss . size ( ) ] ) ;


signature:
public class StringSplitter { /** * Splits the string into an array of strings using the delimiter
 * provided in the constructor .
 * @ param s the string to split
 * @ return the splitted string ( < code > null < / code > if < code > s < / code > is
 * < code > null < / code > ) */
public List < String > splitAsList ( String s ) { } }

implementation: if ( s == null ) return null ; int len = s . length ( ) ; if ( len == 0 ) { return Collections . emptyList ( ) ; } if ( _blockIgnore == null ) return splitNoBlockIgnore ( s ) ; else return splitBlockIgnore ( s ) ;


signature:
public class NullResourceProvider { /** * Builds a resource given a path . Only subclasses know how to do that .
 * @ param path the path to the new resource ( always starts with / )
 * @ return the resource */
@ Override public InternalResource doBuildResource ( String path ) { } }

implementation: return new NullResource ( this , normalizePath ( path ) , normalizePath ( getFullPath ( path ) ) ) ;


signature:
public class NullResourceProvider { /** * The path never represents a directory = > should not end with / */
private static String normalizePath ( String path ) { } }

implementation: path = PathUtils . removeTrailingSlash ( path ) ; path = PathUtils . addLeadingSlash ( path ) ; return path ;


signature:
public class SchemeURIResourceFactory { /** * Based on the URI returns the right resource
 * @ param uri
 * @ return the resource */
public Resource createResource ( URI uri , URIResourceFactory parent ) { } }

implementation: if ( ! getScheme ( ) . equals ( uri . getScheme ( ) ) ) throw new IllegalArgumentException ( "cannot handle: " + uri . getScheme ( ) ) ; return doCreateResource ( uri , parent ) ;


signature:
public class Shutdown { /** * Waits for shutdown to be completed . After calling shutdown , there may still be some pending work
 * that needs to be accomplised . This method will block until it is done but no longer than the
 * timeout .
 * @ param timeout how long to wait maximum for the shutdown
 * @ throws InterruptedException if interrupted while waiting
 * @ throws IllegalStateException if shutdown has not been called
 * @ throws TimeoutException if shutdown still not complete after timeout */
@ Override public void waitForShutdown ( Object timeout ) throws InterruptedException , IllegalStateException , TimeoutException { } }

implementation: if ( ! _shutdown ) throw new IllegalStateException ( "call shutdown first" ) ; pendingCallsCount . waitForCounter ( timeout ) ;


signature:
public class XML { /** * Adds the XML declaration ( < code > & lt ; ? xml version = " 1.0 " ? & gt ; < / code > )
 * @ param xml which buffer to append to
 * @ param versionInfo the version info */
static void addXMLDecl ( StringBuilder xml , String versionInfo ) { } }

implementation: xml . append ( "<?xml version=\"" ) . append ( versionInfo ) . append ( "\"?>\n" ) ;


signature:
public class XML { /** * Adds the XML declaration ( < code > & lt ; ? xml version = " 1.0 " encoding = " UTF - 8"
 * standalone = " yes " ? & gt ; < / code > )
 * @ param versionInfo the version info
 * @ param encoding the encoding ( eg : UTF - 8)
 * @ param standalone < code > true < / code > for standalone */
@ Override public void addXMLDecl ( String versionInfo , String encoding , boolean standalone ) { } }

implementation: _xml . append ( "<?xml version=\"" ) . append ( versionInfo ) ; _xml . append ( "\" encoding=\"" ) ; _xml . append ( encoding ) . append ( "\" standalone=\"" ) ; _xml . append ( standalone ? "yes" : "no" ) ; _xml . append ( "\"?>\n" ) ;


signature:
public class XML { /** * Adds a tag
 * @ param tagName the name of the tag to add
 * @ param tagValue the value of the tag to add */
@ Override public void addTag ( String tagName , String tagValue ) { } }

implementation: if ( tagValue == null ) addEmptyTag ( tagName ) ; else { addOpeningTag ( tagName ) ; _xml . append ( XMLUtils . xmlEncode ( tagValue ) ) ; addClosingTag ( tagName ) ; }


signature:
public class XML { /** * Adds an empty tag which contains the attributes specified . All the
 * properties will be turned into attributes .
 * @ param tagName the name of the empty tag to add
 * @ param attributes the attributes */
@ Override public void addEmptyTag ( String tagName , Map attributes ) { } }

implementation: _xml . append ( '<' ) . append ( tagName ) ; addAttributes ( attributes ) ; _xml . append ( " />" ) ;


signature:
public class XML { /** * Adds an empty tag which contains an attribute
 * @ param tagName the name of the empty tag to add
 * @ param attrName the name of the attribute
 * @ param attrValue the value of the attribute */
@ Override public void addEmptyTag ( String tagName , String attrName , String attrValue ) { } }

implementation: _xml . append ( '<' ) . append ( tagName ) ; addAttribute ( attrName , attrValue ) ; _xml . append ( " />" ) ;


signature:
public class XML { /** * Adds the attribute
 * @ param attrName name of the attribute to add
 * @ param attrValue value of the attribute to add */
private void addAttribute ( String attrName , String attrValue ) { } }

implementation: if ( attrName == null ) return ; _xml . append ( ' ' ) ; _xml . append ( attrName ) . append ( "=\"" ) ; _xml . append ( XMLUtils . xmlEncode ( attrValue ) ) . append ( '"' ) ;


signature:
public class XML { /** * Adds the attributes . All the properties will be used as attributes
 * @ param attributes the attributes to add */
private void addAttributes ( Map attributes ) { } }

implementation: if ( attributes == null ) return ; Iterator iter = attributes . keySet ( ) . iterator ( ) ; while ( iter . hasNext ( ) ) { String attrName = ( String ) iter . next ( ) ; Object attrValue = attributes . get ( attrName ) ; if ( attrValue != null ) addAttribute ( attrName , attrValue . toString ( ) ) ; }


signature:
public class URLResource { /** * Important note : the caller of this method is responsible for properly closing the input
 * stream !
 * @ return an input stream to the resource .
 * @ throws IOException if cannot get an input stream */
@ Override public InputStream getInputStream ( ) throws IOException { } }

implementation: URLConnection urlConnection = _url . openConnection ( ) ; urlConnection . setDoInput ( true ) ; urlConnection . setDoOutput ( false ) ; urlConnection . setUseCaches ( false ) ; urlConnection . setConnectTimeout ( new Long ( _connectTimeout . getDurationInMilliseconds ( ) ) . intValue ( ) ) ; urlConnection . setReadTimeout ( new Long ( _readTimeout . getDurationInMilliseconds ( ) ) . intValue ( ) ) ; urlConnection . connect ( ) ; return urlConnection . getInputStream ( ) ;


signature:
public class URLResource { /** * Extracts the info from the url */
public static ResourceInfo extractInfo ( URL url ) throws IOException { } }

implementation: URLConnection urlConnection = url . openConnection ( ) ; urlConnection . setDoInput ( true ) ; urlConnection . setDoOutput ( false ) ; urlConnection . setUseCaches ( false ) ; urlConnection . connect ( ) ; InputStream is = urlConnection . getInputStream ( ) ; try { return new StaticInfo ( urlConnection . getContentLength ( ) , urlConnection . getLastModified ( ) ) ; } finally { is . close ( ) ; }


signature:
public class URLResource { /** * Creates the resource from a url . . .
 * @ param url
 * @ return the resource */
public static Resource create ( URL url ) { } }

implementation: URLBuilder rootURL = URLBuilder . createFromPath ( "/" ) ; rootURL . setScheme ( url . getProtocol ( ) ) ; rootURL . setHost ( url . getHost ( ) ) ; rootURL . setPort ( url . getPort ( ) ) ; rootURL . setUserInfo ( url . getUserInfo ( ) ) ; return create ( rootURL . toJavaURL ( ) , "/" ) . createRelative ( url . getPath ( ) ) ;


signature:
public class URLResource { /** * Creates the resource from a url . . . The root will be at the path of this url ( ex :
 * if url is http : / / localhost / a / b / c / foo . html then root is / a / b / c ) .
 * @ param url
 * @ return the resource */
public static Resource createFromRoot ( URL url ) { } }

implementation:
String urlPath = url . getPath ( ) ; String path = "/" ; if ( ! urlPath . endsWith ( "/" ) ) { urlPath = PathUtils . addLeadingSlash ( urlPath ) ; int idx = urlPath . lastIndexOf ( "/" ) ; // there will always be one due to previous line . . .
path = urlPath . substring ( idx + 1 ) ; urlPath = urlPath . substring ( 0 , idx ) ; } URLBuilder rootURL = URLBuilder . createFromPath ( urlPath ) ; rootURL . setScheme ( url . getProtocol ( ) ) ; rootURL . setHost ( url . getHost ( ) ) ; rootURL . setPort ( url . getPort ( ) ) ; rootURL . setUserInfo ( url . getUserInfo ( ) ) ; return create ( rootURL . toJavaURL ( ) , "/" ) . createRelative ( path ) ;


signature:
public class URLResource { /** * Creates the resource from a url . . .
 * @ param url
 * @ return the resource */
public static Resource create ( URL url , String rootPath ) { } }

implementation: try { return new URLResourceProvider ( url , rootPath ) . getRootResource ( ) ; } catch ( UnsupportedURIException e ) { throw new RuntimeException ( e ) ; } catch ( URISyntaxException e ) { throw new RuntimeException ( e ) ; }


signature:
public class SchemeURLResourceFactory { /** * Method that needs to be implemented by children . .
 * @ param uri
 * @ param parent the parent resource factory
 * @ return the resource */
@ Override protected Resource doCreateResource ( URI uri , URIResourceFactory parent ) { } }

implementation: try { return URLResource . createFromRoot ( uri . toURL ( ) ) ; } catch ( MalformedURLException e ) { throw new IllegalArgumentException ( uri . toString ( ) , e ) ; }


signature:
public class AbstractResourceProvider { /** * The path to the resource is absolute . Whether it starts with / or not it will be made
 * absolute .
 * Note that it follows the same convention as { @ link File } class in the sense that a resource
 * simply represents a handle and does not imply that the resource exists .
 * @ param path the path to the resource
 * @ return the resource given the path */
@ Override public Resource createResource ( String path ) { } }

implementation: if ( path == null ) return null ; URI uri = URI . create ( path ) . normalize ( ) ; if ( uri . isAbsolute ( ) ) throw new IllegalArgumentException ( path + " => only path with no scheme are supported..." ) ; path = uri . toString ( ) ; return doBuildResource ( PathUtils . addLeadingSlash ( path ) ) ;


signature:
public class AbstractResourceProvider { /** * Returns a new resource with the root resource set to this resource .
 * @ return the new resource */
@ Override public InternalResource chroot ( InternalResource resource ) { } }

implementation:
String path = resource . getPath ( ) ; // when it is a directory , we simply use the provided resource
if ( resource . isDirectory ( ) ) { return doCreateResourceProvider ( path ) . getRootResource ( ) ; } else { // when not a directory , we do a chroot to the parent and then we return the resource
// that points to it
return ( InternalResource ) resource . chroot ( ".." ) . createRelative ( resource . getFilename ( ) ) ; }


signature:
public class AbstractResourceProvider { /** * If this resource denotes a directory , then it will return all resources that are contained in
 * the directory .
 * @ param filter the filter to include only some resources in the result
 * @ return all the resources contained in the directory or < code > null < / code > if not a directory
 * @ throws IOException if there is an error accessing the resource */
@ Override public InternalResource [ ] list ( InternalResource resource , final ResourceFilter filter ) throws IOException { } }

implementation: final List < Resource > resources = new ArrayList < Resource > ( ) ; String path = PathUtils . addTrailingSlash ( resource . getPath ( ) ) ; if ( doList ( path , new ResourceFilter ( ) { @ Override public boolean accept ( Resource resource ) { boolean res = filter . accept ( resource ) ; if ( res ) resources . add ( resource ) ; return res ; } } ) ) { return resources . toArray ( new InternalResource [ resources . size ( ) ] ) ; } else return null ;


signature:
public class AbstractResource { /** * Returns a new resource with the root resource set to the relative path provided . Note that the
 * new resource points at the new root as well .
 * @ param relativePath
 * @ return the new resource */
@ Override public Resource chroot ( String relativePath ) { } }

implementation: return _resourceProvider . chroot ( ( InternalResource ) createRelative ( relativePath ) ) ;


signature:
public class InternalException { /** * Convenient call to adapt the < code > InvocationTargetException < / code > into an
 * < code > InternalException < / code >
 * @ param module the module
 * @ param ite the invocation target exception ( coming from < code > Method . invoke < / code > )
 * @ throws InternalException this method always throw an exception at the end : either a
 * < code > RuntimeException < / code > or < code > Error < / code > or < code > InternalException < / code > */
public static InternalException throwInternalException ( String module , InvocationTargetException ite ) throws InternalException { } }

implementation: try { throw ite . getTargetException ( ) ; } catch ( Error e ) { throw e ; } catch ( RuntimeException e ) { throw e ; } catch ( Throwable e ) { throw new InternalException ( module , e ) ; }


signature:
public class XMLUtils { /** * Encodes the string so that it is XML safe : all characters & lt ; = 127
 * will not be encoded ( converts & lt ; , & gt ; & amp ; & apos ; into their
 * equivalent ( & amp ; lt ; , & amp ; gt ; & amp ; amp ; & amp ; apos ; ) ) . All characters
 * & gt ; 127 will be encoded as & amp ; # xxxx ; with xxxx the hexadecimal
 * value of the character . This method differs from
 * < code > xmlEncode < / code > because it encodes all values & gt ; 127 into a
 * pure ascii xml safe string . In most cases , this method is NOT
 * necessary because with an xml message you can specify the encoding , so
 * there is no need to encode those characters .
 * @ param s the string to encode
 * @ return the encoded string */
public static String xmlEncodeRaw ( String s ) { } }

implementation:
if ( s == null ) return null ; char [ ] chars = s . toCharArray ( ) ; final int len = chars . length ; StringBuilder sb = new StringBuilder ( len ) ; for ( int i = 0 ; i < len ; i ++ ) { char c = chars [ i ] ; if ( c < _chars . length ) { sb . append ( _chars [ c ] ) ; } else if ( Character . isHighSurrogate ( c ) ) { int j = i + 1 ; if ( j < len && Character . isLowSurrogate ( chars [ j ] ) ) { sb . append ( "&#x" ) . append ( Integer . toHexString ( Character . toCodePoint ( c , chars [ j ] ) ) ) . append ( ';' ) ; i = j ; } // else ignore this character , a single high surrogate is an invalid char
} else if ( ! Character . isLowSurrogate ( c ) ) { sb . append ( "&#x" ) . append ( Integer . toHexString ( c ) ) . append ( ';' ) ; } } return sb . toString ( ) ;


signature:
public class XMLUtils { /** * This method descodes a string that was previously encoded for being XML
 * safe . It is the exact opposite of xmlEncode
 * @ param s the string to decode
 * @ return the decoded string
 * @ exception IllegalArgumentException if the string cannot be decoded */
public static String xmlDecode ( String s ) throws IllegalArgumentException { } }

implementation: if ( s == null ) return s ; int idxS = s . indexOf ( '&' ) ; if ( idxS < 0 ) return s ; StringBuilder sb = new StringBuilder ( s . length ( ) ) ; int idxE , idx , size ; char c , c_1 ; int prev = 0 ; while ( idxS != - 1 ) { idxE = s . indexOf ( ';' , idxS ) ; if ( idxE < 0 ) throw new IllegalArgumentException ( "missing ';' in: " + s . substring ( idxS ) ) ; sb . append ( s . substring ( prev , idxS ) ) ; idx = idxS + 1 ; size = idxE - idxS - 1 ; if ( size < 2 ) throw new IllegalArgumentException ( "invalid escape tag: " + s . substring ( idxS , idxE + 1 ) ) ; c = s . charAt ( idx ) ; c_1 = s . charAt ( idx + 1 ) ; switch ( c ) { case 'l' : if ( size != 2 ) throw new IllegalArgumentException ( "invalid escape tag: " + s . substring ( idxS , idxE + 1 ) ) ; if ( c_1 == 't' ) sb . append ( '<' ) ; else throw new IllegalArgumentException ( "invalid escape tag: " + s . substring ( idxS , idxE + 1 ) ) ; break ; case 'g' : if ( size != 2 ) throw new IllegalArgumentException ( "invalid escape tag: " + s . substring ( idxS , idxE + 1 ) ) ; if ( c_1 == 't' ) sb . append ( '>' ) ; else throw new IllegalArgumentException ( "invalid escape tag: " + s . substring ( idxS , idxE + 1 ) ) ; break ; case 'q' : if ( size != 4 ) throw new IllegalArgumentException ( "invalid escape tag: " + s . substring ( idxS , idxE + 1 ) ) ; if ( c_1 != 'u' || s . charAt ( idx + 2 ) != 'o' || s . charAt ( idx + 3 ) != 't' ) throw new IllegalArgumentException ( "invalid escape tag: " + s . substring ( idxS , idxE + 1 ) ) ; else sb . append ( '"' ) ; break ; case 'a' : if ( size == 3 ) { if ( c_1 != 'm' || s . charAt ( idx + 2 ) != 'p' ) throw new IllegalArgumentException ( "invalid escape tag: " + s . substring ( idxS , idxE + 1 ) ) ; else sb . append ( '&' ) ; } else if ( size == 4 ) { if ( c_1 != 'p' || s . charAt ( idx + 2 ) != 'o' || s . charAt ( idx + 3 ) != 's' ) throw new IllegalArgumentException ( "invalid escape tag: " + s . substring ( idxS , idxE + 1 ) ) ; else sb . append ( '\'' ) ; } else throw new IllegalArgumentException ( "invalid escape tag: " + s . substring ( idxS , idxE + 1 ) ) ; break ; case '#' : int codePoint ; try { codePoint = ( c_1 == 'x' ) ? Integer . parseInt ( s . substring ( idx + 2 , idxE ) , 16 ) : Integer . parseInt ( s . substring ( idx + 1 , idxE ) ) ; } catch ( NumberFormatException ex ) { throw new IllegalArgumentException ( "invalid escape tag: " + s . substring ( idxS , idxE + 1 ) ) ; } if ( codePoint < 0 ) throw new IllegalArgumentException ( "invalid character codepoint: " + s . substring ( idxS , idxE + 1 ) ) ; if ( codePoint < Character . MIN_SUPPLEMENTARY_CODE_POINT ) sb . append ( ( char ) codePoint ) ; else sb . append ( Character . toChars ( codePoint ) ) ; break ; default : throw new IllegalArgumentException ( "invalid escape tag: " + s . substring ( idxS , idxE + 1 ) ) ; } prev = idxE + 1 ; idxS = s . indexOf ( "&" , prev ) ; } if ( prev < s . length ( ) ) sb . append ( s . substring ( prev ) ) ; return sb . toString ( ) ;


signature:
public class FilteredResourceProvider { /** * If the path denotes a directory , then it will return all resources that are contained in the
 * directory .
 * @ param path the path to the resource ( it already ends with / )
 * @ param filter the filter to include only some resources in the result
 * @ return < code > true < / code > if it was a directory , < code > false < / code > otherwise */
@ Override public boolean doList ( String path , final ResourceFilter filter ) { } }

implementation: ResourceFilter newFilter = new ResourceFilter ( ) { @ Override public boolean accept ( Resource resource ) { return filter . accept ( doBuildResource ( resource ) ) ; } } ; return _resourceProvider . doList ( path , newFilter ) ;


signature:
public class FileResource { /** * Efficiently returns all information about the resource .
 * @ return information about this resource .
 * @ throws IOException if cannot get information */
@ Override public ResourceInfo getInfo ( ) throws IOException { } }

implementation: if ( _file . exists ( ) ) return new FileInfo ( ) ; else throw new FileNotFoundException ( _file . getPath ( ) ) ;


signature:
public class FileResource { /** * Creates a file resource from a file
 * @ param file the file
 * @ return the resource ( points to this file ) */
public static Resource create ( File file ) { } }

implementation: try { String path = file . getCanonicalPath ( ) ; if ( file . isDirectory ( ) ) path = PathUtils . addTrailingSlash ( path ) ; return create ( new File ( "/" ) , path ) ; } catch ( IOException e ) { throw new IllegalArgumentException ( "invalid file " + file , e ) ; }


signature:
public class FileResource { /** * Creates a file resource from a file , with the root as this file ( if it is a directory
 * otherwise its parent ) .
 * @ param rootFile the root file
 * @ return the resource ( points to this file ) */
public static Resource createFromRoot ( File rootFile ) { } }

implementation: File root = rootFile ; String path = "/" ; if ( ! root . isDirectory ( ) ) { root = rootFile . getParentFile ( ) ; path = rootFile . getName ( ) ; } return create ( root , path ) ;


signature:
public class FileResource { /** * Creates a file resource with the root provided and the path ( relative to the root ) .
 * @ param root the root of the resource
 * @ param path the path ( relative to root )
 * @ return the resource */
public static Resource create ( File root , String path ) { } }

implementation: FileResourceProvider frp = null ; try { frp = new FileResourceProvider ( root ) ; } catch ( IOException e ) { throw new RuntimeException ( e ) ; } return frp . createResource ( path ) ;


signature:
public class ExternalCommand { /** * After creating the command , you have to start it . . .
 * @ throws IOException */
public void start ( ) throws IOException { } }

implementation: _process = _processBuilder . start ( ) ; _out = new InputReader ( new BufferedInputStream ( _process . getInputStream ( ) ) ) ; _err = new InputReader ( new BufferedInputStream ( _process . getErrorStream ( ) ) ) ; _out . start ( ) ; _err . start ( ) ;


signature:
public class ExternalCommand { /** * Properly waits until everything is complete : joins on the thread that
 * reads the output , joins on the thread that reads the error and finally
 * wait for the process to be finished .
 * @ return the status code of the process .
 * @ throws InterruptedException */
public int waitFor ( ) throws InterruptedException { } }

implementation: if ( _process == null ) throw new IllegalStateException ( "you must call start first" ) ; _out . join ( ) ; _err . join ( ) ; return _process . waitFor ( ) ;


signature:
public class ExternalCommand { /** * Properly waits until everything is complete : joins on the thread that
 * reads the output , joins on the thread that reads the error and finally
 * wait for the process to be finished .
 * If the process has not completed before the timeout , throws a
 * { @ link TimeoutException }
 * @ return the status code of the process .
 * @ throws TimeoutException
 * @ throws InterruptedException */
public int waitFor ( long timeout ) throws InterruptedException , TimeoutException { } }

implementation:
if ( _process == null ) throw new IllegalStateException ( "you must call start first" ) ; Chronos c = new Chronos ( ) ; _out . join ( timeout ) ; timeout -= c . tick ( ) ; if ( timeout <= 0 ) throw new TimeoutException ( "Wait timed out" ) ; _err . join ( timeout ) ; timeout -= c . tick ( ) ; if ( timeout <= 0 ) throw new TimeoutException ( "Wait timed out" ) ; // there is no timeout in this API , not much we can do here
// waiting on the other two threads should give us some safety
return _process . waitFor ( ) ;


signature:
public class ExternalCommand { /** * Creates an external process from the command . It is not started and you have to call
 * start on it !
 * @ param commands the command to execute
 * @ return the process */
public static ExternalCommand create ( List < String > commands ) { } }

implementation: ExternalCommand ec = new ExternalCommand ( new ProcessBuilder ( commands ) ) ; return ec ;


signature:
public class ExternalCommand { /** * Creates an external process from the command . The command is executed .
 * @ param commands the commands to execute
 * @ return the process
 * @ throws IOException if there is an error */
public static ExternalCommand start ( String ... commands ) throws IOException { } }

implementation: ExternalCommand ec = new ExternalCommand ( new ProcessBuilder ( commands ) ) ; ec . start ( ) ; return ec ;


signature:
public class ExternalCommand { /** * Executes the external command in the given working directory and waits for it to be
 * finished .
 * @ param workingDirectory the root directory from where to run the command
 * @ param command the command to execute ( should be relative to the working directory
 * @ param args the arguments to the command
 * @ return the process */
public static ExternalCommand execute ( File workingDirectory , String command , String ... args ) throws IOException , InterruptedException { } }

implementation:
try { return executeWithTimeout ( workingDirectory , command , 0 , args ) ; } catch ( TimeoutException e ) { // Can ' t happen !
throw new IllegalStateException ( MODULE + ".execute: Unexpected timeout occurred!" ) ; }


signature:
public class ExternalCommand { /** * Executes the external command in the given working directory and waits ( until timeout
 * is elapsed ) for it to be finished .
 * @ param workingDirectory
 * the root directory from where to run the command
 * @ param command
 * the command to execute ( should be relative to the working directory
 * @ param timeout
 * the maximum amount of time to wait for this external command ( in ms ) . If
 * this value is less than or equal to 0 , timeout is ignored
 * @ param args
 * the arguments to the command
 * @ return the process */
public static ExternalCommand executeWithTimeout ( File workingDirectory , String command , long timeout , String ... args ) throws IOException , InterruptedException , TimeoutException { } }

implementation:
List < String > arguments = new ArrayList < String > ( args . length + 1 ) ; arguments . add ( new File ( workingDirectory , command ) . getAbsolutePath ( ) ) ; arguments . addAll ( Arrays . asList ( args ) ) ; ExternalCommand cmd = ExternalCommand . create ( arguments ) ; cmd . setWorkingDirectory ( workingDirectory ) ; cmd . setRedirectErrorStream ( true ) ; cmd . start ( ) ; /* Use timeout if it is a valid value ! */
if ( timeout <= 0 ) cmd . waitFor ( ) ; else cmd . waitFor ( timeout ) ; if ( log . isDebugEnabled ( ) ) log . debug ( cmd . getStringOutput ( ) ) ; return cmd ;


signature:
public class Chronos { /** * Returns the number of milliseconds ellapsed since the last call to
 * this function .
 * @ return the number of milliseconds since last call */
public long tick ( ) { } }

implementation: long tick = _clock . currentTimeMillis ( ) ; long diff = tick - _tick ; _tick = tick ; return diff ;


signature:
public class Chronos { /** * Returns a string that represents the time elapsed
 * @ return the elapsed time as a string */
public String getElapsedTime ( ) { } }

implementation: StringBuilder sb = new StringBuilder ( "Time: " ) ; sb . append ( this . tick ( ) ) ; sb . append ( " ms" ) ; return sb . toString ( ) ;


signature:
public class JarResource { /** * Important note : the caller of this method is responsible for properly closing the input
 * stream !
 * @ return an input stream to the resource .
 * @ throws IOException if cannot get an input stream */
@ Override public InputStream getInputStream ( ) throws IOException { } }

implementation:
JarFile contentJarFile = getContentJarFile ( ) ; try { CloseJarFileInputStream jarFileInputStream = new CloseJarFileInputStream ( this , contentJarFile , _fullPath ) ; // we are delegating the closure of the jar file to the input stream . . .
contentJarFile = null ; return jarFileInputStream ; } finally { if ( contentJarFile != null ) contentJarFile . close ( ) ; }


signature:
public class JarResource { /** * Efficiently returns all information about the resource .
 * @ return information about this resource .
 * @ throws IOException if cannot get information */
@ Override public ResourceInfo getInfo ( ) throws IOException { } }

implementation:
// represents the root . . .
if ( _fullPath . equals ( "" ) ) { return new StaticInfo ( 0 , // root is a directory . . .
_jarResource . getInfo ( ) . getLastModified ( ) ) ; // last modified is the jar file itself !
} JarFile contentJarFile = getContentJarFile ( ) ; try { JarEntry jarEntry = contentJarFile . getJarEntry ( _fullPath ) ; if ( jarEntry == null ) throw new ResourceNotFoundException ( toURI ( ) ) ; return new StaticInfo ( jarEntry . getSize ( ) , jarEntry . getTime ( ) ) ; } finally { contentJarFile . close ( ) ; }


signature:
public class JarResource { /** * Factory method .
 * @ param uri the uri to the jar . . . note that it can either be jar : or a plain uri to the
 * jar ( ex : file : / / tmp / foo . jar and jar : file : / / tmp / foo . jar ! / are both valid and pointing to the
 * same resource ! ) */
public static Resource create ( URI uri ) throws URISyntaxException , IOException { } }

implementation: return create ( uri , URIResourceFactory . DEFAULT ) ;


signature:
public class JarResource { /** * Factory method .
 * @ param uri the uri to the jar . . . note that it can either be jar : or a plain uri to the
 * jar ( ex : file : / / tmp / foo . jar and jar : file : / / tmp / foo . jar ! / are both valid and pointing to the
 * same resource ! ) */
public static Resource create ( URI uri , URIResourceFactory factory ) throws URISyntaxException { } }

implementation:
String path = "/" ; // case when the URI is already a jar uri
if ( "jar" . equals ( uri . getScheme ( ) ) ) { String schemeSpecificPart = uri . getSchemeSpecificPart ( ) ; if ( schemeSpecificPart == null ) throw new URISyntaxException ( uri . toString ( ) , "no scheme specific part found..." ) ; int idx = schemeSpecificPart . indexOf ( "!/" ) ; if ( idx == - 1 ) throw new URISyntaxException ( uri . toString ( ) , "couldn't find !/" ) ; uri = new URI ( schemeSpecificPart . substring ( 0 , idx ) ) ; path = schemeSpecificPart . substring ( idx + 1 ) ; } // case when the URI points directly to the jar resource
try { ResourceProvider provider = new JarResourceProvider ( factory . createResource ( uri ) ) ; return provider . createResource ( "/" ) . createRelative ( path ) ; } catch ( UnsupportedURIException e ) { URISyntaxException ex = new URISyntaxException ( uri . toString ( ) , "cannot create resource" ) ; ex . initCause ( e ) ; throw ex ; }


signature:
public class JarResource { /** * Convenient call to create a resource from the jar resource ( points at rootPath in the
 * jar . . . )
 * @ param jarResource
 * @ param rootPath where is the root in the jar
 * @ return the resource with root at rootPath */
public static Resource create ( Resource jarResource , String rootPath ) { } }

implementation: return new JarResourceProvider ( jarResource , rootPath ) . getRootResource ( ) ;


signature:
public class AbstractXMLBuilder { /** * Adds a tag
 * @ param tagName the name of the tag to add
 * @ param value the value of the tag to add */
@ Override public void addTag ( String tagName , double value ) { } }

implementation: addTag ( tagName , String . valueOf ( value ) ) ;


signature:
public class AbstractXMLBuilder { /** * Adds a tag which contains an attribute
 * @ param tagName the name of the tag to add
 * @ param value the value of the tag to add
 * @ param attrName the name of the attribute
 * @ param attrValue the value of the attribute */
@ Override public void addTag ( String tagName , int value , String attrName , String attrValue ) { } }

implementation: addTag ( tagName , String . valueOf ( value ) , attrName , attrValue ) ;


signature:
public class AbstractXMLBuilder { /** * Adds a tag which contains the attributes specified . All the
 * properties will be turned into attributes .
 * @ param tagName the name of the tag to add
 * @ param value the value of the tag to add
 * @ param attributes the attributes */
@ Override public void addTag ( String tagName , int value , Map attributes ) { } }

implementation: addTag ( tagName , String . valueOf ( value ) , attributes ) ;


signature:
public class Indent { /** * Indents a block of text . You provide the block of text as a String and
 * the indent object and it returns another String with each line
 * properly indented .
 * @ param block the block of text to indent
 * @ param indent the indentation object to use
 * @ return the indented block */
public static String indentBlock ( String block , Indent indent ) { } }

implementation:
StringBuilder sb = new StringBuilder ( ) ; BufferedReader br = new BufferedReader ( new StringReader ( block ) ) ; String line ; try { while ( ( line = br . readLine ( ) ) != null ) sb . append ( indent ) . append ( line ) . append ( '\n' ) ; } catch ( IOException ex ) { // on a String ? I doubt . . .
} return sb . toString ( ) ;


signature:
public class RAMResource { /** * Important note : the caller of this method is responsible for properly closing the input
 * stream !
 * @ return an input stream to the resource .
 * @ throws IOException if cannot get an input stream */
@ Override public InputStream getInputStream ( ) throws IOException { } }

implementation: RAMEntry entry = getRAMEntry ( ) ; if ( entry == null || entry instanceof RAMDirectory ) throw new ResourceNotFoundException ( toURI ( ) ) ; return new ByteArrayInputStream ( ( ( RAMFile ) entry ) . getContent ( ) ) ;


signature:
public class RAMResource { /** * Efficiently returns all information about the resource .
 * @ return information about this resource .
 * @ throws IOException if cannot get information */
@ Override public ResourceInfo getInfo ( ) throws IOException { } }

implementation: RAMEntry entry = getRAMEntry ( ) ; if ( entry != null ) return new StaticInfo ( entry . getContentLength ( ) , entry . lastModified ( ) ) ; else throw new ResourceNotFoundException ( toURI ( ) ) ;


signature:
public class ClockUtils { /** * Converts the object into a timespan . If already a timespan then simply return the object .
 * Otherwise call { @ link Timespan # parse ( String ) } on < code > t . toString ( ) < / code > . Works well for
 * long and < code > String < / code >
 * @ return a timespan ( < code > null < / code > if t is < code > null < / code > ) */
public static Timespan toTimespan ( Object t ) { } }

implementation: if ( t == null ) return null ; if ( t instanceof Timespan ) { return ( Timespan ) t ; } return Timespan . parse ( t . toString ( ) ) ;


signature:
public class ClockUtils { /** * Computes the end time = now + timeout
 * @ param clock can be < code > null < / code > to use system clock
 * @ param timeout ( see { @ link # toTimespan ( Object ) } )
 * @ return 0 if */
public static long toEndTime ( Clock clock , Object timeout ) { } }

implementation: Timespan t = toTimespan ( timeout ) ; if ( t == null ) return 0 ; if ( clock == null ) clock = SystemClock . INSTANCE ; if ( t . getDurationInMilliseconds ( ) == 0 ) return 0 ; return t . futureTimeMillis ( clock ) ;


signature:
public class RAMDirectory { /** * Equivalent to ' touch ' unix command : updates the last modified date to the value provided
 * and if the entry does not create it , it creates an empty file !
 * @ param name
 * @ param lastModifiedDate
 * @ return the entry ( either a new file or the entry that was modified ) */
public RAMEntry touch ( String name , long lastModifiedDate ) { } }

implementation: RAMEntry ramEntry = _directoryContent . get ( name ) ; if ( ramEntry == null ) { ramEntry = add ( new RAMFile ( _clock , name , new byte [ 0 ] ) ) ; } ramEntry . touch ( lastModifiedDate ) ; return ramEntry ;


signature:
public class RAMDirectory { /** * Copy the entry in this directory with the provided name
 * @ param entry
 * @ return the touched entry */
public RAMEntry add ( RAMEntry entry ) { } }

implementation: touch ( ) ; _directoryContent . put ( entry . name ( ) , entry ) ; return entry ;


signature:
public class RAMDirectory { /** * Creates a file with the content and add it to the directory with this name
 * @ param name
 * @ return the created file */
public RAMFile add ( String name , byte [ ] content ) { } }

implementation: return ( RAMFile ) add ( new RAMFile ( _clock , name , content ) ) ;


signature:
public class RAMDirectory { /** * Creates a file with the content and add it to the directory with this name
 * @ param name
 * @ param content as a string
 * @ return the created file */
public RAMFile add ( String name , String content ) { } }

implementation:
try { return add ( name , content . getBytes ( "UTF-8" ) ) ; } catch ( UnsupportedEncodingException e ) { // should not happen
throw new RuntimeException ( e ) ; }


signature:
public class RAMDirectory { /** * Creates an empty directory and add it to this directory with this name . If the directory
 * already exists , it does not recreate it .
 * @ param name
 * @ return the created directory
 * @ throws IOException if the name represents a file */
public RAMDirectory mkdir ( String name ) throws IOException { } }

implementation: RAMEntry entry = getEntry ( name ) ; if ( entry instanceof RAMDirectory ) { RAMDirectory ramDirectory = ( RAMDirectory ) entry ; return ramDirectory ; } else { if ( entry == null ) { RAMDirectory directory = new RAMDirectory ( _clock , name ) ; return ( RAMDirectory ) add ( directory ) ; } else { throw new IOException ( "File exists: " + name ) ; } }


signature:
public class RAMDirectory { /** * Creates an empty directory and add it to this directory with this path ( equivalent
 * to unix command ) : create all intermediary directories
 * @ param path
 * @ return the created directory */
public RAMDirectory mkdirhier ( String path ) throws IOException { } }

implementation:
RAMDirectory directory = this ; String [ ] pathComponents = path . split ( "/" ) ; for ( String pathComponent : pathComponents ) { // we skip empty path components ( caused by leading / + double / / )
if ( pathComponent . equals ( "" ) ) continue ; RAMEntry entry = directory . getEntry ( pathComponent ) ; if ( entry == null ) { directory = directory . mkdir ( pathComponent ) ; } else { if ( entry instanceof RAMDirectory ) { directory = ( RAMDirectory ) entry ; } else { throw new IOException ( "File exists: " + pathComponent ) ; } } } return directory ;


signature:
public class FileURIResourceFactory { /** * Method that needs to be implemented by children . .
 * @ param uri
 * @ param parent the parent resource factory
 * @ return the resource */
@ Override protected Resource doCreateResource ( URI uri , URIResourceFactory parent ) { } }

implementation: return FileResource . create ( new File ( "/" ) , uri . getPath ( ) ) ;


signature:
public class ResourceProviderChain { /** * Builds a resource given a path . Only subclasses know how to do that .
 * @ param path the path to the new resource ( always starts with / )
 * @ return the resource */
@ Override public InternalResource doBuildResource ( String path ) { } }

implementation:
// since the list is not empty , this variable will never remain null . . .
InternalResource resource = null ; for ( InternalResourceProvider resourceProvider : _resourceProviders ) { resource = resourceProvider . doBuildResource ( path ) ; if ( resource . exists ( ) ) break ; } return new ResourceChain ( this , path , resource ) ;


signature:
public class ResourceProviderChain { /** * Creates a new resource provider given the new path .
 * @ param rootPath
 * @ return the new resource provider */
@ Override public InternalResourceProvider doCreateResourceProvider ( String rootPath ) { } }

implementation: List < InternalResourceProvider > resourceProviders = new ArrayList < InternalResourceProvider > ( _resourceProviders . size ( ) ) ; for ( InternalResourceProvider resourceProvider : _resourceProviders ) { resourceProviders . add ( resourceProvider . doCreateResourceProvider ( rootPath ) ) ; } return new ResourceProviderChain ( resourceProviders ) ;


signature:
public class ResourceProviderChain { /** * If the path denotes a directory , then it will return all resources that are contained in the
 * directory .
 * @ param path the path to the resource
 * @ param filter the filter to include only some resources in the result
 * @ return < code > true < / code > if it was a directory , < code > false < / code > otherwise */
@ Override public boolean doList ( String path , final ResourceFilter filter ) { } }

implementation: boolean isDirectory = false ; ResourceFilter newFilter = new ResourceFilter ( ) { @ Override public boolean accept ( Resource resource ) { return filter . accept ( new ResourceChain ( ResourceProviderChain . this , resource . getPath ( ) , resource ) ) ; } } ; for ( InternalResourceProvider resourceProvider : _resourceProviders ) { isDirectory |= resourceProvider . doList ( path , newFilter ) ; } return isDirectory ;


signature:
public class CodecUtils { /** * Encodes the string using the codec provided .
 * @ param codec encode the string
 * @ param s the string to encode
 * @ return the encoded string */
public static String encodeString ( OneWayCodec codec , String s ) { } }

implementation:
try { return codec . encode ( s . getBytes ( "UTF-8" ) ) ; } catch ( UnsupportedEncodingException ex ) { // shouldn ' t happen
throw new RuntimeException ( ex ) ; }


signature:
public class CodecUtils { /** * Decodes the string using the codec provided . Returns a string
 * @ param codec encode the string
 * @ param s the string to encode
 * @ return the encoded string
 * @ throws Codec . CannotDecodeException if cannot decode the string */
public static String decodeString ( Codec codec , String s ) throws Codec . CannotDecodeException { } }

implementation:
try { return new String ( codec . decode ( s ) , "UTF-8" ) ; } catch ( UnsupportedEncodingException ex ) { // shouldn ' t happen
throw new RuntimeException ( ex ) ; }


signature:
public class CodecUtils { /** * Create a < code > Random < / code > object by extracting the seed from the password . */
public static Random createRandom ( String password ) { } }

implementation:
if ( password == null ) return null ; byte [ ] bytes ; try { MessageDigest md = MessageDigest . getInstance ( "SHA-1" ) ; bytes = md . digest ( password . getBytes ( "UTF-8" ) ) ; } catch ( NoSuchAlgorithmException e ) { // should not happen
throw new RuntimeException ( e ) ; } catch ( UnsupportedEncodingException e ) { // should not happen
throw new RuntimeException ( e ) ; } int len = bytes . length ; // we only take at most 6 bytes = > 48 bits
if ( len > 6 ) len = 6 ; long seed = 0 ; if ( len > 0 ) { seed = bytes [ 0 ] ; for ( int i = 1 ; i < len ; i ++ ) { seed <<= 8 ; seed |= bytes [ i ] ; } } int k = 0 ; for ( int i = len ; i < bytes . length ; i ++ ) { seed ^= ( ( ( long ) bytes [ i ] ) << ( k * 8 ) ) ; if ( k ++ == 5 ) k = 0 ; } return new Random ( seed ) ;


signature:
public class TextUtils { /** * Searches in the string ' < code > s < / code > ' all occurences of the
 * substring ' < code > src < / code > ' and replaces it with the string
 * ' < code > dst < / code > ' .
 * @ param s the string to search
 * @ param src the substring to search for inside s
 * @ param dst the replacing string
 * @ return the string with the text replaced */
public static String searchAndReplace ( String s , String src , String dst ) { } }

implementation: if ( s == null ) return null ; StringBuilder result = new StringBuilder ( ) ; int i = 0 ; int len = s . length ( ) ; int len2 = src . length ( ) ; while ( i < len ) { int index = s . indexOf ( src , i ) ; if ( index == - 1 ) { if ( i == 0 ) return s ; result . append ( s . substring ( i ) ) ; break ; } result . append ( s . substring ( i , index ) ) ; result . append ( dst ) ; i = index + len2 ; } return result . toString ( ) ;


signature:
public class ClassLoaderChain { /** * Creates a chain of class loaders . Handles < code > null < / code > properly .
 * @ param classLoaders
 * @ param createNew whether to create new instance of classloaderchain even if there is only one loader
 * @ return a class loader ( never < code > null < / code > ) */
public static ClassLoader createChain ( List < ClassLoader > classLoaders , Boolean createNew ) { } }

implementation:
List < ClassLoader > list = new ArrayList < ClassLoader > ( classLoaders . size ( ) ) ; for ( ClassLoader classLoader : classLoaders ) { // we skip null class loaders
if ( classLoader == null ) continue ; // we skip null class loaders
if ( classLoader instanceof NullClassLoader ) continue ; // we ' flatten ' the chain . . . no need to have a chain of a chain . . .
if ( classLoader instanceof ClassLoaderChain ) { ClassLoaderChain classLoaderChain = ( ClassLoaderChain ) classLoader ; list . addAll ( classLoaderChain . _classLoaders ) ; } else { list . add ( classLoader ) ; } } if ( list . size ( ) == 0 ) return NullClassLoader . instance ( ) ; // remove duplicates
ClassLoader previous = null ; Iterator < ClassLoader > iter = list . iterator ( ) ; while ( iter . hasNext ( ) ) { ClassLoader next = iter . next ( ) ; if ( next . equals ( previous ) ) iter . remove ( ) ; previous = next ; } // TODO : create a new entry point , and keeping old behavior unchanged .
if ( list . size ( ) == 1 && ! createNew ) return list . get ( 0 ) ; return new ClassLoaderChain ( list ) ;


signature:
public class LocalCacheLeafResource { /** * Initializes the fields ( safe to call multiple times ) . Thread safe . */
private synchronized void init ( ) { } }

implementation:
// already initialized
if ( _resourceInfo != null ) return ; // make a local copy of the file
try { InputStream is = _resource . getInputStream ( ) ; try { File file = GCFile . createTempFile ( LocalCacheLeafResource . class . getName ( ) , _resource . getFilename ( ) ) ; FileOutputStream fos = new FileOutputStream ( file ) ; try { BufferedOutputStream out = new BufferedOutputStream ( fos ) ; IOUtils . copy ( new BufferedInputStream ( is ) , out ) ; out . flush ( ) ; } finally { fos . close ( ) ; } ResourceInfo info = _resource . getInfo ( ) ; _localFile = file ; _resourceInfo = new StaticInfo ( info . getContentLength ( ) , info . getLastModified ( ) ) ; _ioException = null ; } finally { is . close ( ) ; } } catch ( IOException e ) { _localFile = null ; _resourceInfo = new StaticInfo ( 0 , 0 ) ; _ioException = e ; }


signature:
public class LocalCacheLeafResource { /** * Decorates the resource to implement a caching strategy .
 * @ param resource the resource to cache locally
 * @ return the ( locally cached ) resource */
public static LeafResource create ( Resource resource ) { } }

implementation:
try { // if we can access the file then there is no reason to decorate it . . .
resource . getFile ( ) ; return new LeafResourceImpl ( resource ) ; } catch ( IOException e ) { return new LocalCacheLeafResource ( resource ) ; }


signature:
public class CollectionsUtils { /** * Reverses the array in place .
 * @ param array the array to reverse
 * @ return the < em > same < / em > array provided NOT a new one ! */
public static < T > T [ ] reverse ( T [ ] array ) { } }

implementation:
if ( array == null ) return array ; int s = 0 ; int e = array . length - 1 ; while ( s < e ) { // swap index e and s
T tmp = array [ e ] ; array [ e ] = array [ s ] ; array [ s ] = tmp ; s ++ ; e -- ; } return array ;


signature:
public class CollectionsUtils { /** * Turns an array of enumeration values into an enum set
 * @ param clazz the type of the enum
 * @ param ts the array of enums
 * @ return the enum set containing all the values from the array */
public static < T extends Enum < T > > EnumSet < T > toEnumSet ( Class < T > clazz , T ... ts ) { } }

implementation: if ( ts == null ) return null ; EnumSet < T > res = EnumSet . noneOf ( clazz ) ; for ( T t : ts ) { res . add ( t ) ; } return res ;


signature:
public class CollectionsUtils { /** * Convenient call to load a properties file from the provided file */
public static Properties loadProperties ( File file ) throws IOException { } }

implementation: if ( file == null ) return null ; FileReader reader = new FileReader ( file ) ; try { return loadProperties ( reader ) ; } finally { reader . close ( ) ; }


signature:
public class CollectionsUtils { /** * Convenient call to load a properties file from the provided reader */
public static Properties loadProperties ( Reader reader ) throws IOException { } }

implementation: if ( reader == null ) return null ; Properties properties = new Properties ( ) ; properties . load ( reader ) ; return properties ;


signature:
public class Timespan { /** * Adds another timespan to this timespan and return a brand new one . Note that the unit is
 * preserved if < code > other < / code > has the same unit as ' this ' .
 * @ param other the timespan to add
 * @ return a brand new timespan . */
public Timespan add ( Timespan other ) { } }

implementation: if ( getTimeUnit ( ) == other . getTimeUnit ( ) ) return new Timespan ( getDuration ( ) + other . getDuration ( ) , getTimeUnit ( ) ) ; return new Timespan ( getDurationInMilliseconds ( ) + other . getDurationInMilliseconds ( ) , TimeUnit . MILLISECOND ) ;


signature:
public class Timespan { /** * Decomposes this timespan as a map for each unit provided . Example : if this timespan represents
 * 63s and you provide m / s / ms then you will get 3 timespans in the map : one of 1mn , one for 3s
 * and one for 0ms . ( Convenient call ) .
 * @ param timeUnits the time units you want to be part of the decomposition .
 * @ return a map containing an entry for each time unit provided . All others are < code > null < / code > .
 * @ see # getAsTimespans ( EnumSet ) */
public EnumMap < TimeUnit , Timespan > getAsTimespans ( TimeUnit ... timeUnits ) { } }

implementation: return getAsTimespans ( CollectionsUtils . toEnumSet ( TimeUnit . class , timeUnits ) ) ;


signature:
public class Timespan { /** * Returns a string representing this timespan expressed with the units provided .
 * @ param timeUnits the timeunits you want in the decomposition
 * @ return a string representation using the units .
 * @ see # getAsTimespans ( EnumSet ) */
public String getAsString ( EnumSet < TimeUnit > timeUnits ) { } }

implementation: StringBuilder sb = new StringBuilder ( ) ; EnumMap < TimeUnit , Timespan > canonicalTimespans = getAsTimespans ( timeUnits ) ; for ( TimeUnit timeUnit : TIME_UNIT_ORDER ) { if ( canonicalTimespans . containsKey ( timeUnit ) ) { long duration = canonicalTimespans . get ( timeUnit ) . getDuration ( ) ; if ( duration > 0 ) { sb . append ( duration ) . append ( timeUnit . getDisplayChar ( ) ) ; } } } if ( sb . length ( ) == 0 ) { sb . append ( 0 ) ; if ( timeUnits . contains ( getTimeUnit ( ) ) ) sb . append ( getTimeUnit ( ) . getDisplayChar ( ) ) ; } return sb . toString ( ) ;


signature:
public class Timespan { /** * Compares 2 timespan . Based on duration in milliseconds .
 * @ param timespan
 * @ return 0 if same duration in milliseconds , */
@ Override public int compareTo ( Timespan timespan ) { } }

implementation: if ( timespan . getTimeUnit ( ) == getTimeUnit ( ) ) return LangUtils . compare ( getDuration ( ) , timespan . getDuration ( ) ) ; else return LangUtils . compare ( getDurationInMilliseconds ( ) , timespan . getDurationInMilliseconds ( ) ) ;


signature:
public class Timespan { /** * Parses the provided string as a timespan . It should follow the pattern returned by
 * { @ link # getCanonicalString ( ) } . Example : 10m30s
 * @ param timespan
 * @ return the timespan to parse
 * @ throws IllegalArgumentException if the string is not valid */
public static Timespan parseTimespan ( String timespan ) { } }

implementation: if ( timespan == null ) return null ; int len = timespan . length ( ) ; if ( len == 0 ) return ZERO_MILLISECONDS ; int count = 0 ; int timeUnitOrderIdx = 0 ; int timeUnitOrderLen = TIME_UNIT_ORDER . length ; Timespan [ ] timespans = new Timespan [ timeUnitOrderLen ] ; int startDigitsIdx = 0 ; boolean expectingDigits = true ; for ( int i = 0 ; i < len ; i ++ ) { char c = timespan . charAt ( i ) ; if ( c >= '0' && c <= '9' ) { expectingDigits = false ; continue ; } if ( expectingDigits ) throw new IllegalArgumentException ( "found " + c + " was expecting a digit" ) ; for ( ; timeUnitOrderIdx < timeUnitOrderLen ; timeUnitOrderIdx ++ ) { TimeUnit timeUnit = TIME_UNIT_ORDER [ timeUnitOrderIdx ] ; String displayChar = timeUnit . getDisplayChar ( ) ; if ( displayChar . length ( ) == 0 ) throw new IllegalArgumentException ( "found nothing was expecting: " + c ) ; if ( c == displayChar . charAt ( 0 ) ) { try { long duration = Long . parseLong ( timespan . substring ( startDigitsIdx , i ) ) ; timespans [ timeUnitOrderIdx ++ ] = new Timespan ( duration , timeUnit ) ; startDigitsIdx = i + 1 ; expectingDigits = true ; count ++ ; break ; } catch ( NumberFormatException e ) { throw new IllegalArgumentException ( e ) ; } } } } if ( startDigitsIdx < len ) { try { long duration = Long . parseLong ( timespan . substring ( startDigitsIdx , len ) ) ; timespans [ timeUnitOrderLen - 1 ] = new Timespan ( duration , TimeUnit . MILLISECOND ) ; count ++ ; } catch ( NumberFormatException e ) { throw new IllegalArgumentException ( e ) ; } } Timespan [ ] ts = new Timespan [ count ] ; for ( int i = 0 , idx = 0 ; i < timespans . length ; i ++ ) { Timespan t = timespans [ i ] ; if ( t != null ) ts [ idx ++ ] = t ; } return create ( ts ) ;


signature:
public class MemorySize { /** * Returns this memory size as a fractional size representation using the biggest unit size
 * possible . ex : 1.23g
 * @ return a string representing a this memory size as a fraction using the biggest size unit
 * possible */
public String getFractionalSizeAsString ( ) { } }

implementation:
if ( _size == 0 ) return "0" ; long sizeInBytes = getSizeInBytes ( ) ; // determine the biggest size unit with non 0 size
for ( SizeUnit sizeUnit : ORDERED_SIZE_UNIT ) { if ( sizeUnit == SizeUnit . BYTE ) return String . valueOf ( sizeInBytes ) ; if ( sizeInBytes >= sizeUnit . getBytesCount ( ) ) { double fractionalSize = ( double ) sizeInBytes / sizeUnit . getBytesCount ( ) ; return String . format ( "%.2f%s" , fractionalSize , sizeUnit . getDisplayChar ( ) ) ; } } throw new RuntimeException ( "should not reach this line..." ) ;


signature:
public class MemorySize { /** * Return a new instance of MemorySize that is truncated to the given unit
 * @ param sizeUnit
 * @ return a new instance of MemorySize that is truncated to the given unit */
public MemorySize truncate ( SizeUnit sizeUnit ) { } }

implementation: if ( getSizeUnit ( ) == sizeUnit ) return this ; long sizeInBytes = getSizeInBytes ( ) ; if ( sizeInBytes >= sizeUnit . getBytesCount ( ) ) { return new MemorySize ( sizeInBytes / sizeUnit . getBytesCount ( ) , sizeUnit ) ; } else { return ZERO_SIZES . get ( sizeUnit ) ; }


signature:
public class MemorySize { /** * Return a new instance of MemorySize that adds up the size of this object
 * with that of the ' other '
 * @ param other
 * @ return a new instance of MemorySize that adds up the size of this object
 * with the that of the ' other ' */
public MemorySize add ( MemorySize other ) { } }

implementation: if ( other == null ) throw new NullPointerException ( ) ; if ( getSizeUnit ( ) == other . getSizeUnit ( ) ) return new MemorySize ( getSize ( ) + other . getSize ( ) , getSizeUnit ( ) ) ; return new MemorySize ( getSizeInBytes ( ) + other . getSizeInBytes ( ) , SizeUnit . BYTE ) ;


signature:
public class MemorySize { /** * Return a string representation of this instance using the given units
 * E . g . 2g3m4k given units g / m - > " 2g3m "
 * 2g3m4k given units g / k - > " 2g3076k "
 * 3m4k given units t / g - > " 0g "
 * 2g3m given units k / b - > " 2100224k "
 * @ param sizeUnits the sizeUnits you want in the decomposition
 * @ return a string representation of this instance using the given units . */
public String getAsString ( SizeUnit ... sizeUnits ) { } }

implementation: if ( sizeUnits == null || sizeUnits . length == 0 ) return toString ( ) ; return getAsString ( CollectionsUtils . toEnumSet ( SizeUnit . class , sizeUnits ) ) ;


signature:
public class MemorySize { /** * Return a string representation of this instance using the given units
 * E . g . 2g3m4k given units g / m - > " 2g3m "
 * 2g3m4k given units g / k - > " 2g3076k "
 * 3m4k given units t / g - > " 0g "
 * 2g3m given units k / b - > " 2100224k "
 * @ param sizeUnits the sizeUnits you want in the decomposition
 * @ return a string representation of this instance using the given units . */
public String getAsString ( EnumSet < SizeUnit > sizeUnits ) { } }

implementation:
if ( sizeUnits == null || sizeUnits . size ( ) == 0 ) return toString ( ) ; StringBuilder sb = new StringBuilder ( ) ; MemorySize ms = this ; MemorySize prevMs ; // IMPORTANT :
// according to javadoc for EnumSet :
// " The iterator returned by the iteratormethod traverses the elements in their natural order
// ( the order in which the enum constants are declared ) " and the toArray ( ) method of AbstractCollection
// guarantees such an order
Object [ ] unitsAsArr = sizeUnits . toArray ( ) ; int len = unitsAsArr . length ; for ( int i = len - 1 ; i > - 1 ; i -- ) { prevMs = ms ; ms = ms . truncate ( ( SizeUnit ) unitsAsArr [ i ] ) ; if ( ms . getSize ( ) > 0 ) { sb . append ( ms . getSize ( ) ) . append ( ms . getSizeUnit ( ) . getDisplayChar ( ) ) ; } ms = prevMs . subtract ( ms ) ; } if ( sb . length ( ) == 0 ) { SizeUnit smallestUnit = ( SizeUnit ) unitsAsArr [ 0 ] ; sb . append ( "0" ) . append ( smallestUnit . getDisplayChar ( ) ) ; } return sb . toString ( ) ;


signature:
public class MemorySize { /** * Compare with another instance of MemorySize based on size in bytes
 * @ see java . lang . Comparable # compareTo ( java . lang . Object ) */
@ Override public int compareTo ( MemorySize memorySize ) { } }

implementation:
// according to javadoc for interface Comparable < T > , a NullPointerException
// should be thrown when the object to be compared with is null
// http : / / java . sun . com / j2se / 1.5.0 / docs / api / java / lang / Comparable . html # compareTo ( T )
if ( memorySize == null ) throw new NullPointerException ( ) ; if ( getSizeUnit ( ) == memorySize . getSizeUnit ( ) ) return LangUtils . compare ( getSize ( ) , memorySize . getSize ( ) ) ; return LangUtils . compare ( getSizeInBytes ( ) , memorySize . getSizeInBytes ( ) ) ;


signature:
public class MemorySize { /** * Create a new instance of MemorySize by adding up the given
 * array of memorySizes
 * @ param memorySizes
 * @ return a new instance of MemorySize */
public static MemorySize create ( MemorySize ... memorySizes ) { } }

implementation: if ( memorySizes == null ) return null ; if ( memorySizes . length == 0 ) return ZERO_BYTES ; MemorySize res = memorySizes [ 0 ] ; for ( int i = 1 ; i < memorySizes . length ; i ++ ) { MemorySize memorySize = memorySizes [ i ] ; if ( memorySize != null ) res = res . add ( memorySize ) ; } return res ;


signature:
public class MemorySize { /** * Create a new instance of MemorySize by parsing the given string
 * of format e . g . 2g3m4k5
 * @ param memorySizeAsStr
 * @ return a new instance of MemorySize */
public static MemorySize parseMemorySize ( String memorySizeAsStr ) { } }

implementation: if ( memorySizeAsStr == null || memorySizeAsStr . length ( ) == 0 ) return null ; int len = memorySizeAsStr . length ( ) ; int orderedSizeUnitIdx = 0 ; int orderedSizeUnitLen = ORDERED_SIZE_UNIT . length ; int startDigitsIdx = 0 ; boolean expectingDigits = true ; MemorySize ms = ZERO_BYTES ; for ( int i = 0 ; i < len ; i ++ ) { char c = memorySizeAsStr . charAt ( i ) ; if ( c >= '0' && c <= '9' ) { expectingDigits = false ; continue ; } if ( expectingDigits ) throw new IllegalArgumentException ( "Unable to parse '" + memorySizeAsStr + "': found '" + c + "' at pos " + i + ", was expecting a digit" ) ; for ( ; orderedSizeUnitIdx < orderedSizeUnitLen ; orderedSizeUnitIdx ++ ) { SizeUnit sizeUnit = ORDERED_SIZE_UNIT [ orderedSizeUnitIdx ] ; String displayChar = sizeUnit . getDisplayChar ( ) ; if ( displayChar . length ( ) > 0 && c == displayChar . charAt ( 0 ) ) { try { long size = Long . parseLong ( memorySizeAsStr . substring ( startDigitsIdx , i ) ) ; ms = ms . add ( new MemorySize ( size , sizeUnit ) ) ; orderedSizeUnitIdx ++ ; startDigitsIdx = i + 1 ; expectingDigits = true ; break ; } catch ( NumberFormatException e ) { throw new IllegalArgumentException ( "Unable to parse '" + memorySizeAsStr + "'" , e ) ; } } } if ( orderedSizeUnitIdx == orderedSizeUnitLen ) throw new IllegalArgumentException ( "Unable to parse '" + memorySizeAsStr + "': found invalid character '" + c + "' at pos " + i ) ; } if ( startDigitsIdx < len ) { try { long size = Long . parseLong ( memorySizeAsStr . substring ( startDigitsIdx , len ) ) ; ms = ms . add ( new MemorySize ( size , SizeUnit . BYTE ) ) ; } catch ( NumberFormatException e ) { throw new IllegalArgumentException ( "Unable to parse '" + memorySizeAsStr + "'" , e ) ; } } return ms ;


signature:
public class ThreadPerTaskExecutor { /** * Executes the callable in a separate thread and return the future to get the result . Note
 * that this implementation is not efficient and should be used very carefully .
 * @ param callable
 * @ return the future to get the result . */
public static < V > Future < V > execute ( Callable < V > callable ) { } }

implementation: FutureTask < V > futureTask = new FutureTask < V > ( callable ) ; new Thread ( futureTask ) . start ( ) ; return futureTask ;


signature:
public class ExampleActivity { /** * Icons courtesy of https : / / mapicons . mapsmarker . com / */
private ArrayList < IconMarker > createIconMarkers ( ) { } }

implementation: final ArrayList < IconMarker > iconMarkers = new ArrayList < > ( LOCATIONS . length ) ; iconMarkers . add ( new IconMarker ( LOCATIONS [ 0 ] , R . drawable . bread , R . drawable . bread_c ) ) ; iconMarkers . add ( new IconMarker ( LOCATIONS [ 1 ] , R . drawable . butcher , R . drawable . butcher_c ) ) ; iconMarkers . add ( new IconMarker ( LOCATIONS [ 2 ] , R . drawable . fruits , R . drawable . fruits_c ) ) ; iconMarkers . add ( new IconMarker ( LOCATIONS [ 3 ] , R . drawable . grocery , R . drawable . grocery_c ) ) ; iconMarkers . add ( new IconMarker ( LOCATIONS [ 4 ] , R . drawable . patisserie , R . drawable . patisserie_c ) ) ; return iconMarkers ;


signature:
public class MarkerManager { /** * Add a marker to the map .
 * @ param marker marker to add */
public void addMarker ( T marker ) { } }

implementation: final MarkerOptions markerOptions = new MarkerOptions ( ) ; marker . setMarkerManager ( this ) ; marker . prepareMarker ( markerOptions ) ; markerCache . put ( marker , googleMap . addMarker ( markerOptions ) ) ; marker . onAdd ( ) ;


signature:
public class MarkerManager { /** * Remove a marker from the map .
 * @ param marker marker to remove */
public void removeMarker ( T marker ) { } }

implementation: final Marker realMarker = markerCache . get ( marker ) ; if ( realMarker != null ) { realMarker . remove ( ) ; } markerCache . remove ( marker ) ;


signature:
public class BitmapGenerator { /** * Returns a bitmap icon showing a screenshot of the view passed in .
 * @ param view View to convert
 * @ return Bitmap icon of view */
public static BitmapDescriptor fromView ( View view ) { } }

implementation:
// TODO : Single views have trouble with measure .
final int spec = View . MeasureSpec . makeMeasureSpec ( 0 , View . MeasureSpec . UNSPECIFIED ) ; view . measure ( spec , spec ) ; final int width = view . getMeasuredWidth ( ) ; final int height = view . getMeasuredHeight ( ) ; view . layout ( 0 , 0 , width , height ) ; final Bitmap bitmap = Bitmap . createBitmap ( width , height , Bitmap . Config . ARGB_8888 ) ; final Canvas canvas = new Canvas ( bitmap ) ; view . draw ( canvas ) ; return BitmapDescriptorFactory . fromBitmap ( bitmap ) ;


signature:
public class FileObservable { /** * Returns an { @ link Observable } that uses NIO { @ link WatchService } ( and a
 * dedicated thread ) to push modified events to an observable that reads and
 * reports new sequences of bytes to a subscriber . The NIO
 * { @ link WatchService } events are sampled according to
 * < code > sampleTimeMs < / code > so that lots of discrete activity on a file
 * ( for example a log file with very frequent entries ) does not prompt an
 * inordinate number of file reads to pick up changes .
 * @ param file
 * the file to tail
 * @ param startPosition
 * start tailing file at position in bytes
 * @ param sampleTimeMs
 * sample time in millis
 * @ param chunkSize
 * max array size of each element emitted by the Observable . Is
 * also used as the buffer size for reading from the file . Try
 * { @ link FileObservable # DEFAULT _ MAX _ BYTES _ PER _ EMISSION } if you
 * don ' t know what to put here .
 * @ return observable of byte arrays */
public final static Observable < byte [ ] > tailFile ( File file , long startPosition , long sampleTimeMs , int chunkSize ) { } }

implementation:
Preconditions . checkNotNull ( file ) ; Observable < Object > events = from ( file , StandardWatchEventKinds . ENTRY_CREATE , StandardWatchEventKinds . ENTRY_MODIFY , StandardWatchEventKinds . OVERFLOW ) // don ' t care about the event details , just that there
// is one
. cast ( Object . class ) // get lines once on subscription so we tail the lines
// in the file at startup
. startWith ( new Object ( ) ) ; return tailFile ( file , startPosition , sampleTimeMs , chunkSize , events ) ;


signature:
public class FileObservable { /** * Returns an { @ link Observable } that uses given given observable to push
 * modified events to an observable that reads and reports new sequences of
 * bytes to a subscriber . The NIO { @ link WatchService } MODIFY and OVERFLOW
 * events are sampled according to < code > sampleTimeMs < / code > so that lots of
 * discrete activity on a file ( for example a log file with very frequent
 * entries ) does not prompt an inordinate number of file reads to pick up
 * changes . File create events are not sampled and are always passed
 * through .
 * @ param file
 * the file to tail
 * @ param startPosition
 * start tailing file at position in bytes
 * @ param sampleTimeMs
 * sample time in millis for MODIFY and OVERFLOW events
 * @ param chunkSize
 * max array size of each element emitted by the Observable . Is
 * also used as the buffer size for reading from the file . Try
 * { @ link FileObservable # DEFAULT _ MAX _ BYTES _ PER _ EMISSION } if you
 * don ' t know what to put here .
 * @ param events
 * trigger a check for file changes . Use
 * { @ link Observable # interval ( long , TimeUnit ) } for example .
 * @ return observable of byte arrays */
public final static Observable < byte [ ] > tailFile ( File file , long startPosition , long sampleTimeMs , int chunkSize , Observable < ? > events ) { } }

implementation:
Preconditions . checkNotNull ( file ) ; return sampleModifyOrOverflowEventsOnly ( events , sampleTimeMs ) // tail file triggered by events
. lift ( new OperatorFileTailer ( file , startPosition , chunkSize ) ) ;


signature:
public class FileObservable { /** * Returns an { @ link Observable } that uses NIO { @ link WatchService } ( and a
 * dedicated thread ) to push modified events to an observable that reads and
 * reports new lines to a subscriber . The NIO WatchService MODIFY and
 * OVERFLOW events are sampled according to < code > sampleTimeMs < / code > so
 * that lots of discrete activity on a file ( for example a log file with
 * very frequent entries ) does not prompt an inordinate number of file reads
 * to pick up changes . File create events are not sampled and are always
 * passed through .
 * @ param file
 * the file to tail
 * @ param startPosition
 * start tailing file at position in bytes
 * @ param sampleTimeMs
 * sample time in millis for MODIFY and OVERFLOW events
 * @ param charset
 * the character set to use to decode the bytes to a string
 * @ return observable of strings */
public final static Observable < String > tailTextFile ( File file , long startPosition , long sampleTimeMs , Charset charset ) { } }

implementation: return toLines ( tailFile ( file , startPosition , sampleTimeMs , DEFAULT_MAX_BYTES_PER_EMISSION ) , charset ) ;


signature:
public class FileObservable { /** * Returns an { @ link Observable } of String that uses the given events stream
 * to trigger checks on file change so that new lines can be read and
 * emitted .
 * @ param file
 * the file to tail , cannot be null
 * @ param startPosition
 * start tailing file at position in bytes
 * @ param chunkSize
 * max array size of each element emitted by the Observable . Is
 * also used as the buffer size for reading from the file . Try
 * { @ link FileObservable # DEFAULT _ MAX _ BYTES _ PER _ EMISSION } if you
 * don ' t know what to put here .
 * @ param charset
 * the character set to use to decode the bytes to a string
 * @ param events
 * trigger a check for file changes . Use
 * { @ link Observable # interval ( long , TimeUnit ) } for example .
 * @ return observable of strings */
public final static Observable < String > tailTextFile ( File file , long startPosition , int chunkSize , Charset charset , Observable < ? > events ) { } }

implementation: Preconditions . checkNotNull ( file ) ; Preconditions . checkNotNull ( charset ) ; Preconditions . checkNotNull ( events ) ; return toLines ( events . lift ( new OperatorFileTailer ( file , startPosition , chunkSize ) ) . onBackpressureBuffer ( ) , charset ) ;


signature:
public class FileObservable { /** * Returns an { @ link Observable } of { @ link WatchEvent } s from a
 * { @ link WatchService } .
 * @ param watchService
 * WatchService to generate events from
 * @ param scheduler
 * schedules polls of the watchService
 * @ param pollDuration
 * duration of each poll
 * @ param pollDurationUnit
 * time unit for the duration of each poll
 * @ param pollInterval
 * interval between polls of the watchService
 * @ param pollIntervalUnit
 * time unit for the interval between polls
 * @ param backpressureStrategy
 * backpressures strategy to apply
 * @ return an observable of WatchEvents from watchService */
public final static Observable < WatchEvent < ? > > from ( WatchService watchService , Scheduler scheduler , long pollDuration , TimeUnit pollDurationUnit , long pollInterval , TimeUnit pollIntervalUnit , BackpressureStrategy backpressureStrategy ) { } }

implementation: Preconditions . checkNotNull ( watchService ) ; Preconditions . checkNotNull ( scheduler ) ; Preconditions . checkNotNull ( pollDurationUnit ) ; Preconditions . checkNotNull ( backpressureStrategy ) ; Observable < WatchEvent < ? > > o = Observable . create ( new OnSubscribeWatchServiceEvents ( watchService , scheduler , pollDuration , pollDurationUnit , pollInterval , pollIntervalUnit ) ) ; if ( backpressureStrategy == BackpressureStrategy . BUFFER ) { return o . onBackpressureBuffer ( ) ; } else if ( backpressureStrategy == BackpressureStrategy . DROP ) return o . onBackpressureDrop ( ) ; else if ( backpressureStrategy == BackpressureStrategy . LATEST ) return o . onBackpressureLatest ( ) ; else throw new RuntimeException ( "unrecognized backpressureStrategy " + backpressureStrategy ) ;


signature:
public class FileObservable { /** * Returns an { @ link Observable } of { @ link WatchEvent } s from a
 * { @ link WatchService } .
 * @ param watchService
 * { @ link WatchService } to generate events for
 * @ return observable of watch events from the watch service */
public final static Observable < WatchEvent < ? > > from ( WatchService watchService ) { } }

implementation: return from ( watchService , rx . schedulers . Schedulers . trampoline ( ) , Long . MAX_VALUE , TimeUnit . MILLISECONDS , 0 , TimeUnit . SECONDS , BackpressureStrategy . BUFFER ) ;