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();
  }

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
(
)
;
}

Creates process responsible for running lessc shell command by reading the file content from the sourceFilePath

@param sourceFile
the source path of the file from where the lessc will read the less file.
@throws IOException
when the process execution fails.


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()]);
  }

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
(
)
]
)
;
}

Parses out the properties of a selector's body.

@param contents The body; for example, "border: solid 1px red; color: blue;"

Parses out the properties of a selector s body .


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()]);
  }

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
(
)
]
)
;
}

Return an array of the data for tasks performed.

Return an array of the data for tasks performed .


private String getCompilationCommand(final String input) {
    return String.format("compilerWrapper.compile(%s, %s)", WroUtil.toJSMultiLineString(input),
        ecmaScriptVersion);
  }

private
String
getCompilationCommand
(
final
String
input
)
{
return
String
.
format
(
"compilerWrapper.compile(%s, %s)"
,
WroUtil
.
toJSMultiLineString
(
input
)
,
ecmaScriptVersion
)
;
}

Creates compilation command for provided typescript input.

@param input
the TypeScript to compile into js.
@return compilation command.

Creates compilation command for provided typescript input .


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));
    }
  }

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
)
)
;
}
}

Parse header value & puts the found values in headersMap field.

@param header
value to parse.

Parse header value & puts the found values in headersMap field .


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");
  }

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" ) ; }

Populates the map with headers used to disable cache.

Populates the map with headers used to disable cache .


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);
  }

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
!=
)
{
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
)
;
}

Retrieve pathInfo from a given location.

@param request
@param location
where to search contextPath.
@return pathInfo value.

Retrieve pathInfo from a given location .


public static String getServletPathFromLocation(final HttpServletRequest request, final String location) {
    return location.replace(getPathInfoFromLocation(request, location), StringUtils.EMPTY);
  }

public static String getServletPathFromLocation ( final HttpServletRequest request , final String location ) { return location . replace ( getPathInfoFromLocation ( request , location ) , StringUtils . EMPTY ) ; }

Retrieve servletPath from a given location.

@param location
where to search the servletPath.
@return ServletPath string value.

Retrieve servletPath from a given location .


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;
  }

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 ; }

Utility used to verify that requestURI matches provided path


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);
    }
  }

public
static
String
loadRegexpWithKey
(
final
String
key
)
{
InputStream
stream
=
;
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
)
;
}
}

Load the regular expression stored in in regexp.properties resource file.

@param key
the key of the regexp to load.
@return regular expression value.

Load the regular expression stored in in regexp . properties resource file .


public static void safeCopy(final Reader reader, final Writer writer)
      throws IOException {
    try {
      IOUtils.copy(reader, writer);
    } finally {
      IOUtils.closeQuietly(reader);
      IOUtils.closeQuietly(writer);
    }
  }

public static void safeCopy ( final Reader reader , final Writer writer ) throws IOException { try { IOUtils . copy ( reader , writer ) ; } finally { IOUtils . closeQuietly ( reader ) ; IOUtils . closeQuietly ( writer ) ; } }

Copy and close the reader and writer streams.

@param reader
The source stream.
@param writer
The destination stream.
@throws IOException
If content cannot be copy.

Copy and close the reader and writer streams .


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);
    }
  }

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 ) ; } }

Creates a temp file which has a certain extension.

@param extension
of the created temp file.

Creates a temp file which has a certain extension .


public static final String cleanImageUrl(final String imageUrl) {
    notNull(imageUrl);
    return imageUrl.replace('\'', ' ').replace('\"', ' ').trim();
  }

public static final String cleanImageUrl ( final String imageUrl ) { notNull ( imageUrl ) ; return imageUrl . replace ( ' ' , ' ' ) . replace ( ' ' , ' ' ) . trim ( ) ; }

Cleans the image url by trimming result and removing \' or \" characters if such exists.

@param imageUrl
to clean.
@return cleaned image URL.

Cleans the image url by trimming result and removing \ or \ characters if such exists .


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);
  }

Sets the attribute into the servlet context. The name of the attribute will be computed for you.

Sets the attribute into the servlet context . The name of the attribute will be computed for you .


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();
  }

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
(
)
;
}

Generate the dataUri as string associated to the passed InputStream with encoding & type based on provided
fileName.

Generate the dataUri as string associated to the passed InputStream with encoding & type based on provided fileName .


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());
  }

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
(
)
)
;
}

Generates a data URI from a byte array and outputs to the given writer.

@param bytes
The array of bytes to output to the data URI.
@param out
Where to output the data URI.
@param mimeType
The MIME type to specify in the data URI.
@throws java.io.IOException

Generates a data URI from a byte array and outputs to the given writer .


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);
  }

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 ) ; }

Associate a context with the CURRENT request cycle.

@param context {@link Context} to set.

Associate a context with the CURRENT request cycle .


public static void unset() {
    final String correlationId = CORRELATION_ID.get();
    if (correlationId != null) {
      CONTEXT_MAP.remove(correlationId);
    }
    CORRELATION_ID.remove();
  }

public static void unset ( ) { final String correlationId = CORRELATION_ID . get ( ) ; if ( correlationId != null ) { CONTEXT_MAP . remove ( correlationId ) ; } CORRELATION_ID . remove ( ) ; }


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());
    }
  }

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
,
)
;
}
resourceChangeDetector
.
reset
(
)
;
}
catch
(
final
Exception
e
)
{
onException
(
e
)
;
}
finally
{
watch
.
stop
(
)
;
LOG
.
debug
(
"resource watcher info: {}"
,
watch
.
prettyPrint
(
)
)
;
}
}

Check if resources from a group were changed. If a change is detected, the changeListener will be invoked.

@param cacheKey
the cache key which was requested. The key contains the groupName which has to be checked for changes.

Check if resources from a group were changed . If a change is detected the changeListener will be invoked .


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);
  }


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);
    }
  }

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 ) ; } }

Will check if a given resource was changed and will invoke the appropriate callback.

Will check if a given resource was changed and will invoke the appropriate callback .


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();
    }
  }

Updates the hash associated with the resource for a give groupName.

@param hash
the most recent computed hash.
@param groupName
name of the group for which the change of resource is detected.

Updates the hash associated with the resource for a give groupName .


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;
  }

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
;
}

Check if the group has at least one resource of some type.

@param resourceType
type of the searched resource.
@return true if at least one resource of some type exists.

Check if the group has at least one resource of some type .


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;
  }

Creates process responsible for running tsc shell command by reading the file content from the sourceFilePath

@param sourceFile
the source path of the file from where the tsc will read the typescript file.
@param destFile
the destination of the compiled file.
@throws IOException
when the process execution fails.


public static String encodeObject(final java.io.Serializable serializableObject)
    throws java.io.IOException {
    return encodeObject(serializableObject, NO_OPTIONS);
  }

public static String encodeObject ( final java . io . Serializable serializableObject ) throws java . io . IOException { return encodeObject ( serializableObject , NO_OPTIONS ) ; }

Serializes an object and returns the Base64-encoded version of that serialized object.

As of v 2.3, if the object cannot be serialized or there is another error, the method will throw an
java.io.IOException. This is new to v2.3! In earlier versions, it just returned a null value, but in
retrospect that's a pretty poor way to handle it.

The object is not GZip-compressed before being encoded.

@param serializableObject The object to encode
@return The Base64-encoded object
@throws java.io.IOException if there is an error
@throws NullPointerException if serializedObject is null
@since 1.4

