Protégé OWL API programming - java

I have a problem with my code i'm working on an antologie file using Protege OWL API (3.4.8) and i want to have all the classes define by the user in the ontologie , the problem is i keep having errors in the for loop i can't fix those errors, is there any way to get the classes.
package Test;
import java.util.Collection;
import javax.swing.text.html.HTMLDocument.Iterator;
import antlr.collections.List;
import edu.stanford.smi.protege.model.Cls;
import edu.stanford.smi.protegex.owl.ProtegeOWL;
import edu.stanford.smi.protegex.owl.jena.JenaOWLModel;
import edu.stanford.smi.protegex.owl.model.OWLDatatypeProperty;
import edu.stanford.smi.protegex.owl.model.OWLIndividual;
import edu.stanford.smi.protegex.owl.model.OWLModel;
import edu.stanford.smi.protegex.owl.model.OWLNamedClass;
import edu.stanford.smi.protegex.owl.model.OWLObjectProperty;
import edu.stanford.smi.protegex.owl.model.RDFSClass;
public class Class4 {
public static JenaOWLModel owlModel =null;
public static String scorKos_Uri="C:/Users/souad/Desktop/SCOR-KOS.owl";
//where my ontologie file exist
//change the URI by this
"http://protege.cim3.net/file/pub/ontologies/travel/travel.owl"; to have a
OWL file
/**
* #param args
*/
public static void main(String[] args) {
/**
* ontologie
*/
try {
owlModel=ProtegeOWL.createJenaOWLModelFromURI(scorKos_Uri);
System.out.println("Worked");
Collection classes = owlModel.getUserDefinedOWLNamedClasses();
for (Iterator it = classes.iterator(); it.hasNext();) {
OWLNamedClass cls = (OWLNamedClass) it.next();
Collection instances = cls.getInstances(false);
System.out.println("Class " + cls.getBrowserText() + " (" +
instances.size() + ")");
for (Iterator jt = instances.iterator(); jt.hasNext();) {
OWLIndividual individual = (OWLIndividual) jt.next();
System.out.println(" - " + individual.getBrowserText());
}
}
}catch (Exception exception) {
System.out.println("Error can't upload the ontologie ");
System.exit(1);
}
}
}

You're not importing java.util.Iterator.

Related

SQLite Query Not Running in Java

