signature:
public class HTMLWriter { /** * Write out an attribute list , escaping values .
 * The names will have prefixes added to them .
 * @ param atts The attribute list to write .
 * @ throws org . xml . SAXException If there is an error writing the attribute list , this
 * method will throw an IOException wrapped in a
 * SAXException . */
private void writeAttributes ( Attributes atts ) throws SAXException { } }

implementation: int len = atts . getLength ( ) ; for ( int i = 0 ; i < len ; i ++ ) { write ( ' ' ) ; writeName ( atts . getURI ( i ) , atts . getLocalName ( i ) , atts . getQName ( i ) , false ) ; if ( htmlMode && booleanAttribute ( atts . getLocalName ( i ) , atts . getQName ( i ) , atts . getValue ( i ) ) ) break ; write ( "=\"" ) ; String s = atts . getValue ( i ) ; writeEscUTF16 ( s , 0 , s . length ( ) , true ) ; write ( '"' ) ; }


signature:
public class HTMLWriter { /** * Return true if the attribute is an HTML boolean from the above list . */
private boolean booleanAttribute ( String localName , String qName , String value ) { } }

implementation: String name = localName ; if ( name == null ) { int i = qName . indexOf ( ':' ) ; if ( i != - 1 ) name = qName . substring ( i + 1 , qName . length ( ) ) ; } if ( ! name . equals ( value ) ) return false ; for ( int j = 0 ; j < booleans . length ; j ++ ) { if ( name . equals ( booleans [ j ] ) ) return true ; } return false ;


signature:
public class HTMLWriter { /** * Write an array of data characters with escaping .
 * @ param ch The array of characters .
 * @ param start The starting position .
 * @ param length The number of characters to use .
 * @ param isAttVal true if this is an attribute value literal .
 * @ throws org . xml . SAXException If there is an error writing the characters , this method
 * will throw an IOException wrapped in a SAXException . */
private void writeEscUTF16 ( String s , int start , int length , boolean isAttVal ) throws SAXException { } }

implementation: String subString = s . substring ( start , start + length ) ; write ( StringEscapeUtils . escapeHtml4 ( subString ) ) ;


signature:
public class HTMLWriter { /** * Write out the list of Namespace declarations .
 * @ throws org . xml . sax . SAXException This method will throw an IOException wrapped in a
 * SAXException if there is an error writing the Namespace
 * declarations . */
@ SuppressWarnings ( "unchecked" ) private void writeNSDecls ( ) throws SAXException { } }

implementation: Enumeration < String > prefixes = ( Enumeration < String > ) nsSupport . getDeclaredPrefixes ( ) ; while ( prefixes . hasMoreElements ( ) ) { String prefix = ( String ) prefixes . nextElement ( ) ; String uri = nsSupport . getURI ( prefix ) ; if ( uri == null ) { uri = "" ; } write ( ' ' ) ; if ( "" . equals ( prefix ) ) { write ( "xmlns=\"" ) ; } else { write ( "xmlns:" ) ; write ( prefix ) ; write ( "=\"" ) ; } writeEscUTF16 ( uri , 0 , uri . length ( ) , true ) ; write ( '\"' ) ; }


signature:
public class HTMLWriter { /** * Write an element or attribute name .
 * @ param uri The Namespace URI .
 * @ param localName The local name .
 * @ param qName The prefixed name , if available , or the empty string .
 * @ param isElement true if this is an element name , false if it is an attribute
 * name .
 * @ throws org . xml . sax . SAXException This method will throw an IOException wrapped in a
 * SAXException if there is an error writing the name . */
private void writeName ( String uri , String localName , String qName , boolean isElement ) throws SAXException { } }

implementation: String prefix = doPrefix ( uri , qName , isElement ) ; if ( prefix != null && ! "" . equals ( prefix ) ) { write ( prefix ) ; write ( ':' ) ; } if ( localName != null && ! "" . equals ( localName ) ) { write ( localName ) ; } else { int i = qName . indexOf ( ':' ) ; write ( qName . substring ( i + 1 , qName . length ( ) ) ) ; }


signature: public class HTMLWriter { @ Override public void comment ( char [ ] ch , int start , int length ) throws SAXException { } }

implementation: write ( "<!--" ) ; for ( int i = start ; i < start + length ; i ++ ) { write ( ch [ i ] ) ; if ( ch [ i ] == '-' && i + 1 <= start + length && ch [ i + 1 ] == '-' ) write ( ' ' ) ; } write ( "-->" ) ;


signature:
public class Element { /** * Make this element anonymous . Remove any < tt > id < / tt > or < tt > name < / tt >
 * attribute present in the element ' s attributes . */
public void anonymize ( ) { } }

implementation: for ( int i = theAtts . getLength ( ) - 1 ; i >= 0 ; i -- ) { if ( theAtts . getType ( i ) . equals ( "ID" ) || theAtts . getQName ( i ) . equals ( "name" ) ) { theAtts . removeAttribute ( i ) ; } }


signature:
public class Element { /** * Clean the attributes of this element . Attributes with null name ( the name
 * was ill - formed ) or null value ( the attribute was present in the element
 * type but not in this actual element ) are removed . */
public void clean ( ) { } }

implementation: for ( int i = theAtts . getLength ( ) - 1 ; i >= 0 ; i -- ) { String name = theAtts . getLocalName ( i ) ; if ( theAtts . getValue ( i ) == null || name == null || name . length ( ) == 0 ) { theAtts . removeAttribute ( i ) ; continue ; } }


signature:
public class AwsKinesisUtils { /** * Create a AmazonKinesis client configured with some optional properties ( can also be configured using environment variables ) :
 * @ param accessKey - aws access key ( optional )
 * @ param secretKey - aws secret key ( optional )
 * @ param endpoint - kinesis endpoint ( optional * )
 * @ param port - kinesis port ( optional * )
 * @ param region - aws region ( optional * )
 * ( * ) to configure the endpoint , endpoint , port and region must be provided .
 * @ return a configured AmazonKinesis client */
public static AmazonKinesis buildKinesisClient ( @ Nullable String accessKey , @ Nullable String secretKey , @ Nullable String endpoint , @ Nullable Integer port , @ Nullable String region ) { } }

implementation: AmazonKinesisClientBuilder builder = AmazonKinesisClientBuilder . standard ( ) ; setAws ( builder , accessKey , secretKey , endpoint , port , region ) ; return builder . build ( ) ;


signature:
public class AwsKinesisUtils { /** * Ensure that the Kinesis Stream exists ( creates it if does not exist ) .
 * @ param kinesisClient Kinesis client
 * @ param streamName Stream name */
public static void ensureStreamExists ( AmazonKinesis kinesisClient , String streamName ) { } }

implementation: createStreamIfNotExists ( kinesisClient , streamName , 1 ) ; waitStreamActivation ( kinesisClient , streamName , MIN_3 ) ;


signature:
public class AwsKinesisUtils { /** * Create a stream if it does not already exist .
 * @ param kinesis AmazonKinesis client
 * @ param streamName the name of the stream */
private static void createStreamIfNotExists ( AmazonKinesis kinesis , String streamName , int shardCount ) { } }

implementation: performAmazonActionWithRetry ( "createStream" , ( ) -> { DescribeStreamRequest describeStreamRequest = new DescribeStreamRequest ( ) . withStreamName ( streamName ) . withLimit ( 1 ) ; try { kinesis . describeStream ( describeStreamRequest ) ; } catch ( ResourceNotFoundException e ) { kinesis . createStream ( streamName , shardCount ) ; } return null ; } , DEFAULT_RETRY_COUNT , DEFAULT_RETRY_DURATION_IN_MILLIS ) ;


signature:
public class AwsKinesisUtils { /** * Waits that the stream has been created . */
private static void waitStreamActivation ( AmazonKinesis consumer , String streamName , long streamCreationTimeoutMillis ) { } }

implementation:
DescribeStreamRequest describeStreamRequest = new DescribeStreamRequest ( ) . withStreamName ( streamName ) . withLimit ( 1 ) ; DescribeStreamResult describeStreamResult = null ; String streamStatus = null ; long endTime = System . currentTimeMillis ( ) + streamCreationTimeoutMillis ; do { try { describeStreamResult = consumer . describeStream ( describeStreamRequest ) ; streamStatus = describeStreamResult . getStreamDescription ( ) . getStreamStatus ( ) ; if ( ACTIVE_STREAM_STATUS . equals ( streamStatus ) ) { break ; } Thread . sleep ( 100 ) ; } catch ( ResourceNotFoundException | LimitExceededException ignored ) { // ignored
} catch ( InterruptedException e ) { Thread . currentThread ( ) . interrupt ( ) ; throw new AwsKinesisException ( "Thread interrupted while waiting for stream activation" , args -> args . add ( "streamName" , streamName ) , e ) ; } } while ( System . currentTimeMillis ( ) < endTime ) ; if ( describeStreamResult == null || streamStatus == null || ! streamStatus . equals ( ACTIVE_STREAM_STATUS ) ) { throw new AwsKinesisException ( "Stream never went active" , args -> args . add ( "streamName" , streamName ) . add ( "streamCreationTimeoutMillis" , streamCreationTimeoutMillis ) ) ; }


signature:
public class DataTypeManager { /** * TODO very ugly fix */
@ SuppressWarnings ( "unchecked" ) public < T > TypeConverter < T > getTypeConverter ( Class < T > clazz ) { } }

implementation: TypeConverter < T > converter = ( TypeConverter < T > ) TYPE_CONVERTERS . get ( clazz ) ; if ( converter == null ) { converter = value -> ( T ) value ; } return converter ;


signature:
public class DSL { /** * This method has to be called in the default implementation of an entity interface to declare that a relation is the reciprocal of another relation :
 * < ul >
 * < li > the straight relation is defined from the { @ code TAIL } entity to the { @ code HEAD } entity . It must not have a default implementation < / li >
 * < li > the reverse relation is defined from the { @ code HEAD } entity to the { @ code TAIL } entity . It must have a default implementation that call this method < / li >
 * < / ul >
 * At runtime this call is only issued during the model analysis . The entity instances proxies overrides this default implementation to return the needed information . < br >
 * @ param tailEntityClass the { @ code TAIL } entity class
 * @ param relationAccessor the accessor on the { @ code TAIL } entity class that correspond to the straight relation .
 * @ param < TAIL > the TAIL entity
 * @ param < HEAD > the HEAD entity
 * @ return whatever is needed to make the compiler happy */
public static < TAIL , HEAD > Collection < TAIL > reciprocalManyRelation ( Class < TAIL > tailEntityClass , Accessor < TAIL , HEAD > relationAccessor ) { } }

implementation: return THREAD_LOCAL_DSL_HELPER . get ( ) . reciprocalManyRelation ( tailEntityClass , relationAccessor ) ;


signature:
public class IronMigration { /** * Complete snapshot N with lacking instance snapshots from snapshot N - 1
 * @ param targetStoresPath path to store target iron */
private static void completeStoreSnapshotWithMissingInstanceSnapshots ( Path targetStoresPath ) { } }

implementation: String transactionIdRegexAlone = "\"transactionId\"\\s*:\\s*\\d+\\s*," ; String transactionIdRegexReplace = "(.*\"transactionId\"\\s*:\\s*)\\d+(\\s*,.*)" ; Pattern transactionIdPattern = compile ( transactionIdRegexAlone ) ; Set < File > previousSnapshots = new HashSet < > ( ) ; Arrays . stream ( targetStoresPath . resolve ( SNAPSHOT_DIRECTORY_NAME ) . toFile ( ) . listFiles ( ) ) . sorted ( ) . forEach ( snapshot -> { Set < String > snapshotNames = Arrays . stream ( snapshot . listFiles ( ) ) . map ( File :: getName ) . collect ( toSet ( ) ) ; previousSnapshots . stream ( ) . filter ( previousSnapshot -> ! snapshotNames . contains ( previousSnapshot . getName ( ) ) ) . forEach ( previousSnapshot -> { try { Path targetPath = snapshot . toPath ( ) . resolve ( previousSnapshot . getName ( ) ) ; Path sourcePath = previousSnapshot . toPath ( ) ; long count = countTransactionId ( transactionIdPattern , sourcePath ) ; if ( count != 1L ) { throw new StoreException ( "transactionId not found once" , args -> args . add ( "found count" , count ) ) ; } BigInteger newTransactionId = new BigInteger ( snapshot . getName ( ) ) ; replaceTransactionIdValue ( transactionIdRegexReplace , sourcePath , targetPath , newTransactionId . toString ( ) ) ; } catch ( IOException e ) { throw new UncheckedIOException ( e ) ; } } ) ; previousSnapshots . clear ( ) ; previousSnapshots . addAll ( Arrays . stream ( snapshot . listFiles ( ) ) . collect ( toSet ( ) ) ) ; } ) ;