Serializes an object and returns the Base64 - encoded version of that serialized object .


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);
    }
  }

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
)
;
}
}


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();
  }

Recursive method. Add the parsed element group to the group collection. If the group contains group-ref element,
parse recursively this group.

@param element
Group Element to parse.
@param groups
list of parsed groups where the parsed group is added..
@return list of resources associated with this resource

Recursive method . Add the parsed element group to the group collection . If the group contains group - ref element parse recursively this group .


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;
  }

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 ; }

Creates a group and all its associated resources.

@param element
Group element to parse.
@return fully initialized group

Creates a group and all its associated resources .


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);
    }
  }

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
)
!=
)
{
final
Resource
resource
=
createResource
(
resourceElement
)
;
LOG
.
debug
(
"\t\tadding resource: {}"
,
resource
)
;
resources
.
add
(
resource
)
;
}
}

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.

@param resources
list of parsed resources where the parsed resource is added.

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 .


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();
  }

private
Collection
<
Resource
>
getResourcesForGroup
(
final
String
groupName
)
{
final
WroModelInspector
modelInspector
=
new
WroModelInspector
(
model
)
;
final
Group
foundGroup
=
modelInspector
.
getGroupByName
(
groupName
)
;
if
(
foundGroup
==
)
{
final
Element
groupElement
=
allGroupElements
.
get
(
groupName
)
;
if
(
groupElement
==
)
{
throw
new
WroRuntimeException
(
"Invalid group-ref: "
+
groupName
)
;
}
return
parseGroup
(
groupElement
)
;
}
return
foundGroup
.
getResources
(
)
;
}

Search for all resources for a group with a given name.

Search for all resources for a group with a given name .


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");
			}
		}
	}

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"
)
;
}
}
}

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.

@param logger
@param priority

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 .


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;
		}
	}

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 ; } }

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.

@param timerName
the name of the timer
@param todoFlags
@param threadId
of the thread to track, or 0 if only system clock should be
tracked
@return CPU time if timer existed and was running, and -1 otherwise

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 .


public static ElkTimer getNamedTimer(String timerName, int todoFlags) {
		return getNamedTimer(timerName, todoFlags, Thread.currentThread()
				.getId());
	}

public static ElkTimer getNamedTimer ( String timerName , int todoFlags ) { return getNamedTimer ( timerName , todoFlags , Thread . currentThread ( ) . getId ( ) ) ; }

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.

@param timerName
the name of the timer
@param todoFlags
@return timer

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 .


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;
	}

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
!=
)
{
return
previous
;
}
// else
return
key
;
}

Get a timer of the given string name for the given thread. If no such
timer exists yet, then it will be newly created.

@param timerName
the name of the timer
@param todoFlags
@param threadId
of the thread to track, or 0 if only system clock should be
tracked
@return timer

Get a timer of the given string name for the given thread . If no such timer exists yet then it will be newly created .


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);
		}
	}


private void wakeUpWorkers() {
		if (!workersWaiting_) {
			return;
		}
		stopWorkersLock_.lock();
		try {
			workersWaiting_ = false;
			thereAreContextsToProcess_.signalAll();
		} finally {
			stopWorkersLock_.unlock();
		}
	}

private void wakeUpWorkers ( ) { if ( ! workersWaiting_ ) { return ; } stopWorkersLock_ . lock ( ) ; try { workersWaiting_ = false ; thereAreContextsToProcess_ . signalAll ( ) ; } finally { stopWorkersLock_ . unlock ( ) ; } }

waking up all workers waiting for new saturated contexts


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);
	}

Updates the counter for processed contexts and jobs

@param snapshotFinishedWorkers


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
		}

	}

Check if the counter for saturated contexts and processed jobs can be
increased and post-process the finished jobs

@throws InterruptedException

Check if the counter for saturated contexts and processed jobs can be increased and post - process the finished jobs


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;
		}
	}

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 ; } }

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.

@param counter
the counter that should be updated
@param value
the value to which the counter should be updated
@return {@code true} if the counter has been updated

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 .


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;
	}

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
;
}

The default implementation of all methods

@param rule
@param premise
@param premises
@param producer
@return


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));

	}

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.

@param property
The property that should be inserted into taxonomy.

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 .


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);

	}

Flushes index, if needed, and completes loading if there is new input.
Incremental mode should be changed only during completing loading.

@throws ElkException

Flushes index if needed and completes loading if there is new input . Incremental mode should be changed only during completing loading .


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();
		}

	}

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 ( ) ; } }

Ensures that saturation is restored and taxonomies are cleaned. Also
invalidates stages that depend on the saturation if it changed.

@throws ElkException

Ensures that saturation is restored and taxonomies are cleaned . Also invalidates stages that depend on the saturation if it changed .


public synchronized boolean isInconsistent() throws ElkException {

		restoreConsistencyCheck();

		if (!consistencyCheckingState.isInconsistent()) {
			incompleteness_.log(incompleteness_
					.getIncompletenessMonitorForClassification());
		}
		return consistencyCheckingState.isInconsistent();
	}

Check consistency of the current ontology, if this has not been done yet.

@return {@code true} if the ontology is inconsistent, that is,
unsatisfiable.
@throws ElkException
if the reasoning process cannot be completed successfully

Check consistency of the current ontology if this has not been done yet .


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();
	}

Complete the taxonomy computation stage and the stages it depends on, if
it has not been done yet.

@return the class taxonomy implied by the current ontology
@throws ElkInconsistentOntologyException
if the ontology is inconsistent
@throws ElkException
if the reasoning process cannot be completed successfully

Complete the taxonomy computation stage and the stages it depends on if it has not been done yet .


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();
	}

Completes instance taxonomy computation stage and the stages that it
depends on, if this has not been done yet.

@return the instance taxonomy implied by the current ontology
@throws ElkInconsistentOntologyException
if the ontology is inconsistent
@throws ElkException
if the reasoning process cannot be completed successfully

Completes instance taxonomy computation stage and the stages that it depends on if this has not been done yet .


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);
			}

		};

	}

Explains why an ontology inconsistency is entailed. If it is not
entailed, the returned proof is empty.

@param atMostOne
Whether at most one explanation should be returned.
@return An evidence of entailment of ontology inconsistency.

Explains why an ontology inconsistency is entailed . If it is not entailed the returned proof is empty .


@Override
	public boolean preExecute() {
		if (isInitialized_)
			return false;
		LOGGER_.trace("{}: initialized", this);
		this.workerNo = reasoner.getNumberOfWorkers();
		return isInitialized_ = true;
	}

@
Override
public
boolean
preExecute
(
)
{
if
(
isInitialized_
)
return
false
;
LOGGER_
.
trace
(
"{}: initialized"
,
this
)
;
this
.
workerNo
=
reasoner
.
getNumberOfWorkers
(
)
;
return
isInitialized_
=
true
;
}

Initialize the parameters of the computation for this stage; this is the
first thing to be done before stage is executed

@return {@code true} if the operation is successful

Initialize the parameters of the computation for this stage ; this is the first thing to be done before stage is executed


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);
				}
			}
		}
	}

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 ) ; } } } }

Invalidates this stage and all subsequent stages if not already done so


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);
	}

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.

@return 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.

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 .


Collection<IndexedIndividual> getToRemove() {
		if (taxonomy_ == null) {// TODO: Never set taxonomy_ to null !!!
			// no individuals are in taxonomy
			toRemove_.clear();
			return Collections.emptyList();
		}
		// else
		final int size = pruneToRemove();
		/*
		 * since getting the size of the queue is a linear operation, use the
		 * computed size
		 */
		return Operations.getCollection(toRemove_, size);
	}

