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

implementation: try { RhinoScriptBuilder builder = null ; if ( scope == null ) { builder = RhinoScriptBuilder . newClientSideAwareChain ( ) . addJSON ( ) . evaluateChain ( getScriptAsStream ( ) , "cjson.js" ) ; scope = builder . getScope ( ) ; } else { builder = RhinoScriptBuilder . newChain ( scope ) ; } return builder ; } catch ( final Exception e ) { LOG . error ( "Processing error:" + e . getMessage ( ) , e ) ; throw new WroRuntimeException ( "Processing error" , e ) ; }


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

implementation: try { RhinoScriptBuilder builder = null ; if ( scope == null ) { final InputStream initStream = LessCss . class . getResourceAsStream ( SCRIPT_INIT ) ; builder = RhinoScriptBuilder . newClientSideAwareChain ( ) . evaluateChain ( initStream , SCRIPT_INIT ) . evaluateChain ( getScriptAsStream ( ) , DEFAULT_LESS_JS ) ; scope = builder . getScope ( ) ; } else { builder = RhinoScriptBuilder . newChain ( scope ) ; } return builder ; } catch ( final IOException ex ) { throw new IllegalStateException ( "Failed reading javascript less.js" , ex ) ; } catch ( final Exception e ) { LOG . error ( "Processing error:" + e . getMessage ( ) , e ) ; throw new WroRuntimeException ( "Processing error" , e ) ; }


signature:
public class RegexpProperties { /** * Load the properties from the stream . The implementation will handle comments properly by removing them before
 * properties are loaded .
 * @ param inputStream
 * @ return { @ link Properties } containing properties parsed from the stream .
 * @ throws IOException */
public Properties load ( final InputStream inputStream ) throws IOException { } }

implementation: Validate . notNull ( inputStream ) ; final String rawContent = IOUtils . toString ( inputStream , CharEncoding . UTF_8 ) ; parseProperties ( rawContent . replaceAll ( REGEX_COMMENTS , "" ) ) ; return this . properties ;


signature:
public class RegexpProperties { /** * parse the properties from the provided string containing a raw properties */
private void parseProperties ( final String propertiesAsString ) { } }

implementation:
// should work also \ r ? \ n
final String [ ] propertyEntries = propertiesAsString . split ( "\\r?\\n" ) ; for ( final String entry : propertyEntries ) { readPropertyEntry ( entry ) ; }


signature:
public class AbstractWro4jMojo { /** * Creates a { @ link StandaloneContext } by setting properties passed after mojo is initialized . */
private StandaloneContext createStandaloneContext ( ) { } }

implementation: final StandaloneContext runContext = new StandaloneContext ( ) ; runContext . setContextFoldersAsCSV ( getContextFoldersAsCSV ( ) ) ; runContext . setMinimize ( isMinimize ( ) ) ; runContext . setWroFile ( getWroFile ( ) ) ; runContext . setIgnoreMissingResourcesAsString ( isIgnoreMissingResources ( ) ) ; return runContext ;


signature:
public class AbstractWro4jMojo { /** * This method will ensure that you have a right and initialized instance of { @ link StandaloneContextAware } .
 * @ return { @ link WroManagerFactory } implementation . */
protected final WroManagerFactory getManagerFactory ( ) { } }

implementation: if ( managerFactory == null ) { try { managerFactory = wroManagerFactory != null ? createCustomManagerFactory ( ) : newWroManagerFactory ( ) ; onAfterCreate ( managerFactory ) ; } catch ( final MojoExecutionException e ) { throw WroRuntimeException . wrap ( e ) ; } } return managerFactory ;


signature:
public class AbstractWro4jMojo { /** * Creates a custom instance of Manager factory . The wroManagerFactory parameter value is used to identify the manager class . */
private WroManagerFactory createCustomManagerFactory ( ) throws MojoExecutionException { } }

implementation: WroManagerFactory factory = null ; try { final Class < ? > wroManagerFactoryClass = Thread . currentThread ( ) . getContextClassLoader ( ) . loadClass ( wroManagerFactory . trim ( ) ) ; factory = ( WroManagerFactory ) wroManagerFactoryClass . newInstance ( ) ; } catch ( final Exception e ) { throw new MojoExecutionException ( "Invalid wroManagerFactoryClass, called: " + wroManagerFactory , e ) ; } return factory ;


signature:
public class AbstractWro4jMojo { /** * Allows explicitly to override the default implementation of the factory , assuming { @ link # wroManagerFactory }
 * configuration is not set . When overriding this method , make sure that { @ link # onAfterCreate ( WroManagerFactory ) } is
 * invoked on newly created factory for proper initialization . */
protected WroManagerFactory newWroManagerFactory ( ) throws MojoExecutionException { } }

implementation: WroManagerFactory factory = null ; if ( wroManagerFactory == null ) { factory = new ConfigurableWroManagerFactory ( ) ; } getLog ( ) . info ( "wroManagerFactory class: " + factory . getClass ( ) . getName ( ) ) ; return factory ;


signature:
public class AbstractWro4jMojo { /** * Initialize the created { @ link WroManagerFactory } with additional configurations which are not available during
 * creation . Make sure this method is invoked on a custom factory when { @ link # newWroManagerFactory ( ) } is overridden . */
private void onAfterCreate ( final WroManagerFactory factory ) throws MojoExecutionException { } }

implementation:
if ( factory instanceof ExtraConfigFileAware ) { if ( extraConfigFile == null ) { throw new MojoExecutionException ( "The " + factory . getClass ( ) + " requires a valid extraConfigFile!" ) ; } getLog ( ) . debug ( "Using extraConfigFile: " + extraConfigFile . getAbsolutePath ( ) ) ; ( ( ExtraConfigFileAware ) factory ) . setExtraConfigFile ( extraConfigFile ) ; } // initialize before process .
if ( factory instanceof StandaloneContextAware ) { ( ( StandaloneContextAware ) factory ) . initialize ( createStandaloneContext ( ) ) ; }


signature:
public class AbstractWro4jMojo { /** * Store digest for all resources contained inside the list of provided groups . */
private void persistResourceFingerprints ( final List < String > groupNames ) { } }

implementation: final WroModelInspector modelInspector = new WroModelInspector ( getModel ( ) ) ; for ( final String groupName : groupNames ) { final Group group = modelInspector . getGroupByName ( groupName ) ; if ( group != null ) { for ( final Resource resource : group . getResources ( ) ) { getResourceChangeHandler ( ) . remember ( resource ) ; } } }


signature:
public class AbstractWro4jMojo { /** * Check if the provided group is a target group . */
private boolean isTargetGroup ( final Group group ) { } }

implementation:
notNull ( group ) ; final String targetGroups = getTargetGroups ( ) ; // null , means all groups are target groups
return targetGroups == null || targetGroups . contains ( group . getName ( ) ) ;


signature:
public class AbstractWro4jMojo { /** * Update the classpath . */
protected final void extendPluginClasspath ( ) throws MojoExecutionException { } }

implementation:
// this code is inspired from http : / / teleal . org / weblog / Extending % 20the % 20Maven % 20plugin % 20classpath . html
final List < String > classpathElements = new ArrayList < String > ( ) ; try { classpathElements . addAll ( mavenProject . getRuntimeClasspathElements ( ) ) ; } catch ( final DependencyResolutionRequiredException e ) { throw new MojoExecutionException ( "Could not get compile classpath elements" , e ) ; } final ClassLoader classLoader = createClassLoader ( classpathElements ) ; Thread . currentThread ( ) . setContextClassLoader ( classLoader ) ;


signature:
public class MinimizeAwareProcessorDecorator { /** * { @ inheritDoc } */
@ Override protected boolean isEnabled ( final Resource resource ) { } }

implementation:
// apply processor only when minimize is required or the processor is not minimize aware
final boolean applyProcessor = ( resource != null && resource . isMinimize ( ) && minimize ) || ( resource == null && minimize ) || ! isMinimize ( ) ; return super . isEnabled ( resource ) && applyProcessor ;


signature:
public class AbstractWroModelFactory { /** * Override this method , in order to provide different xml definition file name .
 * @ return stream of the xml representation of the model .
 * @ throws IOException
 * if the stream couldn ' t be read . */
protected InputStream getModelResourceAsStream ( ) throws IOException { } }

implementation:
final ServletContext servletContext = context . getServletContext ( ) ; // Don ' t allow NPE , throw a more detailed exception
if ( servletContext == null ) { throw new WroRuntimeException ( "No servletContext is available. Probably you are running this code outside of the request cycle!" ) ; } final String resourceLocation = "/WEB-INF/" + getDefaultModelFilename ( ) ; final InputStream stream = servletContext . getResourceAsStream ( resourceLocation ) ; if ( stream == null ) { throw new IOException ( "Invalid resource requested: " + resourceLocation ) ; } return stream ;


signature:
public class Resource { /** * Creates a resource and set the correct { @ link ResourceType } based on uri extension . If resourceType cannot be
 * identified an exception is thrown .
 * @ param uri of the resource to create .
 * @ return Resource with the provided uri and correct type . */
public static Resource create ( final String uri ) { } }

implementation: final String resourceExtension = FilenameUtils . getExtension ( uri ) ; final ResourceType type = ResourceType . get ( resourceExtension ) ; return new Resource ( uri , type ) ;


signature:
public class Resource { /** * Perform a cleaning of the uri by trimming it and removing last ' / ' character if exists .
 * @ param uri to clean .
 * @ return cleaned uri . */
private static String cleanUri ( final String uri ) { } }

implementation:
String result = uri . trim ( ) ; // handle empty uri
if ( ! StringUtils . isEmpty ( uri ) ) { final int endIndex = result . length ( ) - 1 ; if ( result . lastIndexOf ( '/' ) == endIndex ) { result = result . substring ( 0 , endIndex ) ; } } return result ;


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

implementation:
notNull ( uri , "uri cannot be NULL!" ) ; if ( getWildcardStreamLocator ( ) . hasWildcard ( uri ) ) { final String fullPath = FilenameUtils . getFullPath ( uri ) ; final URL url = new URL ( fullPath ) ; return getWildcardStreamLocator ( ) . locateStream ( uri , new File ( URLDecoder . decode ( url . getFile ( ) , "UTF-8" ) ) ) ; } final URL url = new URL ( uri ) ; final URLConnection connection = url . openConnection ( ) ; // avoid jar file locking on Windows .
connection . setUseCaches ( false ) ; // add explicit user agent header . This is required by some cdn resources which otherwise would return 403 status code .
connection . setRequestProperty ( "User-Agent" , "java" ) ; // setting these timeouts ensures the client does not deadlock indefinitely
// when the server has problems .
connection . setConnectTimeout ( timeout ) ; connection . setReadTimeout ( timeout ) ; return new BufferedInputStream ( connection . getInputStream ( ) ) ;


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

implementation: try { final String content = IOUtils . toString ( reader ) ; String result = ConsoleStripperProcessor . PATTERN . matcher ( content ) . replaceAll ( "" ) ; writer . write ( result ) ; } finally { reader . close ( ) ; writer . close ( ) ; }


signature:
public class DefaultWroManagerFactory { /** * A factory method which uses { @ link WroConfiguration } to get the configured wroManager className .
 * @ param configuration
 * { @ link WroConfiguration } to get the { @ link ConfigConstants # managerFactoryClassName } from . */
public static DefaultWroManagerFactory create ( final WroConfiguration configuration ) { } }

implementation: return create ( new ObjectFactory < WroConfiguration > ( ) { public WroConfiguration create ( ) { return configuration ; } } ) ;


signature:
public class DefaultWroManagerFactory { /** * Initialized inner factory based on provided configuration . */
private WroManagerFactory initFactory ( final Properties properties ) { } }

