java SAX parser giving NullPointerException after change in working code - java

I'm modifying an app that loads data dynamically from an XML file that contains a quiz and displays questions and replies. The change consists in the fact that i want to load a single(hardcoded for now) file instead of using a JFileChooser.
Here's the relevant code working before(undefined variables are class attributes but i won't post the whole class declaration):
public ClassConstructor()
{
JMenuItem load = new JMenuItem("Load");
...
}
load.addActionListener(new ActionListener()
{
public void actionPerformed( ActionEvent e )
{
if(status == UNSAVED_CHANGES)
if(JOptionPane.showConfirmDialog(gThis , "There are unsaved changes. Continue?" , "Unsaved changes" , JOptionPane.OK_CANCEL_OPTION) == 2)
return;
int returnVal = filePick.showOpenDialog(new JPanel());
if(returnVal == JFileChooser.APPROVE_OPTION)
{
try
{
load(filePick.getSelectedFile().getCanonicalPath());
pathname = filePick.getSelectedFile().getCanonicalPath();
}
catch(IOException f)
{
System.out.println(f);
}
setupQuestion("q1");
openingLabel.setText(theBase.getDocumentElement().getAttribute("opening"));
status = FILE_LOADED;
}
}
}
);
private static void load(String fileName)
{
System.out.println(fileName);
try
{
DocumentBuilderFactory dbf =
DocumentBuilderFactory.newInstance();
dbf.setValidating(true);
DocumentBuilder db = dbf.newDocumentBuilder();
db.setErrorHandler(new DefaultHandler());
theBase = db.parse(fileName);
idno = Integer.parseInt(((Element)(theBase.getElementsByTagName("base").item(0))).getAttribute("idno"));
System.out.println(idno);
lastName = fileName;
status = FILE_LOADED;
}
catch(IOException e)
{
System.out.println(e);
}
catch(ParserConfigurationException p)
{
System.out.println(p);
}
catch(SAXException s)
{
System.out.println(s);
}
}
public static void setupQuestion(String qid)
{
linkids = new Vector();
links = new Vector();
qdata = new Vector();
Element e = theBase.getElementById(qid);
question.setText(e.getAttribute("value"));
int items = 0;
NodeList nl = e.getChildNodes();
for(int i=0; i &lt nl.getLength(); i++)
{
if(nl.item(i).getNodeType() == Node.ELEMENT_NODE)
{
items++;
qdata.add(((Element)nl.item(i)).getAttribute("content") );
linkids.add(((Element)nl.item(i)).getAttribute("link"));
links.add((Element)nl.item(i));
}
}
replies.setListData(qdata);
thisq = qid;
}
And now for the code that doesn't work:
public ClassConstructor()
{
//JMenuItem load = new JMenuItem("Load");
load("C:\\file.xml");
pathname = "C:\\file.xml";
setupQuestion("q1");
openingLabel.setText(theBase.getDocumentElement().getAttribute("opening"));
}
// i've dropped load.addActionListener() but rest of the code has no changes
Also, the exception:
Exception in thread "main" java.lang.NullPointerException
and it occurs at question.setText(e.getAttribute("value")); on calling setupQuestion("q1");.
Edit: Interestingly enough System.out.println(fileName); gets printed before the Exception is thrown and System.out.println(idno); is printed after it. Actually on restarting the IDE both echos appear after the exception is thrown.
I've been stuck on this for quite some time. Any help is much appreciated.

Found the culprit. I guess I haven't mentioned everything. I've forgot to allocate memory for question and replies. I am so ashamed.

Related

Most recent version of XML file not being read