Returns collection that contains at least all individuals that are in
taxonomy, but either are removed from ontology or their context became
not saturated.

@return collection that contains at least all individuals that are in
taxonomy, but either are removed from ontology or their context
became not saturated.

Returns collection that contains at least all individuals that are in taxonomy but either are removed from ontology or their context became not saturated .


private static UnsupportedOperationException unsupportedOwlApiMethod(
			String method) {
		String message = "OWL API reasoner method is not implemented: " + method
				+ ".";
		/*
		 * TODO: The method String can be used to create more specific message
		 * types, but with the current large amount of unsupported methods and
		 * non-persistent settings for ignoring them, we better use only one
		 * message type to make it easier to ignore them.
		 */
		LoggerWrap.log(LOGGER_, LogLevel.WARN, MARKER_UNSUPPORTED_METHOD_,
				message);

		return new UnsupportedOperationException(message);
	}

Logs a warning message for unsupported OWL API method

@param method
the method which is not supported
@return the {@link UnsupportedOperationException} saying that this method
is not supported


static <E> void remove(E[] d, int pos) {
		for (;;) {
			int next = getMovedPosition(d, pos);
			E moved = d[pos] = d[next];
			if (moved == null)
				return;
			// else
			pos = next;
		}
	}

static
<
E
>
void
remove
(
E
[
]
d
,
int
pos
)
{
for
(
;
;
)
{
int
next
=
getMovedPosition
(
d
,
pos
)
;
E
moved
=
d
[
pos
]
=
d
[
next
]
;
if
(
moved
==
)
return
;
// else
pos
=
next
;
}
}

Removes the element at the given position of the table shifting, if
necessary, other elements so that all elements can be found by linear
probing.

@param d
the array of the elements
@param pos
the position of data at which to delete the element

Removes the element at the given position of the table shifting if necessary other elements so that all elements can be found by linear probing .


static <K, V> void remove(K[] k, V[] v, int pos) {
		for (;;) {
			int next = getMovedPosition(k, pos);
			K moved = k[pos] = k[next];
			v[pos] = v[next];
			if (moved == null)
				return;
			// else
			pos = next;
		}
	}

static
<
K
,
V
>
void
remove
(
K
[
]
k
,
V
[
]
v
,
int
pos
)
{
for
(
;
;
)
{
int
next
=
getMovedPosition
(
k
,
pos
)
;
K
moved
=
k
[
pos
]
=
k
[
next
]
;
v
[
pos
]
=
v
[
next
]
;
if
(
moved
==
)
return
;
// else
pos
=
next
;
}
}

Removes the element at the given position of the table and the
corresponding value at the same position, shifting, if necessary, other
elements and values so that all elements can be found by linear probing.

@param d
the array of the elements
@param pos
the position of data at which to delete the element

Removes the element at the given position of the table and the corresponding value at the same position shifting if necessary other elements and values so that all elements can be found by linear probing .


static <E> int getMovedPosition(E[] d, int del) {
		int j = del;
		for (;;) {
			if (++j == d.length)
				j = 0;
			// invariant: interval ]del, j] contains only non-null elements
			// whose index is in ]del, j]
			E test = d[j];
			if (test == null)
				return j;
			int k = getIndex(test, d.length);
			// check if k is in ]del, j] (this interval can wrap over)
			if ((del < j) ? (del < k) && (k <= j) : (del < k) || (k <= j))
				// the test element should not be shifted
				continue;
			// else it should be shifted
			return j;
		}

	}

Finds the position of the next element starting from the given position
that would not be found by linear probing if the element at the given
position are deleted. This should be the element whose index is smaller
than this position.

@param d
@param del
@return

Finds the position of the next element starting from the given position that would not be found by linear probing if the element at the given position are deleted . This should be the element whose index is smaller than this position .


static <E> boolean contains(E[] d, Object o) {
		int pos = getPosition(d, o);
		if (d[pos] == null)
			return false;
		// else
		return true;
	}

static
<
E
>
boolean
contains
(
E
[
]
d
,
Object
o
)
{
int
pos
=
getPosition
(
d
,
o
)
;
if
(
d
[
pos
]
==
)
return
false
;
// else
return
true
;
}

Tests if the set represented by given data array contains a given object.

@param d
the elements representing the set
@param o
the object to be tested on inclusion in the set
@return {@code true} if the object occurs in the array and {@code false}
otherwise

Tests if the set represented by given data array contains a given object .


static <E> boolean add(E[] d, E e) {
		int pos = getPosition(d, e);
		if (d[pos] == null) {
			d[pos] = e;
			return true;
		}
		// else the element is already there
		return false;
	}

static
<
E
>
boolean
add
(
E
[
]
d
,
E
e
)
{
int
pos
=
getPosition
(
d
,
e
)
;
if
(
d
[
pos
]
==
)
{
d
[
pos
]
=
e
;
return
true
;
}
// else the element is already there
return
false
;
}

Adds the element to the set represented by given data array, if it did
not contain there already.

@param d
the elements of the set
@param e
the element to be added to the set
@return {@code true} if the set has changed (the element is added),
{@code false} otherwise

Adds the element to the set represented by given data array if it did not contain there already .


public final void checkOccurrenceNumbers() {
		if (LOGGER_.isTraceEnabled())
			LOGGER_.trace(toString() + " occurences: "
					+ printOccurrenceNumbers());
		if (positiveOccurrenceNo < 0 || negativeOccurrenceNo < 0)
			throw new ElkUnexpectedIndexingException(toString()
					+ " has a negative occurrence: " + printOccurrenceNumbers());
	}

public
final
void
checkOccurrenceNumbers
(
)
{
if
(
LOGGER_
.
isTraceEnabled
(
)
)
LOGGER_
.
trace
(
toString
(
)
+
" occurences: "
+
printOccurrenceNumbers
(
)
)
;
if
(
positiveOccurrenceNo
<
0
||
negativeOccurrenceNo
<
0
)
throw
new
ElkUnexpectedIndexingException
(
toString
(
)
+
" has a negative occurrence: "
+
printOccurrenceNumbers
(
)
)
;
}

verifies that occurrence numbers are not negative


public synchronized void add(ClassConclusionTimer timer) {
		this.timeComposedSubsumers += timer.timeComposedSubsumers;
		this.timeDecomposedSubsumers += timer.timeDecomposedSubsumers;
		this.timeBackwardLinks += timer.timeBackwardLinks;
		this.timeForwardLinks += timer.timeForwardLinks;
		this.timeContradictions += timer.timeContradictions;
		this.timePropagations += timer.timePropagations;
		this.timeDisjointSubsumers += timer.timeDisjointSubsumers;
		this.timeContextInitializations += timer.timeContextInitializations;
		this.timeSubContextInitializations += timer.timeSubContextInitializations;
	}

public synchronized void add ( ClassConclusionTimer timer ) { this . timeComposedSubsumers += timer . timeComposedSubsumers ; this . timeDecomposedSubsumers += timer . timeDecomposedSubsumers ; this . timeBackwardLinks += timer . timeBackwardLinks ; this . timeForwardLinks += timer . timeForwardLinks ; this . timeContradictions += timer . timeContradictions ; this . timePropagations += timer . timePropagations ; this . timeDisjointSubsumers += timer . timeDisjointSubsumers ; this . timeContextInitializations += timer . timeContextInitializations ; this . timeSubContextInitializations += timer . timeSubContextInitializations ; }