implementation:
WroManagerFactory factory = null ; final String wroManagerClassName = properties . getProperty ( ConfigConstants . managerFactoryClassName . name ( ) ) ; if ( StringUtils . isEmpty ( wroManagerClassName ) ) { // If no context param was specified we return the default factory
factory = newManagerFactory ( ) ; } else { // Try to find the specified factory class
Class < ? > factoryClass = null ; try { factoryClass = Thread . currentThread ( ) . getContextClassLoader ( ) . loadClass ( wroManagerClassName ) ; factory = ( WroManagerFactory ) factoryClass . newInstance ( ) ; } catch ( final Exception e ) { throw new WroRuntimeException ( "Exception while loading WroManagerFactory class:" + wroManagerClassName , e ) ; } } // add properties if required
if ( factory instanceof ConfigurableWroManagerFactory ) { ( ( ConfigurableWroManagerFactory ) factory ) . addConfigProperties ( properties ) ; } return factory ;


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

implementation: try { return RhinoScriptBuilder . newChain ( ) . evaluateChain ( getStreamForBase2 ( ) , "base2.min.js" ) . evaluateChain ( getStreamForPacker ( ) , "packer.min.js" ) ; } catch ( final IOException ex ) { throw new IllegalStateException ( "Failed reading init script" , ex ) ; }


signature:
public class ModelTransformerFactory { /** * Set a list of transformers to apply on decorated model factory . */
public ModelTransformerFactory setTransformers ( final List < Transformer < WroModel > > modelTransformers ) { } }

implementation: Validate . notNull ( modelTransformers ) ; this . modelTransformers = modelTransformers ; return this ;


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

implementation: WroModel model = super . create ( ) ; LOG . debug ( "using {} transformers" , modelTransformers ) ; for ( final Transformer < WroModel > transformer : modelTransformers ) { injector . inject ( transformer ) ; LOG . debug ( "using transformer: {}" , transformer . getClass ( ) ) ; try { model = transformer . transform ( model ) ; } catch ( final Exception e ) { throw new WroRuntimeException ( "Exception during model transformation" , e ) ; } } return model ;


signature:
public class EmberJs { /** * visible for testing , the init of a HandlebarsJs template */
@ Override public String compile ( final String content , final String name ) { } }

implementation: final String precompiledFunction = super . compile ( content , "" ) ; return String . format ( "(function() {Ember.TEMPLATES[%s] = Ember.Handlebars.template(%s)})();" , name , precompiledFunction ) ;


signature:
public class EmberJs { /** * { @ inheritDoc } */
@ Override protected InputStream getCompilerAsStream ( ) throws IOException { } }

implementation: final Vector < InputStream > inputStreams = new Vector < InputStream > ( ) ; inputStreams . add ( getWebjarLocator ( ) . locate ( WebjarUriLocator . createUri ( "jquery.js" ) ) ) ; inputStreams . add ( getWebjarLocator ( ) . locate ( WebjarUriLocator . createUri ( "handlebars.js" ) ) ) ; inputStreams . add ( getWebjarLocator ( ) . locate ( WebjarUriLocator . createUri ( "ember.js" ) ) ) ; inputStreams . add ( EmberJs . class . getResourceAsStream ( DEFAULT_HEADLESS_RHINO_JS ) ) ; return new SequenceInputStream ( inputStreams . elements ( ) ) ;


signature:
public class AbstractCssUrlRewritingProcessor { /** * Check if url must be replaced or not . The replacement is not needed if the url of the image is absolute ( can be
 * resolved by urlResourceLocator ) or if the url is a data uri ( base64 encoded value ) .
 * @ param url
 * to check .
 * @ return true if url needs to be replaced or remain unchanged . */
protected boolean isReplaceNeeded ( final String url ) { } }

implementation: return ! ( UrlUriLocator . isValid ( url ) || DataUriGenerator . isDataUri ( url . trim ( ) ) ) ;


signature:
public class PreProcessorExecutor { /** * Apply preProcessors on resources and merge them after all preProcessors are applied .
 * @ param resources
 * what are the resources to merge .
 * @ param minimize
 * whether minimize aware processors must be applied or not .
 * @ return preProcessed merged content . */
public String processAndMerge ( final List < Resource > resources , final boolean minimize ) throws IOException { } }

implementation: return processAndMerge ( resources , ProcessingCriteria . create ( ProcessingType . ALL , minimize ) ) ;


signature:
public class PreProcessorExecutor { /** * Apply preProcessors on resources and merge them .
 * @ param resources
 * what are the resources to merge .
 * @ param criteria
 * { @ link ProcessingCriteria } used to identify the processors to apply and those to skip .
 * @ return preProcessed merged content . */
public String processAndMerge ( final List < Resource > resources , final ProcessingCriteria criteria ) throws IOException { } }

implementation: notNull ( criteria ) ; LOG . debug ( "criteria: {}" , criteria ) ; callbackRegistry . onBeforeMerge ( ) ; try { notNull ( resources ) ; LOG . debug ( "process and merge resources: {}" , resources ) ; final StringBuffer result = new StringBuffer ( ) ; if ( shouldRunInParallel ( resources ) ) { result . append ( runInParallel ( resources , criteria ) ) ; } else { for ( final Resource resource : resources ) { LOG . debug ( "\tmerging resource: {}" , resource ) ; result . append ( applyPreProcessors ( resource , criteria ) ) ; } } return result . toString ( ) ; } finally { callbackRegistry . onAfterMerge ( ) ; }


signature:
public class PreProcessorExecutor { /** * runs the pre processors in parallel .
 * @ return merged and pre processed content . */
private String runInParallel ( final List < Resource > resources , final ProcessingCriteria criteria ) throws IOException { } }

implementation:
LOG . debug ( "Running preProcessing in Parallel" ) ; final StringBuffer result = new StringBuffer ( ) ; final List < Callable < String > > callables = new ArrayList < Callable < String > > ( ) ; for ( final Resource resource : resources ) { callables . add ( new Callable < String > ( ) { public String call ( ) throws Exception { LOG . debug ( "Callable started for resource: {} ..." , resource ) ; return applyPreProcessors ( resource , criteria ) ; } } ) ; } final ExecutorService exec = getExecutorService ( ) ; final List < Future < String > > futures = new ArrayList < Future < String > > ( ) ; for ( final Callable < String > callable : callables ) { // decorate with ContextPropagatingCallable in order to allow spawn threads to access the Context
final Callable < String > decoratedCallable = new ContextPropagatingCallable < String > ( callable ) ; futures . add ( exec . submit ( decoratedCallable ) ) ; } for ( final Future < String > future : futures ) { try { result . append ( future . get ( ) ) ; } catch ( final Exception e ) { // propagate original cause
final Throwable cause = e . getCause ( ) ; if ( cause instanceof WroRuntimeException ) { throw ( WroRuntimeException ) cause ; } else if ( cause instanceof IOException ) { throw ( IOException ) cause ; } else { throw new WroRuntimeException ( "Problem during parallel pre processing" , e ) ; } } } return result . toString ( ) ;


signature:
public class PreProcessorExecutor { /** * Apply a list of preprocessors on a resource .
 * @ param resource
 * the { @ link Resource } on which processors will be applied
 * @ param processors
 * the list of processor to apply on the resource . */
private String applyPreProcessors ( final Resource resource , final ProcessingCriteria criteria ) throws IOException { } }

implementation:
final Collection < ResourcePreProcessor > processors = processorsFactory . getPreProcessors ( ) ; LOG . debug ( "applying preProcessors: {}" , processors ) ; String resourceContent = null ; try { resourceContent = getResourceContent ( resource ) ; } catch ( final IOException e ) { LOG . debug ( "Invalid resource found: {}" , resource ) ; if ( Context . get ( ) . getConfig ( ) . isIgnoreMissingResources ( ) ) { return StringUtils . EMPTY ; } else { LOG . error ( "Cannot ignore missing resource:  {}" , resource ) ; throw e ; } } if ( ! processors . isEmpty ( ) ) { Writer writer = null ; for ( final ResourcePreProcessor processor : processors ) { final ResourcePreProcessor decoratedProcessor = decoratePreProcessor ( processor , criteria ) ; writer = new StringWriter ( ) ; final Reader reader = new StringReader ( resourceContent ) ; // decorate and process
decoratedProcessor . process ( resource , reader , writer ) ; // use the outcome for next input
resourceContent = writer . toString ( ) ; } } // add explicitly new line at the end to avoid unexpected comment issue
return String . format ( "%s%n" , resourceContent ) ;


signature:
public class PreProcessorExecutor { /** * Decorates preProcessor with mandatory decorators .
 * This method is synchronized to ensure that processor is injected before it is being used by other thread . */
private synchronized ResourcePreProcessor decoratePreProcessor ( final ResourcePreProcessor processor , final ProcessingCriteria criteria ) { } }

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


signature:
public class LifecycleCallbackRegistry { /** * { @ inheritDoc } */
public void onBeforeModelCreated ( ) { } }

implementation: forEachCallbackDo ( new Function < LifecycleCallback , Void > ( ) { public Void apply ( final LifecycleCallback input ) throws Exception { input . onBeforeModelCreated ( ) ; return null ; } } ) ;


signature:
public class BuildContextHolder { /** * Persist the fallbackStorage to the fallbackStorageFile . This method should be invoked only once during build , since
 * it is relatively expensive . Not invoking it , would break the incremental build feature . */
public void persist ( ) { } }

implementation: OutputStream os = null ; try { os = new FileOutputStream ( fallbackStorageFile ) ; fallbackStorage . store ( os , "Generated" ) ; LOG . debug ( "fallback storage written to {}" , fallbackStorageFile ) ; } catch ( final IOException e ) { LOG . warn ( "Cannot persist fallback storage: {}." , fallbackStorageFile , e ) ; } finally { IOUtils . closeQuietly ( os ) ; }


signature:
public class Injector { /** * Scans the object and inject the supported values into the fields having @ Inject annotation present .
 * @ param object
 * { @ link Object } which will be scanned for @ Inject annotation presence .
 * @ return the injected object instance . Useful for fluent interface . */
public < T > T inject ( final T object ) { } }

implementation:
notNull ( object ) ; // if ( ! Context . isContextSet ( ) ) {
// throw new WroRuntimeException ( " No Context Set " ) ;
if ( ! injectedObjects . containsKey ( computeKey ( object ) ) ) { injectedObjects . put ( computeKey ( object ) , true ) ; processInjectAnnotation ( object ) ; } return object ;


signature:
public class Injector { /** * Check for each field from the passed object if @ Inject annotation is present & inject the required field if
 * supported , otherwise warns about invalid usage .
 * @ param object
 * to check for annotation presence . */
private void processInjectAnnotation ( final Object object ) { } }

implementation:
try { final Collection < Field > fields = getAllFields ( object ) ; for ( final Field field : fields ) { if ( field . isAnnotationPresent ( Inject . class ) ) { if ( ! acceptAnnotatedField ( object , field ) ) { final String message = String . format ( "@Inject cannot be applied on object: %s to field of type: %s using injector %s" , object , field . getType ( ) , this ) ; LOG . error ( message + ". Supported types are: {}" , map . keySet ( ) ) ; throw new WroRuntimeException ( message ) ; } } } // handle special cases like decorators . Perform recursive injection
if ( object instanceof ObjectDecorator ) { processInjectAnnotation ( ( ( ObjectDecorator < ? > ) object ) . getDecoratedObject ( ) ) ; } } catch ( final Exception e ) { LOG . error ( "Error while scanning @Inject annotation" , e ) ; throw WroRuntimeException . wrap ( e , "Exception while trying to process @Inject annotation on object: " + object ) ; }


