I have just imported jena libraries to eclipse to work on rdf-s and it is my first try, but I cannot read a turtle (.ttl) file.
I tried it in the following way:
import java.io.*;
import java.util.*;
import com.hp.hpl.jena.rdf.model.*;
public class Simpsons {
public static void main(String[] args) throws IOException {
Model model=ModelFactory.createDefaultModel();
model.read(new FileInputStream("simpsons.ttl"),null);
}
}
The error I get is the following:
Exception in thread "main" org.apache.jena.riot.RiotException: [line: 1, col: 1 ] Content is not allowed in prolog.
at org.apache.jena.riot.system.ErrorHandlerFactory$ErrorHandlerStd.fatal(ErrorHandlerFactory.java:136)
at org.apache.jena.riot.lang.LangRDFXML$ErrorHandlerBridge.fatalError(LangRDFXML.java:252)
at com.hp.hpl.jena.rdf.arp.impl.ARPSaxErrorHandler.fatalError(ARPSaxErrorHandler.java:48)
at com.hp.hpl.jena.rdf.arp.impl.XMLHandler.warning(XMLHandler.java:209)
at com.hp.hpl.jena.rdf.arp.impl.XMLHandler.fatalError(XMLHandler.java:239)
at org.apache.xerces.util.ErrorHandlerWrapper.fatalError(Unknown Source)
at org.apache.xerces.impl.XMLErrorReporter.reportError(Unknown Source)
at org.apache.xerces.impl.XMLErrorReporter.reportError(Unknown Source)
at org.apache.xerces.impl.XMLErrorReporter.reportError(Unknown Source)
at org.apache.xerces.impl.XMLScanner.reportFatalError(Unknown Source)
at org.apache.xerces.impl.XMLDocumentScannerImpl$PrologDispatcher.dispatch(Unknown Source)
at org.apache.xerces.impl.XMLDocumentFragmentScannerImpl.scanDocument(Unknown Source)
at org.apache.xerces.parsers.DTDConfiguration.parse(Unknown Source)
at org.apache.xerces.parsers.DTDConfiguration.parse(Unknown Source)
at org.apache.xerces.parsers.XMLParser.parse(Unknown Source)
at org.apache.xerces.parsers.AbstractSAXParser.parse(Unknown Source)
at com.hp.hpl.jena.rdf.arp.impl.RDFXMLParser.parse(RDFXMLParser.java:151)
at com.hp.hpl.jena.rdf.arp.ARP.load(ARP.java:119)
at org.apache.jena.riot.lang.LangRDFXML.parse(LangRDFXML.java:142)
at org.apache.jena.riot.RDFParserRegistry$ReaderRIOTFactoryImpl$1.read(RDFParserRegistry.java:142)
at org.apache.jena.riot.RDFDataMgr.process(RDFDataMgr.java:859)
at org.apache.jena.riot.RDFDataMgr.read(RDFDataMgr.java:255)
at org.apache.jena.riot.RDFDataMgr.read(RDFDataMgr.java:241)
at org.apache.jena.riot.adapters.RDFReaderRIOT_Web.read(RDFReaderRIOT_Web.java:62)
at com.hp.hpl.jena.rdf.model.impl.ModelCom.read(ModelCom.java:253)
at assignment2.Simpsons.main(Simpsons.java:11)
Please help me with some ideas because I have no clue what the problem would be as it's my very first try with Jena. I also got a hint from somewhere that I should do the following: :
It seems that Jena is not so good at discovering the RDF serialisation
used in files by itself, especially for files addressed with an URL. A
solution to this problem is to make a method that gets the file
extension of the filename by the use of string functions and returns
the appropriate RDF serialisation format in Jena’s predefined strings.
You can then use your method both for reading input and writing to file
in the correct serialisation format.
but I don't really understand how should I write that method.
The read method you are using assumes that the input format is RDF/XML.
you need to use one of the other read methods.
So it would be:
public static void main(String[] args) throws IOException {
Model model=ModelFactory.createDefaultModel();
model.read(new FileInputStream("simpsons.ttl"),null,"TTL");
}
Following Program will read and traverse over the TTL file
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import org.apache.jena.graph.Triple ;
import org.apache.jena.riot.RDFDataMgr ;
import org.apache.jena.riot.lang.PipedRDFIterator;
import org.apache.jena.riot.lang.PipedRDFStream;
import org.apache.jena.riot.lang.PipedTriplesStream;
public class ReadingTTL
{
public static void main(String... argv) {
final String filename = "yagoTransitiveType2.ttl";
// Create a PipedRDFStream to accept input and a PipedRDFIterator to
// consume it
// You can optionally supply a buffer size here for the
// PipedRDFIterator, see the documentation for details about recommended
// buffer sizes
PipedRDFIterator<Triple> iter = new PipedRDFIterator<>();
final PipedRDFStream<Triple> inputStream = new PipedTriplesStream(iter);
// PipedRDFStream and PipedRDFIterator need to be on different threads
ExecutorService executor = Executors.newSingleThreadExecutor();
// Create a runnable for our parser thread
Runnable parser = new Runnable() {
#Override
public void run() {
// Call the parsing process.
RDFDataMgr.parse(inputStream, filename);
}
};
// Start the parser on another thread
executor.submit(parser);
// We will consume the input on the main thread here
// We can now iterate over data as it is parsed, parsing only runs as
// far ahead of our consumption as the buffer size allows
while (iter.hasNext()) {
Triple next = iter.next();
// Do something with each triple
System.out.println("Subject: "+next.getSubject());
System.out.println("Object: "+next.getObject());
System.out.println("Predicate: "+next.getPredicate());
System.out.println("\n");
}
}
}
Related
I am using Sphinx4 for custome home automatization software and I am stuck on using my custom dict file, for some reason it cant find the file even though I am sure I am using the correct path. This is my code :
package pccomone;
import java.io.File;
import java.io.FileInputStream;
import java.io.InputStream;
import edu.cmu.sphinx.api.Configuration;
import edu.cmu.sphinx.api.LiveSpeechRecognizer;
import edu.cmu.sphinx.api.SpeechResult;
import edu.cmu.sphinx.api.StreamSpeechRecognizer;
public class Main {
private static final String BODICPATH = "PCCom/src/resource/bodict.dict";
public static void main(String args[]) throws Exception{
Configuration configuration = new Configuration();
configuration.setAcousticModelPath("resource:/edu/cmu/sphinx/models/en-us/en-us");
configuration.setDictionaryPath(BODICPATH);
//configuration.setDictionaryPath("resource:/edu/cmu/sphinx/models/en-us/cmudict-en-us.dict"); use only for large commands!!!!!!!!!
configuration.setLanguageModelPath("resource:/edu/cmu/sphinx/models/en-us/en-us.lm.bin");
LiveSpeechRecognizer recognizer = new LiveSpeechRecognizer(configuration);
recognizer.startRecognition(true);
SpeechResult result;
while((result = recognizer.getResult()) != null){
String command = result.getHypothesis();
if(command.equalsIgnoreCase("stop")){
recognizer.stopRecognition();
System.exit(0);
}
System.out.println(command);
}
}
}
I didn't come far since I can't get it to use my custom dict file and the included dict file is way to large for the software to work fast and accurate.
This is the Error,
Exception in thread "main" java.lang.RuntimeException: Allocation of
search manager resources failed
at edu.cmu.sphinx.decoder.search.WordPruningBreadthFirstSearchManager.allocate(WordPruningBreadthFirstSearchManager.java:247)
at edu.cmu.sphinx.decoder.AbstractDecoder.allocate(AbstractDecoder.java:103)
at edu.cmu.sphinx.recognizer.Recognizer.allocate(Recognizer.java:164)
at edu.cmu.sphinx.api.LiveSpeechRecognizer.startRecognition(LiveSpeechRecognizer.java:47)
at pccomone.Main.main(Main.java:26)
Caused by: java.io.FileNotFoundException: PCCom\src\resource\bodict.dict (The system cannot find the path
specified)
at java.io.FileInputStream.open0(Native Method)
at java.io.FileInputStream.open(Unknown Source)
at java.io.FileInputStream.(Unknown Source)
at java.io.FileInputStream.(Unknown Source)
at sun.net.www.protocol.file.FileURLConnection.connect(Unknown Source)
at sun.net.www.protocol.file.FileURLConnection.getInputStream(Unknown
Source)
at java.net.URL.openStream(Unknown Source)
at edu.cmu.sphinx.linguist.dictionary.TextDictionary.allocate(TextDictionary.java:180)
at edu.cmu.sphinx.linguist.lextree.LexTreeLinguist.allocate(LexTreeLinguist.java:332)
at edu.cmu.sphinx.decoder.search.WordPruningBreadthFirstSearchManager.allocate(WordPruningBreadthFirstSearchManager.java:243)
... 4 more
This is my code
import processing.core.PApplet;
import de.fhpotsdam.unfolding.UnfoldingMap;
import de.fhpotsdam.unfolding.utils.MapUtils;
public class SimpleMapApp extends PApplet {
UnfoldingMap map;
public void setup() {
size(750, 600,P2D);
map = new UnfoldingMap(this);
MapUtils.createDefaultEventDispatcher(this, map);
}
public void draw() {
map.draw();
}
}
When i run it throws exception:
Unfolding Map v0.9.6
Using OpenGLMapDisplay with processing.opengl.PGraphics2D
java.io.IOException: Server returned HTTP response code: 500 for URL:
http://a.tiles.wmflabs.org/bw-mapnik/2/2/2.png at
sun.net.www.protocol.http.HttpURLConnection.getInputStream(Unknown
Source) at java.net.URL.openStream(Unknown Source) at
processing.core.PApplet.createInputRaw(PApplet.java:7233) at
processing.core.PApplet.createInput(PApplet.java:7201) at
processing.core.PApplet.loadBytes(PApplet.java:7428) at
processing.core.PApplet.loadImage(PApplet.java:5867) at
de.fhpotsdam.unfolding.tiles.TileLoader.getTileFromUrl(Unknown Source)
at de.fhpotsdam.unfolding.tiles.TileLoader.run(Unknown Source) at
java.lang.Thread.run(Unknown Source)
Try changing your map provider.
map = new UnfoldingMap(this, new Google.GoogleMapProvider());
I am trying to test some data mining algorithms from smile project (https://github.com/haifengl/smile). The testing process is simple (I have included into existing Eclipse project Maven repositories of Smile project), but with the following code I catch a NPE (Null pointer exception) with InputStream , the file is just heavy csv file necessary to be read (included in the same project folder)
package com.algorithms;
import java.io.IOException;
import java.io.InputStream;
import java.text.ParseException;
import smile.data.AttributeDataset;
import smile.data.NominalAttribute;
import smile.data.parser.DelimitedTextParser;
public class DenclueTester {
public void doTestDenclue() throws IOException, ParseException
{
DelimitedTextParser parser = new DelimitedTextParser();
parser.setResponseIndex(new NominalAttribute("class"), 0);
InputStream in = this.getClass().getResourceAsStream("USCensus1990_data1.csv");
AttributeDataset data = parser.parse("US Census data", in);
double[][] x = data.toArray(new double[data.size()][]);
int[] y = data.toArray(new int[data.size()]);
}
public DenclueTester() {} //constructor
}
The following code is executed in main :
public class Dtest
{
public static void main(String[] args) throws IOException, ParseException
{
DenclueTester dt = new DenclueTester();
dt.doTestDenclue();
}
}
Stack trace:
Exception in thread "main" java.lang.NullPointerException
at java.io.Reader.<init>(Unknown Source)
at java.io.InputStreamReader.<init>(Unknown Source)
at smile.data.parser.DelimitedTextParser.parse(DelimitedTextParser.java:234)
at com.algorithms.DenclueTester.doTestDenclue(DenclueTester.java:18)
at com.algorithms.Dtest.main(Dtest.java:26)
Could anyone help me with that?
Solved issue by placing the csv file into /classes/package_name folder. Thanks
I have a web app that needs to be able open a file locally on a client machine, with the ability to save the file after editing. The web app generates a document on the server in a folder that is shared out via WebDAV & FTP and this folder is mounted on the client machine.
I cannot use a file:// type URI as it would not permit saving back to the server.
I intend trying to solve the problem with a small java applet embedded in the web app that handles this file opening, but I am having difficulties with permissions in Java. (Java isn't my field of expertise). Anyhow, I've narrowed the code down to the following:
localfile.html
<html>
<body>
<input id="input" value="Call from Javascript" type="button" onclick="callApplet('/Users/conor/1.txt')">
<script type='text/javascript'>
function callApplet(path) {
applet = document.getElementById('localfile');
applet.openFile(path);
}
</script>
<applet id="localfile" code="localfile.class" archive="localfile.jar" width="150" height="50"></applet>
</body>
</html>
localfile.java
import java.applet.*;
import java.awt.*;
import java.util.*;
import java.lang.*;
import java.text.*;
import java.awt.event.*;
import java.io.*;
import java.security.*;
public class localfile extends Applet {
public localfile() {
Panel p = new Panel();
p.add(new Button("Call from Java"));
add("North",p);
}
public void openFile(String path) {
System.out.println("File: " + path);
final File ffile = new File(path);
System.out.println("Got file.");
if (Desktop.isDesktopSupported()) {
System.out.println("Desktop is supported.");
final Desktop desktop = Desktop.getDesktop();
System.out.println("Got Desktop Handle.");
try {
desktop.open(ffile);
} catch(Exception ex) {
ex.printStackTrace();
}
System.out.println("File Opened.");
}
}
public boolean action(Event evt, Object arg) {
openFile("/Users/conor/1.txt");
return true;
}
}
I have compiled, created a jar file and signed it from the java source.
This produces a page with two buttons - a Java one (for testing) and a Javascript one. The Java button works fine as expected - and I can save the file etc. I want to pass the file path to the applet though so it is really the Javascript button I wish to get working. The Javascript one throws the following though:
Stack Trace
java.security.AccessControlException: access denied ("java.awt.AWTPermission" "showWindowWithoutWarningBanner")
at java.security.AccessControlContext.checkPermission(AccessControlContext.java:366)
at java.security.AccessController.checkPermission(AccessController.java:560)
at java.lang.SecurityManager.checkPermission(SecurityManager.java:549)
at java.awt.Desktop.checkAWTPermission(Desktop.java:239)
at java.awt.Desktop.open(Desktop.java:267)
at localfile.openFile(localfile.java:27)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:601)
at sun.plugin.javascript.JSInvoke.invoke(Unknown Source)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:601)
at sun.plugin.javascript.JSClassLoader.invoke(Unknown Source)
at sun.plugin2.liveconnect.JavaClass$MethodInfo.invoke(Unknown Source)
at sun.plugin2.liveconnect.JavaClass$MemberBundle.invoke(Unknown Source)
at sun.plugin2.liveconnect.JavaClass.invoke0(Unknown Source)
at sun.plugin2.liveconnect.JavaClass.invoke(Unknown Source)
at sun.plugin2.main.client.LiveConnectSupport$PerAppletInfo$DefaultInvocationDelegate.invoke(Unknown Source)
at sun.plugin2.main.client.LiveConnectSupport$PerAppletInfo$3.run(Unknown Source)
at java.security.AccessController.doPrivileged(Native Method)
at sun.plugin2.main.client.LiveConnectSupport$PerAppletInfo.doObjectOp(Unknown Source)
at sun.plugin2.main.client.LiveConnectSupport$PerAppletInfo$LiveConnectWorker.run(Unknown Source)
at java.lang.Thread.run(Thread.java:722)
I have also tried embedding the desktop.open call into a doPrivileged block, as follows:
AccessController.doPrivileged(new PrivilegedAction() {
public Object run() {
try {
desktop.open(ffile);
} catch(Exception ex) {
ex.printStackTrace();
}
return null;
}
});
but that throws error for javascript & java buttons as follows:
java.lang.SecurityException: class "localfile$1" does not match trust level of other classes in the same package
Any help would be appreciated.
Got it to work, so thought I'd post the solution here...
When I was compiling the java file with the doPrivileged call in it, the javac compiler creates two files - localfile.class and localfile$1.class. I wasn't sure initially what the localfile$1.class was and just presumed it was a temporary file of some sort. It was however a class file corresponding to the anonymous class within the doPrilileged block and needed to be included in the .jar file and properly signed.
So anyway, html file is as before, and final java file is as follows:
localfile.java
import java.applet.*;
import java.awt.*;
import java.awt.event.*;
import java.io.*;
import java.security.*;
public class localfile extends Applet {
private static final long serialVersionUID = 1L;
public localfile() {
Panel p = new Panel();
p.add(new Button("Call from Java"));
add("North",p);
}
public void openFile(String path) {
System.out.println("File: " + path);
final File ffile = new File(path);
System.out.println("Got file.");
if (Desktop.isDesktopSupported()) {
System.out.println("Desktop is supported.");
final Desktop desktop = Desktop.getDesktop();
System.out.println("Got Desktop Handle.");
AccessController.doPrivileged(new PrivilegedAction() {
public Object run() {
try {
desktop.open(ffile);
} catch(Exception ex) {
ex.printStackTrace();
}
return null;
}
});
System.out.println("File Opened.");
}
}
public boolean action(Event evt, Object arg) {
openFile("/Users/conor/1.txt");
return true;
}
}
I also found that there was no need to have the javascript in the html file create the applet and insert it into the DOM. I think this was mentioned in the link #VGR linked to but it worked for me without it.
Thanks for all the help guys!
I am trying to call the "dspdf.exe" inside the jar file where this smartpdf class exists. I plan to extract it to a temp location and delete when program ends. However this doesn't seem to work, any help will be appreciated.
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import org.omg.CORBA.portable.InputStream;
public class smartpdf {
static String url="";
static String output="output.pdf";
public static void main(String[] args) throws IOException{
gui mygui = new gui();//gui will call the generate function when user selects
}
public static void generate() throws IOException{
InputStream src = (InputStream) smartpdf.class.getResource("dspdf.exe").openStream();
File exeTempFile = File.createTempFile("dspdf", ".exe");
FileOutputStream out = new FileOutputStream(exeTempFile);
byte[] temp = new byte[32768];
int rc;
while((rc = src.read(temp)) > 0)
out.write(temp, 0, rc);
src.close();
out.close();
exeTempFile.deleteOnExit();
Runtime.getRuntime().exec(exeTempFile.toString()+" "+url+" "+output );
//Runtime.getRuntime().exec("dspdf "+url+" "+output);
}
}
EDIT:
The error that I am getting:
Microsoft Windows XP [Version 5.1.2600]
(C) Copyright 1985-2001 Microsoft Corp.
Exception in thread "main" java.lang.reflect.InvocationTargetException
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source)
at java.lang.reflect.Method.invoke(Unknown Source)
at org.eclipse.jdt.internal.jarinjarloader.JarRsrcLoader.main(JarRsrcLoa
der.java:56)
Caused by: java.lang.ClassCastException: sun.net.www.protocol.jar.JarURLConnecti
on$JarURLInputStream cannot be cast to org.omg.CORBA.portable.InputStream
at smartpdf.generate(smartpdf.java:18)
at smartpdf.main(smartpdf.java:14)
... 5 more
You use the wrong InputStream. Change it to java.io.InputStream.
Why do you use org.omg.CORBA.portable.InputStream instead of a java.io.BufferedInputStream`
with as parameters the inputstream from the resource. I mean this:
BufferedInputStream inputstream = new BufferedInputStream(smartpdf.class.getResourceAsStream(...));
The same for your fileoutput stream: BufferedOutputStream
Don't use
class.getResource(...).openStream();
but use
class.getResourceAsStream(...);
Note also (once you've resolved the InputStream issue) that you should be consuming your spawned process stdout and stderr, otherwise the spawned process may block. See this answer for more details.