Adds all timers of the argument to the corresponding counters of this
object. The timers should not be directly modified other than using this
method during this operation. The timers in the argument will be reseted
after this operation.

@param timer
the object which counters should be added

Adds all timers of the argument to the corresponding counters of this object . The timers should not be directly modified other than using this method during this operation . The timers in the argument will be reseted after this operation .


public synchronized void add(RuleApplicationTimer timer) {
		timeOwlThingContextInitRule += timer.timeOwlThingContextInitRule;
		timeRootContextInitializationRule += timer.timeRootContextInitializationRule;
		timeDisjointSubsumerFromMemberRule += timer.timeDisjointSubsumerFromMemberRule;
		timeContradictionFromNegationRule += timer.timeContradictionFromNegationRule;
		timeObjectIntersectionFromFirstConjunctRule += timer.timeObjectIntersectionFromFirstConjunctRule;
		timeObjectIntersectionFromSecondConjunctRule += timer.timeObjectIntersectionFromSecondConjunctRule;
		timeSuperClassFromSubClassRule += timer.timeSuperClassFromSubClassRule;
		timePropagationFromExistentialFillerRule += timer.timePropagationFromExistentialFillerRule;
		timeObjectUnionFromDisjunctRule += timer.timeObjectUnionFromDisjunctRule;
		timeBackwardLinkChainFromBackwardLinkRule += timer.timeBackwardLinkChainFromBackwardLinkRule;
		timeReflexiveBackwardLinkCompositionRule += timer.timeReflexiveBackwardLinkCompositionRule;
		timeNonReflexiveBackwardLinkCompositionRule += timer.timeNonReflexiveBackwardLinkCompositionRule;
		timeSubsumerBackwardLinkRule += timer.timeSubsumerBackwardLinkRule;
		timeContradictionOverBackwardLinkRule += timer.timeContradictionOverBackwardLinkRule;
		timeContradictionPropagationRule += timer.timeContradictionPropagationRule;
		timeContradictionCompositionRule += timer.timeContradictionCompositionRule;
		timeIndexedObjectIntersectionOfDecomposition += timer.timeIndexedObjectIntersectionOfDecomposition;
		timeIndexedObjectSomeValuesFromDecomposition += timer.timeIndexedObjectSomeValuesFromDecomposition;
		timeIndexedObjectComplementOfDecomposition += timer.timeIndexedObjectComplementOfDecomposition;
		timeIndexedObjectHasSelfDecomposition += timer.timeIndexedObjectHasSelfDecomposition;
		timeContradictionFromOwlNothingRule += timer.timeContradictionFromOwlNothingRule;
		timeSubsumerPropagationRule += timer.timeSubsumerPropagationRule;
		timePropagationInitializationRule += timer.timePropagationInitializationRule;
		timeBackwardLinkFromForwardLinkRule += timer.timeBackwardLinkFromForwardLinkRule;
		timeComposedFromDecomposedSubsumerRule += timer.timeComposedFromDecomposedSubsumerRule;
		timeIndexedClassDecompositionRule += timer.timeIndexedClassDecompositionRule;
		timeIndexedClassFromDefinitionRule += timer.timeIndexedClassFromDefinitionRule;
		timeEquivalentClassFirstFromSecondRule += timer.timeEquivalentClassFirstFromSecondRule;
		timeEquivalentClassSecondFromFirstRule += timer.timeEquivalentClassSecondFromFirstRule;
	}

Add the values the corresponding values of the given timer

@param timer


private static <K, V> V putKeyValue(K[] keys, V[] values, K key, V value) {
		int pos = LinearProbing.getPosition(keys, key);
		if (keys[pos] == null) {
			keys[pos] = key;
			values[pos] = value;
			return null;
		}
		// else
		V oldValue = values[pos];
		values[pos] = value;
		return oldValue;
	}

private
static
<
K
,
V
>
V
putKeyValue
(
K
[
]
keys
,
V
[
]
values
,
K
key
,
V
value
)
{
int
pos
=
LinearProbing
.
getPosition
(
keys
,
key
)
;
if
(
keys
[
pos
]
==
)
{
keys
[
pos
]
=
key
;
values
[
pos
]
=
value
;
return
;
}
// else
V
oldValue
=
values
[
pos
]
;
values
[
pos
]
=
value
;
return
oldValue
;
}

Associates the given key with the given value in the map defined by the
keys and value arrays. If an entry with the key equal to the given one
already exists in the map, the value for this key will be overwritten
with the given value.

@param keys
the keys of the map
@param values
the values of the map
@param key
the key of the entry
@param value
the value of the entry
@return the previous value associated with the key or <tt>null</tt> if
there was no such a previous value.

Associates the given key with the given value in the map defined by the keys and value arrays . If an entry with the key equal to the given one already exists in the map the value for this key will be overwritten with the given value .


private static <K, V> V removeEntry(K[] keys, V[] values, Object key) {
		int pos = LinearProbing.getPosition(keys, key);
		if (keys[pos] == null)
			return null;
		// else
		V result = values[pos];
		LinearProbing.remove(keys, values, pos);
		return result;
	}

private
static
<
K
,
V
>
V
removeEntry
(
K
[
]
keys
,
V
[
]
values
,
Object
key
)
{
int
pos
=
LinearProbing
.
getPosition
(
keys
,
key
)
;
if
(
keys
[
pos
]
==
)
return
;
// else
V
result
=
values
[
pos
]
;
LinearProbing
.
remove
(
keys
,
values
,
pos
)
;
return
result
;
}

Remove the entry in the keys and values such that the key of the entry is
equal to the given object according to the equality function.

@param keys
the array of keys
@param values
the arrays of values
@param key
the key for which to delete the entry
@return the value of the deleted entry, <tt>null</tt> if nothing has been
deleted

Remove the entry in the keys and values such that the key of the entry is equal to the given object according to the equality function .


private void enlarge() {
		int oldCapacity = keys.length;
		if (oldCapacity == LinearProbing.MAXIMUM_CAPACITY)
			throw new IllegalArgumentException(
					"Map cannot grow beyond capacity: "
							+ LinearProbing.MAXIMUM_CAPACITY);
		K oldKeys[] = keys;
		V oldValues[] = values;
		int newCapacity = oldCapacity << 1;
		@SuppressWarnings("unchecked")
		K newKeys[] = (K[]) new Object[newCapacity];
		@SuppressWarnings("unchecked")
		V newValues[] = (V[]) new Object[newCapacity];
		for (int i = 0; i < oldCapacity; i++) {
			K key = oldKeys[i];
			if (key != null)
				putKeyValue(newKeys, newValues, key, oldValues[i]);
		}
		this.keys = newKeys;
		this.values = newValues;
	}

private
void
enlarge
(
)
{
int
oldCapacity
=
keys
.
length
;
if
(
oldCapacity
==
LinearProbing
.
MAXIMUM_CAPACITY
)
throw
new
IllegalArgumentException
(
"Map cannot grow beyond capacity: "
+
LinearProbing
.
MAXIMUM_CAPACITY
)
;
K
oldKeys
[
]
=
keys
;
V
oldValues
[
]
=
values
;
int
newCapacity
=
oldCapacity
<<
1
;
@
SuppressWarnings
(
"unchecked"
)
K
newKeys
[
]
=
(
K
[
]
)
new
Object
[
newCapacity
]
;
@
SuppressWarnings
(
"unchecked"
)
V
newValues
[
]
=
(
V
[
]
)
new
Object
[
newCapacity
]
;
for
(
int
i
=
0
;
i
<
oldCapacity
;
i
++
)
{
K
key
=
oldKeys
[
i
]
;
if
(
key
!=
)
putKeyValue
(
newKeys
,
newValues
,
key
,
oldValues
[
i
]
)
;
}
this
.
keys
=
newKeys
;
this
.
values
=
newValues
;
}