I have created an application which takes user input from textfields and stores it in an XML file. The user can then reload these inputs back into a text field on the click of a button.
The issue I'm having is that the most recent version of the XML file is not being used - for example when I start the application and save new inputs the load function doesn't load the input even though the XML file has the data in it. When I close and then restart the application the load functionality works using the data from the last session. If I try adding new inputs the load button will just cycle through the data from the last session, not using the new points.
So my question is why isn't the current state of the XML file being read?
Save to XML Code:
ArrayList<SavedPosition> posList = new ArrayList<SavedPosition>();
String SAVEDPOS_XML = "savedPos.xml";
save.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
SavedPosition saved = new SavedPosition();
saved.setPosition1(mediaPlayerComponent.getMediaPlayer().getTime());
saved.setPosition2(mediaPlayerComponent2.getMediaPlayer().getTime());
saved.setNBehaviour(textArea.getText());
saved.setABehaviour(textArea1.getText());
saved.setGap(textArea2.getText());
saved.setForces(textArea3.getText());
saved.setFindings(textArea2.getText());
posList.add(saved);
SavedPositions savedPos = new SavedPositions();
savedPos.setSavedPositions(posList);
try {
// create JAXB context and instantiate marshaller
JAXBContext context = JAXBContext.newInstance(SavedPositions.class);
Marshaller m = context.createMarshaller();
m.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, Boolean.TRUE);
//print
m.marshal(savedPos, System.out);
//write to file
m.marshal(savedPos, new File(SAVEDPOS_XML));
} catch (JAXBException ex) {
Logger.getLogger(DoubleViewer.class.getName()).log(Level.SEVERE, null, ex);
}
}
});
XML to Object code:
public class XmlToObject {
public static ArrayList<ArrayList<String>> main() {
ArrayList<ArrayList<String>> obj1 = new ArrayList<ArrayList<String>>();
ArrayList<ArrayList<String>> obj = new ArrayList<ArrayList<String>>();
try{
DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
DocumentBuilder db = dbf.newDocumentBuilder();
Document d = db.parse("savedPos.xml");
XPath xp = XPathFactory.newInstance().newXPath();
NodeList nl = (NodeList) xp.compile("//savedPosition").evaluate(d, XPathConstants.NODESET);
System.out.println("number of saved positions " + nl.getLength());
for (int i = 0; i < nl.getLength(); i++){
String a = (xp.compile("./NBehaviour").evaluate(nl.item(i)));
String b = (xp.compile("./ABehaviour").evaluate(nl.item(i)));
String c = (xp.compile("./gap").evaluate(nl.item(i)));
String d1 = (xp.compile("./forces").evaluate(nl.item(i)));
String e = (xp.compile("./findings").evaluate(nl.item(i)));
String f = (xp.compile("./position1").evaluate(nl.item(i)));
String g = (xp.compile("./position2").evaluate(nl.item(i)));
ArrayList<String> savedPosition = new ArrayList<String>();
savedPosition.add(a);
savedPosition.add(b);
savedPosition.add(c);
savedPosition.add(d1);
savedPosition.add(e);
savedPosition.add(f);
savedPosition.add(g);
obj.add(savedPosition);
}
return obj;
}catch(Exception l){
System.out.println(l.getMessage());
}
return obj1;
}
}
Load button code:
List<ArrayList<String>> obj = XmlToObject.main();
int a = obj.size();
load.addActionListener(new ActionListener() {
int displayedPositionIndex = 0;
public void actionPerformed(ActionEvent e) {
displayedPositionIndex++;
if(displayedPositionIndex >= obj.size()) {
displayedPositionIndex = 0; // to loop back to first after last position
}
setPosition(displayedPositionIndex);
}
private void setPosition(int index) {
List<String> positionData = obj.get(index);
textArea.setText(positionData.get(0));
textArea1.setText(positionData.get(1));
textArea2.setText(positionData.get(2));
textArea3.setText(positionData.get(3));
textArea4.setText(positionData.get(4));
Long position = Long.valueOf(positionData.get(5));
mediaPlayerComponent.getMediaPlayer().setTime(position);
mediaPlayerComponent2.getMediaPlayer().setPosition(Float.parseFloat(positionData.get(6)));
}
});

How to write a unit test for an XML parser I wrote in Java