signature:
public class AwsKinesisTransactionStore { /** * Returns the single created shard ( stream has a single shard ) . */
private Shard getUniqueShard ( ) { } }

implementation: DescribeStreamRequest describeStreamRequest = new DescribeStreamRequest ( ) . withStreamName ( m_streamName ) . withLimit ( 1 ) ; DescribeStreamResult describeStreamResult = performAmazonActionWithRetry ( "describe stream " + m_streamName , ( ) -> m_kinesis . describeStream ( describeStreamRequest ) , DEFAULT_RETRY_COUNT , DEFAULT_RETRY_DURATION_IN_MILLIS ) ; String streamStatus = describeStreamResult . getStreamDescription ( ) . getStreamStatus ( ) ; if ( streamStatus == null || ! streamStatus . equals ( ACTIVE_STREAM_STATUS ) ) { throw new AwsKinesisException ( "Stream does not exist" , args -> args . add ( "streamName" , m_streamName ) ) ; } List < Shard > shards = describeStreamResult . getStreamDescription ( ) . getShards ( ) ; checkState ( shards . size ( ) == 1 , "Kinesis Stream should contain only one shard" , args -> args . add ( "streamName" , m_streamName ) . add ( "shardCount" , shards . size ( ) ) ) ; return shards . get ( 0 ) ;


signature:
public class AwsKinesisTransactionStore { /** * Wait that the minimum duration between two GetShardIteratorRequests has elapsed .
 * @ return true if the duration elapsed , false if the thread has been interrupted */
private boolean waitTheMinimalDurationToExecuteTheNextProvisioningRequest ( ) { } }

implementation: if ( m_lastGetShardIteratorRequestTime != null ) { long delay = m_durationBetweenRequests . get ( ) - ( System . currentTimeMillis ( ) - m_lastGetShardIteratorRequestTime ) ; if ( delay > 0 ) { try { Thread . sleep ( delay ) ; } catch ( InterruptedException e ) { Thread . currentThread ( ) . interrupt ( ) ; return false ; } } } m_lastGetShardIteratorRequestTime = System . currentTimeMillis ( ) ; return true ;


signature:
public class AwsKinesisTransactionStore { /** * Retrieves records corresponding to the request .
 * @ param getRecordsRequest the request
 * @ return records corresponding to the request */
@ Nullable private List < Record > getRecords ( GetRecordsRequest getRecordsRequest ) { } }

implementation: return tryAmazonAction ( "" , ( ) -> { GetRecordsResult getRecordsResult = m_kinesis . getRecords ( getRecordsRequest ) ; m_shardIterator = getRecordsResult . getNextShardIterator ( ) ; List < Record > records = getRecordsResult . getRecords ( ) ; LOG . trace ( "Get records" , args -> args . add ( "streamName" , m_streamName ) . add ( "record number" , records . size ( ) ) . add ( "millisBehindLatest" , getRecordsResult . getMillisBehindLatest ( ) ) ) ; return records ; } , m_durationBetweenRequests ) . orElse ( List . of ( ) ) ;


signature:
public class AwsUtils { /** * Handle retry for amazon quotas
 * @ param < T > the action return type
 * @ param actionLabel action label used for logging purpose only
 * @ param action the action to retry
 * @ param retryLimit retry number limit
 * @ param durationInMillis duration between each retry
 * @ return the action result
 * @ throws AwsException after retry exhausted */
public static < T > T performAmazonActionWithRetry ( String actionLabel , Supplier < T > action , int retryLimit , int durationInMillis ) { } }

implementation:
int retryCount = 0 ; do { try { return action . get ( ) ; } catch ( LimitExceededException | ProvisionedThroughputExceededException | KMSThrottlingException e ) { // We should just wait a little time before trying again
int remainingRetries = retryLimit - retryCount ; LOG . debug ( "Amazon exception caught" , args -> args . add ( "exception" , e . getClass ( ) . getName ( ) ) . add ( "action" , actionLabel ) . add ( "remainingRetryCount" , remainingRetries ) ) ; } sleepUntilInterrupted ( actionLabel , durationInMillis ) ; } while ( retryCount ++ < retryLimit ) ; throw new AwsException ( "Limit exceeded, all retries failed" , args -> args . add ( "action" , actionLabel ) . add ( "retryLimit" , retryLimit ) ) ;


signature:
public class AwsUtils { /** * Try to perform an Amazon action and increase the duration between requests if some exception is exceeding resource usage exception is thrown .
 * @ param < T > the action return type
 * @ param actionLabel action label used for logging purpose only
 * @ param action the action to retry
 * @ param durationBetweenRequests duration between each retry
 * @ return the action result */
public static < T > Optional < T > tryAmazonAction ( String actionLabel , Supplier < T > action , AtomicLong durationBetweenRequests ) { } }

implementation:
try { return of ( action . get ( ) ) ; } catch ( LimitExceededException | ProvisionedThroughputExceededException | KMSThrottlingException e ) { int durationRandomModifier = 1 + RANDOM . nextInt ( 64 ) ; // random duration to make readers out of sync , avoiding simultaneous readings
long updatedDuration = durationBetweenRequests . updateAndGet ( duration -> duration * 2 // twice the duration
+ duration * 2 / durationRandomModifier ) ; // add random duration to avoid simultaneous reads
LOG . debug ( "Update of minimal duration between two get shard iterator requests" , args -> args . add ( "actionLabel" , actionLabel ) . add ( "new minimalDurationBetweenTwoGetShardIteratorRequests" , updatedDuration ) ) ; } return empty ( ) ;


signature:
public class AwsS3Utils { /** * Create a AwsS3SnapshotStore with some properties set to configure S3 client :
 * ( + ) to configure the access , both access key and secret key must be provided .
 * ( * ) to configure the endpoint URL , the endpoint , the port and the region must be provided .
 * @ param accessKey aws access key ( optional + )
 * @ param secretKey aws secret key ( optional + )
 * @ param endpoint s3 endpoint ( optional * )
 * @ param port s3 port ( optional * )
 * @ param region aws region ( optional * )
 * @ return the s3 client */
public static AmazonS3 buildS3Client ( @ Nullable String accessKey , @ Nullable String secretKey , @ Nullable String endpoint , @ Nullable Integer port , @ Nullable String region ) { } }

implementation: AmazonS3ClientBuilder builder = AmazonS3ClientBuilder . standard ( ) ; setAws ( builder , accessKey , secretKey , endpoint , port , region ) ; return builder . build ( ) ;


signature:
public class AwsS3Utils { /** * Throws an exception if the bucket does not exist or is not readable .
 * @ param amazonS3 Amazon S3 client
 * @ param bucketName bucket name */
static String checkBucketIsAccessible ( AmazonS3 amazonS3 , String bucketName ) { } }

implementation: HeadBucketRequest headBucketRequest = new HeadBucketRequest ( bucketName ) ; try { amazonS3 . headBucket ( headBucketRequest ) ; } catch ( AmazonServiceException e ) { throw new AwsS3Exception ( "Bucket is not accessible" , args -> args . add ( "bucketName" , bucketName ) , e ) ; } return bucketName ;


signature:
public class IntrospectionHelper { /** * This method don ' t use cache . Use with care . < br >
 * If caching is required , then use { @ link # getMethodName ( Class , Accessor ) }
 * @ param clazz the class where the method is defined
 * @ param accessor the method reference
 * @ param < T > the type of the class
 * @ return the referenced method */
public static < T > Method retrieveMethod ( Class < T > clazz , Accessor < T , ? > accessor ) { } }

implementation: MethodCallRecorder methodCallRecorder = new MethodCallRecorder ( ) ; T accessorInstance = ProxyFactoryBuilder . < MethodCallRecorder > newProxyFactoryBuilder ( ) . defaultObjectMethods ( ) . unhandled ( ( context , proxy , method , args ) -> { context . setMethod ( method ) ; return DEFAULT_VALUES . get ( method . getReturnType ( ) ) ; } ) . build ( clazz ) . createProxy ( methodCallRecorder ) ; accessor . get ( accessorInstance ) ; Method method = methodCallRecorder . getMethod ( ) ; if ( method == null ) { throw new StoreException ( "Method reference didn't call any method on the class" , args -> args . add ( "className" , clazz . getName ( ) ) ) ; } return method ;


signature:
public class StorePersistence { /** * Load the stores .
 * @ param entityStoresByStoreName the map store name to entity stores
 * @ return latestSnapshotTxId the transaction id of the last snapshot */
Optional < BigInteger > loadStores ( Function < String , EntityStores > entityStoresByStoreName , BiFunction < SerializableSnapshot , String , SerializableSnapshot > snapshotPostProcessor ) { } }

implementation:
Optional < BigInteger > latestSnapshotTxId ; try { latestSnapshotTxId = m_snapshotStore . listSnapshots ( ) . stream ( ) . max ( BigInteger :: compareTo ) ; } catch ( IOException e ) { throw new UnrecoverableStoreException ( "Error occurred when recovering from latest snapshot" , e ) ; } latestSnapshotTxId . ifPresent ( lastTx -> { LOG . info ( "Recovering store from snapshot" , args -> args . add ( "transactionId" , lastTx ) ) ; var postProcess = new SnapshotPostProcessor ( snapshotPostProcessor ) ; try { Flowable . fromPublisher ( m_snapshotStore . createSnapshotReader ( lastTx ) ) . blockingForEach ( reader -> { String storeName = reader . storeName ( ) ; EntityStores entityStores = entityStoresByStoreName . apply ( storeName ) ; SerializableSnapshot serializableSnapshot ; try ( InputStream is = reader . inputStream ( ) ) { serializableSnapshot = m_snapshotSerializer . deserializeSnapshot ( storeName , is ) ; } if ( serializableSnapshot . getSnapshotModelVersion ( ) != SNAPSHOT_MODEL_VERSION ) { throw new UnrecoverableStoreException ( "Snapshot serializable model version is not supported" , args -> args . add ( "version" , serializableSnapshot . getSnapshotModelVersion ( ) ) . add ( "expectedVersion" , SNAPSHOT_MODEL_VERSION ) ) ; } if ( ! lastTx . equals ( serializableSnapshot . getTransactionId ( ) ) ) { throw new UnrecoverableStoreException ( "Snapshot transaction id  mismatch with request transaction id" , args -> args . add ( "snapshotTransactionId" , serializableSnapshot . getTransactionId ( ) ) . add ( "requestTransactionId" , lastTx ) ) ; } SerializableSnapshot finalSnapshot = postProcess . apply ( storeName , serializableSnapshot ) ; finalSnapshot . getEntities ( ) . forEach ( serializableEntityInstances -> { String entityName = serializableEntityInstances . getEntityName ( ) ; EntityStore < ? > entityStore = entityStores . getEntityStore ( entityName ) ; checkArgument ( entityStore != null , "Entity has not be registered in the store" , args -> args . add ( "entityName" , entityName ) ) ; entityStore . recover ( serializableEntityInstances ) ; } ) ; } ) ; } catch ( Exception e ) { throw new UnrecoverableStoreException ( "Error occurred when recovering from latest snapshot" , e ) ; } // update the applicationModelVersion if any consistent load / update
m_applicationModelVersion = postProcess . getConsistentApplicationModelVersion ( ) ; } ) ; if ( ! latestSnapshotTxId . isPresent ( ) ) { LOG . info ( "Store has no snapshot, store is empty, creating it's first snapshot" ) ; } return latestSnapshotTxId ;


signature:
public class DefaultWildcardStreamLocator { /** * { @ inheritDoc } */
public InputStream locateStream ( final String uri , final File folder ) throws IOException { } }

implementation: final Collection < File > files = findMatchedFiles ( new WildcardContext ( uri , folder ) ) ; final ByteArrayOutputStream out = new ByteArrayOutputStream ( ) ; for ( final File file : files ) { if ( file . isFile ( ) ) { final InputStream is = new FileInputStream ( file ) ; IOUtils . copy ( is , out ) ; is . close ( ) ; } else { LOG . debug ( "Ignoring folder: " + file ) ; } } return new BufferedInputStream ( new ByteArrayInputStream ( out . toByteArray ( ) ) ) ;


signature:
public class DefaultWildcardStreamLocator { /** * Creates a { @ link IOFileFilter } which collects found files into a collection and also populates a map with found
 * resources and corresponding files .
 * @ param wildcardContext
 * @ param allFiles - where all found files and folders are collected . */
@ SuppressWarnings ( "serial" ) private IOFileFilter createWildcardCollectorFileFilter ( final WildcardContext wildcardContext , final Collection < File > allFiles ) { } }