private void shrink() {
		int oldCapacity = keys.length;
		if (oldCapacity <= LinearProbing.DEFAULT_INITIAL_CAPACITY)
			return;
		K oldKeys[] = keys;
		V oldValues[] = values;
		int newCapacity = oldCapacity >> 1;
		@SuppressWarnings("unchecked")
		K newKeys[] = (K[]) new Object[newCapacity];
		@SuppressWarnings("unchecked")
		V newValues[] = (V[]) new Object[newCapacity];
		for (int i = 0; i < oldCapacity; i++) {
			K key = oldKeys[i];
			if (key != null)
				putKeyValue(newKeys, newValues, key, oldValues[i]);
		}
		this.keys = newKeys;
		this.values = newValues;
	}

private void shrink ( ) { int oldCapacity = keys . length ; if ( oldCapacity <= LinearProbing . DEFAULT_INITIAL_CAPACITY ) return ; K oldKeys [ ] = keys ; V oldValues [ ] = values ; int newCapacity = oldCapacity >> 1 ; @ SuppressWarnings ( "unchecked" ) K newKeys [ ] = ( K [ ] ) new Object [ newCapacity ] ; @ SuppressWarnings ( "unchecked" ) V newValues [ ] = ( V [ ] ) new Object [ newCapacity ] ; for ( int i = 0 ; i < oldCapacity ; i ++ ) { K key = oldKeys [ i ] ; if ( key != null ) putKeyValue ( newKeys , newValues , key , oldValues [ i ] ) ; } this . keys = newKeys ; this . values = newValues ; }


public void saveConfiguration(File configOnDisk, BaseConfiguration config)
			throws ConfigurationException, IOException {
		/*
		 * Unfortunately, we can't directly write the config on disk because the
		 * parameters in it may be just a subset of those on disk. So we load it
		 * first (alternatively one may use a singleton, which I typically try
		 * to avoid). It should work reasonably well unless there're too many
		 * parameters (in which case we should think of a mini key-value store).
		 */
		InputStream stream = null;
		BaseConfiguration loadedConfig = null;
		Properties diskProps = new Properties();

		try {
			stream = new FileInputStream(configOnDisk);
			loadedConfig = getConfiguration(stream, "", config.getClass());
			// copy parameters
			copyParameters(loadedConfig, diskProps);
		} catch (Throwable e) {
			LOGGER_.info("Overwriting configuration since it can't be loaded (perhaps doesn't exist?)");
		} finally {
			IOUtils.closeQuietly(stream);
		}

		copyParameters(config, diskProps);
		// now save it to the file
		saveProperties(diskProps, configOnDisk);
	}

Not a thread-safe method. Shouldn't be invoked concurrently.

@param configOnDisk
@param config
@throws ConfigurationException
@throws IOException

Not a thread - safe method . Shouldn t be invoked concurrently .


protected static void printDeclarations(Taxonomy<ElkClass> classTaxonomy,
			ElkObject.Factory objectFactory, Appendable writer)
			throws IOException {

		List<ElkClass> classes = new ArrayList<ElkClass>(classTaxonomy
				.getNodes().size() * 2);

		for (TaxonomyNode<ElkClass> classNode : classTaxonomy.getNodes()) {
			for (ElkClass clazz : classNode) {
				if (!clazz.getIri().equals(PredefinedElkIris.OWL_THING)
						&& !clazz.getIri()
								.equals(PredefinedElkIris.OWL_NOTHING)) {
					classes.add(clazz);

				}
			}
		}

		Collections.sort(classes, CLASS_COMPARATOR);

		for (ElkClass clazz : classes) {
			ElkDeclarationAxiom decl = objectFactory.getDeclarationAxiom(clazz);
			OwlFunctionalStylePrinter.append(writer, decl, true);
			writer.append('\n');
		}
	}

protected static void printDeclarations ( Taxonomy < ElkClass > classTaxonomy , ElkObject . Factory objectFactory , Appendable writer ) throws IOException { List < ElkClass > classes = new ArrayList < ElkClass > ( classTaxonomy . getNodes ( ) . size ( ) * 2 ) ; for ( TaxonomyNode < ElkClass > classNode : classTaxonomy . getNodes ( ) ) { for ( ElkClass clazz : classNode ) { if ( ! clazz . getIri ( ) . equals ( PredefinedElkIris . OWL_THING ) && ! clazz . getIri ( ) . equals ( PredefinedElkIris . OWL_NOTHING ) ) { classes . add ( clazz ) ; } } } Collections . sort ( classes , CLASS_COMPARATOR ) ; for ( ElkClass clazz : classes ) { ElkDeclarationAxiom decl = objectFactory . getDeclarationAxiom ( clazz ) ; OwlFunctionalStylePrinter . append ( writer , decl , true ) ; writer . append ( ' ' ) ; } }

Prints class declarations

@param classTaxonomy
@param objectFactory
@param writer
@throws IOException


public static <T extends ElkEntity, I extends ElkEntity, TN extends GenericTypeNode<T, I, TN, IN>, IN extends GenericInstanceNode<T, I, TN, IN>>
			Set<? extends IN> getAllInstanceNodes(final GenericTypeNode<T, I, TN, IN> node) {
		return TaxonomyNodeUtils.collectFromAllReachable(
				node.getDirectSubNodes(),
				node.getDirectInstanceNodes(),
				new Operations.Functor<GenericTypeNode<T, I, TN, IN>, Set<? extends GenericTypeNode<T, I, TN, IN>>>() {
					@Override
					public Set<? extends TN> apply(final GenericTypeNode<T, I, TN, IN> node) {
						return node.getDirectSubNodes();
					}
				},
				new Operations.Functor<GenericTypeNode<T, I, TN, IN>, Set<? extends IN>>() {
					@Override
					public Set<? extends IN> apply(final GenericTypeNode<T, I, TN, IN> node) {
						return node.getDirectInstanceNodes();
					}
				});
	}

public static < T extends ElkEntity , I extends ElkEntity , TN extends GenericTypeNode < T , I , TN , IN > , IN extends GenericInstanceNode < T , I , TN , IN > > Set < ? extends IN > getAllInstanceNodes ( final GenericTypeNode < T , I , TN , IN > node ) { return TaxonomyNodeUtils . collectFromAllReachable ( node . getDirectSubNodes ( ) , node . getDirectInstanceNodes ( ) , new Operations . Functor < GenericTypeNode < T , I , TN , IN > , Set < ? extends GenericTypeNode < T , I , TN , IN > > > ( ) { @ Override public Set < ? extends TN > apply ( final GenericTypeNode < T , I , TN , IN > node ) { return node . getDirectSubNodes ( ) ; } } , new Operations . Functor < GenericTypeNode < T , I , TN , IN > , Set < ? extends IN > > ( ) { @ Override public Set < ? extends IN > apply ( final GenericTypeNode < T , I , TN , IN > node ) { return node . getDirectInstanceNodes ( ) ; } } ) ; }

Returns all instance nodes of the specified type node and all its
sub-nodes.

@param node
The type node whose instances should be returned.
@return all instance nodes of the specified type node and all its
sub-nodes.

