Input:
{ [CODESPLIT] public void process ( final Resource resource , final Reader reader , final Writer writer ) throws IOException { final String content = IOUtils . toString ( reader ) ; final Matcher matcher = PATTERN_PLACEHOLDER . matcher ( content ) ; final StringBuffer sb = new StringBuffer ( ) ; Properties properties = null ; if ( propertiesFactory != null ) { properties = propertiesFactory . create ( ) ; } //be sure that properties will never be null;
 if ( properties == null ) { properties = EMPTY_PROPERTIES ; } while ( matcher . find ( ) ) { final String variableName = matcher . group ( 1 ) ; LOG . debug ( "found placeholder: {}" , variableName ) ; matcher . appendReplacement ( sb , replaceVariable ( properties , variableName ) ) ; } matcher . appendTail ( sb ) ; writer . write ( sb . toString ( ) ) ; }


Input: { [CODESPLIT] public void process ( final Resource resource , final Reader reader , final Writer writer ) throws IOException { getProcessorDecorator ( ) . process ( resource , reader , writer ) ; }


Input: { [CODESPLIT] public void process ( final Reader reader , final Writer writer ) throws IOException { getProcessorDecorator ( ) . process ( reader , writer ) ; }


Input: { [CODESPLIT] @ Override public JsonElement serialize ( final Resource resource , final Type type , final JsonSerializationContext context ) { final JsonObject jsonObject = new JsonObject ( ) ; final String uri = resource . getUri ( ) ; jsonObject . add ( "type" , new JsonPrimitive ( resource . getType ( ) . toString ( ) ) ) ; jsonObject . add ( "minimize" , new JsonPrimitive ( resource . isMinimize ( ) ) ) ; jsonObject . add ( "uri" , new JsonPrimitive ( uri ) ) ; jsonObject . add ( "proxyUri" , new JsonPrimitive ( getExternalUri ( uri ) ) ) ; return jsonObject ; }


Input: Finds the specified URI pattern inside a JAR file . If the specified file isn t a valid JAR default strategy will be used instead . [CODESPLIT] @ Override public InputStream locateStream ( final String uri , final File folder ) throws IOException { notNull ( folder ) ; final File jarPath = getJarFile ( folder ) ; if ( isSupported ( jarPath ) ) { return locateStreamFromJar ( uri , jarPath ) ; } return super . locateStream ( uri , folder ) ; }


Input: Opens the specified JAR file and returns a valid handle . [CODESPLIT] JarFile open ( final File jarFile ) throws IOException { isTrue ( jarFile . exists ( ) , "The JAR file must exists." ) ; return new JarFile ( jarFile ) ; }


Input: Finds the specified wildcard - URI resource ( s ) inside a JAR file and returns an { @link InputStream } to read a bundle of matching resources . [CODESPLIT] private InputStream locateStreamFromJar ( final String uri , final File jarPath ) throws IOException { JarFile jarFile = null ; try { LOG . debug ( "Locating stream from jar: {}" , jarPath ) ; final WildcardContext wildcardContext = new WildcardContext ( uri , jarPath ) ; String classPath = FilenameUtils . getPath ( uri ) ; if ( classPath . startsWith ( ClasspathUriLocator . PREFIX ) ) { classPath = substringAfter ( classPath , ClasspathUriLocator . PREFIX ) ; } jarFile = open ( jarPath ) ; final List < JarEntry > jarEntryList = Collections . list ( jarFile . entries ( ) ) ; final List < JarEntry > filteredJarEntryList = new ArrayList < JarEntry > ( ) ; final List < File > allFiles = new ArrayList < File > ( ) ; for ( final JarEntry entry : jarEntryList ) { final String entryName = entry . getName ( ) ; // ignore the parent folder itself and accept only child resources final boolean isSupportedEntry = entryName . startsWith ( classPath ) && ! entryName . equals ( classPath ) && accept ( entryName , wildcardContext . getWildcard ( ) ) ; if ( isSupportedEntry ) { allFiles . add ( new File ( entryName ) ) ; LOG . debug ( "\tfound jar entry: {}" , entryName ) ; filteredJarEntryList . add ( entry ) ; } } final ByteArrayOutputStream out = new ByteArrayOutputStream ( ) ; triggerWildcardExpander ( allFiles , wildcardContext ) ; for ( final JarEntry entry : filteredJarEntryList ) { final InputStream is = jarFile . getInputStream ( entry ) ; IOUtils . copy ( is , out ) ; is . close ( ) ; } return new BufferedInputStream ( new ByteArrayInputStream ( out . toByteArray ( ) ) ) ; } finally { IOUtils . closeQuietly ( jarFile ) ; } }


Input: Replaces the protocol specific prefix and removes the query path if it exist since it should not be accepted . [CODESPLIT] private String extractPath ( final String uri ) { return DefaultWildcardStreamLocator . stripQueryPath ( uri . replace ( PREFIX , StringUtils . EMPTY ) ) ; }


Input: { [CODESPLIT] public CacheKey create ( final HttpServletRequest request ) { notNull ( request ) ; CacheKey key = null ; final String groupName = groupExtractor . getGroupName ( request ) ; final ResourceType resourceType = groupExtractor . getResourceType ( request ) ; final boolean minimize = isMinimized ( request ) ; if ( groupName != null && resourceType != null ) { key = new CacheKey ( groupName , resourceType , minimize ) ; } return key ; }


Input: Uses isMinimizeEnabled configuration to compute minimize value . [CODESPLIT] private boolean isMinimized ( final HttpServletRequest request ) { return context . getConfig ( ) . isMinimizeEnabled ( ) ? groupExtractor . isMinimized ( request ) : false ; }


Input: write the content to the { [CODESPLIT] private void writeReport ( final OutputStream outputStream ) { Transformer transformer ; try { transformer = TransformerFactory . newInstance ( ) . newTransformer ( ) ; transformer . transform ( new DOMSource ( doc ) , new StreamResult ( outputStream ) ) ; } catch ( Exception e ) { throw WroRuntimeException . wrap ( e , "Problem during Document transformation" ) . logError ( ) ; } }


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


Input: Allow adding more than one uriLocators . [CODESPLIT] public final SimpleUriLocatorFactory addLocator ( final UriLocator ... locators ) { for ( final UriLocator locator : locators ) { uriLocators . add ( locator ) ; } return this ; }


Input: Factory method which takes care of redundant decoration . [CODESPLIT] public static WroModelFactory decorate ( final WroModelFactory decorated , final List < Transformer < WroModel > > modelTransformers ) { return decorated instanceof DefaultWroModelFactoryDecorator ? decorated : new DefaultWroModelFactoryDecorator ( decorated , modelTransformers ) ; }


Input: { [CODESPLIT] public void process ( final Resource resource , final Reader reader , final Writer writer ) throws IOException { try { final String result = new Lessify ( ) . variablizeColors ( IOUtils . toString ( reader ) ) ; writer . write ( result ) ; } finally { reader . close ( ) ; writer . close ( ) ; } }


Input: Adds a ruby require to the ruby script to be run by this RubySassEngine . It s safe to add the same require twice . [CODESPLIT] public void addRequire ( final String require ) { if ( require != null && require . trim ( ) . length ( ) > 0 ) { requires . add ( require . trim ( ) ) ; } }


Input: Transforms a sass content into css using Sass ruby engine . This method is synchronized because the engine itself is not thread - safe . [CODESPLIT] public String process ( final String content ) { if ( isEmpty ( content ) ) { return StringUtils . EMPTY ; } try { synchronized ( this ) { return engineInitializer . get ( ) . eval ( buildUpdateScript ( content ) ) . toString ( ) ; } } catch ( final ScriptException e ) { throw new WroRuntimeException ( e . getMessage ( ) , e ) ; } }


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


Input: Logs the summary as it was collected at this point . [CODESPLIT] public void logSummary ( ) { final String message = totalFoundErrors == 0 ? "No lint errors found." : String . format ( "Found %s errors in %s files." , totalFoundErrors , totalResourcesWithErrors ) ; log . info ( "----------------------------------------" ) ; log . info ( String . format ( "Total resources: %s" , totalResources ) ) ; log . info ( message ) ; log . info ( "----------------------------------------\n" ) ; }


Input: A method which should be invoked on each new resource processing having as a side effect an increment of the counter holding the number of total processed resources . [CODESPLIT] public synchronized void onProcessingResource ( final Resource resource ) { totalResources ++ ; log . debug ( "processing resource: " + resource . getUri ( ) ) ; if ( isLogRequired ( ) ) { log . info ( "Processed until now: " + getTotalResources ( ) + ". Last processed: " + resource . getUri ( ) ) ; updateLastInvocation ( ) ; } }


Input: { [CODESPLIT] @ Override public void process ( final Resource resource , final Reader reader , final Writer writer ) throws IOException { final ResourcePreProcessor decoratedProcessor = getDecoratedObject ( ) ; if ( decoratedProcessor instanceof SupportAware ) { if ( ! ( ( SupportAware ) decoratedProcessor ) . isSupported ( ) ) { throw new WroRuntimeException ( toString ( ) + " processor is not supported on this environment" ) ; } } super . process ( resource , reader , writer ) ; }


Input: Ensure that the returned lock will never be null . [CODESPLIT] private ReadWriteLock getLockForKey ( final K key ) { final ReadWriteLock lock = locks . putIfAbsent ( key , new ReentrantReadWriteLock ( ) ) ; return lock == null ? locks . get ( key ) : lock ; }


Input: Called when { @link CssLintException } is thrown . Allows subclasses to re - throw this exception as a { @link RuntimeException } or handle it differently . [CODESPLIT] protected void onCssLintException ( final CssLintException e , final Resource resource ) { final String uri = resource == null ? StringUtils . EMPTY : resource . getUri ( ) ; LOG . error ( "The following resource: " + uri + " has " + e . getErrors ( ) . size ( ) + " errors." ) ; for ( final CssLintError x : e . getErrors ( ) ) { LOG . error ( uri + " line " + x . getLine ( ) + " column " + x . getCol ( ) + ": " + x . getType ( ) + " " + x . getMessage ( ) ) ; } }


Input: Creates process responsible for running lessc shell command by reading the file content from the sourceFilePath [CODESPLIT] private Process createProcess ( final File sourceFile ) throws IOException { notNull ( sourceFile ) ; final String [ ] commandLine = getCommandLine ( sourceFile . getPath ( ) ) ; LOG . debug ( "CommandLine arguments: {}" , Arrays . asList ( commandLine ) ) ; return new ProcessBuilder ( commandLine ) . redirectErrorStream ( true ) . start ( ) ; }


Input: { [CODESPLIT] @ Override public Map < String , WroModelFactory > provideModelFactories ( ) { final Map < String , WroModelFactory > map = new HashMap < String , WroModelFactory > ( ) ; map . put ( GroovyModelFactory . ALIAS , new GroovyModelFactory ( ) ) ; map . put ( JsonModelFactory . ALIAS , new JsonModelFactory ( ) ) ; map . put ( SmartWroModelFactory . ALIAS , new SmartWroModelFactory ( ) ) ; return map ; }


Input: { [CODESPLIT] @ Override protected InputStream getCompilerAsStream ( ) throws IOException { final String compilerPath = System . getProperty ( PARAM_COMPILER_PATH ) ; LOG . debug ( "compilerPath: {}" , compilerPath ) ; return StringUtils . isEmpty ( compilerPath ) ? getDefaultCompilerStream ( ) : new FileInputStream ( compilerPath ) ; }


Input: { [CODESPLIT] @ Override public String compile ( final String content , final String optionalArgument ) { return String . format ( "Hogan.cache['%s'] = %s;" , optionalArgument , super . compile ( content , "" ) ) ; }


Input: { [CODESPLIT] public Map < String , WroModelFactory > provideModelFactories ( ) { final Map < String , WroModelFactory > map = new HashMap < String , WroModelFactory > ( ) ; map . put ( XmlModelFactory . ALIAS , new XmlModelFactory ( ) ) ; return map ; }


Input: Parses out the properties of a selector s body . [CODESPLIT] private Property [ ] parseProperties ( final String contents ) { final String [ ] parts = contents . split ( ";" ) ; final List < Property > resultsAsList = new ArrayList < Property > ( ) ; for ( String part : parts ) { try { // ignore empty parts if ( ! StringUtils . isEmpty ( part . trim ( ) ) ) { resultsAsList . add ( new Property ( part ) ) ; } } catch ( final Exception e ) { LOG . warn ( e . getMessage ( ) , e ) ; } } return resultsAsList . toArray ( new Property [ resultsAsList . size ( ) ] ) ; }


Input: Return an array of the data for tasks performed . [CODESPLIT] public TaskInfo [ ] getTaskInfo ( ) { if ( ! this . keepTaskList ) { throw new UnsupportedOperationException ( "Task info is not being kept!" ) ; } return ( TaskInfo [ ] ) this . taskList . toArray ( new TaskInfo [ this . taskList . size ( ) ] ) ; }


Input: Return a string with a table describing all tasks performed . For custom reporting call getTaskInfo () and use the task info directly . [CODESPLIT] public String prettyPrint ( ) { final StringBuffer sb = new StringBuffer ( shortSummary ( ) ) ; sb . append ( ' ' ) ; if ( ! this . keepTaskList ) { sb . append ( "No task info kept" ) ; } else { final TaskInfo [ ] tasks = getTaskInfo ( ) ; sb . append ( "-----------------------------------------\n" ) ; sb . append ( "ms     %     Task name\n" ) ; sb . append ( "-----------------------------------------\n" ) ; final NumberFormat nf = NumberFormat . getNumberInstance ( ) ; nf . setMinimumIntegerDigits ( 5 ) ; nf . setGroupingUsed ( false ) ; final NumberFormat pf = NumberFormat . getPercentInstance ( ) ; pf . setMinimumIntegerDigits ( 3 ) ; pf . setGroupingUsed ( false ) ; for ( final TaskInfo task : tasks ) { sb . append ( nf . format ( task . getTimeMillis ( ) ) + "  " ) ; final double totalTimeSeconds = getTotalTimeSeconds ( ) ; final double percentage = totalTimeSeconds == 0 ? 0 : task . getTimeSeconds ( ) / totalTimeSeconds ; sb . append ( pf . format ( percentage ) + "  " ) ; sb . append ( task . getTaskName ( ) + "\n" ) ; } } return sb . toString ( ) ; }


Input: Creates compilation command for provided typescript input . [CODESPLIT] private String getCompilationCommand ( final String input ) { return String . format ( "compilerWrapper.compile(%s, %s)" , WroUtil . toJSMultiLineString ( input ) , ecmaScriptVersion ) ; }


Input: Factory method which creates a { [CODESPLIT] public static ResponseHeadersConfigurer noCache ( ) { return new ResponseHeadersConfigurer ( ) { @ Override public void configureDefaultHeaders ( final Map < String , String > map ) { addNoCacheHeaders ( map ) ; } } ; }


Input: Factory method which creates a { [CODESPLIT] public static ResponseHeadersConfigurer fromConfig ( final WroConfiguration config ) { return new ResponseHeadersConfigurer ( config . getHeader ( ) ) { @ Override public void configureDefaultHeaders ( final Map < String , String > map ) { if ( config . isDebug ( ) ) { // prevent caching when in development mode addNoCacheHeaders ( map ) ; } else { final Calendar cal = Calendar . getInstance ( ) ; cal . roll ( Calendar . YEAR , 1 ) ; map . put ( HttpHeader . CACHE_CONTROL . toString ( ) , DEFAULT_CACHE_CONTROL_VALUE ) ; map . put ( HttpHeader . EXPIRES . toString ( ) , WroUtil . toDateAsString ( cal . getTimeInMillis ( ) ) ) ; // TODO probably this is not a good idea to set this field which will have a different value when there will be // more than one instance of wro4j. map . put ( HttpHeader . LAST_MODIFIED . toString ( ) , WroUtil . toDateAsString ( getLastModifiedTimestamp ( ) ) ) ; } } ; } ; }


Input: Parse header value & puts the found values in headersMap field . [CODESPLIT] private void parseHeader ( final String header ) { LOG . debug ( "parseHeader: {}" , header ) ; final String headerName = header . substring ( 0 , header . indexOf ( ":" ) ) ; if ( ! headersMap . containsKey ( headerName ) ) { final String value = header . substring ( header . indexOf ( ":" ) + 1 ) ; headersMap . put ( headerName , StringUtils . trim ( value ) ) ; } }


Input: Populates the map with headers used to disable cache . [CODESPLIT] private static void addNoCacheHeaders ( final Map < String , String > map ) { map . put ( HttpHeader . PRAGMA . toString ( ) , "no-cache" ) ; map . put ( HttpHeader . CACHE_CONTROL . toString ( ) , "no-cache" ) ; map . put ( HttpHeader . EXPIRES . toString ( ) , "0" ) ; }


Input: Method called for each request and responsible for setting response headers used mostly for cache control . Override this method if you want to change the way headers are set . <br > [CODESPLIT] public void setHeaders ( final HttpServletResponse response ) { // Force resource caching as best as possible for ( final Map . Entry < String , String > entry : headersMap . entrySet ( ) ) { response . setHeader ( entry . getKey ( ) , entry . getValue ( ) ) ; } }


Input: { [CODESPLIT] @ Override public void process ( final Resource resource , final Reader reader , final Writer writer ) throws IOException { final String content = IOUtils . toString ( reader ) ; final CoffeeScript coffeeScript = enginePool . getObject ( ) ; try { writer . write ( coffeeScript . compile ( content ) ) ; } catch ( final Exception e ) { onException ( e ) ; final String resourceUri = resource == null ? StringUtils . EMPTY : "[" + resource . getUri ( ) + "]" ; LOG . error ( "Exception while applying " + getClass ( ) . getSimpleName ( ) + " processor on the " + resourceUri + " resource, no processing applied..." , e ) ; } finally { reader . close ( ) ; writer . close ( ) ; enginePool . returnObject ( coffeeScript ) ; } }


Input: { [CODESPLIT] @ Override public Properties createProperties ( ) { //Merge Properties file content with the filterConfig content. final Properties merged = new Properties ( ) ; try { final Properties props = newDefaultProperties ( ) ; if ( props != null ) { merged . putAll ( props ) ; } } catch ( final Exception e ) { LOG . warn ( "Cannot load properties from default location. Load propertis from filterConfig" , e ) ; } final Properties props = createPropertiesFromFilterConfig ( ) ; merged . putAll ( props ) ; return merged ; }


Input: Creates a more detailed message based on { @link RhinoException } thrown by rhino execution . The message will contain a detailed description of the problem by inspecting the JSON value provided by exception . [CODESPLIT] public static String createExceptionMessage ( final RhinoException e ) { StringBuffer message = new StringBuffer ( "Could not execute the script because: \n" ) ; if ( e instanceof JavaScriptException ) { message . append ( toJson ( ( ( JavaScriptException ) e ) . getValue ( ) ) ) ; } else if ( e instanceof EcmaError ) { final EcmaError ecmaError = ( EcmaError ) e ; message . append ( String . format ( "Error message: %s at line: %s. \nSource: %s" , ecmaError . getErrorMessage ( ) , ecmaError . lineNumber ( ) , ecmaError . lineSource ( ) ) ) ; } else { message . append ( e . getMessage ( ) ) ; } return message . toString ( ) ; }


Input: Recursively convert from native Rhino to JSON . <p > Recognizes JavaScript objects arrays and primitives . <p > Special support for JavaScript dates : converts to { $date : timestamp } in JSON . <p > Special support for MongoDB ObjectId : converts to { $oid : objectid } in JSON . <p > Also recognizes JVM types : java . util . Map java . util . Collection java . util . Date . [CODESPLIT] public static String toJson ( final Object object , final boolean indent ) { final StringBuilder s = new StringBuilder ( ) ; encode ( s , object , indent , indent ? 0 : - 1 ) ; return s . toString ( ) ; }


Input: Retrieve pathInfo from a given location . [CODESPLIT] public static String getPathInfoFromLocation ( final HttpServletRequest request , final String location ) { if ( StringUtils . isEmpty ( location ) ) { throw new IllegalArgumentException ( "Location cannot be empty string!" ) ; } final String contextPath = request . getContextPath ( ) ; if ( contextPath != null ) { if ( startsWithIgnoreCase ( location , contextPath ) ) { return location . substring ( contextPath . length ( ) ) ; } else { return location ; } } final String noSlash = location . substring ( 1 ) ; final int nextSlash = noSlash . indexOf ( ' ' ) ; if ( nextSlash == - 1 ) { return "" ; } return noSlash . substring ( nextSlash ) ; }


Input: Creates a folder like implementation for a class . Ex : com . mycompany . MyClass - > com / mycompany / [CODESPLIT] public static String toPackageAsFolder ( final Class < ? > clazz ) { Validate . notNull ( clazz , "Class cannot be null!" ) ; return clazz . getPackage ( ) . getName ( ) . replace ( ' ' , ' ' ) ; }


Input: <p > Check if a String starts with a specified prefix ( optionally case insensitive ) . < / p > [CODESPLIT] private static boolean startsWith ( final String str , final String prefix , final boolean ignoreCase ) { if ( str == null || prefix == null ) { return ( str == null && prefix == null ) ; } if ( prefix . length ( ) > str . length ( ) ) { return false ; } return str . regionMatches ( ignoreCase , 0 , prefix , 0 , prefix . length ( ) ) ; }


Input: Retrieve servletPath from a given location . [CODESPLIT] public static String getServletPathFromLocation ( final HttpServletRequest request , final String location ) { return location . replace ( getPathInfoFromLocation ( request , location ) , StringUtils . EMPTY ) ; }


Input: Analyze headers of the request and searches for mangled ( by proxy ) for Accept - Encoding header and its mangled variations and gzip header value and its mangled variations . [CODESPLIT] @ SuppressWarnings ( "unchecked" ) public static boolean isGzipSupported ( final HttpServletRequest request ) { if ( request != null ) { final Enumeration < String > headerNames = request . getHeaderNames ( ) ; if ( headerNames != null ) { while ( headerNames . hasMoreElements ( ) ) { final String headerName = headerNames . nextElement ( ) ; final Matcher m = PATTERN_ACCEPT_ENCODING . matcher ( headerName ) ; if ( m . find ( ) ) { final String headerValue = request . getHeader ( headerName ) ; final Matcher mValue = PATTERN_GZIP . matcher ( headerValue ) ; return mValue . find ( ) ; } } } } return false ; }


Input:
Transforms a java multi - line string into javascript multi - line string . This technique was found at { @link http : // stackoverflow . com / questions / 805107 / multiline - strings - in - javascript / } [CODESPLIT] public static String toJSMultiLineString ( final String data ) { final StringBuffer result = new StringBuffer ( "[" ) ; if ( data != null ) { final String [ ] lines = data . split ( "\n" ) ; if ( lines . length == 0 ) { result . append ( "\"\"" ) ; } for ( int i = 0 ; i < lines . length ; i ++ ) { final String line = lines [ i ] ; result . append ( "\"" ) ; result . append ( line . replace ( SEPARATOR_WINDOWS , "\\\\" ) . replace ( "\"" , "\\\"" ) . replaceAll ( "\\r|\\n" , "" ) ) ; // this is used to force a single line to have at least one new line (otherwise cssLint fails).
 if ( lines . length == 1 ) { result . append ( "\\n" ) ; } result . append ( "\"" ) ; if ( i < lines . length - 1 ) { result . append ( "," ) ; } } } result . append ( "].join(\"\\n\")" ) ; return result . toString ( ) ; }


Input: Utility used to verify that requestURI matches provided path [CODESPLIT] public static boolean matchesUrl ( final HttpServletRequest request , final String path ) { final Pattern pattern = Pattern . compile ( ".*" + path + "[/]?" , Pattern . CASE_INSENSITIVE ) ; if ( request . getRequestURI ( ) != null ) { final Matcher m = pattern . matcher ( request . getRequestURI ( ) ) ; return m . matches ( ) ; } return false ; }


Input: A factory method for creating a { @link ResourceProcessor } based on provided { @link ResourcePreProcessor } . [CODESPLIT] public static ResourcePostProcessor newResourceProcessor ( final Resource resource , final ResourcePreProcessor preProcessor ) { return new ResourcePostProcessor ( ) { public void process ( final Reader reader , final Writer writer ) throws IOException { preProcessor . process ( resource , reader , writer ) ; } } ; }


Input: Load the regular expression stored in in regexp . properties resource file . [CODESPLIT] public static String loadRegexpWithKey ( final String key ) { InputStream stream = null ; try { stream = WroUtil . class . getResourceAsStream ( "regexp.properties" ) ; final Properties props = new RegexpProperties ( ) . load ( stream ) ; return props . getProperty ( key ) ; } catch ( final IOException e ) { throw new WroRuntimeException ( "Could not load pattern with key: " + key + " from property file" , e ) ; } finally { closeQuietly ( stream ) ; } }


Input: Copy and close the reader and writer streams . [CODESPLIT] public static void safeCopy ( final Reader reader , final Writer writer ) throws IOException { try { IOUtils . copy ( reader , writer ) ; } finally { IOUtils . closeQuietly ( reader ) ; IOUtils . closeQuietly ( writer ) ; } }


Input: Creates a temp file which has a certain extension . [CODESPLIT] public static File createTempFile ( final String extension ) { try { final String fileName = String . format ( "wro4j-%s.%s" , UUID . randomUUID ( ) . toString ( ) , extension ) ; final File file = new File ( createTempDirectory ( ) , fileName ) ; file . createNewFile ( ) ; return file ; } catch ( final IOException e ) { throw WroRuntimeException . wrap ( e ) ; } }


Input: Join two paths ( using unix separator ) and make sure to use exactly one separator ( by adding or removing one if required ) . [CODESPLIT] public static String joinPath ( final String left , final String right ) { String leftHand = left ; if ( ! left . endsWith ( SEPARATOR_UNIX ) ) { leftHand += SEPARATOR_UNIX ; } return leftHand + right . replaceFirst ( "^/(.*)" , "$1" ) ; }


Input: Cleans the image url by trimming result and removing \ or \ characters if such exists . [CODESPLIT] public static final String cleanImageUrl ( final String imageUrl ) { notNull ( imageUrl ) ; return imageUrl . replace ( ' ' , ' ' ) . replace ( ' ' , ' ' ) . trim ( ) ; }


Input: Similar to { @link FilenameUtils#getFullPath ( String ) } but fixes the problem with Windows platform for situations when the path starts with / ( servlet context relative resources ) which are resolved to \ on windows . [CODESPLIT] public static final String getFullPath ( final String path ) { final String fullPath = FilenameUtils . getFullPath ( path ) ; return replaceWithServletContextSeparatorIfNedded ( fullPath ) ; }


Input: Similar to { @link FilenameUtils#normalize ( String ) } but fixes the problem with Windows platform for situations when the path starts with / ( servlet context relative resources ) which are resolved to \ on windows . [CODESPLIT] public static final String normalize ( final String path ) { final String normalized = FilenameUtils . normalize ( path ) ; return replaceWithServletContextSeparatorIfNedded ( normalized ) ; }


Input: Factory method which uses default name for storing / retrieving attributes in { [CODESPLIT] public static ServletContextAttributeHelper create ( final FilterConfig filterConfig ) { Validate . notNull ( filterConfig ) ; final String nameFromParam = filterConfig . getInitParameter ( INIT_PARAM_NAME ) ; final String name = nameFromParam != null ? nameFromParam : DEFAULT_NAME ; return new ServletContextAttributeHelper ( filterConfig . getServletContext ( ) , name ) ; }


Input: Creates a unique name used as a key to store the attribute in { @link ServletContext } . [CODESPLIT] final String getAttributeName ( final Attribute attribute ) { Validate . notNull ( attribute ) ; return WroServletContextListener . class . getName ( ) + "-" + attribute . name ( ) + "-" + this . name ; }


Input: Sets the attribute into the servlet context . The name of the attribute will be computed for you . [CODESPLIT] final void setAttribute ( final Attribute attribute , final Object object ) { Validate . notNull ( attribute ) ; LOG . debug ( "setting attribute: {} with value: {}" , attribute , object ) ; Validate . isTrue ( attribute . isValid ( object ) , object + " is not of valid subType for attribute: " + attribute ) ; servletContext . setAttribute ( getAttributeName ( attribute ) , object ) ; }


Input: Remove all attributes from { [CODESPLIT] public void clear ( ) { LOG . debug ( "destroying servletContext: {}" , this . name ) ; for ( Attribute attribute : Attribute . values ( ) ) { servletContext . removeAttribute ( getAttributeName ( attribute ) ) ; } }


Input: Generate the dataUri as string associated to the passed InputStream with encoding & type based on provided fileName . [CODESPLIT] public String generateDataURI ( final InputStream inputStream , final String fileName ) throws IOException { final StringWriter writer = new StringWriter ( ) ; final byte [ ] bytes = IOUtils . toByteArray ( inputStream ) ; inputStream . close ( ) ; final String mimeType = getMimeType ( fileName ) ; // actually write generateDataURI ( bytes , writer , mimeType ) ; return writer . toString ( ) ; }


Input: Generates a data URI from a byte array and outputs to the given writer . [CODESPLIT] private void generateDataURI ( final byte [ ] bytes , final Writer out , final String mimeType ) throws IOException { // create the output final StringBuffer buffer = new StringBuffer ( ) ; buffer . append ( DATA_URI_PREFIX ) ; // add MIME type buffer . append ( mimeType ) ; // output base64-encoding buffer . append ( ";base64," ) ; buffer . append ( Base64 . encodeBytes ( bytes ) ) ; // output to writer out . write ( buffer . toString ( ) ) ; }


Input: Factory method for creating { @link ReportXmlFormatter } . [CODESPLIT] public static ReportXmlFormatter create ( final LintReport < LintItem > lintReport , final FormatterType formatterType ) { return new ReportXmlFormatter ( lintReport , formatterType ) ; }


Input: Creates a report which handles the adaptation of type <F > to { @link LintItem } . [CODESPLIT] private static < F > ReportXmlFormatter createInternal ( final LintReport < F > lintReport , final FormatterType formatterType , final Function < F , LintItem > adapter ) { Validate . notNull ( lintReport ) ; final LintReport < LintItem > report = new LintReport < LintItem > ( ) ; for ( final ResourceLintReport < F > reportItem : lintReport . getReports ( ) ) { final Collection < LintItem > lintItems = new ArrayList < LintItem > ( ) ; for ( final F lint : reportItem . getLints ( ) ) { try { LOG . debug ( "Adding lint: {}" , lint ) ; lintItems . add ( adapter . apply ( lint ) ) ; } catch ( final Exception e ) { throw WroRuntimeException . wrap ( e , "Problem while adapting lint item" ) ; } } report . addReport ( ResourceLintReport . create ( reportItem . getResourcePath ( ) , lintItems ) ) ; } return new ReportXmlFormatter ( report , formatterType ) ; }


Input: { [CODESPLIT] @ Override protected void buildDocument ( ) { final Element rootElement = getDocument ( ) . createElement ( formatterType . rootElementName ) ; getDocument ( ) . appendChild ( rootElement ) ; for ( final ResourceLintReport < LintItem > resourceErrors : getLintReport ( ) . getReports ( ) ) { rootElement . appendChild ( createFileElement ( resourceErrors ) ) ; } }


Input: Creates a { [CODESPLIT] private Node createFileElement ( final ResourceLintReport < LintItem > resourceErrors ) { final Element fileElement = getDocument ( ) . createElement ( ELEMENT_FILE ) ; fileElement . setAttribute ( ATTR_NAME , resourceErrors . getResourcePath ( ) ) ; for ( final LintItem error : resourceErrors . getLints ( ) ) { fileElement . appendChild ( createIssueElement ( error ) ) ; } return fileElement ; }


Input: Creates a { [CODESPLIT] private Node createIssueElement ( final LintItem error ) { final Element issueElement = getDocument ( ) . createElement ( getIssueElementName ( ) ) ; final String column = String . valueOf ( error . getColumn ( ) ) ; if ( StringUtils . isNotBlank ( column ) ) { issueElement . setAttribute ( getColumnAttributeName ( ) , column ) ; } final String evidence = error . getEvidence ( ) ; if ( StringUtils . isNotBlank ( evidence ) ) { issueElement . setAttribute ( ATTR_EVIDENCE , evidence ) ; } final String line = String . valueOf ( error . getLine ( ) ) ; if ( StringUtils . isNotBlank ( line ) ) { issueElement . setAttribute ( ATTR_LINE , line ) ; } final String reason = error . getReason ( ) ; if ( StringUtils . isNotBlank ( reason ) ) { issueElement . setAttribute ( getReasonAttributeName ( ) , reason ) ; } final String severity = error . getSeverity ( ) ; if ( StringUtils . isNotBlank ( severity ) ) { issueElement . setAttribute ( ATTR_SEVERITY , severity ) ; } return issueElement ; }


Input: A context useful for running in web context ( inside a servlet container ) . [CODESPLIT] public static Context webContext ( final HttpServletRequest request , final HttpServletResponse response , final FilterConfig filterConfig ) { return new Context ( request , response , filterConfig ) ; }


Input: Associate a context with the CURRENT request cycle . [CODESPLIT] public static void set ( final Context context , final WroConfiguration config ) { notNull ( context ) ; notNull ( config ) ; context . setConfig ( config ) ; final String correlationId = generateCorrelationId ( ) ; CORRELATION_ID . set ( correlationId ) ; CONTEXT_MAP . put ( correlationId , context ) ; }


Input: Remove context from the local thread . [CODESPLIT] public static void unset ( ) { final String correlationId = CORRELATION_ID . get ( ) ; if ( correlationId != null ) { CONTEXT_MAP . remove ( correlationId ) ; } CORRELATION_ID . remove ( ) ; }


Input: Decorates a callable with { @link ContextPropagatingCallable } making it possible to access the { @link Context } from within the decorated callable . [CODESPLIT] public static < T > Callable < T > decorate ( final Callable < T > callable ) { return new ContextPropagatingCallable < T > ( callable ) ; }


Input: Decorates the provided { [CODESPLIT] public static CacheStrategy < CacheKey , CacheValue > decorate ( final CacheStrategy < CacheKey , CacheValue > decorated ) { return decorated instanceof DefaultSynchronizedCacheStrategyDecorator ? decorated : new DefaultSynchronizedCacheStrategyDecorator ( decorated ) ; }


Input: Creates a { [CODESPLIT] private CacheValue computeCacheValueByContent ( final String content ) { String hash = null ; try { if ( content != null ) { if ( LOG . isDebugEnabled ( ) ) { LOG . debug ( "Content to fingerprint: [{}]" , StringUtils . abbreviate ( content , 30 ) ) ; } hash = hashStrategy . getHash ( new ByteArrayInputStream ( content . getBytes ( ) ) ) ; } final CacheValue entry = CacheValue . valueOf ( content , hash ) ; LOG . debug ( "computed entry: {}" , entry ) ; return entry ; } catch ( final IOException e ) { throw new RuntimeException ( "Should never happen" , e ) ; } }


Input: Will try an asynchronous check if the async configuration is enabled . If async check is not configured a synchronous check will be performed . The async check assumes that the { @link ResourceWatcherRequestHandler } is enabled . <p / > If the async check is not allowed ( the request was not passed through { @link WroFilter } ) - no check will be performed . This is important for use - cases when wro resource is included using a taglib which performs a wro api call directly without being invoked through { @link WroFilter } . [CODESPLIT] public boolean tryAsyncCheck ( final CacheKey cacheKey ) { boolean checkInvoked = false ; if ( context . getConfig ( ) . isResourceWatcherAsync ( ) ) { if ( isAsyncCheckAllowed ( ) ) { LOG . debug ( "Checking resourceWatcher asynchronously..." ) ; final Callable < Void > callable = createAsyncCheckCallable ( cacheKey ) ; submit ( callable ) ; checkInvoked = true ; } } else { LOG . debug ( "Async check not allowed. Falling back to sync check." ) ; check ( cacheKey ) ; checkInvoked = true ; } return checkInvoked ; }


Input: Check if resources from a group were changed . If a change is detected the changeListener will be invoked . [CODESPLIT] public void check ( final CacheKey cacheKey , final Callback callback ) { notNull ( cacheKey ) ; LOG . debug ( "started" ) ; final StopWatch watch = new StopWatch ( ) ; watch . start ( "detect changes" ) ; try { final Group group = new WroModelInspector ( modelFactory . create ( ) ) . getGroupByName ( cacheKey . getGroupName ( ) ) ; if ( isGroupChanged ( group . collectResourcesOfType ( cacheKey . getType ( ) ) , callback ) ) { callback . onGroupChanged ( cacheKey ) ; cacheStrategy . put ( cacheKey , null ) ; } resourceChangeDetector . reset ( ) ; } catch ( final Exception e ) { onException ( e ) ; } finally { watch . stop ( ) ; LOG . debug ( "resource watcher info: {}" , watch . prettyPrint ( ) ) ; } }


Input: Invoked when exception occurs . [CODESPLIT] protected void onException ( final Exception e ) { // not using ERROR log intentionally, since this error is not that important LOG . info ( "Could not check for resource changes because: {}" , e . getMessage ( ) ) ; LOG . debug ( "[FAIL] detecting resource change " , e ) ; }


Input: Will check if a given resource was changed and will invoke the appropriate callback . [CODESPLIT] private void checkResourceChange ( final Resource resource , final Group group , final Callback callback , final AtomicBoolean isChanged ) throws Exception { if ( isChanged ( resource , group . getName ( ) ) ) { isChanged . compareAndSet ( false , true ) ; callback . onResourceChanged ( resource ) ; lifecycleCallback . onResourceChanged ( resource ) ; } }


Input: Check if the resource was changed from previous run . The implementation uses resource content digest ( hash ) to check for change . [CODESPLIT] private boolean isChanged ( final Resource resource , final String groupName ) { boolean changed = false ; try { final String uri = resource . getUri ( ) ; // using AtomicBoolean because we need to mutate this variable inside an anonymous class. final AtomicBoolean changeDetected = new AtomicBoolean ( resourceChangeDetector . checkChangeForGroup ( uri , groupName ) ) ; if ( ! changeDetected . get ( ) && resource . getType ( ) == ResourceType . CSS ) { final Reader reader = new InputStreamReader ( locatorFactory . locate ( uri ) ) ; LOG . debug ( "\tCheck @import directive from {}" , resource ) ; createCssImportProcessor ( changeDetected , groupName ) . process ( resource , reader , new StringWriter ( ) ) ; } changed = changeDetected . get ( ) ; } catch ( final IOException e ) { LOG . debug ( "[FAIL] Cannot check {} resource (Exception message: {}). Assuming it is unchanged..." , resource , e . getMessage ( ) ) ; } LOG . debug ( "resource={}, changed={}" , resource . getUri ( ) , changed ) ; return changed ; }


Input: Updates the hash associated with the resource for a give groupName . [CODESPLIT] public void updateHashForGroup ( final String hash , final String groupName ) { notNull ( groupName ) ; this . currentHash = hash ; if ( isChangedHash ( ) ) { LOG . debug ( "Group {} has changed" , groupName ) ; //remove all persisted groups. Starting over.. groups . clear ( ) ; } }


Input: Check if the group has at least one resource of some type . [CODESPLIT] public final boolean hasResourcesOfType ( final ResourceType resourceType ) { notNull ( resourceType , "ResourceType cannot be null!" ) ; for ( final Resource resource : resources ) { if ( resourceType . equals ( resource . getType ( ) ) ) { return true ; } } return false ; }


Input:
Replace one resource with a list of other resources . The use case is related to wildcard expander functionality when resources containing wildcard are replaced with a list of wildcard - free resources . The order of resources is preserved . <p / > The implementation is synchronized because it mutates the collection . [CODESPLIT] public void replace ( final Resource resource , final List < Resource > expandedResources ) { LOG . debug ( "replacing resource {} with expanded resources: {}" , resource , expandedResources ) ; notNull ( resource ) ; notNull ( expandedResources ) ; synchronized ( this ) { boolean found = false ; // use set to avoid duplicates
 final Set < Resource > result = new LinkedHashSet < Resource > ( ) ; for ( final Resource resourceItem : resources ) { if ( resourceItem . equals ( resource ) ) { found = true ; for ( final Resource expandedResource : expandedResources ) { // preserve minimize flag.
 expandedResource . setMinimize ( resource . isMinimize ( ) ) ; result . add ( expandedResource ) ; } } else { result . add ( resourceItem ) ; } } // if no resources found, an invalid replace is performed
 if ( ! found ) { throw new IllegalArgumentException ( "Cannot replace resource: " + resource + " for group: " + this + " because the resource is not a part of this group." ) ; } // update resources with newly built list.
 setResources ( new ArrayList < Resource > ( result ) ) ; } }


Input: Add a { @link Resource } to the collection of resources associated with this group . <p / > The implementation is synchronized because it mutates the collection . [CODESPLIT] public Group addResource ( final Resource resource ) { notNull ( resource ) ; synchronized ( this ) { if ( ! hasResource ( resource ) ) { resources . add ( resource ) ; } else { LOG . debug ( "Resource {} is already contained in this group, skipping it." , resource ) ; } } return this ; }


Input: This method will replace all earlier defined resources with the provided list of resources . <p / > The implementation is synchronized because it mutates the collection . [CODESPLIT] public final void setResources ( final List < Resource > resources ) { notNull ( resources ) ; synchronized ( this ) { this . resources . clear ( ) ; for ( final Resource resource : resources ) { addResource ( resource ) ; } } }


Input: Utility method which copies all entries from source into target . Entries with the same keys from target will be overridden with entries from source . This operation is similar to { @link Map#putAll ( Map ) } but it doesn t require changing generics to construction like [CODESPLIT] protected final void copyAll ( final Map < String , S > source , final Map < String , S > target ) { notNull ( source ) ; notNull ( target ) ; for ( final Map . Entry < String , S > entry : source . entrySet ( ) ) { target . put ( entry . getKey ( ) , entry . getValue ( ) ) ; } }


Input: Creates process responsible for running tsc shell command by reading the file content from the sourceFilePath [CODESPLIT] private Process createProcess ( final File sourceFile , final File destFile ) throws IOException { notNull ( sourceFile ) ; final String [ ] commandLine = getCommandLine ( sourceFile . getPath ( ) , destFile . getPath ( ) ) ; LOG . debug ( "CommandLine arguments: {}" , Arrays . asList ( commandLine ) ) ; final Process process = new ProcessBuilder ( commandLine ) . redirectErrorStream ( true ) . start ( ) ; //Gobblers responsible for reading stream to avoid blocking of the process when the buffer is full. final StreamGobbler errorGobbler = new StreamGobbler ( process . getErrorStream ( ) , "ERROR" ) ; // any output? final StreamGobbler outputGobbler = new StreamGobbler ( process . getInputStream ( ) , "OUTPUT" ) ; // kick them off errorGobbler . start ( ) ; outputGobbler . start ( ) ; return process ; }


Input: Creates the platform specific arguments to run the <code > tsc< / code > shell utility . Default implementation handles windows and unix platforms . [CODESPLIT] protected String [ ] getCommandLine ( final String filePath , final String outFilePath ) { return isWindows ? buildArgumentsForWindows ( filePath , outFilePath ) : buildArgumentsForUnix ( filePath , outFilePath ) ; }


Input:
Initialize script builder for evaluation . [CODESPLIT] private RhinoScriptBuilder initScriptBuilder ( ) { // TODO: Find a way to encapsulate this code
 RhinoScriptBuilder builder = null ; try { if ( scope == null ) { builder = RhinoScriptBuilder . newChain ( ) . addJSON ( ) . evaluateChain ( UglifyJs . class . getResourceAsStream ( "init.js" ) , "initScript" ) . evaluateChain ( getScriptAsStream ( ) , DEFAULT_UGLIFY_JS ) ; scope = builder . getScope ( ) ; } else { builder = RhinoScriptBuilder . newChain ( scope ) ; } return builder ; } catch ( final Exception ex ) { throw new IllegalStateException ( "Failed initializing js" , ex ) ; } }


Input:
Performs Base64 encoding on the <code > raw< / code > ByteBuffer writing it to the <code > encoded< / code > CharBuffer . This is an experimental feature . Currently it does not pass along any options ( such as { @link #DO_BREAK_LINES } or { @link #GZIP } . [CODESPLIT] public static void encode ( final java . nio . ByteBuffer raw , final java . nio . CharBuffer encoded ) { final byte [ ] raw3 = new byte [ 3 ] ; final byte [ ] enc4 = new byte [ 4 ] ; while ( raw . hasRemaining ( ) ) { final int rem = Math . min ( 3 , raw . remaining ( ) ) ; raw . get ( raw3 , 0 , rem ) ; Base64 . encode3to4 ( enc4 , raw3 , rem , Base64 . NO_OPTIONS ) ; for ( int i = 0 ; i < 4 ; i ++ ) { encoded . put ( ( char ) ( enc4 [ i ] & 0xFF ) ) ; } } // end input remaining
 }


Input: Serializes an object and returns the Base64 - encoded version of that serialized object . [CODESPLIT] public static String encodeObject ( final java . io . Serializable serializableObject ) throws java . io . IOException { return encodeObject ( serializableObject , NO_OPTIONS ) ; }


Input:
Initialize the map [CODESPLIT] private void processGroups ( final Document document ) { // handle imports
 final NodeList groupNodeList = document . getElementsByTagName ( TAG_GROUP ) ; for ( int i = 0 ; i < groupNodeList . getLength ( ) ; i ++ ) { final Element groupElement = ( Element ) groupNodeList . item ( i ) ; final String name = groupElement . getAttribute ( ATTR_GROUP_NAME ) ; allGroupElements . put ( name , groupElement ) ; } }


Input:
Recursive method . Add the parsed element group to the group collection . If the group contains group - ref element parse recursively this group . [CODESPLIT] private Collection < Resource > parseGroup ( final Element element ) { final String name = element . getAttribute ( ATTR_GROUP_NAME ) ; final String isAbstractAsString = element . getAttribute ( ATTR_GROUP_ABSTRACT ) ; final boolean isAbstractGroup = StringUtils . isNotEmpty ( isAbstractAsString ) && Boolean . valueOf ( isAbstractAsString ) ; if ( groupsInProcess . contains ( name ) ) { throw new RecursiveGroupDefinitionException ( "Infinite Recursion detected for the group: " + name + ". Recursion path: " + groupsInProcess ) ; } LOG . debug ( "\tadding group: {}" , name ) ; groupsInProcess . add ( name ) ; // skip if this group is already parsed
 final Group parsedGroup = new WroModelInspector ( model ) . getGroupByName ( name ) ; if ( parsedGroup != null ) { // remove before returning
 // this group is parsed, remove from unparsed groups collection
 groupsInProcess . remove ( name ) ; return parsedGroup . getResources ( ) ; } final Group group = createGroup ( element ) ; // this group is parsed, remove from unparsed collection
 groupsInProcess . remove ( name ) ; if ( ! isAbstractGroup ) { // add only non abstract groups
 model . addGroup ( group ) ; } return group . getResources ( ) ; }


Input: Creates a group and all its associated resources . [CODESPLIT] protected Group createGroup ( final Element element ) { final String name = element . getAttribute ( ATTR_GROUP_NAME ) ; final Group group = new Group ( name ) ; final List < Resource > resources = new ArrayList < Resource > ( ) ; final NodeList resourceNodeList = element . getChildNodes ( ) ; for ( int i = 0 ; i < resourceNodeList . getLength ( ) ; i ++ ) { final Node node = resourceNodeList . item ( i ) ; if ( node instanceof Element ) { final Element resourceElement = ( Element ) node ; parseResource ( resourceElement , resources ) ; } } group . setResources ( resources ) ; return group ; }


Input:
Creates a resource from a given resourceElement . It can be css js . If resource tag name is group - ref the method will start a recursive computation . [CODESPLIT] private void parseResource ( final Element resourceElement , final Collection < Resource > resources ) { final String tagName = resourceElement . getTagName ( ) ; final String uri = resourceElement . getTextContent ( ) ; if ( TAG_GROUP_REF . equals ( tagName ) ) { // uri in this case is the group name
 resources . addAll ( getResourcesForGroup ( uri ) ) ; } if ( getResourceType ( resourceElement ) != null ) { final Resource resource = createResource ( resourceElement ) ; LOG . debug ( "\t\tadding resource: {}" , resource ) ; resources . add ( resource ) ; } }


Input: Creates a resource from a given resourceElement . The element is guaranteed to be of a simple non - recursive type ( i . e . css or js ) . [CODESPLIT] protected Resource createResource ( final Element resourceElement ) { final String uri = resourceElement . getTextContent ( ) ; final String minimizeAsString = resourceElement . getAttribute ( ATTR_MINIMIZE ) ; final boolean minimize = StringUtils . isEmpty ( minimizeAsString ) || Boolean . valueOf ( minimizeAsString ) ; final Resource resource = Resource . create ( uri , getResourceType ( resourceElement ) ) ; resource . setMinimize ( minimize ) ; return resource ; }


Input: Search for all resources for a group with a given name . [CODESPLIT] private Collection < Resource > getResourcesForGroup ( final String groupName ) { final WroModelInspector modelInspector = new WroModelInspector ( model ) ; final Group foundGroup = modelInspector . getGroupByName ( groupName ) ; if ( foundGroup == null ) { final Element groupElement = allGroupElements . get ( groupName ) ; if ( groupElement == null ) { throw new WroRuntimeException ( "Invalid group-ref: " + groupName ) ; } return parseGroup ( groupElement ) ; } return foundGroup . getResources ( ) ; }


Input: { [CODESPLIT] public Map < String , HashStrategy > provideHashStrategies ( ) { final Map < String , HashStrategy > map = new HashMap < String , HashStrategy > ( ) ; map . put ( CRC32HashStrategy . ALIAS , new CRC32HashStrategy ( ) ) ; map . put ( MD5HashStrategy . ALIAS , new MD5HashStrategy ( ) ) ; map . put ( SHA1HashStrategy . ALIAS , new SHA1HashStrategy ( ) ) ; return map ; }


Input: { [CODESPLIT] @ Override protected ResourcePreProcessor createFallbackProcessor ( ) { LOG . debug ( "Node CoffeeScript is not supported. Using fallback Rhino processor" ) ; return new LazyProcessorDecorator ( new LazyInitializer < ResourcePreProcessor > ( ) { @ Override protected ResourcePreProcessor initialize ( ) { return new RhinoCoffeeScriptProcessor ( ) ; } } ) ; }


Input:
Replace provided url with the new url if needed . [CODESPLIT] @ Override protected String replaceImageUrl ( final String cssUri , final String imageUrl ) { //Can be null when using standalone context.
 final String contextPath = context . getRequest ( ) != null ? context . getRequest ( ) . getContextPath ( ) : null ; final RewriterContext rewriterContext = new RewriterContext ( ) . setAggregatedFolderPath ( context . getAggregatedFolderPath ( ) ) . setProxyPrefix ( getUrlPrefix ( ) ) . setContextPath ( contextPath ) ; return new ImageUrlRewriter ( rewriterContext ) . rewrite ( cssUri , imageUrl ) ; }


Input: use { [CODESPLIT] @ Deprecated public static < T , K , U , M extends Multimap < K , U > > Collector < T , ? , M > toMultimap ( Function < ? super T , ? extends K > keyMapper , Function < ? super T , ? extends U > valueMapper , Supplier < M > supplier ) { BiConsumer < M , T > accumulator = ( multimap , element ) -> multimap . put ( keyMapper . apply ( element ) , valueMapper . apply ( element ) ) ; BinaryOperator < M > finisher = ( m1 , m2 ) -> { m1 . putAll ( m2 ) ; return m1 ; } ; return new CollectorImpl <> ( supplier , accumulator , finisher , CH_ID ) ; }


Input: mainly use for { [CODESPLIT] public static < R , X extends Throwable > R supplyParallel ( ForkJoinPool pool , ThrowableSupplier < R , X > func ) throws X { checkNotNull ( pool ) ; Throwable [ ] throwable = { null } ; ForkJoinTask < R > task = pool . submit ( ( ) -> { try { return func . get ( ) ; } catch ( Throwable e ) { throwable [ 0 ] = e ; return null ; } } ) ; R r ; try { r = task . get ( ) ; } catch ( ExecutionException | InterruptedException impossible ) { throw new AssertionError ( impossible ) ; } if ( throwable [ 0 ] != null ) { //noinspection unchecked throw ( X ) throwable [ 0 ] ; } return r ; }


Input: @see #tryWait ( Iterable long TimeUnit ) [CODESPLIT] @ Nonnull public static < F extends Future < V > , V > Map < F , V > tryWait ( @ Nonnull Iterable < F > futures , @ Nonnull Duration duration ) throws TryWaitFutureUncheckedException { checkNotNull ( futures ) ; checkNotNull ( duration ) ; return tryWait ( futures , duration . toNanos ( ) , NANOSECONDS ) ; }


Input: A typical usage : { @code <pre > // a fail - safe example List<Future<User >> list = doSomeAsyncTasks () ; Map<Future<User > User > success ; try { success = tryWait ( list 1 SECONDS ) ; } catch ( TryWaitUncheckedException e ) { success = e . getSuccess () ; // there are still some success } [CODESPLIT] @ Nonnull public static < F extends Future < V > , V > Map < F , V > tryWait ( @ Nonnull Iterable < F > futures , @ Nonnegative long timeout , @ Nonnull TimeUnit unit ) throws TryWaitFutureUncheckedException { checkNotNull ( futures ) ; checkArgument ( timeout > 0 ) ; checkNotNull ( unit ) ; return tryWait ( futures , timeout , unit , it -> it , TryWaitFutureUncheckedException :: new ) ; }


Input: @see #tryWait ( Iterable long TimeUnit ThrowableFunction ) [CODESPLIT] @ Nonnull public static < K , V , X extends Throwable > Map < K , V > tryWait ( @ Nonnull Iterable < K > keys , @ Nonnull Duration duration , @ Nonnull ThrowableFunction < K , Future < V > , X > asyncFunc ) throws X , TryWaitUncheckedException { checkNotNull ( keys ) ; checkNotNull ( duration ) ; checkNotNull ( asyncFunc ) ; return tryWait ( keys , duration . toNanos ( ) , NANOSECONDS , asyncFunc ) ; }


Input: A typical usage : { @code <pre > // a fail - safe example List<Integer > list = getSomeIds () ; Map<Integer User > success ; try { success = tryWait ( list 1 SECONDS id - > executor . submit (( ) - > retrieve ( id ))) ; } catch ( TryWaitUncheckedException e ) { success = e . getSuccess () ; // there are still some success } [CODESPLIT] @ Nonnull public static < K , V , X extends Throwable > Map < K , V > tryWait ( @ Nonnull Iterable < K > keys , @ Nonnegative long timeout , @ Nonnull TimeUnit unit , @ Nonnull ThrowableFunction < K , Future < V > , X > asyncFunc ) throws X , TryWaitUncheckedException { return tryWait ( keys , timeout , unit , asyncFunc , TryWaitUncheckedException :: new ) ; }


Input: Creates a { @link ConcurrentExecutor } with the given name ( used as a prefix for creating thread ) and given timeout for running threads . If a thread did not process a job within the given timeout the thread is terminated . [CODESPLIT] public static ConcurrentExecutor create ( String name , long timeout , TimeUnit unit ) { return new ConcurrentExecutorImpl ( name , timeout , unit ) ; }


Input: Print logging information for the timer . The log only shows the recorded time of the completed start - stop cycles . If the timer is still running then it will not be stopped to add the currently measured time to the output but a warning will be logged . [CODESPLIT] public void log ( Logger logger , LogLevel priority ) { if ( LoggerWrap . isEnabledFor ( logger , priority ) ) { String timerLabel ; if ( threadId != 0 ) { timerLabel = name + " (thread " + threadId + ")" ; } else if ( threadCount > 1 ) { timerLabel = name + " (over " + threadCount + " threads)" ; } else { timerLabel = name ; } if ( todoFlags == RECORD_NONE ) { LoggerWrap . log ( logger , priority , "Timer " + timerLabel + " recorded " + measurements + " run(s), no times taken" ) ; } else { String labels = "" ; String values = "" ; String separator ; if ( ( todoFlags & RECORD_CPUTIME ) != 0 && threadId != 0 ) { labels += "CPU" ; values += totalCpuTime / 1000000 ; separator = "/" ; } else { separator = "" ; } if ( ( todoFlags & RECORD_WALLTIME ) != 0 ) { labels += separator + "Wall" ; values += separator + totalWallTime / 1000000 ; } if ( ( todoFlags & RECORD_CPUTIME ) != 0 && threadId != 0 ) { labels += "/CPU avg" ; values += "/" + ( float ) ( totalCpuTime ) / measurements / 1000000 ; } if ( ( todoFlags & RECORD_WALLTIME ) != 0 ) { labels += "/Wall avg" ; values += "/" + ( float ) ( totalWallTime ) / measurements / 1000000 ; } if ( threadCount > 1 ) { if ( ( todoFlags & RECORD_CPUTIME ) != 0 && threadId != 0 ) { labels += "/CPU per thread" ; values += "/" + ( float ) ( totalCpuTime ) / threadCount / 1000000 ; } if ( ( todoFlags & RECORD_WALLTIME ) != 0 ) { labels += "/Wall per thread" ; values += "/" + ( float ) ( totalWallTime ) / threadCount / 1000000 ; } } LoggerWrap . log ( logger , priority , "Time for " + timerLabel + " for " + measurements + " run(s) " + labels + " (ms): " + values ) ; } if ( isRunning ) { logger . warn ( "Timer " + timerLabel + " logged while it was still running" ) ; } } }


Input: Stop a timer of the given string name for the given thread . If no such timer exists - 1 will be returned . Otherwise the return value is the CPU time that was measured . [CODESPLIT] public static long stopNamedTimer ( String timerName , int todoFlags , long threadId ) { ElkTimer key = new ElkTimer ( timerName , todoFlags , threadId ) ; if ( registeredTimers . containsKey ( key ) ) { return registeredTimers . get ( key ) . stop ( ) ; } else { return - 1 ; } }


Input: Get a timer of the given string name that takes all possible times ( todos ) for the current thread . If no such timer exists yet then it will be newly created . [CODESPLIT] public static ElkTimer getNamedTimer ( String timerName ) { return getNamedTimer ( timerName , RECORD_ALL , Thread . currentThread ( ) . getId ( ) ) ; }


Input: Get a timer of the given string name and todos for the current thread . If no such timer exists yet then it will be newly created . [CODESPLIT] public static ElkTimer getNamedTimer ( String timerName , int todoFlags ) { return getNamedTimer ( timerName , todoFlags , Thread . currentThread ( ) . getId ( ) ) ; }


Input: Get a timer of the given string name for the given thread . If no such timer exists yet then it will be newly created . [CODESPLIT] public static ElkTimer getNamedTimer ( String timerName , int todoFlags , long threadId ) { ElkTimer key = new ElkTimer ( timerName , todoFlags , threadId ) ; ElkTimer previous = registeredTimers . putIfAbsent ( key , key ) ; if ( previous != null ) { return previous ; } // else return key ; }


Input: Print statistics about the saturation [CODESPLIT] public void printStatistics ( ) { ruleApplicationFactory_ . getSaturationStatistics ( ) . print ( LOGGER_ ) ; if ( LOGGER_ . isDebugEnabled ( ) ) { if ( aggregatedStats_ . jobsSubmittedNo > 0 ) LOGGER_ . debug ( "Saturation Jobs Submitted=Done+Processed: {}={}+{}" , aggregatedStats_ . jobsSubmittedNo , aggregatedStats_ . jobsAlreadyDoneNo , aggregatedStats_ . jobsProcessedNo ) ; LOGGER_ . debug ( "Locks: " + aggregatedStats_ . locks ) ; } }


Input: waking up all workers waiting for new saturated contexts [CODESPLIT] private void wakeUpWorkers ( ) { if ( ! workersWaiting_ ) { return ; } stopWorkersLock_ . lock ( ) ; try { workersWaiting_ = false ; thereAreContextsToProcess_ . signalAll ( ) ; } finally { stopWorkersLock_ . unlock ( ) ; } }


Input:
Updates the counter for processed contexts and jobs [CODESPLIT] private void updateProcessedCounters ( int snapshotFinishedWorkers ) { if ( isInterrupted ( ) ) { wakeUpWorkers ( ) ; return ; } if ( countStartedWorkers_ . get ( ) > snapshotFinishedWorkers ) { /*
			 * We are not the last worker processing the saturation state, so
			 * the current jobs and contexts may not be processed yet.
			 */ return ; } /*
		 * Otherwise we were the last worker processing the saturation state;
		 * take the values for current jobs and contexts and verify that we are
		 * still the last worker (thus the order is important here).
		 */ int snapshotCountJobsSubmitted = countJobsSubmittedUpper_ . get ( ) ; int snapshotCountContextNonSaturated = saturationState_ . getContextMarkNonSaturatedCount ( ) ; int snapshotCountStartedWorkers = countStartedWorkers_ . get ( ) ; if ( snapshotCountStartedWorkers > snapshotFinishedWorkers ) { /* no longer the last worker */ return ; } /*
		 * If we arrive here, #snapshotCountJobsSubmitted and
		 * #snapshotCountContextNonSaturated represents at least the number of
		 * jobs processed and saturated contexts. Furthermore, since we took
		 * them in this order, we know that all contexts for the processed jobs
		 * were created, saturated, and counted. Now, we updated the
		 * corresponding counters for the processed contexts and jobs but in the
		 * reversed order to make sure that for every job considered to be
		 * processed all contexts were already considered to be processed.
		 */ if ( updateIfSmaller ( countContextsSaturatedLower_ , snapshotCountContextNonSaturated ) ) { /*
			 * Sleeping workers can now take new inputs.
			 */ wakeUpWorkers ( ) ; } updateIfSmaller ( countJobsProcessedLower_ , snapshotCountJobsSubmitted ) ; }


Input:
Check if the counter for saturated contexts and processed jobs can be increased and post - process the finished jobs [CODESPLIT] private void updateFinishedCounters ( ThisStatistics localStatistics ) throws InterruptedException { int snapshotJobsProcessed = countJobsProcessedLower_ . get ( ) ; /*
		 * ensure that all contexts for processed jobs are marked as saturated
		 */ for ( ; ; ) { int snapshotCountContextsSaturatedLower = countContextsSaturatedLower_ . get ( ) ; saturationState_ . setContextsSaturated ( snapshotCountContextsSaturatedLower ) ; if ( saturationState_ . getContextSetSaturatedCount ( ) < snapshotCountContextsSaturatedLower ) { /*
				 * this means that some other worker also sets contexts as
				 * saturated, then it will mark the finished jobs instead
				 */ return ; } /*
			 * ensure that the counter for processed jobs is still up to date
			 */ int updatedSnapshotJobsProcessed = countJobsProcessedLower_ . get ( ) ; if ( updatedSnapshotJobsProcessed == snapshotJobsProcessed ) { break ; } /* else refresh counters */ snapshotJobsProcessed = updatedSnapshotJobsProcessed ; } /*
		 * ensure that all processed jobs are finished
		 */ for ( ; ; ) { int snapshotJobsFinished = countJobsFinishedUpper_ . get ( ) ; if ( snapshotJobsFinished >= snapshotJobsProcessed ) { break ; } /*
			 * update the finished context counter at least to the taken
			 * snapshot value and mark the corresponding number of jobs as
			 * processed
			 */ if ( ! countJobsFinishedUpper_ . compareAndSet ( snapshotJobsFinished , snapshotJobsFinished + 1 ) ) { /* retry */ continue ; } // else J nextJob = jobsInProgress_ . poll ( ) ; IndexedContextRoot root = nextJob . getInput ( ) ; Context rootSaturation = saturationState_ . getContext ( root ) ; if ( rootSaturation . isInitialized ( ) && ! rootSaturation . isSaturated ( ) ) { LOGGER_ . error ( "{}: context for a finished job not saturated!" , rootSaturation ) ; } nextJob . setOutput ( rootSaturation ) ; LOGGER_ . trace ( "{}: saturation finished" , root ) ; localStatistics . jobsProcessedNo ++ ; listener_ . notifyFinished ( nextJob ) ; // can be interrupted } }


Input: Update the counter to the value provided it is greater . Regardless of the returned value it is guaranteed that the value of the counter after execution will be at least the input value . [CODESPLIT] private static boolean updateIfSmaller ( AtomicInteger counter , int value ) { for ( ; ; ) { int snapshotCoutner = counter . get ( ) ; if ( snapshotCoutner >= value ) return false ; if ( counter . compareAndSet ( snapshotCoutner , value ) ) return true ; } }


Input: Adds a { @link BackwardLinkChainFromBackwardLinkRule } inferences for the given { @link ForwardLink } in the given { @link Context } [CODESPLIT] public static boolean addRuleFor ( ForwardLink link , Context context ) { BackwardLinkChainFromBackwardLinkRule rule = context . getBackwardLinkRuleChain ( ) . getCreate ( MATCHER_ , FACTORY_ ) ; return rule . forwardLinksByObjectProperty_ . add ( link . getChain ( ) , link . getTarget ( ) ) ; }


Input: Removes a { @link BackwardLinkChainFromBackwardLinkRule } inferences for the given { @link ForwardLink } from the given { @link Context } [CODESPLIT] public static boolean removeRuleFor ( ForwardLink link , Context context ) { BackwardLinkChainFromBackwardLinkRule rule = context . getBackwardLinkRuleChain ( ) . find ( MATCHER_ ) ; return rule == null ? false : rule . forwardLinksByObjectProperty_ . remove ( link . getChain ( ) , link . getTarget ( ) ) ; }


Input: Tests if a { @link BackwardLinkChainFromBackwardLinkRule } inferences for the given { @link ForwardLink } is present in the given { @link Context } [CODESPLIT] public static boolean containsRuleFor ( ForwardLink link , Context context ) { BackwardLinkChainFromBackwardLinkRule rule = context . getBackwardLinkRuleChain ( ) . find ( MATCHER_ ) ; return rule == null ? false : rule . forwardLinksByObjectProperty_ . contains ( link . getChain ( ) , link . getTarget ( ) ) ; }


Input: The default implementation of all methods [CODESPLIT] protected < P > O defaultVisit ( Rule < P > rule , P premise , ContextPremises premises , ClassInferenceProducer producer ) { if ( LOGGER_ . isTraceEnabled ( ) ) { LOGGER_ . trace ( "ignore {} by {} in {}" , premise , rule , premises ) ; } return null ; }


Input: Computes all sub - { @link IndexedPropertyChain } s of the given { @link IndexedPropertyChain } if not computing before recording all { @link ObjectPropertyInference } s using the provided { @link Producer } . It is ensured that all { @link ObjectPropertyInference } s are applied only once even if the method is called multiple times . [CODESPLIT] static Set < IndexedPropertyChain > getSubPropertyChains ( IndexedPropertyChain input , Producer < ? super SubPropertyChainInference > inferenceProducer , final PropertyHierarchyCompositionState . Dispatcher dispatcher ) { return computeSubProperties ( input , inferenceProducer , dispatcher ) . getSubPropertyChains ( ) ; }


Input: Computes all sub - { @link IndexedObjectProperty } s of the given { @link IndexedPropertyChain } if not computing before recording all { @link ObjectPropertyInference } s using the provided { @link Producer } . It is ensured that all { @link ObjectPropertyInference } s are applied only once even if the method is called multiple times . [CODESPLIT] static Set < IndexedObjectProperty > getSubProperties ( IndexedPropertyChain input , Producer < ? super SubPropertyChainInference > inferenceProducer , final PropertyHierarchyCompositionState . Dispatcher dispatcher ) { return computeSubProperties ( input , inferenceProducer , dispatcher ) . getSubProperties ( ) ; }


Input: Given an { @link IndexedObjectProperty } Computes a { @link Multimap } from { @link IndexedObjectProperty } s to { @link IndexedObjectProperty } consisting of the the assignments T - > S such that both S and ObjectPropertyChain ( S T ) are sub - properties of the given { @link IndexedObjectProperty } . The provided { @link Producer } is used to record all { @link ObjectPropertyInference } s that are applied in this computation of sub - { @link IndexedPropertyChain } s involved . It is ensured that the computation is performed only once . [CODESPLIT] static Multimap < IndexedObjectProperty , IndexedObjectProperty > getLeftSubComposableSubPropertiesByRightProperties ( IndexedObjectProperty input , Producer < ? super SubPropertyChainInference > inferenceProducer , final PropertyHierarchyCompositionState . Dispatcher dispatcher ) { SaturatedPropertyChain saturation = input . getSaturated ( ) ; if ( saturation . leftSubComposableSubPropertiesByRightPropertiesComputed ) return saturation . leftSubComposableSubPropertiesByRightProperties ; // else synchronized ( saturation ) { if ( saturation . leftSubComposableSubPropertiesByRightProperties == null ) saturation . leftSubComposableSubPropertiesByRightProperties = new HashSetMultimap < IndexedObjectProperty , IndexedObjectProperty > ( ) ; } synchronized ( saturation . leftSubComposableSubPropertiesByRightProperties ) { if ( saturation . leftSubComposableSubPropertiesByRightPropertiesComputed ) return saturation . leftSubComposableSubPropertiesByRightProperties ; // else compute it Set < IndexedObjectProperty > subProperties = getSubProperties ( input , inferenceProducer , dispatcher ) ; for ( IndexedPropertyChain subPropertyChain : getSubPropertyChains ( input , inferenceProducer , dispatcher ) ) { if ( subPropertyChain instanceof IndexedComplexPropertyChain ) { IndexedComplexPropertyChain composition = ( IndexedComplexPropertyChain ) subPropertyChain ; Set < IndexedObjectProperty > leftSubProperties = getSubProperties ( composition . getFirstProperty ( ) , inferenceProducer , dispatcher ) ; Set < IndexedObjectProperty > commonSubProperties = new LazySetIntersection < IndexedObjectProperty > ( subProperties , leftSubProperties ) ; if ( commonSubProperties . isEmpty ( ) ) continue ; // else for ( IndexedObjectProperty rightSubProperty : getSubProperties ( composition . getSuffixChain ( ) , inferenceProducer , dispatcher ) ) for ( IndexedObjectProperty commonLeft : commonSubProperties ) saturation . leftSubComposableSubPropertiesByRightProperties . ( rightSubProperty , commonLeft ) ; } } saturation . leftSubComposableSubPropertiesByRightPropertiesComputed = true ; } return saturation . leftSubComposableSubPropertiesByRightProperties ; }


Input:
Adds the specified object property into the taxonomy if it is not in it yet and sets its direct sub - properties if not set yet . [CODESPLIT] private void instertIntoTaxonomy ( final IndexedObjectProperty property ) { /*
		 * @formatter:off
		 *
		 * Transitive reduction and taxonomy computation
		 * 	if sub-properties of a sub-property contain this property,
		 * 		they are equivalent
		 * 	if a property is a strict sub-property of another strict sub-property,
		 * 		it is not direct
		 *
		 * @formatter:on
		 */ final Map < IndexedObjectProperty , ElkObjectProperty > equivalent = collectEquivalent ( property ) ; if ( equivalent == null ) { // Equivalent to top. return ; } final Map < IndexedObjectProperty , Collection < ? extends ElkObjectProperty > > subEquivalent = new ArrayHashMap < IndexedObjectProperty , Collection < ? extends ElkObjectProperty > > ( ) ; final Set < IndexedObjectProperty > indirect = new ArrayHashSet < IndexedObjectProperty > ( ) ; for ( final IndexedObjectProperty subProperty : property . getSaturated ( ) . getSubProperties ( ) ) { if ( equivalent . containsKey ( subProperty ) ) { // subProperty is not strict continue ; } // subProperty is strict final Map < IndexedObjectProperty , ElkObjectProperty > subEq = collectEquivalent ( subProperty ) ; // should not be null, because top cannot be a strict sub-property subEquivalent . put ( subProperty , subEq . values ( ) ) ; for ( final IndexedObjectProperty subSubProperty : subProperty . getSaturated ( ) . getSubProperties ( ) ) { if ( ! subEq . containsKey ( subSubProperty ) ) { // strict indirect . add ( subSubProperty ) ; } } } /*
		 * If property is not equivalent to bottom and there are no strict sub
		 * properties, add the bottom as a default sub property.
		 */ if ( subEquivalent . isEmpty ( ) && ( indexedBottomProperty_ == null || ! equivalent . containsKey ( indexedBottomProperty_ ) ) ) { outputProcessor_ . visit ( new TransitiveReductionOutputEquivalentDirectImpl < ElkObjectProperty > ( equivalent . values ( ) , defaultDirectSubproperties_ ) ) ; return ; } // else final Collection < Collection < ? extends ElkObjectProperty > > direct = Operations . map ( subEquivalent . entrySet ( ) , new Operations . Transformation < Map . Entry < IndexedObjectProperty , Collection < ? extends ElkObjectProperty > > , Collection < ? extends ElkObjectProperty > > ( ) { @ Override public Collection < ? extends ElkObjectProperty > transform ( final Entry < IndexedObjectProperty , Collection < ? extends ElkObjectProperty > > element ) { if ( indirect . contains ( element . getKey ( ) ) ) { return null ; } else { return element . getValue ( ) ; } } } ) ; outputProcessor_ . visit ( new TransitiveReductionOutputEquivalentDirectImpl < ElkObjectProperty > ( equivalent . values ( ) , direct ) ) ; }


Input: Collects sub - properties of <code > property< / code > that are equivalent to it . Returns <code > null< / code > if <code > property< / code > is equivalent to the top property . [CODESPLIT] private Map < IndexedObjectProperty , ElkObjectProperty > collectEquivalent ( final IndexedObjectProperty property ) { final Set < IndexedObjectProperty > subProperties = property . getSaturated ( ) . getSubProperties ( ) ; final Map < IndexedObjectProperty , ElkObjectProperty > equivalent = new ArrayHashMap < IndexedObjectProperty , ElkObjectProperty > ( ) ; for ( final IndexedObjectProperty subProperty : subProperties ) { if ( subProperty . equals ( indexedTopProperty_ ) ) { outputProcessor_ . visit ( new TransitiveReductionOutputExtremeImpl < ElkObjectProperty > ( property . getElkEntity ( ) ) ) ; return null ; } if ( subProperty . getSaturated ( ) . getSubProperties ( ) . contains ( property ) || property . equals ( indexedBottomProperty_ ) ) { equivalent . put ( subProperty , subProperty . getElkEntity ( ) ) ; } } if ( indexedBottomProperty_ . getSaturated ( ) . getSubProperties ( ) . contains ( property ) ) { equivalent . put ( indexedBottomProperty_ , indexedBottomProperty_ . getElkEntity ( ) ) ; } return equivalent ; }


Input: Flushes index if needed and completes loading if there is new input . Incremental mode should be changed only during completing loading . [CODESPLIT] public synchronized void ensureLoading ( ) throws ElkException { if ( ! isLoadingFinished ( ) ) { if ( isIncrementalMode ( ) ) { if ( ! stageManager . incrementalAdditionStage . isCompleted ( ) ) { complete ( stageManager . incrementalAdditionStage ) ; } } else { if ( ! stageManager . contextInitializationStage . isCompleted ( ) ) { complete ( stageManager . contextInitializationStage ) ; } } LOGGER_ . trace ( "Reset axiom loading" ) ; stageManager . inputLoadingStage . invalidateRecursive ( ) ; // Invalidate stages at the beginnings of the dependency chains. stageManager . contextInitializationStage . invalidateRecursive ( ) ; stageManager . incrementalCompletionStage . invalidateRecursive ( ) ; } complete ( stageManager . inputLoadingStage ) ; }


Input: Ensures that saturation is restored and taxonomies are cleaned . Also invalidates stages that depend on the saturation if it changed . [CODESPLIT] private void restoreSaturation ( ) throws ElkException { ensureLoading ( ) ; final boolean changed ; if ( isIncrementalMode ( ) ) { changed = ! stageManager . incrementalTaxonomyCleaningStage . isCompleted ( ) ; complete ( stageManager . incrementalTaxonomyCleaningStage ) ; } else { changed = ! stageManager . contextInitializationStage . isCompleted ( ) ; complete ( stageManager . contextInitializationStage ) ; } if ( changed ) { stageManager . consistencyCheckingStage . invalidateRecursive ( ) ; } }


Input: Check consistency of the current ontology if this has not been done yet . [CODESPLIT] public synchronized boolean isInconsistent ( ) throws ElkException { restoreConsistencyCheck ( ) ; if ( ! consistencyCheckingState . isInconsistent ( ) ) { incompleteness_ . log ( incompleteness_ . getIncompletenessMonitorForClassification ( ) ) ; } return consistencyCheckingState . isInconsistent ( ) ; }


Input: Complete the taxonomy computation stage and the stages it depends on if it has not been done yet . [CODESPLIT] protected Taxonomy < ElkClass > restoreTaxonomy ( ) throws ElkInconsistentOntologyException , ElkException { ruleAndConclusionStats . reset ( ) ; // also restores saturation and cleans the taxonomy if necessary restoreConsistencyCheck ( ) ; if ( consistencyCheckingState . isInconsistent ( ) ) { throw new ElkInconsistentOntologyException ( ) ; } complete ( stageManager . classTaxonomyComputationStage ) ; return classTaxonomyState . getTaxonomy ( ) ; }


Input: Compute the inferred taxonomy of the named classes for the given ontology if it has not been done yet . [CODESPLIT] public synchronized Taxonomy < ElkClass > getTaxonomy ( ) throws ElkInconsistentOntologyException , ElkException { restoreTaxonomy ( ) ; incompleteness_ . log ( incompleteness_ . getIncompletenessMonitorForClassification ( ) ) ; return classTaxonomyState . getTaxonomy ( ) ; }


Input: Compute the inferred taxonomy of the named classes for the given ontology if it has not been done yet . [CODESPLIT] public synchronized Taxonomy < ElkClass > getTaxonomyQuietly ( ) throws ElkException { Taxonomy < ElkClass > result ; try { result = getTaxonomy ( ) ; } catch ( ElkInconsistentOntologyException e ) { LOGGER_ . debug ( "Ontology is inconsistent" ) ; result = new SingletoneTaxonomy < ElkClass , OrphanTaxonomyNode < ElkClass > > ( ElkClassKeyProvider . INSTANCE , getAllClasses ( ) , new TaxonomyNodeFactory < ElkClass , OrphanTaxonomyNode < ElkClass > , Taxonomy < ElkClass > > ( ) { @ Override public OrphanTaxonomyNode < ElkClass > createNode ( final Iterable < ? extends ElkClass > members , final int size , final Taxonomy < ElkClass > taxonomy ) { return new OrphanTaxonomyNode < ElkClass > ( members , size , elkFactory_ . getOwlNothing ( ) , taxonomy ) ; } } ) ; } return result ; }


Input: Completes instance taxonomy computation stage and the stages that it depends on if this has not been done yet . [CODESPLIT] protected InstanceTaxonomy < ElkClass , ElkNamedIndividual > restoreInstanceTaxonomy ( ) throws ElkInconsistentOntologyException , ElkException { ruleAndConclusionStats . reset ( ) ; // also restores saturation and cleans the taxonomy if necessary restoreConsistencyCheck ( ) ; if ( consistencyCheckingState . isInconsistent ( ) ) { throw new ElkInconsistentOntologyException ( ) ; } complete ( stageManager . instanceTaxonomyComputationStage ) ; return instanceTaxonomyState . getTaxonomy ( ) ; }


Input: Compute the inferred taxonomy of the named classes with instances if this has not been done yet . [CODESPLIT] public synchronized InstanceTaxonomy < ElkClass , ElkNamedIndividual > getInstanceTaxonomy ( ) throws ElkInconsistentOntologyException , ElkException { restoreInstanceTaxonomy ( ) ; incompleteness_ . log ( incompleteness_ . getIncompletenessMonitorForClassification ( ) ) ; return instanceTaxonomyState . getTaxonomy ( ) ; }


Input: Compute the inferred taxonomy of the named classes with instances if this has not been done yet . [CODESPLIT] public synchronized InstanceTaxonomy < ElkClass , ElkNamedIndividual > getInstanceTaxonomyQuietly ( ) throws ElkException { InstanceTaxonomy < ElkClass , ElkNamedIndividual > result ; try { result = getInstanceTaxonomy ( ) ; } catch ( ElkInconsistentOntologyException e ) { LOGGER_ . debug ( "Ontology is inconsistent" ) ; result = new SingletoneInstanceTaxonomy < ElkClass , ElkNamedIndividual , OrphanTypeNode < ElkClass , ElkNamedIndividual > > ( ElkClassKeyProvider . INSTANCE , getAllClasses ( ) , new TaxonomyNodeFactory < ElkClass , OrphanTypeNode < ElkClass , ElkNamedIndividual > , Taxonomy < ElkClass > > ( ) { @ Override public OrphanTypeNode < ElkClass , ElkNamedIndividual > createNode ( final Iterable < ? extends ElkClass > members , final int size , final Taxonomy < ElkClass > taxonomy ) { final OrphanTypeNode < ElkClass , ElkNamedIndividual > node = new OrphanTypeNode < ElkClass , ElkNamedIndividual > ( members , size , elkFactory_ . getOwlNothing ( ) , taxonomy , 1 ) ; final Set < ElkNamedIndividual > allNamedIndividuals = getAllNamedIndividuals ( ) ; final Iterator < ElkNamedIndividual > namedIndividualIterator = allNamedIndividuals . iterator ( ) ; if ( namedIndividualIterator . hasNext ( ) ) { // there is at least one individual node . addInstanceNode ( new OrphanInstanceNode < ElkClass , ElkNamedIndividual > ( allNamedIndividuals , allNamedIndividuals . size ( ) , namedIndividualIterator . next ( ) , ElkIndividualKeyProvider . INSTANCE , node ) ) ; } return node ; } } , ElkIndividualKeyProvider . INSTANCE ) ; } return result ; }


Input: Compute the inferred taxonomy of the object properties for the given ontology if it has not been done yet . [CODESPLIT] public synchronized Taxonomy < ElkObjectProperty > getObjectPropertyTaxonomy ( ) throws ElkInconsistentOntologyException , ElkException { ruleAndConclusionStats . reset ( ) ; restoreConsistencyCheck ( ) ; if ( consistencyCheckingState . isInconsistent ( ) ) { throw new ElkInconsistentOntologyException ( ) ; } LOGGER_ . trace ( "Property hierarchy computation" ) ; complete ( stageManager . objectPropertyTaxonomyComputationStage ) ; incompleteness_ . log ( incompleteness_ . getIncompletenessMonitorForClassification ( ) ) ; return objectPropertyTaxonomyState . getTaxonomy ( ) ; }


Input: Compute the inferred taxonomy of the object properties for the given ontology if it has not been done yet . [CODESPLIT] public synchronized Taxonomy < ElkObjectProperty > getObjectPropertyTaxonomyQuietly ( ) throws ElkException { Taxonomy < ElkObjectProperty > result ; try { result = getObjectPropertyTaxonomy ( ) ; } catch ( ElkInconsistentOntologyException e ) { LOGGER_ . debug ( "Ontology is inconsistent" ) ; result = new SingletoneTaxonomy < ElkObjectProperty , OrphanTaxonomyNode < ElkObjectProperty > > ( ElkObjectPropertyKeyProvider . INSTANCE , getAllObjectProperties ( ) , new TaxonomyNodeFactory < ElkObjectProperty , OrphanTaxonomyNode < ElkObjectProperty > , Taxonomy < ElkObjectProperty > > ( ) { @ Override public OrphanTaxonomyNode < ElkObjectProperty > createNode ( final Iterable < ? extends ElkObjectProperty > members , final int size , final Taxonomy < ElkObjectProperty > taxonomy ) { return new OrphanTaxonomyNode < ElkObjectProperty > ( members , size , elkFactory_ . getOwlBottomObjectProperty ( ) , taxonomy ) ; } } ) ; } return result ; }


Input:
If the query results are not cached yet indexes the supplied class expression and if successful computes the query so that the results for this expressions are ready in { @link #classExpressionQueryState_ } . [CODESPLIT] private boolean computeQuery ( final ElkClassExpression classExpression , final boolean computeInstanceTaxonomy ) throws ElkInconsistentOntologyException , ElkException { // Load the query classExpressionQueryState_ . registerQuery ( classExpression ) ; ensureLoading ( ) ; // Complete all stages if ( computeInstanceTaxonomy ) { restoreInstanceTaxonomy ( ) ; } else { restoreTaxonomy ( ) ; } if ( ! classExpressionQueryState_ . isIndexed ( classExpression ) ) { return false ; } /*
		 * If query result is cashed, but there were some changes to the
		 * ontology, it may not be up to date. Whether it is is checked during
		 * stages that clean contexts. These are run, if necessary, by the call
		 * above.
		 */ if ( classExpressionQueryState_ . isComputed ( classExpression ) ) { return true ; } stageManager . classExpressionQueryStage . invalidateRecursive ( ) ; try { complete ( stageManager . classExpressionQueryStage ) ; } catch ( final ElkInterruptedException e ) { if ( classExpressionQueryState_ . isComputed ( classExpression ) ) { /*
				 * If the stage was interrupted, but the query is already
				 * computed, completing the stage will not be attempted during
				 * the next call. We need to call postExecute() manually, so
				 * that the stage wouldn't stay initialized with computation
				 * that already processed all its inputs (or at least the
				 * queried class).
				 */ stageManager . classExpressionQueryStage . postExecute ( ) ; } else { throw e ; } } return true ; }


Input: Decides whether the supplied ( possibly complex ) class expression is satisfiable . The query state is updated accordingly . [CODESPLIT] protected boolean querySatisfiability ( final ElkClassExpression classExpression ) throws ElkInconsistentOntologyException , ElkException { final boolean result ; if ( computeQuery ( classExpression , false ) ) { result = classExpressionQueryState_ . isSatisfiable ( classExpression ) ; } else { // classExpression couldn't be indexed; pretend it is a fresh class result = true ; } // If classExpression is unsatisfiable, the result is complete. if ( result ) { incompleteness_ . log ( incompleteness_ . getIncompletenessMonitorForClassExpressionQuery ( classExpressionQueryState_ . getOccurrenceStore ( classExpression ) ) ) ; } return result ; }


Input: Computes all atomic classes that are equivalent to the supplied ( possibly complex ) class expression . The query state is updated accordingly . [CODESPLIT] protected Node < ElkClass > queryEquivalentClasses ( final ElkClassExpression classExpression ) throws ElkInconsistentOntologyException , ElkException { final Node < ElkClass > result ; if ( computeQuery ( classExpression , false ) ) { final Node < ElkClass > r = classExpressionQueryState_ . getEquivalentClasses ( classExpression ) ; if ( r == null ) { result = classTaxonomyState . getTaxonomy ( ) . getBottomNode ( ) ; } else { result = r ; } } else { // classExpression couldn't be indexed; pretend it is a fresh class result = new QueryNode < ElkClass > ( ElkClassKeyProvider . INSTANCE ) ; } incompleteness_ . log ( incompleteness_ . getIncompletenessMonitorForClassExpressionQuery ( classExpressionQueryState_ . getOccurrenceStore ( classExpression ) ) ) ; return result ; }


Input: Computes all atomic direct super - classes of the supplied ( possibly complex ) class expression . The query state is updated accordingly . [CODESPLIT] protected Set < ? extends Node < ElkClass > > queryDirectSuperClasses ( final ElkClassExpression classExpression ) throws ElkInconsistentOntologyException , ElkException { final Set < ? extends Node < ElkClass > > result ; if ( computeQuery ( classExpression , false ) ) { final Set < ? extends Node < ElkClass > > r = classExpressionQueryState_ . getDirectSuperClasses ( classExpression ) ; if ( r == null ) { result = classTaxonomyState . getTaxonomy ( ) . getBottomNode ( ) . getDirectSuperNodes ( ) ; } else { result = r ; } } else { // classExpression couldn't be indexed; pretend it is a fresh class result = Collections . singleton ( classTaxonomyState . getTaxonomy ( ) . getTopNode ( ) ) ; } incompleteness_ . log ( incompleteness_ . getIncompletenessMonitorForClassExpressionQuery ( classExpressionQueryState_ . getOccurrenceStore ( classExpression ) ) ) ; return result ; }


Input: Computes all atomic direct sub - classes of the supplied ( possibly complex ) class expression . The query state is updated accordingly . [CODESPLIT] protected Set < ? extends Node < ElkClass > > queryDirectSubClasses ( final ElkClassExpression classExpression ) throws ElkInconsistentOntologyException , ElkException { final Set < ? extends Node < ElkClass > > result ; if ( computeQuery ( classExpression , false ) ) { final Taxonomy < ElkClass > taxonomy = classTaxonomyState . getTaxonomy ( ) ; final Set < ? extends Node < ElkClass > > r = classExpressionQueryState_ . getDirectSubClasses ( classExpression , taxonomy ) ; if ( r == null ) { result = taxonomy . getBottomNode ( ) . getDirectSubNodes ( ) ; } else { result = r ; } } else { // classExpression couldn't be indexed; pretend it is a fresh class result = Collections . singleton ( classTaxonomyState . getTaxonomy ( ) . getBottomNode ( ) ) ; } incompleteness_ . log ( incompleteness_ . getIncompletenessMonitorForClassExpressionQuery ( classExpressionQueryState_ . getOccurrenceStore ( classExpression ) ) ) ; return result ; }


Input: Computes all direct instances of the supplied ( possibly complex ) class expression . The query state is updated accordingly . [CODESPLIT] protected Set < ? extends Node < ElkNamedIndividual > > queryDirectInstances ( final ElkClassExpression classExpression ) throws ElkInconsistentOntologyException , ElkException { final Set < ? extends Node < ElkNamedIndividual > > result ; if ( computeQuery ( classExpression , true ) ) { final InstanceTaxonomy < ElkClass , ElkNamedIndividual > taxonomy = instanceTaxonomyState . getTaxonomy ( ) ; final Set < ? extends Node < ElkNamedIndividual > > r = classExpressionQueryState_ . getDirectInstances ( classExpression , taxonomy ) ; if ( r == null ) { result = taxonomy . getBottomNode ( ) . getDirectInstanceNodes ( ) ; } else { result = r ; } } else { // classExpression couldn't be indexed; pretend it is a fresh class result = Collections . emptySet ( ) ; } incompleteness_ . log ( incompleteness_ . getIncompletenessMonitorForClassExpressionQuery ( classExpressionQueryState_ . getOccurrenceStore ( classExpression ) ) ) ; return result ; }


Input: Decides whether the supplied { @code axioms } are entailed by the currently loaded ontology . [CODESPLIT] public synchronized Map < ElkAxiom , EntailmentQueryResult > isEntailed ( final Iterable < ? extends ElkAxiom > axioms ) throws ElkException { entailmentQueryState_ . registerQueries ( axioms ) ; restoreSaturation ( ) ; stageManager . entailmentQueryStage . invalidateRecursive ( ) ; complete ( stageManager . entailmentQueryStage ) ; return entailmentQueryState_ . isEntailed ( axioms ) ; }


Input: Decides whether the supplied { @code axiom } is entailed by the currently loaded ontology . [CODESPLIT] public synchronized EntailmentQueryResult isEntailed ( final ElkAxiom axiom ) throws ElkException { return isEntailed ( Collections . singleton ( axiom ) ) . get ( axiom ) ; }


Input: / * [CODESPLIT] @ Override public Set < ? extends Integer > getSubsumerPositions ( IndexedClassExpressionList disjoint ) { if ( disjointnessAxioms_ == null ) { return null ; } return disjointnessAxioms_ . get ( disjoint ) ; }


Input: Removes from { @link #toDoEntities_ } the entities which no longer occur in the ontology or for the context is already saturated ( thus consistency is already checked ) [CODESPLIT] private int pruneToDo ( ) { int size = 0 ; Iterator < IndexedClassEntity > itr = toDoEntities_ . iterator ( ) ; while ( itr . hasNext ( ) ) { IndexedClassEntity next = itr . next ( ) ; if ( ! next . occurs ( ) ) { itr . remove ( ) ; continue ; } // else Context context = saturationState_ . getContext ( next ) ; if ( context != null && context . isSaturated ( ) ) { itr . remove ( ) ; } else { size ++ ; } } return size ; }


Input: Explains why an ontology inconsistency is entailed . If it is not entailed the returned proof is empty . [CODESPLIT] public Proof < ? extends EntailmentInference > getEvidence ( final boolean atMostOne ) { return new Proof < EntailmentInference > ( ) { @ SuppressWarnings ( "unchecked" ) @ Override public Collection < OntologyInconsistencyEntailmentInference > getInferences ( final Object conclusion ) { if ( ! OntologyInconsistencyImpl . INSTANCE . equals ( conclusion ) ) { return Collections . emptyList ( ) ; } // else final Collection < ? extends IndexedIndividual > inconsistentIndividuals = getInconsistentIndividuals ( ) ; Iterable < OntologyInconsistencyEntailmentInference > result = Operations . map ( inconsistentIndividuals , INDIVIDUAL_TO_ENTAILMENT_INFERENCE ) ; int size = inconsistentIndividuals . size ( ) ; if ( isTopObjectPropertyInBottom_ ) { result = Operations . concat ( Operations . < OntologyInconsistencyEntailmentInference > singleton ( new TopObjectPropertyInBottomEntailsOntologyInconsistencyImpl ( conclusionFactory_ . getSubPropertyChain ( topProperty_ , bottomProperty_ ) ) ) , result ) ; size ++ ; } if ( isOwlThingInconsistent_ ) { result = Operations . concat ( Operations . < OntologyInconsistencyEntailmentInference > singleton ( new OwlThingInconsistencyEntailsOntologyInconsistencyImpl ( conclusionFactory_ . getContradiction ( owlThing_ ) ) ) , result ) ; size ++ ; } if ( atMostOne ) { final Iterator < OntologyInconsistencyEntailmentInference > iter = result . iterator ( ) ; if ( ! iter . hasNext ( ) ) { return Collections . emptyList ( ) ; } // else return Collections . singleton ( iter . next ( ) ) ; } // else return Operations . getCollection ( result , size ) ; } } ; }


Input: Registers the supplied axioms for querying . If all necessary stages are run after calling this method for some axioms neither { @link #isEntailed ( Iterable ) } nor a { @link org . semanticweb . elk . reasoner . query . ProperEntailmentQueryResult ProperEntailmentQueryResult } for any of these axioms will throw { @link ElkQueryException } . [CODESPLIT] void registerQueries ( final Iterable < ? extends ElkAxiom > axioms ) { lastQueries_ . clear ( ) ; for ( final ElkAxiom axiom : axioms ) { LOGGER_ . trace ( "entailment query registered {}" , axiom ) ; lastQueries_ . add ( axiom ) ; QueryState state = queried_ . get ( axiom ) ; if ( state != null ) { queriedEvictor_ . add ( state ) ; continue ; } // Create query state. state = new QueryState ( axiom ) ; queried_ . put ( axiom , state ) ; queriedEvictor_ . add ( state ) ; toLoad_ . offer ( axiom ) ; } }


Input: Decides whether the supplied { @code axioms } are entailed . If some of the supplied axioms was not registered by { @link #registerQueries ( Iterable ) } . [CODESPLIT] Map < ElkAxiom , EntailmentQueryResult > isEntailed ( final Iterable < ? extends ElkAxiom > axioms ) throws ElkQueryException { final Map < ElkAxiom , EntailmentQueryResult > results = new ArrayHashMap < ElkAxiom , EntailmentQueryResult > ( ) ; for ( final ElkAxiom axiom : axioms ) { if ( ! EntailmentQueryConverter . isEntailmentCheckingSupported ( axiom . getClass ( ) ) ) { results . put ( axiom , new UnsupportedQueryTypeEntailmentQueryResultImpl ( axiom ) ) ; continue ; } // else final QueryState state = queried_ . get ( axiom ) ; if ( state == null ) { throw new ElkQueryException ( "Query was not registered: " + axiom ) ; } // else if ( state . indexed == null ) { results . put ( axiom , new UnsupportedIndexingEntailmentQueryResultImpl ( axiom ) ) ; continue ; } // else state . lock ( ) ; results . put ( axiom , state ) ; } return results ; }


Input: Initialize the parameters of the computation for this stage ; this is the first thing to be done before stage is executed [CODESPLIT] @ Override public boolean preExecute ( ) { if ( isInitialized_ ) return false ; LOGGER_ . trace ( "{}: initialized" , this ) ; this . workerNo = reasoner . getNumberOfWorkers ( ) ; return isInitialized_ = true ; }


Input: Clear the parameters of the computation for this stage ; this is the last thing to be done when the stage is executed * [CODESPLIT] @ Override public boolean postExecute ( ) { if ( ! isInitialized_ ) return false ; LOGGER_ . trace ( "{}: done" , this ) ; this . isCompleted_ = true ; this . workerNo = 0 ; this . isInitialized_ = false ; return true ; }


Input: Marks this { @link AbstractReasonerStage } as not completed ; this will require its execution next time unless { @link #setCompleted () } is called [CODESPLIT] boolean invalidate ( ) { if ( ! isCompleted_ && ! isInitialized_ ) { return false ; } LOGGER_ . trace ( "{}: invalidated" , this ) ; isCompleted_ = false ; isInitialized_ = false ; return true ; }


Input: Invalidates this stage and all subsequent stages if not already done so [CODESPLIT] public void invalidateRecursive ( ) { Queue < AbstractReasonerStage > toInvalidate_ = new LinkedList < AbstractReasonerStage > ( ) ; toInvalidate_ . add ( this ) ; AbstractReasonerStage next ; while ( ( next = toInvalidate_ . poll ( ) ) != null ) { if ( next . invalidate ( ) ) { for ( AbstractReasonerStage postStage : next . postStages_ ) { toInvalidate_ . add ( postStage ) ; } } } }


Input: Compute the hash for an entity node . This method implements a simple cache for nodes with unusually large numbers of members . This mainly covers the case where a huge number of classes is equal to owl : Nothing due to modelling errors . [CODESPLIT] @ Override public int hash ( Node < ? extends ElkEntity > node ) { if ( node . size ( ) >= cacheNodeMemberNo ) { if ( hashCache . containsKey ( node ) ) { return hashCache . get ( node ) ; } // else int hash = HashGenerator . combineMultisetHash ( true , node , elkEntityHasher ) ; hashCache . put ( node , hash ) ; return hash ; } // else return HashGenerator . combineMultisetHash ( true , node , elkEntityHasher ) ; }


Input:
Prunes { @link #toAdd_ } . <p > <strong > { @code taxonomy_ } must not be { @code null } !< / strong > [CODESPLIT] private int pruneToAdd ( ) { final Iterator < IndexedIndividual > iter = toAdd_ . iterator ( ) ; int size = 0 ; while ( iter . hasNext ( ) ) { final IndexedIndividual ind = iter . next ( ) ; /* @formatter:off
			 *
			 * Should be pruned when:
			 * it is not in ontology, or
			 * it has types in taxonomy.
			 *
			 * @formatter:on
			 */ if ( ! ind . occurs ( ) ) { iter . remove ( ) ; continue ; } // else final Context context = saturationState_ . getContext ( ind ) ; if ( context == null || ! context . isInitialized ( ) || ! context . isSaturated ( ) ) { // it is not saturated. size ++ ; continue ; } // else final InstanceNode < ElkClass , ElkNamedIndividual > node = taxonomy_ . getInstanceNode ( ind . getElkEntity ( ) ) ; if ( node == null ) { // it is not in taxonomy size ++ ; continue ; } // else if ( ! node . getDirectTypeNodes ( ) . isEmpty ( ) ) { iter . remove ( ) ; continue ; } // else size ++ ; } return size ; }


Input:
Returns collection that contains at least all individuals that are in ontology but either are removed from taxonomy or their type nodes in taxonomy were removed . [CODESPLIT] Collection < IndexedIndividual > getToAdd ( ) { if ( taxonomy_ == null ) { // No individual can be pruned. return toAdd_ ; } // else final int size = pruneToAdd ( ) ; /*
		 * since getting the size of the queue is a linear operation, use the
		 * computed size
		 */ return Operations . getCollection ( toAdd_ , size ) ; }


Input:
Prunes { @link #toRemove_ } . <p > <strong > { @code taxonomy_ } must not be { @code null } !< / strong > [CODESPLIT] private int pruneToRemove ( ) { final Iterator < IndexedIndividual > iter = toRemove_ . iterator ( ) ; int size = 0 ; while ( iter . hasNext ( ) ) { final IndexedIndividual cls = iter . next ( ) ; /* @formatter:off
			 *
			 * Should be pruned when
			 * it is not in taxonomy.
			 *
			 * @formatter:on
			 */ final InstanceNode < ElkClass , ElkNamedIndividual > node = taxonomy_ . getInstanceNode ( cls . getElkEntity ( ) ) ; if ( node == null ) { iter . remove ( ) ; continue ; } // else size ++ ; } return size ; }