signature:
public class PetiteConfig { /** * Specifies default wiring mode . */
public PetiteConfig setDefaultWiringMode ( final WiringMode defaultWiringMode ) { } }

implementation: if ( ( defaultWiringMode == null ) || ( defaultWiringMode == WiringMode . DEFAULT ) ) { throw new PetiteException ( "Invalid default wiring mode: " + defaultWiringMode ) ; } this . defaultWiringMode = defaultWiringMode ; return this ;


signature:
public class PetiteConfig { /** * Resolves wiring mode by checking if default and < code > null < / code > values . */
protected WiringMode resolveWiringMode ( WiringMode wiringMode ) { } }

implementation: if ( ( wiringMode == null ) || ( wiringMode == WiringMode . DEFAULT ) ) { wiringMode = defaultWiringMode ; } return wiringMode ;


signature:
public class SimpleLogger { /** * Prints error message if level is enabled . */
protected void print ( final Level level , final String message , final Throwable throwable ) { } }

implementation: if ( ! isEnabled ( level ) ) { return ; } StringBuilder msg = new StringBuilder ( ) . append ( slf . getElapsedTime ( ) ) . append ( ' ' ) . append ( '[' ) . append ( level ) . append ( ']' ) . append ( ' ' ) . append ( getCallerClass ( ) ) . append ( ' ' ) . append ( '-' ) . append ( ' ' ) . append ( message ) ; System . out . println ( msg . toString ( ) ) ; if ( throwable != null ) { throwable . printStackTrace ( System . out ) ; }


signature:
public class SimpleLogger { /** * Returns called class . */
protected String getCallerClass ( ) { } }

implementation: Exception exception = new Exception ( ) ; StackTraceElement [ ] stackTrace = exception . getStackTrace ( ) ; for ( StackTraceElement stackTraceElement : stackTrace ) { String className = stackTraceElement . getClassName ( ) ; if ( className . equals ( SimpleLoggerProvider . class . getName ( ) ) ) { continue ; } if ( className . equals ( SimpleLogger . class . getName ( ) ) ) { continue ; } if ( className . equals ( Logger . class . getName ( ) ) ) { continue ; } return shortenClassName ( className ) + '.' + stackTraceElement . getMethodName ( ) + ':' + stackTraceElement . getLineNumber ( ) ; } return "N/A" ;


signature:
public class SimpleLogger { /** * Returns shorten class name . */
protected String shortenClassName ( final String className ) { } }

implementation: int lastDotIndex = className . lastIndexOf ( '.' ) ; if ( lastDotIndex == - 1 ) { return className ; } StringBuilder shortClassName = new StringBuilder ( className . length ( ) ) ; int start = 0 ; while ( true ) { shortClassName . append ( className . charAt ( start ) ) ; int next = className . indexOf ( '.' , start ) ; if ( next == lastDotIndex ) { break ; } start = next + 1 ; shortClassName . append ( '.' ) ; } shortClassName . append ( className . substring ( lastDotIndex ) ) ; return shortClassName . toString ( ) ;


signature:
public class JsonSerializer { /** * Defines custom { @ link jodd . json . TypeJsonSerializer } for given path . */
public JsonSerializer withSerializer ( final String pathString , final TypeJsonSerializer typeJsonSerializer ) { } }

implementation: if ( pathSerializersMap == null ) { pathSerializersMap = new HashMap < > ( ) ; } pathSerializersMap . put ( Path . parse ( pathString ) , typeJsonSerializer ) ; return this ;


signature:
public class JsonSerializer { /** * Defines custom { @ link jodd . json . TypeJsonSerializer } for given type . */
public JsonSerializer withSerializer ( final Class type , final TypeJsonSerializer typeJsonSerializer ) { } }

implementation: if ( typeSerializersMap == null ) { typeSerializersMap = new TypeJsonSerializerMap ( TypeJsonSerializerMap . get ( ) ) ; } typeSerializersMap . register ( type , typeJsonSerializer ) ; return this ;


signature:
public class JsonSerializer { /** * Adds excludes with optional parent including . When parents are included ,
 * for each exclude query its parent will be included .
 * For example , exclude of ' aaa . bb . ccc ' would include it ' s parent : ' aaa . bb ' . */
public JsonSerializer exclude ( final boolean includeParent , final String ... excludes ) { } }

implementation: for ( String exclude : excludes ) { if ( includeParent ) { int dotIndex = exclude . lastIndexOf ( '.' ) ; if ( dotIndex != - 1 ) { PathQuery pathQuery = new PathQuery ( exclude . substring ( 0 , dotIndex ) , true ) ; rules . include ( pathQuery ) ; } } PathQuery pathQuery = new PathQuery ( exclude , false ) ; rules . exclude ( pathQuery ) ; } return this ;


signature:
public class JsonSerializer { /** * Excludes type names . You can disable
 * serialization of properties that are of some type .
 * For example , you can disable properties of < code > InputStream < / code > .
 * You can use wildcards to describe type names . */
public JsonSerializer excludeTypes ( final String ... typeNames ) { } }

implementation: if ( excludedTypeNames == null ) { excludedTypeNames = typeNames ; } else { excludedTypeNames = ArraysUtil . join ( excludedTypeNames , typeNames ) ; } return this ;


signature:
public class JsonSerializer { /** * Excludes types . Supports interfaces and subclasses as well . */
public JsonSerializer excludeTypes ( final Class ... types ) { } }

implementation: if ( excludedTypes == null ) { excludedTypes = types ; } else { excludedTypes = ArraysUtil . join ( excludedTypes , types ) ; } return this ;


signature:
public class JsonSerializer { /** * Serializes object into provided appendable . */
public void serialize ( final Object source , final Appendable target ) { } }

implementation: JsonContext jsonContext = createJsonContext ( target ) ; jsonContext . serialize ( source ) ;


signature:
public class JsonSerializer { /** * Serializes object into source . */
public String serialize ( final Object source ) { } }

implementation: FastCharBuffer fastCharBuffer = new FastCharBuffer ( ) ; serialize ( source , fastCharBuffer ) ; return fastCharBuffer . toString ( ) ;


signature:
public class JsonSerializer { /** * Serializes the object , but returns the { @ link CharSequence } . */
public CharSequence serializeToCharSequence ( final Object source ) { } }

implementation: FastCharBuffer fastCharBuffer = new FastCharBuffer ( ) ; serialize ( source , fastCharBuffer ) ; return fastCharBuffer ;


signature:
public class ObjectUtil { /** * Create object copy using serialization mechanism . */
public static < T extends Serializable > T cloneViaSerialization ( final T obj ) throws IOException , ClassNotFoundException { } }

implementation: FastByteArrayOutputStream bos = new FastByteArrayOutputStream ( ) ; ObjectOutputStream out = null ; ObjectInputStream in = null ; Object objCopy = null ; try { out = new ObjectOutputStream ( bos ) ; out . writeObject ( obj ) ; out . flush ( ) ; byte [ ] bytes = bos . toByteArray ( ) ; in = new ObjectInputStream ( new ByteArrayInputStream ( bytes ) ) ; objCopy = in . readObject ( ) ; } finally { StreamUtil . close ( out ) ; StreamUtil . close ( in ) ; } return ( T ) objCopy ;


signature:
public class ObjectUtil { /** * Writes serializable object to a file . Existing file will be overwritten . */
public static void writeObject ( final File dest , final Object object ) throws IOException { } }

implementation: FileOutputStream fos = null ; BufferedOutputStream bos = null ; ObjectOutputStream oos = null ; try { fos = new FileOutputStream ( dest ) ; bos = new BufferedOutputStream ( fos ) ; oos = new ObjectOutputStream ( bos ) ; oos . writeObject ( object ) ; } finally { StreamUtil . close ( oos ) ; StreamUtil . close ( bos ) ; StreamUtil . close ( fos ) ; }


signature:
public class ObjectUtil { /** * Reads serialized object from the file . */
public static Object readObject ( final File source ) throws IOException , ClassNotFoundException { } }

implementation: Object result = null ; FileInputStream fis = null ; BufferedInputStream bis = null ; ObjectInputStream ois = null ; try { fis = new FileInputStream ( source ) ; bis = new BufferedInputStream ( fis ) ; ois = new ObjectInputStream ( bis ) ; result = ois . readObject ( ) ; } finally { StreamUtil . close ( ois ) ; StreamUtil . close ( bis ) ; StreamUtil . close ( fis ) ; } return result ;


signature:
public class ObjectUtil { /** * Serialize an object to byte array . */
public static byte [ ] objectToByteArray ( final Object obj ) throws IOException { } }

implementation: FastByteArrayOutputStream bos = new FastByteArrayOutputStream ( ) ; ObjectOutputStream oos = null ; try { oos = new ObjectOutputStream ( bos ) ; oos . writeObject ( obj ) ; } finally { StreamUtil . close ( oos ) ; } return bos . toByteArray ( ) ;


signature:
public class ObjectUtil { /** * De - serialize an object from byte array . */
public static Object byteArrayToObject ( final byte [ ] data ) throws IOException , ClassNotFoundException { } }

implementation: Object retObj = null ; ByteArrayInputStream bais = new ByteArrayInputStream ( data ) ; ObjectInputStream ois = null ; try { ois = new ObjectInputStream ( bais ) ; retObj = ois . readObject ( ) ; } finally { StreamUtil . close ( ois ) ; } return retObj ;


signature:
public class DefaultResultSetMapper { /** * { @ inheritDoc } */
@ Override public Class [ ] resolveTables ( ) { } }

implementation:
List < Class > classes = new ArrayList < > ( tableNames . length ) ; String lastTableName = null ; resultColumns . clear ( ) ; for ( int i = 0 ; i < tableNames . length ; i ++ ) { String tableName = tableNames [ i ] ; String columnName = columnNames [ i ] ; if ( tableName == null ) { // maybe JDBC driver does not support it
throw new DbOomException ( dbOomQuery , "Table name missing in meta-data" ) ; } if ( ( ! tableName . equals ( lastTableName ) ) || ( resultColumns . contains ( columnName ) ) ) { resultColumns . clear ( ) ; lastTableName = tableName ; DbEntityDescriptor ded = dbEntityManager . lookupTableName ( tableName ) ; if ( ded == null ) { throw new DbOomException ( dbOomQuery , "Table name not registered: " + tableName ) ; } classes . add ( ded . getType ( ) ) ; } resultColumns . add ( columnName ) ; } return classes . toArray ( new Class [ 0 ] ) ;


signature:
public class DefaultResultSetMapper { /** * Resolves { @ link jodd . db . oom . DbEntityDescriptor } for all given types ,
 * so not to repeat every time . */
protected DbEntityDescriptor [ ] resolveDbEntityDescriptors ( final Class [ ] types ) { } }

implementation: if ( cachedDbEntityDescriptors == null ) { DbEntityDescriptor [ ] descs = new DbEntityDescriptor [ types . length ] ; for ( int i = 0 ; i < types . length ; i ++ ) { Class type = types [ i ] ; if ( type != null ) { descs [ i ] = dbEntityManager . lookupType ( type ) ; } } cachedDbEntityDescriptors = descs ; } return cachedDbEntityDescriptors ;


signature:
public class DefaultResultSetMapper { /** * Creates table names for all specified types .
 * Since this is usually done once per result set , these names are cached .
 * Type name will be < code > null < / code > for simple names , i . e . for all those
 * types that returns < code > null < / code > when used by { @ link DbEntityManager # lookupType ( Class ) } . */
protected String [ ] resolveTypesTableNames ( final Class [ ] types ) { } }

implementation: if ( types != cachedUsedTypes ) { cachedTypesTableNames = createTypesTableNames ( types ) ; cachedUsedTypes = types ; } return cachedTypesTableNames ;


signature:
public class DefaultResultSetMapper { /** * Resolved mapped type names for each type . */
protected String [ ] [ ] resolveMappedTypesTableNames ( final Class [ ] types ) { } }

implementation: if ( cachedMappedNames == null ) { String [ ] [ ] names = new String [ types . length ] [ ] ; for ( int i = 0 ; i < types . length ; i ++ ) { Class type = types [ i ] ; if ( type != null ) { DbEntityDescriptor ded = cachedDbEntityDescriptors [ i ] ; if ( ded != null ) { Class [ ] mappedTypes = ded . getMappedTypes ( ) ; if ( mappedTypes != null ) { names [ i ] = createTypesTableNames ( mappedTypes ) ; } } } } cachedMappedNames = names ; } return cachedMappedNames ;