signature:
public class Injector { /** * Return all fields for given object , also those from the super classes . */
private Collection < Field > getAllFields ( final Object object ) { } }

implementation:
final Collection < Field > fields = new ArrayList < Field > ( ) ; fields . addAll ( Arrays . asList ( object . getClass ( ) . getDeclaredFields ( ) ) ) ; // inspect super classes
Class < ? > superClass = object . getClass ( ) . getSuperclass ( ) ; while ( superClass != null ) { fields . addAll ( Arrays . asList ( superClass . getDeclaredFields ( ) ) ) ; superClass = superClass . getSuperclass ( ) ; } return fields ;


signature:
public class Injector { /** * Analyze the field containing { @ link Inject } annotation and set its value to appropriate value . Override this method
 * if you want to inject something else but uriLocatorFactory .
 * @ param object
 * an object containing @ Inject annotation .
 * @ param field
 * { @ link Field } object containing { @ link Inject } annotation .
 * @ return true if field was injected with some not null value .
 * @ throws IllegalAccessException */
private boolean acceptAnnotatedField ( final Object object , final Field field ) throws IllegalAccessException { } }

implementation:
boolean accept = false ; // accept private modifiers
field . setAccessible ( true ) ; for ( final Map . Entry < Class < ? > , Object > entry : map . entrySet ( ) ) { if ( entry . getKey ( ) . isAssignableFrom ( field . getType ( ) ) ) { Object value = entry . getValue ( ) ; // treat factories as a special case for lazy load of the objects .
if ( value instanceof InjectorObjectFactory ) { value = ( ( InjectorObjectFactory < ? > ) value ) . create ( ) ; inject ( value ) ; } field . set ( object , value ) ; accept = true ; break ; } } return accept ;


signature:
public class ImageUrlRewriter { /** * Computes the url of the image to be replaced in a css resource .
 * @ param cssUri
 * the uri of the css where the image is located .
 * @ param imageUrl
 * the url of the image ( relative or absolute ) .
 * @ return replaced url of the image . */
public String rewrite ( final String cssUri , final String imageUrl ) { } }

implementation:
notNull ( cssUri ) ; notNull ( imageUrl ) ; if ( StringUtils . isEmpty ( imageUrl ) ) { return imageUrl ; } if ( ServletContextUriLocator . isValid ( cssUri ) ) { if ( ServletContextUriLocator . isValid ( imageUrl ) ) { return prependContextPath ( imageUrl ) ; } // Treat WEB - INF special case
if ( ServletContextUriLocator . isProtectedResource ( cssUri ) ) { return context . proxyPrefix + computeNewImageLocation ( cssUri , imageUrl ) ; } // Compute the folder where the final css is located . This is important for computing image location after url
// rewriting .
// Prefix of the path to the overwritten image url . This will be of the following type : " . . / " or " . . / . . " depending
// on the depth of the aggregatedFolderPath .
final String aggregatedPathPrefix = computeAggregationPathPrefix ( context . aggregatedFolderPath ) ; LOG . debug ( "computed aggregatedPathPrefix {}" , aggregatedPathPrefix ) ; String newImageLocation = computeNewImageLocation ( aggregatedPathPrefix + cssUri , imageUrl ) ; if ( newImageLocation . startsWith ( ServletContextUriLocator . PREFIX ) ) { newImageLocation = prependContextPath ( newImageLocation ) ; } LOG . debug ( "newImageLocation: {}" , newImageLocation ) ; return newImageLocation ; } if ( ClasspathUriLocator . isValid ( cssUri ) ) { final String proxyUrl = context . proxyPrefix + computeNewImageLocation ( cssUri , imageUrl ) ; final String contextRelativeUrl = prependContextPath ( imageUrl ) ; // final String contextRelativeUrl = context . contextPath + imageUrl ;
// leave imageUrl unchanged if it is a servlet context relative resource
return ( ServletContextUriLocator . isValid ( imageUrl ) ? contextRelativeUrl : proxyUrl ) ; } if ( UrlUriLocator . isValid ( cssUri ) ) { final String computedCssUri = ServletContextUriLocator . isValid ( imageUrl ) ? computeCssUriForExternalServer ( cssUri ) : cssUri ; return computeNewImageLocation ( computedCssUri , imageUrl ) ; } throw new WroRuntimeException ( "Could not replace imageUrl: " + imageUrl + ", contained at location: " + cssUri ) ;


signature:
public class ImageUrlRewriter { /** * Css files hosted on external server , should use its host as the root context when rewriting image url ' s starting
 * with ' / ' character . */
private String computeCssUriForExternalServer ( final String cssUri ) { } }

implementation:
String exernalServerCssUri = cssUri ; try { // compute the host of the external server ( with protocol & port ) .
final String serverHost = cssUri . replace ( new URL ( cssUri ) . getPath ( ) , StringUtils . EMPTY ) ; // the uri should end mandatory with /
exernalServerCssUri = serverHost + ServletContextUriLocator . PREFIX ; LOG . debug ( "using {} host as cssUri" , exernalServerCssUri ) ; } catch ( final MalformedURLException e ) { // should never happen
} return exernalServerCssUri ;


signature:
public class ImageUrlRewriter { /** * Concatenates cssUri and imageUrl after few changes are applied to both input parameters .
 * @ param cssUri
 * the URI of css resource .
 * @ param imageUrl
 * the URL of image referred in css .
 * @ return processed new location of image url . */
private String computeNewImageLocation ( final String cssUri , final String imageUrl ) { } }

implementation:
LOG . debug ( "cssUri: {}, imageUrl {}" , cssUri , imageUrl ) ; final String cleanImageUrl = cleanImageUrl ( imageUrl ) ; // TODO move to ServletContextUriLocator as a helper method ?
// for the following input : / a / b / c / 1 . css = > / a / b / c /
int idxLastSeparator = cssUri . lastIndexOf ( ServletContextUriLocator . PREFIX ) ; if ( idxLastSeparator == - 1 ) { if ( ClasspathUriLocator . isValid ( cssUri ) ) { idxLastSeparator = cssUri . lastIndexOf ( ClasspathUriLocator . PREFIX ) ; // find the index of ' : ' character used by classpath prefix
if ( idxLastSeparator >= 0 ) { idxLastSeparator += ClasspathUriLocator . PREFIX . length ( ) - 1 ; } } if ( idxLastSeparator < 0 ) { throw new IllegalStateException ( "Invalid cssUri: " + cssUri + ". Should contain at least one '/' character!" ) ; } } final String cssUriFolder = cssUri . substring ( 0 , idxLastSeparator + 1 ) ; // remove ' / ' from imageUrl if it starts with one .
final String processedImageUrl = cleanImageUrl . startsWith ( ServletContextUriLocator . PREFIX ) ? cleanImageUrl . substring ( 1 ) : cleanImageUrl ; final String computedImageLocation = cleanPath ( cssUriFolder + processedImageUrl ) ; LOG . debug ( "computedImageLocation: {}" , computedImageLocation ) ; return computedImageLocation ;


signature:
public class CacheKey { /** * Add a custom key - value pair attribute . Each pair is added to an internal map . The custom attributes can be used to
 * make the key more fine grained ( Ex : based on browser version or a request parameter ) . Both elements of the
 * attribute ( key & value ) should be not null . If any of these are null , the attribute won ' t be added .
 * @ param key
 * string representing the key of the attribute .
 * @ param value
 * string representing the value of the attribute .
 * @ return reference to current { @ link CacheKey } used for fluent interface . */
public CacheKey addAttribute ( final String key , final String value ) { } }

implementation: if ( key != null && value != null ) { map . put ( key , value ) ; } return this ;


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

implementation: try { final YuiCssCompressor compressor = new YuiCssCompressor ( reader ) ; compressor . compress ( writer , linebreakpos ) ; } catch ( final Exception e ) { LOG . error ( "Exception occured while processing resource: " + resource + " using processor: " + ALIAS ) ; onException ( e ) ; } finally { reader . close ( ) ; writer . close ( ) ; }


signature:
public class BaseWroManagerFactory { /** * { @ inheritDoc } */
public void onCachePeriodChanged ( final long period ) { } }

implementation: try { managerInitializer . get ( ) . onCachePeriodChanged ( period ) ; } catch ( final WroRuntimeException e ) { LOG . warn ( "[FAIL] Unable to reload cache, probably because invoked outside of context" ) ; }


signature:
public class BaseWroManagerFactory { /** * { @ inheritDoc } */
public void onModelPeriodChanged ( final long period ) { } }

implementation: try { managerInitializer . get ( ) . onModelPeriodChanged ( period ) ; } catch ( final WroRuntimeException e ) { LOG . warn ( "[FAIL] Unable to reload model, probably because invoked outside of context" ) ; }


signature:
public class BaseWroManagerFactory { /** * Add a single model transformer . */
public BaseWroManagerFactory addModelTransformer ( final Transformer < WroModel > modelTransformer ) { } }

implementation: if ( modelTransformers == null ) { modelTransformers = new ArrayList < Transformer < WroModel > > ( ) ; } this . modelTransformers . add ( modelTransformer ) ; return this ;


signature:
public class ResourceBundleProcessor { /** * Set the aggregatedFolderPath if required . */
private void initAggregatedFolderPath ( final HttpServletRequest request , final ResourceType type ) { } }

implementation: if ( ResourceType . CSS == type && context . getAggregatedFolderPath ( ) == null ) { final String requestUri = request . getRequestURI ( ) ; final String cssFolder = StringUtils . removeEnd ( requestUri , FilenameUtils . getName ( requestUri ) ) ; final String aggregatedFolder = StringUtils . removeStart ( cssFolder , request . getContextPath ( ) ) ; LOG . debug ( "set aggregatedFolderPath: {}" , aggregatedFolder ) ; Context . get ( ) . setAggregatedFolderPath ( aggregatedFolder ) ; }


signature:
public class CssVariablesProcessor { /** * Extract variables map from variables body .
 * @ param variablesBody
 * string containing variables mappings .
 * @ return map with extracted variables . */
private Map < String , String > extractVariables ( final String variablesBody ) { } }

implementation: final Map < String , String > map = new HashMap < String , String > ( ) ; final Matcher m = PATTERN_VARIABLES_BODY . matcher ( variablesBody ) ; LOG . debug ( "parsing variables body" ) ; while ( m . find ( ) ) { final String key = m . group ( 1 ) ; final String value = m . group ( 2 ) ; if ( map . containsKey ( key ) ) { LOG . warn ( "A duplicate variable name found with name: {} and value: {}." , key , value ) ; } map . put ( key , value ) ; } return map ;


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

implementation: try { final String css = IOUtils . toString ( reader ) ; final String result = parseCss ( css ) ; writer . write ( result ) ; } finally { reader . close ( ) ; writer . close ( ) ; }


signature:
public class CssVariablesProcessor { /** * Parse css , find all defined variables & replace them .
 * @ param css
 * to parse . */
private String parseCss ( final String css ) { } }

implementation:
// map containing variables & their values
final Map < String , String > map = new HashMap < String , String > ( ) ; final StringBuffer sb = new StringBuffer ( ) ; final Matcher m = PATTERN_VARIABLES_DEFINITION . matcher ( css ) ; while ( m . find ( ) ) { final String variablesBody = m . group ( 1 ) ; // LOG . debug ( " variables body : " + variablesBody ) ;
// extract variables
map . putAll ( extractVariables ( variablesBody ) ) ; // remove variables definition
m . appendReplacement ( sb , "" ) ; } m . appendTail ( sb ) ; // LOG . debug ( " replaced variables : " + result ) ;
return replaceVariables ( sb . toString ( ) , map ) ;