The context is as follows:
I've got objects that represent Tweets (from Twitter). Each object has an id, a date and the id of the original tweet (if there was one).
I receive a file of tweets (where each tweet is in the format of 05/04/2014 12:00:00, tweetID, originalID and is in its' own line) and I want to save them as an XML file where each field has its' own tag.
I want to then be able to read the file and return a list of Tweet objects corresponding to the Tweets from the XML file.
After writing the XML parser that does this I want to test that it works correctly. I've got no idea how to test this.
The XML Parser:
public class TweetToXMLConverter implements TweetImporterExporter {
//there is a single file used for the tweets database
static final String xmlPath = "src/main/resources/tweetsDataBase.xml";
//some "defines", as we like to call them ;)
static final String DB_HEADER = "tweetDataBase";
static final String TWEET_HEADER = "tweet";
static final String TWEET_ID_FIELD = "id";
static final String TWEET_ORIGIN_ID_FIELD = "original tweet";
static final String TWEET_DATE_FIELD = "tweet date";
static File xmlFile;
static boolean initialized = false;
#Override
public void createDB() {
try {
Element tweetDB = new Element(DB_HEADER);
Document doc = new Document(tweetDB);
doc.setRootElement(tweetDB);
XMLOutputter xmlOutput = new XMLOutputter();
// display nice nice? WTF does that chinese whacko want?
xmlOutput.setFormat(Format.getPrettyFormat());
xmlOutput.output(doc, new FileWriter(xmlPath));
xmlFile = new File(xmlPath);
initialized = true;
} catch (IOException io) {
System.out.println(io.getMessage());
}
}
#Override
public void addTweet(Tweet tweet) {
if (!initialized) {
//TODO throw an exception? should not come to pass!
return;
}
SAXBuilder builder = new SAXBuilder();
try {
Document document = (Document) builder.build(xmlFile);
Element newTweet = new Element(TWEET_HEADER);
newTweet.setAttribute(new Attribute(TWEET_ID_FIELD, tweet.getTweetID()));
newTweet.setAttribute(new Attribute(TWEET_DATE_FIELD, tweet.getDate().toString()));
if (tweet.isRetweet())
newTweet.addContent(new Element(TWEET_ORIGIN_ID_FIELD).setText(tweet.getOriginalTweet()));
document.getRootElement().addContent(newTweet);
} catch (IOException io) {
System.out.println(io.getMessage());
} catch (JDOMException jdomex) {
System.out.println(jdomex.getMessage());
}
}
//break glass in case of emergency
#Override
public void addListOfTweets(List<Tweet> list) {
for (Tweet t : list) {
addTweet(t);
}
}
#Override
public List<Tweet> getListOfTweets() {
if (!initialized) {
//TODO throw an exception? should not come to pass!
return null;
}
try {
SAXBuilder builder = new SAXBuilder();
Document document;
document = (Document) builder.build(xmlFile);
List<Tweet> $ = new ArrayList<Tweet>();
for (Object o : document.getRootElement().getChildren(TWEET_HEADER)) {
Element rawTweet = (Element) o;
String id = rawTweet.getAttributeValue(TWEET_ID_FIELD);
String original = rawTweet.getChildText(TWEET_ORIGIN_ID_FIELD);
Date date = new Date(rawTweet.getAttributeValue(TWEET_DATE_FIELD));
$.add(new Tweet(id, original, date));
}
return $;
} catch (JDOMException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return null;
}
}
Some usage:
private TweetImporterExporter converter;
List<Tweet> tweetList = converter.getListOfTweets();
for (String tweetString : lines)
converter.addTweet(new Tweet(tweetString));
How can I make sure the the XML file I read (that contains tweets) corresponds to the file I receive (in the form stated above)?
How can I make sure the tweets I add to the file correspond to the ones I tried to add?
Assuming that you have the following model:
public class Tweet {
private Long id;
private Date date;
private Long originalTweetid;
//getters and seters
}
The process would be the following:
create an isntance of TweetToXMLConverter
create a list of Tweet instances that you expect to receive after parsing the file
feed the converter the list you generated
compare the list received by parsing the list and the list you initiated at the start of the test
public class MainTest {
private TweetToXMLConverter converter;
private List<Tweet> tweets;
#Before
public void setup() {
Tweet tweet = new Tweet(1, "05/04/2014 12:00:00", 2);
Tweet tweet2 = new Tweet(2, "06/04/2014 12:00:00", 1);
Tweet tweet3 = new Tweet(3, "07/04/2014 12:00:00", 2);
tweets.add(tweet);
tweets.add(tweet2);
tweets.add(tweet3);
converter = new TweetToXMLConverter();
converter.addListOfTweets(tweets);
}
#Test
public void testParse() {
List<Tweet> parsedTweets = converter.getListOfTweets();
Assert.assertEquals(parsedTweets.size(), tweets.size());
for (int i=0; i<parsedTweets.size(); i++) {
//assuming that both lists are sorted
Assert.assertEquals(parsedTweets.get(i), tweets.get(i));
};
}
}
I am using JUnit for the actual testing.

Method does not load data to jTable when said method is outside of the main GUI class

The problem with my program is that once the "getMP3Tags" method is removed from the main class which is called ""musicManagerUI", and placed within it's own class, the method does not send anything over to the appropriate methods in the "musicManagerUI" class. However, if the "getMP3Tags" method is placed within the "musicManagerUI" class then everything works perfectly. I want to know why this happens and if anyone can help me to resolve this issue, as I don't want to cluster up the "musicManagerUI" class with loads of methods.
Here is the constructor for the main class "musicManagerUI":
public musicManagerUI() {
super ("Music Manager");
initComponents();
handlerClass handler = new handlerClass();
jMenuItem5.addMouseListener(handler);
}
Here is one the four methods which prints out data to the jTable:
public void printArtistName(ArrayList arrayOfArtistNames)
{
DefaultTableModel model = (DefaultTableModel) jTable2.getModel();
if (arrayOfArtistNames == null) {model.setValueAt("No Artist Names Found", 0, 0);}
else {
Object [] rowData;
rowData = new Object[3];
for (Object x : arrayOfArtistNames)
{
model.addRow(rowData);
model.setValueAt(x, counterArtist, 0);
counterArtist++;
}
}
}
Here is the code for the mousepressed handler method:
public void mousePressed(MouseEvent e) {
DefaultTableModel model = (DefaultTableModel) jTable2.getModel();
if (counterArtist == 0){}
else if (counterArtist > 0) {
model.setRowCount(0);
counterArtist = 0; counterTitle = 0; counterAlbum = 0; genre = 0;}
String FILE_DIR = "C:\\Users\\Hazzy\\Desktop\\test-data\\";
String FILE_TEXT_EXT = ".mp3";
findCertainExtension fw = new findCertainExtension();
try {
fw.getMP3Tags(FILE_DIR);
} catch (IOException ex) {
System.err.println(" Could Not read file in ");
} catch (TagException ex) {
System.err.println(" Could Not find tag");
}
}
And finally the "getMP3Tags" method:
public void getMP3Tags( String path ) throws IOException, TagException,
try{
File root = new File( path );
File[] list = root.listFiles();
ArrayList addArtistTitle = new ArrayList();
ArrayList addTrackTitle = new ArrayList();
ArrayList addAlbumTitle = new ArrayList();
ArrayList addGenre = new ArrayList();
if (list == null) return;
for ( File f : list ) {
if ( f.isDirectory()) {
getMP3Tags( f.getAbsolutePath() );
}
else if (!f.getAbsoluteFile().toString().toLowerCase().endsWith("mp3"))
{
getMP3Tags(f.getAbsolutePath());
}
else{
musicManagerUI setFields = new musicManagerUI ();
//System.out.println(f.getAbsoluteFile());
for (Object x : list) {}
MP3File mp3file = new MP3File(f.getAbsoluteFile());
ID3v2_2 name = (ID3v2_2) mp3file.getID3v2Tag();
if (name.getLeadArtist().isEmpty() == true){ name.setLeadArtist("Unknown");}
else if (name.getSongTitle().isEmpty() == true) {name.setSongTitle("Unknown");}
else if (name.getSongGenre().isEmpty() == true) {name.setSongGenre("Unknown");}
else if (name.getAlbumTitle().isEmpty() == true) {name.setAlbumTitle("Unknown");}
addArtistTitle.add(name.getLeadArtist());
addTrackTitle.add(name.getSongTitle());
addAlbumTitle.add(name.getAlbumTitle());
addGenre.add(name.getSongGenre());
}
}
musicManagerUI sendTrackInfo = new musicManagerUI();
sendTrackInfo.printArtistName(addArtistTitle);
sendTrackInfo.printTrackTitle(addTrackTitle);
sendTrackInfo.printAlbumTitle(addAlbumTitle);
sendTrackInfo.printGenre(addGenre);
}
catch(NullPointerException e){
System.err.println("Unknown Artist");
//return;
}
}
}
For this program I am using the ID3 Tagging Library/API. If you need the full code then please email me. Thanks in advance.
Some other sources which may be useful:
JTable does not show anything?
Loading Java JTable: Why does it not work?
My first thought is that in your getMP3Tags method you are calling
musicManagerUI setFields = new musicManagerUI ();
Which is creating a new instance of the musicManagerUI which has no relationship to the one that is on the screen...
What you might consider doing is passing a reference of the current instance of musicManagerUI to the method instead...
fw.getMP3Tags(FILE_DIR, this);
Assuming this is an instance of musicManagerUI which is actually been displayed...
ps- I should mention that you are actually create another instance of musicManagerUI in the getMP3Tags...
musicManagerUI sendTrackInfo = new musicManagerUI();