I created a database using DB Browser for SQLite. Now I am trying to run queries to retrieve data from the database, and I have run into an issue. When I run the query in DB Browser, the query runs smoothly. When I attempt to run the same query in Java, I get an error message. I triple-checked the query string. I looked to make sure I was not using SQLite keywords incorrectly. Why am I getting an error when I run this query Java?
SELECT
subject.id, main.name, main.link, subject.name, main_subject.weight
FROM
main_subject
LEFT JOIN
main ON main_subject.mainId = main.id
LEFT JOIN
subject ON main_subject.subjectId = subject.id
The query running correctly in DB Browser.
MCVE:
Main
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import java.io.File;
import java.io.IOException;
import java.lang.reflect.Type;
import java.nio.file.Files;
import java.util.ArrayList;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.Set;
import java.util.logging.Level;
import java.util.logging.Logger;
/**
* #author sedrick
*/
public class Main
{
public static void main(String[] args)
{
try (DatabaseHandler databaseHandler = new DatabaseHandler()) {
List<BySubjectItemTwo> bySubjectItemTwos = databaseHandler.getBySubjectItems();
bySubjectItemTwos.forEach(System.out::println);
//databaseHandler.getByTitleItems().forEach(System.out::println);
}
catch (Exception ex) {
Logger.getLogger(Main.class.getName()).log(Level.SEVERE, null, ex);
}
}
}
DatabaseHandler
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.List;
import java.util.logging.Level;
import java.util.logging.Logger;
/**
*
* #author sedrick
*/
public class DatabaseHandler implements AutoCloseable
{
String dbString = "jdbc:sqlite:qDatabase.sqlite3";
private Connection conn;
public DatabaseHandler()
{
try {
conn = DriverManager.getConnection(dbString);
System.out.println("Connected to qDatabase!");
}
catch (SQLException ex) {
Logger.getLogger(DatabaseHandler.class.getName()).log(Level.SEVERE, null, ex);
}
}
#Override
public void close() throws Exception
{
conn.close();
}
public List<BySubjectItemTwo> getBySubjectItems()
{
List<BySubjectItemTwo> returnList = new ArrayList();
String sqlString = "SELECT subject.id, main.name, main.link, subject.name, main_subject.weight FROM main_subject LEFT JOIN main ON main_subject.mainId = main.id LEFT JOIN subject ON main_subject.subjectId = subject.id";
try (Statement stmt = conn.createStatement(); ResultSet rs = stmt.executeQuery(sqlString)) {
while (rs.next()) {
System.out.println(rs.getInt("subject.id") + " - " + rs.getString("main.name") + " - " + rs.getString("main.link") + " - " + rs.getString("subject.name") + " - " + rs.getInt("main_subject.weight"));
//returnList.add(new BySubjectItemTwo(rs.getInt("subject.id"), rs.getString("main.name"), rs.getString("main.link"), rs.getString("subject.name"), rs.getInt("main_subject.weight")));
}
}
catch (SQLException e) {
System.out.println(e.getMessage());
}
return returnList;
}
}
BySubjectItemTwo
/**
*
* #author sedrick
*/
public class BySubjectItemTwo
{
private int subjectId;
private String mainName;
private String mainLink;
private String subjectName;
private int mainSubjectWeight;
public BySubjectItemTwo(int subjectId, String mainName, String mainLink, String subjectName, int mainSubjectWeight)
{
this.subjectId = subjectId;
this.mainName = mainName;
this.mainLink = mainLink;
this.subjectName = subjectName;
this.mainSubjectWeight = mainSubjectWeight;
}
public int getSubjectWeight()
{
return mainSubjectWeight;
}
public void setSubjectWeight(int mainSubjectWeight)
{
this.mainSubjectWeight = mainSubjectWeight;
}
public int getSubjectId()
{
return subjectId;
}
public void setSubjectId(int subjectId)
{
this.subjectId = subjectId;
}
public String getMainName()
{
return mainName;
}
public void setMainName(String mainName)
{
this.mainName = mainName;
}
public String getMainLink()
{
return mainLink;
}
public void setMainLink(String mainLink)
{
this.mainLink = mainLink;
}
public String getSubjectName()
{
return subjectName;
}
public void setSubjectName(String subjectName)
{
this.subjectName = subjectName;
}
#Override
public String toString()
{
StringBuilder sb = new StringBuilder();
sb.append("BySubjectItemTwo{subjectId=").append(subjectId);
sb.append(", mainName=").append(mainName);
sb.append(", mainLink=").append(mainLink);
sb.append(", subjectName=").append(subjectName);
sb.append(", subjectWeight=").append(mainSubjectWeight);
sb.append('}');
return sb.toString();
}
}
Error
----------< sed.work:CreateDatabaseByTitleAndSubjectDatabase >----------
Building CreateDatabaseByTitleAndSubjectDatabase 1.0-SNAPSHOT
--------------------------------[ jar ]---------------------------------
--- exec-maven-plugin:1.5.0:exec (default-cli) # CreateDatabaseByTitleAndSubjectDatabase ---
Connected to qDatabase!
[SQLITE_ERROR] SQL error or missing database (ambiguous column name: subject.id)
------------------------------------------------------------------------
BUILD SUCCESS
------------------------------------------------------------------------
Total time: 1.484 s
Finished at: 2020-10-16T12:42:35-05:00
------------------------------------------------------------------------
Netbean's Info
Product Version: Apache NetBeans IDE 12.1
Java: 15; Java HotSpot(TM) 64-Bit Server VM 15+36-1562
Runtime: Java(TM) SE Runtime Environment 15+36-1562
System: Windows 10 version 10.0 running on amd64; Cp1252; en_US (nb)
Maven Project
This:
FROM main_subject, main, subject
is the problem with your query.
Remove , main, subject from your statement.
The tables main and subject are correctly joined after the LEFT joins.
When you use them also in the FROM clause this creates additional references and CROSS joins to the same tables.
Also, although SQLite allows a query to return more than 1 columns with the same name, it is a good practice to alias columns so that in the resultset all column names are different.
So give aliases to main.name and subject.name, something like this:
SELECT subject.id, main.name AS main_name, ..., subject.name AS subject_name, ...
and when you retrieve the column values don't use the table prefixes:
System.out.println(rs.getInt("id") + " - " + rs.getString("main_name") + " - " + rs.getString("link") + " - " + rs.getString("subject_name") + " - " + rs.getInt("weight"));

