add properties to individual and insert them all into my file.owl - java

I have a class, MAN. I want to add an individual, jack, with properties:
hasage="50"
hasadress="france"
How can I create my individual jack and add properties to him and save them into my file database.owl? Here is the connection. I use Eclipse and the Jena API.
JenaOWLModel owlModel ;
OntModel model;
owlModel = ProtegeOWL.createJenaOWLModelFromURI("file:///C:/database.owl");
model = owlModel.getOntModel();
i am begging you to help me , it still fiew days for my thesis defence this CODE work perfectly i can save individuals in my file.owl BUT i couldnt add properties to those individuals and save them with.
please help me what should i do , i am realy worried thanks a lot in advance
public class testins {
static JenaOWLModel owlModel ;
public static void main(String[] args) {
OntModel model;
javax.swing.JDialog jDialog1 = new javax.swing.JDialog();
try{
owlModel = ProtegeOWL.createJenaOWLModelFromURI("file:///D:/file.owl");// the link of my owl file
model = owlModel.getOntModel();
JOptionPane.showMessageDialog(jDialog1,
"loaded with success","Information",JOptionPane.INFORMATION_MESSAGE);
}
catch(Exception e){
JOptionPane.showMessageDialog(jDialog1,
"error",
"Information",
JOptionPane.INFORMATION_MESSAGE);
}
OWLNamedClass theAlert = owlModel.getOWLNamedClass("Alert"); //my class Alert
theAlert.createOWLIndividual("indivname1"); //i add here an indevidual
theAlert.createOWLIndividual("indivname2"); //i add here another indevidual
// now how to add to those two Individuals properties ?? each individual has 2
// properties , the property witch its name est_evaluer and the second est_analyser those
// to properties will contain values so here is my problem how to add those values to an
// individual and save all of them
Collection errors ;
String fileName ;
fileName= ("D:/file.owl");
errors = new ArrayList();
//here i'll save it and it work ,it mean that i find in my file "file.owl"
//individuals i added witch are "indivname1" and "indivname2" in my class ALERT
// so now my problem is how to add properties to those indiviuals i add , and save them also
try{ owlModel.save(new File(fileName).toURI(), FileUtils.langXMLAbbrev, errors);
System.out.println("File saved with " + errors.size() + " errors.");
}
catch(Exception e){
}
}
}

You didn't say what the namespace you are using is. So I'm going to assume http://example.org/example#, adjust as necessary.
String NS = "http://example.org/example#";
// create ex:Man class
OntClass man = model.createClass( NS + "Man" );
// create individual ex:jack
Individual jack = model.createIndividual( NS + "jack", man );
// create some properties - probably better to use FOAF here really
DatatypeProperty age = model.createDatatypeProperty( NS + "age" );
DatatypeProperty address = model.createDatatypeProperty( NS + "address" );
jack.addProperty( age, model.createTypedLiteral( 50 ) )
.addProperty( address, model.createLiteral( "France" ) );

Related

I cannot understand how an ArrayList can have Class object as a datatype

