Using persistent layout with custom nodes and edges - java

I'm using the Jung library to create graphs. I want to use the persistent layout to generate the same graph every time.
I copied pasted this working code:
http://jung.sourceforge.net/site/jung-samples/xref/edu/uci/ics/jung/samples/PersistentLayoutDemo.html?
And all I changed was the graph that was being created. The graph I created has custom nodes and edges. But now when I try to to restore I get (im using eclipse):
Exception in thread "main" java.lang.Error: Unresolved compilation problem:
at helloworld.main.main(main.java:161)
And when i go to the problems view in eclipse(i was at console before) there are 2 errors:
1) Syntax error on token ";", { expected after this token
This is at the line:
BufferedReader reader = new BufferedReader(new FileReader("Topology2.csv"));
2)Syntax error, insert "}" to complete Block
This is at the line :
PersistentLayout<nodes,Edges> persistentLayout;
This is my code:
public class main {
/**
* the graph
*/public static nodes find(String a, ArrayList<nodes> b) {
for (int i = 0; i < b.size(); i++) {
if (a.compareTo(b.get(i).name) == 0){
return b.get(i);
}
}
//System.out.println("Couldnt find node: " + a);
return b.get(0);
}
/**
* the name of the file where the layout is saved
*/
String fileName;
/**
* the visual component and renderer for the graph
*/
VisualizationViewer<nodes,Edges> vv;
PersistentLayout<nodes,Edges> persistentLayout;
/**
* create an instance of a simple graph with controls to
* demo the persistence and zoom features.
*
* #param fileName where to save/restore the graph positions
*/
public main(final String fileName) throws Exception {
Graph<nodes, Edges> g = new SparseMultigraph<nodes, Edges>();
ArrayList<nodes> araylist = new ArrayList<nodes>();
String line = null;
BufferedReader reader = new BufferedReader(new FileReader("Topology2.csv"));
while ((line = reader.readLine()) != null) {
nodes newNode = new nodes (line);
araylist.add(newNode);
}
reader.close();
BufferedReader reader2 = new BufferedReader(new FileReader("Topology.csv"));
int counter = 0;
while ((line = reader2.readLine()) != null) {
counter++;
String[] a = line.split(",");
int number = a.length;
//System.out.println("length: " + number);
nodes origin = find(a[0],araylist);
nodes prev = find(a[1], araylist);
if (number >= 3) {
nodes next = find(a[2], araylist);
g.addEdge(new Edges(counter,origin,next),origin, next);
}
g.addEdge(new Edges(counter,origin,prev),origin, prev);
counter++;
}
reader2.close();
this.fileName = fileName;
// create a simple graph for the demo
persistentLayout =
new PersistentLayoutImpl<nodes,Edges>(new FRLayout<nodes,Edges>(g));
vv = new VisualizationViewer<nodes,Edges>(persistentLayout);
// add my listener for ToolTips
vv.setVertexToolTipTran sformer(new ToStringLabeller());
DefaultModalGraphMouse gm = new DefaultModalGraphMouse();
vv.setGraphMouse(gm);
// create a frome to hold the graph
final JFrame frame = new JFrame();
frame.getContentPane().add(new GraphZoomScrollPane(vv));
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
// create a control panel and buttons for demo
// functions
JPanel p = new JPanel();
JButton persist = new JButton("Save Layout");
// saves the graph vertex positions to a file
persist.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
try {
persistentLayout.persist(fileName);
} catch (IOException e1) {
System.err.println("got "+e1);
}
}
});
p.add(persist);
JButton restore = new JButton("Restore Layout");
// restores the graph vertex positions from a file
// if new vertices were added since the last 'persist',
// they will be placed at random locations
restore.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
// PersistentLayout<nodes,Edges> pl = (PersistentLayout<nodes,Edges>) vv.getGraphLayout();
try {
persistentLayout.restore(fileName);
} catch (Exception e1) {
e1.printStackTrace();
}
}
});
p.add(restore);
p.add(gm.getModeComboBox());
frame.getContentPane().add(p, BorderLayout.SOUTH);
frame.pack();//setSize(600, 600);
frame.setVisible(true);
}
/**
* a driver for this demo
* #param args should hold the filename for the persistence demo
* #throws Exception
*/
public static void main(String[] args) throws Exception {
String filename;
if (args.length >= 1)
filename = args[0];
else
filename = "PersistentLayoutDemo.out";
new main(filename);
}
}
Code for custom edges:
public class Edges {
int id;
nodes start;
nodes end;
public Edges(int id_, nodes a, nodes b) {
id = id_;
start = a;
end = b;
}
}
Code for custom nodes:
package helloworld;
import java.io.Serializable;
public class nodes {
String name = "";
nodes next = null;
nodes prev = null;
boolean alarm = false;
String alarmLevel = "";
String alarmCaption = "";
String alarmInfo = "";
public nodes(String na) {
name = na;
}
public nodes(String na, String n, String p, boolean a, String lvl, String cap, String info) {
name = na;
next = new nodes();
prev = new nodes();
next.name = n;
prev.name = p;
alarm = a;
alarmLevel = lvl;
alarmCaption = cap;
alarmInfo = info;
}
public nodes() {
// TODO Auto-generated constructor stub
}
}