Reading XSD from URL using Java

Objective : I want to read a WSDL and print the services in the WSDL, complex types and Complex type definitions.
Worked : I've used WSDL4J for reading WSDL and successfully able to print the services and their parameters (complex types). Now I want to read the complex type definitions which is available in XSD. I'm unable to read XSD .Is ther any way to do it ?
I'm getting XSModel as null
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import java.util.Map;
import javax.wsdl.BindingOperation;
import javax.wsdl.Definition;
import javax.wsdl.WSDLException;
import javax.wsdl.xml.WSDLReader;
import org.w3c.dom.bootstrap.DOMImplementationRegistry;
import com.ibm.wsdl.BindingImpl;
import com.ibm.wsdl.xml.WSDLReaderImpl;
import com.sun.org.apache.xerces.internal.impl.xs.XSImplementationImpl;
import com.sun.org.apache.xerces.internal.xs.XSLoader;
import com.sun.org.apache.xerces.internal.xs.XSModel;
public class WSDLDetails {
public static void main(String[] args) {
try {
String wsdlURL = "https://abc.xyz.com/webservice/MessagingSevice?WSDL";
String xsdURL = "https://abc.xyz.com/webservice/MessagingSevice?xsd=1";
java.lang.System.setProperty("https.protocols", "TLSv1.2");
getAllBindingOperation(wsdlURL);
readXSD(xsdURL);
} catch (Exception e) {
e.printStackTrace();
}
}
public static List<String> getAllBindingOperation(String wsdlUrl) {
List<BindingOperation> operationList = new ArrayList();
List<String> nameList = new ArrayList();
try {
WSDLReader reader = new WSDLReaderImpl();
reader.setFeature("javax.wsdl.verbose", false);
Definition definition = reader.readWSDL(wsdlUrl.toString());
Map<String, BindingImpl> defMap = definition.getAllBindings();
Collection<BindingImpl> collection = defMap.values();
for (BindingImpl binding : collection) {
operationList.addAll(binding.getBindingOperations());
}
for (BindingOperation operation:operationList) {
nameList.add(operation.getName());
System.out.println("Name :: " + operation.getName());
System.out.println("Request :: " + operation.getBindingInput());
System.out.println("Response :: " + operation.getBindingOutput());
}
} catch (WSDLException e) {
System.out.println("get wsdl operation fail.");
e.printStackTrace();
}
return nameList;
}
public static void readXSD(String xsdURL) {
try {
System.setProperty(DOMImplementationRegistry.PROPERTY, "com.sun.org.apache.xerces.internal.dom.DOMXSImplementationSourceImpl");
DOMImplementationRegistry registry = DOMImplementationRegistry.newInstance();
com.sun.org.apache.xerces.internal.impl.xs.XSImplementationImpl impl = (XSImplementationImpl) registry.getDOMImplementation("XS-Loader");
XSLoader schemaLoader = impl.createXSLoader(null);
XSModel model = schemaLoader.loadURI(xsdURL);
System.out.println(model);
} catch (Exception e) {
e.printStackTrace();
}
}
You can use xsd2java plugin with maven
https://github.com/qaware/xsd2java-gradle-plugin
Here is an example showing how to retrieve the XSModel from an XSD URL, and print the complex types declared therein.
import org.apache.xerces.impl.xs.XMLSchemaLoader;
import org.apache.xerces.impl.xs.XSComplexTypeDecl;
import org.apache.xerces.impl.xs.XSElementDecl;
import org.apache.xerces.xs.XSConstants;
import org.apache.xerces.xs.XSModel;
import org.apache.xerces.xs.XSNamedMap;
import org.apache.xerces.xs.XSTypeDefinition;
public class Test {
public static void main(String[] args) {
try {
String xsdURL = "http://fsharp.github.io/FSharp.Data/data/po.xsd";
XMLSchemaLoader xsLoader = new XMLSchemaLoader();
XSModel xsModel = xsLoader.loadURI(xsdURL);
// print global element declarations
System.out.println("\nGlobal Element Declarations:");
XSNamedMap globalElemDecls = xsModel.getComponents(XSConstants.ELEMENT_DECLARATION);
globalElemDecls.forEach((k,v) -> System.out.println((XSElementDecl) v));
// print global complex type declarations
System.out.println("\nGlobal Complex Type Declarations:");
XSNamedMap globalComplexTypeDecls = xsModel.getComponents(XSTypeDefinition.COMPLEX_TYPE);
globalComplexTypeDecls.forEach((k,v) -> System.out.println((XSComplexTypeDecl) v));
} catch (Exception e) {
e.printStackTrace();
}
}
}
If you got null at xsLoader.loadURI(xsdURL), it is likely there are some flaws in the given XSD file. For example, "White spaces are required between publicId and systemId". You might need to fix these flaws first.

I am not able to update ontology model

I have made an Ontologu in Protege and imported in Eclipse.My ontology already 10 instances and i want to add more instances.The following piece of code adds instances to existing class (Noun) of ontology. After excecution it do not update ontology model and shows same number of instances.
public static void main(String[] args) throws OWLException, IOException{
OWLOntologyManager manager = OWLManager.createOWLOntologyManager();
File file = new File("D:\\word.owl");{
OntModel model=ModelFactory.createOntologyModel(OntModelSpec.OWL_MEM_RULE_INF);
System.out.println("Model is called successfully");
OWLOntology ont = manager.loadOntologyFromOntologyDocument(file);
System.out.println("Loaded ontology: " + ont);
String SOURCE = ("D:\\word.owl");
String NS = SOURCE;
OntModel base = ModelFactory.createOntologyModel(OntModelSpec.OWL_MEM_RULE_INF);
base.read( SOURCE, "" );
OntModel inf =ModelFactory.createOntologyModel(OntModelSpec.OWL_MEM_RULE_INF, base );
OntClass Noun = base.getOntClass( NS + "Noun" );
Individual jack = base.createIndividual( NS + "Jack", Noun );
Individual Helley = base.createIndividual( NS + "Helley", Noun );
manager.saveOntology(ont);
System.out.println("Number of individuals: " + ont.getIndividualsInSignature().size());
}
}
}
Output
Model is called successfully
Loaded ontology:
Number of individuals: 10
I dont use that API but I can see your issue.
At the start of your code you create an OWLOntology object:
OWLOntology ont = manager.loadOntologyFromOntologyDocument(file);
And here is the issue, you do not alter ont anywhere in your code, so when you call the line below, it will only show/save the same 10 individuals that you loaded from file at the beginning of your code:
manager.saveOntology(ont);
System.out.println("Number of individuals: " + ont.getIndividualsInSignature().size());
So to fix this you need to somehow modify ont to include the new Individual before using the above lines.
This works:
import java.io.FileWriter;
import java.io.InputStream;
import org.apache.jena.ontology.Individual;
import org.apache.jena.ontology.OntClass;
import org.apache.jena.ontology.OntModel;
import org.apache.jena.ontology.OntModelSpec;
import org.apache.jena.rdf.model.ModelFactory;
import org.apache.jena.util.FileManager;
import org.apache.jena.vocabulary.RDF;
public class Mgt {
public static void main(String[] args) throws Exception {
String namespace = "http://www.semanticweb.org/Word#";
String file = "word.owl";
OntModel jenaModel = ModelFactory.createOntologyModel(OntModelSpec.OWL_MEM_RULE_INF);
InputStream in = FileManager.get().open(file);
jenaModel.read(in, null);
OntClass Noun = jenaModel.getOntClass(namespace + "Noun");
Individual Organization = Noun.createIndividual(namespace + "Organization");
jenaModel.add(Organization, RDF.type, Noun);
FileWriter out = new FileWriter("word.out.owl");
jenaModel.getWriter("RDF/XML-ABBREV").write(jenaModel, out, namespace);
out.close();
}
}
Note that namespace is not related to the file name.
Updated Code It gives Exception in thread "main" java.lang.NullPointerException
at Mgt.main(Mgt.java:29)
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStream;
import org.apache.jena.ontology.Individual;
import org.apache.jena.ontology.OntClass;
import org.apache.jena.ontology.OntModel;
import org.apache.jena.ontology.OntModelSpec;
import org.apache.jena.rdf.model.ModelFactory;
import org.apache.jena.util.FileManager;
public class Mgt {
static OntModel jenaModel = null;
public static void main(String[] args) throws Exception{
String file =("D:\\word.owl");
jenaModel = ModelFactory.createOntologyModel(OntModelSpec.OWL_MEM_RULE_INF);
InputStream in = FileManager.get().open(file);
try
{
jenaModel.read(in, null);
}
catch (Exception e)
{
e.printStackTrace();
}
System.out.println("Ontology " + file + " loaded.");
OntClass Noun = jenaModel.getOntClass( "http://www.semanticweb.org/Word#Noun" );
Individual Organization = Noun.createIndividual(file + "Organization");
FileWriter out = null;
try {
// XML format - long and verbose
out = new FileWriter( file);
jenaModel.write( out, "RDF/XML" );
}
finally {
if (out != null) {
try {out.close();
} catch (IOException ignore) {}
}
}
}
}