implementation: notNull ( wildcardContext ) ; notNull ( allFiles ) ; return new WildcardFileFilter ( wildcardContext . getWildcard ( ) ) { @ Override public boolean accept ( final File file ) { final boolean accept = super . accept ( file ) ; if ( accept ) { LOG . debug ( "\tfound resource: {}" , file . getPath ( ) ) ; allFiles . add ( file ) ; } return accept ; } } ;


signature:
public class DefaultWildcardStreamLocator { /** * Validates arguments used by { @ link DefaultWildcardStreamLocator # findMatchedFiles ( String , File ) } method .
 * @ throws IOException if supplied arguments are invalid or cannot be handled by this locator . */
private void validate ( final WildcardContext wildcardContext ) throws IOException { } }

implementation: notNull ( wildcardContext ) ; final String uri = wildcardContext . getUri ( ) ; final File folder = wildcardContext . getFolder ( ) ; if ( uri == null || folder == null || ! folder . isDirectory ( ) ) { final StringBuffer message = new StringBuffer ( "Invalid folder provided" ) ; if ( folder != null ) { message . append ( ", with path: " ) . append ( folder . getPath ( ) ) ; } message . append ( ", with fileNameWithWildcard: " ) . append ( uri ) ; throw new IOException ( message . toString ( ) ) ; } if ( ! hasWildcard ( uri ) ) { throw new IOException ( "No wildcard detected for the uri: " + uri ) ; } LOG . debug ( "uri: {}" , uri ) ; LOG . debug ( "folder: {}" , folder . getPath ( ) ) ; LOG . debug ( "wildcard: {}" , wildcardContext . getWildcard ( ) ) ;


signature:
public class DefaultWildcardStreamLocator { /** * Uses the wildcardExpanderHandler to process all found files and directories .
 * @ param files
 * a collection of all files and folders found during wildcard matching .
 * @ VisibleForTestOnly */
void triggerWildcardExpander ( final Collection < File > allFiles , final WildcardContext wildcardContext ) throws IOException { } }

implementation:
LOG . debug ( "wildcard resources: {}" , allFiles ) ; if ( allFiles . isEmpty ( ) ) { final String message = String . format ( "No resource found for wildcard: %s" , wildcardContext . getWildcard ( ) ) ; LOG . warn ( message ) ; throw new IOException ( message ) ; } if ( wildcardExpanderHandler != null ) { try { wildcardExpanderHandler . apply ( allFiles ) ; } catch ( final IOException e ) { // preserve exception type if the exception is already an IOException
throw e ; } catch ( final Exception e ) { LOG . debug ( "wildcard expanding error. Reporting original exception" , e ) ; throw new IOException ( "Exception during expanding wildcard: " + e . getMessage ( ) ) ; } }


signature:
public class StringUtils { /** * Replace all occurrences of a substring within a string with another string .
 * @ param inString
 * String to examine
 * @ param oldPattern
 * String to replace
 * @ param newPattern
 * String to insert
 * @ return a String with the replacements */
private static String replace ( final String inString , final String oldPattern , final String newPattern ) { } }

implementation:
if ( ! hasLength ( inString ) || ! hasLength ( oldPattern ) || newPattern == null ) { return inString ; } final StringBuffer sbuf = new StringBuffer ( ) ; // output StringBuffer we ' ll build up
int pos = 0 ; // our position in the old string
int index = inString . indexOf ( oldPattern ) ; // the index of an occurrence we ' ve found , or - 1
final int patLen = oldPattern . length ( ) ; while ( index >= 0 ) { sbuf . append ( inString . substring ( pos , index ) ) ; sbuf . append ( newPattern ) ; pos = index + patLen ; index = inString . indexOf ( oldPattern , pos ) ; } sbuf . append ( inString . substring ( pos ) ) ; // remember to append any characters to the right of a match
return sbuf . toString ( ) ;


signature:
public class StringUtils { /** * Convenience method to return a Collection as a delimited ( e . g . CSV ) String .
 * E . g . useful for < code > toString ( ) < / code > implementations .
 * @ param coll
 * the Collection to display
 * @ param delim
 * the delimiter to use ( probably a " , " )
 * @ return the delimited String */
private static String collectionToDelimitedString ( final Collection < String > coll , final String delim ) { } }

implementation: return collectionToDelimitedString ( coll , delim , EMPTY , EMPTY ) ;


signature:
public class StringUtils { /** * Delete any character in a given String .
 * @ param inString
 * the original String
 * @ param charsToDelete
 * a set of characters to delete . E . g . " az \ n " will delete ' a ' s , ' z ' s
 * and new lines .
 * @ return the resulting String */
private static String deleteAny ( final String inString , final String charsToDelete ) { } }

implementation: if ( ! hasLength ( inString ) || ! hasLength ( charsToDelete ) ) { return inString ; } final StringBuffer out = new StringBuffer ( ) ; for ( int i = 0 ; i < inString . length ( ) ; i ++ ) { final char c = inString . charAt ( i ) ; if ( charsToDelete . indexOf ( c ) == - 1 ) { out . append ( c ) ; } } return out . toString ( ) ;


signature:
public class RhinoTypeScriptProcessor { /** * { @ inheritDoc } */
@ Override public void process ( final Resource resource , final Reader reader , final Writer writer ) throws IOException { } }

implementation:
LOG . debug ( "processing resource: {}" , resource ) ; final String content = IOUtils . toString ( reader ) ; final TypeScriptCompiler compiler = enginePool . getObject ( ) ; try { writer . write ( compiler . compile ( content ) ) ; } catch ( final Exception e ) { onException ( e , content ) ; } finally { // return for later reuse
enginePool . returnObject ( compiler ) ; reader . close ( ) ; writer . close ( ) ; }


signature:
public class EmberJsProcessor { /** * { @ inheritDoc } */
@ Override protected String getArgument ( final Resource resource ) { } }

implementation: final String name = resource == null ? "" : FilenameUtils . getBaseName ( resource . getUri ( ) ) ; return String . format ( "'%s'" , name ) ;


signature:
public class ConfigurableRequestHandlerFactory { /** * { @ inheritDoc } */
private RequestHandlerFactory newRequestHandlerFactory ( ) { } }

implementation:
final SimpleRequestHandlerFactory factory = new SimpleRequestHandlerFactory ( ) ; final List < RequestHandler > requestHandlers = getConfiguredStrategies ( ) ; for ( final RequestHandler requestHandler : requestHandlers ) { factory . addHandler ( requestHandler ) ; } // use default when none provided
if ( requestHandlers . isEmpty ( ) ) { LOG . debug ( "No locators configured. Using Default locator factory." ) ; return new DefaultRequestHandlerFactory ( ) ; } return factory ;


signature:
public class LintReport { /** * Add a single lint report to underlying collection .
 * @ param resourceLintReport
 * { @ link ResourceLintReport } to add .
 * @ return reference to this { @ link LintReport } object ( fluent interface ) . */
public LintReport < T > addReport ( final ResourceLintReport < T > resourceLintReport ) { } }

implementation: Validate . notNull ( resourceLintReport ) ; reports . add ( resourceLintReport ) ; return this ;


signature:
public class AbstractLinter { /** * Initialize script builder for evaluation . */
private RhinoScriptBuilder initScriptBuilder ( ) { } }

implementation: try { if ( builder == null ) { builder = RhinoScriptBuilder . newChain ( ) . evaluateChain ( DEFINE_WINDOW , "window" ) . evaluateChain ( getScriptAsStream ( ) , "linter.js" ) ; } return builder ; } catch ( final IOException e ) { throw new WroRuntimeException ( "Failed reading init script" , e ) ; }


signature:
public class AbstractLinter { /** * Validates a js using jsHint and throws { @ link LinterException } if the js is invalid . If no exception is thrown , the
 * js is valid .
 * @ param data
 * js content to process . */
public void validate ( final String data ) throws LinterException { } }

implementation: final StopWatch watch = new StopWatch ( ) ; watch . start ( "init" ) ; final RhinoScriptBuilder builder = initScriptBuilder ( ) ; watch . stop ( ) ; watch . start ( "lint" ) ; final String packIt = buildLinterScript ( WroUtil . toJSMultiLineString ( data ) , getOptions ( ) ) ; final boolean valid = Boolean . parseBoolean ( builder . evaluate ( packIt , "check" ) . toString ( ) ) ; if ( ! valid ) { final String json = builder . addJSON ( ) . evaluate ( String . format ( "JSON.stringify(JSON.decycle(%s.errors))" , getLinterName ( ) ) , "stringify errors" ) . toString ( ) ; LOG . debug ( "json {}" , json ) ; final Type type = new TypeToken < List < LinterError > > ( ) { } . getType ( ) ; final List < LinterError > errors = new Gson ( ) . fromJson ( json , type ) ; LOG . debug ( "errors {}" , errors ) ; throw new LinterException ( ) . setErrors ( errors ) ; } LOG . debug ( "result: {}" , valid ) ; watch . stop ( ) ; LOG . debug ( watch . prettyPrint ( ) ) ;


signature:
public class AbstractLinter { /** * TODO this method is duplicated in { @ link CssLint } . Extract and reuse it .
 * @ param data
 * script to process .
 * @ param options
 * options to set as true
 * @ return Script used to pack and return the packed result . */
private String buildLinterScript ( final String data , final String options ) { } }

implementation: return String . format ( "%s(%s,%s);" , getLinterName ( ) , data , optionsBuilder . buildFromCsv ( options ) ) ;


signature:
public class ConfigurableWroManagerFactory { /** * Reuse { @ link ConfigurableProcessorsFactory } for processors lookup . */
@ Override protected ProcessorsFactory newProcessorsFactory ( ) { } }

implementation: return new ConfigurableProcessorsFactory ( ) { @ Override protected Properties newProperties ( ) { final Properties props = new Properties ( ) ; updatePropertiesWithConfiguration ( props , ConfigurableProcessorsFactory . PARAM_PRE_PROCESSORS ) ; updatePropertiesWithConfiguration ( props , ConfigurableProcessorsFactory . PARAM_POST_PROCESSORS ) ; return props ; } @ Override protected Map < String , ResourcePostProcessor > getPostProcessorStrategies ( final ProcessorProvider provider ) { final Map < String , ResourcePostProcessor > map = super . getPostProcessorStrategies ( provider ) ; contributePostProcessors ( map ) ; return map ; } @ Override protected Map < String , ResourcePreProcessor > getPreProcessorStrategies ( final ProcessorProvider provider ) { final Map < String , ResourcePreProcessor > map = super . getPreProcessorStrategies ( provider ) ; contributePreProcessors ( map ) ; return map ; } } ;


signature:
public class ConfigurableWroManagerFactory { /** * Add to properties a new key with value extracted either from filterConfig or from configurable properties file .
 * This method helps to ensure backward compatibility of the filterConfig vs configProperties configuration .
 * @ param props
 * the { @ link Properties } which will be populated with the value extracted from filterConfig or
 * configProperties for the provided key .
 * @ param key
 * to read from filterConfig or configProperties and put into props . */
private void updatePropertiesWithConfiguration ( final Properties props , final String key ) { } }

implementation:
final FilterConfig filterConfig = Context . get ( ) . getFilterConfig ( ) ; // first , retrieve value from init - param for backward compatibility
final String valuesAsString = filterConfig . getInitParameter ( key ) ; if ( valuesAsString != null ) { props . setProperty ( key , valuesAsString ) ; } else { // retrieve value from configProperties file
final String value = getConfigProperties ( ) . getProperty ( key ) ; if ( value != null ) { props . setProperty ( key , value ) ; } }


signature:
public class ConfigurableWroManagerFactory { /** * Use this method rather than accessing the field directly , because it will create a default one if none is provided . */
private Properties getConfigProperties ( ) { } }

implementation: if ( configProperties == null ) { configProperties = newConfigProperties ( ) ; if ( additionalConfigProperties != null ) { configProperties . putAll ( additionalConfigProperties ) ; } } return configProperties ;


signature:
public class ConfigurableWroManagerFactory { /** * Override this method to provide a different config properties file location . It is very likely that you would like
 * it to be the same as the one used by the { @ link FilterConfigWroConfigurationFactory } . The default properties file
 * location is / WEB - INF / wro . properties .
 * @ return a not null properties object used as a secondary configuration option for processors if these are not
 * configured in init - param . */
protected Properties newConfigProperties ( ) { } }