Inside the nodes constructor you're assigning next.name but never initializing next, which is null. That's at least part of your problem.
Side note: your edge class has references to two nodes objects for no readily apparent reason, and I'm not sure what the prev and next are for in the nodes class, either.
You need to figure out what your data model is supposed to be, and bear in mind that the Graph class is keeping track of the node/edge connections.

Related

Verifying information about the graph

I'm having difficulty attempting to print the contents of my Graph using a toString method. Moreover, I do not receive an error when I add my Vertex to my Graph but I am unsure if I am properly adding my Vertexes. Thank you to anyone for any help!
Here's the App.
public class App
{
public static void main(String[] args)
{
File EdgeFile = new File("/User/src/main/java/edu.sdsu.cs/datastructures/threeVertexList.csv");
File VertexFile = new File("User/src/main/java/edu.sdsu.cs/datastructures/threeEdgesList.csv");
if (EdgeFile.exists() && EdgeFile.isFile() && VertexFile.exists() && VertexFile.isFile()) // Checks to see if Files are in existence
{
IGraph<String, Integer> Graph = new WDGraph<>(); // Instantiating the Graph
BufferedReader in = null;
try {
in = new BufferedReader(new FileReader("cities.csv"));
String read = null;
while ((read = in.readLine()) != null) {
String[] split = read.split(",");
for (String part : split) {
Graph.addVertex(part);
}
}
} catch (IOException e) {
System.out.println("There was a problem: " + e);
e.printStackTrace();
} finally {
try {
in.close();
} catch (Exception e) {
}
}
}
else
{
System.out.println("Error: Incorrect number of input arguments (0 or 2 expected), X provided");
}
toString(); // method to overwrite to check contents of Vertices
}
}
Here is my Graph.
class WDGraph<V,E> implements IGraph<V,E> {
private final List<IVertex> nodes;
private final List<IEdge> edges;
WDGraph() {
this.nodes = nodes;
this.edges = edges;
}
private List<IVertex> getVertexes() {
return nodes;
}
private List<IEdge> getEdges() {
return edges;
}

ArrayList different method's scope

I have a problem with the code below. I'm getting different results base on where the line list = new ArrayList<InClass>(); is declared. In place //B but everything works fine when I add it to //A and I cannot understand the difference. Here is the code:
import java.util.*;
import java.io.*;
public class ArrayListOne {
private ArrayList<InClass> list;
private InClass in;
public static void main(String args[]) {
ArrayListOne a = new ArrayListOne();
a.readFile();
}
public void readFile() {
//A
/**
* adding "list = new ArrayList<InClass>();"
* getting all 4 lines of test.txt
*/
try {
File file = new File("test.txt");
BufferedReader reader = new BufferedReader(new FileReader(file));
String line = null;
while ((line = reader.readLine()) != null) {
assignToObject(line);
}
} catch (Exception ex) {
ex.printStackTrace();
}
readObject();
}
public void assignToObject(String s) {
//B
/**
* adding "list = new ArrayList<InClass>();"
* getting just last line of test.txt
*/
InClass n = new InClass(s);
list.add(n);
System.out.println(list.size());
}
public void readObject() {
for (int i=0; i<list.size(); i++) {
in = list.get(i);
System.out.println(in.stTest);
}
}
//inner class
public class InClass {
String stTest;
public InClass(String s) {
stTest = s;
}
}
}
the test.txt has 3 lines. in //A, I'm getting all three lines (what I want) but in //B I just get the last line.
It's easier to see the difference if you "inline" assignToObject() by copy-pasting the contents of assignToObject() to the proper place in readFile():
public void readFile() {
// B
// list = new ArrayList<InClass>();
try {
File file = new File("test.txt");
BufferedReader reader = new BufferedReader(new FileReader(file));
String line = null;
while ((line = reader.readLine()) != null) {
// Here is where assignToObject() was //
// B
// list = new ArrayList<InClass>();
InClass n = new InClass(line);
list.add(n);
System.out.println(list.size());
}
} catch (Exception ex) {
ex.printStackTrace();
}
readObject();
}
Now think about if you put list = new ArrayList<InClass>() in A and B.
If you declare list = new ArrayList<InClass>() at A (i.e. inside readFile()), the statement will be executed once -- when readFile() is called in main(). So you'll end up with one ArrayList containing everything you need.
However, if you declare list = new ArrayList<InClass>() at B (i.e. inside assignToObject()), you'll get a new list for every line you read (i.e. every time you call assignToObject()). This means that every iteration you'll end up with a new ArrayList that only contains the most recently read line. The ArrayList containing the previous line was thrown away, as the reference that used to point to it now points to a new object.

Null pointer when trying to access an integer in another class in java

I'm trying to make a simple color manipulation program that allows you to change the color of a box in a window. I'm using some preset colors by reading them in from a file into a class that I have specifically set up to contain those values. I'm using arrays to contain all the preset values and when I try to access the individual elements of that array, I keep getting a nullpointer exception. This is my first time try to use java, so I assume i'm making a boneheaded mistake.
Here is my code:
package color.sampler;
import java.io.*;
import javax.swing.*;
import javax.swing.event.*;
public class ColorSampler extends JFrame
{
protected ColorFrame sampler;
public JList colorList;
protected colors [] listOfColors;
/**
* #param args the command line arguments
*/
public static void main(String[] args) throws IOException
{
new ColorSampler("ColorSampler");
}
public ColorSampler(String title) throws IOException
{
super(title);
setBounds(100,100,300,300);
addWindowListener(new WindowDestroyer());
sampler = new ColorFrame();
getContentPane().setLayout(null);
getContentPane().add(sampler);
sampler.setBounds(10,10,270,200);
FileInputStream stream = new FileInputStream("C:\\java input\\input.txt");
InputStreamReader reader;
reader = new InputStreamReader(stream);
StreamTokenizer tokens = new StreamTokenizer(reader);
int numColors, counter;
numColors = 11;
counter = 0;
listOfColors = new colors[numColors];
while(tokens.nextToken() != tokens.TT_EOF)
{
listOfColors[counter].name = (String)tokens.sval;
tokens.nextToken();
listOfColors[counter].r = (int)tokens.nval;
System.out.println(listOfColors[counter].r);
tokens.nextToken();
listOfColors[counter].g = (int)tokens.nval;
tokens.nextToken();
listOfColors[counter].b = (int)tokens.nval;
counter++;
}
stream.close();
colorList = new JList();
colorList.addListSelectionListener(new ListHandler());
String colorString[];
colorString = new String[numColors];
for(counter = 0; counter < numColors; counter++)
{
colorString[counter] = listOfColors[counter].name;
}
colorList.setListData(colorString);
getContentPane().add(colorList);
setVisible(true);
// TODO code application logic here
}
private class ListHandler implements ListSelectionListener
{
#Override
public void valueChanged(ListSelectionEvent e)
{
if(e.getSource() == colorList)
{
if(!e.getValueIsAdjusting())
{
int i = colorList.getSelectedIndex();
String s = (String) colorList.getSelectedValue();
System.out.println("Position " + i + " selected: " + s);
}
}
}
}
}
and the class I'm using to store the values:
public class colors
{
public int r, g, b;
public String name;
public colors()
{
r = 0;
g = 0;
b = 0;
name = "bob";
}
}
So, how would I fix the issue caused when I try to access the first element's name in the array?
I guess you need to initialize each object of the listOfColors array also, change your while loop to...
counter = 0;
listOfColors = new colors[numColors];
while(tokens.nextToken() != tokens.TT_EOF)
{
listOfColors[counter] = new Colors();
listOfColors[counter].name = (String)tokens.sval;
tokens.nextToken();
listOfColors[counter].r = (int)tokens.nval;
System.out.println(listOfColors[counter].r);
tokens.nextToken();
listOfColors[counter].g = (int)tokens.nval;
tokens.nextToken();
listOfColors[counter].b = (int)tokens.nval;
counter++;
}
Just because you do this:
listOfColors = new colors[numColors];
doesn't mean that the array has anything in it. In fact, at this point, it is an array of null values. You need to construct a colors object for each element before setting the names and color values.
And by the way, the class name for colors should start with a capital: Colors.

A Producer-Consumer implemented using java threads writes only half the data to file

Hello I have a problem wherein I have to read a huge csv file. remove first field from it, then store only unique values to a file. I have written a program using threads which implements producer-consumer pattern.
Class CSVLineStripper does what the name suggests. Takes a line out of csv, removes first field from every line and adds it to a queue. CSVLineProcessor then takes that field stores all one by one in an arraylist and checks if fields are unique so only uniques are stored. Arraylist is only used for reference. every unique field is written to a file.
Now what is happening is that all fields are stripped correctly. I run about 3000 lines it's all correct. When I start the program for all lines, which are around 7,00,000 + lines, i get incomplete records, about 1000 unique are not taken. Every field is enclosed in double-quotes. What is weird is that the last field in the file that is generated is an incomplete word and ending double quote is missing. Why is this happening?
import java.util.*;
import java.io.*;
class CSVData
{
Queue <String> refererHosts = new LinkedList <String> ();
Queue <String> uniqueReferers = new LinkedList <String> (); // final writable queue of unique referers
private int finished = 0;
private int safety = 100;
private String line = "";
public CSVData(){}
public synchronized String getCSVLine() throws InterruptedException{
int i = 0;
while(refererHosts.isEmpty()){
if(i < safety){
wait(10);
}else{
return null;
}
i++;
}
finished = 0;
line = refererHosts.poll();
return line;
}
public synchronized void putCSVLine(String CSVLine){
if(finished == 0){
refererHosts.add(CSVLine);
this.notifyAll();
}
}
}
class CSVLineStripper implements Runnable //Producer
{
private CSVData cd;
private BufferedReader csv;
public CSVLineStripper(CSVData cd, BufferedReader csv){ // CONSTRUCTOR
this.cd = cd;
this.csv = csv;
}
public void run() {
System.out.println("Producer running");
String line = "";
String referer = "";
String [] CSVLineFields;
int limit = 700000;
int lineCount = 1;
try {
while((line = csv.readLine()) != null){
CSVLineFields = line.split(",");
referer = CSVLineFields[0];
cd.putCSVLine(referer);
lineCount++;
if(lineCount >= limit){
break;
}
}
} catch (IOException e) {
e.printStackTrace();
}
System.out.println("<<<<<< PRODUCER FINISHED >>>>>>>");
}
private String printString(String [] str){
String string = "";
for(String s: str){
string = string + " "+s;
}
return string;
}
}
class CSVLineProcessor implements Runnable
{
private CSVData cd;
private FileWriter fw = null;
private BufferedWriter bw = null;
public CSVLineProcessor(CSVData cd, BufferedReader bufferedReader){ // CONSTRUCTOR
this.cd = cd;
try {
this.fw = new FileWriter("unique_referer_dump.txt");
} catch (IOException e) {
e.printStackTrace();
}
this.bw = new BufferedWriter(fw);
}
public void run() {
System.out.println("Consumer Started");
String CSVLine = "";
int safety = 10000;
ArrayList <String> list = new ArrayList <String> ();
while(CSVLine != null || safety <= 10000){
try {
CSVLine = cd.getCSVLine();
if(!list.contains(CSVLine)){
list.add(CSVLine);
this.CSVDataWriter(CSVLine);
}
} catch (Exception e) {
e.printStackTrace();
}
if(CSVLine == null){
break;
}else{
safety++;
}
}
System.out.println("<<<<<< CONSUMER FINISHED >>>>>>>");
System.out.println("Unique referers found in 30000 records "+list.size());
}
private void CSVDataWriter(String referer){
try {
bw.write(referer+"\n");
} catch (Exception e) {
e.printStackTrace();
}
}
}
public class RefererCheck2
{
public static void main(String [] args) throws InterruptedException
{
String pathToCSV = "/home/shantanu/DEV_DOCS/Contextual_Work/excite_domain_kw_site_wise_click_rev2.csv";
CSVResourceHandler csvResHandler = new CSVResourceHandler(pathToCSV);
CSVData cd = new CSVData();
CSVLineProcessor consumer = new CSVLineProcessor(cd, csvResHandler.getCSVFileHandler());
CSVLineStripper producer = new CSVLineStripper(cd, csvResHandler.getCSVFileHandler());
Thread consumerThread = new Thread(consumer);
Thread producerThread = new Thread(producer);
producerThread.start();
consumerThread.start();
}
}
This is how a sample input is:
"xyz.abc.com","4432"."clothing and gifts","true"
"pqr.stu.com","9537"."science and culture","false"
"0.stu.com","542331"."education, studies","false"
"m.dash.com","677665"."technology, gadgets","false"
Producer stores in queue:
"xyz.abc.com"
"pqr.stu.com"
"0.stu.com"
"m.dash.com"
Consumer stores uniques in the file, but after opening file contents one would see
"xyz.abc.com"
"pqr.stu.com"
"0.st
Couple things, you are breaking after 700k, not 7m, also you are not flushing your buffered writer, so the last stuff you could be incomplete, add flush at end and close all your resources. Debugger is a good idea :)