signature:
public class CssVariablesProcessor { /** * Replace variables from css with provided variables map .
 * @ param cleanCss
 * used to replace variable placeholders .
 * @ param variables
 * map of variables used for substitution .
 * @ return css with all variables replaced . */
private String replaceVariables ( final String css , final Map < String , String > variables ) { } }

implementation: final StringBuffer sb = new StringBuffer ( ) ; final Matcher m = PATTERN_VARIABLE_HOLDER . matcher ( css ) ; while ( m . find ( ) ) { final String oldMatch = m . group ( ) ; final String variableName = m . group ( 1 ) ; final String variableValue = variables . get ( variableName ) ; if ( variableValue != null ) { final String newReplacement = oldMatch . replace ( oldMatch , variableValue ) ; m . appendReplacement ( sb , newReplacement . trim ( ) ) ; } else { LOG . warn ( "No variable with name " + variableName + " was found!" ) ; } } m . appendTail ( sb ) ; return sb . toString ( ) ;


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

implementation: try { super . process ( resource , reader , writer ) ; } finally { IOUtils . closeQuietly ( reader ) ; IOUtils . closeQuietly ( writer ) ; }


signature:
public class DefaultProcessorDecorator { /** * { @ inheritDoc } */
@ Override protected boolean isEnabled ( final Resource resource ) { } }

implementation: final boolean isApplicable = resource != null ? isEligible ( criteria . isMinimize ( ) , resource . getType ( ) ) : true ; return super . isEnabled ( resource ) && isApplicable ;


signature:
public class TimestampNamingStrategy { /** * { @ inheritDoc } */
public String rename ( final String originalName , final InputStream inputStream ) { } }

implementation: final String baseName = FilenameUtils . getBaseName ( originalName ) ; final String extension = FilenameUtils . getExtension ( originalName ) ; final long timestamp = getTimestamp ( ) ; final StringBuilder sb = new StringBuilder ( baseName ) . append ( "-" ) . append ( timestamp ) ; if ( ! StringUtils . isEmpty ( extension ) ) { sb . append ( "." ) . append ( extension ) ; } return sb . toString ( ) ;


signature:
public class ConfigurableCacheStrategy { /** * { @ inheritDoc } */
@ Override protected Map < String , CacheStrategy < CacheKey , CacheValue > > getStrategies ( final CacheStrategyProvider provider ) { } }

implementation: return provider . provideCacheStrategies ( ) ;


signature:
public class ProcessorDecorator { /** * Transforms a post processor into pre processor . */
private static ResourcePreProcessor toPreProcessor ( final ResourcePostProcessor postProcessor ) { } }

implementation: return new AbstractProcessorDecoratorSupport < ResourcePostProcessor > ( postProcessor ) { public void process ( final Resource resource , final Reader reader , final Writer writer ) throws IOException { postProcessor . process ( reader , writer ) ; } @ Override protected boolean isMinimizeInternal ( ) { return isMinimizeForProcessor ( postProcessor ) ; } @ Override protected SupportedResourceType getSupportedResourceTypeInternal ( ) { return getSupportedResourceTypeForProcessor ( postProcessor ) ; } @ Override public String toString ( ) { return postProcessor . toString ( ) ; } } ;


signature:
public class ProcessorDecorator { /** * Indicates if the processor is eligible for usage based on provided criteria .
 * @ param minimize
 * - when true the processor should be minimize aware .
 * @ param searchedType
 * - the type of the accepted processor . If the processor will have no type specified it will still be
 * eligible .
 * @ return true if this processor is of searchedType . */
public final boolean isEligible ( final boolean minimize , final ResourceType searchedType ) { } }

implementation: Validate . notNull ( searchedType ) ; final SupportedResourceType supportedType = getSupportedResourceType ( ) ; final boolean isTypeSatisfied = supportedType == null || ( supportedType != null && searchedType == supportedType . value ( ) ) ; final boolean isMinimizedSatisfied = minimize == true || ! isMinimize ( ) ; return isTypeSatisfied && isMinimizedSatisfied ;


signature:
public class AbstractLinterProcessor { /** * Called when { @ link LinterException } is thrown . Allows subclasses to re - throw this exception as a
 * { @ link RuntimeException } or handle it differently . The default implementation simply logs the errors .
 * @ param e { @ link LinterException } which has occurred .
 * @ param resource the processed resource which caused the exception . */
protected void onLinterException ( final LinterException e , final Resource resource ) { } }

implementation: LOG . error ( "The following resource: " + resource + " has " + e . getErrors ( ) . size ( ) + " errors." , e ) ;


signature:
public class WroServletContextListener { /** * { @ inheritDoc } */
public final void contextInitialized ( final ServletContextEvent event ) { } }

implementation: this . servletContext = event . getServletContext ( ) ; attributeHelper = new ServletContextAttributeHelper ( this . servletContext , getListenerName ( ) ) ; initListener ( event . getServletContext ( ) ) ;


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

implementation:
final StopWatch watch = new StopWatch ( ) ; watch . start ( "pack" ) ; // initialize rhino context
Context . enter ( ) ; try { final String script = IOUtils . toString ( reader ) ; final String stripConsole = null ; // normal , warn , all
LOG . debug ( "compressing script: {}" , StringUtils . abbreviate ( script , 40 ) ) ; final String out = Compressor . compressScript ( script , 0 , 0 , stripConsole ) ; writer . write ( out ) ; } finally { Context . exit ( ) ; reader . close ( ) ; writer . close ( ) ; watch . stop ( ) ; LOG . debug ( watch . prettyPrint ( ) ) ; }


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

implementation: StopWatch stopWatch = null ; if ( isDebug ( ) ) { stopWatch = new StopWatch ( ) ; before ( stopWatch ) ; } try { super . process ( resource , reader , writer ) ; } finally { if ( isDebug ( ) ) { after ( stopWatch ) ; } }


signature:
public class ConfigurableLocatorFactory { /** * { @ inheritDoc } */
private UriLocatorFactory newLocatorFactory ( ) { } }

implementation:
final SimpleUriLocatorFactory factory = new SimpleUriLocatorFactory ( ) ; final List < UriLocator > locators = getConfiguredStrategies ( ) ; for ( final UriLocator locator : locators ) { factory . addLocator ( locator ) ; } // use default when none provided
if ( locators . isEmpty ( ) ) { LOG . debug ( "No locators configured. Using Default locator factory." ) ; return new DefaultUriLocatorFactory ( ) ; } return factory ;


signature:
public class SaasUriLocator { /** * { @ inheritDoc } */
public boolean accept ( final String url ) { } }

implementation:
if ( url == null ) return false ; final String extension = FilenameUtils . getExtension ( url ) ; // scss file have either no extension or scss
// maybe check for the " _ " ?
if ( "" . equals ( extension ) || "scss" . equals ( extension ) ) { boolean result = getScssFile ( url ) != null ; if ( ! result ) { LOG . debug ( "Possible scss file not found {}" , url ) ; } return result ; } else { return false ; }


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

implementation: Validate . notNull ( uri , "URI cannot be NULL!" ) ; LOG . debug ( "loading  scss file: {}" , uri ) ; return new FileInputStream ( getScssFile ( uri ) ) ;


signature:
public class DestroyableLazyInitializer { /** * Destroy the initialized object . This will trigger the re - initialization when
 * { @ link DestroyableLazyInitializer # get ( ) } method is invoked . */
public void destroy ( ) { } }

implementation: if ( isInitialized ( ) ) { if ( get ( ) instanceof Destroyable ) { try { ( ( Destroyable ) get ( ) ) . destroy ( ) ; } catch ( final Exception e ) { LOG . error ( "destroy operation failed" , e ) ; } } } object = null ;


signature:
public class FallbackCssDataUriProcessor { /** * { @ inheritDoc } */
@ Override protected String replaceDeclaration ( final String originalDeclaration , final String modifiedDeclaration ) { } }

implementation: return originalDeclaration . equals ( modifiedDeclaration ) ? modifiedDeclaration : computeNewDeclaration ( originalDeclaration , modifiedDeclaration ) ;


signature:
public class GzipFilter { /** * { @ 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 ; if ( isGzipAllowed ( request ) ) { doGzipResponse ( request , response , chain ) ; } else { LOG . debug ( "Gzip not allowed. Proceeding with chain." ) ; chain . doFilter ( request , response ) ; }


signature:
public class GzipFilter { /** * Performs actual gzip of the filtered content . */
private void doGzipResponse ( final HttpServletRequest req , final HttpServletResponse response , final FilterChain chain ) throws IOException , ServletException { } }

implementation:
LOG . debug ( "Applying gzip on resource: " + req . getRequestURI ( ) ) ; response . setHeader ( HttpHeader . CONTENT_ENCODING . toString ( ) , "gzip" ) ; final ByteArrayOutputStream baos = new ByteArrayOutputStream ( ) ; final CountingOutputStream countingStream = new CountingOutputStream ( new GZIPOutputStream ( new BufferedOutputStream ( baos ) ) ) ; // final GZIPOutputStream gzout = new GZIPOutputStream ( new BufferedOutputStream ( baos ) ) ;
// Perform gzip operation in - memory before sending response
final HttpServletResponseWrapper wrappedResponse = new RedirectedStreamServletResponseWrapper ( countingStream , response ) ; chain . doFilter ( req , wrappedResponse ) ; // close underlying stream
countingStream . close ( ) ; response . setContentLength ( countingStream . getCount ( ) ) ; // avoid NO CONTENT error thrown by jetty when gzipping empty response
if ( countingStream . getCount ( ) > 0 ) { IOUtils . write ( baos . toByteArray ( ) , response . getOutputStream ( ) ) ; }


signature:
public class PathPatternProcessorDecorator { /** * Decorates a processor which will be applied on provided patterns .
 * @ param processor
 * The processor to decorate .
 * @ param patterns
 * an array of patterns on which the processor will be applied .
 * @ return decorated processor . */
public static PathPatternProcessorDecorator include ( final Object processor , final String ... patterns ) { } }

implementation: return new PathPatternProcessorDecorator ( processor , true , patterns ) ;


signature:
public class PathPatternProcessorDecorator { /** * Decorates a processor which will not be applied on provided patterns .
 * @ param processor
 * The processor to decorate .
 * @ param patterns
 * an array of patterns on which the processor will not be applied .
 * @ return decorated processor . */
public static PathPatternProcessorDecorator exclude ( final Object processor , final String ... patterns ) { } }

implementation: return new PathPatternProcessorDecorator ( processor , false , patterns ) ;


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

implementation:
if ( resource != null ) { final String uri = resource . getUri ( ) ; LOG . debug ( "matching uri: {}" , uri ) ; if ( includes ) { // Match ( p1 OR p2 OR . . pn )
for ( String pattern : patterns ) { if ( matcher . match ( pattern , uri ) ) { LOG . debug ( "Processing resource: {}. Match found: {}" , uri , toString ( ) ) ; getDecoratedObject ( ) . process ( resource , reader , writer ) ; return ; } } } else { boolean process = true ; // Match ! ( p1 AND p2 AND . . pn )
for ( String pattern : patterns ) { if ( matcher . match ( pattern , uri ) ) { process = false ; break ; } } if ( process ) { LOG . debug ( "Processing resource: {}. Match found: {}" , uri , toString ( ) ) ; getDecoratedObject ( ) . process ( resource , reader , writer ) ; return ; } } LOG . debug ( "Skipping {} from {}. No match found: {}" , new Object [ ] { uri , getDecoratedObject ( ) , toString ( ) } ) ; WroUtil . safeCopy ( reader , writer ) ; } else { throw new WroRuntimeException ( "Wrong usage of " + toString ( ) + ". Please use it as a pre-processor." ) ; }