implementation:
// default location is / WEB - INF / wro . properties
final Properties props = new Properties ( ) ; try { return new ServletContextPropertyWroConfigurationFactory ( Context . get ( ) . getServletContext ( ) ) . createProperties ( ) ; } catch ( final Exception e ) { LOG . warn ( "No configuration property file found. Using default values." , e ) ; } return props ;


signature:
public class ConfigurableProcessorsFactory { /** * To be used for internal usage . Ensure that returned object is not null . */
private Map < String , ResourcePreProcessor > getPreProcessorsMap ( ) { } }

implementation: if ( this . preProcessorsMap == null ) { synchronized ( this ) { if ( this . preProcessorsMap == null ) { this . preProcessorsMap = newPreProcessorsMap ( ) ; } } } return this . preProcessorsMap ;


signature:
public class ConfigurableProcessorsFactory { /** * To be used for internal usage . Ensure that returned object is not null . */
private Map < String , ResourcePostProcessor > getPostProcessorsMap ( ) { } }

implementation: if ( this . postProcessorsMap == null ) { synchronized ( this ) { if ( this . postProcessorsMap == null ) { this . postProcessorsMap = newPostProcessorsMap ( ) ; } } } return this . postProcessorsMap ;


signature:
public class JsonModelFactory { /** * { @ inheritDoc } */
@ Override public synchronized WroModel create ( ) { } }

implementation: final StopWatch stopWatch = new StopWatch ( "Create Wro Model from Groovy" ) ; try { stopWatch . start ( "createModel" ) ; final Type type = new TypeToken < WroModel > ( ) { } . getType ( ) ; final InputStream is = getModelResourceAsStream ( ) ; if ( is == null ) { throw new WroRuntimeException ( "Invalid model stream provided!" ) ; } final WroModel model = new Gson ( ) . fromJson ( new InputStreamReader ( new AutoCloseInputStream ( is ) ) , type ) ; LOG . debug ( "json model: {}" , model ) ; if ( model == null ) { throw new WroRuntimeException ( "Invalid content provided, cannot build model!" ) ; } return model ; } catch ( final Exception e ) { throw new WroRuntimeException ( "Invalid model found!" , e ) ; } finally { stopWatch . stop ( ) ; LOG . debug ( stopWatch . prettyPrint ( ) ) ; }


signature:
public class SmartWroModelFactory { /** * Use this factory method when you want to use the { @ link SmartWroModelFactory } in standalone ( maven plugin ) context .
 * The autoDetect flag is set to true if the wroFile path is the same as the default wro file name . */
public static SmartWroModelFactory createFromStandaloneContext ( final StandaloneContext context ) { } }

implementation: notNull ( context ) ; final boolean autoDetectWroFile = WroUtil . normalize ( context . getWroFile ( ) . getPath ( ) ) . contains ( WroUtil . normalize ( DEFAULT_WRO_FILE ) ) ; if ( ! autoDetectWroFile ) { LOG . debug ( "autoDetect is " + autoDetectWroFile + " because wroFile: " + context . getWroFile ( ) + " is not the same as the default one: " + DEFAULT_WRO_FILE ) ; } return new SmartWroModelFactory ( ) . setWroFile ( context . getWroFile ( ) ) . setAutoDetectWroFile ( autoDetectWroFile ) ;


signature:
public class SmartWroModelFactory { /** * Handles the resource model auto detection . */
private InputStream createAutoDetectedStream ( final String defaultFileName ) throws IOException { } }

implementation:
try { Validate . notNull ( wroFile , "Cannot call this method if wroFile is null!" ) ; if ( autoDetectWroFile ) { final File file = new File ( wroFile . getParentFile ( ) , defaultFileName ) ; LOG . debug ( "\tloading autodetected wro file: " + file ) ; return new FileInputStream ( file ) ; } LOG . debug ( "loading wroFile: " + wroFile ) ; return new FileInputStream ( wroFile ) ; } catch ( final FileNotFoundException e ) { // When auto detect is turned on , do not skip trying . . because the auto detection assume that the wro file name
// can be wrong .
if ( autoDetectWroFile ) { throw e ; } throw new WroRuntimeException ( "The wroFile doesn't exist. Skip trying with other wro model factories" , e ) ; }


signature:
public class SmartWroModelFactory { /** * { @ inheritDoc } */
@ Override public WroModel create ( ) { } }

implementation:
if ( factoryList == null ) { factoryList = newWroModelFactoryFactoryList ( ) ; } if ( factoryList != null ) { // Holds the details about model creation which are logged only when no model can be created
final StringBuffer logMessageBuffer = new StringBuffer ( ) ; for ( final WroModelFactory factory : factoryList ) { try { // use injector for aggregated modelFactories
injector . inject ( factory ) ; final Class < ? extends WroModelFactory > factoryClass = factory . getClass ( ) . asSubclass ( WroModelFactory . class ) ; logMessageBuffer . append ( " Using " + getClassName ( factoryClass ) + " for model creation..\n" ) ; return factory . create ( ) ; } catch ( final WroRuntimeException e ) { LOG . debug ( "[FAIL] creating model... will try another factory: {}" , e . getCause ( ) ) ; logMessageBuffer . append ( "[FAIL] Model creation using " + getClassName ( factory . getClass ( ) ) + " failed. Trying another ...\n" ) ; logMessageBuffer . append ( "[FAIL] Exception occured while building the model using: " + getClassName ( factory . getClass ( ) ) + " " + e . getMessage ( ) ) ; // stop trying with other factories if the reason is IOException
if ( ! autoDetectWroFile && e . getCause ( ) instanceof IOException ) { throw e ; } } } LOG . error ( logMessageBuffer . toString ( ) ) ; } throw new WroRuntimeException ( "Cannot create model using any of provided factories" ) ;


signature:
public class CssImportInspector { /** * Removes all @ import statements from css . */
public final String removeImportStatements ( ) { } }

implementation:
final StringBuffer sb = new StringBuffer ( ) ; while ( matcher . find ( ) ) { // replace @ import with empty string
matcher . appendReplacement ( sb , StringUtils . EMPTY ) ; } matcher . appendTail ( sb ) ; return sb . toString ( ) ;


signature:
public class DefaultProcessorProvider { /** * { @ inheritDoc } */
public Map < String , ResourcePreProcessor > providePreProcessors ( ) { } }

implementation: final Map < String , ResourcePreProcessor > map = new HashMap < String , ResourcePreProcessor > ( ) ; populateProcessorsMap ( map ) ; return map ;


signature:
public class DefaultProcessorProvider { /** * Creates a map of postProcessors form a map of preProcessors . This method will be removed in 1.5.0 release when
 * there will be no differences between pre & post processor interface . */
private Map < String , ResourcePostProcessor > toPostProcessors ( final Map < String , ResourcePreProcessor > preProcessorsMap ) { } }

implementation: final Map < String , ResourcePostProcessor > map = new HashMap < String , ResourcePostProcessor > ( ) ; for ( final Entry < String , ResourcePreProcessor > entry : preProcessorsMap . entrySet ( ) ) { map . put ( entry . getKey ( ) , new ProcessorDecorator ( entry . getValue ( ) ) ) ; } return map ;


signature:
public class TaskExecutor { /** * The implementation uses jsr166 ForkJoinPool implementation in case it is available and can be used ,
 * otherwise the default { @ link ExecutorService } is used .
 * @ return the { @ link ExecutorService } responsible for running the tasks . */
protected ExecutorService newExecutor ( ) { } }

implementation: try { final ExecutorService executor = ( ExecutorService ) Class . forName ( "java.util.concurrent.ForkJoinPool" ) . newInstance ( ) ; LOG . debug ( "Using ForkJoinPool as task executor." ) ; return executor ; } catch ( final Exception e ) { LOG . debug ( "ForkJoinPool class is not available, using default executor." , e ) ; return Executors . newFixedThreadPool ( Runtime . getRuntime ( ) . availableProcessors ( ) ) ; }


signature:
public class TaskExecutor { /** * TODO rename to submitAll .
 * Submits a chunk of jobs for parallel execution . This is a blocking operation - it will end execution when all
 * submitted tasks are finished .
 * @ param callables
 * a { @ link Collection } of { @ link Callable } to execute . When the provided collection contains only one item ,
 * the task will be executed synchronously .
 * @ throws Exception
 * if an exception occurred during callable execution . */
public void submit ( final Collection < Callable < T > > callables ) throws Exception { } }

implementation: Validate . notNull ( callables ) ; final StopWatch watch = new StopWatch ( ) ; watch . start ( "init" ) ; final long start = System . currentTimeMillis ( ) ; final AtomicLong totalTime = new AtomicLong ( ) ; LOG . debug ( "running {} tasks" , callables . size ( ) ) ; if ( callables . size ( ) == 1 ) { final T result = callables . iterator ( ) . next ( ) . call ( ) ; onResultAvailable ( result ) ; } else { LOG . debug ( "Running tasks in parallel" ) ; watch . stop ( ) ; watch . start ( "submit tasks" ) ; for ( final Callable < T > callable : callables ) { getCompletionService ( ) . submit ( decorate ( callable , totalTime ) ) ; } watch . stop ( ) ; watch . start ( "consume results" ) ; for ( int i = 0 ; i < callables . size ( ) ; i ++ ) { doConsumeResult ( ) ; } } watch . stop ( ) ; destroy ( ) ; LOG . debug ( "Number of Tasks: {}" , callables . size ( ) ) ; final long averageExecutionTime = callables . size ( ) != 0 ? totalTime . longValue ( ) / callables . size ( ) : 0 ; LOG . debug ( "Average Execution Time: {}" , averageExecutionTime ) ; LOG . debug ( "Total Task Time: {}" , totalTime ) ; LOG . debug ( "Grand Total Execution Time: {}" , System . currentTimeMillis ( ) - start ) ; LOG . debug ( watch . prettyPrint ( ) ) ;


signature:
public class JawrCssMinifierProcessor { /** * { @ inheritDoc } */
public void process ( final Resource resource , final Reader reader , final Writer writer ) throws IOException { } }

implementation: try { final String content = IOUtils . toString ( reader ) ; final StringBuffer result = new JawrCssMinifier ( ) . minifyCSS ( new StringBuffer ( content ) ) ; writer . write ( result . toString ( ) ) ; writer . flush ( ) ; } catch ( final Exception e ) { final String resourceUri = resource == null ? StringUtils . EMPTY : "[" + resource . getUri ( ) + "]" ; String message = "Exception while applying " + getClass ( ) . getSimpleName ( ) + " processor on the " + resourceUri + " resource" ; LOG . error ( message , e ) ; throw new IOException ( message ) ; } finally { reader . close ( ) ; writer . close ( ) ; }


signature:
public class AbstractJsTemplateCompiler { /** * Compiles the javascript template into plain javascript .
 * @ param content
 * the template to be compiled .
 * @ param optionalArgument
 * any additional arguments used by template script .
 * @ return the compiled javascript . */
public String compile ( final String content , final String optionalArgument ) { } }

implementation: final RhinoScriptBuilder builder = initScriptBuilder ( ) ; final String argStr = createArgStr ( optionalArgument ) + createArgStr ( getArguments ( ) ) ; final String compileScript = String . format ( "%s(%s%s);" , getCompileCommand ( ) , WroUtil . toJSMultiLineString ( content ) , argStr ) ; return ( String ) builder . evaluate ( compileScript , getCompileCommand ( ) ) ;


signature:
public class JsTemplateCompilerProcessor { /** * { @ inheritDoc } */
@ Override public void process ( final Resource resource , final Reader reader , final Writer writer ) throws IOException { } }

implementation: final String content = IOUtils . toString ( reader ) ; final AbstractJsTemplateCompiler jsCompiler = enginePool . getObject ( ) ; try { writer . write ( jsCompiler . compile ( content , getArgument ( resource ) ) ) ; } finally { enginePool . returnObject ( jsCompiler ) ; reader . close ( ) ; writer . close ( ) ; }


signature:
public class CssDataUriPreProcessor { /** * Similar to { @ link CssDataUriPreProcessor # isReplaceAccepted ( String ) } , but decides whether the computed dataUri
 * should replace the image url . It is useful when you want to limit the dataUri size . By default the size of dataUri
 * is limited to 32KB ( because IE8 has a 32KB limitation ) .
 * @ param dataUri
 * base64 encoded stream .
 * @ return true if dataUri should replace original image url . */
protected boolean isReplaceAccepted ( final String dataUri ) { } }

