Accessing Object Property for Individual using Apache Jena - java

I have created an OWL ontology using Protégé, describing a patient database system. I am now attempting to develop a Java code using Apache Jena to read the OWL file I created, then perform a number of operations on it. My primary goal is to get my code to be able to find a specific Individual by name (Patient name for example) and then access a specific Object Property for that individual, and output its value. For example, A patient "John" has an object property "Treated_By" which corresponds to another individual "Amy" (Amy is an individual of type doctor). However, I have been unable to figure out which Jena method is used to retrieve Object property values from a certain individual.
Here is my code (Please ignore comments, they are fragments of previous attempts for this task):
public class Main {
public static void main(String[] args) {
OntModel model = ModelFactory.createOntologyModel(OntModelSpec.OWL_MEM);
String fileName = "C:/Users/Ahmed Medhat/Documents/assignment1ontv3.0.owl";
try {
InputStream inputStream = new FileInputStream(fileName);
model.read(inputStream, "RDF/XML");
//model.read(inputStream, "OWL/XML");
inputStream.close();
} catch (Exception e) {
System.out.println(e.getMessage());
}
Scanner sc = new Scanner(System.in);
System.out.println("Enter Patient Name: ");
String patientName = sc.next();
ExtendedIterator<Individual> itI = model.listIndividuals();
while (itI.hasNext()) {
Individual i = itI.next();
String localName = i.getLocalName();
//System.out.println(patientName);
//System.out.println(localName);
if(localName.equals(patientName))
{
//System.out.println("Conditional Code Accessed.");
OntClass Class = i.getOntClass();
System.out.println("Patient Disease is: " + Class.listDeclaredProperties());
}
System.out.println("Failed.");
}
}
}

Try this (replace the property URI accordingly):
final Property p = model.createObjectProperty("http://example.org/Treated_by");
final RDFNode object = i.getPropertyValue(p);

Related

Java: ClassNotFound Classpath issues

Im trying to read some information from a file into some objects. Main method just reads the Information into some string variables then uses those strings to initialize objects. Pretty simple. The objects are stored using a BST.
However, The error Im getting is ClassNotFoundException. Except when I run the java 'file' command, 'file' is spelled and capitalized correctly.
I've been reading that you can change the path that JVM uses when searching for class files.
so I tried:
set CLASSPATH=$CLASSPATH=~/../../BackEnd
but that didn't do anything..
Here is my main file..
import java.util.Scanner;
import java.io.File;
class BackEnd
{
public static void main(String args[]) throws java.io.FileNotFoundException
{
Tree.ServiceTree providers = new Tree.ServiceTree();
String path = "./providers.txt";
Scanner read = new Scanner (new File(path));
read.useDelimiter(",");
String information[] = new String[5];//array of strings used to store info from file, then used to initialize objects
try
{
while(read.hasNext())
{
for(int i = 0; i < 5; ++i)
{
information[i] = read.nextLine();//read in all the info into the array
}
Services.Service newService;//used as dynamic reference to be passed to tree
Services.Service serviceInfo = new Services.Service(information[0], information[1]);//initalizes base class to be passed to derived constructor
switch(information[0])//check type to initalize appropriate object
{
case "Dogwalk":
newService = new Services.Dogwalk(serviceInfo, information[2], information[3]);
case "Groceries":
newService = new Services.Groceries(serviceInfo, information[2], information[3]);
case "Housework":
newService = new Services.Housework(serviceInfo, information[2], information[3]);
}
providers.insert(information[4], newService);
}
read.close();
throw new java.io.FileNotFoundException("File not found...");
}
catch(java.io.FileNotFoundException exception)
{
System.out.println("File not found");
}
//providers.display();
}
}
Figured it out. Error had nothing to do with compilation or class path and was due
to uninitialized variable newService

Apriori Algorithm gives memory locations