signature:
public class ResourceChangeHandler { /** * Factory method which requires all mandatory fields . */
public static ResourceChangeHandler create ( final WroManagerFactory managerFactory , final Log log ) { } }

implementation: notNull ( managerFactory , "WroManagerFactory was not set" ) ; notNull ( log , "Log was not set" ) ; return new ResourceChangeHandler ( ) . setManagerFactory ( managerFactory ) . setLog ( log ) ;


signature:
public class ResourceChangeHandler { /** * Will persist the information regarding the provided resource in some internal store . This information will be used
 * later to check if the resource is changed .
 * @ param resource
 * { @ link Resource } to touch . */
public void remember ( final Resource resource ) { } }

implementation:
final WroManager manager = getManagerFactory ( ) . create ( ) ; final HashStrategy hashStrategy = manager . getHashStrategy ( ) ; final UriLocatorFactory locatorFactory = manager . getUriLocatorFactory ( ) ; if ( rememberedSet . contains ( resource . getUri ( ) ) ) { // only calculate fingerprints and check imports if not already done
getLog ( ) . debug ( "Resource with uri '" + resource . getUri ( ) + "' has already been updated in this run." ) ; } else { try { final String fingerprint = hashStrategy . getHash ( locatorFactory . locate ( resource . getUri ( ) ) ) ; getBuildContextHolder ( ) . setValue ( resource . getUri ( ) , fingerprint ) ; rememberedSet . add ( resource . getUri ( ) ) ; getLog ( ) . debug ( "Persist fingerprint for resource '" + resource . getUri ( ) + "' : " + fingerprint ) ; if ( resource . getType ( ) == ResourceType . CSS ) { final Reader reader = new InputStreamReader ( locatorFactory . locate ( resource . getUri ( ) ) ) ; getLog ( ) . debug ( "Check @import directive from " + resource ) ; // persist fingerprints in imported resources .
persistFingerprintsForCssImports ( resource , reader ) ; } } catch ( final IOException e ) { getLog ( ) . debug ( "could not check fingerprint of resource: " + resource ) ; } }


signature:
public class ResourceChangeHandler { /** * Invokes the provided function for each detected css import .
 * @ param func
 * a function ( closure ) invoked for each found import . It will be provided as argument the uri of imported
 * css . */
private void forEachCssImportApply ( final Function < String , ChangeStatus > func , final Resource resource , final Reader reader ) throws IOException { } }

implementation: final ResourcePreProcessor processor = createCssImportProcessor ( func ) ; InjectorBuilder . create ( getManagerFactory ( ) ) . build ( ) . inject ( processor ) ; processor . process ( resource , reader , new StringWriter ( ) ) ;


signature:
public class ResourceChangeHandler { /** * After invoking this method on a resource , the next invocation of { @ link # isResourceChanged ( Resource ) } will return
 * true .
 * @ param resourceUri
 * uri of the resource to clear from persisted storage . */
public void forget ( final Resource resource ) { } }

implementation: if ( resource != null ) { getBuildContextHolder ( ) . setValue ( resource . getUri ( ) , null ) ; rememberedSet . remove ( resource . getUri ( ) ) ; }


signature:
public class ConfigurableHashStrategy { /** * { @ inheritDoc } */
public String getHash ( final InputStream inputStream ) throws IOException { } }

implementation: try { return getConfiguredStrategy ( ) . getHash ( inputStream ) ; } finally { IOUtils . closeQuietly ( inputStream ) ; }


signature:
public class ResourceLintReport { /** * Factory method for creating a { @ link ResourceLintReport } instance .
 * @ param resourcePath
 * the path of the of the resource
 * @ param lints
 * a collection of lints associated with a resource .
 * @ return { @ link ResourceLintReport } with all lints set . */
public static < T > ResourceLintReport < T > create ( final String resourcePath , final Collection < T > lints ) { } }

implementation: return new ResourceLintReport < T > ( resourcePath , lints ) ;


signature:
public class ResourceLintReport { /** * This filtering is required , in order to ensure that no nulls are passed ( which happens when using gson for
 * deserializing json collection .
 * @ param collection
 * to filter .
 * @ return a null free collection of item by filtering found nulls . */
private List < T > filter ( final Collection < T > collection ) { } }

implementation: final List < T > nullFreeList = new ArrayList < T > ( ) ; if ( collection != null ) { for ( final T item : collection ) { if ( item != null ) { nullFreeList . add ( item ) ; } } } return nullFreeList ;


signature:
public class DefaultGroupExtractor { /** * { @ inheritDoc } */
public String getGroupName ( final HttpServletRequest request ) { } }

implementation:
Validate . notNull ( request ) ; String uri = request . getRequestURI ( ) ; // check if include or uri path are present and use one of these as request uri .
final String includeUriPath = ( String ) request . getAttribute ( ATTR_INCLUDE_PATH ) ; uri = includeUriPath != null ? includeUriPath : uri ; final String groupName = FilenameUtils . getBaseName ( stripSessionID ( uri ) ) ; return StringUtils . isEmpty ( groupName ) ? null : groupName ;


signature:
public class DefaultGroupExtractor { /** * Extracts the resource type , by parsing the uri & finds the extension . If extension is valid ( ' css ' or ' js ' ) ,
 * returns corresponding ResourceType , otherwise throws exception .
 * Valid examples of uri are : < code > / context / somePath / test . js < / code > or < code > / context / somePath / test . css < / code >
 * { @ inheritDoc } */
public ResourceType getResourceType ( final HttpServletRequest request ) { } }

implementation: Validate . notNull ( request ) ; final String uri = request . getRequestURI ( ) ; Validate . notNull ( uri ) ; ResourceType type = null ; try { type = ResourceType . get ( FilenameUtils . getExtension ( stripSessionID ( uri ) ) ) ; } catch ( final IllegalArgumentException e ) { LOG . debug ( "[FAIL] Cannot identify resourceType for uri: {}" , uri ) ; } return type ;


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

implementation: return String . format ( "%s.%s?" + PARAM_MINIMIZE + "=%s" , groupName , resourceType . name ( ) . toLowerCase ( ) , minimize ) ;


signature:
public class DefaultGroupExtractor { /** * The minimization is can be switched off only in debug mode .
 * @ return false if the request contains parameter { @ link DefaultGroupExtractor # PARAM _ MINIMIZE } with value false ,
 * otherwise returns true . */
public boolean isMinimized ( final HttpServletRequest request ) { } }

implementation: Validate . notNull ( request ) ; final String minimizeAsString = request . getParameter ( PARAM_MINIMIZE ) ; return ! ( Context . get ( ) . getConfig ( ) . isDebug ( ) && "false" . equalsIgnoreCase ( minimizeAsString ) ) ;


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

implementation: try { final String script = IOUtils . toString ( reader ) ; writer . write ( script ) ; if ( isSemicolonNeeded ( script ) ) { writer . write ( ';' ) ; } } finally { reader . close ( ) ; writer . close ( ) ; }


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

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


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

implementation:
LOG . debug ( "Applying {} processor" , toString ( ) ) ; validate ( ) ; try { final String result = parseCss ( resource , IOUtils . toString ( reader ) ) ; writer . write ( result ) ; } finally { // imkportant to avoid memory leak
clearProcessedImports ( ) ; reader . close ( ) ; writer . close ( ) ; }


signature:
public class AbstractCssImportPreProcessor { /** * Find a set of imported resources inside a given resource . */
private List < Resource > findImportedResources ( final String resourceUri , final String cssContent ) throws IOException { } }

implementation:
// it should be sorted
final List < Resource > imports = new ArrayList < Resource > ( ) ; final String css = cssContent ; final List < String > foundImports = findImports ( css ) ; for ( final String importUrl : foundImports ) { final Resource importedResource = createImportedResource ( resourceUri , importUrl ) ; // check if already exist
if ( imports . contains ( importedResource ) ) { LOG . debug ( "[WARN] Duplicate imported resource: {}" , importedResource ) ; } else { imports . add ( importedResource ) ; onImportDetected ( importedResource . getUri ( ) ) ; } } return imports ;


signature:
public class AbstractCssImportPreProcessor { /** * Build a { @ link Resource } object from a found importedResource inside a given resource . */
private Resource createImportedResource ( final String resourceUri , final String importUrl ) { } }

implementation: final String absoluteUrl = uriLocatorFactory . getInstance ( importUrl ) != null ? importUrl : computeAbsoluteUrl ( resourceUri , importUrl ) ; return Resource . create ( absoluteUrl , ResourceType . CSS ) ;


signature:
public class AbstractCssImportPreProcessor { /** * Computes absolute url of the imported resource .
 * @ param relativeResourceUri uri of the resource containing the import statement .
 * @ param importUrl found import url .
 * @ return absolute url of the resource to import . */
private String computeAbsoluteUrl ( final String relativeResourceUri , final String importUrl ) { } }

implementation:
final String folder = WroUtil . getFullPath ( relativeResourceUri ) ; // remove ' . . / ' & normalize the path .
return StringUtils . cleanPath ( folder + importUrl ) ;


signature:
public class ResourceProxyRequestHandler { /** * Used to identify whether the { @ link HttpServletResponse # SC _ NOT _ MODIFIED } or { @ link HttpServletResponse # SC _ OK }
 * should be returned . Currently a single timestamp is used to detect the change for all resources . This might be no
 * accurate , but at least it allows sending NOT _ MODIFIED header much often resulting in less load on the server .
 * Override this method if a different way detecting change is required .
 * @ return true if the requested resource is changed on the server and the latest version should be returned . */
protected boolean isResourceChanged ( final HttpServletRequest request ) { } }

implementation: try { final long ifModifiedSince = request . getDateHeader ( HttpHeader . IF_MODIFIED_SINCE . toString ( ) ) ; return ifModifiedSince < getHeadersConfigurer ( ) . getLastModifiedTimestamp ( ) ; } catch ( final Exception e ) { LOG . warn ( "Could not extract IF_MODIFIED_SINCE header for request: " + request . getRequestURI ( ) + ". Assuming content is changed. " , e ) ; return true ; }


signature:
public class ResourceProxyRequestHandler { /** * Builds the request path for this request handler using the assumption that { @ link WroFilter } has a mapping ending
 * with a < code > * < / code > character .
 * @ param requestUri
 * of wro request used to compute the path to this request handler . This request uri is required , because we
 * do not know how the wro filter is mapped .
 * @ return the path for this handler . */
public static String createProxyPath ( final String requestUri , final String resourceId ) { } }

implementation: notNull ( requestUri ) ; notNull ( resourceId ) ; return requestUri + getRequestHandlerPath ( resourceId ) ;


signature:
public class AbstractConfigurableMultipleStrategy { /** * Creates a comma separated list of items .
 * @ VisibleForTesting */
public static String createItemsAsString ( final String ... items ) { } }

implementation: final StringBuffer sb = new StringBuffer ( ) ; for ( int i = 0 ; i < items . length ; i ++ ) { sb . append ( items [ i ] ) ; if ( i < items . length - 1 ) { sb . append ( TOKEN_DELIMITER ) ; } } return sb . toString ( ) ;


signature:
public class AbstractConfigurableMultipleStrategy { /** * Creates a list of aliases based on provided string containing comma separated values of aliases .
 * @ param aliasCsv
 * string representation of tokens separated by ' , ' character .
 * @ return a list of non empty strings . */
private List < String > getAliasList ( final String aliasCsv ) { } }