implementation: try { final byte [ ] bytes = dataUri . getBytes ( CharEncoding . UTF_8 ) ; final boolean exceedLimit = bytes . length >= SIZE_LIMIT ; LOG . debug ( "dataUri size: {}KB, limit exceeded: {}" , bytes . length / 1024 , exceedLimit ) ; return ! exceedLimit ; } catch ( final UnsupportedEncodingException e ) { throw new WroRuntimeException ( "Should never happen" , e ) ; }


signature:
public class CopyrightKeeperProcessorDecorator { /** * { @ inheritDoc } */
@ Override public void process ( final Resource resource , final Reader reader , final Writer writer ) throws IOException { } }

implementation:
try { final String content = IOUtils . toString ( reader ) ; final Matcher originalMatcher = PATTERN_COPYRIGHT . matcher ( content ) ; final StringBuffer copyrightBuffer = new StringBuffer ( ) ; while ( originalMatcher . find ( ) ) { LOG . debug ( "found copyright comment" ) ; // add copyright header to the buffer .
copyrightBuffer . append ( originalMatcher . group ( ) ) ; } LOG . debug ( "buffer: {}" , copyrightBuffer ) ; final Writer processedWriter = new StringWriter ( ) ; getDecoratedObject ( ) . process ( resource , new StringReader ( content ) , processedWriter ) ; final Matcher processedMatcher = PATTERN_COPYRIGHT . matcher ( processedWriter . toString ( ) ) ; if ( ! processedMatcher . find ( ) ) { writer . write ( copyrightBuffer . toString ( ) ) ; } writer . write ( processedWriter . toString ( ) ) ; } finally { reader . close ( ) ; writer . close ( ) ; }


signature:
public class ConfigurableWroFilter { /** * { @ inheritDoc } */
@ Override protected ObjectFactory < WroConfiguration > newWroConfigurationFactory ( final FilterConfig filterConfig ) { } }

implementation:
if ( properties == null ) { // when no
properties = new Properties ( ) ; properties . setProperty ( ConfigConstants . debug . name ( ) , String . valueOf ( debug ) ) ; properties . setProperty ( ConfigConstants . gzipResources . name ( ) , String . valueOf ( gzipEnabled ) ) ; properties . setProperty ( ConfigConstants . jmxEnabled . name ( ) , String . valueOf ( jmxEnabled ) ) ; properties . setProperty ( ConfigConstants . cacheUpdatePeriod . name ( ) , String . valueOf ( cacheUpdatePeriod ) ) ; properties . setProperty ( ConfigConstants . modelUpdatePeriod . name ( ) , String . valueOf ( modelUpdatePeriod ) ) ; properties . setProperty ( ConfigConstants . disableCache . name ( ) , String . valueOf ( disableCache ) ) ; if ( encoding != null ) { properties . setProperty ( ConfigConstants . encoding . name ( ) , encoding ) ; } if ( mbeanName != null ) { properties . setProperty ( ConfigConstants . mbeanName . name ( ) , mbeanName ) ; } } return new PropertyWroConfigurationFactory ( properties ) ;


signature:
public class FallbackAwareWroModelFactory { /** * { @ inheritDoc } */
@ Override public WroModel create ( ) { } }

implementation: WroModel newModel = null ; try { newModel = super . create ( ) ; } catch ( final WroRuntimeException e ) { LOG . error ( "Error while creating the model" , e ) ; } if ( newModel == null ) { LOG . warn ( "Couldn't load new model, reusing last Valid Model!" ) ; if ( lastValidModel == null ) { throw new WroRuntimeException ( "No valid model was found!" ) ; } return lastValidModel ; } lastValidModel = newModel ; return lastValidModel ;


signature:
public class ExceptionHandlingProcessorDecorator { /** * { @ inheritDoc } */
@ Override public void process ( final Resource resource , final Reader reader , final Writer writer ) throws IOException { } }

implementation:
final String resourceContent = IOUtils . toString ( reader ) ; final Reader innerReader = new StringReader ( resourceContent ) ; final StringWriter innerWriter = new StringWriter ( ) ; try { super . process ( resource , innerReader , innerWriter ) ; writer . write ( innerWriter . toString ( ) ) ; } catch ( final Exception e ) { final String processorName = toString ( ) ; if ( isIgnoreFailingProcessor ( ) ) { LOG . debug ( "Ignoring failed processor. Original Exception" , e ) ; writer . write ( resourceContent ) ; // don ' t wrap exception unless required
} else { LOG . error ( "Failed to process the resource: {} using processor: {}. Reason: {}" , resource , processorName , e . getMessage ( ) ) ; final String resourceUri = resource != null ? resource . getUri ( ) : null ; throw WroRuntimeException . wrap ( e , "The processor: " + processorName + " faile while processing uri: " + resourceUri ) . setResource ( resource ) ; } } finally { reader . close ( ) ; writer . close ( ) ; }


signature:
public class GroupExtractorDecorator { /** * { @ inheritDoc } */
public String encodeGroupUrl ( final String groupName , final ResourceType resourceType , final boolean minimize ) { } }

implementation: return decorated . encodeGroupUrl ( groupName , resourceType , minimize ) ;


signature:
public class WroConfiguration { /** * Notify all listeners about cachePeriod property changed . If passed newValue is null , the oldValue is taken as new
 * value . This is the case when the reloadCache is invoked .
 * @ param newValue
 * value to set . */
private void reloadCacheWithNewValue ( final Long newValue ) { } }

implementation: final long newValueAsPrimitive = newValue == null ? getCacheUpdatePeriod ( ) : newValue ; LOG . debug ( "invoking {} listeners" , cacheUpdatePeriodListeners . size ( ) ) ; for ( final PropertyChangeListener listener : cacheUpdatePeriodListeners ) { final PropertyChangeEvent event = new PropertyChangeEvent ( this , "cache" , getCacheUpdatePeriod ( ) , newValueAsPrimitive ) ; listener . propertyChange ( event ) ; }


signature:
public class WroConfiguration { /** * Notify all listeners about cachePeriod property changed . If passed newValue is null , the oldValue is taken as new
 * value . This is the case when the reloadModel is invoked .
 * @ param newValue
 * value to set . */
private void reloadModelWithNewValue ( final Long newValue ) { } }

implementation: final long newValueAsPrimitive = newValue == null ? getModelUpdatePeriod ( ) : newValue ; for ( final PropertyChangeListener listener : modelUpdatePeriodListeners ) { final PropertyChangeEvent event = new PropertyChangeEvent ( this , "model" , getModelUpdatePeriod ( ) , newValueAsPrimitive ) ; listener . propertyChange ( event ) ; }


signature:
public class SchedulerHelper { /** * Factory method . Creates a { @ link SchedulerHelper } which consumes a factory providing a runnable . This approach
 * allows lazy runnable initialization .
 * @ param runnableFactory
 * a factory creating the runnable to schedule .
 * @ param name
 * the name associated with this { @ link SchedulerHelper } ( useful to detect if this class is causing a memory
 * leak . */
public static SchedulerHelper create ( final LazyInitializer < Runnable > runnableFactory , final String name ) { } }

implementation: return new SchedulerHelper ( runnableFactory , name ) ;


signature:
public class SchedulerHelper { /** * Run the scheduler with the provided period of time . If the scheduler is already started , it will be stopped ( not
 * before the running job is complete ) .
 * @ param period
 * new period for scheduling .
 * @ param timeUnit
 * what kind of time unit is associated with the period . */
public SchedulerHelper scheduleWithPeriod ( final long period , final TimeUnit timeUnit ) { } }

implementation: notNull ( timeUnit ) ; LOG . debug ( "period: {} [{}]" , period , timeUnit ) ; if ( this . period != period ) { this . period = period ; if ( ! poolInitializer . get ( ) . isShutdown ( ) ) { startScheduler ( period , timeUnit ) ; } else { LOG . warn ( "Cannot schedule because destroy was already called!" ) ; } } return this ;


signature:
public class SchedulerHelper { /** * The following method shuts down an ExecutorService in two phases , first by calling shutdown to reject incoming
 * tasks , and then calling shutdownNow , if necessary , to cancel any lingering tasks :
 * @ param destroyNow
 * - if true , any running operation will be stopped immediately , otherwise scheduler will await termination . */
private synchronized void destroyScheduler ( ) { } }

implementation:
if ( ! poolInitializer . get ( ) . isShutdown ( ) ) { // Disable new tasks from being submitted
poolInitializer . get ( ) . shutdown ( ) ; if ( future != null ) { future . cancel ( true ) ; } try { while ( ! poolInitializer . get ( ) . awaitTermination ( 5 , TimeUnit . SECONDS ) ) { LOG . debug ( "Termination awaited: {}" , name ) ; poolInitializer . get ( ) . shutdownNow ( ) ; } } catch ( final InterruptedException e ) { LOG . debug ( "Interrupted Exception occured during scheduler destroy" , e ) ; // ( Re - ) Cancel if current thread also interrupted
poolInitializer . get ( ) . shutdownNow ( ) ; // Preserve interrupt status
Thread . currentThread ( ) . interrupt ( ) ; } finally { LOG . debug ( "[STOP] Scheduler terminated successfully! {}" , name ) ; } }


signature:
public class DispatcherStreamLocator { /** * / * * When using JBoss Portal and it has some funny quirks . . . actually a portal application have several small web
 * application behind it . So when it intercepts a requests for portal then it start bombing the the application behind
 * the portal with multiple threads ( web requests ) that are combined with threads for wro4j .
 * @ param location
 * a path to a request relative resource to locate .
 * @ return a valid stream for required location . This method will never return a null .
 * @ throws IOException
 * if the stream cannot be located at the specified location . */
public InputStream getInputStream ( final HttpServletRequest request , final HttpServletResponse response , final String location ) throws IOException { } }

implementation:
if ( request == null || response == null || location == null ) { throw new IOException ( "Cannot get stream for location: " + location + " because either request, response or location is not available" ) ; } // where to write the bytes of the stream
final ByteArrayOutputStream os = new ByteArrayOutputStream ( ) ; boolean warnOnEmptyStream = false ; try { final RequestDispatcher dispatcher = request . getRequestDispatcher ( location ) ; if ( dispatcher != null ) { // Wrap request
final ServletRequest servletRequest = getWrappedServletRequest ( request , location ) ; // Wrap response
final ServletResponse servletResponse = new RedirectedStreamServletResponseWrapper ( os , response ) ; LOG . debug ( "dispatching request to location: {}" , location ) ; // use dispatcher
dispatcher . include ( servletRequest , servletResponse ) ; warnOnEmptyStream = true ; // force flushing - the content will be written to BytArrayOutputStream .
// Otherwise exactly 32K of data will be written .
servletResponse . getWriter ( ) . flush ( ) ; os . close ( ) ; } } catch ( final Exception e ) { LOG . debug ( "Could not dispatch request for location {}" , location ) ; // Not only servletException can be thrown , also dispatch . include can throw NPE when the scheduler runs outside
// of the request cycle , thus connection is unavailable . This is caused mostly when invalid resources are
// included .
return locateExternal ( request , location ) ; } try { // fallback to external resource locator if the dispatcher is empty
if ( os . size ( ) == 0 ) { return locateExternal ( request , location ) ; } } finally { if ( warnOnEmptyStream && os . size ( ) == 0 ) { LOG . debug ( "Wrong or empty resource with location: {}" , location ) ; } } return new ByteArrayInputStream ( os . toByteArray ( ) ) ;


signature:
public class DispatcherStreamLocator { /** * Build a wrapped servlet request which will be used for dispatching . */
private ServletRequest getWrappedServletRequest ( final HttpServletRequest request , final String location ) { } }

implementation:
final HttpServletRequest wrappedRequest = new HttpServletRequestWrapper ( request ) { @ Override public String getRequestURI ( ) { return getContextPath ( ) + location ; } @ Override public String getPathInfo ( ) { return WroUtil . getPathInfoFromLocation ( this , location ) ; } @ Override public String getServletPath ( ) { return WroUtil . getServletPathFromLocation ( this , location ) ; } } ; // add an attribute to mark this request as included from wro
wrappedRequest . setAttribute ( ATTRIBUTE_INCLUDED_BY_DISPATCHER , Boolean . TRUE ) ; return wrappedRequest ;


signature:
public class SimpleProcessorsFactory { /** * { @ inheritDoc } */
public void setResourcePreProcessors ( final Collection < ResourcePreProcessor > processors ) { } }

implementation: preProcessors . clear ( ) ; if ( processors != null ) { preProcessors . addAll ( processors ) ; }


signature:
public class SimpleProcessorsFactory { /** * { @ inheritDoc } */
public void setResourcePostProcessors ( final Collection < ResourcePostProcessor > processors ) { } }