Let the user enter the filename

I created an interface that allows to add instances in an rdf file. I put the filepath in the readRDFfile parameter and the same filepath in Filewriter (in order to update the file when user add instances). But i'd like to allow user enter the name file he want to create when I execute the code. And FileWriter must take this file in parameter when user add instances.
My problem is that I don't know how to put the file that user has chosen and that was read in readRDFfile, in Filewriter parameter in order to be updated when he adds instances.
import java.util.*;
import java.util.List;
import com.hp.hpl.jena.rdf.model.*;
import com.hp.hpl.jena.ontology.*;
import com.hp.hpl.jena.ontology.impl.*;
import com.hp.hpl.jena.util.*;
import java.io.*;
import java.awt.*;
import java.awt.event.*;
import com.hp.hpl.jena.vocabulary.RDF;
import com.hp.hpl.jena.vocabulary.XSD;
import com.hp.hpl.jena.util.iterator.ExtendedIterator;
public class FamilyModel extends Frame
{
TextField[]tabTF=new TextField[4];
Button bAjout, bModifier, bSupprimer, bPrecedent, bSuivant, bValiderModif; //buttons Add, Remove, Previous, Next
OntModel model;
Onto onto;
int indice=0;
int p=0;
Resource p1;
Button creerBouton(String S, int x, int y)
{
Button b=new Button(S);
add(b);
b.setBounds(x,y,120,30);
return b;
}
void creerLabel(String etiquette, int x, int y)
{
Label la=new Label(etiquette);
la.setBounds(x,y,100,25);
add(la);
}
public FamilyModel ()
{
setLayout (null);
setBackground (Color.pink);
setBounds (100,200,900,450);
creerLabel("Prenom : ",10,50);
creerLabel("Nom : ",10,100);
creerLabel("Date de Naissance: ",10,145);
creerLabel("Genre (H ou F): ",10,190);
//TextFields
for(int i=0;i<4;i++)
{
tabTF[i]=new TextField("");
tabTF[i].setBackground(Color.white);
add(tabTF[i]);
}
tabTF[0].setBounds(120,45,150,25);
tabTF[1].setBounds(120,100,150,25);
tabTF[2].setBounds(120,145, 100,25);
tabTF[3].setBounds(120,190, 45,25);
bAjout=creerBouton("Ajouter",20,250);
setVisible(true);
bModifier=creerBouton("Modifier",138,250);
setVisible(true);
//bSupprimer=creerBouton("Supprimer",250,250);
//setVisible(true);
bPrecedent=creerBouton("Precedent",360,250);
bSuivant=creerBouton("Suivant",450,250);
bSupprimer=creerBouton("Supprimer",600,250);
setVisible(true);
onto = new Onto();
readRDFfile();
traitement(this);
}
void traitement(Frame fenetre)
{
bAjout.addActionListener(new ActionAjoutPersonne());
//bModifier.addActionListener(new ActionModifier());
//bValiderModif.addActionListener(new ActionModif());
bSuivant.addActionListener(new ActionSuivant());
bPrecedent.addActionListener(new ActionPrecedent());
bSupprimer.addActionListener(new ActionSupprimer());
}
//Button Add
public class ActionAjoutPersonne implements ActionListener
{
public void actionPerformed(ActionEvent evt)
{
p1=onto.model.createResource(onto.uriBase+"#"+tabTF[0].getText());
p1.addProperty(onto.aPourPrenom, tabTF[0].getText());
p1.addProperty(onto.aPourNom, tabTF[1].getText());
p1.addProperty(onto.aDateNaiss, tabTF[2].getText());
if (tabTF[3].getText().equals("F"))
{
p1.addProperty(onto.aGenre, tabTF[3].getText());
p1.addProperty(RDF.type, onto.femme);
}
else if (tabTF[3].getText().equals("H"))
{
p1.addProperty(onto.aGenre, tabTF[3].getText());
p1.addProperty(RDF.type, onto.homme);
}
StringWriter sw = new StringWriter();
onto.model.write(sw, "RDF/XML-ABBREV");
String owlCode = sw.toString();
File file = new File("d:/Onto.rdf");
try{
FileWriter fw = new FileWriter(file);
fw.write(owlCode);
fw.close();
} catch(FileNotFoundException fnfe){
fnfe.printStackTrace();}
catch(IOException ioe){
ioe.printStackTrace();
}
}
}
//Button Remove
public class ActionSupprimer implements ActionListener
{
public void actionPerformed(ActionEvent evt)
{
List<Statement> statementsToRemove = new ArrayList<Statement>();
StmtIterator iter = onto.model.listStatements();
while (iter.hasNext())
{
Statement stmt = iter.nextStatement();
Resource subject = stmt.getSubject();
Property predicate = stmt.getPredicate();
RDFNode object = stmt.getObject();
if(subject.toString().equals (onto.uriBase+"#"+tabTF[0].getText()))
{
statementsToRemove.add(stmt);
}
}
for( Statement stmt : statementsToRemove)
{
onto.model.remove(stmt);
}
StringWriter sw = new StringWriter();
onto.model.write(sw, "RDF/XML-ABBREV");
String owlCode = sw.toString();
File file = new File("d:/Onto.rdf");
try{
FileWriter fw = new FileWriter(file);
fw.write(owlCode);
fw.close();
} catch(FileNotFoundException fnfe){
fnfe.printStackTrace();}
catch(IOException ioe){
ioe.printStackTrace();
}
}
}
//Read Onto.rdf
public void readRDFfile()
{
String inputFile="D:/Onto.rdf";
try
{
InputStream in =new FileInputStream(inputFile);
if (in == null) {
System.out.println("File not found");
}
onto.model.read(in, null);
}catch(Exception e) {
System.out.println("model.read catched error: " + e);
}
}
//Button Next
class ActionSuivant implements ActionListener
{
public void actionPerformed(ActionEvent evt)
{
++indice;
ExtendedIterator instances = onto.personne.listInstances();
Individual instance = null;
Individual firstInstance = null;
for (p = 0; p < indice && instances.hasNext(); p++) {
instance = (Individual) instances.next();
if (firstInstance == null) {
firstInstance = instance;
}
}
if (p < indice) {
indice = 1;
instance = firstInstance;
}
tabTF[0].setText(instance.getPropertyValue(onto.aPourPrenom).toString());
tabTF[1].setText(instance.getPropertyValue(onto.aPourNom).toString());
tabTF[2].setText(instance.getPropertyValue(onto.aDateNaiss).toString());
tabTF[3].setText(instance.getPropertyValue(onto.aGenre).toString());
}
}
class ActionPrecedent implements ActionListener
{
public void actionPerformed(ActionEvent evt)
{
--indice;
//Instances de la Classe Personne
ExtendedIterator instances=onto.personne.listInstances();
Individual instance = null;
for(p = 0; p < indice && instances.hasNext(); p++)
{
instance = (Individual) instances.next();
}
tabTF[0].setText(instance.getPropertyValue(onto.aPourPrenom).toString());
tabTF[1].setText(instance.getPropertyValue(onto.aPourNom).toString());
tabTF[2].setText(instance.getPropertyValue(onto.aDateNaiss).toString());
tabTF[3].setText(instance.getPropertyValue(onto.aGenre).toString());
}
}
//Ontology
public class Onto
{
OntClass personne, genre, homme, femme, feminin, masculin, evenement, deces, mariage, divorce;
OntModel model;
String uriBase;
ObjectProperty aPourFils, aPourFille, aGenre;
DatatypeProperty aPourNom, aPourPrenom, aDateNaiss;
public Onto (){
model = ModelFactory.createOntologyModel( OntModelSpec.OWL_MEM_MICRO_RULE_INF );
uriBase = "http://www.something.com/FAM";
model.createOntology(uriBase);
//Classes
personne = model.createClass(uriBase+"personne");
femme = model.createClass(uriBase+"femme");
homme = model.createClass(uriBase+"homme");
genre = model.createClass(uriBase+"genre");
feminin = model.createClass(uriBase+"feminin");
masculin = model.createClass(uriBase+"masculin");
evenement = model.createClass(uriBase+"evenement");
deces = model.createClass(uriBase+"deces");
mariage = model.createClass(uriBase+"mariage");
divorce = model.createClass(uriBase+"divorce");
//Sub-classes
genre.addSubClass(feminin);
genre.addSubClass(masculin);
personne.addSubClass(homme);
personne.addSubClass(femme);
evenement.addSubClass(deces);
evenement.addSubClass(mariage);
evenement.addSubClass(divorce);
aPourFils = model.createObjectProperty(uriBase+"aPourFils");
aPourFils.setDomain(personne);
aPourFils.setRange(homme);
aPourFille = model.createObjectProperty(uriBase+"aPourFille");
aPourFille.setDomain(personne);
aPourFille.setRange(femme);
aGenre = model.createObjectProperty(uriBase+"aGenre");
aGenre.setDomain(personne);
aGenre.setRange(genre);
aPourNom = model.createDatatypeProperty(uriBase+"aPourNom");
aPourNom.setDomain(personne);
aPourNom.setRange(XSD.xstring);
aPourPrenom = model.createDatatypeProperty(uriBase+"aPourPrenom");
aPourPrenom.setDomain(personne);
aPourPrenom.setRange(XSD.xstring);
aDateNaiss = model.createDatatypeProperty(uriBase+"aDateNaiss");
aDateNaiss.setDomain(personne);
aDateNaiss.setRange(XSD.xstring);
}
}
public static void main(String args[])
{
new FamilyModel();
}
}
If your app has a GUI, the standard way to select an input file would be to use a file chooser, for example JFileChooser if your app is Swing based, or FileDialog if you want to stick to AWT components.
Here is an exmaple for JFileChooser:
int returnVal = fc.showOpenDialog(FileChooserDemo.this);
if (returnVal == JFileChooser.APPROVE_OPTION) {
File file = fc.getSelectedFile();
String filename = file.getName();
}
JFileChooser Tutorial:
http://download.oracle.com/javase/tutorial/uiswing/components/filechooser.html
If your app is command line based (which I gather it not the case from your code for handling button clicks), you could make the input be one of the command line arguments when you run the app, and you could read it out of args[] array passed into main().
There are many options and schools of thought regarding how to get data from the user. Most of this depends on who the user will be and how they are going to be interacting with this program. A couple I've listed.
Command Line Interface This is my favorite because I'm in the terminal a lot and write a lot of bash scripts. Very simple and low development overhead, while still being extensible. You'll need to add code in your main method to retrieve options and values. I like using Apache Commons CLI even though it's not under active development, there is a good tutorial.
Graphical User Interface Use Java Swing or a web application to create a UI around your app. This will inevitably take much longer than any other option but will be the most accessible for non-technical users.
Standard In If you just want the program to pause and prompt the user on the console with no bells or whistles use this in main (if you using
Console con = System.console();
String file = con.readLine("File Name: ");

Categories

Resources