import java.time.LocalDate;
import java.util.ArrayList;
class Books{
String bookName, authorName;
public Books(String bName, String aName){
this.authorName = aName;
this.bookName = bName;
}
#Override
public String toString(){
return "Book Details{Book name: "+bookName+", Author: "+authorName+"}";
}
}
public class Ex7_LibraryManagementSystem {
What is going on here? I'm new to java so I don't get the ArrayList that much. Are we creating an ArrayList with a class datatype??? Does this part falls in Advance Java or do I need to revise my basics again? I'm confused with all these class Books passing as an argument thing
ArrayList<Books> booksList;
Ex7_LibraryManagementSystem(ArrayList<Books> bookName){
this.booksList = bookName;
}
public void addBooks(Books b){
this.booksList.add(b);
System.out.println("Book Added Successfully");
}
public void issuedBooks(Books b,String issuedTo,String issuedOn){
if(booksList.isEmpty()){
System.out.println("All Books are issued.No books are available right now");
}
else{
if(booksList.contains(b))
{
this.booksList.remove(b);
System.out.println("Book "+b.bookName+" is issued successfully to "+issuedTo+" on "+issuedOn);
}
else{
System.out.println("Sorry! The Book "+b.bookName+" is already been issued to someone");
}
}
}
public void returnBooks(Books b, String returnFrom){
this.booksList.add(b);
System.out.println("Book is returned successfully from "+returnFrom+" to the Library");
}
public static void main(String[] args) {
Also please Explain why are we creating this below ArrayList
ArrayList<Books> book1 = new ArrayList<>();
LocalDate ldt = LocalDate.now();
Books b1 = new Books("Naruto","Kisishima");
book1.add(b1);
Books b2 = new Books("Naruto Shippuden","Kisishima");
book1.add(b2);
Books b3 = new Books("Attack On Titan","Bhaluche");
book1.add(b3);
Books b4 = new Books("Akame Ga Kill","Killer bee");
book1.add(b4);
Books b5 = new Books("Death Note","Light");
book1.add(b5);
Ex7_LibraryManagementSystem l = new Ex7_LibraryManagementSystem(book1);
// l.addBooks(new Books("Boruto","Naruto"));
l.issuedBooks(b3,"Sanan",ldt.getDayOfMonth()+"/"+ldt.getMonthValue()+"/"+ldt.getYear());
l.issuedBooks(b1,"Sandy",ldt.getDayOfMonth()+"/"+ldt.getMonthValue()+"/"+ldt.getYear());
// l.issuedBooks(b2,"Suleman",ldt.getDayOfMonth()+"/"+ldt.getMonthValue()+"/"+ldt.getYear());
// l.issuedBooks(b4,"Sanju",ldt.getDayOfMonth()+"/"+ldt.getMonthValue()+"/"+ldt.getYear());
// l.issuedBooks(b5,"Thor",ldt.getDayOfMonth()+"/"+ldt.getMonthValue()+"/"+ldt.getYear());
l.issuedBooks(b1,"anuj",ldt.getDayOfMonth()+"/"+ldt.getMonthValue()+"/"+ldt.getYear());
}
}
Please Help Me...Thank you!
Generics
You asked:
ArrayList<Books> booksList;
What is going on here? I'm new to java so I don't get the ArrayList that much. Are we creating an ArrayList with a class datatype???
You need to learn about Generics in Java.
ArrayList is collection, a data structure for holding objects.
<Book> (after fixing your misnomer Books) is telling the compiler that we intend to store only objects of the Book class in this particular collection.
If we mistakenly try to put a Dog object or an Invoice object into that collection, the compiler will complain. You will get an error message at compile-time explaining that only objects of the Book class can be put into that collection.
Also, you can put objects that are from a class that is a subclass of Book. Imagine you had HardCoverBook and SoftCoverBook classes that both extend from the Book class. Objects of those subclasses can also go into a collection of Book objects.
Other issues
Naming is important. Clear naming makes your code easier to read and comprehend.
So your class Books describes a single book. So it should be named in the singular, Book.
When collecting a bunch of book objects, such as a List, name that collection in the plural. For example List < Book > books.
Your book class could be more briefly written as a record. And we could shorten the names of your member fields.
record Book( String title, String author ) {}
We could shorten Ex7_LibraryManagementSystem to Library.
We need two lists rather than the one seen in your code. Given your scenario, we want to move books between a list for books on hand and a list of books loaned out.
More naming: The argument in your constructor should not be bookName, it should be something like initialInventory. And the type of that parameter should be simply Collection rather than specifically ArrayList or even List.
When passing in a collection of Book objects, copy them into our internally-managed lists. We don’t want the calling code to be able to change the collection between our back. By making a copy, we take control.
For that matter, your books are not ordered, so no need for List. If the book objects are meant to be unique, we can collect them as Set rather than List — but I'll ignore that point.
Your addBooks adds only a single book, so rename in the singular.
"Issue" is an odd term; "loan" seems more appropriate to a library. Similarly, the issuedBooks method could use better naming, including not being in past-tense. Use date-time classes to represent date-time values, such as LocalDate for a date-only value (without time-of-day, and without time zone or offset). Mark those arguments final to avoid accidentally changing them in your method.
loanBook ( final Book book , final String borrower , final LocalDate dateLoaned ) { … }
I recommend checking for conditions that should never happen, to make sure all is well. So rather than assume a book is on loan, verify. If things seem amiss, report.
After those changes, we have something like this.
package work.basil.example.lib;
import java.time.Instant;
import java.time.LocalDate;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import java.util.Set;
record Book( String title , String author )
{
}
public class Library
{
private List < Book > booksOnHand, booksOnLoan;
Library ( Collection < Book > initialInventory )
{
this.booksOnHand = new ArrayList <>( initialInventory );
this.booksOnLoan = new ArrayList <>( this.booksOnHand.size() );
}
public void addBook ( Book b )
{
this.booksOnHand.add( b );
System.out.println( "Book added successfully." );
}
public void loanBook ( final Book book , final String borrower , final LocalDate dateLoaned )
{
if ( this.booksOnHand.isEmpty() )
{
System.out.println( "All Books are issued. No books are available right now." );
}
else
{
if ( this.booksOnHand.contains( book ) )
{
this.booksOnHand.remove( book );
this.booksOnLoan.add( book );
System.out.println( "Book " + book.title() + " by " + book.author() + " is loaned to " + borrower + " on " + dateLoaned );
}
else if ( this.booksOnLoan.contains( book ) )
{
System.out.println( "Sorry! The Book " + book.title() + " by " + book.author() + " is out on loan." );
}
else
{
System.out.println( "ERROR – We should never have reached this point in the code. " );
}
}
}
public void returnBook ( Book book , String returnFrom )
{
if ( this.booksOnLoan.contains( book ) )
{
this.booksOnLoan.remove( book );
this.booksOnHand.add( book );
System.out.println( "The Book " + book.title() + " by " + book.author() + " has been returned to the Library." );
}
else
{
System.out.println( "The Book " + book.title() + " by " + book.author() + " is not out on loan, so it cannot be returned to the Library." );
}
}
public String reportInventory ( )
{
StringBuilder report = new StringBuilder();
report.append( "On hand: " + this.booksOnHand );
report.append( "\n" );
report.append( "On load: " + this.booksOnLoan );
return report.toString();
}
public static void main ( String[] args )
{
List < Book > stockOfBooks =
List.of(
new Book( "Naruto" , "Kisishima" ) ,
new Book( "Naruto Shippuden" , "Kisishima" ) ,
new Book( "Attack On Titan" , "Bhaluche" ) ,
new Book( "Akame Ga Kill" , "Killer bee" ) ,
new Book( "Death Note" , "Light" )
);
Book b1 = stockOfBooks.get( 0 ), b2 = stockOfBooks.get( 1 ), b3 = stockOfBooks.get( 2 );
Library library = new Library( stockOfBooks );
library.loanBook( b3 , "Sanan" , LocalDate.now() );
library.loanBook( b1 , "Sandy" , LocalDate.now().plusDays( 1 ) );
library.loanBook( b2 , "anuj" , LocalDate.now().plusDays( 2 ) );
library.returnBook( b1 , "Sandy" );
System.out.println( library.reportInventory() );
}
}
When run.
Book Attack On Titan by Bhaluche is loaned to Sanan on 2022-04-19
Book Naruto by Kisishima is loaned to Sandy on 2022-04-20
Book Naruto Shippuden by Kisishima is loaned to anuj on 2022-04-21
The Book Naruto by Kisishima has been returned to the Library.
On hand: [Book[title=Akame Ga Kill, author=Killer bee], Book[title=Death Note, author=Light], Book[title=Naruto, author=Kisishima]]
On load: [Book[title=Attack On Titan, author=Bhaluche], Book[title=Naruto Shippuden, author=Kisishima]]