I have my application which need to get associations via the Apriori Algorithm. In order to achieve results I use Weka dependency. Though I want to get associations it prints memory locations. I have attached the output as well. Thanks.
Here is my code:
public class App
{
static Logger log = Logger.getLogger(App.class.getName());
public static BufferedReader readDataFile(String filename) {
BufferedReader inputReader = null;
try {
inputReader = new BufferedReader(new FileReader(filename));
} catch (FileNotFoundException ex) {
}
return inputReader;
}
public static void main( String[] args ) throws Exception {
//Define ArrayList to Add Clustered Information
ArrayList<FastVector[]> associationInfoArrayList = new ArrayList<FastVector[]>();
Apriori apriori = new Apriori();
apriori.setNumRules(15);
BufferedReader datafile = readDataFile("/media/jingi_ingi/IR1_CPRA_X6/Documents/ss.arff");
Instances data = new Instances(datafile);
// Instances instances = new Instances(datafile);
apriori.buildAssociations(data);
log.debug("Testing Apriori Algo Results Started ....");
log.debug("-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-");
log.debug("Number of Associations : " + apriori.getNumRules());
log.debug("Adding Association Information to ArrayList ..");
Object objectArrayOfAssociations[] = new Object[apriori.getNumRules()];
log.debug(apriori.getAllTheRules().toString());
for(int i=0; i<apriori.getNumRules(); i++) {
objectArrayOfAssociations[i] = apriori.getAllTheRules();
log.debug("Associations Discovered : " + objectArrayOfAssociations[i].toString());
}
}
}
Output of the Application:
2015-04-05 20:16:42 DEBUG App:48 - Associations Discovered :
[Lweka.core.FastVector;#19a96bae
2015-04-05 20:16:42 DEBUG App:48 - Associations Discovered :
[Lweka.core.FastVector;#19a96bae
2015-04-05 20:16:42 DEBUG App:48 - Associations Discovered :
[Lweka.core.FastVector;#19a96bae
2015-04-05 20:16:42 DEBUG App:48 - Associations Discovered :
[Lweka.core.FastVector;#19a96bae
apriori.getAllTheRules()
returns an Array of FastVectors, but FastVector doesn't have a toString() method to dump its contents as implied by your intentions. You can extend FastVector and add your own toString() or write a little helper method to dump the contents as desired. Here's an example
Something like:
for(FastVector fastVector : apriori.getAllTheRules())
log.debug(fastVector.getRevision());
// or whichever attribute you want to show

SuperCSV reading from multiple files and parsing into one bean object

I am currently trying to read in multiple CSV files using beanReader before taking a few columns from each and parsing them into one bean.
So far I cannot seem to parse columns from different files into one bean object. Is this even possible with ICsvBeanReader?
Yes, it's possible :) As of Super CSV 2.2.0 you can read into an existing bean (see javadoc).
The following example uses 3 readers simultaneously (operating on 3 different files) - the first reader is used to create the bean, the other 2 just update the existing bean. This approach assumes that each file has the same number of rows (and that each row number represents the same person). If they don't, but they share some unique identifier, you'll have to read all the records from the first file into memory first, then update from the second/third matching on the identifier.
I've tried to make it a little bit smart, so you don't have to hard-code the name mapping - it just nulls out the headers it doesn't know about (so that Super CSV doesn't attempt to map fields that don't exist in your bean - see the partial reading examples on the website). Of course this will only work if your file has headers - otherwise you'll just have to hard code the mapping arrays with nulls in the appropriate places.
Person bean
public class Person {
private String firstName;
private String sex;
private String country;
// getters/setters
}
Example code
public class Example {
private static final String FILE1 = "firstName,lastName\nJohn,Smith\nSally,Jones";
private static final String FILE2 = "age,sex\n21,male\n24,female";
private static final String FILE3 = "city,country\nBrisbane,Australia\nBerlin,Germany";
private static final List<String> DESIRED_HEADERS = Arrays.asList("firstName", "sex", "country");
#Test
public void testMultipleFiles() throws Exception {
try (
ICsvBeanReader reader1 = new CsvBeanReader(new StringReader(FILE1), CsvPreference.STANDARD_PREFERENCE);
ICsvBeanReader reader2 = new CsvBeanReader(new StringReader(FILE2), CsvPreference.STANDARD_PREFERENCE);
ICsvBeanReader reader3 = new CsvBeanReader(new StringReader(FILE3), CsvPreference.STANDARD_PREFERENCE);){
String[] mapping1 = getNameMappingFromHeader(reader1);
String[] mapping2 = getNameMappingFromHeader(reader2);
String[] mapping3 = getNameMappingFromHeader(reader3);
Person person;
while((person = reader1.read(Person.class, mapping1)) != null){
reader2.read(person, mapping2);
reader3.read(person, mapping3);
System.out.println(person);
}
}
}
private String[] getNameMappingFromHeader(ICsvBeanReader reader) throws IOException{
String[] header = reader.getHeader(true);
// only read in the desired fields (set unknown headers to null to ignore)
for (int i = 0; i < header.length; i++){
if (!DESIRED_HEADERS.contains(header[i])){
header[i] = null;
}
}
return header;
}
}
Output
Person [firstName=John, sex=male, country=Australia]
Person [firstName=Sally, sex=female, country=Germany]

Getting variables from another .java file using reflection

I've managed to get reflection working by getting and formatting the variables in the class that the toString() method is in.
public class ReadFile {
public int test1 =0;
public String test2 = "hello";
Boolean test3 = false;
int test4 = 1;
public static void main(String[] args) throws IOException{
ReadFile test = new ReadFile();
System.out.println(test);
}
public String toString(){
//Make a string builder so we can build up a string
StringBuilder result = new StringBuilder();
//Declare a new line constant
final String NEW_LINE = System.getProperty("line.separator");
//Gets the name of THIS Object
result.append(this.getClass().getName() );
result.append(" Class {" );
result.append(NEW_LINE);
//Determine fields declared in this class only (no fields of superclass)
Field[] fields = this.getClass().getDeclaredFields();
//Print field names paired with their values
for ( Field field : fields ) {
result.append(" ");
try {
result.append(field.getType() + " ");
result.append( field.getName() );
result.append(": ");
//requires access to private field:
result.append( field.get(this) );
} catch ( IllegalAccessException ex ) {
System.out.println(ex);
}
result.append(NEW_LINE);
}
result.append("}");
return result.toString();
}
}
However I was wondering whether it would be possible to specify a specific file in the directory for the toString() to work on?
I have tried getting a file and plugging it in the System.out.println() but the way I see it is you need to make an instance of a class and give it the instance for it to work. So I'm not sure how that can be done programatically.
I have been trying something like this:
Path path = FileSystems.getDefault().getPath("D:\\Directory\\Foo\\Bar\\Test.java", args);
File file = path.toFile();
System.out.println(file);
However I don't get very far with it, I've mainly been seeing if I can convert the file into anything usable but I'm not sure what I need to be doing!
Any advice would be great.
I think you need to look into the ClassLoader API - you need to get an new URLClassLoader and ask it to load your .java file into the JVM. You can then reflect on it.
You can try to read the package information from the file (D:\Directory\Foo\Bar\Test.java) and than try to load it the class by its name:
Class.forName(nameOfTheClass)
Java API Class

Java: CSV file read & write

I'm reading 2 csv files: store_inventory & new_acquisitions.
I want to be able to compare the store_inventory csv file with new_acquisitions.
1) If the item names match just update the quantity in store_inventory.
2) If new_acquisitions has a new item that does not exist in store_inventory, then add it to the store_inventory.
Here is what i have done so far but its not very good. I added comments where i need to add taks 1 & 2.
Any advice or code to do the above tasks would be great! thanks.
File new_acq = new File("/src/test/new_acquisitions.csv");
Scanner acq_scan = null;
try {
acq_scan = new Scanner(new_acq);
} catch (FileNotFoundException ex) {
Logger.getLogger(mainpage.class.getName()).log(Level.SEVERE, null, ex);
}
String itemName;
int quantity;
Double cost;
Double price;
File store_inv = new File("/src/test/store_inventory.csv");
Scanner invscan = null;
try {
invscan = new Scanner(store_inv);
} catch (FileNotFoundException ex) {
Logger.getLogger(mainpage.class.getName()).log(Level.SEVERE, null, ex);
}
String itemNameInv;
int quantityInv;
Double costInv;
Double priceInv;
while (acq_scan.hasNext()) {
String line = acq_scan.nextLine();
if (line.charAt(0) == '#') {
continue;
}
String[] split = line.split(",");
itemName = split[0];
quantity = Integer.parseInt(split[1]);
cost = Double.parseDouble(split[2]);
price = Double.parseDouble(split[3]);
while(invscan.hasNext()) {
String line2 = invscan.nextLine();
if (line2.charAt(0) == '#') {
continue;
}
String[] split2 = line2.split(",");
itemNameInv = split2[0];
quantityInv = Integer.parseInt(split2[1]);
costInv = Double.parseDouble(split2[2]);
priceInv = Double.parseDouble(split2[3]);
if(itemName == itemNameInv) {
//update quantity
}
}
//add new entry into csv file
}
Thanks again for any help. =]
Suggest you use one of the existing CSV parser such as Commons CSV or Super CSV instead of reinventing the wheel. Should make your life a lot easier.
Your implementation makes the common mistake of breaking the line on commas by using line.split(","). This does not work because the values themselves might have commas in them. If that happens, the value must be quoted, and you need to ignore commas within the quotes. The split method can not do this -- I see this mistake a lot.
Here is the source of an implementation that does it correctly:
http://agiletribe.purplehillsbooks.com/2012/11/23/the-only-class-you-need-for-csv-files/
With help of the open source library uniVocity-parsers, you could develop with pretty clean code as following:
private void processInventory() throws IOException {
/**
* ---------------------------------------------
* Read CSV rows into list of beans you defined
* ---------------------------------------------
*/
// 1st, config the CSV reader with row processor attaching the bean definition
CsvParserSettings settings = new CsvParserSettings();
settings.getFormat().setLineSeparator("\n");
BeanListProcessor<Inventory> rowProcessor = new BeanListProcessor<Inventory>(Inventory.class);
settings.setRowProcessor(rowProcessor);
settings.setHeaderExtractionEnabled(true);
// 2nd, parse all rows from the CSV file into the list of beans you defined
CsvParser parser = new CsvParser(settings);
parser.parse(new FileReader("/src/test/store_inventory.csv"));
List<Inventory> storeInvList = rowProcessor.getBeans();
Iterator<Inventory> storeInvIterator = storeInvList.iterator();
parser.parse(new FileReader("/src/test/new_acquisitions.csv"));
List<Inventory> newAcqList = rowProcessor.getBeans();
Iterator<Inventory> newAcqIterator = newAcqList.iterator();
// 3rd, process the beans with business logic
while (newAcqIterator.hasNext()) {
Inventory newAcq = newAcqIterator.next();
boolean isItemIncluded = false;
while (storeInvIterator.hasNext()) {
Inventory storeInv = storeInvIterator.next();
// 1) If the item names match just update the quantity in store_inventory
if (storeInv.getItemName().equalsIgnoreCase(newAcq.getItemName())) {
storeInv.setQuantity(newAcq.getQuantity());
isItemIncluded = true;
}
}
// 2) If new_acquisitions has a new item that does not exist in store_inventory,
// then add it to the store_inventory.
if (!isItemIncluded) {
storeInvList.add(newAcq);
}
}
}
Just follow this code sample I worked out according to your requirements. Note that the library provided simplified API and significent performance for parsing CSV files.
The operation you are performing will require that for each item in your new acquisitions, you will need to search each item in inventory for a match. This is not only not efficient, but the scanner that you have set up for your inventory file would need to be reset after each item.
I would suggest that you add your new acquisitions and your inventory to collections and then iterate over your new acquisitions and look up the new item in your inventory collection. If the item exists, update the item. If it doesnt, add it to the inventory collection. For this activity, it might be good to write a simple class to contain an inventory item. It could be used for both the new acquisitions and for the inventory. For a fast lookup, I would suggest that you use HashSet or HashMap for your inventory collection.
At the end of the process, dont forget to persist the changes to your inventory file.
As Java doesn’t support parsing of CSV files natively, we have to rely on third party library. Opencsv is one of the best library available for this purpose. It’s open source and is shipped with Apache 2.0 licence which makes it possible for commercial use.
Here, this link should help you and others in the situations!
For writing to CSV
public void writeCSV() {
// Delimiter used in CSV file
private static final String NEW_LINE_SEPARATOR = "\n";
// CSV file header
private static final Object[] FILE_HEADER = { "Empoyee Name","Empoyee Code", "In Time", "Out Time", "Duration", "Is Working Day" };
String fileName = "fileName.csv");
List<Objects> objects = new ArrayList<Objects>();
FileWriter fileWriter = null;
CSVPrinter csvFilePrinter = null;
// Create the CSVFormat object with "\n" as a record delimiter
CSVFormat csvFileFormat = CSVFormat.DEFAULT.withRecordSeparator(NEW_LINE_SEPARATOR);
try {
fileWriter = new FileWriter(fileName);
csvFilePrinter = new CSVPrinter(fileWriter, csvFileFormat);
csvFilePrinter.printRecord(FILE_HEADER);
// Write a new student object list to the CSV file
for (Object object : objects) {
List<String> record = new ArrayList<String>();
record.add(object.getValue1().toString());
record.add(object.getValue2().toString());
record.add(object.getValue3().toString());
csvFilePrinter.printRecord(record);
}
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
fileWriter.flush();
fileWriter.close();
csvFilePrinter.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
You can use Apache Commons CSV api.
FYI this anwser : https://stackoverflow.com/a/42198895/6549532
Read / Write Example

Categories