001    package nl.tudelft.tbm.eeni.owlstructure.processor;
002    
003    import com.hp.hpl.jena.ontology.OntClass;
004    import com.hp.hpl.jena.ontology.OntModel;
005    import nl.tudelft.tbm.eeni.owlstructure.utils.OntologyUtils;
006    import org.apache.commons.logging.Log;
007    import org.apache.commons.logging.LogFactory;
008    
009    import java.util.Collection;
010    
011    public class ThingExtender implements IOntologyProcessor {
012    
013        static Log log = LogFactory.getLog(FunctionalPropertyInferer.class);
014    
015        public static enum Target {
016            /* let all classes without superclasses extend owl:Thing */
017            TOP_CLASSES,
018            /* let all classes extend owl:Thing */
019            ALL_CLASSES
020        }
021    
022        private Target target;
023    
024        public ThingExtender(Target topClasses) {
025            this.target = topClasses;
026        }
027    
028        public ThingExtender() {
029            this(Target.TOP_CLASSES);
030        }
031    
032        @Override
033        public OntModel process(OntModel ontModel) {
034            // Fetch or create the owl:Thing class
035            OntClass Thing = OntologyUtils.getOwlThing(ontModel);
036    
037            // Copy all classes to a list first to avoid ConcurrentModification exceptions
038            Collection<OntClass> ontClasses = ontModel.listClasses().toList();
039    
040            for (OntClass ontClass : ontClasses) {
041                // We shouldn't extend Thing into Thing
042                if (!ontClass.equals(Thing)) {
043                    // Make ontClass extend Thing if...
044                    // (1) the target is ALL_CLASSES and ontClass does not already have superclass Thing
045                    // (2) the target is TOP_CLASSES and ontClass has no supers
046                    switch (target) {
047                        case ALL_CLASSES:
048                            if (!ontClass.hasSuperClass(Thing)) {
049                                log.info("Adding owl:Thing superclass to " + ontClass.getLocalName());
050                                ontClass.addSuperClass(Thing);
051                            }
052                            break;
053    
054                        case TOP_CLASSES:
055                            if (ontClass.listSuperClasses().toList().isEmpty()) {
056                                log.info("Adding owl:Thing superclass to " + ontClass.getLocalName());
057                                ontClass.addSuperClass(Thing);
058                            }
059                            break;
060                    }
061                }
062            }
063    
064            // Return the processed ontology
065            return ontModel;
066        }
067    }