implementation: postProcessors . clear ( ) ; if ( processors != null ) { postProcessors . addAll ( processors ) ; }


signature:
public class SimpleProcessorsFactory { /** * Add a { @ link ResourcePostProcessor } . */
public SimpleProcessorsFactory addPostProcessor ( final ResourcePostProcessor processor ) { } }

implementation:
if ( processor . getClass ( ) . isAnnotationPresent ( Minimize . class ) ) { // TODO move large messages to properties file
LOG . warn ( "It is recommended to add minimize aware processors to " + "pre processors instead of post processor, otherwise you " + "won't be able to disable minimization on specific resources " + "using minimize='false' attribute." ) ; } postProcessors . add ( processor ) ; return this ;


signature:
public class JsonHPack { /** * Initialize script builder for evaluation . */
private RhinoScriptBuilder initScriptBuilder ( ) { } }

implementation: try { return RhinoScriptBuilder . newClientSideAwareChain ( ) . addJSON ( ) . evaluateChain ( getScriptAsStream ( ) , DEFAULT_JS ) ; } catch ( final Exception e ) { LOG . error ( "Processing error:" + e . getMessage ( ) , e ) ; throw new WroRuntimeException ( "Processing error" , e ) ; }


signature:
public class ProviderFinder { /** * Creates a { @ link ProviderFinder } which will find providers of type provided as argument . .
 * @ param type
 * the type of providers to search .
 * @ return { @ link ProviderFinder } handling providers lookup . */
public static < T > ProviderFinder < T > of ( final Class < T > type ) { } }

implementation: return new ProviderFinder < T > ( type ) ;


signature:
public class ProviderFinder { /** * Collects also providers of type { @ link ConfigurableProvider } if the T type is a supertype of
 * { @ link ConfigurableProvider } . If the type is already { @ link ConfigurableProvider } , it will be ignored to avoid
 * adding of duplicate providers .
 * @ param providers
 * the list where found providers will be added . */
@ SuppressWarnings ( "unchecked" ) private void collectConfigurableProviders ( final List < T > providers ) { } }

implementation: if ( type . isAssignableFrom ( ConfigurableProvider . class ) && ( type != ConfigurableProvider . class ) ) { final Iterator < ConfigurableProvider > iterator = lookupProviders ( ConfigurableProvider . class ) ; for ( ; iterator . hasNext ( ) ; ) { final T provider = ( T ) iterator . next ( ) ; LOG . debug ( "found provider: {}" , provider ) ; providers . add ( provider ) ; } }


signature:
public class ProviderFinder { /** * This method is useful for mocking the lookup operation . The implementation will try to use java . util . ServiceLoader
 * by default ( available in jdk6 ) and will fallback to ServiceRegistry for earlier JDK versions . The reason for this
 * is to support GAE environment which doesn ' t contain the ServiceRegistry in its whitelist .
 * @ param providerClass
 * the class of the provider to lookup .
 * @ VisibleForTesting
 * @ return the iterator of found providers . */
@ SuppressWarnings ( "unchecked" ) < P > Iterator < P > lookupProviders ( final Class < P > providerClass ) { } }

implementation: LOG . debug ( "searching for providers of type : {}" , providerClass ) ; try { final Class < ? > serviceLoader = getClass ( ) . getClassLoader ( ) . loadClass ( "java.util.ServiceLoader" ) ; LOG . debug ( "using {} to lookupProviders" , serviceLoader . getName ( ) ) ; return ( ( Iterable < P > ) serviceLoader . getMethod ( "load" , Class . class ) . invoke ( serviceLoader , providerClass ) ) . iterator ( ) ; } catch ( final Exception e ) { LOG . debug ( "ServiceLoader is not available. Falling back to ServiceRegistry." , e ) ; } LOG . debug ( "using {} to lookupProviders" , ServiceRegistry . class . getName ( ) ) ; return ServiceRegistry . lookupProviders ( providerClass ) ;


signature:
public class SpringWroFilter { /** * { @ inheritDoc } */
@ Override protected void doInit ( final FilterConfig filterConfig ) throws ServletException { } }

implementation:
String targetBeanName = filterConfig . getInitParameter ( PARAM_TARGET_BEAN_NAME ) ; // apply default targetBeanName
targetBeanName = StringUtils . isEmpty ( targetBeanName ) ? DEFAULT_TARGET_BEAN_NAME : targetBeanName ; final WebApplicationContext ctx = WebApplicationContextUtils . getWebApplicationContext ( filterConfig . getServletContext ( ) ) ; factory = ( WroManagerFactory ) ctx . getBean ( targetBeanName , WroManagerFactory . class ) ; if ( factory == null ) { throw new WroRuntimeException ( "Could not locate: " + WroManagerFactory . class . getName ( ) + " instance in applicationContext with bean name: " + targetBeanName ) ; }


signature:
public class AggregatedFolderPathResolver { /** * The idea is to compute the aggregatedFolderPath based on a root folder . The root folder is determined by comparing
 * the cssTargetFolder ( the folder where aggregated css files are located ) with build directory or contextFolder . If
 * rootFolder is null , then the result is also null ( equivalent to using the cssTargetFolder the same as the root
 * folder .
 * @ return the aggregated folder path , based on the cssDestinationFolder ( if set ) and the build folder or the
 * contextFolder . */
public String resolve ( ) { } }

implementation:
notNull ( buildDirectory , "Build directory cannot be null!" ) ; notNull ( log , "Logger cannot be null!" ) ; String result = null ; final File cssTargetFolder = cssDestinationFolder == null ? destinationFolder : cssDestinationFolder ; File rootFolder = null ; notNull ( cssTargetFolder , "cssTargetFolder cannot be null!" ) ; if ( buildFinalName != null && cssTargetFolder . getPath ( ) . startsWith ( buildFinalName . getPath ( ) ) ) { rootFolder = buildFinalName ; } else if ( cssTargetFolder . getPath ( ) . startsWith ( buildDirectory . getPath ( ) ) ) { rootFolder = buildDirectory ; } else { // find first best match
for ( final String contextFolder : getContextFolders ( ) ) { if ( cssTargetFolder . getPath ( ) . startsWith ( contextFolder ) ) { rootFolder = new File ( contextFolder ) ; break ; } } } log . debug ( "buildDirectory: " + buildDirectory ) ; log . debug ( "contextFolders: " + contextFoldersAsCSV ) ; log . debug ( "cssTargetFolder: " + cssTargetFolder ) ; log . debug ( "rootFolder: " + rootFolder ) ; if ( rootFolder != null ) { result = StringUtils . removeStart ( cssTargetFolder . getPath ( ) , rootFolder . getPath ( ) ) ; } log . debug ( "computedAggregatedFolderPath: " + result ) ; return result ;


signature:
public class AggregatedFolderPathResolver { /** * Use { @ link StandaloneContext } to tokenize the contextFoldersAsCSV value . */
private String [ ] getContextFolders ( ) { } }

implementation: final StandaloneContext context = new StandaloneContext ( ) ; context . setContextFoldersAsCSV ( contextFoldersAsCSV ) ; return context . getContextFolders ( ) ;


signature:
public class Transformers { /** * Creates a { @ link Transformer } which replace a original filename extension with a new extension .
 * @ param newExtension extension to use for the returned value .
 * @ return original filename but with the new extension . */
public static Transformer < String > extensionTransformer ( final String newExtension ) { } }

implementation: return new Transformer < String > ( ) { public String transform ( final String input ) { return FilenameUtils . getBaseName ( input ) + "." + newExtension ; } } ;


signature:
public class Transformers { /** * Appends a suffix to the source baseName .
 * @ param suffix to append .
 * @ return { @ link Transformer } capable to append a suffix to provided baseName . */
public static Transformer < String > baseNameSuffixTransformer ( final String suffix ) { } }

implementation: return new Transformer < String > ( ) { public String transform ( final String input ) { final String baseName = FilenameUtils . getBaseName ( input ) ; final String extension = FilenameUtils . getExtension ( input ) ; return baseName + suffix + "." + extension ; } } ;


signature:
public class JSMin { /** * action - - do something ! What you do is determined by the argument :
 * < ul >
 * < li > 1 Output A . Copy B to A . Get the next B . < / li >
 * < li > 2 Copy B to A . Get the next B . ( Delete A ) . < / li >
 * < li > 3 Get the next B . ( Delete B ) . < / li >
 * < / ul >
 * action treats a string as a single character . Wow ! < br / >
 * action recognizes a regular expression if it is preceded by ( or , or = . */
void action ( final int d ) throws IOException , UnterminatedRegExpLiteralException , UnterminatedCommentException , UnterminatedStringLiteralException { } }

implementation: switch ( d ) { case 1 : out . write ( theA ) ; if ( theA == theB && ( theA == '+' || theA == '-' ) && theY != theA ) { out . write ( ' ' ) ; } case 2 : theA = theB ; if ( theA == '\'' || theA == '"' || theA == '`' ) { for ( ; ; ) { out . write ( theA ) ; theA = get ( ) ; if ( theA == theB ) { break ; } if ( theA <= '\n' ) { throw new UnterminatedStringLiteralException ( ) ; } if ( theA == '\\' ) { out . write ( theA ) ; theA = get ( ) ; } } } case 3 : theB = next ( ) ; if ( theB == '/' && ( theA == '(' || theA == ',' || theA == '=' || theA == ':' || theA == '[' || theA == '!' || theA == '&' || theA == '|' || theA == '?' || theA == '+' || theA == '-' || theA == '~' || theA == '*' || theA == '/' || theA == '{' || theA == '\n' ) ) { out . write ( theA ) ; if ( theA == '/' || theA == '*' ) { out . write ( ' ' ) ; } out . write ( theB ) ; for ( ; ; ) { theA = get ( ) ; if ( theA == '[' ) { for ( ; ; ) { out . write ( theA ) ; theA = get ( ) ; if ( theA == ']' ) { break ; } if ( theA == '\\' ) { out . write ( theA ) ; theA = get ( ) ; } if ( theA <= '\n' ) { throw new UnterminatedRegExpLiteralException ( ) ; } } } else if ( theA == '/' ) { switch ( peek ( ) ) { case '/' : case '*' : throw new UnterminatedRegExpLiteralException ( ) ; } break ; } else if ( theA == '\\' ) { out . write ( theA ) ; theA = get ( ) ; } else if ( theA <= '\n' ) { throw new UnterminatedRegExpLiteralException ( ) ; } out . write ( theA ) ; } theB = next ( ) ; } }


signature:
public class ContentTypeResolver { /** * Returns a valid HTTP contentType ' s for a given filename . It first relies on the custom defaultContentTypeMap and if
 * not found it will fall back to defaultFileTypeMap from javax . activation . FileTypeMap . Examples : - " somefile . css "
 * resolves to " text / css " . - " somefile . js . png " resolves to " image / png " - " / blah / index . html resolves to " text / html " .
 * The implementation uses reflection to load < code > javax . activation . FileTypeMap < / code > class ( available in jdk6 ) in
 * order to be compatible with jdk5 . If this class is not available , the default content type is returned .
 * @ param fileName
 * with an filename extension
 * @ return contentType */
public static String get ( final String fileName ) { } }

implementation: final String extension = FilenameUtils . getExtension ( WroUtil . removeQueryString ( fileName . toLowerCase ( ) ) ) ; if ( defaultContentTypeMap . containsKey ( extension ) ) { return defaultContentTypeMap . get ( extension ) ; } try { final Class < ? > fileTypeMapClass = ClassLoader . getSystemClassLoader ( ) . loadClass ( "javax.activation.FileTypeMap" ) ; LOG . debug ( "using {} to resolve contentType" , fileTypeMapClass . getName ( ) ) ; final Object fileTypeMap = fileTypeMapClass . getMethod ( "getDefaultFileTypeMap" ) . invoke ( fileTypeMapClass ) ; return ( String ) fileTypeMapClass . getMethod ( "getContentType" , String . class ) . invoke ( fileTypeMap , fileName ) ; } catch ( final Exception e ) { LOG . debug ( "FileTypeMap is not available (probably jdk5 is used). Exception {}, with message: {}" , e . getClass ( ) , e . getMessage ( ) ) ; LOG . debug ( "Will use default content type: {} for fileName: {}" , DEFAULT_CONTENT_TYPE , fileName ) ; } return DEFAULT_CONTENT_TYPE ;


