idx
int64
0
41.2k
question
stringlengths
74
4.21k
target
stringlengths
5
888
2,600
protected void addModuleArg ( String jsFile , String moduleName , List < String > args , StringBuilder moduleArg ) { int argIdx = 0 ; for ( Iterator < String > iterArg = args . iterator ( ) ; iterArg . hasNext ( ) ; argIdx ++ ) { String arg = iterArg . next ( ) ; if ( arg . equals ( JS_ARG ) ) { iterArg . next ( ) ; arg = iterArg . next ( ) ; argIdx += 2 ; } if ( arg . equals ( MODULE_ARG ) ) { arg = iterArg . next ( ) ; argIdx ++ ; Matcher matcher = MODULE_ARG_PATTERN . matcher ( arg ) ; if ( matcher . find ( ) ) { String dep = matcher . group ( 1 ) ; if ( dep != null ) { List < String > moduleDependencies = Arrays . asList ( dep . split ( MODULE_DEPENDENCIES_SEPARATOR ) ) ; if ( moduleDependencies . contains ( moduleName ) ) { break ; } } } else { throw new BundlingProcessException ( "There were an error in the generation of the module dependencies." ) ; } } } args . add ( argIdx ++ , JS_ARG ) ; args . add ( argIdx ++ , jsFile ) ; args . add ( argIdx ++ , MODULE_ARG ) ; args . add ( argIdx ++ , moduleArg . toString ( ) ) ; }
Adds the module argument taking in account the module dependencies
2,601
private Set < String > getClosureModuleDependencies ( JoinableResourceBundle bundle , List < String > dependencies ) { Set < String > bundleDependencies = new HashSet < > ( ) ; if ( bundle . getDependencies ( ) != null ) { for ( JoinableResourceBundle depBundle : bundle . getDependencies ( ) ) { bundleDependencies . add ( depBundle . getName ( ) ) ; } } for ( String depBundleName : dependencies ) { if ( bundle . getInclusionPattern ( ) . isGlobal ( ) && depBundleName . equals ( bundle . getName ( ) ) ) { break ; } else { bundleDependencies . add ( depBundleName ) ; } } return bundleDependencies ; }
Returns the module bundle dependency from the bundle dependency and the declared dependencies
2,602
private void checkBundleName ( String bundleName , Map < String , JoinableResourceBundle > bundleMap ) { if ( ! JAWR_ROOT_MODULE_NAME . equals ( bundleName ) ) { boolean moduleExist = bundleMap . get ( bundleName ) != null ; if ( ! moduleExist ) { throw new BundlingProcessException ( "The bundle name '" + bundleName + "' defined in 'jawr.js.closure.modules' is not defined in the configuration. Please check your configuration." ) ; } } }
Checks the bundle name
2,603
public static void copy ( InputStream input , Writer writer ) throws IOException { copy ( new InputStreamReader ( input ) , writer ) ; }
Writes all the contents of an InputStream to a Writer .
2,604
public static void copy ( InputStream input , OutputStream output , boolean closeStreams ) throws IOException { try { copy ( input , output ) ; } finally { if ( closeStreams ) { close ( input ) ; close ( output ) ; } } }
Writes all the contents of an InputStream to an OutputStream .
2,605
public static void write ( byte [ ] byteArray , OutputStream out ) throws IOException { if ( byteArray != null ) { out . write ( byteArray ) ; } }
Writes all the contents of a byte array to an OutputStream .
2,606
public static void copy ( ReadableByteChannel inChannel , WritableByteChannel outChannel ) throws IOException { if ( inChannel instanceof FileChannel ) { ( ( FileChannel ) inChannel ) . transferTo ( 0 , ( ( FileChannel ) inChannel ) . size ( ) , outChannel ) ; } else { final ByteBuffer buffer = ByteBuffer . allocateDirect ( 16 * 1024 ) ; try { while ( inChannel . read ( buffer ) != - 1 ) { buffer . flip ( ) ; outChannel . write ( buffer ) ; buffer . compact ( ) ; } buffer . flip ( ) ; while ( buffer . hasRemaining ( ) ) { outChannel . write ( buffer ) ; } } finally { IOUtils . close ( inChannel ) ; IOUtils . close ( outChannel ) ; } } }
Copy the readable byte channel to the writable byte channel
2,607
public String getId ( ) { StringBuilder strId = new StringBuilder ( ) ; strId . append ( id ) ; if ( nextProcessor != null ) { strId . append ( "," ) . append ( nextProcessor . getId ( ) ) ; } return strId . toString ( ) ; }
Returns the ID of the ChainedResourceBundlePostProcessor
2,608
public void addNextProcessor ( ChainedResourceBundlePostProcessor nextProcessor ) { if ( ! isVariantPostProcessor ) { isVariantPostProcessor = nextProcessor . isVariantPostProcessor ( ) ; } if ( this . nextProcessor == null ) { this . nextProcessor = nextProcessor ; } else { this . nextProcessor . addNextProcessor ( nextProcessor ) ; } }
Set the next post processor in the chain .
2,609
public static String [ ] extractBinaryResourceInfo ( String path ) { String [ ] resourceInfo = new String [ 2 ] ; String resourcePath = path ; if ( resourcePath . startsWith ( JawrConstant . URL_SEPARATOR ) ) { resourcePath = resourcePath . substring ( 1 ) ; } Matcher matcher = CACHE_BUSTER_PATTERN . matcher ( resourcePath ) ; StringBuffer result = new StringBuffer ( ) ; if ( matcher . find ( ) ) { matcher . appendReplacement ( result , StringUtils . isEmpty ( matcher . group ( GENERATED_BINARY_WEB_RESOURCE_PREFIX_INDEX ) ) ? CACHE_BUSTER_STANDARD_BINARY_WEB_RESOURCE_REPLACE_PATTERN : CACHE_BUSTER_GENERATED_BINARY_WEB_RESOURCE_REPLACE_PATTERN ) ; resourceInfo [ 0 ] = result . toString ( ) ; resourceInfo [ 1 ] = matcher . group ( 1 ) ; } else { resourceInfo [ 0 ] = path ; } return resourceInfo ; }
Returns the binary resource info from the path
2,610
public static String normalizePathMapping ( String pathMapping ) { String normalizedPathMapping = normalizePath ( pathMapping ) ; if ( normalizedPathMapping . endsWith ( "/**" ) ) normalizedPathMapping = normalizedPathMapping . substring ( 0 , normalizedPathMapping . length ( ) - 3 ) ; return normalizedPathMapping ; }
Normalizes a bundle path mapping . If it ends with a wildcard the wildcard is removed .
2,611
public static String asDirPath ( String path ) { String dirPath = path ; if ( ! path . equals ( JawrConstant . URL_SEPARATOR ) ) { dirPath = JawrConstant . URL_SEPARATOR + normalizePath ( path ) + JawrConstant . URL_SEPARATOR ; } return dirPath ; }
Normalizes a path and adds a separator at its start and its end .
2,612
public static String joinDomainToPath ( String domainName , String path ) { StringBuilder sb = new StringBuilder ( ) ; if ( domainName . endsWith ( JawrConstant . URL_SEPARATOR ) ) { sb . append ( domainName . substring ( 0 , domainName . length ( ) - 1 ) ) ; } else { sb . append ( domainName ) ; } sb . append ( JawrConstant . URL_SEPARATOR ) . append ( PathNormalizer . normalizePath ( path ) ) ; return sb . toString ( ) ; }
Normalizes a domain name and a path and joins them as a single url .
2,613
public static final Set < String > normalizePaths ( Set < String > paths ) { Set < String > ret = new HashSet < > ( ) ; for ( Iterator < String > it = paths . iterator ( ) ; it . hasNext ( ) ; ) { String path = normalizePath ( ( String ) it . next ( ) ) ; ret . add ( path ) ; } return ret ; }
Normalizes all the paths in a Set .
2,614
public static String addGetParameter ( String path , String parameterKey , String parameter ) { StringBuilder sb = new StringBuilder ( path ) ; if ( path . indexOf ( "?" ) > 0 ) { sb . append ( "&" ) ; } else { sb . append ( "?" ) ; } sb . append ( parameterKey ) . append ( "=" ) . append ( parameter ) ; return sb . toString ( ) ; }
Adds a key and value to the request path & or ? will be used as needed
2,615
public static String getParentPath ( String path ) { String parentPath = null ; if ( StringUtils . isEmpty ( path ) ) { parentPath = "" ; } else { parentPath = path ; if ( parentPath . length ( ) > 1 && parentPath . endsWith ( JawrConstant . URL_SEPARATOR ) ) { parentPath = parentPath . substring ( 0 , parentPath . length ( ) - 2 ) ; } int index = parentPath . lastIndexOf ( JawrConstant . URL_SEPARATOR ) ; if ( index > 0 ) { return parentPath . substring ( 0 , index + 1 ) ; } else { parentPath = JawrConstant . URL_SEPARATOR ; } } return parentPath ; }
Determines the parent path of a filename or a directory .
2,616
public static String getPathName ( String path ) { String pathName = null ; if ( StringUtils . isEmpty ( path ) ) { pathName = "" ; } else { pathName = path ; if ( pathName . length ( ) > 1 && pathName . endsWith ( JawrConstant . URL_SEPARATOR ) ) { pathName = pathName . substring ( 0 , pathName . length ( ) - 1 ) ; } int index = pathName . lastIndexOf ( JawrConstant . URL_SEPARATOR ) ; if ( index > 0 ) { pathName = pathName . substring ( index + 1 ) ; } else { pathName = JawrConstant . URL_SEPARATOR ; } } return pathName ; }
Determines the filename of a path .
2,617
static final String uppercaseDrive ( String path ) { String resultPath = null ; if ( path != null ) { if ( path . length ( ) >= 2 && path . charAt ( 1 ) == ':' ) { resultPath = Character . toUpperCase ( path . charAt ( 0 ) ) + path . substring ( 1 ) ; } else { resultPath = path ; } } return resultPath ; }
Cygwin prefers lowercase drive letters but other parts of maven use uppercase
2,618
public String getCommonProperty ( String key , String defaultValue ) { return props . getProperty ( PropertiesBundleConstant . PROPS_PREFIX + key , defaultValue ) ; }
Returns the value of the common property or the default value if no value is defined instead .
2,619
public String getCustomBundleProperty ( String bundleName , String key , String defaultValue ) { return props . getProperty ( prefix + PropertiesBundleConstant . BUNDLE_FACTORY_CUSTOM_PROPERTY + bundleName + key , defaultValue ) ; }
Returns the value of the custom bundle property or the default value if no value is defined
2,620
public List < String > getCustomBundlePropertyAsList ( String bundleName , String key ) { List < String > propertiesList = new ArrayList < > ( ) ; StringTokenizer tk = new StringTokenizer ( getCustomBundleProperty ( bundleName , key , "" ) , "," ) ; while ( tk . hasMoreTokens ( ) ) propertiesList . add ( tk . nextToken ( ) . trim ( ) ) ; return propertiesList ; }
Returns as a list the comma separated values of a property
2,621
public Map < String , VariantSet > getCustomBundleVariantSets ( String bundleName ) { Map < String , VariantSet > variantSets = new HashMap < > ( ) ; StringTokenizer tk = new StringTokenizer ( getCustomBundleProperty ( bundleName , PropertiesBundleConstant . BUNDLE_FACTORY_CUSTOM_VARIANTS , "" ) , ";" ) ; while ( tk . hasMoreTokens ( ) ) { String [ ] mapEntry = tk . nextToken ( ) . trim ( ) . split ( ":" ) ; String type = mapEntry [ 0 ] ; String defaultVariant = mapEntry [ 1 ] ; String values = mapEntry [ 2 ] ; String [ ] variantsArray = StringUtils . split ( values , "," ) ; List < String > variants = new ArrayList < > ( ) ; variants . addAll ( Arrays . asList ( variantsArray ) ) ; VariantSet variantSet = new VariantSet ( type , defaultVariant , variants ) ; variantSets . put ( type , variantSet ) ; } return variantSets ; }
Returns the map of variantSet for the bundle
2,622
public String getProperty ( String key , String defaultValue ) { return props . getProperty ( prefix + key , defaultValue ) ; }
Returns the value of a property or the default value if no value is defined
2,623
public Set < String > getPropertyBundleNameSet ( ) { Set < String > bundleNameSet = new HashSet < > ( ) ; for ( Object key : props . keySet ( ) ) { Matcher matcher = bundleNamePattern . matcher ( ( String ) key ) ; if ( matcher . matches ( ) ) { String id = matcher . group ( 2 ) ; bundleNameSet . add ( id ) ; } } return bundleNameSet ; }
Returns the set of names for the bundles
2,624
private Map < String , String > getCustomMap ( Pattern keyPattern ) { Map < String , String > map = new HashMap < > ( ) ; for ( Iterator < Object > it = props . keySet ( ) . iterator ( ) ; it . hasNext ( ) ; ) { String key = ( String ) it . next ( ) ; Matcher matcher = keyPattern . matcher ( key ) ; if ( matcher . matches ( ) ) { String id = matcher . group ( 2 ) ; String propertyValue = props . getProperty ( key ) ; map . put ( id , propertyValue ) ; } } return map ; }
Returns the map where the key is the 2 group of the pattern and the value is the property value
2,625
public Locale getFallbackLocale ( ) { Locale locale = null ; if ( this . fallbackToSystemLocale ) { locale = Locale . getDefault ( ) ; } else { locale = new Locale ( "" , "" ) ; } return locale ; }
Returns the fall - back locale
2,626
private void initialize ( JawrConfig config ) { StopWatch stopWatch = new StopWatch ( "Initializing JS engine for Autoprefixer" ) ; stopWatch . start ( ) ; String script = config . getProperty ( AUTOPREFIXER_SCRIPT_LOCATION , AUTOPREFIXER_SCRIPT_DEFAULT_LOCATION ) ; String jsEngineName = config . getJavascriptEngineName ( AUTOPREFIXER_JS_ENGINE ) ; jsEngine = new JavascriptEngine ( jsEngineName , true ) ; jsEngine . getBindings ( ) . put ( "logger" , LOGGER ) ; try ( InputStream inputStream = getResourceInputStream ( config , script ) ) { jsEngine . evaluate ( "autoprefixer.js" , inputStream ) ; } catch ( IOException e ) { throw new BundlingProcessException ( e ) ; } String strOptions = config . getProperty ( AUTOPREFIXER_SCRIPT_OPTIONS , AUTOPREFIXER_DEFAULT_OPTIONS ) ; this . options = jsEngine . execEval ( strOptions ) ; jsEngine . evaluate ( "initAutoPrefixer.js" , String . format ( "if(logger.isDebugEnabled()){ logger.debug('Autoprefixer config : '+autoprefixer(%s).info());}" , strOptions ) ) ; jsEngine . evaluate ( "jawrAutoPrefixerProcess.js" , "function process(cssSource, opts){\n" + "var result = autoprefixer.process.apply(autoprefixer, [cssSource, opts]);\n" + "if(result.warnings){\n" + "result.warnings().forEach(function(message){\n" + "if(logger.isWarnEnabled()){\n" + "logger.warn(message.toString());\n" + "}\n" + "});}\n" + "return result.css;\n" + "}" ) ; stopWatch . stop ( ) ; if ( PERF_LOGGER . isDebugEnabled ( ) ) { PERF_LOGGER . debug ( stopWatch . shortSummary ( ) ) ; } }
Initialize the postprocessor
2,627
private String generateContent ( GeneratorContext context , ResourceBundlesHandler bundlesHandler , String bundlePath , Map < String , String > variants ) { String cssGeneratorBundlePath = PathNormalizer . joinPaths ( context . getConfig ( ) . getServletMapping ( ) , ResourceGenerator . CSS_DEBUGPATH ) ; JoinableResourceBundle tempBundle = new JoinableResourceBundleImpl ( cssGeneratorBundlePath , null , null , "css" , null , null , context . getConfig ( ) . getGeneratorRegistry ( ) ) ; BundleProcessingStatus tempStatus = new BundleProcessingStatus ( BundleProcessingStatus . BUNDLE_PROCESSING_TYPE , tempBundle , context . getResourceReaderHandler ( ) , context . getConfig ( ) ) ; CSSURLPathRewriterPostProcessor postProcessor = new CSSURLPathRewriterPostProcessor ( ) ; ResourceBundlePathsIterator it = null ; StringWriter resultWriter = new StringWriter ( ) ; StringBuffer result = resultWriter . getBuffer ( ) ; ConditionalCommentCallbackHandler callbackHandler = new ConditionalCommentRenderer ( resultWriter ) ; if ( bundlesHandler . isGlobalResourceBundle ( bundlePath ) ) { it = bundlesHandler . getGlobalResourceBundlePaths ( bundlePath , callbackHandler , variants ) ; } else { it = bundlesHandler . getBundlePaths ( bundlePath , callbackHandler , variants ) ; } while ( it . hasNext ( ) ) { BundlePath resourcePath = it . nextPath ( ) ; if ( resourcePath != null ) { tempStatus . setLastPathAdded ( resourcePath . getPath ( ) ) ; Reader cssReader = null ; try { JoinableResourceBundle bundle = context . getBundle ( ) ; cssReader = context . getResourceReaderHandler ( ) . getResource ( bundle , resourcePath . getPath ( ) , true ) ; StringWriter writer = new StringWriter ( ) ; IOUtils . copy ( cssReader , writer , true ) ; StringBuffer resourceData = postProcessor . postProcessBundle ( tempStatus , writer . getBuffer ( ) ) ; result . append ( "/** CSS resource : " ) . append ( resourcePath . getPath ( ) ) . append ( " **/\n" ) ; result . append ( resourceData ) ; if ( it . hasNext ( ) ) { result . append ( "\n\n" ) ; } } catch ( ResourceNotFoundException e ) { LOGGER . debug ( "The resource '" + resourcePath . getPath ( ) + "' was not found" ) ; } catch ( IOException e ) { throw new BundlingProcessException ( e ) ; } finally { IOUtils . close ( cssReader ) ; } } } return result . toString ( ) ; }
Generates the Css content for the bundle path
2,628
private Map < String , String > getVariantMap ( ResourceBundlesHandler bundlesHandler , String contextPath , String bundlePath ) { JoinableResourceBundle bundle = bundlesHandler . resolveBundleForPath ( bundlePath ) ; Set < String > variantTypes = bundle . getVariants ( ) . keySet ( ) ; String variantKey = getVariantKey ( contextPath ) ; String [ ] variantValues = new String [ 0 ] ; if ( variantKey . length ( ) > 0 ) { if ( variantKey . length ( ) == 1 ) { variantValues = new String [ ] { "" , "" } ; } else { variantValues = variantKey . split ( String . valueOf ( JawrConstant . VARIANT_SEPARATOR_CHAR ) ) ; } } Map < String , String > variants = new HashMap < > ( ) ; if ( variantTypes . size ( ) != variantValues . length ) { throw new BundlingProcessException ( "For the resource '" + contextPath + "', the number variant types for the bundle don't match the variant values." ) ; } int i = 0 ; for ( String variantType : variantTypes ) { variants . put ( variantType , variantValues [ i ++ ] ) ; } return variants ; }
Returns the variant map from the context path
2,629
private String getBundlePath ( String contextPath ) { String bundlePath = contextPath ; int idx = - 1 ; if ( bundlePath . startsWith ( JawrConstant . URL_SEPARATOR ) ) { idx = bundlePath . indexOf ( JawrConstant . URL_SEPARATOR , 1 ) ; } else { idx = bundlePath . indexOf ( JawrConstant . URL_SEPARATOR , 1 ) ; } if ( idx != - 1 ) { bundlePath = bundlePath . substring ( idx ) ; } return bundlePath ; }
Returns the IE Css bundle path from the context path
2,630
private String getVariantKey ( String contextPath ) { String resultPath = contextPath . substring ( 1 ) ; String variantKey = "" ; String prefix = resultPath . substring ( 0 , resultPath . indexOf ( JawrConstant . URL_SEPARATOR ) ) ; if ( prefix . indexOf ( '.' ) != - 1 ) { variantKey = prefix . substring ( prefix . indexOf ( '.' ) + 1 ) ; } return variantKey . trim ( ) ; }
Returns the variant key from the context path .
2,631
public static BundleRendererContext getBundleRendererContext ( HttpServletRequest request , BundleRenderer renderer ) { String bundleRendererCtxAttributeName = BUNDLE_RENDERER_CONTEXT_ATTR_PREFIX + renderer . getResourceType ( ) ; String jawrErrorDispathAttributeName = JAWR_ERROR_DISPATCH + renderer . getResourceType ( ) ; clearRequestWhenDispatch ( request , ERROR_EXCEPTION , bundleRendererCtxAttributeName , jawrErrorDispathAttributeName ) ; String jawrForwardDispathAttributeName = JAWR_FOWARD_DISPATCH + renderer . getResourceType ( ) ; clearRequestWhenDispatch ( request , FORWARD_REQUEST_URI , bundleRendererCtxAttributeName , jawrForwardDispathAttributeName ) ; BundleRendererContext ctx = ( BundleRendererContext ) request . getAttribute ( bundleRendererCtxAttributeName ) ; if ( ctx == null ) { ctx = new BundleRendererContext ( request , renderer . getBundler ( ) . getConfig ( ) ) ; request . setAttribute ( bundleRendererCtxAttributeName , ctx ) ; } return ctx ; }
Returns the bundle renderer context .
2,632
protected static void clearRequestWhenDispatch ( HttpServletRequest request , String requestDispatchAttribute , String bundleRendererCtxAttributeName , String jawrDispathAttributeName ) { if ( request . getAttribute ( requestDispatchAttribute ) != null && request . getAttribute ( jawrDispathAttributeName ) == null ) { request . removeAttribute ( bundleRendererCtxAttributeName ) ; request . setAttribute ( jawrDispathAttributeName , Boolean . TRUE ) ; } }
Clears the request when dispatch
2,633
public static void setBundleRendererContext ( ServletRequest request , String resourceType , BundleRendererContext ctx ) { String globalBundleAddedAttributeName = BUNDLE_RENDERER_CONTEXT_ATTR_PREFIX + resourceType ; request . setAttribute ( globalBundleAddedAttributeName , ctx ) ; }
Sets the bundle renderer context .
2,634
public static boolean isRequestGzippable ( HttpServletRequest req , JawrConfig jawrConfig ) { boolean rets ; if ( ! jawrConfig . isGzipResourcesModeOn ( ) ) rets = false ; else if ( req . getHeader ( "Accept-Encoding" ) != null && req . getHeader ( "Accept-Encoding" ) . contains ( "gzip" ) ) { if ( ! jawrConfig . isGzipResourcesForIESixOn ( ) && isIE6orLess ( req ) ) { rets = false ; if ( LOGGER . isDebugEnabled ( ) ) { LOGGER . debug ( "Gzip enablement for IE executed, with result:" + rets ) ; } } else rets = true ; } else rets = false ; return rets ; }
Determines whether gzip is suitable for the current request given the current config .
2,635
public static boolean isIE ( HttpServletRequest req ) { String agent = req . getHeader ( "User-Agent" ) ; return null != agent && agent . contains ( "MSIE" ) ; }
Checks if the user agent is IE
2,636
private static boolean isIEVersionInferiorOrEqualTo ( HttpServletRequest req , int ieVersion ) { boolean result = false ; String agent = req . getHeader ( "User-Agent" ) ; if ( LOGGER . isDebugEnabled ( ) ) { LOGGER . debug ( "User-Agent for this request:" + agent ) ; } if ( agent != null ) { Matcher matcher = IE_USER_AGENT_PATTERN . matcher ( agent ) ; if ( matcher . find ( ) ) { int version = Integer . parseInt ( matcher . group ( 1 ) ) ; if ( version <= ieVersion ) { result = true ; } } } return result ; }
Checks if the user agent is IE and the version is equal or less than the one passed in parameter
2,637
public static void setRequestDebuggable ( HttpServletRequest req , JawrConfig jawrConfig ) { if ( jawrConfig . getDebugOverrideKey ( ) . length ( ) > 0 && null != req . getParameter ( JawrConstant . OVERRIDE_KEY_PARAMETER_NAME ) && jawrConfig . getDebugOverrideKey ( ) . equals ( req . getParameter ( JawrConstant . OVERRIDE_KEY_PARAMETER_NAME ) ) ) { ThreadLocalJawrContext . setDebugOverriden ( true ) ; } else { ThreadLocalJawrContext . setDebugOverriden ( false ) ; } inheritSessionDebugProperty ( req ) ; }
Determines whether to override the debug settings . Sets the debugOverride status on ThreadLocalJawrContext
2,638
public static void inheritSessionDebugProperty ( HttpServletRequest request ) { HttpSession session = request . getSession ( false ) ; if ( session != null ) { String sessionId = session . getId ( ) ; JawrApplicationConfigManager appConfigMgr = ( JawrApplicationConfigManager ) session . getServletContext ( ) . getAttribute ( JawrConstant . JAWR_APPLICATION_CONFIG_MANAGER ) ; if ( appConfigMgr != null && appConfigMgr . isDebugSessionId ( sessionId ) ) { ThreadLocalJawrContext . setDebugOverriden ( true ) ; } } }
Sets a request debuggable if the session is a debuggable session .
2,639
public static String getRenderedUrl ( String url , JawrConfig jawrConfig , String contextPath , boolean sslRequest ) { String contextPathOverride = getContextPathOverride ( sslRequest , jawrConfig ) ; String renderedUrl = url ; if ( contextPathOverride != null && ( ( jawrConfig . isDebugModeOn ( ) && jawrConfig . isUseContextPathOverrideInDebugMode ( ) ) || ! jawrConfig . isDebugModeOn ( ) ) ) { String override = contextPathOverride ; if ( "" . equals ( override ) ) { if ( url . startsWith ( "/" ) ) { renderedUrl = renderedUrl . substring ( 1 ) ; } } else { renderedUrl = PathNormalizer . joinPaths ( override , renderedUrl ) ; } } else { renderedUrl = PathNormalizer . joinPaths ( contextPath , renderedUrl ) ; } return renderedUrl ; }
Renders the URL taking in account the context path the jawr config
2,640
public static boolean refreshConfigIfNeeded ( HttpServletRequest request , JawrConfig jawrConfig ) { boolean refreshed = false ; if ( request . getAttribute ( JawrConstant . JAWR_BUNDLE_REFRESH_CHECK ) == null ) { request . setAttribute ( JawrConstant . JAWR_BUNDLE_REFRESH_CHECK , Boolean . TRUE ) ; if ( jawrConfig . getRefreshKey ( ) . length ( ) > 0 && null != request . getParameter ( JawrConstant . REFRESH_KEY_PARAM ) && jawrConfig . getRefreshKey ( ) . equals ( request . getParameter ( JawrConstant . REFRESH_KEY_PARAM ) ) ) { JawrApplicationConfigManager appConfigMgr = ( JawrApplicationConfigManager ) request . getSession ( ) . getServletContext ( ) . getAttribute ( JawrConstant . JAWR_APPLICATION_CONFIG_MANAGER ) ; if ( appConfigMgr == null ) { throw new IllegalStateException ( "JawrApplicationConfigManager is not present in servlet context. Initialization of Jawr either failed or never occurred." ) ; } appConfigMgr . refreshConfig ( ) ; refreshed = true ; } } return refreshed ; }
Refresh the Jawr config if a manual reload has been ask using the refresh key parameter from the URL
2,641
public Map < String , Map < String , VariantSet > > getSkinMapping ( ResourceBrowser rsBrowser , JawrConfig config ) { Map < String , Map < String , VariantSet > > currentSkinMapping = new HashMap < > ( ) ; PropertiesConfigHelper props = new PropertiesConfigHelper ( config . getConfigProperties ( ) , JawrConstant . CSS_TYPE ) ; Set < String > skinRootDirectories = props . getPropertyAsSet ( JawrConstant . SKIN_DEFAULT_ROOT_DIRS ) ; if ( skinMappingType . equals ( JawrConstant . SKIN_TYPE_MAPPING_SKIN_LOCALE ) ) { updateSkinMappingUsingTypeSkinLocale ( rsBrowser , config , currentSkinMapping , skinRootDirectories ) ; } else { updateSkinMappingUsingTypeLocaleSkin ( rsBrowser , config , currentSkinMapping , skinRootDirectories ) ; } return currentSkinMapping ; }
Returns the skin mapping from the Jawr config
2,642
private void updateSkinMappingUsingTypeSkinLocale ( ResourceBrowser rsBrowser , JawrConfig config , Map < String , Map < String , VariantSet > > skinMapping , Set < String > skinRootDirectories ) { String defaultSkinName = null ; String defaultLocaleName = null ; for ( Iterator < String > itRootDir = skinRootDirectories . iterator ( ) ; itRootDir . hasNext ( ) ; ) { String defaultSkinDir = PathNormalizer . asDirPath ( itRootDir . next ( ) ) ; String defaultSkinDirName = PathNormalizer . getPathName ( defaultSkinDir ) ; String skinRootDir = PathNormalizer . getParentPath ( defaultSkinDir ) ; String skinName = null ; String localeName = null ; if ( LocaleUtils . LOCALE_SUFFIXES . contains ( defaultSkinDirName ) ) { localeName = defaultSkinDirName ; skinName = PathNormalizer . getPathName ( skinRootDir ) ; skinRootDir = PathNormalizer . getParentPath ( skinRootDir ) ; } else { skinName = defaultSkinDirName ; } if ( defaultSkinName == null ) { defaultSkinName = skinName ; } else if ( ! defaultSkinName . equals ( skinName ) ) { throw new BundlingProcessException ( "The default skin for the skin root directories are not the same. Please check your configuration." ) ; } if ( defaultLocaleName == null ) { defaultLocaleName = localeName ; } else if ( ! defaultLocaleName . equals ( localeName ) ) { throw new BundlingProcessException ( "The default locale for the skin root directories are not the same. Please check your configuration." ) ; } checkRootDirectoryNotOverlap ( defaultSkinDir , skinRootDirectories ) ; Map < String , VariantSet > variantsMap = getVariants ( rsBrowser , skinRootDir , skinName , localeName , true ) ; skinMapping . put ( skinRootDir , variantsMap ) ; } cssSkinResolver . setDefaultSkin ( defaultSkinName ) ; cssSkinResolver . setSkinCookieName ( config . getSkinCookieName ( ) ) ; }
Returns the skin mapping from the Jawr config here the resource mapping type is skin_locale
2,643
private void updateSkinMappingUsingTypeLocaleSkin ( ResourceBrowser rsBrowser , JawrConfig config , Map < String , Map < String , VariantSet > > skinMapping , Set < String > skinRootDirectories ) { String defaultSkinName = null ; String defaultLocaleName = null ; for ( Iterator < String > itRootDir = skinRootDirectories . iterator ( ) ; itRootDir . hasNext ( ) ; ) { String defaultLocaleDir = PathNormalizer . asDirPath ( itRootDir . next ( ) ) ; String defaultLocaleDirName = PathNormalizer . getPathName ( defaultLocaleDir ) ; String localeRootDir = PathNormalizer . getParentPath ( defaultLocaleDir ) ; String skinName = null ; String localeName = null ; if ( ! LocaleUtils . LOCALE_SUFFIXES . contains ( defaultLocaleDirName ) ) { skinName = defaultLocaleDirName ; localeName = PathNormalizer . getPathName ( localeRootDir ) ; localeRootDir = PathNormalizer . getParentPath ( localeRootDir ) ; } else { localeName = defaultLocaleDirName ; } if ( defaultSkinName == null ) { defaultSkinName = skinName ; } else if ( ! defaultSkinName . equals ( skinName ) ) { throw new BundlingProcessException ( "The default skin for the skin root directories are not the same. Please check your configuration." ) ; } if ( defaultLocaleName == null ) { defaultLocaleName = localeName ; } else if ( ! defaultLocaleName . equals ( localeName ) ) { throw new BundlingProcessException ( "The default locale for the skin root directories are not the same. Please check your configuration." ) ; } checkRootDirectoryNotOverlap ( defaultLocaleDir , skinRootDirectories ) ; Map < String , VariantSet > variantsMap = getVariants ( rsBrowser , localeRootDir , skinName , localeName , false ) ; skinMapping . put ( localeRootDir , variantsMap ) ; } CssSkinVariantResolver skinResolver = ( CssSkinVariantResolver ) config . getGeneratorRegistry ( ) . getVariantResolver ( JawrConstant . SKIN_VARIANT_TYPE ) ; if ( skinResolver == null ) { skinResolver = new CssSkinVariantResolver ( defaultSkinName , config . getSkinCookieName ( ) ) ; config . getGeneratorRegistry ( ) . registerVariantResolver ( skinResolver ) ; } else { skinResolver . setDefaultSkin ( defaultSkinName ) ; skinResolver . setSkinCookieName ( config . getSkinCookieName ( ) ) ; } }
Returns the skin mapping from the Jawr config here the resource mapping type is locale_skin
2,644
public String getSkinRootDir ( String path , Set < String > skinRootDirs ) { String skinRootDir = null ; for ( String skinDir : skinRootDirs ) { if ( path . startsWith ( skinDir ) ) { skinRootDir = skinDir ; } } return skinRootDir ; }
Returns the skin root dir of the path given in parameter
2,645
private Map < String , VariantSet > getVariants ( ResourceBrowser rsBrowser , String rootDir , String defaultSkinName , String defaultLocaleName , boolean mappingSkinLocale ) { Set < String > paths = rsBrowser . getResourceNames ( rootDir ) ; Set < String > skinNames = new HashSet < > ( ) ; Set < String > localeVariants = new HashSet < > ( ) ; for ( Iterator < String > itPath = paths . iterator ( ) ; itPath . hasNext ( ) ; ) { String path = rootDir + itPath . next ( ) ; if ( rsBrowser . isDirectory ( path ) ) { String dirName = PathNormalizer . getPathName ( path ) ; if ( mappingSkinLocale ) { skinNames . add ( dirName ) ; updateLocaleVariants ( rsBrowser , path , localeVariants ) ; } else { if ( LocaleUtils . LOCALE_SUFFIXES . contains ( dirName ) ) { localeVariants . add ( dirName ) ; updateSkinVariants ( rsBrowser , path , skinNames ) ; } } } } return getVariants ( defaultSkinName , skinNames , defaultLocaleName , localeVariants ) ; }
Initialize the skinMapping from the parent path
2,646
private Map < String , VariantSet > getVariants ( String defaultSkin , Set < String > skinNames , String defaultLocaleName , Set < String > localeVariants ) { Map < String , VariantSet > skinVariants = new HashMap < > ( ) ; if ( ! skinNames . isEmpty ( ) ) { skinVariants . put ( JawrConstant . SKIN_VARIANT_TYPE , new VariantSet ( JawrConstant . SKIN_VARIANT_TYPE , defaultSkin , skinNames ) ) ; } if ( ! localeVariants . isEmpty ( ) ) { skinVariants . put ( JawrConstant . LOCALE_VARIANT_TYPE , new VariantSet ( JawrConstant . LOCALE_VARIANT_TYPE , defaultLocaleName , localeVariants ) ) ; } return skinVariants ; }
Returns the skin variants
2,647
private void updateLocaleVariants ( ResourceBrowser rsBrowser , String path , Set < String > localeVariants ) { Set < String > skinPaths = rsBrowser . getResourceNames ( path ) ; for ( Iterator < String > itSkinPath = skinPaths . iterator ( ) ; itSkinPath . hasNext ( ) ; ) { String skinPath = path + itSkinPath . next ( ) ; if ( rsBrowser . isDirectory ( skinPath ) ) { String skinDirName = PathNormalizer . getPathName ( skinPath ) ; if ( LocaleUtils . LOCALE_SUFFIXES . contains ( skinDirName ) ) { localeVariants . add ( skinDirName ) ; } } } }
Update the locale variants from the directory path given in parameter
2,648
private void updateSkinVariants ( ResourceBrowser rsBrowser , String path , Set < String > skinVariants ) { Set < String > skinPaths = rsBrowser . getResourceNames ( path ) ; for ( Iterator < String > itSkinPath = skinPaths . iterator ( ) ; itSkinPath . hasNext ( ) ; ) { String skinPath = path + itSkinPath . next ( ) ; if ( rsBrowser . isDirectory ( skinPath ) ) { String skinDirName = PathNormalizer . getPathName ( skinPath ) ; skinVariants . add ( skinDirName ) ; } } }
Update the skin variants from the directory path given in parameter
2,649
private void checkRootDirectoryNotOverlap ( String dir , Set < String > skinRootDirectories ) { String rootDir = removeLocaleSuffixIfExist ( dir ) ; for ( Iterator < String > itSkinDir = skinRootDirectories . iterator ( ) ; itSkinDir . hasNext ( ) ; ) { String skinDir = PathNormalizer . asDirPath ( itSkinDir . next ( ) ) ; if ( ! skinDir . equals ( dir ) ) { skinDir = removeLocaleSuffixIfExist ( skinDir ) ; if ( skinDir . startsWith ( rootDir ) ) { throw new BundlingProcessException ( "There is a misconfiguration. It is not allowed to have a skin root directory containing another one." ) ; } } } }
Check if there are no directory which is contained in another root directory
2,650
private String removeLocaleSuffixIfExist ( String dir ) { String result = dir ; String dirName = PathNormalizer . getPathName ( dir ) ; if ( LocaleUtils . LOCALE_SUFFIXES . contains ( dirName ) ) { result = dir . substring ( 0 , dir . indexOf ( "/" + dirName ) + 1 ) ; } return result ; }
Removes from the directory path the locale suffix if it exists
2,651
private VariantResourceReaderStrategy getVariantStrategy ( GeneratorContext context , Map < String , VariantSet > variantSetMap ) { VariantResourceReaderStrategy strategy = null ; try { strategy = ( VariantResourceReaderStrategy ) resourceProviderStrategyClass . newInstance ( ) ; strategy . initVariantProviderStrategy ( context , variantSetMap ) ; } catch ( InstantiationException | IllegalAccessException e ) { throw new BundlingProcessException ( e ) ; } return strategy ; }
Returns the variant strategy
2,652
private Reader getResourceReader ( JoinableResourceBundle bundle , String originalPath , ResourceReaderHandler readerHandler , String skinRootDir , String [ ] paths , Map < String , String > variantMap ) { Reader reader = null ; StringBuilder path = new StringBuilder ( skinRootDir ) ; String skinVariant = ( String ) variantMap . get ( JawrConstant . SKIN_VARIANT_TYPE ) ; String localeVariant = ( String ) variantMap . get ( JawrConstant . LOCALE_VARIANT_TYPE ) ; if ( skinMappingType . equals ( JawrConstant . SKIN_TYPE_MAPPING_SKIN_LOCALE ) ) { paths [ 0 ] = skinVariant ; if ( localeVariant != null ) { paths [ 1 ] = localeVariant ; } } else { paths [ 0 ] = localeVariant ; if ( skinVariant != null ) { paths [ 1 ] = skinVariant ; } } for ( int i = 0 ; i < paths . length ; i ++ ) { path . append ( paths [ i ] ) ; if ( i + 1 < paths . length ) { path . append ( JawrConstant . URL_SEPARATOR ) ; } } try { String finalPath = path . toString ( ) ; reader = readerHandler . getResource ( bundle , finalPath ) ; if ( ! originalPath . equals ( finalPath ) ) { String content = IOUtils . toString ( reader ) ; StringBuffer result = urlRewriter . rewriteUrl ( finalPath , originalPath , content ) ; reader = new StringReader ( result . toString ( ) ) ; } } catch ( ResourceNotFoundException | IOException e ) { } return reader ; }
Returns the reader for the resource path defined in parameter
2,653
private void initTempDirectory ( String tempDirRoot , boolean createTempSubDir ) { tempDirPath = tempDirRoot ; if ( tempDirPath . contains ( "%20" ) ) tempDirPath = tempDirPath . replaceAll ( "%20" , " " ) ; this . textDirPath = tempDirPath + File . separator + TEMP_TEXT_SUBDIR ; this . gzipDirPath = tempDirPath + File . separator + TEMP_GZIP_SUBDIR ; this . cssClasspathDirPath = tempDirPath + File . separator + TEMP_CSS_CLASSPATH_SUBDIR ; if ( createTempSubDir ) { try { createDir ( tempDirPath ) ; createDir ( textDirPath ) ; createDir ( gzipDirPath ) ; createDir ( cssClasspathDirPath ) ; } catch ( IOException e ) { throw new BundlingProcessException ( "Unexpected IOException creating temporary jawr directory" , e ) ; } } }
Initialize the temporary directories
2,654
public Properties getJawrBundleMapping ( ) { final Properties bundleMapping = new Properties ( ) ; InputStream is = null ; try { is = getBundleMappingStream ( ) ; if ( is != null ) { ( ( Properties ) bundleMapping ) . load ( is ) ; } else { LOGGER . info ( "The jawr bundle mapping '" + mappingFileName + "' is not found" ) ; } } catch ( IOException e ) { LOGGER . info ( "Error while loading the jawr bundle mapping '" + JawrConstant . JAWR_JS_MAPPING_PROPERTIES_FILENAME + "'" ) ; } finally { IOUtils . close ( is ) ; } return bundleMapping ; }
Returns the bundle mapping
2,655
private InputStream getBundleMappingStream ( ) { InputStream is = null ; try { is = getTemporaryResourceAsStream ( PathNormalizer . concatWebPath ( tempDirPath + "/" , mappingFileName ) ) ; } catch ( ResourceNotFoundException e ) { } return is ; }
Returns the bundle mapping file
2,656
public ReadableByteChannel getResourceBundleChannel ( String bundleName , boolean gzipBundle ) throws ResourceNotFoundException { String tempFileName = getStoredBundlePath ( bundleName , gzipBundle ) ; InputStream is = getTemporaryResourceAsStream ( tempFileName ) ; return Channels . newChannel ( is ) ; }
Returns the readable byte channel from the bundle name
2,657
private String getStoredBundlePath ( String bundleName , boolean asGzippedBundle ) { String tempFileName ; if ( asGzippedBundle ) tempFileName = gzipDirPath ; else tempFileName = textDirPath ; return getStoredBundlePath ( tempFileName , bundleName ) ; }
Resolves the file name with which a bundle is stored .
2,658
private String getStoredBundlePath ( String rootDir , String bundleName ) { if ( bundleName . indexOf ( '/' ) != - 1 ) { bundleName = bundleName . replace ( '/' , File . separatorChar ) ; } if ( ! bundleName . startsWith ( File . separator ) ) { rootDir += File . separator ; } return rootDir + PathNormalizer . escapeToPhysicalPath ( bundleName ) ; }
Resolves the file path of the bundle from the root directory .
2,659
@ SuppressWarnings ( "resource" ) private void storeBundle ( String bundleName , String bundledResources , boolean gzipFile , String rootdir ) { if ( LOGGER . isDebugEnabled ( ) ) { String msg = "Storing a generated " + ( gzipFile ? "and gzipped" : "" ) + " bundle with an id of:" + bundleName ; LOGGER . debug ( msg ) ; } try { bundleName = bundleName . replaceAll ( ":" , "_" ) ; if ( bundleName . indexOf ( '/' ) != - 1 ) { StringTokenizer tk = new StringTokenizer ( bundleName , "/" ) ; StringBuilder pathName = new StringBuilder ( rootdir ) ; while ( tk . hasMoreTokens ( ) ) { String name = tk . nextToken ( ) ; if ( tk . hasMoreTokens ( ) ) { pathName . append ( File . separator ) . append ( name ) ; createDir ( pathName . toString ( ) ) ; } } bundleName = bundleName . replace ( '/' , File . separatorChar ) ; } File store = createNewFile ( rootdir + File . separator + bundleName ) ; GZIPOutputStream gzOut = null ; Writer wr = null ; try { if ( gzipFile ) { FileOutputStream fos = new FileOutputStream ( store ) ; gzOut = new GZIPOutputStream ( fos ) ; byte [ ] data = bundledResources . getBytes ( charset . name ( ) ) ; gzOut . write ( data , 0 , data . length ) ; } else { FileOutputStream fos = new FileOutputStream ( store ) ; FileChannel channel = fos . getChannel ( ) ; wr = Channels . newWriter ( channel , charset . newEncoder ( ) , - 1 ) ; wr . write ( bundledResources ) ; } } finally { IOUtils . close ( gzOut ) ; IOUtils . close ( wr ) ; } } catch ( IOException e ) { if ( ThreadLocalJawrContext . isInterruptingProcessingBundle ( ) || e instanceof ClosedByInterruptException ) { throw new InterruptBundlingProcessException ( ) ; } throw new BundlingProcessException ( "Unexpected IOException creating temporary jawr file" , e ) ; } }
Stores a resource bundle either in text or binary gzipped format .
2,660
private File createDir ( String path ) throws IOException { if ( path . contains ( "%20" ) ) path = path . replaceAll ( "%20" , " " ) ; File dir = new File ( path ) ; if ( ! dir . exists ( ) && ! dir . mkdirs ( ) ) throw new BundlingProcessException ( "Error creating temporary jawr directory with path:" + dir . getPath ( ) ) ; if ( LOGGER . isDebugEnabled ( ) ) { LOGGER . debug ( "Created dir: " + dir . getCanonicalPath ( ) ) ; } return dir ; }
Creates a directory . If dir is not created for some reason a runtime exception is thrown .
2,661
private File createNewFile ( String path ) throws IOException { if ( path . contains ( "%20" ) ) path = path . replaceAll ( "%20" , " " ) ; File newFile = new File ( path ) ; if ( ! newFile . exists ( ) && ! newFile . createNewFile ( ) ) { throw new BundlingProcessException ( "Unable to create a temporary file at " + path ) ; } if ( LOGGER . isDebugEnabled ( ) ) LOGGER . debug ( "Created file: " + newFile . getCanonicalPath ( ) ) ; return newFile ; }
Creates a file . If dir is not created for some reason a runtimeexception is thrown .
2,662
public void stopWatching ( ) { if ( LOGGER . isDebugEnabled ( ) ) { LOGGER . debug ( "Stopping resource watching" ) ; } this . stopWatching . set ( true ) ; jawrEvtProcessor . stopProcessing ( ) ; jawrEvtProcessor . interrupt ( ) ; }
Sets the flag indicating if we must stop the resource watching
2,663
public synchronized void initPathToResourceBundleMap ( List < JoinableResourceBundle > bundles ) throws IOException { for ( JoinableResourceBundle bundle : bundles ) { removePathMappingFromPathMap ( bundle ) ; List < PathMapping > mappings = bundle . getMappings ( ) ; for ( PathMapping pathMapping : mappings ) { register ( pathMapping ) ; } List < FilePathMapping > fMappings = bundle . getLinkedFilePathMappings ( ) ; for ( FilePathMapping fMapping : fMappings ) { register ( fMapping ) ; } } }
Initialize the map which links path to asset bundle
2,664
private void register ( PathMapping pathMapping ) throws IOException { GeneratorRegistry generatorRegistry = bundlesHandler . getConfig ( ) . getGeneratorRegistry ( ) ; List < PathMapping > mappings = new ArrayList < > ( ) ; if ( generatorRegistry . isPathGenerated ( pathMapping . getPath ( ) ) ) { List < PathMapping > genPathMappings = generatorRegistry . getGeneratedPathMappings ( pathMapping . getBundle ( ) , pathMapping . getPath ( ) , rsReader ) ; if ( genPathMappings != null ) { mappings . addAll ( genPathMappings ) ; } else { mappings . add ( pathMapping ) ; } } else { mappings . add ( pathMapping ) ; } for ( PathMapping pMapping : mappings ) { String filePath = rsReader . getFilePath ( pMapping . getPath ( ) ) ; registerPathMapping ( pMapping , filePath ) ; } }
Register a path mapping
2,665
private void registerPathMapping ( PathMapping pathMapping , String filePath ) throws IOException { if ( filePath != null ) { Path p = Paths . get ( filePath ) ; boolean isDir = Files . isDirectory ( p ) ; if ( ! isDir ) { p = p . getParent ( ) ; } if ( pathMapping . isRecursive ( ) ) { registerAll ( p , Arrays . asList ( pathMapping ) ) ; } else { register ( p , Arrays . asList ( pathMapping ) ) ; } } }
Register the path mapping
2,666
private void removePathMappingFromPathMap ( JoinableResourceBundle bundle ) { for ( List < PathMapping > pathMappings : pathToResourceBundle . values ( ) ) { for ( Iterator < PathMapping > iterator = pathMappings . iterator ( ) ; iterator . hasNext ( ) ; ) { PathMapping pathMapping = ( PathMapping ) iterator . next ( ) ; if ( pathMapping . getBundle ( ) . getName ( ) . equals ( bundle . getName ( ) ) ) { iterator . remove ( ) ; } } } }
Removes the path mapping of the bundle given in parameter from map which links Path to resource bundle
2,667
private List < JawrConfigManagerMBean > getInitializedConfigurationManagers ( ) { final List < JawrConfigManagerMBean > mBeans = new ArrayList < > ( ) ; if ( jsMBean != null ) { mBeans . add ( jsMBean ) ; } if ( cssMBean != null ) { mBeans . add ( cssMBean ) ; } if ( binaryMBean != null ) { mBeans . add ( binaryMBean ) ; } return mBeans ; }
Returns the list of initialized configuration managers .
2,668
public JawrConfigManagerMBean getConfigMgr ( String resourceType ) { JawrConfigManagerMBean configMgr = null ; if ( resourceType . equals ( JS_TYPE ) ) { configMgr = jsMBean ; } else if ( resourceType . equals ( CSS_TYPE ) ) { configMgr = cssMBean ; } else if ( resourceType . equals ( BINARY_TYPE ) ) { configMgr = binaryMBean ; } return configMgr ; }
Returns the config manager MBean from the resource type
2,669
public String getStringValue ( String property ) { final List < JawrConfigManagerMBean > mBeans = getInitializedConfigurationManagers ( ) ; try { if ( mBeans . size ( ) == 3 ) { if ( areEquals ( getProperty ( jsMBean , property ) , getProperty ( cssMBean , property ) , getProperty ( binaryMBean , property ) ) ) { return getProperty ( jsMBean , property ) ; } else { return NOT_IDENTICAL_VALUES ; } } if ( mBeans . size ( ) == 2 ) { JawrConfigManagerMBean mBean1 = mBeans . get ( 0 ) ; JawrConfigManagerMBean mBean2 = mBeans . get ( 1 ) ; if ( areEquals ( getProperty ( mBean1 , property ) , getProperty ( mBean2 , property ) ) ) { return getProperty ( mBean1 , property ) ; } else { return NOT_IDENTICAL_VALUES ; } } JawrConfigManagerMBean mBean1 = mBeans . get ( 0 ) ; return getProperty ( mBean1 , property ) ; } catch ( NoSuchMethodException | IllegalAccessException | InvocationTargetException e ) { return ERROR_VALUE ; } }
Returns the string value of the configuration managers
2,670
public void setStringValue ( String property , String value ) { try { if ( jsMBean != null ) { setProperty ( jsMBean , property , value ) ; } if ( cssMBean != null ) { setProperty ( cssMBean , property , value ) ; } if ( binaryMBean != null ) { setProperty ( binaryMBean , property , value ) ; } } catch ( IllegalAccessException | InvocationTargetException | NoSuchMethodException e ) { throw new JmxConfigException ( "Exception while setting the string value" , e ) ; } }
Update the property with the string value in each config manager .
2,671
public boolean areEquals ( String str1 , String str2 ) { return ( str1 == null && str2 == null || str1 != null && str2 != null && str1 . equals ( str2 ) ) ; }
Returns true if the 2 string are equals .
2,672
public boolean areEquals ( String str1 , String str2 , String str3 ) { return ( str1 == null && str2 == null && str3 == null || str1 != null && str2 != null && str3 != null && str1 . equals ( str2 ) && str2 . equals ( str3 ) ) ; }
Returns true if the 3 string are equals .
2,673
public static String getLocalizedBundleName ( String bundleName , String localeKey ) { String newName = bundleName ; int idxSeparator = bundleName . lastIndexOf ( '.' ) ; if ( StringUtils . isNotEmpty ( localeKey ) && idxSeparator != - 1 ) { newName = bundleName . substring ( 0 , idxSeparator ) ; newName += '_' + localeKey ; newName += bundleName . substring ( idxSeparator ) ; } return newName ; }
Returns the localized bundle name
2,674
private static void addSuffixIfAvailable ( String messageBundlePath , Set < String > availableLocaleSuffixes , Locale locale , String fileSuffix , ServletContext servletContext ) { String localMsgResourcePath = toBundleName ( messageBundlePath , locale ) + fileSuffix ; URL resourceUrl = getResourceBundleURL ( localMsgResourcePath , servletContext ) ; if ( resourceUrl != null ) { 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 ) ; } }
Adds the locale suffix if the message resource bundle file exists .
2,675
public static URL getResourceBundleURL ( String resourcePath , ServletContext servletContext ) { URL resourceUrl = null ; try { resourceUrl = ClassLoaderResourceUtils . getResourceURL ( resourcePath , LocaleUtils . class ) ; } catch ( Exception e ) { } if ( resourceUrl == null && servletContext != null && resourcePath . startsWith ( "grails-app/" ) ) { try { resourceUrl = servletContext . getResource ( "/WEB-INF/" + resourcePath ) ; } catch ( MalformedURLException e ) { } } return resourceUrl ; }
Returns the resource bundle URL
2,676
@ SuppressWarnings ( "unchecked" ) private StringBuffer buildEngineScript ( StringBuffer engineScript , ServletContext servletContext ) { List < Container > containers = ContainerUtil . getAllPublishedContainers ( servletContext ) ; String allowGetForSafariButMakeForgeryEasier = "" ; String scriptTagProtection = DwrConstants . SCRIPT_TAG_PROTECTION ; String pollWithXhr = "" ; String sessionCookieName = "JSESSIONID" ; for ( Iterator < Container > it = containers . iterator ( ) ; it . hasNext ( ) ; ) { Container container = it . next ( ) ; ServerLoadMonitor monitor = ( ServerLoadMonitor ) container . getBean ( ServerLoadMonitor . class . getName ( ) ) ; pollWithXhr = monitor . supportsStreaming ( ) ? "false" : "true" ; if ( null != container . getBean ( "allowGetForSafariButMakeForgeryEasier" ) ) { allowGetForSafariButMakeForgeryEasier = ( String ) container . getBean ( "allowGetForSafariButMakeForgeryEasier" ) ; } if ( null != container . getBean ( "scriptTagProtection" ) ) { scriptTagProtection = ( String ) container . getBean ( "scriptTagProtection" ) ; } if ( null != container . getBean ( "sessionCookieName" ) ) { sessionCookieName = ( String ) container . getBean ( "sessionCookieName" ) ; } } StringBuffer sb = new StringBuffer ( ) ; Matcher matcher = PARAMS_PATTERN . matcher ( engineScript ) ; while ( matcher . find ( ) ) { String match = matcher . group ( ) ; if ( "${allowGetForSafariButMakeForgeryEasier}" . equals ( match ) ) { matcher . appendReplacement ( sb , allowGetForSafariButMakeForgeryEasier ) ; } else if ( "${pollWithXhr}" . equals ( match ) ) { matcher . appendReplacement ( sb , pollWithXhr ) ; } else if ( "${sessionCookieName}" . equals ( match ) ) { matcher . appendReplacement ( sb , sessionCookieName ) ; } else if ( "${scriptTagProtection}" . equals ( match ) ) { matcher . appendReplacement ( sb , scriptTagProtection ) ; } else if ( "${scriptSessionId}" . equals ( match ) ) { matcher . appendReplacement ( sb , "\"+JAWR.dwr_scriptSessionId+\"" ) ; } else if ( "${defaultPath}" . equals ( match ) ) { matcher . appendReplacement ( sb , "\"+JAWR.jawr_dwr_path+\"" ) ; } } DWRParamWriter . setUseDynamicSessionId ( true ) ; matcher . appendTail ( sb ) ; return sb ; }
Performs replacement on the engine . js script from DWR . Mainly copies what DWR does only at startup . A couple params are actually replaced to references to javascript vars that jawr will create on the page .
2,677
private StringBuffer readDWRScript ( String classpath ) { StringBuffer sb = null ; try { InputStream is = ClassLoaderResourceUtils . getResourceAsStream ( classpath , this ) ; ReadableByteChannel chan = Channels . newChannel ( is ) ; Reader r = Channels . newReader ( chan , "utf-8" ) ; StringWriter sw = new StringWriter ( ) ; IOUtils . copy ( r , sw , true ) ; sb = sw . getBuffer ( ) ; } catch ( FileNotFoundException e ) { throw new BundlingProcessException ( e ) ; } catch ( IOException e ) { throw new BundlingProcessException ( e ) ; } return sb ; }
Read a DWR utils script from the classpath .
2,678
@ SuppressWarnings ( "unchecked" ) private StringBuffer getInterfaceScript ( String scriptName , ServletContext servletContext ) { StringBuffer sb = new StringBuffer ( ENGINE_INIT ) ; List < Container > containers = ContainerUtil . getAllPublishedContainers ( servletContext ) ; boolean found = false ; for ( Iterator < Container > it = containers . iterator ( ) ; it . hasNext ( ) && ! found ; ) { Container container = it . next ( ) ; CreatorManager ctManager = ( CreatorManager ) container . getBean ( CreatorManager . class . getName ( ) ) ; if ( null != ctManager ) { Remoter remoter = ( Remoter ) container . getBean ( Remoter . class . getName ( ) ) ; String path = getPathReplacementString ( container ) ; try { String script = remoter . generateInterfaceScript ( scriptName , path ) ; found = true ; script = removeEngineInit ( script ) ; sb . append ( script ) ; } catch ( SecurityException ex ) { throw new BundlingProcessException ( ex ) ; } } } if ( ! found ) throw new IllegalArgumentException ( "The DWR bean named '" + scriptName + "' was not found in any DWR configuration instance." ) ; return sb ; }
Returns a script with a specified DWR interface
2,679
private String getPathReplacementString ( Container container ) { String path = JS_PATH_REF ; if ( null != container . getBean ( DWR_OVERRIDEPATH_PARAM ) ) { path = ( String ) container . getBean ( DWR_OVERRIDEPATH_PARAM ) ; } else if ( null != container . getBean ( DWR_MAPPING_PARAM ) ) { path = JS_CTX_PATH + container . getBean ( DWR_MAPPING_PARAM ) ; } return path ; }
Gets the appropriate path replacement string for a DWR container
2,680
@ SuppressWarnings ( { "unchecked" , "rawtypes" } ) private StringBuffer getAllPublishedInterfaces ( ServletContext servletContext ) { StringBuffer sb = new StringBuffer ( ) ; List < Container > containers = ContainerUtil . getAllPublishedContainers ( servletContext ) ; for ( Iterator < Container > it = containers . iterator ( ) ; it . hasNext ( ) ; ) { Container container = ( Container ) it . next ( ) ; CreatorManager ctManager = ( CreatorManager ) container . getBean ( CreatorManager . class . getName ( ) ) ; if ( null != ctManager ) { Remoter remoter = ( Remoter ) container . getBean ( Remoter . class . getName ( ) ) ; String path = getPathReplacementString ( container ) ; boolean debugMode = ctManager . isDebug ( ) ; Collection creators = null ; if ( ! ( ctManager instanceof DefaultCreatorManager ) ) { if ( ! debugMode ) LOGGER . warn ( "The current creatormanager is a custom implementation [" + ctManager . getClass ( ) . getName ( ) + "]. Debug mode is off, so the mapping dwr:_** is likely to trigger a SecurityException." + " Attempting to get all published creators..." ) ; creators = ctManager . getCreatorNames ( ) ; } else { DefaultCreatorManager dfCreator = ( DefaultCreatorManager ) ctManager ; try { dfCreator . setDebug ( true ) ; creators = ctManager . getCreatorNames ( ) ; } finally { dfCreator . setDebug ( debugMode ) ; } } for ( Iterator < String > names = creators . iterator ( ) ; names . hasNext ( ) ; ) { String script = remoter . generateInterfaceScript ( names . next ( ) , path ) ; script = removeEngineInit ( script ) ; sb . append ( script ) ; } } } return sb ; }
Returns a script with all the DWR interfaces available in the servletcontext
2,681
private String removeEngineInit ( String script ) { int start = script . indexOf ( ENGINE_INIT ) ; int end = start + ENGINE_INIT . length ( ) ; StringBuffer rets = new StringBuffer ( ) ; if ( start > 0 ) { rets . append ( script . substring ( 0 , start ) ) . append ( "\n" ) ; } rets . append ( script . substring ( end ) ) ; return rets . toString ( ) ; }
Removes the engine init script so that it is not repeated unnecesarily .
2,682
public String getVariant ( String variantType ) { String variant = null ; if ( bundleVariants != null ) { variant = ( String ) bundleVariants . get ( variantType ) ; } return variant ; }
Returns the current variant for the variant type specified in parameter
2,683
protected String prepareStyles ( ) { StringBuffer styles = new StringBuffer ( ) ; prepareAttribute ( styles , "id" , getAttribute ( "styleId" ) ) ; prepareAttribute ( styles , "style" , getAttribute ( "style" ) ) ; prepareAttribute ( styles , "class" , getAttribute ( "styleClass" ) ) ; prepareAttribute ( styles , "title" , getAttribute ( "title" ) ) ; prepareAttribute ( styles , "alt" , getAttribute ( "alt" ) ) ; prepareInternationalization ( styles ) ; return styles . toString ( ) ; }
Prepares the style attributes for inclusion in the component s HTML tag .
2,684
protected String prepareEventHandlers ( ) { StringBuffer handlers = new StringBuffer ( ) ; prepareMouseEvents ( handlers ) ; prepareKeyEvents ( handlers ) ; return handlers . toString ( ) ; }
Prepares the event handlers for inclusion in the component s HTML tag .
2,685
protected void prepareMouseEvents ( StringBuffer handlers ) { prepareAttribute ( handlers , "onclick" , getAttribute ( "onclick" ) ) ; prepareAttribute ( handlers , "ondblclick" , getAttribute ( "ondblclick" ) ) ; prepareAttribute ( handlers , "onmouseover" , getAttribute ( "onmouseover" ) ) ; prepareAttribute ( handlers , "onmouseout" , getAttribute ( "onmouseout" ) ) ; prepareAttribute ( handlers , "onmousemove" , getAttribute ( "onmousemove" ) ) ; prepareAttribute ( handlers , "onmousedown" , getAttribute ( "onmousedown" ) ) ; prepareAttribute ( handlers , "onmouseup" , getAttribute ( "onmouseup" ) ) ; }
Prepares the mouse event handlers appending them to the the given StringBuffer .
2,686
protected void prepareKeyEvents ( StringBuffer handlers ) { prepareAttribute ( handlers , "onkeydown" , getAttribute ( "onkeydown" ) ) ; prepareAttribute ( handlers , "onkeyup" , getAttribute ( "onkeyup" ) ) ; prepareAttribute ( handlers , "onkeypress" , getAttribute ( "onkeypress" ) ) ; }
Prepares the keyboard event handlers appending them to the the given StringBuffer .
2,687
protected void prepareImageUrl ( FacesContext context , StringBuffer results ) throws IOException { String src = ( String ) getAttributes ( ) . get ( "src" ) ; boolean base64 = Boolean . parseBoolean ( ( String ) getAttributes ( ) . get ( "base64" ) ) ; prepareAttribute ( results , "src" , getImageUrl ( context , src , base64 ) ) ; }
Prepare the image URL
2,688
public void process ( JawrWatchEvent evt ) { Path resolvedPath = evt . getResolvedPath ( ) ; List < PathMapping > mappings = watcher . getPathToResourceBundle ( ) . get ( evt . getDirPath ( ) ) ; if ( mappings != null ) { boolean isDir = Files . isDirectory ( resolvedPath , NOFOLLOW_LINKS ) ; List < JoinableResourceBundle > bundles = new ArrayList < > ( ) ; List < PathMapping > recursivePathMappings = new ArrayList < > ( ) ; for ( PathMapping mapping : mappings ) { String filePath = resolvedPath . toFile ( ) . getAbsolutePath ( ) ; if ( mapping . isAsset ( ) ) { String fileName = FileNameUtils . getName ( filePath ) ; if ( fileName . equals ( FileNameUtils . getName ( mapping . getPath ( ) ) ) ) { bundles . add ( mapping . getBundle ( ) ) ; } } else { if ( isDir ) { if ( mapping . isRecursive ( ) && ( ! mapping . hasFileFilter ( ) || mapping . accept ( filePath ) ) ) { bundles . add ( mapping . getBundle ( ) ) ; } } else if ( ! mapping . hasFileFilter ( ) || mapping . accept ( filePath ) ) { bundles . add ( mapping . getBundle ( ) ) ; } if ( mapping . isRecursive ( ) ) { recursivePathMappings . add ( mapping ) ; } } } if ( ! bundles . isEmpty ( ) ) { bundlesHandler . notifyModification ( bundles ) ; } if ( ! recursivePathMappings . isEmpty ( ) ) { if ( evt . getKind ( ) == ENTRY_CREATE && isDir ) { try { watcher . registerAll ( resolvedPath , recursivePathMappings ) ; } catch ( IOException e ) { if ( LOGGER . isWarnEnabled ( ) ) { LOGGER . warn ( e . getMessage ( ) ) ; } } } } } lastProcessTime . set ( Calendar . getInstance ( ) . getTimeInMillis ( ) ) ; }
Process the event
2,689
public boolean hasNoEventToProcess ( ) { long currentTime = Calendar . getInstance ( ) . getTimeInMillis ( ) ; return watchEvents . isEmpty ( ) && ( currentTime - lastProcessTime . get ( ) > bundlesHandler . getConfig ( ) . getSmartBundlingDelayAfterLastEvent ( ) ) ; }
Returns true if there is no more event to process
2,690
public CompressionResult compress ( String scriptSource ) { Object result = null ; StopWatch stopWatch = new StopWatch ( ) ; stopWatch . start ( "Compressing using Uglify" ) ; try { result = jsEngine . invokeFunction ( "minify" , scriptSource , options ) ; } catch ( NoSuchMethodException | ScriptException e ) { throw new BundlingProcessException ( e ) ; } stopWatch . stop ( ) ; if ( PERF_LOGGER . isDebugEnabled ( ) ) { PERF_LOGGER . debug ( stopWatch . prettyPrint ( ) ) ; } return ( CompressionResult ) result ; }
Invoke the uglyfication process on the given script code
2,691
protected String getUrlPath ( String match , String originalPath , String newCssPath ) throws IOException { String url = match . substring ( match . indexOf ( '(' ) + 1 , match . lastIndexOf ( ')' ) ) . trim ( ) ; String quoteStr = "" ; if ( url . startsWith ( "'" ) || url . startsWith ( "\"" ) ) { quoteStr = url . charAt ( 0 ) + "" ; url = url . substring ( 1 , url . length ( ) - 1 ) ; } String urlSuffix = "" ; int idxUrlSuffix = - 1 ; int idx1 = url . indexOf ( "?" ) ; int idx2 = url . indexOf ( "#" ) ; if ( idx1 != - 1 && idx2 == - 1 || idx1 == - 1 && idx2 != - 1 ) { idxUrlSuffix = Math . max ( idx1 , idx2 ) ; } else if ( idx1 != - 1 && idx2 != - 1 ) { idxUrlSuffix = Math . min ( idx1 , idx2 ) ; } if ( idxUrlSuffix != - 1 ) { urlSuffix = url . substring ( idxUrlSuffix ) ; url = url . substring ( 0 , idxUrlSuffix ) ; } if ( StringUtils . isNotEmpty ( contextPath ) && url . startsWith ( contextPath ) ) { String rootRelativePath = PathNormalizer . getRootRelativePath ( originalPath ) ; url = rootRelativePath + url . substring ( contextPath . length ( ) ) ; } int firstSlash = url . indexOf ( '/' ) ; if ( 0 == firstSlash || ( firstSlash != - 1 && url . charAt ( ++ firstSlash ) == '/' ) ) { StringBuilder sb = new StringBuilder ( "url(" ) ; sb . append ( quoteStr ) . append ( url ) . append ( urlSuffix ) . append ( quoteStr ) . append ( ")" ) ; return sb . toString ( ) ; } if ( url . startsWith ( URL_SEPARATOR ) ) url = url . substring ( 1 , url . length ( ) ) ; else if ( url . startsWith ( "./" ) ) url = url . substring ( 2 , url . length ( ) ) ; String imgUrl = getRewrittenImagePath ( originalPath , newCssPath , url ) ; String finalUrl = "url(" + quoteStr + imgUrl + urlSuffix + quoteStr + ")" ; Matcher urlMatcher = URL_PATTERN . matcher ( finalUrl ) ; if ( urlMatcher . find ( ) ) { finalUrl = PathNormalizer . normalizePath ( finalUrl ) ; } return finalUrl ; }
Transform a matched url so it points to the proper relative path with respect to the given path .
2,692
protected String getRewrittenImagePath ( String originalCssPath , String newCssPath , String url ) throws IOException { String imgUrl = null ; boolean generatedImg = false ; if ( binaryRsHandler != null ) { GeneratorRegistry imgRsGeneratorRegistry = binaryRsHandler . getConfig ( ) . getGeneratorRegistry ( ) ; generatedImg = imgRsGeneratorRegistry . isGeneratedBinaryResource ( url ) ; } String fullImgPath = PathNormalizer . concatWebPath ( originalCssPath , url ) ; if ( ! generatedImg ) { if ( StringUtils . isNotEmpty ( binaryServletPath ) ) { fullImgPath = binaryServletPath + JawrConstant . URL_SEPARATOR + fullImgPath ; } imgUrl = PathNormalizer . getRelativeWebPath ( PathNormalizer . getParentPath ( newCssPath ) , fullImgPath ) ; } else { imgUrl = url ; } return imgUrl ; }
Returns the rewritten image path
2,693
private boolean isInstanceOf ( Object rd , List < Class < ? > > interfaces ) { boolean result = false ; for ( Class < ? > class1 : interfaces ) { if ( class1 . isInstance ( rd ) ) { result = true ; break ; } } return result ; }
Checks if an object is an instance of on interface from a list of interface
2,694
public Object evaluate ( String scriptName , Reader reader ) { try { scriptEngine . put ( ScriptEngine . FILENAME , scriptName ) ; return scriptEngine . eval ( reader ) ; } catch ( ScriptException e ) { throw new BundlingProcessException ( "Error while evaluating script : " + scriptName , e ) ; } }
Evaluates the script
2,695
public Object evaluateString ( String scriptName , String source , Bindings bindings ) { try { scriptEngine . put ( ScriptEngine . FILENAME , scriptName ) ; return scriptEngine . eval ( source , bindings ) ; } catch ( ScriptException e ) { throw new BundlingProcessException ( "Error while evaluating script : " + scriptName , e ) ; } }
Evaluates the JS passed in parameter
2,696
public Object evaluate ( String scriptName , InputStream stream ) { return evaluate ( scriptName , new InputStreamReader ( stream ) ) ; }
Evaluates a script
2,697
public Object parseJSON ( String strJson ) throws ScriptException , NoSuchMethodException { Object json = scriptEngine . eval ( "JSON" ) ; Object data = invokeMethod ( json , "parse" , strJson ) ; return data ; }
Returns the JSON object from a string
2,698
public Object execEval ( String arg ) { try { return scriptEngine . eval ( "eval(" + arg + ")" ) ; } catch ( ScriptException e ) { throw new BundlingProcessException ( "Error while evaluating a script" , e ) ; } }
Launch eval function on the argument given in parameter
2,699
protected Document getWebXmlDocument ( String baseDir ) throws ParserConfigurationException , FactoryConfigurationError , SAXException , IOException { File webXml = new File ( baseDir , WEB_XML_FILE_PATH ) ; DocumentBuilder docBuilder = DocumentBuilderFactory . newInstance ( ) . newDocumentBuilder ( ) ; docBuilder . setEntityResolver ( new EntityResolver ( ) { public InputSource resolveEntity ( String publicId , String systemId ) throws SAXException , IOException { return null ; } } ) ; Document doc = docBuilder . parse ( webXml ) ; return doc ; }
Returns the XML document of the web . xml file