Returns all instance nodes of the specified type node and all its sub - nodes .


@Override
	public void clear() {
		modCount++;
		E[] tab = buckets;
		for (int i = 0; i < tab.length; i++)
			tab[i] = null;
		size = 0;
	}

@ Override public void clear ( ) { modCount ++ ; E [ ] tab = buckets ; for ( int i = 0 ; i < tab . length ; i ++ ) tab [ i ] = null ; size = 0 ; }

Removes all entries from this set. The set will be empty after this call
returns.

Removes all entries from this set . The set will be empty after this call returns .


public static int combineMultisetHash(boolean finalize, int... hashes) {
		int hash = 0;
		for (int h : hashes) {
			hash = hash + h;
		}
		if (finalize) {
			hash = combineListHash(hash);
		}
		return hash;
	}

public static int combineMultisetHash ( boolean finalize , int ... hashes ) { int hash = 0 ; for ( int h : hashes ) { hash = hash + h ; } if ( finalize ) { hash = combineListHash ( hash ) ; } return hash ; }

Combine many hash codes with an associative commutative hash function.
Associativity ensures that the result of this functions can be further
combined with other hash codes for getting the same result as if all hash
codes had been combined in one step.

If finalize is false, then the method as such represents an associative
commutative hash, i.e. the return value can be combined with other
set-based hash codes in any order without making a difference. If
finalize is true, then the method combines its arguments with a
commutative hash, but shuffles the overall result. The method as such
then is neither an associative nor a commutative operation. This mode of
operation should be used whenever no further elements are to be added to
the set of hashes.

@param finalize
@param hashes
@return the combined hash code

Combine many hash codes with an associative commutative hash function . Associativity ensures that the result of this functions can be further combined with other hash codes for getting the same result as if all hash codes had been combined in one step .


public static int combineListHash(int... hashes) {
		int hash = 0;
		for (int h : hashes) {
			hash += h;
			hash += (hash << 10);
			hash ^= (hash >> 6);
		}
		hash += (hash << 3);
		hash ^= (hash >> 11);
		hash += (hash << 15);

		return hash;
	}

public static int combineListHash ( int ... hashes ) { int hash = 0 ; for ( int h : hashes ) { hash += h ; hash += ( hash << 10 ) ; hash ^= ( hash >> 6 ) ; } hash += ( hash << 3 ) ; hash ^= ( hash >> 11 ) ; hash += ( hash << 15 ) ; return hash ; }

Combine many hash codes into one in a way that depends on their order.

The current implementation is based on the Jenkins One-at-a-Time hash,
see http://www.burtleburtle.net/bob/hash/doobs.html and also
http://en.wikipedia.org/wiki/Jenkins_hash_function.

@param hashes
@return the combined hash code

Combine many hash codes into one in a way that depends on their order .


public static int copy(InputStream input, OutputStream output)
			throws IOException {
		byte[] buffer = new byte[BUFFER_SIZE];

		BufferedInputStream in = new BufferedInputStream(input, BUFFER_SIZE);
		BufferedOutputStream out = new BufferedOutputStream(output, BUFFER_SIZE);
		int count = 0, n = 0;

		try {
			while ((n = in.read(buffer, 0, BUFFER_SIZE)) != -1) {
				out.write(buffer, 0, n);
				count += n;
			}
			out.flush();
		} finally {
			IOUtils.closeQuietly(in);
			IOUtils.closeQuietly(out);
		}

		return count;
	}

public static int copy ( InputStream input , OutputStream output ) throws IOException { byte [ ] buffer = new byte [ BUFFER_SIZE ] ; BufferedInputStream in = new BufferedInputStream ( input , BUFFER_SIZE ) ; BufferedOutputStream out = new BufferedOutputStream ( output , BUFFER_SIZE ) ; int count = 0 , n = 0 ; try { while ( ( n = in . read ( buffer , 0 , BUFFER_SIZE ) ) != - 1 ) { out . write ( buffer , 0 , n ) ; count += n ; } out . flush ( ) ; } finally { IOUtils . closeQuietly ( in ) ; IOUtils . closeQuietly ( out ) ; } return count ; }

Copies bytes from the input stream to the output stream

@param input
@param output

@return The number of bytes copied
@throws IOException


public IncompletenessMonitor getReasonerIncompletenessMonitor(
			final IncompletenessMonitor... additionalMonitors) {
		final List<IncompletenessMonitor> monitors = new ArrayList<IncompletenessMonitor>(
				additionalMonitors.length + 1);
		monitors.add(getIncompletenessDueToStatedAxiomsMonitor());
		monitors.addAll(Arrays.asList(additionalMonitors));
		return new DelegatingIncompletenessMonitor(monitors) {
			@Override
			public boolean logNewIncompletenessReasons(final Logger logger) {
				final boolean result = super.logNewIncompletenessReasons(
						logger);
				if (result) {
					LoggerWrap.log(logger, LogLevel.WARN, MARKER_,
							"Reasoning may be incomplete! See log level INFO for more details.");
				}
				return result;
			}
		};
	}

Combines the provided partial incompleteness monitors into the top-level
monitor for reasoning tasks.

@param additionalMonitors
The partial monitors.
@return The top-level monitor for reasoning tasks.

Combines the provided partial incompleteness monitors into the top - level monitor for reasoning tasks .


protected static <T extends ElkEntity> void processTaxomomy(
			final Taxonomy<T> taxonomy, final Appendable writer)
					throws IOException {

		final ElkObject.Factory factory = new ElkObjectEntityRecyclingFactory();

		// Declarations.

		final List<T> members = new ArrayList<T>(
				taxonomy.getNodes().size() * 2);

		for (final TaxonomyNode<T> node : taxonomy.getNodes()) {
			for (final T member : node) {
				// TODO: this should check whether IRIs are predefined!
				if (!member.getIri()
						.equals(taxonomy.getTopNode().getCanonicalMember()
								.getIri())
						&& !member.getIri().equals(taxonomy.getBottomNode()
								.getCanonicalMember().getIri())) {
					members.add(member);
				}
			}
		}

		Collections.sort(members, taxonomy.getKeyProvider().getComparator());

		printDeclarations(members, factory, writer);

		// Relations.

		final TreeSet<T> canonicalMembers = new TreeSet<T>(
				taxonomy.getKeyProvider().getComparator());
		for (final TaxonomyNode<T> node : taxonomy.getNodes()) {
			canonicalMembers.add(node.getCanonicalMember());
		}

		for (final T canonicalMember : canonicalMembers) {
			final TaxonomyNode<T> node = taxonomy.getNode(canonicalMember);

			final ArrayList<T> orderedEquivalentMembers = new ArrayList<T>(
					node.size());
			for (final T member : node) {
				orderedEquivalentMembers.add(member);
			}
			Collections.sort(orderedEquivalentMembers,
					taxonomy.getKeyProvider().getComparator());

			final TreeSet<T> orderedSuperMembers = new TreeSet<T>(
					taxonomy.getKeyProvider().getComparator());
			for (final TaxonomyNode<T> superNode : node.getDirectSuperNodes()) {
				orderedSuperMembers.add(superNode.getCanonicalMember());
			}

			printMemberAxioms(canonicalMember, orderedEquivalentMembers,
					orderedSuperMembers, taxonomy, factory, writer);
		}
	}

Process a taxonomy and write a normalized serialization.

@param taxonomy
@param writer
@throws IOException

Process a taxonomy and write a normalized serialization .