implementation: LOG . debug ( "configured aliases: {}" , aliasCsv ) ; final List < String > list = new ArrayList < String > ( ) ; if ( ! StringUtils . isEmpty ( aliasCsv ) ) { final String [ ] tokens = aliasCsv . split ( TOKEN_DELIMITER ) ; for ( final String token : tokens ) { list . add ( token . trim ( ) ) ; } } return list ;


signature:
public class RhinoScriptBuilder { /** * Initialize the context . */
private ScriptableObject createContext ( final ScriptableObject initialScope ) { } }

implementation:
final Context context = getContext ( ) ; context . setOptimizationLevel ( - 1 ) ; // TODO redirect errors from System . err to LOG . error ( )
context . setErrorReporter ( new ToolErrorReporter ( false ) ) ; context . setLanguageVersion ( Context . VERSION_1_8 ) ; InputStream script = null ; final ScriptableObject scriptCommon = ( ScriptableObject ) context . initStandardObjects ( initialScope ) ; try { script = new AutoCloseInputStream ( getClass ( ) . getResourceAsStream ( "commons.js" ) ) ; context . evaluateReader ( scriptCommon , new InputStreamReader ( script ) , "commons.js" , 1 , null ) ; } catch ( final IOException e ) { throw new RuntimeException ( "Problem while evaluationg commons script." , e ) ; } finally { IOUtils . closeQuietly ( script ) ; } return scriptCommon ;


signature:
public class RhinoScriptBuilder { /** * Add a client side environment to the script context ( client - side aware ) .
 * @ return { @ link RhinoScriptBuilder } used to chain evaluation of the scripts .
 * @ throws IOException */
public RhinoScriptBuilder addClientSideEnvironment ( ) { } }

implementation:
try { // final InputStream scriptEnv = getClass ( ) . getResourceAsStream ( SCRIPT _ ENV ) ;
final InputStream scriptEnv = new WebjarUriLocator ( ) . locate ( "env.rhino.js" ) ; evaluateChain ( scriptEnv , SCRIPT_ENV ) ; return this ; } catch ( final IOException e ) { throw new RuntimeException ( "Couldn't initialize env.rhino script" , e ) ; }


signature:
public class RhinoScriptBuilder { /** * This method will load JSON utility and aslo a Douglas Crockford ' s < a
 * href = " https : / / github . com / douglascrockford / JSON - js / blob / master / cycle . js " > utility < / a > required for decycling objects
 * which would fail otherwise when using JSON . stringify . */
public RhinoScriptBuilder addJSON ( ) { } }

implementation: try { final InputStream script = new AutoCloseInputStream ( new WebjarUriLocator ( ) . locate ( WebjarUriLocator . createUri ( "20110223/json2.js" ) ) ) ; final InputStream scriptCycle = getClass ( ) . getResourceAsStream ( SCRIPT_CYCLE ) ; evaluateChain ( script , SCRIPT_JSON ) ; evaluateChain ( scriptCycle , SCRIPT_CYCLE ) ; return this ; } catch ( final IOException e ) { throw new RuntimeException ( "Couldn't initialize json2.min.js script" , e ) ; }


signature:
public class RhinoScriptBuilder { /** * Evaluates a script and return { @ link RhinoScriptBuilder } for a chained script evaluation .
 * @ param stream { @ link InputStream } of the script to evaluate .
 * @ param sourceName the name of the evaluated script .
 * @ return { @ link RhinoScriptBuilder } chain with required script evaluated .
 * @ throws IOException if the script couldn ' t be retrieved . */
public RhinoScriptBuilder evaluateChain ( final InputStream stream , final String sourceName ) throws IOException { } }

implementation: notNull ( stream ) ; try { getContext ( ) . evaluateReader ( scope , new InputStreamReader ( stream ) , sourceName , 1 , null ) ; return this ; } catch ( final RhinoException e ) { if ( e instanceof RhinoException ) { LOG . error ( "RhinoException: {}" , RhinoUtils . createExceptionMessage ( e ) ) ; } throw e ; } catch ( final RuntimeException e ) { LOG . error ( "Exception caught" , e ) ; throw e ; } finally { stream . close ( ) ; }


signature:
public class RhinoScriptBuilder { /** * Evaluates a script and return { @ link RhinoScriptBuilder } for a chained script evaluation .
 * @ param script the string representation of the script to evaluate .
 * @ param sourceName the name of the evaluated script .
 * @ return evaluated object .
 * @ throws IOException if the script couldn ' t be retrieved . */
public RhinoScriptBuilder evaluateChain ( final String script , final String sourceName ) { } }

implementation: notNull ( script ) ; getContext ( ) . evaluateString ( scope , script , sourceName , 1 , null ) ; return this ;


signature:
public class RhinoScriptBuilder { /** * Evaluates a script from a reader .
 * @ param reader { @ link Reader } of the script to evaluate .
 * @ param sourceName the name of the evaluated script .
 * @ return evaluated object .
 * @ throws IOException if the script couldn ' t be retrieved . */
public Object evaluate ( final Reader reader , final String sourceName ) throws IOException { } }

implementation: notNull ( reader ) ; try { return evaluate ( IOUtils . toString ( reader ) , sourceName ) ; } finally { reader . close ( ) ; }


signature:
public class RhinoScriptBuilder { /** * Evaluates a script .
 * @ param script string representation of the script to evaluate .
 * @ param sourceName the name of the evaluated script .
 * @ return evaluated object .
 * @ throws IOException if the script couldn ' t be retrieved . */
public Object evaluate ( final String script , final String sourceName ) { } }

implementation:
notNull ( script ) ; // make sure we have a context associated with current thread
try { return getContext ( ) . evaluateString ( scope , script , sourceName , 1 , null ) ; } catch ( final RhinoException e ) { final String message = RhinoUtils . createExceptionMessage ( e ) ; LOG . error ( "JavaScriptException occured: {}" , message ) ; throw new WroRuntimeException ( message ) ; } finally { // Rhino throws an exception when trying to exit twice . Make sure we don ' t get any exception
if ( Context . getCurrentContext ( ) != null ) { Context . exit ( ) ; } }


signature:
public class WroManager { /** * Perform processing of the uri .
 * @ throws IOException
 * when any IO related problem occurs or if the request cannot be processed . */
public final void process ( ) throws IOException { } }

implementation:
// reschedule cache & model updates
final WroConfiguration config = Context . get ( ) . getConfig ( ) ; cacheSchedulerHelper . scheduleWithPeriod ( config . getCacheUpdatePeriod ( ) ) ; modelSchedulerHelper . scheduleWithPeriod ( config . getModelUpdatePeriod ( ) ) ; resourceBundleProcessor . serveProcessedBundle ( ) ;


signature:
public class WroManager { /** * Encodes a fingerprint of the resource into the path . The result may look like this : $ { fingerprint } / myGroup . js
 * @ return a path to the resource with the fingerprint encoded as a folder name . */
public final String encodeVersionIntoGroupPath ( final String groupName , final ResourceType resourceType , final boolean minimize ) { } }

implementation:
// TODO use CacheKeyFactory
final CacheKey key = new CacheKey ( groupName , resourceType , minimize ) ; final CacheValue cacheValue = cacheStrategy . get ( key ) ; final String groupUrl = groupExtractor . encodeGroupUrl ( groupName , resourceType , minimize ) ; // encode the fingerprint of the resource into the resource path
return formatVersionedResource ( cacheValue . getHash ( ) , groupUrl ) ;


signature:
public class WroManager { /** * Format the version of the resource in the path . Default implementation use hash as a folder : < hash > / groupName . js .
 * The implementation can be changed to follow a different versioning style , like version parameter :
 * / groupName . js ? version = < hash >
 * @ param hash
 * Hash of the resource .
 * @ param resourcePath
 * Path of the resource .
 * @ return formatted versioned path of the resource . */
protected String formatVersionedResource ( final String hash , final String resourcePath ) { } }

implementation: return String . format ( "%s/%s" , hash , resourcePath ) ;


signature:
public class WroManager { /** * Called when { @ link WroManager } is being taken out of service . */
public final void destroy ( ) { } }

implementation: try { cacheSchedulerHelper . destroy ( ) ; modelSchedulerHelper . destroy ( ) ; cacheStrategy . destroy ( ) ; modelFactory . destroy ( ) ; resourceWatcher . destroy ( ) ; destroyProcessors ( ) ; } catch ( final Exception e ) { LOG . error ( "Exception occured during manager destroy!" , e ) ; } finally { LOG . debug ( "WroManager destroyed" ) ; }


signature:
public class WroManager { /** * Invokes destroy method on all { @ link Destroyable } processors . */
private void destroyProcessors ( ) throws Exception { } }

implementation: for ( final ResourcePreProcessor processor : processorsFactory . getPreProcessors ( ) ) { if ( processor instanceof Destroyable ) { ( ( Destroyable ) processor ) . destroy ( ) ; } } for ( final ResourcePostProcessor processor : processorsFactory . getPostProcessors ( ) ) { if ( processor instanceof Destroyable ) { ( ( Destroyable ) processor ) . destroy ( ) ; } }


signature:
public class ConfigurableProviderSupport { /** * { @ inheritDoc } */
public Map < String , CacheStrategy < CacheKey , CacheValue > > provideCacheStrategies ( ) { } }

implementation: return new HashMap < String , CacheStrategy < CacheKey , CacheValue > > ( ) ;


signature:
public class ResourceWatcherRequestHandler { /** * Checks if the provided url is a resource proxy request .
 * @ param url
 * to check .
 * @ return true if the provided url is a proxy resource . */
private boolean isHandlerRequest ( final HttpServletRequest request ) { } }

implementation: String apiHandlerValue = request . getParameter ( PATH_API ) ; return PATH_HANDLER . equals ( apiHandlerValue ) && retrieveCacheKey ( request ) != null ;


signature:
public class ResourceWatcherRequestHandler { /** * Computes the servlet context relative url to call this handler using a server - side invocation . Hides the details
 * about creating a valid url and providing the authorization key required to invoke this handler . */
public static String createHandlerRequestPath ( final CacheKey cacheKey , final HttpServletRequest request ) { } }

implementation: final String handlerQueryPath = getRequestHandlerPath ( cacheKey . getGroupName ( ) , cacheKey . getType ( ) ) ; return request . getServletPath ( ) + handlerQueryPath ;


signature:
public class Wro4jMojo { /** * Encodes a version using some logic .
 * @ param group
 * the name of the resource to encode .
 * @ param input
 * the stream of the result content .
 * @ return the name of the resource with the version encoded . */
private String rename ( final String group , final InputStream input ) throws Exception { } }

implementation: try { final String newName = getManagerFactory ( ) . create ( ) . getNamingStrategy ( ) . rename ( group , input ) ; groupNames . setProperty ( group , newName ) ; return newName ; } catch ( final IOException e ) { throw new MojoExecutionException ( "Error occured during renaming" , e ) ; }


signature:
public class Wro4jMojo { /** * Computes the destination folder based on resource type .
 * @ param resourceType
 * { @ link ResourceType } to process .
 * @ return destinationFoder where the result of resourceType will be copied .
 * @ throws MojoExecutionException
 * if computed folder is null . */
private File computeDestinationFolder ( final ResourceType resourceType ) throws MojoExecutionException { } }

implementation: File folder = destinationFolder ; if ( resourceType == ResourceType . JS ) { if ( jsDestinationFolder != null ) { folder = jsDestinationFolder ; } } if ( resourceType == ResourceType . CSS ) { if ( cssDestinationFolder != null ) { folder = cssDestinationFolder ; } } getLog ( ) . info ( "folder: " + folder ) ; if ( folder == null ) { throw new MojoExecutionException ( "Couldn't compute destination folder for resourceType: " + resourceType + ". That means that you didn't define one of the following parameters: " + "destinationFolder, cssDestinationFolder, jsDestinationFolder" ) ; } if ( ! folder . exists ( ) ) { folder . mkdirs ( ) ; } return folder ;


