idx
int64
0
41.2k
question
stringlengths
74
4.21k
target
stringlengths
5
888
2,500
public boolean isHandlingCssImage ( String cssResourcePath ) { boolean isHandlingCssImage = false ; ResourceGenerator generator = resolveResourceGenerator ( cssResourcePath ) ; if ( generator != null && cssImageResourceGeneratorRegistry . contains ( generator ) ) { isHandlingCssImage = true ; } return isHandlingCssImage ; }
Returns true if the generator associated to the css resource path handle also CSS image .
2,501
public boolean isGeneratedBinaryResource ( String resourcePath ) { boolean isGeneratedImage = false ; ResourceGenerator generator = resolveResourceGenerator ( resourcePath ) ; if ( generator != null && binaryResourceGeneratorRegistry . contains ( generator ) ) { isGeneratedImage = true ; } return isGeneratedImage ; }
Returns true if the generator associated to the binary resource path is an Image generator .
2,502
public Map < String , String > resolveVariants ( HttpServletRequest request ) { Map < String , String > variants = new TreeMap < > ( ) ; for ( VariantResolver resolver : variantResolvers . values ( ) ) { String value = resolver . resolveVariant ( request ) ; if ( value != null ) { variants . put ( resolver . getVariantType ( ) , value ) ; } } return variants ; }
Resolve the variants for the request passed in parameter
2,503
public Map < String , String > getAvailableVariantMap ( Map < String , VariantSet > variants , Map < String , String > curVariants ) { Map < String , String > availableVariantMap = new HashMap < > ( ) ; for ( Entry < String , VariantSet > entry : variants . entrySet ( ) ) { String variantType = entry . getKey ( ) ; VariantSet variantSet = entry . getValue ( ) ; String variant = variantSet . getDefaultVariant ( ) ; if ( curVariants . containsKey ( variantType ) ) { String curVariant = curVariants . get ( variantType ) ; VariantResolver resolver = variantResolvers . get ( variantType ) ; if ( resolver != null ) { variant = resolver . getAvailableVariant ( curVariant , variants . get ( variantType ) ) ; if ( variant == null ) { variant = variants . get ( variantType ) . getDefaultVariant ( ) ; } } else { throw new BundlingProcessException ( "Unable to find variant resolver for variant type '" + variantType + "'" ) ; } } availableVariantMap . put ( variantType , variant ) ; } return availableVariantMap ; }
Returns the available variants .
2,504
public List < PathMapping > getGeneratedPathMappings ( JoinableResourceBundle bundle , String path , ResourceReaderHandler rsReader ) { List < PathMapping > pathMappings = null ; ResourceGenerator resourceGenerator = getResourceGenerator ( path ) ; if ( resourceGenerator instanceof PathMappingProvider ) { pathMappings = ( ( PathMappingProvider ) resourceGenerator ) . getPathMappings ( bundle , path , rsReader ) ; } return pathMappings ; }
Returns the PathMapping for the generated resource
2,505
protected void prependBase64EncodedResources ( StringBuffer sb , Map < String , Base64EncodedResource > encodedImages ) { Iterator < Entry < String , Base64EncodedResource > > it = encodedImages . entrySet ( ) . iterator ( ) ; StringBuilder mhtml = new StringBuilder ( ) ; String lineSeparator = StringUtils . STR_LINE_FEED ; mhtml . append ( "/*!" ) . append ( lineSeparator ) ; mhtml . append ( "Content-Type: multipart/related; boundary=\"" + BOUNDARY_SEPARATOR + "\"" ) . append ( lineSeparator ) . append ( lineSeparator ) ; while ( it . hasNext ( ) ) { Entry < String , Base64EncodedResource > pair = it . next ( ) ; Base64EncodedResource encodedResource = ( Base64EncodedResource ) pair . getValue ( ) ; mhtml . append ( BOUNDARY_SEPARATOR_PREFIX + BOUNDARY_SEPARATOR ) . append ( lineSeparator ) ; mhtml . append ( "Content-Type:" ) . append ( encodedResource . getType ( ) ) . append ( lineSeparator ) ; mhtml . append ( "Content-Location:" ) . append ( encodedResource . getId ( ) ) . append ( lineSeparator ) ; mhtml . append ( "Content-Transfer-Encoding:base64" ) . append ( lineSeparator ) . append ( lineSeparator ) ; mhtml . append ( encodedResource . getBase64Encoding ( ) ) . append ( lineSeparator ) . append ( lineSeparator ) ; } mhtml . append ( BOUNDARY_SEPARATOR_PREFIX + BOUNDARY_SEPARATOR + BOUNDARY_SEPARATOR_PREFIX ) . append ( lineSeparator ) ; mhtml . append ( "*/" ) . append ( lineSeparator ) . append ( lineSeparator ) ; sb . insert ( 0 , mhtml . toString ( ) ) ; }
Prepend the base64 encoded resources to the bundle data
2,506
private int getPriority ( ResourceReader o1 ) { int priority = 0 ; if ( o1 instanceof ServletContextResourceReader ) { priority = baseDirHighPriority ? 5 : 4 ; } else if ( o1 instanceof FileSystemResourceReader ) { priority = baseDirHighPriority ? 4 : 5 ; } else if ( o1 instanceof CssSmartSpritesResourceReader ) { priority = 1 ; } else if ( o1 instanceof ResourceGenerator ) { if ( ( ( ResourceGenerator ) o1 ) . getResolver ( ) . getType ( ) . equals ( ResolverType . PREFIXED ) ) { priority = 3 ; } else { priority = 2 ; } } return priority ; }
Returns the priority of the resource reader
2,507
private void initMapping ( BinaryResourcesHandler binaryRsHandler ) { if ( jawrConfig . getUseBundleMapping ( ) && rsBundleHandler . isExistingMappingFile ( ) ) { Iterator < Entry < Object , Object > > mapIterator = bundleMapping . entrySet ( ) . iterator ( ) ; while ( mapIterator . hasNext ( ) ) { Entry < Object , Object > entry = mapIterator . next ( ) ; binaryRsHandler . addMapping ( ( String ) entry . getKey ( ) , entry . getValue ( ) . toString ( ) ) ; } } else { String binaryResourcesDefinition = jawrConfig . getBinaryResourcesDefinition ( ) ; if ( binaryResourcesDefinition != null ) { StringTokenizer tokenizer = new StringTokenizer ( binaryResourcesDefinition , "," ) ; while ( tokenizer . hasMoreTokens ( ) ) { String pathMapping = tokenizer . nextToken ( ) ; if ( generatorRegistry . isGeneratedBinaryResource ( pathMapping ) && hasBinaryFileExtension ( pathMapping ) ) { addBinaryResourcePath ( binaryRsHandler , pathMapping ) ; } else if ( pathMapping . endsWith ( "/" ) ) { addItemsFromDir ( binaryRsHandler , pathMapping , false ) ; } else if ( pathMapping . endsWith ( "/**" ) ) { addItemsFromDir ( binaryRsHandler , pathMapping . substring ( 0 , pathMapping . lastIndexOf ( "**" ) ) , true ) ; } else if ( hasBinaryFileExtension ( pathMapping ) ) { addBinaryResourcePath ( binaryRsHandler , pathMapping ) ; } else LOGGER . warn ( "Wrong mapping [" + pathMapping + "] for image bundle. Please check configuration. " ) ; } } } if ( jawrConfig . getUseBundleMapping ( ) && ! rsBundleHandler . isExistingMappingFile ( ) ) { rsBundleHandler . storeJawrBundleMapping ( bundleMapping ) ; } if ( LOGGER . isDebugEnabled ( ) ) LOGGER . debug ( "Finish creation of map for image bundle" ) ; }
Initialize the mapping of the binary web resources handler
2,508
private void addBinaryResourcePath ( BinaryResourcesHandler binRsHandler , String resourcePath ) { try { String resultPath = CheckSumUtils . getCacheBustedUrl ( resourcePath , rsReaderHandler , jawrConfig ) ; binRsHandler . addMapping ( resourcePath , resultPath ) ; bundleMapping . put ( resourcePath , resultPath ) ; } catch ( IOException e ) { LOGGER . error ( "An exception occurs while defining the mapping for the file : " + resourcePath , e ) ; } catch ( ResourceNotFoundException e ) { LOGGER . error ( "Impossible to define the checksum for the resource '" + resourcePath + "'. Unable to retrieve the content of the file." ) ; } }
Add an binary resource path to the binary map
2,509
private boolean hasBinaryFileExtension ( String path ) { boolean result = false ; int extFileIdx = path . lastIndexOf ( "." ) ; if ( extFileIdx != - 1 && extFileIdx + 1 < path . length ( ) ) { String extension = path . substring ( extFileIdx + 1 ) ; result = binaryMimeTypeMap . containsKey ( extension ) ; } return result ; }
Returns true of the path contains a binary file extension
2,510
private void addItemsFromDir ( BinaryResourcesHandler binRsHandler , String dirName , boolean addSubDirs ) { Set < String > resources = rsReaderHandler . getResourceNames ( dirName ) ; if ( LOGGER . isDebugEnabled ( ) ) { LOGGER . debug ( "Adding " + resources . size ( ) + " resources from path [" + dirName + "] to binary bundle" ) ; } GeneratorRegistry binGeneratorRegistry = binRsHandler . getConfig ( ) . getGeneratorRegistry ( ) ; List < String > folders = new ArrayList < > ( ) ; boolean generatedPath = binGeneratorRegistry . isPathGenerated ( dirName ) ; for ( String resourceName : resources ) { String resourcePath = PathNormalizer . joinPaths ( dirName , resourceName , generatedPath ) ; if ( hasBinaryFileExtension ( resourceName ) ) { addBinaryResourcePath ( binRsHandler , resourcePath ) ; if ( LOGGER . isDebugEnabled ( ) ) LOGGER . debug ( "Added to item path list:" + PathNormalizer . asPath ( resourcePath ) ) ; } else if ( addSubDirs ) { try { if ( rsReaderHandler . isDirectory ( resourcePath ) ) { folders . add ( resourceName ) ; } } catch ( InvalidPathException e ) { if ( LOGGER . isDebugEnabled ( ) ) LOGGER . debug ( "Enable to define if the following resource is a directory : " + PathNormalizer . asPath ( resourcePath ) ) ; } } } if ( addSubDirs ) { for ( String folderName : folders ) { addItemsFromDir ( binRsHandler , PathNormalizer . joinPaths ( dirName , folderName ) , true ) ; } } }
Adds all the resources within a path to the image map .
2,511
protected String getContentType ( String filePath , HttpServletRequest request ) { String requestUri = request . getRequestURI ( ) ; String extension = getExtension ( filePath ) ; if ( extension == null ) { LOGGER . info ( "No extension found for the request URI : " + requestUri ) ; return null ; } String binContentType = ( String ) binaryMimeTypeMap . get ( extension ) ; if ( binContentType == null ) { LOGGER . info ( "No binary extension match the extension '" + extension + "' for the request URI : " + requestUri ) ; return null ; } return binContentType ; }
Returns the content type for the image
2,512
private String getRealFilePath ( String fileName , BundleHashcodeType bundleHashcodeType ) { String realFilePath = fileName ; if ( bundleHashcodeType . equals ( BundleHashcodeType . INVALID_HASHCODE ) ) { int idx = realFilePath . indexOf ( JawrConstant . URL_SEPARATOR , 1 ) ; if ( idx != - 1 ) { realFilePath = realFilePath . substring ( idx ) ; } } else { String [ ] resourceInfo = PathNormalizer . extractBinaryResourceInfo ( realFilePath ) ; realFilePath = resourceInfo [ 0 ] ; } return realFilePath ; }
Removes the cache buster
2,513
private InputStream getResourceInputStream ( String path ) { InputStream is = config . getContext ( ) . getResourceAsStream ( path ) ; if ( is == null ) { try { is = ClassLoaderResourceUtils . getResourceAsStream ( path , this ) ; } catch ( FileNotFoundException e ) { throw new BundlingProcessException ( e ) ; } } return is ; }
Returns the resource input stream
2,514
public String compile ( String resourcePath , String coffeeScriptSource ) { String result = null ; try { result = ( String ) jsEngine . invokeMethod ( coffeeScript , "compile" , coffeeScriptSource , options ) ; } catch ( NoSuchMethodException | ScriptException e ) { throw new BundlingProcessException ( e ) ; } return result ; }
Compile the CoffeeScript source to a JS source
2,515
public StringBuffer serializeBundles ( ) { StringBuffer sb = new StringBuffer ( "{" ) ; for ( Iterator < String > it = keyMap . keySet ( ) . iterator ( ) ; it . hasNext ( ) ; ) { String currentKey = it . next ( ) ; handleKey ( sb , keyMap , currentKey , currentKey , ! it . hasNext ( ) ) ; } return sb . append ( "}" ) ; }
Creates a javascript object literal representing a set of message resources .
2,516
@ SuppressWarnings ( "unchecked" ) private void handleKey ( final StringBuffer sb , Map < String , Object > currentLeaf , String currentKey , String fullKey , boolean isLeafLast ) { Map < String , Object > newLeaf = ( Map < String , Object > ) currentLeaf . get ( currentKey ) ; if ( bundleValues . containsKey ( fullKey ) ) { addValuedKey ( sb , currentKey , fullKey ) ; if ( ! newLeaf . isEmpty ( ) ) { sb . append ( ",({" ) ; for ( Iterator < String > it = newLeaf . keySet ( ) . iterator ( ) ; it . hasNext ( ) ; ) { String newKey = it . next ( ) ; handleKey ( sb , newLeaf , newKey , fullKey + "." + newKey , ! it . hasNext ( ) ) ; } sb . append ( "}))" ) ; } else { sb . append ( ")" ) ; } } else if ( ! newLeaf . isEmpty ( ) ) { sb . append ( getJsonKey ( currentKey ) ) . append ( ":{" ) ; for ( Iterator < String > it = newLeaf . keySet ( ) . iterator ( ) ; it . hasNext ( ) ; ) { String newKey = it . next ( ) ; handleKey ( sb , newLeaf , newKey , fullKey + "." + newKey , ! it . hasNext ( ) ) ; } sb . append ( "}" ) ; } if ( ! isLeafLast ) sb . append ( "," ) ; }
Processes a leaf from the key map adding its name and values recursively in a javascript object literal structure where values are invocations of a method that returns a function .
2,517
private String getJsonKey ( String key ) { String jsonKey = key ; if ( addQuoteToKey ) { jsonKey = JavascriptStringUtil . quote ( key ) ; } return jsonKey ; }
Returns the json key for messages taking in account the addQuoteToKey attribute .
2,518
private void addValuedKey ( final StringBuffer sb , String key , String fullKey ) { sb . append ( getJsonKey ( key ) ) . append ( ":" ) . append ( FUNC ) . append ( JavascriptStringUtil . quote ( bundleValues . get ( fullKey ) . toString ( ) ) ) ; }
Add a key and its value to the object literal .
2,519
public String generateAntiSpamMailto ( String name , String email ) { StringTokenizer st = new StringTokenizer ( email , "@" ) ; if ( Security . containsXssRiskyCharacters ( email ) || st . countTokens ( ) != 2 ) { throw new IllegalArgumentException ( "Invalid email address: " + email ) ; } String before = st . nextToken ( ) ; String after = st . nextToken ( ) ; StringBuffer buffer = new StringBuffer ( ) ; buffer . append ( "Contact " ) ; buffer . append ( Security . replaceXmlCharacters ( name ) ) ; buffer . append ( " using: <span id=\"asmgLink\"></span>\n" ) ; buffer . append ( "<script type='text/javascript'>\n" ) ; buffer . append ( "var before = '" ) ; buffer . append ( before ) ; buffer . append ( "';\n" ) ; buffer . append ( "var after = '" ) ; buffer . append ( after ) ; buffer . append ( "';\n" ) ; buffer . append ( "var link = \"<a href='mail\" + \"to:\" + before + '@' + after + \"'>\" + before + '@' + after + \"</a>\";\n" ) ; buffer . append ( "document.getElementById(\"asmgLink\").innerHTML = link;\n" ) ; buffer . append ( "</script>\n" ) ; buffer . append ( "<noscript>[" ) ; buffer . append ( before ) ; buffer . append ( " at " ) ; buffer . append ( after ) ; buffer . append ( "]</noscript>\n" ) ; return buffer . toString ( ) ; }
Generate an anti - spam mailto link from an email address
2,520
private static void addSuffixIfAvailable ( String messageBundlePath , List < String > availableLocaleSuffixes , Locale locale , String fileSuffix , GrailsServletContextResourceReader rsReader ) { String localMsgResourcePath = toBundleName ( messageBundlePath , locale ) + fileSuffix ; boolean isFileSystemResourcePath = rsReader . isFileSystemPath ( localMsgResourcePath ) ; boolean resourceFound = false ; String path = localMsgResourcePath ; if ( ! isFileSystemResourcePath ) { path = WEB_INF_DIR + localMsgResourcePath ; } InputStream is = null ; try { is = rsReader . getResourceAsStream ( path ) ; resourceFound = is != null ; } finally { IOUtils . close ( is ) ; } if ( resourceFound ) { String suffix = localMsgResourcePath . substring ( messageBundlePath . length ( ) ) ; if ( suffix . length ( ) > 0 ) { if ( suffix . length ( ) == fileSuffix . length ( ) ) { suffix = "" ; } else { suffix = suffix . substring ( 1 , suffix . length ( ) - fileSuffix . length ( ) ) ; } } availableLocaleSuffixes . add ( suffix ) ; } }
Add the locale suffix if the message resource bundle file exists .
2,521
public static boolean isPluginResoucePath ( String resourcePath ) { Matcher matcher = PLUGIN_RESOURCE_PATTERN . matcher ( resourcePath ) ; return matcher . find ( ) ; }
Returns true is the resource path is a plugin path
2,522
public static String getRealResourcePath ( String path , Map < String , String > pluginMsgPathMap ) { String realPath = path ; Matcher matcher = PLUGIN_RESOURCE_PATTERN . matcher ( path ) ; StringBuffer sb = new StringBuffer ( ) ; if ( matcher . find ( ) ) { String pluginName = matcher . group ( 2 ) ; String pluginPath = pluginMsgPathMap . get ( pluginName ) ; if ( pluginPath != null ) { matcher . appendReplacement ( sb , RegexUtil . adaptReplacementToMatcher ( pluginPath + "/" ) ) ; matcher . appendTail ( sb ) ; realPath = sb . toString ( ) ; if ( LOGGER . isDebugEnabled ( ) ) { LOGGER . debug ( "Plugin path '" + path + "' mapped to '" + realPath + "'" ) ; } } else { if ( LOGGER . isDebugEnabled ( ) ) { LOGGER . debug ( "No Plugin path found for '" + pluginName ) ; } } } return realPath ; }
Handle the mapping of the resource path to the right one . This can be the case for plugin resources . It will returns the file system path or the real path or the same path if the path has not been remapped
2,523
public void handleClientSideHandlerRequest ( HttpServletRequest request , HttpServletResponse response ) { Handler handler ; Map < String , String > variants = config . getGeneratorRegistry ( ) . resolveVariants ( request ) ; String variantKey = VariantUtils . getVariantKey ( variants ) ; if ( handlerCache . containsKey ( variantKey ) ) { handler = ( Handler ) handlerCache . get ( variantKey ) ; } else { StringBuffer sb = rsHandler . getClientSideHandler ( ) . getClientSideHandlerScript ( request ) ; handler = new Handler ( sb , Integer . toString ( sb . hashCode ( ) ) ) ; handlerCache . put ( variantKey , handler ) ; } if ( useNotModifiedHeader ( request , handler . hash ) ) { response . setStatus ( HttpServletResponse . SC_NOT_MODIFIED ) ; return ; } response . setHeader ( HEADER_ETAG , handler . hash ) ; response . setDateHeader ( HEADER_LAST_MODIFIED , START_TIME ) ; response . setContentType ( JAVASCRIPT_CONTENT_TYPE ) ; if ( RendererRequestUtils . isRequestGzippable ( request , this . config ) ) { try { response . setHeader ( "Content-Encoding" , "gzip" ) ; GZIPOutputStream gzOut = new GZIPOutputStream ( response . getOutputStream ( ) ) ; byte [ ] data = handler . data . toString ( ) . getBytes ( this . config . getResourceCharset ( ) . name ( ) ) ; gzOut . write ( data , 0 , data . length ) ; gzOut . close ( ) ; } catch ( IOException e ) { throw new BundlingProcessException ( "Unexpected IOException writing ClientSideHandlerScript" , e ) ; } } else { StringReader rd = new StringReader ( handler . data . toString ( ) ) ; try { Writer writer = response . getWriter ( ) ; IOUtils . copy ( rd , writer , true ) ; } catch ( IOException e ) { throw new BundlingProcessException ( "Unexpected IOException writing ClientSideHandlerScript" , e ) ; } } }
Generates a locale dependent script used to include bundles in non dynamic html pages . Uses a cache of said scripts to avoid constant regeneration . It also keeps track of eTags and if - modified - since headers to take advantage of client side caching .
2,524
private boolean useNotModifiedHeader ( HttpServletRequest request , String scriptEtag ) { long modifiedHeader = - 1 ; try { modifiedHeader = request . getDateHeader ( HEADER_IF_MODIFIED ) ; if ( modifiedHeader != - 1 ) modifiedHeader -= modifiedHeader % 1000 ; } catch ( RuntimeException ex ) { } String eTag = request . getHeader ( HEADER_IF_NONE ) ; if ( modifiedHeader == - 1 ) { return scriptEtag . equals ( eTag ) ; } else if ( null == eTag ) { return modifiedHeader <= START_TIME ; } else { return scriptEtag . equals ( eTag ) && modifiedHeader <= START_TIME ; } }
Determines whether a response should get a 304 response and empty body according to etags and if - modified - since headers .
2,525
private void addFilePathMapping ( BundlePathMapping bundlePathMapping , Set < String > paths ) { for ( String path : paths ) { addFilePathMapping ( bundlePathMapping , path ) ; } }
Adds paths to the file path mapping
2,526
private void addFilePathMapping ( BundlePathMapping bundlePathMapping , List < BundlePath > itemPathList ) { for ( BundlePath bundlePath : itemPathList ) { addFilePathMapping ( bundlePathMapping , bundlePath . getPath ( ) ) ; } }
Adds bundle paths to the file path mapping
2,527
private static String getFullImagePath ( String imgSrc , BinaryResourcesHandler binaryRsHandler , HttpServletRequest request ) { String contextPath = request . getContextPath ( ) ; if ( ! binaryRsHandler . getConfig ( ) . getGeneratorRegistry ( ) . isGeneratedBinaryResource ( imgSrc ) && ! imgSrc . startsWith ( "/" ) ) { imgSrc = PathNormalizer . concatWebPath ( request . getRequestURI ( ) , imgSrc ) ; int idx = imgSrc . indexOf ( contextPath ) ; if ( idx > - 1 ) { imgSrc = imgSrc . substring ( idx + contextPath . length ( ) ) ; } } return imgSrc ; }
Returns the full image path to handle the relative path
2,528
public static String getImageUrl ( String imgSrc , PageContext pageContext ) { BinaryResourcesHandler imgRsHandler = ( BinaryResourcesHandler ) pageContext . getServletContext ( ) . getAttribute ( JawrConstant . BINARY_CONTEXT_ATTRIBUTE ) ; if ( null == imgRsHandler ) throw new JawrLinkRenderingException ( "You are using a Jawr image tag while the Jawr Image servlet has not been initialized. Initialization of Jawr Image servlet either failed or never occurred." ) ; HttpServletResponse response = ( HttpServletResponse ) pageContext . getResponse ( ) ; HttpServletRequest request = ( HttpServletRequest ) pageContext . getRequest ( ) ; return getImageUrl ( imgSrc , imgRsHandler , request , response ) ; }
Sames as its counterpart only meant to be used as a JSP EL function .
2,529
public static String getBase64EncodedImage ( String imgSrc , BinaryResourcesHandler binaryRsHandler , HttpServletRequest request ) { String encodedResult = null ; if ( null == binaryRsHandler ) { throw new JawrLinkRenderingException ( "You are using a Jawr image tag while the Jawr Image servlet has not been initialized. Initialization of Jawr Image servlet either failed or never occurred." ) ; } imgSrc = getFullImagePath ( imgSrc , binaryRsHandler , request ) ; encodedResult = binaryRsHandler . getCacheUrl ( BASE64_KEY_PREFIX + imgSrc ) ; if ( encodedResult == null ) { try { String fileExtension = FileNameUtils . getExtension ( imgSrc ) ; String fileMimeType = ( String ) MIMETypesSupport . getSupportedProperties ( ImageTagUtils . class ) . get ( fileExtension ) ; InputStream is = binaryRsHandler . getRsReaderHandler ( ) . getResourceAsStream ( imgSrc ) ; ByteArrayOutputStream out = new ByteArrayOutputStream ( ) ; IOUtils . copy ( is , out , true ) ; byte [ ] data = out . toByteArray ( ) ; encodedResult = new String ( Base64Encoder . encode ( data ) ) ; encodedResult = DATA_PREFIX + fileMimeType + ";base64," + encodedResult ; binaryRsHandler . addMapping ( BASE64_KEY_PREFIX + imgSrc , encodedResult ) ; } catch ( ResourceNotFoundException e ) { LOGGER . warn ( "Unable to find the image '" + imgSrc + "' while generating image tag." ) ; } catch ( IOException e ) { LOGGER . warn ( "Unable to copy the image '" + imgSrc + "' while generating image tag." ) ; } } return encodedResult ; }
Returns the base64 image of the image path given in parameter
2,530
public static void setClosingTag ( String flavor ) { if ( FLAVORS_XHTML_EXTENDED . equalsIgnoreCase ( flavor ) ) { closingFlavor = POST_XHTML_EXT_TAG ; } else if ( FLAVORS_HTML . equalsIgnoreCase ( flavor ) ) closingFlavor = POST_HTML_TAG ; else closingFlavor = POST_TAG ; }
Utility method to get the closing tag value based on a config parameter .
2,531
private boolean isForcedToRenderIeCssBundleInDebug ( BundleRendererContext ctx , boolean debugOn ) { return debugOn && getResourceType ( ) . equals ( JawrConstant . CSS_TYPE ) && bundler . getConfig ( ) . isForceCssBundleInDebugForIEOn ( ) && RendererRequestUtils . isIE ( ctx . getRequest ( ) ) ; }
Returns true if the renderer must render a CSS bundle link even in debug mode
2,532
private void renderIeCssBundleLink ( BundleRendererContext ctx , Writer out , BundlePath bundlePath ) throws IOException { Random randomSeed = new Random ( ) ; int random = randomSeed . nextInt ( ) ; if ( random < 0 ) random *= - 1 ; String path = GeneratorRegistry . IE_CSS_GENERATOR_PREFIX + GeneratorRegistry . PREFIX_SEPARATOR + bundlePath . getPath ( ) ; path = PathNormalizer . createGenerationPath ( path , bundler . getConfig ( ) . getGeneratorRegistry ( ) , "d=" + random ) ; out . write ( createBundleLink ( path , null , null , ctx . getContextPath ( ) , ctx . isSslRequest ( ) ) ) ; }
Renders the CSS link to retrieve the CSS bundle for IE in debug mode .
2,533
private String compile ( JoinableResourceBundle bundle , String content , String path , GeneratorContext ctx ) throws ScriptException , IOException { try ( InputStream is = getResourceInputStream ( JAWR_IMPORTER_RB ) ) { String script = IOUtils . toString ( is ) ; rubyEngine . eval ( script ) ; } SimpleBindings bindings = new SimpleBindings ( ) ; JawrSassResolver scssResolver = new JawrSassResolver ( bundle , path , rsHandler , useAbsoluteURL ) ; bindings . put ( JAWR_RESOLVER_VAR , scssResolver ) ; String compiledScss = rubyEngine . eval ( buildScript ( path , content ) , bindings ) . toString ( ) ; addLinkedResources ( path , ctx , scssResolver . getLinkedResources ( ) ) ; return compiledScss ; }
Compile the Sass content
2,534
private String buildScript ( String path , String content ) { StringBuilder script = new StringBuilder ( ) ; script . append ( "require 'rubygems'\n" + "require 'sass/plugin'\n" + "require 'sass/engine'\n" ) ; content = SassRubyUtils . normalizeMultiByteString ( content ) ; script . append ( String . format ( "customImporter = Sass::Importers::JawrImporter.new(@jawrResolver) \n" + "name = \"%s\"\n" + "result = Sass::Engine.new(\"%s\", {:importer => customImporter, :filename => name, :syntax => :scss, :cache => false}).render" , path , content . replace ( "\"" , "\\\"" ) . replace ( "#" , "\\#" ) ) ) ; return script . toString ( ) ; }
Builds the ruby script to execute
2,535
public final void setCharsetName ( String charsetName ) { if ( ! Charset . isSupported ( charsetName ) ) throw new IllegalArgumentException ( "The specified charset [" + charsetName + "] is not supported by the jvm." ) ; this . charsetName = charsetName ; }
Set the charsetname to be used to interpret and generate resource .
2,536
public void setGeneratorRegistry ( GeneratorRegistry generatorRegistry ) { this . generatorRegistry = generatorRegistry ; this . generatorRegistry . setConfig ( this ) ; localeResolver = null ; if ( configProperties . getProperty ( JAWR_LOCALE_RESOLVER ) == null ) { localeResolver = new DefaultLocaleResolver ( ) ; } else { localeResolver = ( LocaleResolver ) ClassLoaderResourceUtils . buildObjectInstance ( configProperties . getProperty ( JAWR_LOCALE_RESOLVER ) ) ; } this . generatorRegistry . registerVariantResolver ( new LocaleVariantResolverWrapper ( localeResolver ) ) ; registerResolver ( new BrowserResolver ( ) , JAWR_BROWSER_RESOLVER ) ; registerResolver ( new ConnectionTypeResolver ( ) , JAWR_CONNECTION_TYPE_SCHEME_RESOLVER ) ; registerResolver ( new CssSkinVariantResolver ( ) , JAWR_CSS_SKIN_RESOLVER ) ; }
Set the generator registry
2,537
private VariantResolver registerResolver ( VariantResolver defaultResolver , String configPropertyName ) { VariantResolver resolver = null ; if ( configProperties . getProperty ( configPropertyName ) == null ) { resolver = defaultResolver ; } else { resolver = ( VariantResolver ) ClassLoaderResourceUtils . buildObjectInstance ( configProperties . getProperty ( configPropertyName ) ) ; } this . generatorRegistry . registerVariantResolver ( resolver ) ; return resolver ; }
Register a resolver in the generator registry
2,538
public final void setCssLinkFlavor ( String cssLinkFlavor ) { if ( CSSHTMLBundleLinkRenderer . FLAVORS_HTML . equalsIgnoreCase ( cssLinkFlavor ) || CSSHTMLBundleLinkRenderer . FLAVORS_XHTML . equalsIgnoreCase ( cssLinkFlavor ) || CSSHTMLBundleLinkRenderer . FLAVORS_XHTML_EXTENDED . equalsIgnoreCase ( cssLinkFlavor ) ) CSSHTMLBundleLinkRenderer . setClosingTag ( cssLinkFlavor ) ; else { throw new IllegalArgumentException ( "The value for the jawr.csslinks.flavor " + "property [" + cssLinkFlavor + "] is invalid. " + "Please check the docs for valid values " ) ; } }
Sets the css link flavor
2,539
public boolean getBooleanProperty ( String propertyName , boolean defaultValue ) { return Boolean . valueOf ( getProperty ( propertyName , Boolean . toString ( defaultValue ) ) ) ; }
Returns the boolean property value
2,540
public String getProperty ( String key , String defaultValue ) { String property = configProperties . getProperty ( key , defaultValue ) ; if ( property != null ) { property = property . trim ( ) ; } return property ; }
Returns the value of the property associated to the key passed in parameter
2,541
public String getJavascriptEngineName ( String defaultJsEnginePropName ) { String jsEngineName = null ; if ( StringUtils . isEmpty ( defaultJsEnginePropName ) ) { jsEngineName = getJavascriptEngineName ( ) ; } else { jsEngineName = getProperty ( defaultJsEnginePropName ) ; if ( StringUtils . isEmpty ( jsEngineName ) ) { jsEngineName = getJavascriptEngineName ( ) ; } } return jsEngineName ; }
Returns the name of JS engine to use
2,542
public void setControllerMapping ( String controllerMapping ) { if ( controllerMapping . endsWith ( "/" ) ) { this . controllerMapping = controllerMapping . substring ( 0 , controllerMapping . length ( ) - 1 ) ; } else { this . controllerMapping = controllerMapping ; } }
Sets the controller mapping
2,543
public void augmentConfiguration ( Properties configToAdd ) { for ( Entry < Object , Object > entry : configToAdd . entrySet ( ) ) { String configKey = ( String ) entry . getKey ( ) ; String configValue = ( String ) entry . getValue ( ) ; if ( null != privateConfigProperties && privateConfigProperties . contains ( configKey ) ) { LOGGER . warn ( "The property " + configKey + " can not be overridden. It will remain with a value of " + configProperties . get ( configKey ) ) ; continue ; } if ( isAugmentable ( configKey ) ) { String currentValue = configProperties . getProperty ( configKey ) ; currentValue += "," + configValue ; configProperties . put ( configKey , currentValue ) ; } else configProperties . put ( configKey , configValue ) ; } }
Augments the base configuration with the properties specified as parameter .
2,544
public HttpServlet initServlet ( ) throws Exception { servlet = ( HttpServlet ) servletClass . newInstance ( ) ; servlet . init ( servletConfig ) ; return servlet ; }
Create a new instance of the servlet and initialize it .
2,545
public static String getChecksum ( String url , ResourceReaderHandler rsReader , JawrConfig jawrConfig ) throws IOException , ResourceNotFoundException { String checksum = null ; InputStream is = null ; boolean generatedBinaryResource = jawrConfig . getGeneratorRegistry ( ) . isGeneratedBinaryResource ( url ) ; try { if ( ! generatedBinaryResource ) { url = PathNormalizer . asPath ( url ) ; } is = rsReader . getResourceAsStream ( url ) ; if ( is != null ) { checksum = CheckSumUtils . getChecksum ( is , jawrConfig . getBinaryHashAlgorithm ( ) ) ; } else { throw new ResourceNotFoundException ( url ) ; } } catch ( FileNotFoundException e ) { throw new ResourceNotFoundException ( url ) ; } finally { IOUtils . close ( is ) ; } return checksum ; }
Return the checksum of the path given in parameter if the resource is not found null will b returned .
2,546
public static String getCacheBustedUrl ( String url , ResourceReaderHandler rsReader , JawrConfig jawrConfig ) throws IOException , ResourceNotFoundException { String checksum = getChecksum ( url , rsReader , jawrConfig ) ; String result = JawrConstant . CACHE_BUSTER_PREFIX ; boolean generatedBinaryResource = jawrConfig . getGeneratorRegistry ( ) . isGeneratedBinaryResource ( url ) ; if ( generatedBinaryResource ) { int idx = url . indexOf ( GeneratorRegistry . PREFIX_SEPARATOR ) ; String generatorPrefix = url . substring ( 0 , idx ) ; url = url . substring ( idx + 1 ) ; result = generatorPrefix + "_cb" ; } result = result + checksum ; if ( ! url . startsWith ( "/" ) ) { result = result + "/" ; } return PathNormalizer . asPath ( result + url ) ; }
Return the cache busted url associated to the url passed in parameter if the resource is not found null will b returned .
2,547
public static String getChecksum ( InputStream is , String algorithm ) throws IOException { if ( algorithm . equals ( JawrConstant . CRC32_ALGORITHM ) ) { return getCRC32Checksum ( is ) ; } else if ( algorithm . equals ( JawrConstant . MD5_ALGORITHM ) ) { return getMD5Checksum ( is ) ; } else { throw new BundlingProcessException ( "The checksum algorithm '" + algorithm + "' is not supported.\n" + "The only supported algorithm are 'CRC32' or 'MD5'." ) ; } }
Returns the checksum value of the input stream taking in count the algorithm passed in parameter
2,548
public static String getCRC32Checksum ( InputStream is ) throws IOException { Checksum checksum = new CRC32 ( ) ; byte [ ] bytes = new byte [ 1024 ] ; int len = 0 ; while ( ( len = is . read ( bytes ) ) >= 0 ) { checksum . update ( bytes , 0 , len ) ; } return Long . toString ( checksum . getValue ( ) ) ; }
Returns the CRC 32 Checksum of the input stream
2,549
public static String getMD5Checksum ( InputStream is ) throws IOException { byte [ ] digest = null ; try { MessageDigest md = MessageDigest . getInstance ( JawrConstant . MD5_ALGORITHM ) ; InputStream digestIs = new DigestInputStream ( is , md ) ; while ( digestIs . read ( ) != - 1 ) { } digest = md . digest ( ) ; } catch ( NoSuchAlgorithmException e ) { throw new BundlingProcessException ( "MD5 algorithm needs to be installed" , e ) ; } return new BigInteger ( 1 , digest ) . toString ( 16 ) ; }
Returns the MD5 Checksum of the input stream
2,550
public static String getProperty ( Object bean , String name ) throws NoSuchMethodException , IllegalAccessException , InvocationTargetException { String value = null ; PropertyDescriptor descriptor = getPropertyDescriptor ( bean , name ) ; if ( descriptor == null ) { throw new NoSuchMethodException ( "Unknown property '" + name + "'" ) ; } Method readMethod = descriptor . getReadMethod ( ) ; if ( readMethod == null ) { throw new NoSuchMethodException ( "Property '" + name + "' has no getter method" ) ; } Object result = ( Object ) invokeMethod ( readMethod , bean , new Object [ 0 ] ) ; if ( result != null ) { value = result . toString ( ) ; } return value ; }
Return the value of the specified simple property of the specified bean with string conversions .
2,551
public static void setProperty ( Object bean , String name , Object value ) throws IllegalAccessException , InvocationTargetException , NoSuchMethodException { if ( bean == null ) { throw new IllegalArgumentException ( "No bean specified" ) ; } if ( name == null ) { throw new IllegalArgumentException ( "No name specified" ) ; } PropertyDescriptor descriptor = getPropertyDescriptor ( bean , name ) ; if ( descriptor == null ) { throw new NoSuchMethodException ( "Unknown property '" + name + "'" ) ; } Method writeMethod = descriptor . getWriteMethod ( ) ; if ( writeMethod == null ) { throw new NoSuchMethodException ( "Property '" + name + "' has no setter method" ) ; } Object values [ ] = new Object [ 1 ] ; values [ 0 ] = value ; invokeMethod ( writeMethod , bean , values ) ; }
Set the value of the specified simple property of the specified bean with no type conversions .
2,552
private static Object invokeMethod ( Method method , Object bean , Object [ ] values ) throws IllegalAccessException , InvocationTargetException { try { return method . invoke ( bean , values ) ; } catch ( IllegalArgumentException e ) { LOGGER . error ( "Method invocation failed." , e ) ; throw new IllegalArgumentException ( "Cannot invoke " + method . getDeclaringClass ( ) . getName ( ) + "." + method . getName ( ) + " - " + e . getMessage ( ) ) ; } }
This utility method just catches and wraps IllegalArgumentException .
2,553
private boolean isSearchingForVariantInPostProcessNeeded ( ) { boolean needToSearch = false ; ResourceBundlePostProcessor [ ] postprocessors = new ResourceBundlePostProcessor [ ] { postProcessor , unitaryCompositePostProcessor , compositePostProcessor , unitaryCompositePostProcessor } ; for ( ResourceBundlePostProcessor resourceBundlePostProcessor : postprocessors ) { if ( resourceBundlePostProcessor != null && ( ( AbstractChainedResourceBundlePostProcessor ) resourceBundlePostProcessor ) . isVariantPostProcessor ( ) ) { needToSearch = true ; break ; } } return needToSearch ; }
Checks if it is needed to search for variant in post process
2,554
private void splitBundlesByType ( List < JoinableResourceBundle > bundles ) { List < JoinableResourceBundle > tmpGlobal = new ArrayList < > ( ) ; List < JoinableResourceBundle > tmpContext = new ArrayList < > ( ) ; for ( JoinableResourceBundle bundle : bundles ) { if ( bundle . getInclusionPattern ( ) . isGlobal ( ) ) { tmpGlobal . add ( bundle ) ; } else { tmpContext . add ( bundle ) ; } } Collections . sort ( tmpGlobal , new GlobalResourceBundleComparator ( ) ) ; globalBundles = new CopyOnWriteArrayList < > ( ) ; globalBundles . addAll ( tmpGlobal ) ; contextBundles = new CopyOnWriteArrayList < > ( ) ; contextBundles . addAll ( tmpContext ) ; initBundlePrefixes ( ) ; initCompositeBundleMap ( globalBundles ) ; initCompositeBundleMap ( contextBundles ) ; }
Splits the bundles in two lists one for global lists and other for the remaining bundles .
2,555
protected void initBundlePrefixes ( ) { bundlePrefixes = new CopyOnWriteArrayList < > ( ) ; for ( JoinableResourceBundle bundle : globalBundles ) { if ( StringUtils . isNotEmpty ( bundle . getBundlePrefix ( ) ) ) { bundlePrefixes . add ( bundle . getBundlePrefix ( ) ) ; } } for ( JoinableResourceBundle bundle : contextBundles ) { if ( StringUtils . isNotEmpty ( bundle . getBundlePrefix ( ) ) ) { bundlePrefixes . add ( bundle . getBundlePrefix ( ) ) ; } } }
Initialize the bundle prefixes
2,556
private ResourceBundlePathsIterator getBundleIterator ( DebugMode debugMode , List < JoinableResourceBundle > bundles , ConditionalCommentCallbackHandler commentCallbackHandler , Map < String , String > variants ) { ResourceBundlePathsIterator bundlesIterator ; if ( debugMode . equals ( DebugMode . DEBUG ) ) { bundlesIterator = new DebugModePathsIteratorImpl ( bundles , commentCallbackHandler , variants ) ; } else if ( debugMode . equals ( DebugMode . FORCE_NON_DEBUG_IN_IE ) ) { bundlesIterator = new IECssDebugPathsIteratorImpl ( bundles , commentCallbackHandler , variants ) ; } else { bundlesIterator = new PathsIteratorImpl ( bundles , commentCallbackHandler , variants ) ; } return bundlesIterator ; }
Returns the bundle iterator
2,557
private StringReader processInLive ( Reader reader ) throws IOException { String requestURL = ThreadLocalJawrContext . getRequestURL ( ) ; StringWriter swriter = new StringWriter ( ) ; IOUtils . copy ( reader , swriter , true ) ; String updatedContent = swriter . getBuffer ( ) . toString ( ) ; if ( requestURL != null ) { updatedContent = updatedContent . replaceAll ( JawrConstant . JAWR_BUNDLE_PATH_PLACEHOLDER_PATTERN , requestURL ) ; } return new StringReader ( updatedContent ) ; }
Process the bundle content in live
2,558
protected String getJawrConfigHashcode ( ) { try { return CheckSumUtils . getMD5Checksum ( config . getConfigProperties ( ) . toString ( ) ) ; } catch ( IOException e ) { throw new BundlingProcessException ( "Unable to calculate Jawr config checksum" , e ) ; } }
Returns the jawr config hashcode
2,559
private void executeGlobalPreprocessing ( List < JoinableResourceBundle > bundlesToBuild , boolean processBundleFlag , StopWatch stopWatch ) { stopProcessIfNeeded ( ) ; if ( resourceTypePreprocessor != null ) { if ( stopWatch != null ) { stopWatch . start ( "Global preprocessing" ) ; } GlobalPreprocessingContext ctx = new GlobalPreprocessingContext ( config , resourceHandler , processBundleFlag ) ; resourceTypePreprocessor . processBundles ( ctx , bundles ) ; List < JoinableResourceBundle > currentBundles = getBundlesToRebuild ( ) ; for ( JoinableResourceBundle b : currentBundles ) { if ( ! bundlesToBuild . contains ( b ) ) { bundlesToBuild . add ( b ) ; } } if ( stopWatch != null ) { stopWatch . stop ( ) ; } } }
Executes the global preprocessing
2,560
public synchronized void rebuildModifiedBundles ( ) { stopProcessIfNeeded ( ) ; StopWatch stopWatch = ThreadLocalJawrContext . getStopWatch ( ) ; if ( config . getUseSmartBundling ( ) ) { if ( watcher != null ) { while ( ! watcher . hasNoEventToProcess ( ) ) { try { if ( LOGGER . isInfoEnabled ( ) ) { LOGGER . info ( "Wait until there is no more watch event to process" ) ; } Thread . sleep ( config . getSmartBundlingDelayAfterLastEvent ( ) ) ; } catch ( InterruptedException e ) { } } } List < JoinableResourceBundle > bundlesToRebuild = getBundlesToRebuild ( ) ; for ( JoinableResourceBundle bundle : bundlesToRebuild ) { bundle . resetBundleMapping ( ) ; } build ( bundlesToRebuild , true , stopWatch ) ; } else { LOGGER . warn ( "You should turn on \"smart bundling\" feature to be able to rebuild modified bundles." ) ; } }
Rebuilds the bundles given in parameter
2,561
public void build ( List < JoinableResourceBundle > bundlesToBuild , boolean forceWriteBundleMapping , StopWatch stopWatch ) { stopProcessIfNeeded ( ) ; if ( LOGGER . isInfoEnabled ( ) ) { LOGGER . info ( "Starting bundle processing" ) ; } notifyStartBundlingProcess ( ) ; boolean mappingFileExists = resourceBundleHandler . isExistingMappingFile ( ) ; boolean processBundleFlag = ! config . getUseBundleMapping ( ) || ! mappingFileExists ; executeGlobalPreprocessing ( bundlesToBuild , processBundleFlag , stopWatch ) ; for ( JoinableResourceBundle bundle : bundlesToBuild ) { stopProcessIfNeeded ( ) ; if ( stopWatch != null ) { stopWatch . start ( "Processing bundle '" + bundle . getName ( ) + "'" ) ; } if ( ! ThreadLocalJawrContext . isBundleProcessingAtBuildTime ( ) && null != bundle . getAlternateProductionURL ( ) ) { if ( LOGGER . isDebugEnabled ( ) ) { LOGGER . debug ( "No bundle generated for '" + bundle . getId ( ) + "' because a production URL is defined for this bundle." ) ; } } if ( bundle instanceof CompositeResourceBundle ) { joinAndStoreCompositeResourcebundle ( ( CompositeResourceBundle ) bundle ) ; } else { joinAndStoreBundle ( bundle ) ; } if ( config . getUseBundleMapping ( ) ) { JoinableResourceBundlePropertySerializer . serializeInProperties ( bundle , resourceBundleHandler . getResourceType ( ) , bundleMapping ) ; } bundle . setDirty ( false ) ; if ( stopWatch != null ) { stopWatch . stop ( ) ; } } executeGlobalPostProcessing ( processBundleFlag , stopWatch ) ; storeJawrBundleMapping ( resourceBundleHandler . isExistingMappingFile ( ) , true ) ; try { if ( watcher != null ) { watcher . initPathToResourceBundleMap ( bundlesToBuild ) ; } } catch ( IOException e ) { throw new BundlingProcessException ( e ) ; } notifyEndBundlingProcess ( ) ; if ( LOGGER . isInfoEnabled ( ) ) { LOGGER . info ( "End of bundle processing" ) ; } }
Builds the bundles given in parameter
2,562
private void storeJawrBundleMapping ( boolean mappingFileExists , boolean force ) { if ( config . getUseBundleMapping ( ) && ( ! mappingFileExists || force ) ) { bundleMapping . setProperty ( JawrConstant . JAWR_CONFIG_HASHCODE , getJawrConfigHashcode ( ) ) ; resourceBundleHandler . storeJawrBundleMapping ( bundleMapping ) ; if ( resourceBundleHandler . getResourceType ( ) . equals ( JawrConstant . CSS_TYPE ) ) { BinaryResourcesHandler binaryRsHandler = ( BinaryResourcesHandler ) config . getContext ( ) . getAttribute ( JawrConstant . BINARY_CONTEXT_ATTRIBUTE ) ; if ( binaryRsHandler != null ) { JawrConfig binaryJawrConfig = binaryRsHandler . getConfig ( ) ; String jawrWorkingDirectory = binaryJawrConfig . getJawrWorkingDirectory ( ) ; if ( binaryJawrConfig . getUseBundleMapping ( ) && ( jawrWorkingDirectory == null || ! jawrWorkingDirectory . startsWith ( JawrConstant . URL_SEPARATOR ) ) ) { Properties props = new Properties ( ) ; props . putAll ( binaryRsHandler . getBinaryPathMap ( ) ) ; props . setProperty ( JawrConstant . JAWR_CONFIG_HASHCODE , Integer . toString ( binaryJawrConfig . getConfigProperties ( ) . hashCode ( ) ) ) ; binaryRsHandler . getRsBundleHandler ( ) . storeJawrBundleMapping ( props ) ; } } } } }
Stores the Jawr bundle mapping
2,563
private void executeGlobalPostProcessing ( boolean processBundleFlag , StopWatch stopWatch ) { if ( resourceTypePostprocessor != null ) { if ( stopWatch != null ) { stopWatch . start ( "Global postprocessing" ) ; } GlobalPostProcessingContext ctx = new GlobalPostProcessingContext ( config , this , resourceHandler , processBundleFlag ) ; resourceTypePostprocessor . processBundles ( ctx , this . bundles ) ; if ( stopWatch != null ) { stopWatch . stop ( ) ; } } }
Execute the global post processing
2,564
private void joinAndStoreCompositeResourcebundle ( CompositeResourceBundle composite ) { stopProcessIfNeeded ( ) ; BundleProcessingStatus status = new BundleProcessingStatus ( BundleProcessingStatus . FILE_PROCESSING_TYPE , composite , resourceHandler , config ) ; Map < String , VariantSet > compositeBundleVariants = new HashMap < > ( ) ; for ( JoinableResourceBundle childbundle : composite . getChildBundles ( ) ) { if ( childbundle . getVariants ( ) != null ) compositeBundleVariants = VariantUtils . concatVariants ( compositeBundleVariants , childbundle . getVariants ( ) ) ; } composite . setVariants ( compositeBundleVariants ) ; if ( needToSearchForVariantInPostProcess || hasVariantPostProcessor ( composite ) ) { status . setSearchingPostProcessorVariants ( true ) ; joinAndPostProcessBundle ( composite , status ) ; Map < String , VariantSet > postProcessVariants = status . getPostProcessVariants ( ) ; if ( ! postProcessVariants . isEmpty ( ) ) { if ( LOGGER . isDebugEnabled ( ) ) { LOGGER . debug ( "Post process variants found for bundle " + composite . getId ( ) + ":" + postProcessVariants ) ; } Map < String , VariantSet > newVariants = VariantUtils . concatVariants ( composite . getVariants ( ) , postProcessVariants ) ; composite . setVariants ( newVariants ) ; status . setSearchingPostProcessorVariants ( false ) ; joinAndPostProcessBundle ( composite , status ) ; } } else { status . setSearchingPostProcessorVariants ( false ) ; joinAndPostProcessBundle ( composite , status ) ; } }
Joins the members of a composite bundle in all its variants storing in a separate file for each variant .
2,565
private boolean hasVariantPostProcessor ( JoinableResourceBundle bundle ) { boolean hasVariantPostProcessor = false ; ResourceBundlePostProcessor bundlePostProcessor = bundle . getBundlePostProcessor ( ) ; if ( bundlePostProcessor != null && ( ( AbstractChainedResourceBundlePostProcessor ) bundlePostProcessor ) . isVariantPostProcessor ( ) ) { hasVariantPostProcessor = true ; } else { bundlePostProcessor = bundle . getUnitaryPostProcessor ( ) ; if ( bundlePostProcessor != null && ( ( AbstractChainedResourceBundlePostProcessor ) bundlePostProcessor ) . isVariantPostProcessor ( ) ) { hasVariantPostProcessor = true ; } } return hasVariantPostProcessor ; }
Checks if the bundle has variant post processor
2,566
private void joinAndPostProcessBundle ( CompositeResourceBundle composite , BundleProcessingStatus status ) { JoinableResourceBundleContent store ; stopProcessIfNeeded ( ) ; List < Map < String , String > > allVariants = VariantUtils . getAllVariants ( composite . getVariants ( ) ) ; allVariants . add ( null ) ; for ( Map < String , String > variants : allVariants ) { status . setBundleVariants ( variants ) ; store = new JoinableResourceBundleContent ( ) ; for ( JoinableResourceBundle childbundle : composite . getChildBundles ( ) ) { if ( ! childbundle . getInclusionPattern ( ) . isIncludeOnlyOnDebug ( ) ) { JoinableResourceBundleContent childContent = joinAndPostprocessBundle ( childbundle , variants , status ) ; status . setProcessingType ( BundleProcessingStatus . FILE_PROCESSING_TYPE ) ; StringBuffer content = executeUnitaryPostProcessing ( composite , status , childContent . getContent ( ) , this . unitaryCompositePostProcessor ) ; childContent . setContent ( content ) ; store . append ( childContent ) ; } } store = postProcessJoinedCompositeBundle ( composite , store . getContent ( ) , status ) ; String variantKey = VariantUtils . getVariantKey ( variants ) ; String name = VariantUtils . getVariantBundleName ( composite . getId ( ) , variantKey , false ) ; storeBundle ( name , store ) ; initBundleDataHashcode ( composite , store , variantKey ) ; } }
Joins and post process the variant composite bundle
2,567
private JoinableResourceBundleContent postProcessJoinedCompositeBundle ( CompositeResourceBundle composite , StringBuffer content , BundleProcessingStatus status ) { JoinableResourceBundleContent store = new JoinableResourceBundleContent ( ) ; StringBuffer processedContent = null ; status . setProcessingType ( BundleProcessingStatus . BUNDLE_PROCESSING_TYPE ) ; ResourceBundlePostProcessor bundlePostProcessor = composite . getBundlePostProcessor ( ) ; if ( null != bundlePostProcessor ) { processedContent = bundlePostProcessor . postProcessBundle ( status , content ) ; } else if ( null != this . compositePostProcessor ) { processedContent = this . compositePostProcessor . postProcessBundle ( status , content ) ; } else { processedContent = content ; } store . setContent ( processedContent ) ; return store ; }
Postprocess the composite bundle only if a composite bundle post processor is defined
2,568
private void initBundleDataHashcode ( JoinableResourceBundle bundle , JoinableResourceBundleContent store , String variant ) { String bundleHashcode = bundleHashcodeGenerator . generateHashCode ( config , store . getContent ( ) . toString ( ) ) ; bundle . setBundleDataHashCode ( variant , bundleHashcode ) ; }
Initialize the bundle data hashcode and initialize the bundle mapping if needed
2,569
private void joinAndStoreBundle ( JoinableResourceBundle bundle ) { BundleProcessingStatus status = new BundleProcessingStatus ( BundleProcessingStatus . FILE_PROCESSING_TYPE , bundle , resourceHandler , config ) ; JoinableResourceBundleContent store = null ; if ( needToSearchForVariantInPostProcess || hasVariantPostProcessor ( bundle ) ) { status . setSearchingPostProcessorVariants ( true ) ; joinAndPostProcessBundle ( bundle , status ) ; status . setSearchingPostProcessorVariants ( false ) ; Map < String , VariantSet > postProcessVariants = status . getPostProcessVariants ( ) ; if ( ! postProcessVariants . isEmpty ( ) ) { if ( LOGGER . isDebugEnabled ( ) ) { LOGGER . debug ( "Post process variants found for bundle " + bundle . getId ( ) + ":" + postProcessVariants ) ; } Map < String , VariantSet > newVariants = VariantUtils . concatVariants ( bundle . getVariants ( ) , postProcessVariants ) ; bundle . setVariants ( newVariants ) ; joinAndPostProcessBundle ( bundle , status ) ; } } else { status . setSearchingPostProcessorVariants ( false ) ; joinAndPostProcessBundle ( bundle , status ) ; } store = joinAndPostprocessBundle ( bundle , null , status ) ; storeBundle ( bundle . getId ( ) , store ) ; initBundleDataHashcode ( bundle , store , null ) ; }
Joins the members of a bundle and stores it
2,570
private void storeBundle ( String bundleId , JoinableResourceBundleContent store ) { stopProcessIfNeeded ( ) ; if ( bundleMustBeProcessedInLive ( store . getContent ( ) . toString ( ) ) ) { liveProcessBundles . add ( bundleId ) ; } resourceBundleHandler . storeBundle ( bundleId , store ) ; }
Store the bundle
2,571
private void joinAndPostProcessBundle ( JoinableResourceBundle bundle , BundleProcessingStatus status ) { JoinableResourceBundleContent store ; List < Map < String , String > > allVariants = VariantUtils . getAllVariants ( bundle . getVariants ( ) ) ; allVariants . add ( null ) ; for ( Map < String , String > variantMap : allVariants ) { status . setBundleVariants ( variantMap ) ; String variantKey = VariantUtils . getVariantKey ( variantMap ) ; String name = VariantUtils . getVariantBundleName ( bundle . getId ( ) , variantKey , false ) ; store = joinAndPostprocessBundle ( bundle , variantMap , status ) ; storeBundle ( name , store ) ; initBundleDataHashcode ( bundle , store , variantKey ) ; } }
Join and post process the bundle taking in account all its variants .
2,572
private JoinableResourceBundleContent joinAndPostprocessBundle ( JoinableResourceBundle bundle , Map < String , String > variants , BundleProcessingStatus status ) { JoinableResourceBundleContent bundleContent = new JoinableResourceBundleContent ( ) ; StringBuffer bundleData = new StringBuffer ( ) ; StringBuffer store = null ; try { boolean firstPath = true ; Iterator < BundlePath > pathIterator = null ; if ( bundle . getInclusionPattern ( ) . isIncludeOnlyOnDebug ( ) ) { pathIterator = bundle . getItemDebugPathList ( variants ) . iterator ( ) ; } else { pathIterator = bundle . getItemPathList ( variants ) . iterator ( ) ; } for ( Iterator < BundlePath > it = pathIterator ; it . hasNext ( ) ; ) { StringWriter writer = new StringWriter ( ) ; BufferedWriter bwriter = new BufferedWriter ( writer ) ; String path = ( String ) it . next ( ) . getPath ( ) ; if ( LOGGER . isDebugEnabled ( ) ) LOGGER . debug ( "Adding file [" + path + "] to bundle " + bundle . getId ( ) ) ; Reader rd = null ; try { rd = resourceHandler . getResource ( bundle , path , true ) ; } catch ( ResourceNotFoundException e ) { LOGGER . warn ( "A mapped resource was not found: [" + path + "]. Please check your configuration" ) ; continue ; } status . setLastPathAdded ( path ) ; rd = new UnicodeBOMReader ( rd , config . getResourceCharset ( ) ) ; if ( ! firstPath && ( ( UnicodeBOMReader ) rd ) . hasBOM ( ) ) { ( ( UnicodeBOMReader ) rd ) . skipBOM ( ) ; } else { firstPath = false ; } IOUtils . copy ( rd , bwriter , true ) ; StringBuffer buffer = writer . getBuffer ( ) ; if ( ! buffer . toString ( ) . endsWith ( StringUtils . STR_LINE_FEED ) ) { buffer . append ( StringUtils . STR_LINE_FEED ) ; } status . setProcessingType ( BundleProcessingStatus . FILE_PROCESSING_TYPE ) ; bundleData . append ( executeUnitaryPostProcessing ( bundle , status , buffer , this . unitaryPostProcessor ) ) ; } store = executeBundlePostProcessing ( bundle , status , bundleData ) ; } catch ( IOException e ) { throw new BundlingProcessException ( "Unexpected IOException generating collected file [" + bundle . getId ( ) + "]." , e ) ; } bundleContent . setContent ( store ) ; return bundleContent ; }
Reads all the members of a bundle and executes all associated postprocessors .
2,573
private StringBuffer executeUnitaryPostProcessing ( JoinableResourceBundle bundle , BundleProcessingStatus status , StringBuffer content , ResourceBundlePostProcessor defaultPostProcessor ) { StringBuffer bundleData = new StringBuffer ( ) ; status . setProcessingType ( BundleProcessingStatus . FILE_PROCESSING_TYPE ) ; if ( null != bundle . getUnitaryPostProcessor ( ) ) { StringBuffer resourceData = bundle . getUnitaryPostProcessor ( ) . postProcessBundle ( status , content ) ; bundleData . append ( resourceData ) ; } else if ( null != defaultPostProcessor ) { if ( LOGGER . isDebugEnabled ( ) ) LOGGER . debug ( "POSTPROCESSING UNIT:" + status . getLastPathAdded ( ) ) ; StringBuffer resourceData = defaultPostProcessor . postProcessBundle ( status , content ) ; bundleData . append ( resourceData ) ; } else { bundleData = content ; } return bundleData ; }
Executes the unitary resource post processing
2,574
private StringBuffer executeBundlePostProcessing ( JoinableResourceBundle bundle , BundleProcessingStatus status , StringBuffer bundleData ) { StringBuffer store ; status . setProcessingType ( BundleProcessingStatus . BUNDLE_PROCESSING_TYPE ) ; status . setLastPathAdded ( bundle . getId ( ) ) ; if ( null != bundle . getBundlePostProcessor ( ) ) store = bundle . getBundlePostProcessor ( ) . postProcessBundle ( status , bundleData ) ; else if ( null != this . postProcessor ) store = this . postProcessor . postProcessBundle ( status , bundleData ) ; else store = bundleData ; return store ; }
Execute the bundle post processing
2,575
private Container getContainer ( final GeneratorContext context ) { List < Container > containers = StartupUtil . getAllPublishedContainers ( context . getServletContext ( ) ) ; for ( Container container : containers ) { return container ; } throw new RuntimeException ( "FATAL: unable to find DWR Container!" ) ; }
Get the DWR Container . If multiple DWR containers exist in the ServletContext the first found is returned .
2,576
private String getInterfaceScript ( String scriptName , final GeneratorContext context ) throws IOException { Container container = getContainer ( context ) ; CreatorManager ctManager = ( CreatorManager ) container . getBean ( CreatorManager . class . getName ( ) ) ; if ( ctManager . getCreator ( scriptName , false ) != null ) { InterfaceHandler handler = ( InterfaceHandler ) ContainerUtil . getHandlerForUrlProperty ( container , INTERFACE_HANDLER_URL ) ; return handler . generateInterfaceScript ( context . getServletContext ( ) . getContextPath ( ) , context . getConfig ( ) . getDwrMapping ( ) , scriptName ) ; } else throw new IllegalArgumentException ( "The DWR bean named '" + scriptName + "' was not found in any DWR configuration instance." ) ; }
Get a specific interface script
2,577
private String getAllPublishedInterfaces ( final GeneratorContext context ) throws IOException { StringBuilder sb = new StringBuilder ( ) ; Container container = getContainer ( context ) ; CreatorManager ctManager = ( CreatorManager ) container . getBean ( CreatorManager . class . getName ( ) ) ; if ( null != ctManager ) { Collection < String > creators ; if ( ctManager instanceof DefaultCreatorManager ) { DefaultCreatorManager creatorManager = ( DefaultCreatorManager ) ctManager ; boolean currentDebugValue = creatorManager . isDebug ( ) ; creatorManager . setDebug ( true ) ; creators = ctManager . getCreatorNames ( false ) ; creatorManager . setDebug ( currentDebugValue ) ; } else { log . warn ( "Getting creator names from an unknown CreatorManager. This may fail ..." ) ; creators = ctManager . getCreatorNames ( false ) ; } List < String > creatorList = new ArrayList < > ( creators ) ; Collections . sort ( creatorList ) ; for ( String name : creatorList ) { if ( log . isDebugEnabled ( ) ) log . debug ( "_** mapping: generating found interface named: " + name ) ; InterfaceHandler handler = ( InterfaceHandler ) ContainerUtil . getHandlerForUrlProperty ( container , INTERFACE_HANDLER_URL ) ; sb . append ( handler . generateInterfaceScript ( context . getServletContext ( ) . getContextPath ( ) , context . getConfig ( ) . getDwrMapping ( ) , name ) ) ; } } return sb . toString ( ) ; }
Get all interfaces in one script
2,578
protected String compile ( JoinableResourceBundle bundle , String content , String path , GeneratorContext context ) { try { JawrScssResolver scssResolver = new JawrScssResolver ( bundle , rsHandler ) ; JawrScssStylesheet sheet = new JawrScssStylesheet ( bundle , content , path , scssResolver , context . getCharset ( ) ) ; sheet . compile ( urlMode ) ; String parsedScss = sheet . printState ( ) ; addLinkedResources ( path , context , scssResolver . getLinkedResources ( ) ) ; return parsedScss ; } catch ( Exception e ) { throw new BundlingProcessException ( "Unable to generate content for resource path : '" + path + "'" , e ) ; } }
Compile the SASS source to a CSS source
2,579
protected Reader generateResourceForDebug ( Reader rd , GeneratorContext context ) { StringWriter writer = new StringWriter ( ) ; try { IOUtils . copy ( rd , writer ) ; String content = rewriteUrl ( context , writer . toString ( ) ) ; rd = new StringReader ( content ) ; } catch ( IOException e ) { throw new BundlingProcessException ( e ) ; } return rd ; }
Returns the resource in debug mode . Here an extra step is used to rewrite the URL in debug mode
2,580
protected String rewriteUrl ( GeneratorContext context , String content ) throws IOException { JawrConfig jawrConfig = context . getConfig ( ) ; CssImageUrlRewriter rewriter = new CssImageUrlRewriter ( jawrConfig ) ; String bundlePath = PathNormalizer . joinPaths ( jawrConfig . getServletMapping ( ) , ResourceGenerator . CSS_DEBUGPATH ) ; StringBuffer result = rewriter . rewriteUrl ( context . getPath ( ) , bundlePath , content ) ; return result . toString ( ) ; }
Rewrite the URL for debug mode
2,581
private String getBinaryServletMapping ( ) { String binaryServletMapping = null ; BinaryResourcesHandler binaryRsHandler = ( BinaryResourcesHandler ) config . getContext ( ) . getAttribute ( JawrConstant . BINARY_CONTEXT_ATTRIBUTE ) ; if ( binaryRsHandler != null ) { binaryServletMapping = binaryRsHandler . getConfig ( ) . getServletMapping ( ) ; } return binaryServletMapping ; }
Retrieves the binary servlet mapping
2,582
public String [ ] getBaseNames ( boolean warDeployed ) { String [ ] names = configParam . split ( GrailsLocaleUtils . RESOURCE_BUNDLE_SEPARATOR ) ; List < String > baseNames = new ArrayList < String > ( ) ; for ( String baseName : names ) { boolean isPluginResoucePath = GrailsLocaleUtils . isPluginResoucePath ( baseName ) ; if ( warDeployed ) { if ( isPluginResoucePath ) { baseName = WEB_INF_DIR + rsReader . getRealResourcePath ( baseName ) ; } else { baseName = PROPERTIES_DIR + baseName . substring ( baseName . lastIndexOf ( '.' ) + 1 ) ; } } else { if ( isPluginResoucePath ) { baseName = URI_ABSOLUTE_FILE_PREFIX + rsReader . getRealResourcePath ( baseName ) ; } else { baseName = URI_RELATIVE_FILE_PREFIX + baseName . replaceAll ( REGEX_DOT_CHARACTER , JawrConstant . URL_SEPARATOR ) ; } } baseNames . add ( baseName ) ; } return baseNames . toArray ( new String [ ] { } ) ; }
Returns the basenames
2,583
protected AbstractChainedGlobalProcessor < GlobalPostProcessingContext > buildProcessorByKey ( String key ) { AbstractChainedGlobalProcessor < GlobalPostProcessingContext > processor = null ; if ( key . equals ( JawrConstant . GLOBAL_GOOGLE_CLOSURE_POSTPROCESSOR_ID ) ) { processor = new ClosureGlobalPostProcessor ( ) ; } return processor ; }
Build the global preprocessor from the ID given in parameter
2,584
private void updateBundlesDirtyState ( List < JoinableResourceBundle > bundles , CssSmartSpritesResourceReader cssSpriteResourceReader ) { for ( JoinableResourceBundle bundle : bundles ) { List < BundlePath > bundlePaths = bundle . getItemPathList ( ) ; for ( BundlePath bundlePath : bundlePaths ) { String path = bundlePath . getPath ( ) ; File stdFile = cssSpriteResourceReader . getGeneratedCssFile ( path ) ; File bckFile = cssSpriteResourceReader . getBackupFile ( path ) ; if ( bckFile . exists ( ) ) { try { if ( ! FileUtils . contentEquals ( stdFile , bckFile ) ) { bundle . setDirty ( true ) ; break ; } } catch ( IOException e ) { throw new BundlingProcessException ( "Issue while generating smartsprite bundle" , e ) ; } } cssSpriteResourceReader . getResource ( bundle , path ) ; } } }
Update the bundles dirty state
2,585
private void generateSprites ( ResourceReaderHandler cssRsHandler , BinaryResourcesHandler binaryRsHandler , Set < String > resourcePaths , JawrConfig jawrConfig , Charset charset ) { MessageLevel msgLevel = MessageLevel . valueOf ( ERROR_LEVEL ) ; String sinkLevel = WARN_LEVEL ; if ( LOGGER . isTraceEnabled ( ) || LOGGER . isDebugEnabled ( ) || LOGGER . isInfoEnabled ( ) ) { msgLevel = MessageLevel . valueOf ( INFO_LEVEL ) ; sinkLevel = INFO_LEVEL ; } else if ( LOGGER . isWarnEnabled ( ) || LOGGER . isErrorEnabled ( ) ) { msgLevel = MessageLevel . valueOf ( WARN_LEVEL ) ; sinkLevel = WARN_LEVEL ; } MessageLog messageLog = new MessageLog ( new MessageSink [ ] { new LogMessageSink ( sinkLevel ) } ) ; SmartSpritesResourceHandler smartSpriteRsHandler = new SmartSpritesResourceHandler ( cssRsHandler , binaryRsHandler . getRsReaderHandler ( ) , jawrConfig . getGeneratorRegistry ( ) , binaryRsHandler . getConfig ( ) . getGeneratorRegistry ( ) , charset . toString ( ) , messageLog ) ; smartSpriteRsHandler . setContextPath ( jawrConfig . getProperty ( JawrConstant . JAWR_CSS_URL_REWRITER_CONTEXT_PATH ) ) ; String outDir = cssRsHandler . getWorkingDirectory ( ) + JawrConstant . CSS_SMARTSPRITES_TMP_DIR ; File tmpDir = new File ( outDir ) ; if ( ! tmpDir . exists ( ) ) { if ( ! tmpDir . mkdirs ( ) ) { throw new BundlingProcessException ( "Impossible to create temporary directory : " + tmpDir ) ; } } else { try { File backupDir = new File ( cssRsHandler . getWorkingDirectory ( ) + JawrConstant . SPRITE_BACKUP_GENERATED_CSS_DIR ) ; if ( ! backupDir . exists ( ) ) { if ( ! backupDir . mkdirs ( ) ) { throw new BundlingProcessException ( "Impossible to create temporary directory : " + backupDir ) ; } } FileUtils . copyDirectory ( tmpDir , backupDir ) ; FileUtils . cleanDirectory ( tmpDir ) ; } catch ( IOException e ) { throw new BundlingProcessException ( "Impossible to clean temporary directory : " + outDir , e ) ; } } SmartSpritesParameters params = new SmartSpritesParameters ( "/" , null , outDir , null , msgLevel , "" , PngDepth . valueOf ( "AUTO" ) , false , charset . toString ( ) , true ) ; SpriteBuilder spriteBuilder = new SpriteBuilder ( params , messageLog , smartSpriteRsHandler ) ; try { spriteBuilder . buildSprites ( resourcePaths ) ; } catch ( IOException e ) { throw new BundlingProcessException ( "Unable to build sprites" , e ) ; } }
Generates the image sprites from the smartsprites annotation in the CSS rewrite the CSS files to references the generated sprites .
2,586
private Set < String > getResourcePaths ( List < JoinableResourceBundle > bundles ) { Set < String > resourcePaths = new HashSet < > ( ) ; for ( JoinableResourceBundle bundle : bundles ) { for ( BundlePath bundlePath : bundle . getItemPathList ( ) ) { resourcePaths . add ( bundlePath . getPath ( ) ) ; } } return resourcePaths ; }
Returns the list of all CSS files defined in the bundles .
2,587
private static List < Map < String , String > > getVariants ( Map < String , String > curVariant , String variantType , Collection < String > variantList ) { List < Map < String , String > > variants = new ArrayList < > ( ) ; for ( String variant : variantList ) { Map < String , String > map = new HashMap < > ( ) ; if ( curVariant != null ) { map . putAll ( curVariant ) ; } map . put ( variantType , variant ) ; variants . add ( map ) ; } return variants ; }
Returns the list of variant maps which are initialized with the current map values and each element of the list contains an element of the variant list with the variant type as key
2,588
private static List < String > getVariantKeys ( String variantKeyPrefix , Collection < String > variants ) { List < String > variantKeys = new ArrayList < > ( ) ; for ( String variant : variants ) { if ( variant == null ) { variant = "" ; } if ( variantKeyPrefix == null ) { variantKeys . add ( variant ) ; } else { variantKeys . add ( variantKeyPrefix + variant ) ; } } return variantKeys ; }
Returns the variant keys
2,589
public static String getVariantKey ( Map < String , String > variants ) { String variantKey = "" ; if ( variants != null ) { variantKey = getVariantKey ( variants , variants . keySet ( ) ) ; } return variantKey ; }
Returns the variant key from the variants given in parameter
2,590
public static String getVariantKey ( Map < String , String > curVariants , Set < String > variantTypes ) { String variantKey = "" ; if ( curVariants != null && variantTypes != null ) { Map < String , String > tempVariants = new TreeMap < > ( curVariants ) ; StringBuilder variantKeyBuf = new StringBuilder ( ) ; for ( Entry < String , String > entry : tempVariants . entrySet ( ) ) { if ( variantTypes . contains ( entry . getKey ( ) ) ) { String value = entry . getValue ( ) ; if ( value == null ) { value = "" ; } variantKeyBuf . append ( value + JawrConstant . VARIANT_SEPARATOR_CHAR ) ; } } variantKey = variantKeyBuf . toString ( ) ; if ( StringUtils . isNotEmpty ( variantKey ) && variantKey . charAt ( variantKey . length ( ) - 1 ) == JawrConstant . VARIANT_SEPARATOR_CHAR ) { variantKey = variantKey . substring ( 0 , variantKey . length ( ) - 1 ) ; } } return variantKey ; }
Resolves a registered path from a locale key using the same algorithm used to locate ResourceBundles .
2,591
public static String getVariantBundleName ( String bundleName , String variantKey , boolean iGeneratedResource ) { String newName = bundleName ; if ( StringUtils . isNotEmpty ( variantKey ) ) { int idxSeparator = bundleName . lastIndexOf ( '.' ) ; if ( ! iGeneratedResource && idxSeparator != - 1 ) { newName = bundleName . substring ( 0 , idxSeparator ) ; newName += JawrConstant . VARIANT_SEPARATOR_CHAR + variantKey ; newName += bundleName . substring ( idxSeparator ) ; } else { newName += JawrConstant . VARIANT_SEPARATOR_CHAR + variantKey ; } } return newName ; }
Get the bundle name taking in account the variant key
2,592
public static String getVariantBundleName ( String bundleName , Map < String , String > variants , boolean isGeneratedResource ) { String variantKey = getVariantKey ( variants ) ; return getVariantBundleName ( bundleName , variantKey , isGeneratedResource ) ; }
Returns the bundle name from the variants given in parameter
2,593
public static Map < String , VariantSet > concatVariants ( Map < String , VariantSet > variantSet1 , Map < String , VariantSet > variantSet2 ) { Map < String , VariantSet > result = new HashMap < > ( ) ; if ( ! isEmpty ( variantSet1 ) && isEmpty ( variantSet2 ) ) { result . putAll ( variantSet1 ) ; } else if ( isEmpty ( variantSet1 ) && ! isEmpty ( variantSet2 ) ) { result . putAll ( variantSet2 ) ; } else if ( ! isEmpty ( variantSet1 ) && ! isEmpty ( variantSet2 ) ) { Set < String > keySet = new HashSet < > ( ) ; keySet . addAll ( variantSet1 . keySet ( ) ) ; keySet . addAll ( variantSet2 . keySet ( ) ) ; for ( String variantType : keySet ) { VariantSet variants1 = variantSet1 . get ( variantType ) ; VariantSet variants2 = variantSet2 . get ( variantType ) ; Set < String > variants = new HashSet < > ( ) ; String defaultVariant = null ; if ( variants1 != null && variants2 != null && ! variants1 . hasSameDefaultVariant ( variants2 ) ) { throw new BundlingProcessException ( "For the variant type '" + variantType + "', the variant sets defined in your bundles don't have the same default value." ) ; } if ( variants1 != null ) { variants . addAll ( variants1 ) ; defaultVariant = variants1 . getDefaultVariant ( ) ; } if ( variants2 != null ) { variants . addAll ( variants2 ) ; defaultVariant = variants2 . getDefaultVariant ( ) ; } VariantSet variantSet = new VariantSet ( variantType , defaultVariant , variants ) ; result . put ( variantType , variantSet ) ; } } return result ; }
Concatenates 2 map of variant sets .
2,594
public void cleanDirectory ( final File directory ) throws IOException { if ( ! directory . exists ( ) ) { final String message = directory + " does not exist" ; throw new IllegalArgumentException ( message ) ; } if ( ! directory . isDirectory ( ) ) { final String message = directory + " is not a directory" ; throw new IllegalArgumentException ( message ) ; } Delete deleteTask = new Delete ( ) ; deleteTask . setProject ( getProject ( ) ) ; deleteTask . setDir ( directory ) ; deleteTask . execute ( ) ; if ( ! directory . exists ( ) ) { directory . mkdirs ( ) ; } }
Clean a directory without deleting it .
2,595
private String [ ] getClosureCompilerArgs ( GlobalPostProcessingContext ctx , List < JoinableResourceBundle > tmpBundles , Map < String , String > resultBundlePathMapping ) { List < String > args = new ArrayList < > ( ) ; JawrConfig config = ctx . getJawrConfig ( ) ; List < JoinableResourceBundle > bundles = new ArrayList < > ( tmpBundles ) ; initCompilerClosureArgumentsFromConfig ( args , config ) ; String excludedBundlesProp = config . getProperty ( JAWR_JS_CLOSURE_BUNDLES_EXCLUDED , "" ) ; List < String > excludedBundles = Arrays . asList ( excludedBundlesProp . replaceAll ( " " , "" ) . split ( MODULE_DEPENDENCIES_SEPARATOR ) ) ; Map < String , JoinableResourceBundle > bundleMap = new HashMap < > ( ) ; for ( JoinableResourceBundle bundle : bundles ) { if ( ! excludedBundles . contains ( bundle . getName ( ) ) ) { bundleMap . put ( bundle . getName ( ) , bundle ) ; } } String modules = config . getProperty ( JAWR_JS_CLOSURE_MODULES ) ; List < String > depModulesArgs = new ArrayList < > ( ) ; List < String > globalBundleDependencies = getGlobalBundleDependencies ( ctx , excludedBundles ) ; initModulesArgs ( resultBundlePathMapping , args , bundles , bundleMap , modules , depModulesArgs , globalBundleDependencies ) ; for ( JoinableResourceBundle bundle : bundles ) { if ( ! excludedBundles . contains ( bundle . getName ( ) ) ) { generateBundleModuleArgs ( args , bundleMap , resultBundlePathMapping , bundle , globalBundleDependencies ) ; } } args . addAll ( depModulesArgs ) ; if ( LOGGER . isDebugEnabled ( ) ) { StringBuilder strArg = new StringBuilder ( ) ; for ( String arg : args ) { strArg . append ( arg ) . append ( " " ) ; } LOGGER . debug ( "Closure Compiler Args : " + strArg . toString ( ) ) ; } return args . toArray ( new String [ ] { } ) ; }
Returns the closure compiler arguments
2,596
private List < String > getGlobalBundleDependencies ( GlobalPostProcessingContext ctx , List < String > excludedBundles ) { List < JoinableResourceBundle > globalBundles = getRsBundlesHandler ( ctx ) . getGlobalBundles ( ) ; List < String > globalBundleDependencies = new ArrayList < > ( ) ; for ( JoinableResourceBundle globalBundle : globalBundles ) { if ( ! excludedBundles . contains ( globalBundle . getName ( ) ) ) { globalBundleDependencies . add ( globalBundle . getName ( ) ) ; } } return globalBundleDependencies ; }
Returns the global bundle dependencies
2,597
private void initCompilerClosureArgumentsFromConfig ( List < String > args , JawrConfig config ) { Set < Entry < Object , Object > > entrySet = config . getConfigProperties ( ) . entrySet ( ) ; for ( Entry < Object , Object > propEntry : entrySet ) { String key = ( String ) propEntry . getKey ( ) ; if ( key . startsWith ( JAWR_JS_CLOSURE_PREFIX ) && ! JAWR_JS_CLOSURE_SPECIFIC_PROPERTIES . contains ( key ) ) { String compilerArgName = key . substring ( JAWR_JS_CLOSURE_PREFIX . length ( ) ) ; checkCompilerArgumentName ( compilerArgName ) ; String compilerArgValue = ( String ) propEntry . getValue ( ) ; compilerArgValue = getCompilerArgValue ( compilerArgName , compilerArgValue ) ; args . add ( CLOSURE_ARGUMENT_NAME_PREFIX + compilerArgName ) ; args . add ( propEntry . getValue ( ) . toString ( ) ) ; } } if ( ! args . contains ( COMPILATION_LEVEL_ARG ) ) { args . add ( COMPILATION_LEVEL_ARG ) ; args . add ( WHITESPACE_ONLY_COMPILATION_LEVEL ) ; } if ( ! args . contains ( WARNING_LEVEL_ARG ) ) { args . add ( WARNING_LEVEL_ARG ) ; args . add ( VERBOSE_WARNING_LEVEL ) ; } }
Initialize the closure argument from the Jawr config
2,598
private String getCompilerArgValue ( String compilerArgName , String compilerArgValue ) { if ( compilerArgName . equals ( COMPILATION_LEVEL ) ) { if ( ! ADVANCED_OPTIMIZATIONS_COMPILATION_LEVEL . equalsIgnoreCase ( compilerArgValue ) && ! WHITESPACE_ONLY_COMPILATION_LEVEL . equalsIgnoreCase ( compilerArgValue ) && ! SIMPLE_OPTIMIZATIONS_COMPILATION_LEVEL . equalsIgnoreCase ( compilerArgValue ) ) { if ( StringUtils . isNotEmpty ( compilerArgValue ) ) { LOGGER . debug ( "Closure compilation level defined in config '" + compilerArgValue + "' is not part of the available " + "ones [WHITESPACE_ONLY, SIMPLE_OPTIMIZATIONS, ADVANCED_OPTIMIZATIONS" ) ; } compilerArgValue = WHITESPACE_ONLY_COMPILATION_LEVEL ; } LOGGER . debug ( "Closure compilation level used : " + compilerArgValue ) ; } return compilerArgValue ; }
Returns the compiler argument value
2,599
private void generateBundleModuleArgs ( List < String > args , Map < String , JoinableResourceBundle > bundleMap , Map < String , String > resultBundleMapping , JoinableResourceBundle bundle , List < String > dependencies ) { Set < String > bundleDependencies = getClosureModuleDependencies ( bundle , dependencies ) ; Map < String , VariantSet > bundleVariants = bundle . getVariants ( ) ; List < Map < String , String > > variants = VariantUtils . getAllVariants ( bundleVariants ) ; if ( variants . isEmpty ( ) ) { variants . add ( null ) ; } for ( Map < String , String > variant : variants ) { String jsFile = VariantUtils . getVariantBundleName ( bundle . getId ( ) , variant , false ) ; String moduleName = VariantUtils . getVariantBundleName ( bundle . getName ( ) , variant , false ) ; resultBundleMapping . put ( moduleName , jsFile ) ; StringBuilder moduleArg = new StringBuilder ( ) ; moduleArg . append ( moduleName + ":1:" ) ; for ( String dep : bundleDependencies ) { checkBundleName ( dep , bundleMap ) ; JoinableResourceBundle dependencyBundle = bundleMap . get ( dep ) ; List < String > depVariantKeys = VariantUtils . getAllVariantKeysFromFixedVariants ( dependencyBundle . getVariants ( ) , variant ) ; for ( String depVariantKey : depVariantKeys ) { String depBundleName = VariantUtils . getVariantBundleName ( dep , depVariantKey , false ) ; moduleArg . append ( depBundleName ) ; moduleArg . append ( MODULE_DEPENDENCIES_SEPARATOR ) ; } } moduleArg . append ( JAWR_ROOT_MODULE_NAME ) ; addModuleArg ( jsFile , moduleName , args , moduleArg ) ; } }
Generates the bundle module arguments for the closure compiler