PlayFramework how to access list from super controller

I am completing my university project, but I encountered weird problem. Since I am a student, apologize in the adavance if it is prosaic.
I have my BasicCommonController which has List backendErrors = new ArrayList<>()
, and I have another Controller which extends BasicCommonController, and I'm able to access backendErrors list from BasicCommonController, but I am not able
to put new Element to the list, wchich is always empty. I have tried to access via super.backendErrors, but it also does not work.
How to add some error to the super.backendErrors and access it in another Controllers
this is abstract controller:
package controllers;
import org.apache.commons.lang3.StringUtils;
import play.Logger;
import play.Play;
import play.mvc.Controller;
import java.util.ArrayList;
import java.util.List;
/**
* Created by vv on 22.04.2017.
*/
public class BasicAbstractController extends Controller {
public static final String GO_HOME = "/";
public List<String> backendErrors = new ArrayList<>();
public static String getPlaceToObserve(){
String place = Play.application().configuration().getString("storage.place");
if(StringUtils.isNotBlank(place)){
return place;
}
return StringUtils.EMPTY;
}
public static String getServerInstance(){
String instance = Play.application().configuration().getString("storage.place");
if(StringUtils.isNotBlank(instance)){
return instance;
}
return StringUtils.EMPTY;
}
}
this is example controller
package controllers;
import com.google.common.io.Files;
import com.sun.org.apache.regexp.internal.RE;
import constans.AppCommunicates;
import play.Logger;
import play.mvc.Http;
import play.mvc.Result;
import util.FileUtil;
import java.io.File;
import java.io.IOException;
import java.util.List;
/**
* Created by vv on 22.04.2017.
*/
public class FileUploadController extends BasicAbstractController {
public Result upload() {
Http.MultipartFormData<File> body = request().body().asMultipartFormData();
Http.MultipartFormData.FilePart<File> picture = body.getFile("picture");
if (picture != null) {
String fileName = picture.getFilename();
String contentType = picture.getContentType();
File file = picture.getFile();
File fileToSave = new File(getPlaceToObserve() + "/" + picture.getFilename());
try{
Files.copy(file,fileToSave);
}
catch (IOException ioe){
Logger.error("Unable to write file");
}
Logger.error("File Handled Cuccessfully");
return redirect(GO_HOME);
} else {
flash("error", "Missing file");
return badRequest();
}
}
public Result delete(String fileName){
List<File> files = FileUtil.getCurrentFileNames();
File fileToDelete = null;
for (File file : files) {
if(file.getName().equals(fileName)){
fileToDelete = file;
break;
}
}
boolean deletionResult = FileUtil.deleteGivenFile(fileToDelete);
if(!deletionResult){
// i am not able to add smthg here
backendErrors.add(AppCommunicates.UNABLE_TO_DELETE_FILE);
}
return redirect(GO_HOME);
}
}
I am not able to add nor access list from other controllers