signature:
public class Wro4jMojo { /** * Process a single group . */
private void processGroup ( final String group , final File parentFoder ) throws Exception { } }

implementation:
ByteArrayOutputStream resultOutputStream = null ; InputStream resultInputStream = null ; try { getLog ( ) . info ( "processing group: " + group ) ; // mock request
final HttpServletRequest request = Mockito . mock ( HttpServletRequest . class ) ; Mockito . when ( request . getContextPath ( ) ) . thenReturn ( normalizeContextPath ( contextPath ) ) ; Mockito . when ( request . getRequestURI ( ) ) . thenReturn ( group ) ; // mock response
final HttpServletResponse response = Mockito . mock ( HttpServletResponse . class ) ; resultOutputStream = new ByteArrayOutputStream ( ) ; Mockito . when ( response . getOutputStream ( ) ) . thenReturn ( new DelegatingServletOutputStream ( resultOutputStream ) ) ; // init context
final WroConfiguration config = Context . get ( ) . getConfig ( ) ; // the maven plugin should ignore empty groups , since it will try to process all types of resources .
config . setIgnoreEmptyGroup ( true ) ; Context . set ( Context . webContext ( request , response , Mockito . mock ( FilterConfig . class ) ) , config ) ; Context . get ( ) . setAggregatedFolderPath ( getAggregatedPathResolver ( ) . resolve ( ) ) ; // perform processing
getManagerFactory ( ) . create ( ) . process ( ) ; // encode version & write result to file
resultInputStream = new UnclosableBufferedInputStream ( resultOutputStream . toByteArray ( ) ) ; final File destinationFile = new File ( parentFoder , rename ( group , resultInputStream ) ) ; final File parentFolder = destinationFile . getParentFile ( ) ; if ( ! parentFolder . exists ( ) ) { // make directories if required
parentFolder . mkdirs ( ) ; } destinationFile . createNewFile ( ) ; // allow the same stream to be read again
resultInputStream . reset ( ) ; getLog ( ) . debug ( "Created file: " + destinationFile . getName ( ) ) ; final OutputStream fos = new FileOutputStream ( destinationFile ) ; // use reader to detect encoding
IOUtils . copy ( resultInputStream , fos ) ; fos . close ( ) ; // delete empty files
if ( destinationFile . length ( ) == 0 ) { getLog ( ) . debug ( "No content found for group: " + group ) ; destinationFile . delete ( ) ; } else { getLog ( ) . info ( "file size: " + destinationFile . getName ( ) + " -> " + destinationFile . length ( ) + " bytes" ) ; getLog ( ) . info ( destinationFile . getAbsolutePath ( ) + " (" + destinationFile . length ( ) + " bytes" + ")" ) ; } } finally { // instruct the build about the change in context of incremental build
if ( getBuildContext ( ) != null ) { getBuildContext ( ) . refresh ( parentFoder ) ; } if ( resultOutputStream != null ) { resultOutputStream . close ( ) ; } if ( resultInputStream != null ) { resultInputStream . close ( ) ; } }


signature:
public class WroRuntimeException { /** * Wraps original exception into { @ link WroRuntimeException } and throw it .
 * @ param e
 * the exception to wrap .
 * @ param message
 * the message of the exception to wrap . */
public static WroRuntimeException wrap ( final Exception e , final String message ) { } }

implementation: if ( e instanceof WroRuntimeException ) { return ( WroRuntimeException ) e ; } return new WroRuntimeException ( message , e ) ;


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

implementation:
final String content = IOUtils . toString ( reader ) ; final CompilerOptions compilerOptions = optionsPool . getObject ( ) ; final Compiler compiler = newCompiler ( compilerOptions ) ; try { final String fileName = resource == null ? "wro4j-processed-file.js" : resource . getUri ( ) ; final SourceFile [ ] input = new SourceFile [ ] { SourceFile . fromInputStream ( fileName , new ByteArrayInputStream ( content . getBytes ( getEncoding ( ) ) ) ) } ; SourceFile [ ] externs = getExterns ( resource ) ; if ( externs == null ) { // fallback to empty array when null is provided .
externs = new SourceFile [ ] { } ; } Result result = null ; result = compiler . compile ( Arrays . asList ( externs ) , Arrays . asList ( input ) , compilerOptions ) ; if ( result . success ) { writer . write ( compiler . toSource ( ) ) ; } else { throw new WroRuntimeException ( "Compilation has errors: " + Arrays . asList ( result . errors ) ) ; } } catch ( final Exception e ) { onException ( e ) ; } finally { reader . close ( ) ; writer . close ( ) ; optionsPool . returnObject ( compilerOptions ) ; }


signature:
public class ResourceChangeDetector { /** * Check if an uri from a particular group has changed .
 * @ param uri
 * the uri to check for change .
 * @ param groupName
 * the name of the group where the uri belongs to .
 * @ return true if the change is detected for the provided uri . */
public boolean checkChangeForGroup ( final String uri , final String groupName ) throws IOException { } }

implementation: notNull ( uri ) ; notNull ( groupName ) ; LOG . debug ( "group={}, uri={}" , groupName , uri ) ; final ResourceChangeInfo resourceInfo = changeInfoMap . get ( uri ) ; if ( resourceInfo . isCheckRequiredForGroup ( groupName ) ) { final InputStream inputStream = locatorFactory . locate ( uri ) ; try { final String currentHash = hashStrategy . getHash ( inputStream ) ; resourceInfo . updateHashForGroup ( currentHash , groupName ) ; } finally { IOUtils . closeQuietly ( inputStream ) ; } } return resourceInfo . isChanged ( groupName ) ;


signature:
public class BourbonCssProcessor { /** * A getter used for lazy loading , overrides RubySassEngine # getEngine ( ) and ensure the
 * bourbon gem is imported ( required ) . */
@ Override protected RubySassEngine newEngine ( ) { } }

implementation: final RubySassEngine engine = super . newEngine ( ) ; engine . addRequire ( BOURBON_GEM_REQUIRE ) ; return engine ;


signature:
public class HandlebarsJs { /** * { @ inheritDoc } */
@ Override public String compile ( final String content , final String name ) { } }

implementation: return HANDLEBARS_JS_TEMPLATES_INIT + "templates[" + name + "] = template(" + super . compile ( content , "" ) + " ); })();" ;


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

implementation: try { RhinoScriptBuilder builder = null ; if ( scope == null ) { final String scriptInit = "var exports = {};" ; builder = RhinoScriptBuilder . newChain ( ) . evaluateChain ( scriptInit , "initSass" ) . evaluateChain ( getScriptAsStream ( ) , DEFAULT_SASS_JS ) ; scope = builder . getScope ( ) ; } else { builder = RhinoScriptBuilder . newChain ( scope ) ; } return builder ; } catch ( final IOException ex ) { throw new WroRuntimeException ( "Failed reading javascript sass.js" , ex ) ; }


signature:
public class StandaloneServletContextUriLocator { /** * This implementation will try to locate the provided resource inside contextFolder configured by standaloneContext .
 * If a resource cannot be located , the next contextFolder from the list will be tried . The first successful result
 * will be returned . */
@ Override public InputStream locate ( final String uri ) throws IOException { } }

implementation: validState ( standaloneContext != null , "Locator was not initialized properly. StandaloneContext missing." ) ; Exception lastException = null ; final String [ ] contextFolders = standaloneContext . getContextFolders ( ) ; for ( final String contextFolder : contextFolders ) { try { return locateStreamWithContextFolder ( uri , contextFolder ) ; } catch ( final IOException e ) { lastException = e ; LOG . debug ( "Could not locate: {} using contextFolder: {}" , uri , contextFolder ) ; } } final String exceptionMessage = String . format ( "No valid resource '%s' found inside any of contextFolders: %s" , uri , Arrays . toString ( standaloneContext . getContextFolders ( ) ) ) ; throw new IOException ( exceptionMessage , lastException ) ;


signature:
public class StandaloneServletContextUriLocator { /** * TODO this is duplicated code ( from super ) - > find a way to reuse it . */
private InputStream locateStreamWithContextFolder ( final String uri , final String contextFolder ) throws IOException , FileNotFoundException { } }

implementation: if ( getWildcardStreamLocator ( ) . hasWildcard ( uri ) ) { final String fullPath = WroUtil . getFullPath ( uri ) ; final String realPath = contextFolder + fullPath ; return getWildcardStreamLocator ( ) . locateStream ( uri , new File ( realPath ) ) ; } final String uriWithoutPrefix = uri . replaceFirst ( PREFIX , EMPTY ) ; final File file = new File ( contextFolder , uriWithoutPrefix ) ; LOG . debug ( "Opening file: " + file . getPath ( ) ) ; return new FileInputStream ( file ) ;


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