public synchronized boolean submit(I input) throws InterruptedException {
		if (termination || isInterrupted())
			return false;
		buffer_.put(input);
		return true;
	}

public synchronized boolean submit ( I input ) throws InterruptedException { if ( termination || isInterrupted ( ) ) return false ; buffer_ . put ( input ) ; return true ; }

Submitting a new input for processing. Submitted input jobs are first
buffered, and then concurrently processed by workers. If the buffer is
full, the method blocks until new space is available.

@param input
the input to be processed
@return {@code true} if the input has been successfully submitted for
computation; the input cannot be submitted, e.g., if
{@link #finish()} has been called
@throws InterruptedException
thrown if interrupted during waiting for space to be
available

Submitting a new input for processing . Submitted input jobs are first buffered and then concurrently processed by workers . If the buffer is full the method blocks until new space is available .


public static void append(Appendable appender, ElkObject elkObject)
			throws IOException {
		append(appender, elkObject, false);
	}

public static void append ( Appendable appender , ElkObject elkObject ) throws IOException { append ( appender , elkObject , false ) ; }

Printing an ELK Object through an appender.

@param appender
the appender used for printing
@param elkObject
the ELK Object to print
@throws IOException
if an I/O Error occurs

Printing an ELK Object through an appender .


private QueryState markNotComputed(
			final IndexedClassExpression queryClass) {
		final QueryState state = indexed_.get(queryClass);
		if (state == null || !state.isComputed) {
			return null;
		}
		state.isComputed = false;
		if (state.node != null) {
			removeAllRelated(queryClass, state.node);
			state.node = null;
		}
		return state;
	}

private QueryState markNotComputed ( final IndexedClassExpression queryClass ) { final QueryState state = indexed_ . get ( queryClass ) ; if ( state == null || ! state . isComputed ) { return null ; } state . isComputed = false ; if ( state . node != null ) { removeAllRelated ( queryClass , state . node ) ; state . node = null ; } return state ; }

If the specified query was added to the index, this method marks it as
not-computed and deletes the query results.

@param queryClass
@return query state iff the parameter was queried, added to the index,
and the query was computed just before the call and was marked
not-computed by this call, otherwise {@code null}.

If the specified query was added to the index this method marks it as not - computed and deletes the query results .


@Override
	public synchronized void addDirectTypeNode(final UTN typeNode) {
		LOGGER_.trace("{}: new direct type-node {}", this, typeNode);

		directTypeNodes_.add(typeNode);
	}

@
Override
public
synchronized
void
addDirectTypeNode
(
final
UTN
typeNode
)
{
LOGGER_
.
trace
(
"{}: new direct type-node {}"
,
this
,
typeNode
)
;
directTypeNodes_
.
add
(
typeNode
)
;
}

Add a direct super-class node. This method is not thread safe.

@param typeNode
node to add

Add a direct super - class node . This method is not thread safe .


protected static void checkChainMatch(
			final ElkSubObjectPropertyExpression fullChain,
			final int startPos) {
		// verifies that start position exists in full chain
		fullChain.accept(new ElkSubObjectPropertyExpressionVisitor<Void>() {

			void fail() {
				throw new IllegalArgumentException(fullChain + ", " + startPos);
			}

			Void defaultVisit(ElkObjectPropertyExpression expression) {
				if (startPos != 0) {
					fail();
				}
				return null;
			}

			@Override
			public Void visit(ElkObjectPropertyChain expression) {
				if (startPos < 0 || startPos >= expression
						.getObjectPropertyExpressions().size())
					fail();
				return null;
			}

			@Override
			public Void visit(ElkObjectInverseOf expression) {
				return defaultVisit(expression);
			}

			@Override
			public Void visit(ElkObjectProperty expression) {
				return defaultVisit(expression);
			}
		});

	}

some methods for checking correctness of arguments


public static <T> Set<T> filter(final Set<? extends T> input,
			final Condition<? super T> condition, final int size) {
		return new Set<T>() {

			@Override
			public int size() {
				return size;
			}

			@Override
			public boolean isEmpty() {
				return size == 0;
			}

			@Override
			@SuppressWarnings("unchecked")
			public boolean contains(Object o) {

				if (!input.contains(o))
					return false;

				T elem = null;

				try {
					elem = (T) o;
				} catch (ClassCastException cce) {
					return false;
				}
				/*
				 * here's why the condition must be consistent with equals(): we
				 * check it on the passed element while we really need to check
				 * it on the element which is in the underlying set (and is
				 * equal to o according to equals()). However, as long as the
				 * condition is consistent, the result will be the same.
				 */
				return condition.holds(elem);
			}

			@Override
			public Iterator<T> iterator() {
				return filter(input, condition).iterator();
			}

			@Override
			public Object[] toArray() {
				Object[] result = new Object[size];
				int i = 0;
				for (Object o : filter(input, condition)) {
					result[i++] = o;
				}
				return result;
			}

			@Override
			public <S> S[] toArray(S[] a) {
				throw new UnsupportedOperationException();
			}

			@Override
			public boolean add(T e) {
				throw new UnsupportedOperationException();
			}

			@Override
			public boolean remove(Object o) {
				throw new UnsupportedOperationException();
			}

			@Override
			public boolean containsAll(Collection<?> c) {
				for (Object o : c) {
					if (contains(o))
						return false;
				}
				return true;
			}

			@Override
			public boolean addAll(Collection<? extends T> c) {
				throw new UnsupportedOperationException();
			}

			@Override
			public boolean retainAll(Collection<?> c) {
				throw new UnsupportedOperationException();
			}

			@Override
			public boolean removeAll(Collection<?> c) {
				throw new UnsupportedOperationException();
			}

			@Override
			public void clear() {
				throw new UnsupportedOperationException();
			}

		};

	}

Returns read-only view of the given set consisting of the elements
satisfying a given condition, if the number of such elements is known

@param input
the given set to be filtered
@param condition
the condition used for filtering the set. Must be consistent
with equals() for T, that is: a.equals(b) must imply that
holds(a) == holds(b)
@param size
the number of elements in the filtered set
@return the set consisting of the elements of the input set satisfying
the given condition

Returns read - only view of the given set consisting of the elements satisfying a given condition if the number of such elements is known


public static <I, O> Set<O> map(final Set<? extends I> input,
			final FunctorEx<I, O> functor) {
		return new AbstractSet<O>() {

			@Override
			public Iterator<O> iterator() {
				return new MapIterator<I, O>(input.iterator(), functor);
			}

			@Override
			public boolean contains(Object o) {
				I element = functor.deapply(o);

				return element == null ? false : input.contains(element);
			}

			@Override
			public int size() {
				return input.size();
			}

		};
	}

public static < I , O > Set < O > map ( final Set < ? extends I > input , final FunctorEx < I , O > functor ) { return new AbstractSet < O > ( ) { @ Override public Iterator < O > iterator ( ) { return new MapIterator < I , O > ( input . iterator ( ) , functor ) ; } @ Override public boolean contains ( Object o ) { I element = functor . deapply ( o ) ; return element == null ? false : input . contains ( element ) ; } @ Override public int size ( ) { return input . size ( ) ; } } ; }

A simple second-order map function for sets

@param input
@param functor
@return a set which contains the results of applying the functor to the
elements in the input set

A simple second - order map function for sets


public boolean add(int s, E e) {
		if (e == null)
			throw new NullPointerException();
		int mask = (1 << s);
		int oldMask = addMask(logs, data, masks, e, mask);
		int newMask = oldMask | mask;
		if (newMask == oldMask)
			return false;
		else if (oldMask == 0
				&& ++occupied == LinearProbing.getUpperSize(data.length))
			enlarge();
		sizes[s]++;
		return true;
	}

public boolean add ( int s , E e ) { if ( e == null ) throw new NullPointerException ( ) ; int mask = ( 1 << s ) ; int oldMask = addMask ( logs , data , masks , e , mask ) ; int newMask = oldMask | mask ; if ( newMask == oldMask ) return false ; else if ( oldMask == 0 && ++ occupied == LinearProbing . getUpperSize ( data . length ) ) enlarge ( ) ; sizes [ s ] ++ ; return true ; }

Inserts a given element into the given slice

@param s
the slice id
@param e
the elements to be inserted in to the given slice
@return {@code true} if the given element did not occur in the given
slice and thus was inserted. Otherwise {@code false} is returned
and nothing is modified.


public boolean remove(int s, Object o) {
		if (o == null)
			throw new NullPointerException();
		int mask = 1 << s;
		int oldMask = removeMask(logs, data, masks, o, mask);
		int newMask = oldMask & ~mask;
		if (newMask == oldMask)
			return false;
		// else
		if (newMask == 0
				&& --occupied == LinearProbing.getLowerSize(data.length))
			shrink();
		sizes[s]--;
		return true;
	}

public
boolean
remove
(
int
s
,
Object
o
)
{
if
(
o
==
)
throw
new
NullPointerException
(
)
;
int
mask
=
1
<<
s
;
int
oldMask
=
removeMask
(
logs
,
data
,
masks
,
o
,
mask
)
;
int
newMask
=
oldMask
&
~
mask
;
if
(
newMask
==
oldMask
)
return
false
;
// else
if
(
newMask
==
0
&&
occupied
==
LinearProbing
.
getLowerSize
(
data
.
length
)
)
shrink
(
)
;
sizes
[
s
]
;
return
true
;
}

Removes the given object from the given slice

@param s
the slice id
@param o
the object that should be removed from the given slice
@return {@code true} if the given object is equal to some element of the
given slice; this element will be removed from the slice. If
there is no such an object, {@code false} is returned and nothing
is modified


public synchronized void add(ClassConclusionCounter counter) {
		this.countSubClassInclusionDecomposed += counter.countSubClassInclusionDecomposed;
		this.countSubClassInclusionComposed += counter.countSubClassInclusionComposed;
		this.countBackwardLink += counter.countBackwardLink;
		this.countForwardLink += counter.countForwardLink;
		this.countContradiction += counter.countContradiction;
		this.countPropagation += counter.countPropagation;
		this.countDisjointSubsumer += counter.countDisjointSubsumer;
		this.countContextInitialization += counter.countContextInitialization;
		this.countSubContextInitialization += counter.countSubContextInitialization;
	}

public synchronized void add ( ClassConclusionCounter counter ) { this . countSubClassInclusionDecomposed += counter . countSubClassInclusionDecomposed ; this . countSubClassInclusionComposed += counter . countSubClassInclusionComposed ; this . countBackwardLink += counter . countBackwardLink ; this . countForwardLink += counter . countForwardLink ; this . countContradiction += counter . countContradiction ; this . countPropagation += counter . countPropagation ; this . countDisjointSubsumer += counter . countDisjointSubsumer ; this . countContextInitialization += counter . countContextInitialization ; this . countSubContextInitialization += counter . countSubContextInitialization ; }

Adds all counters of the argument to the corresponding counters of this
object. The counters should not be directly modified other than using
this method during this operation. The counter in the argument will be
reseted after this operation.

@param counter
the object which counters should be added

Adds all counters of the argument to the corresponding counters of this object . The counters should not be directly modified other than using this method during this operation . The counter in the argument will be reseted after this operation .


public static void logMemoryUsage(Logger logger, LogLevel priority) {
		if (LoggerWrap.isEnabledFor(logger, priority)) {
			// Getting the runtime reference from system
			Runtime runtime = Runtime.getRuntime();

			LoggerWrap.log(logger, priority, "Memory (MB) Used/Total/Max: "
					+ (runtime.totalMemory() - runtime.freeMemory())
					/ megaBytes + "/" + runtime.totalMemory() / megaBytes + "/"
					+ runtime.maxMemory() / megaBytes);
		}
	}

Log the current total memory usage with the specified priority.

@param logger
@param priority

Log the current total memory usage with the specified priority .


public synchronized void setConfigurationOptions(
			ReasonerConfiguration config) {
		this.workerNo_ = config.getParameterAsInt(
				ReasonerConfiguration.NUM_OF_WORKING_THREADS);

		setAllowIncrementalMode(config.getParameterAsBoolean(
				ReasonerConfiguration.INCREMENTAL_MODE_ALLOWED));

	}

public synchronized void setConfigurationOptions ( ReasonerConfiguration config ) { this . workerNo_ = config . getParameterAsInt ( ReasonerConfiguration . NUM_OF_WORKING_THREADS ) ; setAllowIncrementalMode ( config . getParameterAsBoolean ( ReasonerConfiguration . INCREMENTAL_MODE_ALLOWED ) ) ; }

This supposed to be the central place where the reasoner gets its
configuration options

@param config


public synchronized boolean shutdown(long timeout, TimeUnit unit)
			throws InterruptedException {
		boolean success = true;
		if (success) {
			LOGGER_.info("ELK reasoner has shut down");
		} else {
			LOGGER_.error("ELK reasoner failed to shut down!");
		}
		return success;

	}

public
synchronized
boolean
shutdown
(
long
timeout
,
TimeUnit
unit
)
throws
InterruptedException
{
boolean
success
=
true
;
if
(
success
)
{
LOGGER_
.
info
(
"ELK reasoner has shut down"
)
;
}
else
{
LOGGER_
.
error
(
"ELK reasoner failed to shut down!"
)
;
}
return
success
;
}

Tries to shut down the reasoner within the specified time

@param timeout
the maximum time to wait
@param unit
the time unit of the timeout argument
@return {@code true} if the operation was successful
@throws InterruptedException
if the current thread was interrupted


public void printHeader() {
		printSeparator();
		addPadding(' ', headerParams_);
		logger_.debug(String.format(headerFormat_, headerParams_));
		printSeparator();
	}

public void printHeader ( ) { printSeparator ( ) ; addPadding ( ' ' , headerParams_ ) ; logger_ . debug ( String . format ( headerFormat_ , headerParams_ ) ) ; printSeparator ( ) ; }

Prints the heading together with the separators


public void print(Object... values) {
		addPadding('.', values);
		logger_.debug(String.format(valuesFormat_, values));
	}

public void print ( Object ... values ) { addPadding ( ' ' , values ) ; logger_ . debug ( String . format ( valuesFormat_ , values ) ) ; }

Formats and the given values, adding padding symbols if necessary. The
given array may be modified, but the values themselves are not modified.

@param values

Formats and the given values adding padding symbols if necessary . The given array may be modified but the values themselves are not modified .


static String getString(char c, int n) {
		StringBuilder sb = new StringBuilder();
		for (int i = 0; i < n; i++) {
			sb.append(c);
		}
		return sb.toString();
	}

static String getString ( char c , int n ) { StringBuilder sb = new StringBuilder ( ) ; for ( int i = 0 ; i < n ; i ++ ) { sb . append ( c ) ; } return sb . toString ( ) ; }

Creates a string of the given length consisting of the given character

@param c
@param n
@return