Java csv parser/writer

I'm trying to get a CSV from some data retrieved by Oracle. I have just to write the csv, using the result of the query as column of csv. This is my code:
// get data
final List<myDto> dataCsv = myDao.getdata();
StringWriter writer = new StringWriter();
CSVWriter csvWriter = new CSVWriter(writer,';');
List<String[]> result = toStringArray(dataCsv);
csvWriter.writeAll(result);
csvWriter.close();
return Response.ok(result).header("Content-Disposition", "attachment; filename=" + fileName).build();`
Obviously it can't find toStringArray(). But have I to build it? Do I really need it? How do I have to edit the edit to get it working?
If you just follow the example from the link that you've given, you'll see what they're doing...
private static List<String[]> toStringArray(List<Employee> emps) {
List<String[]> records = new ArrayList<String[]>();
//add header record
records.add(new String[]{"ID","Name","Role","Salary"});
Iterator<Employee> it = emps.iterator();
while(it.hasNext()){
Employee emp = it.next();
records.add(new String[]{emp.getId(),emp.getName(),emp.getRole(),emp.getSalary()});
}
return records;
}
Essentially, you need to build a List of String[]. Each String[] represents a single line of data for the CSV, with each element of the array being a value. So, yes, you need to build a List from your data model and pass it to the CSVWriter's writeAll() method.
The first String[] in the list is the column headers for the CSV. The subsequent String arrays are the data itself.
Apache Commons CSV
The Apache Commons CSV library can help with the chore of reading/writing CSV files. It handles several variants of the CSV format, including the one used by Oracle.
• CSVFormat.ORACLE
Employee.java
Let's make a class for Employee.
package work.basil.example;
import java.util.Objects;
public class Employee {
public Integer id;
public String name, role;
public Integer salary;
public Employee ( Integer id , String name , String role , Integer salary ) {
Objects.requireNonNull( id ); // etc.
this.id = id;
this.name = name;
this.role = role;
this.salary = salary;
}
#Override
public String toString ( ) {
return "Employee{ " +
"id=" + id +
" | name='" + name + '\'' +
" | role='" + role + '\'' +
" | salary=" + salary +
" }";
}
}
Example app
Make another class to mimic retrieving your DTOs. Then we write to a CSV file.
Obviously it can't find toStringArray(). But have I to build it? Do I really need it? How do I have to edit the edit to get it working?
To answer your specific Question, there is no toStringArray method to create field values for the CSV from your DTO object‘s member variables.
Binding
This idea of mapping input or output data with member variables of a Java object is generally known as binding.
There are sophisticated binding libraries for Java to bind your objects with XML and with JSON, JAXB and JSON-B respectively. Objects can be automatically written out to XML or JSON text, as well as “re-hydrated” back to objects when read from such XML or JSON text.
But for CSV with a simpler library such as Apache Commons CSV, we read and write each field of data individually for each object. You pass each DTO object member variable, and Commons CSV will write those values out to the CSV text with any needed encapsulating quote marks, commas, and escaping.
You can see this in the code below, in this line:
printer.printRecord( e.id , e.name , e.role , e.salary );
EmployeeIo.java
Here is the entire EmployeeIo.java file where Io means input-output.
package work.basil.example;
import org.apache.commons.csv.CSVFormat;
import org.apache.commons.csv.CSVPrinter;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.ArrayList;
import java.util.List;
public class EmployeeIo {
public static void main ( String[] args ) {
EmployeeIo app = new EmployeeIo();
app.doIt();
}
private void doIt ( ) {
// Mimic a collection of DTO objects coming from the database.
List < Employee > employees = new ArrayList <>( 3 );
employees.add( new Employee( 101 , "Alice" , "Boss" , 11_000 ) );
employees.add( new Employee( 102 , "Bob" , "Worker" , 12_000 ) );
employees.add( new Employee( 103 , "Carol" , "Worker" , 13_000 ) );
Path path = Paths.get( "/Users/basilbourque/Employees.csv" );
this.write( employees , path );
}
public void write ( final List < Employee > employees , final Path path ) {
try ( final CSVPrinter printer = CSVFormat.ORACLE.withHeader( "Id" , "Name" , "Role" , "Salary" ).print( path , StandardCharsets.UTF_8 ) ; ) {
for ( Employee e : employees ) {
printer.printRecord( e.id , e.name , e.role , e.salary );
}
} catch ( IOException e ) {
e.printStackTrace();
}
}
}
When run, we produce a file.

ArrayList method return

I'm working in a project with DB. There are a method that collect info from the DB and set the info in ArrayList:
public ArrayList<Director> listAll(){
ArrayList<Director>list = new ArrayList<Director>();
Director direc = new Director();
int cont=0;
String sql = "select * from director;";
try{
ResultSet res = objBBDD.sentencia.executeQuery(sql);
while(res.next()){
direc.setCode(res.getInt("CODE"));
direc.setName(res.getString("NAME"));
direc.setNationality(res.getString("NATIONALITY"));
direc.setOscar(res.getInt("OSCAR"));
list.add(direc);
// THIS IS USE TO CONFIRM IF IT WORKS ///////////////////////////////////////
// JOptionPane.showMessageDialog(null,"Code:"+list.get(cont).getCode()+"Nombre"+list.get(cont).getName());
// cont++;
}
}catch (SQLException e) {
e.printStackTrace();
}
return list;
}
I use JOptionPane.showMessageDialog to see if I get info from DB and is added correctly to de ArrayList, and it's works.
Now the ArrayList back the invoker class, this is the method:
private void stackArray(){
ArrayList<Director>arrayDir = new ArrayList<Director> ();
ArrayList<Director>arrayDir = conexion.listAll();
// JOptionPane.showMessageDialog(null,"Code:"+arrayDir.get(0).getCode()+"Name"+arrayDir.get(0).getName());
// JOptionPane.showMessageDialog(null,"Code:"+arrayDir.get(1).getCode()+"Name"+arrayDir.get(1).getName());
// JOptionPane.showMessageDialog(null,"Code:"+arrayDir.get(2).getCode()+"Name"+arrayDir.get(2).getName());
}
Again I use the JOptionPane.showMesageDialog to show the first three positions, but it's not work, the problem, as far as I've seen, is all the positions have the same object saved (exactly the last).
Summarizing the ArrayList have the same object (last in DB), there are no problems at run or compile.
I don't know if I write something bad, or just a noob fail.
the problem, as far as I've seen, is all the positions have the same
object saved (exactly the last).
You are changing value of same instance Director. Thats why, you seen the last value of Director object. You should create new instance of Director with iteration of while loop.
ResultSet res = objBBDD.sentencia.executeQuery(sql);
while(res.next){
Director direc = new Director();// Declare Director instance here.
.....
list.add(direc);
}

Storing objects in a database java

So I'm working on a program to interface with a file based database. Mostly I'm trying to figure out how to work with it so that I can make objects and store their information in the database so that I can pull the data later.
IE Object Taylor
Name = Taylor
Age = 20
School = Whatever
So that I can get back on and call that information up when queried.
This is an example of an object I want to store. I may be doing this part wrong.
package com.catalyse.db;
public class Taylor implements java.io.Serializable
{
public String name = "Taylor M May";
public int age = 20;
public String school = "UC Boulder";
}
The DB structure I'm using is based on RandomAccessFile and I didn't make it, I'm just trying to figure out how to implement it.
package com.catalyse.db;
import java.util.*;
import java.util.Scanner;
/**
* Simple test class for the RecordsFile example. To run the test,
* set you CLASSPATH and then type "java hamner.dbtest.TestRecords"
*/
public class Run {
static void log(String s) {
System.out.println(s);
}
private static String name()
{
Scanner name = new Scanner(System.in);
String name1 = name.next();
return name1;
}
public static void main (String[] args) throws Exception {
System.out.println(new Date());
Scanner SC = new Scanner(System.in);
log("What would you like to name the database?");
String filename = SC.next();
log("creating records file...");
RecordsFile recordsFile = new RecordsFile(filename+".records", 64);
log("adding a record...");
RecordWriter rw = new RecordWriter("foo.username");
rw.writeObject(new Taylor());
recordsFile.insertRecord(rw);
log("reading record...");
RecordReader rr = recordsFile.readRecord("foo.username");
Taylor name = (Taylor)rr.readObject();
System.out.println("\tlast access was at: " + name.toString());
log("test completed.");
}
}
And here is what I get back from it,
Wed Nov 20 11:56:04 MST 2013
What would you like to name the database?
save3
creating records file...
adding a record...
reading record...
last access was at: com.catalyse.db.Taylor#50aed564
test completed.
My problem is that I want it to return information about the class, not just its name and location in the DB.
You need to override the toString method.
public String toString()
{
StringBuilder sb = new StringBuilder();
sb.append("Name: ");
sb.append(this.name);
//rest of fields
return sb.toString();
}
As a matter of clarity, you are not returning its location in the database. You are getting back the object hashValue + the class name.
At this point
Taylor name = (Taylor)rr.readObject();
You can access whatever information you like in the object, e.g.
Taylor name = (Taylor)rr.readObject();
System.out.println(name.age + ", " + name.name + ", " + name.school);
Alternatively, just add a
public String toString()
{
return name + ", " + age + ", " + school;
}
method in Taylor and then output it like so
Taylor name = (Taylor)rr.readObject();
System.out.println(name);
Now, concerning...
System.out.println("\tlast access was at: " + name.toString());
name.toString() isn't really required. If you append an object to a String then it automatically calls that objects toString() method to get a value.
Lastly, I'd like to note that generally we don't access object members like name, school and age by just accessing them. We generally make them private members then add methods to get and set them, so that we control and can track how they are manipulated.

How to sort data in a table data structure in Java?

I need to sort data based on the third column of the table data structure. I tried based on the answers for the following question. But my sorting does not work. Please help me in this.
Here goes my code.
Object[] data = new Object[y];
rst.beforeFirst();
while (rst.next()) {
int p_id = Integer.parseInt(rst.getString(1));
String sw2 = "select sum(quantity) from tbl_order_detail where product_id=" + p_id;
rst1 = stmt1.executeQuery(sw2);
rst1.next();
String sw3 = "select max(order_date) from tbl_order where tbl_order.`Order_ID` in (select tbl_order_detail.`Order_ID` from tbl_order_detail where product_id=" + p_id + ")";
rst2 = stmt2.executeQuery(sw3);
rst2.next();
data[i] = new Object[]{new String(rst.getString(2)), new String(rst.getString(3)), new Integer(rst1.getString(1)), new String(rst2.getString(1))};
i++;
}
ColumnComparator cc = new ColumnComparator(2);
Arrays.sort(data, cc);
if (i == 0) {
table.addCell("");
table.addCell("");
table.addCell("");
table.addCell("");
} else {
for (int j = 0; j < y; j++) {
Object[] theRow = (Object[]) data[j];
table.addCell((String) theRow[0]);
table.addCell((String) theRow[1]);
table.addCell((String) theRow[2]);
table.addCell((String) theRow[3]);
}
Sample Expected Output:
Product_code Product_name Quantity Order_date
FK Cake 3000 2010-12-09
CK Jelly 100 2010-09-23
F juice 30 2010-12-09
but what I get is:
Product_code Product_name Quantity Order_date
CK Jelly 100 2010-09-23
F juice 30 2010-12-09
FK Cake 3000 2010-12-09
You have far too much going on here. You're mingling database access and UI all into a single method. I'd separate those concerns.
I'd also recommend having the database do the sorting. Add an ORDER BY to the SELECT and let the database do the work.
I'd map the data from the SELECT into an object that had a Comparator for sorting. Load the ResultSet into a List of that object; you can have all your wishes that way.
Is the problem the data or the comparator? In the other posting you where shown how to create a simple test program using hard coded data. The code you posted here doesn't help us because we don't have access to your database and we don't know if you are accessing the data correctly.
The output looks like it is sorted in ascending order by "String" value. So it does indeed look like the data is wrong. I don't know what the problem is since it looks like you are adding an Integer value to the array.
You want the output in descending order by amount, so you need to set a Comparator property to do this.
Anyway to make sure the problem wasn't with my Comparator I created a simple test:
import java.util.*;
public class SortSIJ
{
public static void main(String args[])
{
Object[] data = new Object[3];
data[0] = new Object[] {"CK", "Jelly", new Integer(100), "2010-09-23"};
data[1] = new Object[] {"FK", "Cake", new Integer(3000), "2010-12-09"};
data[2] = new Object[] {"F", "juice", new Integer(30), "2010-12-09"};
ColumnComparator cc = new ColumnComparator(2);
cc.setAscending( false );
Arrays.sort(data, cc);
for (Object row: data)
{
Object[] theRow = (Object[])row;
System.out.println( Arrays.asList(theRow) );
}
}
}
The output looks fine to me. All I can suggest is that you modify the ColumnComparator to add the following line of code to verify the Object type that is being sorted.
System.out.println(o1.getClass());
When I do that I get the following output:
class java.lang.Integer
class java.lang.Integer
[FK, Cake, 3000, 2010-12-09]
[CK, Jelly, 100, 2010-09-23]
[F, juice, 30, 2010-12-09]

Categories

Resources