implementation: try { RhinoScriptBuilder builder = null ; if ( scope == null ) { builder = RhinoScriptBuilder . newChain ( ) . evaluateChain ( getScriptAsStream ( ) , DEFAULT_CSSLINT_JS ) ; 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 CssLint { /** * Validates a css resource using cssLint and throws { @ link CssLintException } if the resource is invalid . If no exception is thrown ,
 * the resource is valid .
 * @ param data
 * css content to process .
 * @ throws CssLintException
 * when parsed css has some kind of problems . */
public void validate ( final String data ) throws CssLintException { } }

implementation: final StopWatch watch = new StopWatch ( ) ; watch . start ( "init" ) ; final RhinoScriptBuilder builder = initScriptBuilder ( ) ; watch . stop ( ) ; watch . start ( "cssLint" ) ; LOG . debug ( "options: {}" , this . options ) ; final String script = buildCssLintScript ( WroUtil . toJSMultiLineString ( data ) ) ; LOG . debug ( "script: {}" , script ) ; builder . evaluate ( script , "CSSLint.verify" ) . toString ( ) ; final boolean valid = Boolean . parseBoolean ( builder . evaluate ( "result.length == 0" , "checkNoErrors" ) . toString ( ) ) ; if ( ! valid ) { final String json = builder . addJSON ( ) . evaluate ( "JSON.stringify(result)" , "CssLint messages" ) . toString ( ) ; LOG . debug ( "json {}" , json ) ; final Type type = new TypeToken < List < CssLintError > > ( ) { } . getType ( ) ; final List < CssLintError > errors = new Gson ( ) . fromJson ( json , type ) ; LOG . debug ( "Errors: {}" , errors ) ; throw new CssLintException ( ) . setErrors ( errors ) ; } LOG . debug ( "isValid: {}" , valid ) ; watch . stop ( ) ; LOG . debug ( watch . prettyPrint ( ) ) ;


signature:
public class ObjectPoolHelper { /** * Ensure that a not null pool will be created . */
private GenericObjectPool < T > createObjectPool ( final ObjectFactory < T > objectFactory ) { } }

implementation: final GenericObjectPool < T > pool = newObjectPool ( objectFactory ) ; notNull ( pool ) ; return pool ;


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

implementation:
final String content = IOUtils . toString ( reader ) ; final Matcher matcher = PATTERN_PLACEHOLDER . matcher ( content ) ; final StringBuffer sb = new StringBuffer ( ) ; Properties properties = null ; if ( propertiesFactory != null ) { properties = propertiesFactory . create ( ) ; } // be sure that properties will never be null ;
if ( properties == null ) { properties = EMPTY_PROPERTIES ; } while ( matcher . find ( ) ) { final String variableName = matcher . group ( 1 ) ; LOG . debug ( "found placeholder: {}" , variableName ) ; matcher . appendReplacement ( sb , replaceVariable ( properties , variableName ) ) ; } matcher . appendTail ( sb ) ; writer . write ( sb . toString ( ) ) ;


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

implementation: getProcessorDecorator ( ) . process ( resource , reader , writer ) ;


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

implementation: getProcessorDecorator ( ) . process ( reader , writer ) ;


signature:
public class ResourceSerializer { /** * { @ inheritDoc } */
@ Override public JsonElement serialize ( final Resource resource , final Type type , final JsonSerializationContext context ) { } }

implementation: final JsonObject jsonObject = new JsonObject ( ) ; final String uri = resource . getUri ( ) ; jsonObject . add ( "type" , new JsonPrimitive ( resource . getType ( ) . toString ( ) ) ) ; jsonObject . add ( "minimize" , new JsonPrimitive ( resource . isMinimize ( ) ) ) ; jsonObject . add ( "uri" , new JsonPrimitive ( uri ) ) ; jsonObject . add ( "proxyUri" , new JsonPrimitive ( getExternalUri ( uri ) ) ) ; return jsonObject ;


signature:
public class JarWildcardStreamLocator { /** * Finds the specified URI pattern inside a JAR file . If the specified file isn ' t a valid JAR default strategy will be
 * used instead . */
@ Override public InputStream locateStream ( final String uri , final File folder ) throws IOException { } }

implementation: notNull ( folder ) ; final File jarPath = getJarFile ( folder ) ; if ( isSupported ( jarPath ) ) { return locateStreamFromJar ( uri , jarPath ) ; } return super . locateStream ( uri , folder ) ;


signature:
public class JarWildcardStreamLocator { /** * Opens the specified JAR file and returns a valid handle .
 * @ param jarFile
 * Location of the valid JAR file to read . It cannot be null .
 * @ return A valid { @ link JarFile } to read resources .
 * @ throws IllegalArgumentException
 * If the file cannot be opened because an { @ link IOException } .
 * @ VisibleForTestOnly */
JarFile open ( final File jarFile ) throws IOException { } }

implementation: isTrue ( jarFile . exists ( ) , "The JAR file must exists." ) ; return new JarFile ( jarFile ) ;


signature:
public class JarWildcardStreamLocator { /** * Finds the specified wildcard - URI resource ( s ) inside a JAR file and returns an { @ link InputStream } to read a bundle
 * of matching resources .
 * @ param uri
 * Resource ( s ) URI to match . It cannot be null or empty .
 * @ param jarPath
 * A valid JAR file . It cannot be null .
 * @ return A valid { @ link InputStream } to read the bundle . Clients are responsible of closing this { @ link InputStream }
 * @ throws IOException
 * If there ' s any error reading the JAR file . */
private InputStream locateStreamFromJar ( final String uri , final File jarPath ) throws IOException { } }

implementation:
JarFile jarFile = null ; try { LOG . debug ( "Locating stream from jar: {}" , jarPath ) ; final WildcardContext wildcardContext = new WildcardContext ( uri , jarPath ) ; String classPath = FilenameUtils . getPath ( uri ) ; if ( classPath . startsWith ( ClasspathUriLocator . PREFIX ) ) { classPath = substringAfter ( classPath , ClasspathUriLocator . PREFIX ) ; } jarFile = open ( jarPath ) ; final List < JarEntry > jarEntryList = Collections . list ( jarFile . entries ( ) ) ; final List < JarEntry > filteredJarEntryList = new ArrayList < JarEntry > ( ) ; final List < File > allFiles = new ArrayList < File > ( ) ; for ( final JarEntry entry : jarEntryList ) { final String entryName = entry . getName ( ) ; // ignore the parent folder itself and accept only child resources
final boolean isSupportedEntry = entryName . startsWith ( classPath ) && ! entryName . equals ( classPath ) && accept ( entryName , wildcardContext . getWildcard ( ) ) ; if ( isSupportedEntry ) { allFiles . add ( new File ( entryName ) ) ; LOG . debug ( "\tfound jar entry: {}" , entryName ) ; filteredJarEntryList . add ( entry ) ; } } final ByteArrayOutputStream out = new ByteArrayOutputStream ( ) ; triggerWildcardExpander ( allFiles , wildcardContext ) ; for ( final JarEntry entry : filteredJarEntryList ) { final InputStream is = jarFile . getInputStream ( entry ) ; IOUtils . copy ( is , out ) ; is . close ( ) ; } return new BufferedInputStream ( new ByteArrayInputStream ( out . toByteArray ( ) ) ) ; } finally { IOUtils . closeQuietly ( jarFile ) ; }


signature:
public class WebjarsUriLocator { /** * Replaces the protocol specific prefix and removes the query path if it exist , since it should not be accepted . */
private String extractPath ( final String uri ) { } }

implementation: return DefaultWildcardStreamLocator . stripQueryPath ( uri . replace ( PREFIX , StringUtils . EMPTY ) ) ;


signature:
public class DefaultCacheKeyFactory { /** * { @ inheritDoc } */
public CacheKey create ( final HttpServletRequest request ) { } }

implementation: notNull ( request ) ; CacheKey key = null ; final String groupName = groupExtractor . getGroupName ( request ) ; final ResourceType resourceType = groupExtractor . getResourceType ( request ) ; final boolean minimize = isMinimized ( request ) ; if ( groupName != null && resourceType != null ) { key = new CacheKey ( groupName , resourceType , minimize ) ; } return key ;


signature:
public class DefaultCacheKeyFactory { /** * Uses isMinimizeEnabled configuration to compute minimize value . */
private boolean isMinimized ( final HttpServletRequest request ) { } }

implementation: return context . getConfig ( ) . isMinimizeEnabled ( ) ? groupExtractor . isMinimized ( request ) : false ;


signature:
public class AbstractReportXmlFormatter { /** * write the content to the { @ link OutputStream } */
private void writeReport ( final OutputStream outputStream ) { } }

implementation: Transformer transformer ; try { transformer = TransformerFactory . newInstance ( ) . newTransformer ( ) ; transformer . transform ( new DOMSource ( doc ) , new StreamResult ( outputStream ) ) ; } catch ( Exception e ) { throw WroRuntimeException . wrap ( e , "Problem during Document transformation" ) . logError ( ) ; }


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

implementation: final StopWatch stopWatch = new StopWatch ( "Create Wro Model from Groovy" ) ; final Script script ; try { stopWatch . start ( "parseStream" ) ; script = new GroovyShell ( ) . parse ( new InputStreamReader ( new AutoCloseInputStream ( getModelResourceAsStream ( ) ) ) ) ; LOG . debug ( "Parsing groovy script to build the model" ) ; stopWatch . stop ( ) ; stopWatch . start ( "parseScript" ) ; final WroModel model = GroovyModelParser . parse ( script ) ; stopWatch . stop ( ) ; LOG . debug ( "groovy model: {}" , model ) ; if ( model == null ) { throw new WroRuntimeException ( "Invalid content provided, cannot build model!" ) ; } return model ; } catch ( final IOException e ) { throw new WroRuntimeException ( "Invalid model found!" , e ) ; } finally { LOG . debug ( stopWatch . prettyPrint ( ) ) ; }


signature:
public class SimpleUriLocatorFactory { /** * Allow adding more than one uriLocators .
 * @ param locators list of { @ link UriLocator } arguments . */
public final SimpleUriLocatorFactory addLocator ( final UriLocator ... locators ) { } }

implementation: for ( final UriLocator locator : locators ) { uriLocators . add ( locator ) ; } return this ;


signature:
public class DefaultWroModelFactoryDecorator { /** * Factory method which takes care of redundant decoration . */
public static WroModelFactory decorate ( final WroModelFactory decorated , final List < Transformer < WroModel > > modelTransformers ) { } }

implementation: return decorated instanceof DefaultWroModelFactoryDecorator ? decorated : new DefaultWroModelFactoryDecorator ( decorated , modelTransformers ) ;


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

implementation: try { final String result = new Lessify ( ) . variablizeColors ( IOUtils . toString ( reader ) ) ; writer . write ( result ) ; } finally { reader . close ( ) ; writer . close ( ) ; }


signature:
public class RubySassEngine { /** * Adds a ruby require to the ruby script to be run by this RubySassEngine . It ' s safe to add the same require twice .
 * @ param require
 * The name of the require , e . g . bourbon */
public void addRequire ( final String require ) { } }

implementation: if ( require != null && require . trim ( ) . length ( ) > 0 ) { requires . add ( require . trim ( ) ) ; }


signature:
public class RubySassEngine { /** * Transforms a sass content into css using Sass ruby engine . This method is synchronized because the engine itself is
 * not thread - safe .
 * @ param content
 * the Sass content to process . */
public String process ( final String content ) { } }

implementation: if ( isEmpty ( content ) ) { return StringUtils . EMPTY ; } try { synchronized ( this ) { return engineInitializer . get ( ) . eval ( buildUpdateScript ( content ) ) . toString ( ) ; } } catch ( final ScriptException e ) { throw new WroRuntimeException ( e . getMessage ( ) , e ) ; }


signature:
public class CRC32HashStrategy { /** * { @ inheritDoc } */
public String getHash ( final InputStream input ) throws IOException { } }

implementation: if ( input == null ) { throw new IllegalArgumentException ( "Content cannot be null!" ) ; } try { LOG . debug ( "creating hash using CRC32 algorithm" ) ; final Checksum checksum = new CRC32 ( ) ; final byte [ ] bytes = new byte [ 1024 ] ; int len = 0 ; while ( ( len = input . read ( bytes ) ) >= 0 ) { checksum . update ( bytes , 0 , len ) ; } final String hash = new BigInteger ( Long . toString ( checksum . getValue ( ) ) ) . toString ( 16 ) ; LOG . debug ( "CRC32 hash: {}" , hash ) ; return hash ; } finally { IOUtils . closeQuietly ( input ) ; }


signature:
public class ProgressIndicator { /** * Logs the summary as it was collected at this point . */
public void logSummary ( ) { } }

implementation: final String message = totalFoundErrors == 0 ? "No lint errors found." : String . format ( "Found %s errors in %s files." , totalFoundErrors , totalResourcesWithErrors ) ; log . info ( "----------------------------------------" ) ; log . info ( String . format ( "Total resources: %s" , totalResources ) ) ; log . info ( message ) ; log . info ( "----------------------------------------\n" ) ;


signature:
public class ProgressIndicator { /** * A method which should be invoked on each new resource processing , having as a side effect an increment of the
 * counter holding the number of total processed resources . */
public synchronized void onProcessingResource ( final Resource resource ) { } }

implementation: totalResources ++ ; log . debug ( "processing resource: " + resource . getUri ( ) ) ; if ( isLogRequired ( ) ) { log . info ( "Processed until now: " + getTotalResources ( ) + ". Last processed: " + resource . getUri ( ) ) ; updateLastInvocation ( ) ; }


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

implementation: final ResourcePreProcessor decoratedProcessor = getDecoratedObject ( ) ; if ( decoratedProcessor instanceof SupportAware ) { if ( ! ( ( SupportAware ) decoratedProcessor ) . isSupported ( ) ) { throw new WroRuntimeException ( toString ( ) + " processor is not supported on this environment" ) ; } } super . process ( resource , reader , writer ) ;


signature:
public class AbstractSynchronizedCacheStrategyDecorator { /** * Ensure that the returned lock will never be null . */
private ReadWriteLock getLockForKey ( final K key ) { } }

implementation: final ReadWriteLock lock = locks . putIfAbsent ( key , new ReentrantReadWriteLock ( ) ) ; return lock == null ? locks . get ( key ) : lock ;