Getting all columns from get result in HBase dynamically

I am working on a Get object as retrieved from a table in Habse. I want to dynamically retrieve all column values related to that get since I don't know the exact name of column families
val result1 = hTable.get(g)
if (!result1.isEmpty) {
//binaryEpisodes = result1.getValue(Bytes.toBytes("episodes"),Bytes.toBytes("episodes"))
//instead of above retrieve all values dynamically
}
Simple way :
get rawcells and knowing CF , columns information.
You have to do something like below example
public static void printResult(Result result, Logger logger) {
logger.info("Row: ");
for (Cell cell : result.rawCells()) {
byte[] family = CellUtil.cloneFamily(cell);
byte[] column = CellUtil.cloneQualifier(cell);
byte[] value = CellUtil.cloneValue(cell);
logger.info("\t" + Bytes.toString(family) + ":" + Bytes.toString(column) + " = " + Bytes.toString(value));
}
}
Hbase Admin way : Hbase client API was exposed by HbaseAdmin class like below...
Client would be like
package mytest;
import com.usertest.*;
import java.io.IOException;
import java.util.Date;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
public class ListHbaseTablesAndColumns {
public static void main(String[] args) {
try {
HbaseMetaData hbaseMetaData =new HbaseMetaData();
for(String hbaseTable:hbaseMetaData .getTableNames(".*yourtables.*")){
for (String column : hbaseMetaData .getColumns(hbaseTable, 10000)) {
System.out.println(hbaseTable + "," + column);
}
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
Use below class to Get HbaseMetaData..
package com.usertest;
import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.hbase.*;
import org.apache.hadoop.hbase.client.*;
import org.apache.hadoop.hbase.filter.PageFilter;
import java.io.IOException;
import java.util.*;
import java.util.regex.Pattern;
public class HbaseMetaData {
private HBaseAdmin hBaseAdmin;
private Configuration hBaseConfiguration;
public HbaseMetaData () throws IOException {
this.hBaseConfiguration = HBaseConfiguration.create();
this.hBaseAdmin = new HBaseAdmin(hBaseConfiguration);
}
/** get all Table names **/
public List<String> getTableNames(String regex) throws IOException {
Pattern pattern=Pattern.compile(regex);
List<String> tableList = new ArrayList<String>();
TableName[] tableNames=hBaseAdmin.listTableNames();
for (TableName tableName:tableNames){
if(pattern.matcher(tableName.toString()).find()){
tableList.add(tableName.toString());
}
}
return tableList;
}
/** Get all columns **/
public Set<String> getColumns(String hbaseTable) throws IOException {
return getColumns(hbaseTable, 10000);
}
/** get all columns from the table **/
public Set<String> getColumns(String hbaseTable, int limitScan) throws IOException {
Set<String> columnList = new TreeSet<String>();
HTable hTable=new HTable(hBaseConfiguration, hbaseTable);
Scan scan=new Scan();
scan.setFilter(new PageFilter(limitScan));
ResultScanner results = hTable.getScanner(scan);
for(Result result:results){
for(KeyValue keyValue:result.list()){
columnList.add(
new String(keyValue.getFamily()) + ":" +
new String(keyValue.getQualifier())
);
}
}
return columnList;
}
}

Categories

Resources