Java parses OWL ontology for addition and deletion operations

First configure the path of the operation ontology (match your own path):

 //The name of the owl file changes as the owl file changes.
    String metaName = "newmeta_11.owl";
//The IRI of the owl file changes as the owl file changes.
    String ontologyIRI = "http://www.semanticweb.org/asus/ontologies/2022/6/untitled-ontology-23";
/**
     * Try to load the metadata file, try to find the latest version of the metadata file, and read the owl file without restarting the project.
     */
    public void reloadMetaFile() throws OWLOntologyCreationException, FileNotFoundException {
        String metaFile = metadataService.getLatestMetafile();
        metadataService.reload(metaFile);
    }

The following is the use of java code to operate OWL ontology classes:

Add ontology class Controller layer:

/**
     * Add ontology class
     *
     * @param className subclass name, also the ontology class to be added
     * @param parentClassName parent class name
     * @return QueryResponse
     */
    @RequestMapping(value = "/addClass", produces = "application/json;charset=UTF-8", method = RequestMethod.POST)
    public QueryResponse addClass(@RequestParam(value = "className", defaultValue = "") String className,
                                  @RequestParam(value = "parentClassName", defaultValue = "") String parentClassName) {
        return metadataEditService.addClass(className, parentClassName);
    }

Service layer:

/**
     * Add ontology class
     *
     * @param className The class name to be added
     * @param parentClassName parent class name
     * @return QueryResponse
     */
    public QueryResponse addClass(String className, String parentClassName) {
        QueryResponse response = new QueryResponse();
        JSONObject jsonObject = new JSONObject();

        // Get the path of the owl file
        String metaPath = sysConfig.getMetadata() + "/";
        try {
            File file = new File(metaPath + metaName);
            OWLOntologyManager manager = OWLManager.createOWLOntologyManager();
            //Load the file and convert it into an ontology object. At this time, ontology is the ontology that has been obtained.
            OWLOntology ontology = manager.loadOntologyFromOntologyDocument(file);
            // Get the ontology data factory
            OWLDataFactory factory = manager.getOWLDataFactory();
            // Set of axioms added to the basic statements expressed by the ontology
            Set<OWLDeclarationAxiom> axiomSet = new HashSet<>();

            List<String> classList = new ArrayList<>();
            // Get all classes
            List<OWLClass> classes = new ArrayList<>(ontology.getClassesInSignature());
            //Save the class name into the class collection
            for (OWLClass aClass : classes) {
                classList.add(aClass.getIRI().getFragment().toString());
            }

            //Remove all spaces, including spaces in between
            String removeSpacesClassName = className.replaceAll(" ", "");
            //Use tool class to determine whether it is empty
            if (!StringUtil.isEmpty(removeSpacesClassName)) {
                // Determine whether the ontology class to be added already exists
                if (!classList.contains(removeSpacesClassName)) {
                    //Create the IRI of the new class and keep the format consistent
                    IRI classIRI = IRI.create(ontologyIRI + "#" + removeSpacesClassName);
                    if (parentClassName.isEmpty()) {
                        // If the parent class is empty, create the subclass directly
                        OWLClass name = factory.getOWLClass(classIRI);
                        //Add class
                        axiomSet.add(factory.getOWLDeclarationAxiom(name));
                        //Add completed
                        manager.addAxioms(ontology, axiomSet);
                        //Save the picture
                        manager.saveOntology(ontology, new TurtleDocumentFormat(), IRI.create(file.toURI()));
                        response.setSuccess(true);
                        log.info("Add ontology class successfully!");
                        response.setMsg("Add ontology class successfully!");
                    } else {
                        // Get the parent class
                        OWLClass superclass = ontology.classesInSignature()
                                .filter(owlClass -> owlClass.getIRI().getRemainder().get().equals(parentClassName))
                                .findFirst()
                                .get();

                        //Create subclass
                        OWLClass subclass = factory.getOWLClass(classIRI);

                        //Define the relationship between subclasses and parent classes
                        Set<OWLAxiom> subAndSuper = new HashSet<>();
                        subAndSuper.add(factory.getOWLSubClassOfAxiom(subclass, superclass));

                        //Add subclass and parent class relationships to the ontology
                        manager.addAxioms(ontology, subAndSuper.stream());
                        manager.addAxioms(ontology, axiomSet);
                    }

                    //Save the body
                    manager.saveOntology(ontology, new TurtleDocumentFormat(), IRI.create(file.toURI()));
                    response.setSuccess(true);
                    log.info("Add ontology class successfully!");
                    response.setMsg("Add ontology class successfully!");
                } else {
                    response.setSuccess(false);
                    log.info("This concept already exists, adding the ontology class failed!");
                    return QueryResponse.genErr("This concept already exists, adding ontology class failed!");
                }
                //Try to load the metadata file, try to find the latest version of the metadata file, and read the owl file without restarting the project
                reloadMetaFile();
            } else {
                response.setSuccess(false);
                log.info("New concepts cannot be empty!");
                return QueryResponse.genErr("The new concept cannot be empty!");
            }

        } catch (OWLOntologyCreationException | OWLOntologyStorageException | FileNotFoundException e) {
            e.printStackTrace();
            response.setSuccess(false);
            log.info("Failed to add ontology class!");
            return QueryResponse.genErr("Failed to add ontology class!");
        }
        return response;
    }

Delete the ontology class Controller layer:

/**
     * Delete the ontology class
     *
     * @param removeClassName The name of the ontology class to be deleted
     * @return QueryResponse
     */
    @RequestMapping(value = "/removeClass", produces = "application/json;charset=UTF-8", method = RequestMethod.POST)
    public QueryResponse removeClass(@RequestParam(value = "removeClassName", defaultValue = "") String removeClassName) {
        return metadataEditService.removeClass(removeClassName);
    }

Service layer:

/**
     * Delete the ontology class
     *
     * @param removeClassName The name of the class to be deleted
     * @return QueryResponse
     */
    public QueryResponse removeClass(String removeClassName) {
        QueryResponse response = new QueryResponse();
        JSONObject jsonObject = new JSONObject();
        //Get the path of the owl file
        String metaPath = sysConfig.getMetadata() + "/";
        try {
            OntologyHelper helper = new OntologyHelper();
            //Load file
            File file = new File(metaPath + metaName);
            OWLOntology ontology = helper.readOntology(file);
            //Our removeClassName here gives the added class name above, obtains all classes through the ontology class, traverses and gets the removeClassName class
            OWLClass aClass = ontology.classesInSignature()
                    .filter(owlClass -> owlClass.getIRI().getRemainder().get().equals(removeClassName))
                    .findFirst()
                    .get();
            //To delete, use the OWLAxiom class
            Set<OWLAxiom> axiomsToRemove = new HashSet<OWLAxiom>();
            //Start traversing
            for (OWLAxiom ax : ontology.getAxioms()) {
                //Put it in when it is found that the class in the collection is the same as the class to be deleted
                if (ax.getSignature().contains(aClass)) {
                    axiomsToRemove.add(ax);
                }
            }
            //Perform deletion operation
            helper.removeAxioms(ontology, axiomsToRemove);
            helper.writeOntology(ontology, file, "owl");
            response.setSuccess(true);
            log.info("Delete ontology class successfully!");
            response.setMsg("Delete ontology class successfully!");
        } catch (OWLOntologyCreationException | OWLOntologyStorageException e) {
            e.printStackTrace();
            response.setSuccess(false);
            log.info("Deletion of ontology class failed!");
            return QueryResponse.genErr("Failed to delete ontology class!");
        }
        return response;
    }