signature:
public class ContentTypeResolver { /** * Returns a valid HTTP contentType ' s for a given filename with charset . It first relies on the custom
 * defaultContentTypeMap and if not found it will fall back to defaultFileTypeMap from javax . activation . FileTypeMap .
 * Examples : - ( " somefile . css " , " UTF - 8 " ) resolves to " text / css " ; charset = UTF - 8 " . - ( " somefile . js . png " , " UTF - 8 " )
 * resolves to " image / png " - ( " / blah / index . html , " UTF - 8 " ) resolves to " text / html ; charset = 8"
 * @ param fileName
 * with an filename extension
 * @ param encoding
 * which encoding to use
 * @ return contentType */
public static String get ( final String fileName , final String encoding ) { } }

implementation: final String contentType = get ( fileName ) ; if ( requiresCharset . contains ( contentType ) ) { return contentType + "; charset=" + encoding ; } return contentType ;


signature:
public class ClasspathUriLocator { /** * { @ inheritDoc } */
public InputStream locate ( final String uri ) throws IOException { } }

implementation:
Validate . notNull ( uri , "URI cannot be NULL!" ) ; // replace prefix & clean path by removing ' . . ' characters if exists and
// normalizing the location to use .
String location = StringUtils . cleanPath ( uri . replaceFirst ( PREFIX , "" ) ) . trim ( ) ; if ( getWildcardStreamLocator ( ) . hasWildcard ( location ) ) { try { return locateWildcardStream ( uri , location ) ; } catch ( final IOException e ) { if ( location . contains ( "?" ) ) { location = DefaultWildcardStreamLocator . stripQueryPath ( location ) ; LOG . debug ( "Trying fallback location: {}" , location ) ; } } } final InputStream is = Thread . currentThread ( ) . getContextClassLoader ( ) . getResourceAsStream ( location ) ; if ( is == null ) { throw new IOException ( "Couldn't get InputStream from this resource: " + uri ) ; } return is ;


signature:
public class ClasspathUriLocator { /** * Builds a { @ link JarWildcardStreamLocator } in order to get resources from the full classpath . */
@ Override public WildcardStreamLocator newWildcardStreamLocator ( ) { } }

implementation: return new JarWildcardStreamLocator ( ) { @ Override public boolean hasWildcard ( final String uri ) { return isEnableWildcards ( ) && super . hasWildcard ( uri ) ; } } ;


signature:
public class DefaultNamingStrategyProvider { /** * { @ inheritDoc } */
public Map < String , NamingStrategy > provideNamingStrategies ( ) { } }

implementation: final Map < String , NamingStrategy > map = new HashMap < String , NamingStrategy > ( ) ; map . put ( TimestampNamingStrategy . ALIAS , new TimestampNamingStrategy ( ) ) ; map . put ( NoOpNamingStrategy . ALIAS , new NoOpNamingStrategy ( ) ) ; map . put ( DefaultHashEncoderNamingStrategy . ALIAS , new DefaultHashEncoderNamingStrategy ( ) ) ; map . put ( FolderHashEncoderNamingStrategy . ALIAS , new FolderHashEncoderNamingStrategy ( ) ) ; return map ;


signature:
public class RedirectedStreamServletResponseWrapper { /** * Use an empty stream to avoid container writing unwanted message when a resource is missing .
 * @ param sc
 * status code .
 * @ param msg */
private void onError ( final int sc , final String msg ) { } }

implementation: LOG . debug ( "Error detected with code: {} and message: {}" , sc , msg ) ; final OutputStream emptyStream = new ByteArrayOutputStream ( ) ; printWriter = new PrintWriter ( emptyStream ) ; servletOutputStream = new DelegatingServletOutputStream ( emptyStream ) ;


signature:
public class RedirectedStreamServletResponseWrapper { /** * By default , redirect does not allow writing to output stream its content . In order to support this use - case , we
 * need to open a new connection and read the content manually . */
@ Override public void sendRedirect ( final String location ) throws IOException { } }

implementation: try { LOG . debug ( "redirecting to: {}" , location ) ; final InputStream is = externalResourceLocator . locate ( location ) ; IOUtils . copy ( is , servletOutputStream ) ; is . close ( ) ; servletOutputStream . close ( ) ; } catch ( final IOException e ) { LOG . warn ( "{}: Invalid response for location: {}" , e . getClass ( ) . getName ( ) , location ) ; throw e ; }


signature:
public class WildcardExpanderModelTransformer { /** * { @ inheritDoc } */
public synchronized WroModel transform ( final WroModel input ) { } }

implementation: final WroModel model = input ; for ( final Group group : model . getGroups ( ) ) { final List < Resource > resources = group . getResources ( ) ; for ( final Resource resource : resources ) { processResource ( group , resource ) ; } } LOG . debug ( "Transformed model: {}" , model ) ; return model ;


signature:
public class WildcardExpanderModelTransformer { /** * Process each resource and replace it with a collection of resources if it contains wildcard . */
private void processResource ( final Group group , final Resource resource ) { } }

implementation:
final UriLocator uriLocator = locatorFactory . getInstance ( resource . getUri ( ) ) ; if ( uriLocator instanceof WildcardUriLocatorSupport ) { final WildcardStreamLocator wildcardStreamLocator = ( ( WildcardUriLocatorSupport ) uriLocator ) . getWildcardStreamLocator ( ) ; // TODO should we probably handle the situation when wildcard is present , but the implementation is not
// expandedHandledAware ?
if ( wildcardStreamLocator . hasWildcard ( resource . getUri ( ) ) && wildcardStreamLocator instanceof WildcardExpanderHandlerAware ) { final WildcardExpanderHandlerAware expandedHandler = ( WildcardExpanderHandlerAware ) wildcardStreamLocator ; LOG . debug ( "Expanding resource: {}" , resource . getUri ( ) ) ; final String baseNameFolder = computeBaseNameFolder ( resource , uriLocator , expandedHandler ) ; LOG . debug ( "baseNameFolder: {}" , baseNameFolder ) ; expandedHandler . setWildcardExpanderHandler ( createExpanderHandler ( group , resource , baseNameFolder ) ) ; try { // trigger the wildcard replacement
uriLocator . locate ( resource . getUri ( ) ) ; } catch ( final IOException e ) { // log only
LOG . debug ( "[FAIL] problem while trying to expand wildcard for the following resource uri: {}" , resource . getUri ( ) ) ; } finally { // remove the handler , it is not needed anymore
expandedHandler . setWildcardExpanderHandler ( null ) ; } } }


signature:
public class WildcardExpanderModelTransformer { /** * Computes the file name of the folder where the resource is located . The implementation uses a trick by invoking the
 * { @ link WildcardExpanderHandlerAware } to get the baseName . */
private String computeBaseNameFolder ( final Resource resource , final UriLocator uriLocator , final WildcardExpanderHandlerAware expandedHandler ) { } }

implementation:
// Find the baseName
// add a recursive wildcard to trigger the wildcard detection . The simple wildcard ( ' * ' ) is not enough because it
// won ' t work for folders containing only directories with no files .
LOG . debug ( "computeBaseNameFolder for resource {}" , resource ) ; final String resourcePath = FilenameUtils . getFullPath ( resource . getUri ( ) ) + DefaultWildcardStreamLocator . RECURSIVE_WILDCARD ; LOG . debug ( "resourcePath: {}" , resourcePath ) ; // use thread local because we need to assign a File inside an anonymous class and it fits perfectly
final ThreadLocal < String > baseNameFolderHolder = new ThreadLocal < String > ( ) ; expandedHandler . setWildcardExpanderHandler ( createBaseNameComputerFunction ( baseNameFolderHolder ) ) ; try { uriLocator . locate ( resourcePath ) ; } catch ( final Exception e ) { LOG . debug ( "[FAIL] Exception caught during wildcard expanding for resource: {}\n with exception message {}" , resourcePath , e . getMessage ( ) ) ; } if ( baseNameFolderHolder . get ( ) == null ) { LOG . debug ( "[FAIL] Cannot compute baseName folder for resource: {}" , resource ) ; } return baseNameFolderHolder . get ( ) ;


signature:
public class DuplicatesAwareCssDataUriPreProcessor { /** * Replace provided url with the new url if needed .
 * @ param imageUrl to replace .
 * @ param cssUri Uri of the parsed css .
 * @ return replaced url . */
@ Override protected final String replaceImageUrl ( final String cssUri , final String imageUrl ) { } }

implementation: if ( ! imageUrls . contains ( imageUrl ) ) { imageUrls . add ( imageUrl ) ; return super . replaceImageUrl ( cssUri , imageUrl ) ; } LOG . debug ( "duplicate Image url detected: '{}', skipping dataUri replacement" , imageUrl ) ; return imageUrl ;


signature:
public class AbstractUriLocatorFactory { /** * Locates an InputStream for the given uri .
 * @ param uri to locate .
 * @ return { @ link InputStream } of the resource .
 * @ throws IOException if uri is invalid or resource couldn ' t be located . */
public final InputStream locate ( final String uri ) throws IOException { } }

implementation: final UriLocator uriLocator = getInstance ( uri ) ; if ( uriLocator == null ) { throw new WroRuntimeException ( "No locator is capable of handling uri: " + uri ) ; } LOG . debug ( "[OK] locating {} using locator: {}" , uri , uriLocator . getClass ( ) . getSimpleName ( ) ) ; return new AutoCloseInputStream ( uriLocator . locate ( uri ) ) ;


signature:
public class CoffeeScript { /** * Initialize script builder for evaluation . */
private RhinoScriptBuilder initScriptBuilder ( ) { } }

implementation: try { RhinoScriptBuilder builder = null ; if ( scope == null ) { builder = RhinoScriptBuilder . newChain ( ) . evaluateChain ( getCoffeeScriptAsStream ( ) , DEFAULT_COFFE_SCRIPT ) ; scope = builder . getScope ( ) ; } else { builder = RhinoScriptBuilder . newChain ( scope ) ; } return builder ; } catch ( final IOException ex ) { throw new IllegalStateException ( "Failed reading init script" , ex ) ; }


signature:
public class CoffeeScript { /** * Validates a js using jsHint and throws { @ link LinterException } if the js is invalid . If no exception is thrown , the
 * js is valid .
 * @ param data
 * js content to process . */
public String compile ( final String data ) { } }

implementation: final RhinoScriptBuilder builder = initScriptBuilder ( ) ; final String compileScript = String . format ( "CoffeeScript.compile(%s, %s);" , WroUtil . toJSMultiLineString ( data ) , buildOptions ( ) ) ; return ( String ) builder . evaluate ( compileScript , "CoffeeScript.compile" ) ;


signature:
public class WroFilter { /** * Creates configuration by looking up in servletContext attributes . If none is found , a new one will be created using
 * the configuration factory .
 * @ return { @ link WroConfiguration } object . */
private WroConfiguration createConfiguration ( ) { } }

implementation:
// Extract config from servletContext ( if already configured )
// TODO use a named helper
final WroConfiguration configAttribute = ServletContextAttributeHelper . create ( filterConfig ) . getWroConfiguration ( ) ; if ( configAttribute != null ) { setConfiguration ( configAttribute ) ; } return getWroConfigurationFactory ( ) . create ( ) ;


signature:
public class WroFilter { /** * Creates { @ link WroManagerFactory } . */
private WroManagerFactory createWroManagerFactory ( ) { } }

implementation: if ( wroManagerFactory == null ) { final WroManagerFactory managerFactoryAttribute = ServletContextAttributeHelper . create ( filterConfig ) . getManagerFactory ( ) ; LOG . debug ( "managerFactory attribute: {}" , managerFactoryAttribute ) ; wroManagerFactory = managerFactoryAttribute != null ? managerFactoryAttribute : newWroManagerFactory ( ) ; } LOG . debug ( "created managerFactory: {}" , wroManagerFactory ) ; return wroManagerFactory ;


signature:
public class WroFilter { /** * Expose MBean to tell JMX infrastructure about our MBean ( only if jmxEnabled is true ) . */
private void registerMBean ( ) { } }

implementation: if ( wroConfiguration . isJmxEnabled ( ) ) { try { mbeanServer = getMBeanServer ( ) ; final ObjectName name = getMBeanObjectName ( ) ; if ( ! mbeanServer . isRegistered ( name ) ) { mbeanServer . registerMBean ( wroConfiguration , name ) ; } } catch ( final JMException e ) { LOG . error ( "Exception occured while registering MBean" , e ) ; } }


signature:
public class WroFilter { /** * Register property change listeners . */
private void registerChangeListeners ( ) { } }