using dbpedia spotlight in java or scala

Does anyone know where to find a little how to on using dbpedia spotlight in java or scala? Or could anyone explain how it's done? I can't find any information on this...
The DBpedia Spotlight wiki pages would be a good place to start.
And I believe the installation page has listed the most popular ways (using a jar, or set up a web service) to use the application.
It includes instructions on using the Java/Scala API with your own installation, or calling the Web Service.
There are some additional data needed to be downloaded to run your own server for full service, good time to make a coffee for yourself.
you need download dbpedia spotlight (jar file) after that u can use next two classes ( author pablomendes ) i only make some change .
public class db extends AnnotationClient {
//private final static String API_URL = "http://jodaiber.dyndns.org:2222/";
private static String API_URL = "http://spotlight.dbpedia.org:80/";
private static double CONFIDENCE = 0.0;
private static int SUPPORT = 0;
private static String powered_by ="non";
private static String spotter ="CoOccurrenceBasedSelector";//"LingPipeSpotter"=Annotate all spots
//AtLeastOneNounSelector"=No verbs and adjs.
//"CoOccurrenceBasedSelector" =No 'common words'
//"NESpotter"=Only Per.,Org.,Loc.
private static String disambiguator ="Default";//Default ;Occurrences=Occurrence-centric;Document=Document-centric
private static String showScores ="yes";
#SuppressWarnings("static-access")
public void configiration(double CONFIDENCE,int SUPPORT,
String powered_by,String spotter,String disambiguator,String showScores){
this.CONFIDENCE=CONFIDENCE;
this.SUPPORT=SUPPORT;
this.powered_by=powered_by;
this.spotter=spotter;
this.disambiguator=disambiguator;
this.showScores=showScores;
}
public List<DBpediaResource> extract(Text text) throws AnnotationException {
LOG.info("Querying API.");
String spotlightResponse;
try {
String Query=API_URL + "rest/annotate/?" +
"confidence=" + CONFIDENCE
+ "&support=" + SUPPORT
+ "&spotter=" + spotter
+ "&disambiguator=" + disambiguator
+ "&showScores=" + showScores
+ "&powered_by=" + powered_by
+ "&text=" + URLEncoder.encode(text.text(), "utf-8");
LOG.info(Query);
GetMethod getMethod = new GetMethod(Query);
getMethod.addRequestHeader(new Header("Accept", "application/json"));
spotlightResponse = request(getMethod);
} catch (UnsupportedEncodingException e) {
throw new AnnotationException("Could not encode text.", e);
}
assert spotlightResponse != null;
JSONObject resultJSON = null;
JSONArray entities = null;
try {
resultJSON = new JSONObject(spotlightResponse);
entities = resultJSON.getJSONArray("Resources");
} catch (JSONException e) {
//throw new AnnotationException("Received invalid response from DBpedia Spotlight API.");
}
LinkedList<DBpediaResource> resources = new LinkedList<DBpediaResource>();
if(entities!=null)
for(int i = 0; i < entities.length(); i++) {
try {
JSONObject entity = entities.getJSONObject(i);
resources.add(
new DBpediaResource(entity.getString("#URI"),
Integer.parseInt(entity.getString("#support"))));
} catch (JSONException e) {
LOG.error("JSON exception "+e);
}
}
return resources;
}
}
second class
/**
* #author pablomendes
*/
public abstract class AnnotationClient {
public Logger LOG = Logger.getLogger(this.getClass());
private List<String> RES = new ArrayList<String>();
// Create an instance of HttpClient.
private static HttpClient client = new HttpClient();
public List<String> getResu(){
return RES;
}
public String request(HttpMethod method) throws AnnotationException {
String response = null;
// Provide custom retry handler is necessary
method.getParams().setParameter(HttpMethodParams.RETRY_HANDLER,
new DefaultHttpMethodRetryHandler(3, false));
try {
// Execute the method.
int statusCode = client.executeMethod(method);
if (statusCode != HttpStatus.SC_OK) {
LOG.error("Method failed: " + method.getStatusLine());
}
// Read the response body.
byte[] responseBody = method.getResponseBody(); //TODO Going to buffer response body of large or unknown size. Using getResponseBodyAsStream instead is recommended.
// Deal with the response.
// Use caution: ensure correct character encoding and is not binary data
response = new String(responseBody);
} catch (HttpException e) {
LOG.error("Fatal protocol violation: " + e.getMessage());
throw new AnnotationException("Protocol error executing HTTP request.",e);
} catch (IOException e) {
LOG.error("Fatal transport error: " + e.getMessage());
LOG.error(method.getQueryString());
throw new AnnotationException("Transport error executing HTTP request.",e);
} finally {
// Release the connection.
method.releaseConnection();
}
return response;
}
protected static String readFileAsString(String filePath) throws java.io.IOException{
return readFileAsString(new File(filePath));
}
protected static String readFileAsString(File file) throws IOException {
byte[] buffer = new byte[(int) file.length()];
#SuppressWarnings("resource")
BufferedInputStream f = new BufferedInputStream(new FileInputStream(file));
f.read(buffer);
return new String(buffer);
}
static abstract class LineParser {
public abstract String parse(String s) throws ParseException;
static class ManualDatasetLineParser extends LineParser {
public String parse(String s) throws ParseException {
return s.trim();
}
}
static class OccTSVLineParser extends LineParser {
public String parse(String s) throws ParseException {
String result = s;
try {
result = s.trim().split("\t")[3];
} catch (ArrayIndexOutOfBoundsException e) {
throw new ParseException(e.getMessage(), 3);
}
return result;
}
}
}
public void saveExtractedEntitiesSet(String Question, LineParser parser, int restartFrom) throws Exception {
String text = Question;
int i=0;
//int correct =0 ; int error = 0;int sum = 0;
for (String snippet: text.split("\n")) {
String s = parser.parse(snippet);
if (s!= null && !s.equals("")) {
i++;
if (i<restartFrom) continue;
List<DBpediaResource> entities = new ArrayList<DBpediaResource>();
try {
entities = extract(new Text(snippet.replaceAll("\\s+"," ")));
System.out.println(entities.get(0).getFullUri());
} catch (AnnotationException e) {
// error++;
LOG.error(e);
e.printStackTrace();
}
for (DBpediaResource e: entities) {
RES.add(e.uri());
}
}
}
}
public abstract List<DBpediaResource> extract(Text text) throws AnnotationException;
public void evaluate(String Question) throws Exception {
evaluateManual(Question,0);
}
public void evaluateManual(String Question, int restartFrom) throws Exception {
saveExtractedEntitiesSet(Question,new LineParser.ManualDatasetLineParser(), restartFrom);
}
}
main()
public static void main(String[] args) throws Exception {
String Question ="Is the Amazon river longer than the Nile River?";
db c = new db ();
c.configiration(0.0, 0, "non", "CoOccurrenceBasedSelector", "Default", "yes");
System.out.println("resource : "+c.getResu());
}
I just add one little fix for your answer.
Your code is running, if you add the evaluate method call:
public static void main(String[] args) throws Exception {
String question = "Is the Amazon river longer than the Nile River?";
db c = new db ();
c.configiration(0.0, 0, "non", "CoOccurrenceBasedSelector", "Default", "yes");
c.evaluate(question);
System.out.println("resource : "+c.getResu());
}
Lamine
In the request method of the second class (AnnotationClient) in Adel's answer, the author Pablo Mendes hasn't finished
TODO Going to buffer response body of large or unknown size. Using getResponseBodyAsStream instead is recommended.
which is an annoying warning that needs to be removed by replacing
byte[] responseBody = method.getResponseBody(); //TODO Going to buffer response body of large or unknown size. Using getResponseBodyAsStream instead is recommended.
// Deal with the response.
// Use caution: ensure correct character encoding and is not binary data
response = new String(responseBody);
with
Reader in = new InputStreamReader(method.getResponseBodyAsStream(), "UTF-8");
StringWriter writer = new StringWriter();
org.apache.commons.io.IOUtils.copy(in, writer);
response = writer.toString();

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