signature:
public class DefaultResultSetMapper { /** * Creates table names for given types . */
protected String [ ] createTypesTableNames ( final Class [ ] types ) { } }

implementation: String [ ] names = new String [ types . length ] ; for ( int i = 0 ; i < types . length ; i ++ ) { if ( types [ i ] == null ) { names [ i ] = null ; continue ; } DbEntityDescriptor ded = dbEntityManager . lookupType ( types [ i ] ) ; if ( ded != null ) { String tableName = ded . getTableName ( ) ; tableName = tableName . toUpperCase ( ) ; names [ i ] = tableName ; } } return names ;


signature:
public class DefaultResultSetMapper { /** * Reads column value from result set . Since this method may be called more then once for
 * the same column , it caches column values . */
@ SuppressWarnings ( { } }

implementation: "unchecked" } ) protected Object readColumnValue ( final int colNdx , final Class destinationType , final Class < ? extends SqlType > sqlTypeClass , final int columnDbSqlType ) { if ( colNdx != cachedColumnNdx ) { try { SqlType sqlType ; if ( sqlTypeClass != null ) { sqlType = SqlTypeManager . get ( ) . lookupSqlType ( sqlTypeClass ) ; } else { sqlType = SqlTypeManager . get ( ) . lookup ( destinationType ) ; } if ( sqlType != null ) { cachedColumnValue = sqlType . readValue ( resultSet , colNdx + 1 , destinationType , columnDbSqlType ) ; } else { cachedColumnValue = resultSet . getObject ( colNdx + 1 ) ; cachedColumnValue = TypeConverterManager . get ( ) . convertType ( cachedColumnValue , destinationType ) ; } } catch ( SQLException sex ) { throw new DbOomException ( dbOomQuery , "Invalid value for column #" + ( colNdx + 1 ) , sex ) ; } cachedColumnNdx = colNdx ; } return cachedColumnValue ;


signature:
public class DefaultResultSetMapper { /** * { @ inheritDoc } */
@ Override public Object [ ] parseObjects ( final Class ... types ) { } }

implementation:
resultColumns . clear ( ) ; int totalTypes = types . length ; Object [ ] result = new Object [ totalTypes ] ; boolean [ ] resultUsage = new boolean [ totalTypes ] ; DbEntityDescriptor [ ] dbEntityDescriptors = resolveDbEntityDescriptors ( types ) ; String [ ] typesTableNames = resolveTypesTableNames ( types ) ; String [ ] [ ] mappedNames = resolveMappedTypesTableNames ( types ) ; int currentResult = 0 ; cachedColumnNdx = - 1 ; int colNdx = 0 ; while ( colNdx < totalColumns ) { // no more types for mapping ?
if ( currentResult >= totalTypes ) { break ; } // skip columns that doesn ' t map
Class currentType = types [ currentResult ] ; if ( currentType == null ) { colNdx ++ ; currentResult ++ ; resultColumns . clear ( ) ; continue ; } String columnName = columnNames [ colNdx ] ; int columnDbSqlType = columnDbSqlTypes [ colNdx ] ; String tableName = tableNames [ colNdx ] ; String resultTableName = typesTableNames [ currentResult ] ; if ( resultTableName == null ) { // match : simple type
result [ currentResult ] = readColumnValue ( colNdx , currentType , null , columnDbSqlType ) ; resultUsage [ currentResult ] = true ; colNdx ++ ; currentResult ++ ; resultColumns . clear ( ) ; continue ; } // match table
boolean tableMatched = false ; if ( tableName == null ) { tableMatched = true ; } else if ( resultTableName . equals ( tableName ) ) { tableMatched = true ; } else { String [ ] mapped = mappedNames [ currentResult ] ; if ( mapped != null ) { for ( String m : mapped ) { if ( m . equals ( tableName ) ) { tableMatched = true ; break ; } } } } if ( tableMatched ) { if ( ! resultColumns . contains ( columnName ) ) { // DbEntityDescriptor ded = dbEntityManager . lookupType ( currentType ) ;
DbEntityDescriptor ded = dbEntityDescriptors [ currentResult ] ; DbEntityColumnDescriptor dec = ded . findByColumnName ( columnName ) ; String propertyName = ( dec == null ? null : dec . getPropertyName ( ) ) ; // check if a property that matches column name exist
if ( propertyName != null ) { // if current entity instance does not exist ( i . e . we are at the first column
// of some entity ) , create the instance and store it
if ( result [ currentResult ] == null ) { result [ currentResult ] = dbEntityManager . createEntityInstance ( currentType ) ; } /* boolean success = value ! = null ?
 BeanUtil . setDeclaredPropertySilent ( result [ currentResult ] , propertyName , value ) :
 BeanUtil . hasDeclaredProperty ( result [ currentResult ] , propertyName ) ; */
Class type = BeanUtil . declared . getPropertyType ( result [ currentResult ] , propertyName ) ; if ( type != null ) { // match : entity
dec . updateDbSqlType ( columnDbSqlType ) ; // updates column db sql type information for the entity ! ! !
Class < ? extends SqlType > sqlTypeClass = dec . getSqlTypeClass ( ) ; Object value = readColumnValue ( colNdx , type , sqlTypeClass , columnDbSqlType ) ; if ( value != null ) { // inject column value into existing entity
BeanUtil . declared . setProperty ( result [ currentResult ] , propertyName , value ) ; resultUsage [ currentResult ] = true ; } colNdx ++ ; resultColumns . add ( columnName ) ; continue ; } } } } // go to next type , i . e . result
currentResult ++ ; resultColumns . clear ( ) ; } resultColumns . clear ( ) ; for ( int i = 0 ; i < resultUsage . length ; i ++ ) { if ( ! resultUsage [ i ] ) { result [ i ] = null ; } } if ( cacheEntities ) { cacheResultSetEntities ( result ) ; } return result ;


signature:
public class DefaultResultSetMapper { /** * Caches returned entities . Replaces new instances with existing ones . */
protected void cacheResultSetEntities ( final Object [ ] result ) { } }

implementation:
if ( entitiesCache == null ) { entitiesCache = new HashMap < > ( ) ; } for ( int i = 0 ; i < result . length ; i ++ ) { Object object = result [ i ] ; if ( object == null ) { continue ; } DbEntityDescriptor ded = cachedDbEntityDescriptors [ i ] ; if ( ded == null ) { // not a type , continue
continue ; } // calculate key
Object key ; if ( ded . hasIdColumn ( ) ) { // noinspection unchecked
key = ded . getKeyValue ( object ) ; } else { key = object ; } Object cachedObject = entitiesCache . get ( key ) ; if ( cachedObject == null ) { // object is not in the cache , add it
entitiesCache . put ( key , object ) ; } else { // object is in the cache , replace it
result [ i ] = cachedObject ; } }


signature:
public class ProviderResolver { /** * Resolves all providers in the class */
public ProviderDefinition [ ] resolve ( final Class type , final String name ) { } }

implementation:
ClassDescriptor cd = ClassIntrospector . get ( ) . lookup ( type ) ; MethodDescriptor [ ] methods = cd . getAllMethodDescriptors ( ) ; List < ProviderDefinition > list = new ArrayList < > ( ) ; for ( MethodDescriptor methodDescriptor : methods ) { Method method = methodDescriptor . getMethod ( ) ; PetiteProvider petiteProvider = method . getAnnotation ( PetiteProvider . class ) ; if ( petiteProvider == null ) { continue ; } String providerName = petiteProvider . value ( ) ; if ( StringUtil . isBlank ( providerName ) ) { // default provider name
providerName = method . getName ( ) ; if ( providerName . endsWith ( "Provider" ) ) { providerName = StringUtil . substring ( providerName , 0 , - 8 ) ; } } ProviderDefinition providerDefinition ; if ( Modifier . isStatic ( method . getModifiers ( ) ) ) { providerDefinition = new ProviderDefinition ( providerName , method ) ; } else { providerDefinition = new ProviderDefinition ( providerName , name , method ) ; } list . add ( providerDefinition ) ; } ProviderDefinition [ ] providers ; if ( list . isEmpty ( ) ) { providers = ProviderDefinition . EMPTY ; } else { providers = list . toArray ( new ProviderDefinition [ 0 ] ) ; } return providers ;


signature:
public class TableNamingStrategy { /** * Converts entity ( type ) name to table name . */
public String convertEntityNameToTableName ( String entityName ) { } }

implementation: int ndx = entityName . indexOf ( entityNameTerminator ) ; if ( ndx != - 1 ) { entityName = entityName . substring ( 0 , ndx ) ; } StringBuilder tableName = new StringBuilder ( entityName . length ( ) * 2 ) ; if ( prefix != null ) { tableName . append ( prefix ) ; } if ( splitCamelCase ) { String convertedTableName = Format . fromCamelCase ( entityName , separatorChar ) ; tableName . append ( convertedTableName ) ; } else { tableName . append ( entityName ) ; } if ( suffix != null ) { tableName . append ( suffix ) ; } if ( ! changeCase ) { return tableName . toString ( ) ; } return uppercase ? toUppercase ( tableName ) . toString ( ) : toLowercase ( tableName ) . toString ( ) ;


signature:
public class TableNamingStrategy { /** * Converts table name to entity ( type ) name . */
public String convertTableNameToEntityName ( final String tableName ) { } }

implementation: StringBuilder className = new StringBuilder ( tableName . length ( ) ) ; int len = tableName . length ( ) ; int i = 0 ; if ( prefix != null ) { if ( tableName . startsWith ( prefix ) ) { i = prefix . length ( ) ; } } if ( suffix != null ) { if ( tableName . endsWith ( suffix ) ) { len -= suffix . length ( ) ; } } if ( splitCamelCase ) { boolean toUpper = true ; for ( ; i < len ; i ++ ) { char c = tableName . charAt ( i ) ; if ( c == separatorChar ) { toUpper = true ; continue ; } if ( toUpper ) { className . append ( Character . toUpperCase ( c ) ) ; toUpper = false ; } else { className . append ( Character . toLowerCase ( c ) ) ; } } return className . toString ( ) ; } return tableName . substring ( i , len ) ;


signature:
public class TableNamingStrategy { /** * Applies table naming strategy to given table name hint .
 * Returns full table name . */
public String applyToTableName ( final String tableName ) { } }

implementation: String entityName = convertTableNameToEntityName ( tableName ) ; return convertEntityNameToTableName ( entityName ) ;


signature:
public class CoreConnectionPool { /** * { @ inheritDoc } */
@ Override public synchronized void init ( ) { } }

implementation: if ( initialised ) { return ; } if ( log . isInfoEnabled ( ) ) { log . info ( "Core connection pool initialization" ) ; } try { Class . forName ( driver ) ; } catch ( ClassNotFoundException cnfex ) { throw new DbSqlException ( "Database driver not found: " + driver , cnfex ) ; } if ( minConnections > maxConnections ) { minConnections = maxConnections ; } availableConnections = new ArrayList < > ( maxConnections ) ; busyConnections = new ArrayList < > ( maxConnections ) ; for ( int i = 0 ; i < minConnections ; i ++ ) { try { Connection conn = DriverManager . getConnection ( url , user , password ) ; availableConnections . add ( new ConnectionData ( conn ) ) ; } catch ( SQLException sex ) { throw new DbSqlException ( "No database connection" , sex ) ; } } initialised = true ;


signature:
public class CoreConnectionPool { /** * { @ inheritDoc } */
@ Override public synchronized Connection getConnection ( ) { } }

implementation:
if ( availableConnections == null ) { throw new DbSqlException ( "Connection pool is not initialized" ) ; } if ( ! availableConnections . isEmpty ( ) ) { int lastIndex = availableConnections . size ( ) - 1 ; ConnectionData existingConnection = availableConnections . get ( lastIndex ) ; availableConnections . remove ( lastIndex ) ; // If conn on available list is closed ( e . g . , it timed out ) , then remove it from available list
// and repeat the process of obtaining a conn . Also wake up threads that were waiting for a
// conn because maxConnection limit was reached .
long now = System . currentTimeMillis ( ) ; boolean isValid = isConnectionValid ( existingConnection , now ) ; if ( ! isValid ) { if ( log . isDebugEnabled ( ) ) { log . debug ( "Pooled connection not valid, resetting" ) ; } notifyAll ( ) ; // freed up a spot for anybody waiting
return getConnection ( ) ; } else { if ( log . isDebugEnabled ( ) ) { log . debug ( "Returning valid pooled connection" ) ; } busyConnections . add ( existingConnection ) ; existingConnection . lastUsed = now ; return existingConnection . connection ; } } if ( log . isDebugEnabled ( ) ) { log . debug ( "No more available connections" ) ; } // no available connections
if ( ( ( availableConnections . size ( ) + busyConnections . size ( ) ) < maxConnections ) && ! connectionPending ) { makeBackgroundConnection ( ) ; } else if ( ! waitIfBusy ) { throw new DbSqlException ( "Connection limit reached: " + maxConnections ) ; } // wait for either a new conn to be established ( if you called makeBackgroundConnection ) or for
// an existing conn to be freed up .
try { wait ( ) ; } catch ( InterruptedException ie ) { // ignore
} // someone freed up a conn , so try again .
return getConnection ( ) ;


signature:
public class CoreConnectionPool { /** * Checks if existing connection is valid and available . It may happens
 * that if connection is not used for a while it becomes inactive ,
 * although not technically closed . */
private boolean isConnectionValid ( final ConnectionData connectionData , final long now ) { } }

implementation: if ( ! validateConnection ) { return true ; } if ( now < connectionData . lastUsed + validationTimeout ) { return true ; } Connection conn = connectionData . connection ; if ( validationQuery == null ) { try { return ! conn . isClosed ( ) ; } catch ( SQLException sex ) { return false ; } } boolean valid = true ; Statement st = null ; try { st = conn . createStatement ( ) ; st . execute ( validationQuery ) ; } catch ( SQLException sex ) { valid = false ; } finally { if ( st != null ) { try { st . close ( ) ; } catch ( SQLException ignore ) { } } } return valid ;


signature:
public class CoreConnectionPool { /** * Close all the connections . Use with caution : be sure no connections are in
 * use before calling . Note that you are not < i > required < / i > to call this
 * when done with a ConnectionPool , since connections are guaranteed to be
 * closed when garbage collected . But this method gives more control
 * regarding when the connections are closed . */
@ Override public synchronized void close ( ) { } }

implementation: if ( log . isInfoEnabled ( ) ) { log . info ( "Core connection pool shutdown" ) ; } closeConnections ( availableConnections ) ; availableConnections = new ArrayList < > ( maxConnections ) ; closeConnections ( busyConnections ) ; busyConnections = new ArrayList < > ( maxConnections ) ;


signature:
public class ServletDispatcherActionResult { /** * Renders the view by dispatching to the target JSP . */
@ Override protected void renderView ( final ActionRequest actionRequest , final String target ) throws Exception { } }

implementation:
HttpServletRequest request = actionRequest . getHttpServletRequest ( ) ; HttpServletResponse response = actionRequest . getHttpServletResponse ( ) ; RequestDispatcher dispatcher = request . getRequestDispatcher ( target ) ; if ( dispatcher == null ) { response . sendError ( SC_NOT_FOUND , "Result not found: " + target ) ; // should never happened
return ; } // If we ' re included , then include the view , otherwise do forward .
// This allow the page to , for example , set content type .
if ( DispatcherUtil . isPageIncluded ( request , response ) ) { dispatcher . include ( request , response ) ; } else { dispatcher . forward ( request , response ) ; }


signature:
public class ServletDispatcherActionResult { /** * Locates target using path with various extensions appended . */
@ Override protected String locateTarget ( final ActionRequest actionRequest , String path ) { } }

implementation: String target ; if ( path . endsWith ( StringPool . SLASH ) ) { path = path + defaultViewPageName ; } for ( final String ext : defaultViewExtensions ) { target = path + ext ; if ( targetExists ( actionRequest , target ) ) { return target ; } } return null ;


signature:
public class ServletDispatcherActionResult { /** * Returns < code > true < / code > if target exists . */
protected boolean targetExists ( final ActionRequest actionRequest , final String target ) { } }

implementation: if ( log . isDebugEnabled ( ) ) { log . debug ( "target check: " + target ) ; } final ServletContext servletContext = actionRequest . getHttpServletRequest ( ) . getServletContext ( ) ; try { return servletContext . getResource ( target ) != null ; } catch ( MalformedURLException ignore ) { return false ; }


signature:
public class BufferResponseWrapper { /** * Returns buffered writer if buffering is enabled ,
 * otherwise returns the original writer . */
@ Override public PrintWriter getWriter ( ) throws IOException { } }

implementation: preResponseCommit ( ) ; if ( buffer == null ) { return getResponse ( ) . getWriter ( ) ; } return buffer . getWriter ( ) ;


signature:
public class BufferResponseWrapper { /** * Returns buffered output stream if buffering is enabled ,
 * otherwise returns the original stream . */
@ Override public ServletOutputStream getOutputStream ( ) throws IOException { } }

implementation: preResponseCommit ( ) ; if ( buffer == null ) { return getResponse ( ) . getOutputStream ( ) ; } return buffer . getOutputStream ( ) ;


signature:
public class BufferResponseWrapper { /** * Returns buffered content as chars , no matter if stream or writer is used .
 * Returns < code > null < / code > if buffering was not enabled . */
public char [ ] getBufferContentAsChars ( ) { } }

implementation:
if ( buffer == null ) { return null ; } if ( ! buffer . isUsingStream ( ) ) { return buffer . toCharArray ( ) ; } byte [ ] content = buffer . toByteArray ( ) ; String encoding = getContentTypeEncoding ( ) ; if ( encoding == null ) { // assume default encoding
return CharUtil . toCharArray ( content ) ; } else { return CharUtil . toCharArray ( content , encoding ) ; }


signature:
public class BufferResponseWrapper { /** * Writes content to original output stream , using either output stream or writer , depending
 * on how the content was buffered . It is assumed that provided content is a modified
 * wrapped content . */
public void writeContentToResponse ( final char [ ] content ) throws IOException { } }

implementation: if ( buffer == null ) { return ; } if ( buffer . isUsingStream ( ) ) { ServletOutputStream outputStream = getResponse ( ) . getOutputStream ( ) ; String encoding = getContentTypeEncoding ( ) ; if ( encoding == null ) { outputStream . write ( CharUtil . toByteArray ( content ) ) ; } else { outputStream . write ( CharUtil . toByteArray ( content , encoding ) ) ; } outputStream . flush ( ) ; } else { Writer out = getResponse ( ) . getWriter ( ) ; out . write ( content ) ; out . flush ( ) ; }


signature:
public class BufferResponseWrapper { /** * Writes ( unmodified ) buffered content , using either output stream or writer .
 * May be used for writing the unmodified response . Of course , you may
 * { @ link # print ( String ) modify } buffered data by altering the buffer content . */
public void writeContentToResponse ( ) throws IOException { } }

implementation: if ( buffer == null ) { return ; } if ( buffer . isUsingStream ( ) ) { ServletOutputStream outputStream = getResponse ( ) . getOutputStream ( ) ; outputStream . write ( buffer . toByteArray ( ) ) ; outputStream . flush ( ) ; } else { Writer out = getResponse ( ) . getWriter ( ) ; out . write ( buffer . toCharArray ( ) ) ; out . flush ( ) ; }


signature:
public class BufferResponseWrapper { /** * Sets the content type and enables or disables buffering . */
@ Override public void setContentType ( final String type ) { } }

implementation: super . setContentType ( type ) ; contentTypeResolver = new ContentTypeHeaderResolver ( type ) ; if ( bufferContentType ( type , contentTypeResolver . getMimeType ( ) , contentTypeResolver . getEncoding ( ) ) ) { enableBuffering ( ) ; } else { disableBuffering ( ) ; }


signature:
public class BufferResponseWrapper { /** * Prevents setting content - length if buffering enabled . */
@ Override public void setHeader ( final String name , final String value ) { } }

implementation: String lowerName = name . toLowerCase ( ) ; if ( lowerName . equals ( CONTENT_TYPE ) ) { setContentType ( value ) ; } else if ( buffer == null || ! lowerName . equals ( CONTENT_LENGTH ) ) { super . setHeader ( name , value ) ; }


signature:
public class BufferResponseWrapper { /** * Prevents setting content - length if buffering enabled . */
@ Override public void setIntHeader ( final String name , final int value ) { } }

implementation: if ( buffer == null || ! name . equalsIgnoreCase ( CONTENT_LENGTH ) ) { super . setIntHeader ( name , value ) ; }


signature:
public class BufferResponseWrapper { /** * Appends string to the buffer . */
public void print ( final String string ) throws IOException { } }

implementation:
if ( isBufferStreamBased ( ) ) { String encoding = getContentTypeEncoding ( ) ; byte [ ] bytes ; if ( encoding == null ) { bytes = string . getBytes ( ) ; } else { bytes = string . getBytes ( encoding ) ; } buffer . getOutputStream ( ) . write ( bytes ) ; return ; } // make sure at least writer is initialized
buffer . getWriter ( ) . write ( string ) ;


signature:
public class AuthAction { /** * Authenticate user and start user session . */
protected JsonResult login ( ) { } }

implementation:
T authToken ; authToken = loginViaBasicAuth ( servletRequest ) ; if ( authToken == null ) { authToken = loginViaRequestParams ( servletRequest ) ; } if ( authToken == null ) { log . warn ( "Login failed." ) ; return JsonResult . of ( HttpStatus . error401 ( ) . unauthorized ( "Login failed." ) ) ; } log . info ( "login OK!" ) ; final UserSession < T > userSession = new UserSession < > ( authToken , userAuth . tokenValue ( authToken ) ) ; userSession . start ( servletRequest , servletResponse ) ; // return token
return tokenAsJson ( authToken ) ;


signature:
public class AuthAction { /** * Prepares the JSON payload that carries on the token value . */
protected JsonResult tokenAsJson ( final T authToken ) { } }

implementation: final JsonObject jsonObject = new JsonObject ( ) ; jsonObject . put ( "token" , userAuth . tokenValue ( authToken ) ) ; return JsonResult . of ( jsonObject ) ;


signature:
public class AuthAction { /** * Tries to login user with form data . Returns session object , otherwise returns < code > null < / code > . */
protected T loginViaRequestParams ( final HttpServletRequest servletRequest ) { } }

implementation: final String username = servletRequest . getParameter ( PARAM_USERNAME ) . trim ( ) ; if ( StringUtil . isEmpty ( username ) ) { return null ; } final String password = servletRequest . getParameter ( PARAM_PASSWORD ) . trim ( ) ; return userAuth . login ( username , password ) ;


signature:
public class AuthAction { /** * Tries to login user with basic authentication . */
protected T loginViaBasicAuth ( final HttpServletRequest servletRequest ) { } }

implementation: final String username = ServletUtil . resolveAuthUsername ( servletRequest ) ; if ( username == null ) { return null ; } final String password = ServletUtil . resolveAuthPassword ( servletRequest ) ; return userAuth . login ( username , password ) ;


signature:
public class AuthAction { /** * Logout hook . */
protected JsonResult logout ( ) { } }

implementation: log . debug ( "logout user" ) ; UserSession . stop ( servletRequest , servletResponse ) ; return JsonResult . of ( HttpStatus . ok ( ) ) ;


signature:
public class LazyMap { /** * - - - - - utils */
private static < V > Set < V > set ( final int size , final V [ ] array ) { } }

implementation: int index = 0 ; final Set < V > set = new HashSet < > ( ) ; for ( final V v : array ) { set . add ( v ) ; index ++ ; if ( index == size ) { break ; } } return set ;


signature:
public class FileUtil { /** * Simple factory for { @ link File } objects but with home resolving . */
public static File file ( String fileName ) { } }

implementation: fileName = StringUtil . replace ( fileName , USER_HOME , SystemUtil . info ( ) . getHomeDir ( ) ) ; return new File ( fileName ) ;


signature:
public class FileUtil { /** * Converts { @ link File } { @ link URL } s to { @ link File } . Ignores other schemes and returns { @ code null } . */
public static File toFile ( final URL url ) { } }

implementation: String fileName = toFileName ( url ) ; if ( fileName == null ) { return null ; } return file ( fileName ) ;


signature:
public class FileUtil { /** * Converts { @ link File } { @ link URL } s to file name . Accepts only { @ link URL } s with ' file ' protocol .
 * Otherwise , for other schemes returns { @ code null } .
 * @ param url { @ link URL } to convert
 * @ return file name */
public static String toFileName ( final URL url ) { } }

implementation: if ( ( url == null ) || ! ( url . getProtocol ( ) . equals ( FILE_PROTOCOL ) ) ) { return null ; } String filename = url . getFile ( ) . replace ( '/' , File . separatorChar ) ; return URLDecoder . decode ( filename , encoding ( ) ) ;


signature:
public class FileUtil { /** * Returns a file of either a folder or a containing archive . */
public static File toContainerFile ( final URL url ) { } }

implementation: String protocol = url . getProtocol ( ) ; if ( protocol . equals ( FILE_PROTOCOL ) ) { return toFile ( url ) ; } String path = url . getPath ( ) ; return new File ( URI . create ( path . substring ( ZERO , path . lastIndexOf ( "!/" ) ) ) ) ;


signature:
public class FileUtil { /** * Creates all directories at once .
 * @ param dirs Directories to make .
 * @ throws IOException if cannot create directory . */
public static File mkdirs ( final File dirs ) throws IOException { } }

implementation: if ( dirs . exists ( ) ) { checkIsDirectory ( dirs ) ; return dirs ; } return checkCreateDirectory ( dirs ) ;


signature:
public class FileUtil { /** * Creates single directory .
 * @ throws IOException if cannot create directory . */
public static File mkdir ( final File dir ) throws IOException { } }

implementation: if ( dir . exists ( ) ) { checkIsDirectory ( dir ) ; return dir ; } return checkCreateDirectory ( dir ) ;


signature:
public class FileUtil { /** * Implements the Unix " touch " utility . It creates a new { @ link File }
 * with size 0 or , if the { @ link File } exists already , it is opened and
 * closed without modifying it , but updating the { @ link File } date and time . */
public static void touch ( final File file ) throws IOException { } }

implementation: if ( ! file . exists ( ) ) { StreamUtil . close ( new FileOutputStream ( file , false ) ) ; } file . setLastModified ( System . currentTimeMillis ( ) ) ;


signature:
public class FileUtil { /** * Copies a { @ link File } to another { @ link File } .
 * @ param srcFile Source { @ link File } .
 * @ param destFile Destination { @ link File } .
 * @ throws IOException if cannot copy */
public static void copyFile ( final File srcFile , final File destFile ) throws IOException { } }

implementation: checkFileCopy ( srcFile , destFile ) ; _copyFile ( srcFile , destFile ) ;


signature:
public class FileUtil { /** * Internal file copy when most of the pre - checking has passed .
 * @ param srcFile Source { @ link File } .
 * @ param destFile Destination { @ link File } .
 * @ throws IOException if cannot copy */
private static void _copyFile ( final File srcFile , final File destFile ) throws IOException { } }

implementation:
if ( destFile . exists ( ) ) { if ( destFile . isDirectory ( ) ) { throw new IOException ( "Destination '" + destFile + "' is a directory" ) ; } } // do copy file
FileInputStream input = null ; FileOutputStream output = null ; try { input = new FileInputStream ( srcFile ) ; output = new FileOutputStream ( destFile , false ) ; StreamUtil . copy ( input , output ) ; } finally { StreamUtil . close ( output ) ; StreamUtil . close ( input ) ; } // done
if ( srcFile . length ( ) != destFile . length ( ) ) { throw new IOException ( "Copy file failed of '" + srcFile + "' to '" + destFile + "' due to different sizes" ) ; } destFile . setLastModified ( srcFile . lastModified ( ) ) ;


signature:
public class FileUtil { /** * Copies a { @ link File } to directory with specified copy params and returns copied destination . */
public static File copyFileToDir ( final File srcFile , final File destDir ) throws IOException { } }

implementation: checkExistsAndDirectory ( destDir ) ; File destFile = file ( destDir , srcFile . getName ( ) ) ; copyFile ( srcFile , destFile ) ; return destFile ;


signature:
public class FileUtil { /** * Copies directory with specified copy params .
 * @ see # _ copyDirectory ( File , File ) */
public static void copyDir ( final File srcDir , final File destDir ) throws IOException { } }

implementation: checkDirCopy ( srcDir , destDir ) ; _copyDirectory ( srcDir , destDir ) ;


signature:
public class FileUtil { /** * Moves a { @ link File } .
 * @ param srcFile Source { @ link File } .
 * @ param destFile Destination directory .
 * @ throws IOException */
private static void _moveFile ( final File srcFile , final File destFile ) throws IOException { } }

implementation: if ( destFile . exists ( ) ) { checkIsFile ( destFile ) ; destFile . delete ( ) ; } final boolean rename = srcFile . renameTo ( destFile ) ; if ( ! rename ) { _copyFile ( srcFile , destFile ) ; srcFile . delete ( ) ; }


signature:
public class FileUtil { /** * Moves a file to a directory .
 * @ param srcFile Source { @ link File } .
 * @ param destDir Destination directory .
 * @ throws IOException if there is an error during move . */
public static File moveFileToDir ( final File srcFile , final File destDir ) throws IOException { } }

implementation: checkExistsAndDirectory ( destDir ) ; return moveFile ( srcFile , file ( destDir , srcFile . getName ( ) ) ) ;


signature:
public class FileUtil { /** * Moves a directory .
 * @ param srcDest Source directory
 * @ param destDir Destination directory .
 * @ throws IOException if there is an error during move . */
private static void _moveDirectory ( final File srcDest , File destDir ) throws IOException { } }

implementation: if ( destDir . exists ( ) ) { checkIsDirectory ( destDir ) ; destDir = file ( destDir , destDir . getName ( ) ) ; destDir . mkdir ( ) ; } final boolean rename = srcDest . renameTo ( destDir ) ; if ( ! rename ) { _copyDirectory ( srcDest , destDir ) ; deleteDir ( srcDest ) ; }


signature:
public class FileUtil { /** * Cleans a directory without deleting it .
 * @ param destDir destination to clean .
 * @ throws IOException if something went wrong . */
public static void cleanDir ( final File destDir ) throws IOException { } }

implementation: checkExists ( destDir ) ; checkIsDirectory ( destDir ) ; File [ ] files = destDir . listFiles ( ) ; if ( files == null ) { throw new IOException ( "Failed to list contents of: " + destDir ) ; } IOException exception = null ; for ( File file : files ) { try { if ( file . isDirectory ( ) ) { deleteDir ( file ) ; } else { file . delete ( ) ; } } catch ( IOException ioex ) { exception = ioex ; continue ; } } if ( exception != null ) { throw exception ; }


signature:
public class FileUtil { /** * Reads UTF file content as char array .
 * @ param file { @ link File } to read .
 * @ return array of characters .
 * @ throws IOException if something went wrong . */
public static char [ ] readUTFChars ( final File file ) throws IOException { } }

implementation: checkExists ( file ) ; checkIsFile ( file ) ; UnicodeInputStream in = unicodeInputStreamOf ( file ) ; try { return StreamUtil . readChars ( in , detectEncoding ( in ) ) ; } finally { StreamUtil . close ( in ) ; }


signature:
public class FileUtil { /** * Reads file content as char array .
 * @ param file { @ link File } to read .
 * @ param encoding Encoding to use .
 * @ return array of characters .
 * @ throws IOException if something went wrong . */
public static char [ ] readChars ( final File file , final String encoding ) throws IOException { } }

implementation: checkExists ( file ) ; checkIsFile ( file ) ; InputStream in = streamOf ( file , encoding ) ; try { return StreamUtil . readChars ( in , encoding ) ; } finally { StreamUtil . close ( in ) ; }


signature:
public class FileUtil { /** * Write characters . append = false
 * @ see # outChars ( File , char [ ] , String , boolean ) */
public static void writeChars ( final File dest , final char [ ] data , final String encoding ) throws IOException { } }

implementation: outChars ( dest , data , encoding , false ) ;


signature:
public class FileUtil { /** * Writes characters to { @ link File } destination .
 * @ param dest destination { @ link File }
 * @ param data Data as a { @ link String }
 * @ param encoding Encoding as a { @ link String }
 * @ param append { @ code true } if appending ; { @ code false } if { @ link File } should be overwritten .
 * @ throws IOException if something went wrong . */
protected static void outChars ( final File dest , final char [ ] data , final String encoding , final boolean append ) throws IOException { } }

implementation: if ( dest . exists ( ) ) { checkIsFile ( dest ) ; } Writer out = new BufferedWriter ( StreamUtil . outputStreamWriterOf ( new FileOutputStream ( dest , append ) , encoding ) ) ; try { out . write ( data ) ; } finally { StreamUtil . close ( out ) ; }


signature:
public class FileUtil { /** * Detects optional BOM and reads UTF { @ link String } from a { @ link File } .
 * If BOM is missing , UTF - 8 is assumed .
 * @ param file { @ link File } to read .
 * @ return String in UTF encoding .
 * @ throws IOException if copy to { @ link InputStream } errors .
 * @ see # unicodeInputStreamOf ( File )
 * @ see StreamUtil # copy ( InputStream , String ) */
public static String readUTFString ( final File file ) throws IOException { } }

implementation: UnicodeInputStream in = unicodeInputStreamOf ( file ) ; try { return StreamUtil . copy ( in , detectEncoding ( in ) ) . toString ( ) ; } finally { StreamUtil . close ( in ) ; }


signature:
public class FileUtil { /** * Detects optional BOM and reads UTF { @ link String } from an { @ link InputStream } .
 * If BOM is missing , UTF - 8 is assumed .
 * @ param inputStream { @ link InputStream } to read .
 * @ return String in UTF encoding .
 * @ throws IOException if copy to { @ link InputStream } errors .
 * @ see # unicodeInputStreamOf ( File )
 * @ see StreamUtil # copy ( InputStream , String ) */
public static String readUTFString ( final InputStream inputStream ) throws IOException { } }

implementation: UnicodeInputStream in = null ; try { in = new UnicodeInputStream ( inputStream , null ) ; return StreamUtil . copy ( in , detectEncoding ( in ) ) . toString ( ) ; } finally { StreamUtil . close ( in ) ; }


signature:
public class FileUtil { /** * Reads { @ link File } content as { @ link String } encoded in provided encoding .
 * For UTF encoded files , detects optional BOM characters .
 * @ param file { @ link File } to read .
 * @ param encoding Encoding to use .
 * @ return String representing { @ link File } content .
 * @ throws IOException if copy to { @ link InputStream } errors .
 * @ see # streamOf ( File , String )
 * @ see StreamUtil # copy ( InputStream , String ) */
public static String readString ( final File file , final String encoding ) throws IOException { } }

implementation: checkExists ( file ) ; checkIsFile ( file ) ; InputStream in = streamOf ( file , encoding ) ; try { return StreamUtil . copy ( in , encoding ) . toString ( ) ; } finally { StreamUtil . close ( in ) ; }


signature:
public class FileUtil { /** * Writes String . append = false
 * @ see # outString ( File , String , String , boolean ) */
public static void writeString ( final File dest , final String data , final String encoding ) throws IOException { } }

implementation: outString ( dest , data , encoding , false ) ;


signature:
public class FileUtil { /** * Appends String . append = true
 * @ see # outString ( File , String , String , boolean ) */
public static void appendString ( final File dest , final String data , final String encoding ) throws IOException { } }

implementation: outString ( dest , data , encoding , true ) ;


signature:
public class FileUtil { /** * Writes data using encoding to { @ link File } .
 * @ param dest destination { @ link File }
 * @ param data Data as a { @ link String }
 * @ param encoding Encoding as a { @ link String }
 * @ param append { @ code true } if appending ; { @ code false } if { @ link File } should be overwritten .
 * @ throws IOException if something went wrong . */
protected static void outString ( final File dest , final String data , final String encoding , final boolean append ) throws IOException { } }

implementation: if ( dest . exists ( ) ) { checkIsFile ( dest ) ; } FileOutputStream out = null ; try { out = new FileOutputStream ( dest , append ) ; out . write ( data . getBytes ( encoding ) ) ; } finally { StreamUtil . close ( out ) ; }


signature:
public class FileUtil { /** * Write { @ link InputStream } in to { @ link FileOutputStream } .
 * @ param out { @ link FileOutputStream } to write to .
 * @ param in { @ link InputStream } to read .
 * @ throws IOException if there is an issue reading / writing . */
public static void writeStream ( final FileOutputStream out , final InputStream in ) throws IOException { } }

implementation: try { StreamUtil . copy ( in , out ) ; } finally { StreamUtil . close ( out ) ; }


signature:
public class FileUtil { /** * Reads lines from source { @ link File } with specified encoding and returns lines as { @ link String } s in array .
 * @ param file { @ link File } to read .
 * @ param encoding Endoing to use .
 * @ return array of Strings which represents lines in the { @ link File } .
 * @ throws IOException if { @ link File } does not exist or is not a { @ link File } or there is an issue reading
 * the { @ link File } . */
public static String [ ] readLines ( final File file , final String encoding ) throws IOException { } }

implementation: checkExists ( file ) ; checkIsFile ( file ) ; List < String > list = new ArrayList < > ( ) ; InputStream in = streamOf ( file , encoding ) ; try { BufferedReader br = new BufferedReader ( StreamUtil . inputStreamReadeOf ( in , encoding ) ) ; String strLine ; while ( ( strLine = br . readLine ( ) ) != null ) { list . add ( strLine ) ; } } finally { StreamUtil . close ( in ) ; } return list . toArray ( new String [ 0 ] ) ;


signature:
public class FileUtil { /** * Read file and returns byte array with contents .
 * @ param file { @ link File } to read
 * @ param count number of bytes to read
 * @ return byte array from { @ link File } contents .
 * @ throws IOException if not a { @ link File } or { @ link File } does not exist or file size is
 * larger than { @ link Integer # MAX _ VALUE } . */
public static byte [ ] readBytes ( final File file , final int count ) throws IOException { } }

implementation: checkExists ( file ) ; checkIsFile ( file ) ; long numToRead = file . length ( ) ; if ( numToRead >= Integer . MAX_VALUE ) { throw new IOException ( "File is larger then max array size" ) ; } if ( count > NEGATIVE_ONE && count < numToRead ) { numToRead = count ; } byte [ ] bytes = new byte [ ( int ) numToRead ] ; RandomAccessFile randomAccessFile = new RandomAccessFile ( file , "r" ) ; randomAccessFile . readFully ( bytes ) ; randomAccessFile . close ( ) ; return bytes ;


signature:
public class FileUtil { /** * Write bytes . append = false
 * @ see # outBytes ( File , byte [ ] , int , int , boolean ) */
public static void writeBytes ( final File dest , final byte [ ] data , final int off , final int len ) throws IOException { } }

implementation: outBytes ( dest , data , off , len , false ) ;


signature:
public class FileUtil { /** * Appends bytes . append = true
 * @ see # outBytes ( File , byte [ ] , int , int , boolean ) */
public static void appendBytes ( final File dest , final byte [ ] data , final int off , final int len ) throws IOException { } }

implementation: outBytes ( dest , data , off , len , true ) ;


signature:
public class FileUtil { /** * Writes data to { @ link File } destination .
 * @ param dest destination { @ link File }
 * @ param data Data as a { @ link String }
 * @ param off the start offset in the data .
 * @ param len the number of bytes to write .
 * @ param append { @ code true } if appending ; { @ code false } if { @ link File } should be overwritten .
 * @ throws IOException if something went wrong . */
protected static void outBytes ( final File dest , final byte [ ] data , final int off , final int len , final boolean append ) throws IOException { } }

implementation: if ( dest . exists ( ) ) { checkIsFile ( dest ) ; } FileOutputStream out = null ; try { out = new FileOutputStream ( dest , append ) ; out . write ( data , off , len ) ; } finally { StreamUtil . close ( out ) ; }


signature:
public class FileUtil { /** * - - - - - equals content */
public static boolean compare ( final String file1 , final String file2 ) throws IOException { } }

implementation: return compare ( file ( file1 ) , file ( file2 ) ) ;


signature:
public class FileUtil { /** * Compare the contents of two { @ link File } s to determine if they are equal or
 * not .
 * This method checks to see if the two { @ link File } s are different lengths
 * or if they point to the same { @ link File } , before resorting to byte - by - byte
 * comparison of the contents .
 * Code origin : Avalon */
public static boolean compare ( final File one , final File two ) throws IOException { } }

implementation: boolean file1Exists = one . exists ( ) ; if ( file1Exists != two . exists ( ) ) { return false ; } if ( ! file1Exists ) { return true ; } if ( ( ! one . isFile ( ) ) || ( ! two . isFile ( ) ) ) { throw new IOException ( "Only files can be compared" ) ; } if ( one . length ( ) != two . length ( ) ) { return false ; } if ( equals ( one , two ) ) { return true ; } InputStream input1 = null ; InputStream input2 = null ; try { input1 = new FileInputStream ( one ) ; input2 = new FileInputStream ( two ) ; return StreamUtil . compare ( input1 , input2 ) ; } finally { StreamUtil . close ( input1 ) ; StreamUtil . close ( input2 ) ; }


signature:
public class FileUtil { /** * Uses { @ link File # lastModified ( ) } for reference .
 * @ see # isNewer ( File , long ) */
public static boolean isNewer ( final File file , final File reference ) { } }

implementation: checkReferenceExists ( reference ) ; return isNewer ( file , reference . lastModified ( ) ) ;


signature:
public class FileUtil { /** * Uses { @ link File # lastModified ( ) } for reference .
 * @ see # isOlder ( File , long ) */
public static boolean isOlder ( final File file , final File reference ) { } }

implementation: checkReferenceExists ( reference ) ; return isOlder ( file , reference . lastModified ( ) ) ;


signature:
public class FileUtil { /** * Smart copy . If source is a directory , copy it to destination .
 * Otherwise , if destination is directory , copy source file to it .
 * Otherwise , try to copy source file to destination file .
 * @ param src source { @ link File }
 * @ param dest destination { @ link File }
 * @ throws IOException if there is an error copying .
 * @ see # copyDir ( File , File )
 * @ see # copyFileToDir ( File , File )
 * @ see # copyFile ( File , File ) */
public static void copy ( final File src , final File dest ) throws IOException { } }

implementation: if ( src . isDirectory ( ) ) { copyDir ( src , dest ) ; return ; } if ( dest . isDirectory ( ) ) { copyFileToDir ( src , dest ) ; return ; } copyFile ( src , dest ) ;


signature:
public class FileUtil { /** * Smart move . If source is a directory , move it to destination .
 * Otherwise , if destination is directory , move source { @ link File } to it .
 * Otherwise , try to move source { @ link File } to destination { @ link File } .
 * @ param src source { @ link File }
 * @ param dest destination { @ link File }
 * @ throws IOException if there is an error moving .
 * @ see # moveDir ( File , File )
 * @ see # moveFileToDir ( File , File )
 * @ see # moveFile ( File , File ) */
public static void move ( final File src , final File dest ) throws IOException { } }

implementation: if ( src . isDirectory ( ) ) { moveDir ( src , dest ) ; return ; } if ( dest . isDirectory ( ) ) { moveFileToDir ( src , dest ) ; return ; } moveFile ( src , dest ) ;


signature:
public class FileUtil { /** * Smart delete of destination file or directory .
 * @ throws IOException if there is an issue deleting the file / directory .
 * @ see # deleteFile ( File )
 * @ see # deleteDir ( File ) */
public static void delete ( final File dest ) throws IOException { } }

implementation: if ( dest . isDirectory ( ) ) { deleteDir ( dest ) ; return ; } deleteFile ( dest ) ;


signature:
public class FileUtil { /** * Check if one { @ link File } is an ancestor of second one .
 * @ param strict if c then this method returns { @ code true } if ancestor
 * and { @ link File } are equal
 * @ return { @ code true } if ancestor is parent of { @ link File } ; otherwise , { @ code false } */
public static boolean isAncestor ( final File ancestor , final File file , final boolean strict ) { } }

implementation: File parent = strict ? getParentFile ( file ) : file ; while ( true ) { if ( parent == null ) { return false ; } if ( parent . equals ( ancestor ) ) { return true ; } parent = getParentFile ( parent ) ; }


signature:
public class FileUtil { /** * Returns parent for the file . The method correctly
 * processes " . " and " . . " in { @ link File } names . The name
 * remains relative if was relative before .
 * Returns { @ code null } if the { @ link File } has no parent .
 * @ param file { @ link File }
 * @ return { @ code null } if the { @ link File } has no parent . */
public static File getParentFile ( final File file ) { } }

implementation: int skipCount = ZERO ; File parentFile = file ; while ( true ) { parentFile = parentFile . getParentFile ( ) ; if ( parentFile == null ) { return null ; } if ( StringPool . DOT . equals ( parentFile . getName ( ) ) ) { continue ; } if ( StringPool . DOTDOT . equals ( parentFile . getName ( ) ) ) { skipCount ++ ; continue ; } if ( skipCount > ZERO ) { skipCount -- ; continue ; } return parentFile ; }


signature:
public class FileUtil { /** * Checks if file and its ancestors are acceptable by using { @ link FileFilter # accept ( File ) } .
 * @ param file { @ link File } to check .
 * @ param fileFilter { @ link FileFilter } to use .
 * @ return if file and its ancestors are acceptable */
public static boolean isFilePathAcceptable ( File file , final FileFilter fileFilter ) { } }

implementation: do { if ( fileFilter != null && ! fileFilter . accept ( file ) ) { return false ; } file = file . getParentFile ( ) ; } while ( file != null ) ; return true ;


signature:
public class FileUtil { /** * Creates temporary directory .
 * @ see # createTempFile ( String , String , File ) */
public static File createTempDirectory ( final String prefix , final String suffix , final File tempDir ) throws IOException { } }

implementation: File file = createTempFile ( prefix , suffix , tempDir ) ; file . delete ( ) ; file . mkdir ( ) ; return file ;


signature:
public class FileUtil { /** * Creates temporary { @ link File } .
 * @ param prefix The prefix string to be used in generating the file ' s
 * name ; must be at least three characters long
 * @ param suffix The suffix string to be used in generating the file ' s
 * name ; may be { @ code null } , in which case the
 * suffix { @ code " . tmp " } will be used
 * @ param tempDir The directory in which the file is to be created , or
 * { @ code null } if the default temporary - file
 * directory is to be used
 * @ param create If { @ code create } is set to { @ code true } { @ link File } will be
 * physically created on the file system . Otherwise , it will be created and then
 * deleted - trick that will make temp { @ link File } exist only if they are used .
 * @ return File */
public static File createTempFile ( final String prefix , final String suffix , final File tempDir , final boolean create ) throws IOException { } }

implementation: File file = createTempFile ( prefix , suffix , tempDir ) ; file . delete ( ) ; if ( create ) { file . createNewFile ( ) ; } return file ;


signature:
public class FileUtil { /** * Creates temporary { @ link File } . Wraps Java method and repeats creation several times
 * if something fails .
 * @ param prefix The prefix string to be used in generating the file ' s
 * name ; must be at least three characters long
 * @ param suffix The suffix string to be used in generating the file ' s
 * name ; may be { @ code null } , in which case the
 * suffix { @ code " . tmp " } will be used
 * @ param tempDir The directory in which the file is to be created , or
 * { @ code null } if the default temporary - file
 * directory is to be used */
public static File createTempFile ( final String prefix , final String suffix , final File tempDir ) throws IOException { } }

implementation:
int exceptionsCount = ZERO ; while ( true ) { try { return File . createTempFile ( prefix , suffix , tempDir ) . getCanonicalFile ( ) ; } catch ( IOException ioex ) { // fixes java . io . WinNTFileSystem . createFileExclusively access denied
if ( ++ exceptionsCount >= 50 ) { throw ioex ; } } }


signature:
public class FileUtil { /** * Checks the start of the file for ASCII control characters
 * @ param file { @ link File }
 * @ return true if the the start of the { @ link File } is ASCII control characters . */
public static boolean isBinary ( final File file ) throws IOException { } }

implementation: byte [ ] bytes = readBytes ( file , 128 ) ; for ( byte b : bytes ) { if ( b < 32 && b != 9 && b != 10 && b != 13 ) { return true ; } } return false ;


signature:
public class FileUtil { /** * Returns either new { @ link FileInputStream } or new { @ link UnicodeInputStream } .
 * @ return either { @ link FileInputStream } or { @ link UnicodeInputStream } .
 * @ throws IOException if something went wrong .
 * @ see # unicodeInputStreamOf ( InputStream , String ) */
private static InputStream streamOf ( final File file , final String encoding ) throws IOException { } }

implementation: InputStream in = new FileInputStream ( file ) ; if ( encoding . startsWith ( "UTF" ) ) { in = unicodeInputStreamOf ( in , encoding ) ; } return in ;


signature:
public class FileUtil { /** * Detect encoding on { @ link UnicodeInputStream } by using { @ link UnicodeInputStream # getDetectedEncoding ( ) } .
 * @ param in { @ link UnicodeInputStream }
 * @ return UTF encoding as a String . If encoding could not be detected , defaults to { @ link StringPool # UTF _ 8 } .
 * @ see UnicodeInputStream # getDetectedEncoding ( ) */
private static String detectEncoding ( final UnicodeInputStream in ) { } }

implementation: String encoding = in . getDetectedEncoding ( ) ; if ( encoding == null ) { encoding = StringPool . UTF_8 ; } return encoding ;


signature:
public class FileUtil { /** * Checks if { @ link File } exists . Throws IllegalArgumentException if not .
 * @ param file { @ link File }
 * @ throws IllegalArgumentException if file does not exist . */
private static void checkReferenceExists ( final File file ) throws IllegalArgumentException { } }

implementation: try { checkExists ( file ) ; } catch ( FileNotFoundException e ) { throw new IllegalArgumentException ( "Reference file not found: " + file ) ; }


signature:
public class FileUtil { /** * Checks if directory can be created . Throws IOException if it cannot .
 * This actually creates directory ( and its ancestors ) ( as per { @ link File # mkdirs ( ) } } ) .
 * @ param dir Directory
 * @ throws IOException if directory cannot be created . */
private static File checkCreateDirectory ( final File dir ) throws IOException { } }

implementation: if ( ! dir . mkdirs ( ) ) { throw new IOException ( MSG_CANT_CREATE + dir ) ; } return dir ;


signature:
public class FileUtil { /** * Checks that srcDir exists , that it is a directory and if srcDir and destDir are not equal .
 * @ param srcDir Source directory
 * @ param destDir Destination directory
 * @ throws IOException if any of the above conditions are not true . */
private static void checkDirCopy ( final File srcDir , final File destDir ) throws IOException { } }

implementation: checkExists ( srcDir ) ; checkIsDirectory ( srcDir ) ; if ( equals ( srcDir , destDir ) ) { throw new IOException ( "Source '" + srcDir + "' and destination '" + destDir + "' are equal" ) ; }


signature:
public class FileUtil { /** * Checks that file copy can occur .
 * @ param srcFile Source { @ link File }
 * @ param destFile Destination { @ link File }
 * @ throws IOException if srcFile does not exist or is not a file or
 * srcFile and destFile are equal or cannot create ancestor directories . */
private static void checkFileCopy ( final File srcFile , final File destFile ) throws IOException { } }

implementation: checkExists ( srcFile ) ; checkIsFile ( srcFile ) ; if ( equals ( srcFile , destFile ) ) { throw new IOException ( "Files '" + srcFile + "' and '" + destFile + "' are equal" ) ; } File destParent = destFile . getParentFile ( ) ; if ( destParent != null && ! destParent . exists ( ) ) { checkCreateDirectory ( destParent ) ; }


signature:
public class FastBooleanBuffer { /** * Appends another fast buffer to this one . */
public FastBooleanBuffer append ( final FastBooleanBuffer buff ) { } }

implementation: if ( buff . offset == 0 ) { return this ; } append ( buff . buffer , 0 , buff . offset ) ; return this ;


signature:
public class Cli { /** * Prints the usage line . */
public void printUsage ( final String commandName ) { } }

implementation: final StringBuilder usage = new StringBuilder ( commandName ) ; for ( final Option option : options ) { if ( option . shortName != null ) { usage . append ( " [-" ) . append ( option . shortName ) . append ( "]" ) ; } else if ( option . longName != null ) { usage . append ( " [--" ) . append ( option . longName ) . append ( "]" ) ; } } for ( final Param param : params ) { usage . append ( " " ) . append ( param . label ) ; } System . out . println ( usage ) ;


signature:
public class ActionsManager { /** * Resolves action method for given action class ane method name . */
public Method resolveActionMethod ( final Class < ? > actionClass , final String methodName ) { } }

implementation: MethodDescriptor methodDescriptor = ClassIntrospector . get ( ) . lookup ( actionClass ) . getMethodDescriptor ( methodName , false ) ; if ( methodDescriptor == null ) { throw new MadvocException ( "Public method not found: " + actionClass . getSimpleName ( ) + "#" + methodName ) ; } return methodDescriptor . getMethod ( ) ;


signature:
public class ActionsManager { /** * Registers action with provided action class and method name .
 * @ see # registerAction ( Class , Method , ActionDefinition ) */
public ActionRuntime registerAction ( final Class actionClass , final String actionMethodName , final ActionDefinition actionDefinition ) { } }

implementation: Method actionMethod = resolveActionMethod ( actionClass , actionMethodName ) ; return registerAction ( actionClass , actionMethod , actionDefinition ) ;


signature:
public class ActionsManager { /** * Registration main point . Does two things :
 * < ul >
 * < li > { @ link jodd . madvoc . component . ActionMethodParser # parse ( Class , java . lang . reflect . Method , ActionDefinition ) parse action }
 * and creates { @ link ActionRuntime } < / li >
 * < li > { @ link # registerActionRuntime ( ActionRuntime ) registers } created { @ link ActionRuntime } < / li >
 * < / ul >
 * Returns created { @ link ActionRuntime } .
 * @ see # registerActionRuntime ( ActionRuntime ) */
public ActionRuntime registerAction ( final Class actionClass , final Method actionMethod , final ActionDefinition actionDefinition ) { } }

implementation: final ActionRuntime actionRuntime = actionMethodParser . parse ( actionClass , actionMethod , actionDefinition ) ; if ( actionRuntime == null ) { return null ; } return registerActionRuntime ( actionRuntime ) ;


signature:
public class ActionsManager { /** * Registers manually created { @ link ActionRuntime action runtime configurations } .
 * Optionally , if action path with the same name already exist ,
 * exception will be thrown . */
public ActionRuntime registerActionRuntime ( final ActionRuntime actionRuntime ) { } }

implementation:
final String actionPath = actionRuntime . getActionPath ( ) ; final String method = actionRuntime . getActionMethod ( ) ; log . debug ( ( ) -> "Madvoc action: " + ifNotNull ( method , m -> m + " " ) + actionRuntime . getActionPath ( ) + " => " + actionRuntime . createActionString ( ) ) ; final RouteChunk routeChunk = routes . registerPath ( method , actionPath ) ; if ( routeChunk . value ( ) != null ) { // existing chunk
if ( detectDuplicatePathsEnabled ) { throw new MadvocException ( "Duplicate action path for [" + actionRuntime + "] occupied by: [" + routeChunk . value ( ) + "]" ) ; } } else { actionsCount ++ ; } routeChunk . bind ( actionRuntime ) ; // finally
runtimes . put ( actionRuntime . createActionString ( ) , actionRuntime ) ; // async check
if ( actionRuntime . isAsync ( ) ) { asyncMode = true ; } return actionRuntime ;


signature:
public class ActionsManager { /** * - - - - - look - up */
public ActionRuntime lookup ( final String method , final String [ ] actionPath ) { } }

implementation: return routes . lookup ( method , actionPath ) ;


signature:
public class ActionsManager { /** * Registers new path alias . */
public void registerPathAlias ( final String alias , final String path ) { } }

implementation: final String existing = pathAliases . put ( alias , path ) ; if ( existing != null ) { throw new MadvocException ( "Duplicated alias detected: [" + alias + "] for paths: " + path + ", " + existing ) ; }


signature:
public class LoopIterator { /** * Iterates to next value at the beginning of the loop . */
public boolean next ( ) { } }

implementation: if ( ! looping ) { return false ; } if ( last ) { return false ; } if ( count == 0 ) { value = start ; first = true ; } else { value += step ; first = false ; } count ++ ; last = isLastIteration ( value + step ) ; return true ;


signature:
public class CharArraySequence { /** * Static constructor that creates a char sequence by making a copy of provided char array . */
public static CharArraySequence from ( final char [ ] value , final int offset , final int len ) { } }

implementation: final char [ ] buffer = new char [ value . length ] ; System . arraycopy ( value , offset , buffer , 0 , len ) ; return new CharArraySequence ( buffer ) ;


signature:
public class FastShortBuffer { /** * Appends another fast buffer to this one . */
public FastShortBuffer append ( final FastShortBuffer buff ) { } }


signature:
public class DelegateAdvice { /** * Looks up for method in target object and invokes it using reflection . */
public Object execute ( ) throws Exception { } }

implementation:
String methodName = ProxyTarget . targetMethodName ( ) ; Class [ ] argTypes = ProxyTarget . createArgumentsClassArray ( ) ; Object [ ] args = ProxyTarget . createArgumentsArray ( ) ; // lookup method on target object class ( and not # targetClass ! ( )
Class type = _target . getClass ( ) ; Method method = type . getMethod ( methodName , argTypes ) ; // remember context classloader
ClassLoader contextClassLoader = Thread . currentThread ( ) . getContextClassLoader ( ) ; Object result ; try { // change class loader
Thread . currentThread ( ) . setContextClassLoader ( type . getClassLoader ( ) ) ; // invoke
result = method . invoke ( _target , args ) ; } finally { // return context classloader
Thread . currentThread ( ) . setContextClassLoader ( contextClassLoader ) ; } return ProxyTarget . returnValue ( result ) ;


signature:
public class JoyScanner { /** * Defines class and it ' s classloader to scan . This is not required in Java8
 * and would not hurt anything if called . However , for Java9 , you should
 * pass < i > any < / i > user - application class , so Jodd can figure out the real
 * class path to scan . */
@ Override public JoyScanner scanClasspathOf ( final Class applicationClass ) { } }

implementation: requireNotStarted ( classScanner ) ; appClasses . add ( applicationClass ) ; return this ;


signature:
public class JoyScanner { /** * Shortcut for { @ link # scanClasspathOf ( Class ) } . */
@ Override public JoyScanner scanClasspathOf ( final Object applicationObject ) { } }

implementation: requireNotStarted ( classScanner ) ; return scanClasspathOf ( applicationObject . getClass ( ) ) ;


signature:
public class JoyScanner { /** * Configures scanner class finder . Works for all three scanners :
 * Petite , DbOom and Madvoc . All scanners by default include all jars ,
 * but exclude all entries . */
@ Override public void start ( ) { } }

implementation:
initLogger ( ) ; log . info ( "SCANNER start ----------" ) ; classScanner = new ClassScanner ( ) { @ Override protected void scanJarFile ( final File file ) { log . debug ( "Scanning jar: " + file ) ; super . scanJarFile ( file ) ; } @ Override protected void scanClassPath ( final File root ) { log . debug ( "Scanning path: " + root ) ; super . scanClassPath ( root ) ; } } ; if ( log . isDebugEnabled ( ) ) { log . debug ( "Scan entries: " + Converter . get ( ) . toString ( includedEntries ) ) ; log . debug ( "Scan jars: " + Converter . get ( ) . toString ( includedJars ) ) ; log . debug ( "Scan exclude jars: " + Converter . get ( ) . toString ( excludedJars ) ) ; log . debug ( "Scan ignore exception: " + ignoreExceptions ) ; } classScanner . excludeCommonEntries ( ) ; classScanner . excludeCommonJars ( ) ; classScanner . excludeJars ( excludedJars . toArray ( new String [ 0 ] ) ) ; if ( includedEntries . isEmpty ( ) && includedJars . isEmpty ( ) ) { // nothing was explicitly included
classScanner . excludeAllEntries ( false ) ; } else { // something was included by user
classScanner . excludeAllEntries ( true ) ; includedEntries . add ( "jodd.*" ) ; } classScanner . detectEntriesMode ( true ) . includeEntries ( includedEntries . toArray ( new String [ 0 ] ) ) . includeJars ( includedJars . toArray ( new String [ 0 ] ) ) . ignoreException ( ignoreExceptions ) . scanDefaultClasspath ( ) ; appClasses . forEach ( clazz -> classScanner . scan ( ClassPathURLs . of ( null , clazz ) ) ) ; log . info ( "SCANNER OK!" ) ;


signature:
public class HtmlStaplerTagAdapter { /** * - - - - - javascripts */
@ Override public void script ( final Tag tag , final CharSequence body ) { } }

implementation: if ( ! insideConditionalComment ) { String src = Util . toString ( tag . getAttributeValue ( "src" ) ) ; if ( src == null ) { super . script ( tag , body ) ; return ; } if ( jsBundleAction . acceptLink ( src ) ) { String link = jsBundleAction . processLink ( src ) ; if ( link != null ) { tag . setAttributeValue ( "src" , link ) ; super . script ( tag , body ) ; } return ; } } super . script ( tag , body ) ;


signature:
public class HtmlStaplerTagAdapter { /** * - - - - - conditional comments */
@ Override public void condComment ( final CharSequence expression , final boolean isStartingTag , final boolean isHidden , final boolean isHiddenEndTag ) { } }

implementation: insideConditionalComment = isStartingTag ; super . condComment ( expression , isStartingTag , isHidden , isHiddenEndTag ) ;


signature:
public class HtmlStaplerTagAdapter { /** * Post process final content . Required for < code > RESOURCE _ ONLY < / code > strategy . */
public char [ ] postProcess ( char [ ] content ) { } }

implementation: content = jsBundleAction . replaceBundleId ( content ) ; content = cssBundleAction . replaceBundleId ( content ) ; return content ;


signature:
public class UncheckedException { /** * Wraps checked exceptions in a < code > UncheckedException < / code > .
 * Unchecked exceptions are not wrapped . */
public static < V > V callAndWrapException ( final Callable < V > callable ) { } }

implementation: try { return callable . call ( ) ; } catch ( IOException ioex ) { throw new UncheckedIOException ( ioex ) ; } catch ( RuntimeException rtex ) { throw rtex ; } catch ( Exception t ) { throw new UncheckedException ( t ) ; }


signature:
public class UncheckedException { /** * Wraps checked exceptions in a < code > UncheckedException < / code > .
 * Unchecked exceptions are not wrapped . */
public static void runAndWrapException ( final CallableVoid callable ) { } }

implementation: try { callable . call ( ) ; } catch ( IOException ioex ) { throw new UncheckedIOException ( ioex ) ; } catch ( RuntimeException rtex ) { throw rtex ; } catch ( Exception t ) { throw new UncheckedException ( t ) ; }


signature:
public class Scanner { /** * Finds a character in some range and returns its index .
 * Returns < code > - 1 < / code > if character is not found . */
protected final int find ( final char target , int from , final int end ) { } }

implementation: while ( from < end ) { if ( input [ from ] == target ) { break ; } from ++ ; } return ( from == end ) ? - 1 : from ;


signature:
public class Scanner { /** * Finds character buffer in some range and returns its index .
 * Returns < code > - 1 < / code > if character is not found . */
protected final int find ( final char [ ] target , int from , final int end ) { } }

implementation: while ( from < end ) { if ( match ( target , from ) ) { break ; } from ++ ; } return ( from == end ) ? - 1 : from ;


signature:
public class Scanner { /** * Matches char buffer with content on given location . */
protected final boolean match ( final char [ ] target , final int ndx ) { } }

implementation: if ( ndx + target . length >= total ) { return false ; } int j = ndx ; for ( int i = 0 ; i < target . length ; i ++ , j ++ ) { if ( input [ j ] != target [ i ] ) { return false ; } } return true ;


signature:
public class Scanner { /** * Matches char buffer given in uppercase with content at current location , that will
 * be converted to upper case to make case - insensitive matching . */
public final boolean matchUpperCase ( final char [ ] uppercaseTarget ) { } }

implementation: if ( ndx + uppercaseTarget . length > total ) { return false ; } int j = ndx ; for ( int i = 0 ; i < uppercaseTarget . length ; i ++ , j ++ ) { final char c = CharUtil . toUpperAscii ( input [ j ] ) ; if ( c != uppercaseTarget [ i ] ) { return false ; } } return true ;


signature:
public class Scanner { /** * Creates char sub - sequence from the input . */
protected final CharSequence charSequence ( final int from , final int to ) { } }

implementation: if ( from == to ) { return CharArraySequence . EMPTY ; } return CharArraySequence . of ( input , from , to - from ) ;


signature:
public class Scanner { /** * Calculates { @ link Position current position } : offset , line and column . */
protected Position position ( final int position ) { } }

implementation: int line ; int offset ; int lastNewLineOffset ; if ( position > lastOffset ) { line = 1 ; offset = 0 ; lastNewLineOffset = 0 ; } else { line = lastLine ; offset = lastOffset ; lastNewLineOffset = lastLastNewLineOffset ; } while ( offset < position ) { final char c = input [ offset ] ; if ( c == '\n' ) { line ++ ; lastNewLineOffset = offset + 1 ; } offset ++ ; } lastOffset = offset ; lastLine = line ; lastLastNewLineOffset = lastNewLineOffset ; return new Position ( position , line , position - lastNewLineOffset + 1 ) ;


signature:
public class LeanJtxWorker { /** * Requests for transaction and returns non - null value < b > only < / b > when new transaction
 * is created ! When < code > null < / code > is returned , transaction may be get by
 * { @ link # getCurrentTransaction ( ) } .
 * @ see jodd . jtx . JtxTransactionManager # requestTransaction ( jodd . jtx . JtxTransactionMode ) */
public JtxTransaction maybeRequestTransaction ( final JtxTransactionMode txMode , final Object scope ) { } }

implementation: if ( txMode == null ) { return null ; } JtxTransaction currentTx = txManager . getTransaction ( ) ; JtxTransaction requestedTx = txManager . requestTransaction ( txMode , scope ) ; if ( currentTx == requestedTx ) { return null ; } return requestedTx ;


signature:
public class LeanJtxWorker { /** * Commits transaction if created in the same level where this method is invoked .
 * Returns < code > true < / code > if transaction was actually committed or < code > false < / code >
 * if transaction was not created on this level . */
public boolean maybeCommitTransaction ( final JtxTransaction tx ) { } }

implementation: if ( tx == null ) { return false ; } log . debug ( "commit tx" ) ; tx . commit ( ) ; return true ;


signature:
public class LeanJtxWorker { /** * Rollbacks transaction if created in the same scope where this method is invoked .
 * If not , current transaction is marked for rollback .
 * Returns < code > true < / code > if transaction was actually roll backed . */
public boolean markOrRollbackTransaction ( JtxTransaction tx , final Throwable cause ) { } }

implementation: if ( tx == null ) { tx = getCurrentTransaction ( ) ; if ( tx == null ) { return false ; } log . debug ( "set rollback only tx" ) ; tx . setRollbackOnly ( cause ) ; return false ; } log . debug ( "rollback tx" ) ; tx . rollback ( ) ; return true ;


signature:
public class ClassPathURLs { /** * Returns urls for the classloader .
 * @ param classLoader classloader in which to find urls
 * @ return list of urls or { @ code null } if not found */
public static URL [ ] of ( ClassLoader classLoader , Class clazz ) { } }

implementation: if ( clazz == null ) { clazz = ClassPathURLs . class ; } if ( classLoader == null ) { classLoader = clazz . getClassLoader ( ) ; } final Set < URL > urls = new LinkedHashSet < > ( ) ; while ( classLoader != null ) { if ( classLoader instanceof URLClassLoader ) { URLClassLoader urlClassLoader = ( URLClassLoader ) classLoader ; URL [ ] allURLS = urlClassLoader . getURLs ( ) ; Collections . addAll ( urls , allURLS ) ; break ; } URL classUrl = classModuleUrl ( classLoader , clazz ) ; if ( classUrl != null ) { urls . add ( classUrl ) ; } classUrl = classModuleUrl ( classLoader , ClassPathURLs . class ) ; if ( classUrl != null ) { urls . add ( classUrl ) ; } ModuleDescriptor moduleDescriptor = clazz . getModule ( ) . getDescriptor ( ) ; if ( moduleDescriptor != null ) { moduleDescriptor . requires ( ) . forEach ( req -> { ModuleLayer . boot ( ) . findModule ( req . name ( ) ) . ifPresent ( mod -> { ClassLoader moduleClassLoader = mod . getClassLoader ( ) ; if ( moduleClassLoader != null ) { URL url = moduleClassLoader . getResource ( MANIFEST ) ; if ( url != null ) { url = fixManifestUrl ( url ) ; urls . add ( url ) ; } } } ) ; } ) ; } classLoader = classLoader . getParent ( ) ; } return urls . toArray ( new URL [ 0 ] ) ;


signature:
public class Base32Benchmark { /** * - - - - - Apache Commons Codec - Base32 */
@ Benchmark public String encode_Apache_Base32 ( ) { } }

implementation: return new org . apache . commons . codec . binary . Base32 ( false ) . encodeAsString ( to_be_encoded ) ;


signature:
public class Email { /** * Appends BCC address .
 * @ param to { @ link EmailAddress } to add .
 * @ return this */
public Email bcc ( final EmailAddress to ) { } }

implementation: this . bcc = ArraysUtil . append ( this . bcc , to ) ; return _this ( ) ;


signature:
public class Email { /** * Appends BCC address .
 * @ param personalName personal name .
 * @ param bcc email address .
 * @ return this
 * @ see # bcc ( EmailAddress ) */
public Email bcc ( final String personalName , final String bcc ) { } }

implementation: return bcc ( new EmailAddress ( personalName , bcc ) ) ;


signature:
public class Email { /** * Appends one or more BCC addresses .
 * @ param bccs vararg of { @ link EmailAddress } es to set .
 * @ return this */
public Email bcc ( final EmailAddress ... bccs ) { } }

implementation: this . bcc = ArraysUtil . join ( this . bcc , valueOrEmptyArray ( bccs ) ) ; return _this ( ) ;


signature:
public class AdaptiveFileUploadFactory { /** * { @ inheritDoc } */
@ Override public FileUpload create ( final MultipartRequestInputStream input ) { } }

implementation: return new AdaptiveFileUpload ( input , memoryThreshold , uploadPath , maxFileSize , breakOnError , fileExtensions , allowFileExtensions ) ;


signature:
public class TypeJsonSerializerMap { /** * Registers default set of { @ link jodd . json . TypeJsonSerializer serializers } . */
public void registerDefaults ( ) { } }

implementation:
// main
map . put ( Object . class , new ObjectJsonSerializer ( ) ) ; map . put ( Map . class , new MapJsonSerializer ( ) ) ; map . put ( Iterable . class , new IterableJsonSerializer ( ) ) ; map . put ( JsonObject . class , new JsonObjectSerializer ( ) ) ; map . put ( JsonArray . class , new JsonArraySerializer ( ) ) ; // arrays
map . put ( int [ ] . class , new IntArrayJsonSerializer ( ) ) ; map . put ( long [ ] . class , new LongArrayJsonSerializer ( ) ) ; map . put ( double [ ] . class , new DoubleArrayJsonSerializer ( ) ) ; map . put ( float [ ] . class , new FloatArrayJsonSerializer ( ) ) ; map . put ( boolean [ ] . class , new BooleanArrayJsonSerializer ( ) ) ; map . put ( byte [ ] . class , new ByteArrayJsonSerializer ( ) ) ; map . put ( Integer [ ] . class , new ArraysJsonSerializer < Integer > ( ) { @ Override protected int getLength ( final Integer [ ] array ) { return array . length ; } @ Override protected Integer get ( final Integer [ ] array , final int index ) { return array [ index ] ; } } ) ; map . put ( Long [ ] . class , new ArraysJsonSerializer < Long > ( ) { @ Override protected int getLength ( final Long [ ] array ) { return array . length ; } @ Override protected Long get ( final Long [ ] array , final int index ) { return array [ index ] ; } } ) ; map . put ( Arrays . class , new ArraysJsonSerializer ( ) ) ; // strings
TypeJsonSerializer jsonSerializer = new CharSequenceJsonSerializer ( ) ; map . put ( String . class , jsonSerializer ) ; map . put ( StringBuilder . class , jsonSerializer ) ; map . put ( CharSequence . class , jsonSerializer ) ; // number
jsonSerializer = new NumberJsonSerializer ( ) ; map . put ( Number . class , jsonSerializer ) ; map . put ( Integer . class , jsonSerializer ) ; map . put ( int . class , jsonSerializer ) ; map . put ( Long . class , jsonSerializer ) ; map . put ( long . class , jsonSerializer ) ; DoubleJsonSerializer doubleJsonSerializer = new DoubleJsonSerializer ( ) ; map . put ( Double . class , doubleJsonSerializer ) ; map . put ( double . class , doubleJsonSerializer ) ; FloatJsonSerializer floatJsonSerializer = new FloatJsonSerializer ( ) ; map . put ( Float . class , floatJsonSerializer ) ; map . put ( float . class , floatJsonSerializer ) ; map . put ( BigInteger . class , jsonSerializer ) ; map . put ( BigDecimal . class , jsonSerializer ) ; // other
map . put ( Boolean . class , new BooleanJsonSerializer ( ) ) ; map . put ( boolean . class , new BooleanJsonSerializer ( ) ) ; map . put ( Date . class , new DateJsonSerializer ( ) ) ; map . put ( Calendar . class , new CalendarJsonSerializer ( ) ) ; map . put ( JulianDate . class , new JulianDateSerializer ( ) ) ; map . put ( LocalDateTime . class , new LocalDateTimeSerializer ( ) ) ; map . put ( LocalDate . class , new LocalDateSerializer ( ) ) ; map . put ( LocalTime . class , new LocalTimeSerializer ( ) ) ; map . put ( Enum . class , new EnumJsonSerializer ( ) ) ; map . put ( File . class , new FileJsonSerializer ( FileJsonSerializer . Type . PATH ) ) ; // map . putUnsafe ( ) ; ( Collection . class , new CollectionJsonSerializer ( ) ) ;
jsonSerializer = new CharacterJsonSerializer ( ) ; map . put ( Character . class , jsonSerializer ) ; map . put ( char . class , jsonSerializer ) ; map . put ( UUID . class , new UUIDJsonSerializer ( ) ) ; map . put ( Class . class , new ClassJsonSerializer ( ) ) ; // clear cache
cache . clear ( ) ;


signature:
public class TypeJsonSerializerMap { /** * Registers new serializer . */
public void register ( final Class type , final TypeJsonSerializer typeJsonSerializer ) { } }

implementation: map . put ( type , typeJsonSerializer ) ; cache . clear ( ) ;


signature:
public class TypeJsonSerializerMap { /** * Get type serializer from map . First the current map is used .
 * If element is missing , default map will be used , if exist . */
protected TypeJsonSerializer lookupSerializer ( final Class type ) { } }

implementation: TypeJsonSerializer tjs = map . get ( type ) ; if ( tjs == null ) { if ( defaultSerializerMap != null ) { tjs = defaultSerializerMap . map . get ( type ) ; } } return tjs ;


signature:
public class MultipartStreamParser { /** * - - - - - load and extract */
protected void putFile ( final String name , final FileUpload value ) { } }

implementation: if ( requestFiles == null ) { requestFiles = new HashMap < > ( ) ; } FileUpload [ ] fileUploads = requestFiles . get ( name ) ; if ( fileUploads != null ) { fileUploads = ArraysUtil . append ( fileUploads , value ) ; } else { fileUploads = new FileUpload [ ] { value } ; } requestFiles . put ( name , fileUploads ) ;


signature:
public class MultipartStreamParser { /** * Extracts uploaded files and parameters from the request data . */
public void parseRequestStream ( final InputStream inputStream , final String encoding ) throws IOException { } }

implementation:
setParsed ( ) ; MultipartRequestInputStream input = new MultipartRequestInputStream ( inputStream ) ; input . readBoundary ( ) ; while ( true ) { FileUploadHeader header = input . readDataHeader ( encoding ) ; if ( header == null ) { break ; } if ( header . isFile ) { String fileName = header . fileName ; if ( fileName . length ( ) > 0 ) { if ( header . contentType . indexOf ( "application/x-macbinary" ) > 0 ) { input . skipBytes ( 128 ) ; } } FileUpload newFile = fileUploadFactory . create ( input ) ; newFile . processStream ( ) ; if ( fileName . length ( ) == 0 ) { // file was specified , but no name was provided , therefore it was not uploaded
if ( newFile . getSize ( ) == 0 ) { newFile . size = - 1 ; } } putFile ( header . formFieldName , newFile ) ; } else { // no file , therefore it is regular form parameter .
FastByteArrayOutputStream fbos = new FastByteArrayOutputStream ( ) ; input . copyAll ( fbos ) ; String value = encoding != null ? new String ( fbos . toByteArray ( ) , encoding ) : new String ( fbos . toByteArray ( ) ) ; putParameter ( header . formFieldName , value ) ; } input . skipBytes ( 1 ) ; input . mark ( 1 ) ; // read byte , but may be end of stream
int nextByte = input . read ( ) ; if ( nextByte == - 1 || nextByte == '-' ) { input . reset ( ) ; break ; } input . reset ( ) ; }


signature:
public class MultipartStreamParser { /** * Returns single value of a parameter . If parameter name is used for
 * more then one parameter , only the first one will be returned .
 * @ return parameter value , or < code > null < / code > if not found */
public String getParameter ( final String paramName ) { } }

implementation: if ( requestParameters == null ) { return null ; } String [ ] values = requestParameters . get ( paramName ) ; if ( ( values != null ) && ( values . length > 0 ) ) { return values [ 0 ] ; } return null ;


signature:
public class MultipartStreamParser { /** * Returns all values all of the values the given request parameter has . */
public String [ ] getParameterValues ( final String paramName ) { } }

implementation: if ( requestParameters == null ) { return null ; } return requestParameters . get ( paramName ) ;


signature:
public class MultipartStreamParser { /** * Returns uploaded file .
 * @ param paramName parameter name of the uploaded file
 * @ return uploaded file or < code > null < / code > if parameter name not found */
public FileUpload getFile ( final String paramName ) { } }

implementation: if ( requestFiles == null ) { return null ; } FileUpload [ ] values = requestFiles . get ( paramName ) ; if ( ( values != null ) && ( values . length > 0 ) ) { return values [ 0 ] ; } return null ;


signature:
public class MultipartStreamParser { /** * Returns all uploaded files the given request parameter has . */
public FileUpload [ ] getFiles ( final String paramName ) { } }

implementation: if ( requestFiles == null ) { return null ; } return requestFiles . get ( paramName ) ;


signature:
public class CharacterEncodingFilter { /** * Place this filter into service .
 * @ param filterConfig The filter configuration object */
@ Override public void init ( final FilterConfig filterConfig ) { } }

implementation: this . filterConfig = filterConfig ; this . encoding = filterConfig . getInitParameter ( "encoding" ) ; if ( this . encoding == null ) { this . encoding = JoddCore . encoding ; } this . ignore = Converter . get ( ) . toBooleanValue ( filterConfig . getInitParameter ( "ignore" ) , true ) ;


signature:
public class TemplateParser { /** * Parses template and returns generated sql builder . */
public void parse ( final DbSqlBuilder sqlBuilder , final String template ) { } }

implementation:
int length = template . length ( ) ; int last = 0 ; while ( true ) { int mark = template . indexOf ( '$' , last ) ; if ( mark == - 1 ) { if ( last < length ) { sqlBuilder . appendRaw ( template . substring ( last ) ) ; } break ; } int escapesCount = countEscapes ( template , mark ) ; // check if escaped
if ( escapesCount > 0 ) { boolean isEscaped = escapesCount % 2 != 0 ; int escapesToAdd = escapesCount >> 1 ; sqlBuilder . appendRaw ( template . substring ( last , mark - escapesCount + escapesToAdd ) + '$' ) ; if ( isEscaped ) { last = mark + 1 ; continue ; } } else { sqlBuilder . appendRaw ( template . substring ( last , mark ) ) ; } int end ; if ( template . startsWith ( MACRO_TABLE , mark ) ) { mark += MACRO_TABLE . length ( ) ; end = findMacroEnd ( template , mark ) ; onTable ( sqlBuilder , template . substring ( mark , end ) ) ; } else if ( template . startsWith ( MACRO_COLUMN , mark ) ) { mark += MACRO_COLUMN . length ( ) ; end = findMacroEnd ( template , mark ) ; onColumn ( sqlBuilder , template . substring ( mark , end ) ) ; } else if ( template . startsWith ( MACRO_MATCH , mark ) ) { mark += MACRO_MATCH . length ( ) ; end = findMacroEnd ( template , mark ) ; onMatch ( sqlBuilder , template . substring ( mark , end ) ) ; } else if ( template . startsWith ( MACRO_VALUE , mark ) ) { mark += MACRO_VALUE . length ( ) ; end = findMacroEnd ( template , mark ) ; onValue ( sqlBuilder , template . substring ( mark , end ) ) ; } else { mark ++ ; // reference found
end = mark ; // find macro end
while ( end < length ) { if ( ! isReferenceChar ( template , end ) ) { break ; } end ++ ; } onReference ( sqlBuilder , template . substring ( mark , end ) ) ; end -- ; } end ++ ; last = end ; }


signature:
public class TemplateParser { /** * Finds macros end . */
protected int findMacroEnd ( final String template , final int fromIndex ) { } }

implementation: int endIndex = template . indexOf ( '}' , fromIndex ) ; if ( endIndex == - 1 ) { throw new DbSqlBuilderException ( "Template syntax error, some macros are not closed. Error at: '..." + template . substring ( fromIndex ) ) ; } return endIndex ;


signature:
public class TemplateParser { /** * Count escapes to the left . */
protected int countEscapes ( final String template , int macroIndex ) { } }

implementation: macroIndex -- ; int escapeCount = 0 ; while ( macroIndex >= 0 ) { if ( template . charAt ( macroIndex ) != ESCAPE_CHARACTER ) { break ; } escapeCount ++ ; macroIndex -- ; } return escapeCount ;


signature:
public class TemplateParser { /** * - - - - - handlers */
protected void onTable ( final DbSqlBuilder sqlBuilder , final String allTables ) { } }

implementation: String [ ] tables = StringUtil . split ( allTables , StringPool . COMMA ) ; for ( String table : tables ) { sqlBuilder . table ( table ) ; }


signature:
public class HttpUtil { /** * Builds a query string from given query map . */
public static String buildQuery ( final HttpMultiMap < ? > queryMap , final String encoding ) { } }

implementation: if ( queryMap . isEmpty ( ) ) { return StringPool . EMPTY ; } int queryMapSize = queryMap . size ( ) ; StringBand query = new StringBand ( queryMapSize * 4 ) ; int count = 0 ; for ( Map . Entry < String , ? > entry : queryMap ) { String key = entry . getKey ( ) ; key = URLCoder . encodeQueryParam ( key , encoding ) ; Object value = entry . getValue ( ) ; if ( value == null ) { if ( count != 0 ) { query . append ( '&' ) ; } query . append ( key ) ; count ++ ; } else { if ( count != 0 ) { query . append ( '&' ) ; } query . append ( key ) ; count ++ ; query . append ( '=' ) ; String valueString = URLCoder . encodeQueryParam ( value . toString ( ) , encoding ) ; query . append ( valueString ) ; } } return query . toString ( ) ;


signature:
public class HttpUtil { /** * Parses query from give query string . Values are optionally decoded . */
public static HttpMultiMap < String > parseQuery ( final String query , final boolean decode ) { } }

implementation: final HttpMultiMap < String > queryMap = HttpMultiMap . newCaseInsensitiveMap ( ) ; if ( StringUtil . isBlank ( query ) ) { return queryMap ; } int lastNdx = 0 ; while ( lastNdx < query . length ( ) ) { int ndx = query . indexOf ( '&' , lastNdx ) ; if ( ndx == - 1 ) { ndx = query . length ( ) ; } final String paramAndValue = query . substring ( lastNdx , ndx ) ; ndx = paramAndValue . indexOf ( '=' ) ; if ( ndx == - 1 ) { queryMap . add ( paramAndValue , null ) ; } else { String name = paramAndValue . substring ( 0 , ndx ) ; if ( decode ) { name = URLDecoder . decodeQuery ( name ) ; } String value = paramAndValue . substring ( ndx + 1 ) ; if ( decode ) { value = URLDecoder . decodeQuery ( value ) ; } queryMap . add ( name , value ) ; } lastNdx += paramAndValue . length ( ) + 1 ; } return queryMap ;


signature:
public class HttpUtil { /** * Makes nice header names . */
public static String prepareHeaderParameterName ( final String headerName ) { } }

implementation:
// special cases
if ( headerName . equals ( "etag" ) ) { return HttpBase . HEADER_ETAG ; } if ( headerName . equals ( "www-authenticate" ) ) { return "WWW-Authenticate" ; } char [ ] name = headerName . toCharArray ( ) ; boolean capitalize = true ; for ( int i = 0 ; i < name . length ; i ++ ) { char c = name [ i ] ; if ( c == '-' ) { capitalize = true ; continue ; } if ( capitalize ) { name [ i ] = Character . toUpperCase ( c ) ; capitalize = false ; } else { name [ i ] = Character . toLowerCase ( c ) ; } } return new String ( name ) ;


signature:
public class HttpUtil { /** * Extracts media - type from value of " Content Type " header . */
public static String extractMediaType ( final String contentType ) { } }

implementation: int index = contentType . indexOf ( ';' ) ; if ( index == - 1 ) { return contentType ; } return contentType . substring ( 0 , index ) ;