implementation:
wroConfiguration . registerCacheUpdatePeriodChangeListener ( new PropertyChangeListener ( ) { public void propertyChange ( final PropertyChangeEvent event ) { // reset cache headers when any property is changed in order to avoid browser caching
headersConfigurer = newResponseHeadersConfigurer ( ) ; wroManagerFactory . onCachePeriodChanged ( valueAsLong ( event . getNewValue ( ) ) ) ; } } ) ; wroConfiguration . registerModelUpdatePeriodChangeListener ( new PropertyChangeListener ( ) { public void propertyChange ( final PropertyChangeEvent event ) { headersConfigurer = newResponseHeadersConfigurer ( ) ; wroManagerFactory . onModelPeriodChanged ( valueAsLong ( event . getNewValue ( ) ) ) ; } } ) ; LOG . debug ( "Cache & Model change listeners were registered" ) ;


signature:
public class WroFilter { /** * Perform actual processing . */
private void processRequest ( final HttpServletRequest request , final HttpServletResponse response ) throws ServletException , IOException { } }

implementation:
setResponseHeaders ( response ) ; // process the uri using manager
wroManagerFactory . create ( ) . process ( ) ;


signature:
public class WroFilter { /** * Invoked when a { @ link Exception } is thrown . Allows custom exception handling . The default implementation proceeds
 * with filter chaining when exception is thrown .
 * @ param e
 * { @ link Exception } thrown during request processing . */
protected void onException ( final Exception e , final HttpServletResponse response , final FilterChain chain ) { } }

implementation:
LOG . error ( "Exception occured" , e ) ; try { LOG . warn ( "Cannot process. Proceeding with chain execution." ) ; chain . doFilter ( Context . get ( ) . getRequest ( ) , response ) ; } catch ( final Exception ex ) { // should never happen ( use debug level to suppress unuseful logs )
LOG . debug ( "Error while chaining the request" , ex ) ; }


signature:
public class WroFilter { /** * Once set , this configuration will be used , instead of the one built by the factory .
 * @ param config
 * a not null { @ link WroConfiguration } to set . */
public final void setConfiguration ( final WroConfiguration config ) { } }

implementation: notNull ( config ) ; wroConfigurationFactory = new ObjectFactory < WroConfiguration > ( ) { public WroConfiguration create ( ) { return config ; } } ;


signature:
public class WroFilter { /** * { @ inheritDoc } */
public void destroy ( ) { } }

implementation:
// Avoid memory leak by unregistering mBean on destroy
unregisterMBean ( ) ; if ( wroManagerFactory != null ) { wroManagerFactory . destroy ( ) ; } if ( wroConfiguration != null ) { wroConfiguration . destroy ( ) ; } Context . destroy ( ) ;


signature:
public class WroModel { /** * Identify duplicate group names .
 * @ param groups a collection of group to validate . */
private void identifyDuplicateGroupNames ( final Collection < Group > groups ) { } }

implementation: LOG . debug ( "identifyDuplicateGroupNames" ) ; final List < String > groupNames = new ArrayList < String > ( ) ; for ( final Group group : groups ) { if ( groupNames . contains ( group . getName ( ) ) ) { throw new WroRuntimeException ( "Duplicate group name detected: " + group . getName ( ) ) ; } groupNames . add ( group . getName ( ) ) ; }


signature:
public class WroModel { /** * Merge this model with another model . This is useful for supporting model imports .
 * @ param importedModel model to import . */
public void merge ( final WroModel importedModel ) { } }

implementation: Validate . notNull ( importedModel , "imported model cannot be null!" ) ; LOG . debug ( "merging importedModel: {}" , importedModel ) ; for ( final String groupName : new WroModelInspector ( importedModel ) . getGroupNames ( ) ) { if ( new WroModelInspector ( this ) . getGroupNames ( ) . contains ( groupName ) ) { throw new WroRuntimeException ( "Duplicate group name detected: " + groupName ) ; } final Group importedGroup = new WroModelInspector ( importedModel ) . getGroupByName ( groupName ) ; addGroup ( importedGroup ) ; }


signature:
public class PackerJsProcessor { /** * { @ inheritDoc } */
@ Override public void process ( final Resource resource , final Reader reader , final Writer writer ) throws IOException { } }

implementation: final String content = IOUtils . toString ( reader ) ; final PackerJs packerJs = enginePool . getObject ( ) ; try { writer . write ( packerJs . pack ( content ) ) ; } catch ( final WroRuntimeException e ) { onException ( e ) ; final String resourceUri = resource == null ? StringUtils . EMPTY : "[" + resource . getUri ( ) + "]" ; LOG . warn ( "Exception while applying " + getClass ( ) . getSimpleName ( ) + " processor on the " + resourceUri + " resource, no processing applied..." , e ) ; } finally { reader . close ( ) ; writer . close ( ) ; enginePool . returnObject ( packerJs ) ; }


signature:
public class InjectableUriLocatorFactoryDecorator { /** * This implementation shows the problem with current design of locator implementation . Needs to be changed . */
public InputStream locate ( final String uri ) throws IOException { } }

implementation: final UriLocator locator = getInstance ( uri ) ; if ( locator == null ) { return getDecoratedObject ( ) . locate ( uri ) ; } return locator . locate ( uri ) ;


signature:
public class JSMinProcessor { /** * { @ inheritDoc } */
public void process ( final Resource resource , final Reader reader , final Writer writer ) throws IOException { } }

implementation: final InputStream is = new ProxyInputStream ( new ReaderInputStream ( reader , getEncoding ( ) ) ) { } ; final OutputStream os = new ProxyOutputStream ( new WriterOutputStream ( writer , getEncoding ( ) ) ) ; try { new JSMin ( is , os ) . jsmin ( ) ; is . close ( ) ; os . close ( ) ; } catch ( final Exception e ) { throw WroRuntimeException . wrap ( e ) ; } finally { IOUtils . closeQuietly ( is ) ; IOUtils . closeQuietly ( os ) ; }


signature:
public class GroupsProcessor { /** * Apply resourcePostProcessors .
 * @ param cacheKey
 * the { @ link CacheKey } being processed .
 * @ param content
 * to process with all postProcessors .
 * @ return the post processed content . */
private String applyPostProcessors ( final CacheKey cacheKey , final String content ) throws IOException { } }

implementation: final Collection < ResourcePostProcessor > processors = processorsFactory . getPostProcessors ( ) ; LOG . debug ( "appying post processors: {}" , processors ) ; if ( processors . isEmpty ( ) ) { return content ; } final Resource resource = Resource . create ( cacheKey . getGroupName ( ) , cacheKey . getType ( ) ) ; Reader reader = new StringReader ( content . toString ( ) ) ; Writer writer = null ; for ( final ResourcePostProcessor processor : processors ) { final ResourcePreProcessor decoratedProcessor = decorateProcessor ( processor , cacheKey . isMinimize ( ) ) ; writer = new StringWriter ( ) ; decoratedProcessor . process ( resource , reader , writer ) ; reader = new StringReader ( writer . toString ( ) ) ; } return writer . toString ( ) ;


signature:
public class GroupsProcessor { /** * This method is synchronized to ensure that processor is injected before it is being used by other thread .
 * @ return a decorated processor . */
private synchronized ProcessorDecorator decorateProcessor ( final ResourcePostProcessor processor , final boolean minimize ) { } }

implementation: final ProcessorDecorator decorated = new DefaultProcessorDecorator ( processor , minimize ) { @ Override public void process ( final Resource resource , final Reader reader , final Writer writer ) throws IOException { try { callbackRegistry . onBeforePostProcess ( ) ; super . process ( resource , reader , writer ) ; } finally { callbackRegistry . onAfterPostProcess ( ) ; } } } ; injector . inject ( decorated ) ; return decorated ;


signature:
public class WroContextFilter { /** * { @ inheritDoc } */
public final void doFilter ( final ServletRequest req , final ServletResponse res , final FilterChain chain ) throws IOException , ServletException { } }

implementation:
final HttpServletRequest request = ( HttpServletRequest ) req ; final HttpServletResponse response = ( HttpServletResponse ) res ; // preserve current correlationId to ensure proper clean up during nested requests .
final String originalCorrelationId = Context . isContextSet ( ) ? Context . getCorrelationId ( ) : null ; Context . set ( Context . webContext ( request , response , this . filterConfig ) , getWroConfiguration ( ) ) ; final String correlationId = Context . getCorrelationId ( ) ; try { chain . doFilter ( request , response ) ; } finally { Context . setCorrelationId ( correlationId ) ; Context . unset ( ) ; if ( originalCorrelationId != null ) { Context . setCorrelationId ( originalCorrelationId ) ; } }


signature:
public class AbstractProcessorsFilter { /** * { @ inheritDoc } */
public void doFilter ( final ServletRequest req , final ServletResponse res , final FilterChain chain ) throws IOException , ServletException { } }

implementation:
final HttpServletRequest request = ( HttpServletRequest ) req ; final HttpServletResponse response = ( HttpServletResponse ) res ; try { // add request , response & servletContext to thread local
Context . set ( Context . webContext ( request , response , filterConfig ) ) ; final ByteArrayOutputStream os = new ByteArrayOutputStream ( ) ; final HttpServletResponse wrappedResponse = new RedirectedStreamServletResponseWrapper ( os , response ) ; chain . doFilter ( request , wrappedResponse ) ; final Reader reader = new StringReader ( new String ( os . toByteArray ( ) , Context . get ( ) . getConfig ( ) . getEncoding ( ) ) ) ; final StringWriter writer = new StringWriter ( ) ; final String requestUri = request . getRequestURI ( ) . replaceFirst ( request . getContextPath ( ) , "" ) ; doProcess ( requestUri , reader , writer ) ; // it is important to update the contentLength to new value , otherwise the transfer can be closed without all
// bytes being read . Some browsers ( chrome ) complains with the following message : ERR _ CONNECTION _ CLOSED
final int contentLength = writer . getBuffer ( ) . length ( ) ; response . setContentLength ( contentLength ) ; // Content length can be 0 when the 30x ( not modified ) status code is returned .
if ( contentLength > 0 ) { IOUtils . write ( writer . toString ( ) , response . getOutputStream ( ) ) ; } } catch ( final RuntimeException e ) { onRuntimeException ( e , response , chain ) ; } finally { Context . unset ( ) ; }


signature:
public class AbstractProcessorsFilter { /** * Applies configured processor on the intercepted stream . */
private void doProcess ( final String requestUri , final Reader reader , final Writer writer ) throws IOException { } }

implementation:
Reader input = reader ; Writer output = null ; LOG . debug ( "processing resource: {}" , requestUri ) ; try { final StopWatch stopWatch = new StopWatch ( ) ; final Injector injector = InjectorBuilder . create ( new BaseWroManagerFactory ( ) ) . build ( ) ; final List < ResourcePreProcessor > processors = getProcessorsList ( ) ; if ( processors == null || processors . isEmpty ( ) ) { IOUtils . copy ( reader , writer ) ; } else { for ( final ResourcePreProcessor processor : processors ) { stopWatch . start ( "Using " + processor . getClass ( ) . getSimpleName ( ) ) ; // inject all required properties
injector . inject ( processor ) ; output = new StringWriter ( ) ; LOG . debug ( "Using {} processor" , processor ) ; processor . process ( createResource ( requestUri ) , input , output ) ; input = new StringReader ( output . toString ( ) ) ; stopWatch . stop ( ) ; } LOG . debug ( stopWatch . prettyPrint ( ) ) ; if ( output != null ) { writer . write ( output . toString ( ) ) ; } } } finally { reader . close ( ) ; writer . close ( ) ; }


signature:
public class AbstractProcessorsFilter { /** * Invoked when a { @ link RuntimeException } is thrown . Allows custom exception handling . The default implementation
 * redirects to 404 for a specific { @ link WroRuntimeException } exception when in DEPLOYMENT mode .
 * @ param e
 * { @ link RuntimeException } thrown during request processing . */
protected void onRuntimeException ( final RuntimeException e , final HttpServletResponse response , final FilterChain chain ) { } }

implementation:
LOG . debug ( "RuntimeException occured" , e ) ; try { LOG . debug ( "Cannot process. Proceeding with chain execution." ) ; chain . doFilter ( Context . get ( ) . getRequest ( ) , response ) ; } catch ( final Exception ex ) { // should never happen
LOG . error ( "Error while chaining the request." ) ; }


signature:
public class OptionsBuilder { /** * Split multiple options into an array of options .
 * @ param optionAsString string representation of multiple options .
 * @ return an array of options . */
public String [ ] splitOptions ( final String optionAsString ) { } }

implementation: return optionAsString == null ? ArrayUtils . EMPTY_STRING_ARRAY : optionAsString . split ( "(?ims),(?![^\\[\\]]*\\])" ) ;