How to create a Fuseki SPARQL server connection in Android Studio - java

How can I create a connection to a Fuseki server through the android studio and upload my owl file into the Fuseki server in order to send SPARQL query and get the result?
I did it from the command-line and it works fine but I need to do it through the android studio.
I found some code but "DatasetAccessor and DatasetAccessorFactory" can not be resolved
public static void uploadRDF(File rdf, String serviceURI)
throws IOException {
// parse the file
Model m = ModelFactory.createDefaultModel();
try (FileInputStream in = new FileInputStream(rdf)) {
m.read(in, null, "RDF/XML");
}
// upload the resulting model
DatasetAccessor accessor = DatasetAccessorFactory
.createHTTP(serviceURI);
accessor.putModel(m);
}

Related

Can static content on spring-boot-web application be dynamic (refreshed)?

I am still searching around this subject, but I cannot find a simple solution, and I don't sure it doesn't exist.
Part 1
I have a service on my application that's generating an excel doc, by the dynamic DB data.
public static void
notiSubscribersToExcel(List<NotificationsSubscriber>
data) {
//generating the file dynamically from DB's data
String prefix = "./src/main/resources/static";
String directoryName = prefix + "/documents/";
String fileName = directoryName + "subscribers_list.xlsx";
File directory = new File(directoryName);
if (! directory.exists()){
directory.mkdir();
// If you require it to make the entire directory path including parents,
// use directory.mkdirs(); here instead.
}
try (OutputStream fileOut = new FileOutputStream(fileName)) {
wb.write(fileOut);
fileOut.close();
wb.close();
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
Part 2
I want to access it from the browser, so when I call it will get downloaded.
I know that for the static content, all I need to do is to call to the file, from the browser like that:
http://localhost:8080/documents/myfile.xlsx
After I would be able to do it, all I need is to create link to this url from my client app.
The problem -
Currently if I call to the file as above, it will download only the file which have been there in the compiling stage, but if I am generating a new files after the app is running the content won't be available.
It seems that the content is (as it's called) "static" and cannot be changed after startup.
So my question is
is there is a way to define a folder on the app structure that will be dynamic? I just want to access the new generated file.
BTW I found this answer and others which doing configuration methods, or web services, but I don't want all this. And I have tried some of them, but the result is the same.
FYI I don't bundle my client app with the server app, I run them from different hosts
The problem is to download the file with the dynamic content from a Spring app.
This can be solved with Spring BOOT. Here is the solution as shown in this illustration - when i click Download report, my app generates a dynamic Excel report and its downloaded to the browser:
From a JS, make a get request to a Spring Controller:
function DownloadReport(e){
//Post the values to the controller
window.location="../report" ;
}
Here is the Spring Controller GET Method with /report:
#RequestMapping(value = ["/report"], method = [RequestMethod.GET])
#ResponseBody
fun report(request: HttpServletRequest, response: HttpServletResponse) {
// Call exportExcel to generate an EXCEL doc with data using jxl.Workbook
val excelData = excel.exportExcel(myList)
try {
// Download the report.
val reportName = "ExcelReport.xls"
response.contentType = "application/vnd.ms-excel"
response.setHeader("Content-disposition", "attachment; filename=$reportName")
org.apache.commons.io.IOUtils.copy(excelData, response.outputStream)
response.flushBuffer()
} catch (e: Exception) {
e.printStackTrace()
}
}
This code is implemented in Kotlin - but you can implement it as easily in Java too.

Conversion from OWLOntology to Jena Model in Java

I need to convert data from OWLOntology object(part of OWL api) to Model object(part of Jena Api). My Java program should be able to load owl file and send its content to fuseki server. According to what I read, working with fuseki server via Java program is possible only with Jena Api, that's why I use it.
So I found some example of sending ontologies to fuseki server using Jena api, and modified it to this function :
private static void sendOntologyToFuseki(DatasetAccessor accessor, OWLOntology owlModel){
Model model;
/*
..
conversion from OWLOntology to Model
..
*/
if(accessor != null){
accessor.add(model);
}
}
This function should add new ontologies to fuseki server. Any ideas how to fill missing conversion? Or any other ideas, how to send ontologies to fuseki server using OWL api?
I read solution of this :
Sparql query doesn't upadate when insert some data through java code
but purpose of my java program is to send these ontologies incrementally, because it's quite big data and if I load them into local memory, my computer does not manage it.
The idea is to write to a Java OutputStream and pipe this into an InputStream. A possible implementation could look like this:
/**
* Converts an OWL API ontology into a JENA API model.
* #param ontology the OWL API ontology
* #return the JENA API model
*/
public static Model getModel(final OWLOntology ontology) {
Model model = ModelFactory.createDefaultModel();
try (PipedInputStream is = new PipedInputStream(); PipedOutputStream os = new PipedOutputStream(is)) {
new Thread(new Runnable() {
#Override
public void run() {
try {
ontology.getOWLOntologyManager().saveOntology(ontology, new TurtleDocumentFormat(), os);
os.close();
} catch (OWLOntologyStorageException | IOException e) {
e.printStackTrace();
}
}
}).start();
model.read(is, null, "TURTLE");
return model;
} catch (Exception e) {
throw new RuntimeException("Could not convert OWL API ontology to JENA API model.", e);
}
}
Alternatively, you could simply use ByteArrayOutputStream and ByteArrayInputStream instead of piped streams.
To avoid such kind of dreadful transformation through i/o streams you can use ONT-API: it implements direct reading of the owl-axioms from the graph without any conversion

How to serve .jasper file with HTTP Server?

I am creating HTTP server with Tomee, i am placed jasper report file (.jasper) in webapp directory. if i access http://localhost:8080/test.jasper in browser, the browser will prompt to download the file.
In my java project i'm creating simple code to access that link and then preview the report. I use async-http-client library for request.
DefaultAsyncHttpClient client = new DefaultAsyncHttpClient();
BoundRequestBuilder brb = client.prepareGet("http://localhost:8765/qa/test.jasper");
Future<InputStream> f = brb.execute(new AsyncCompletionHandler<InputStream>() {
#Override
public InputStream onCompleted(Response resp) {
try {
String[][] data = {{"Jakarta"},{"Surabaya"},{"Solo"},{"Denpasar"}};
String[] columnNames = {"City"};
DefaultTableModel dtm = new DefaultTableModel(data, columnNames);
Map<String,Object> params = new HashMap<>();
JasperPrint jPrint = JasperFillManager.fillReport(
resp.getResponseBodyAsStream(),
params,
new JRTableModelDataSource(dtm)
);
JasperViewer jpView = new JasperViewer(jPrint,false);
jpView.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
jpView.setSize(800, 600);
jpView.setLocationRelativeTo(null);
jpView.setVisible(true);
} catch (JRException ex) {
System.out.println(ex.getMessage());
}
return resp.getResponseBodyAsStream();
}
});
From my code above, i got an error Error loading object from InputStream
normally i can use
InputStream input = MainContext.class.getResourceAsStream(filename);
But i want to replace file input stream with http request (stream too).
How exactly i can serve .jasper file with http server...?
Error loading object from InputStream error came from corrupt InputStream, if i download .jasper file normally via browser and execute the report with JRLoader.loadObjectFromFile(path to file) it doesn't works too, because tomee give corrupt file (the source file not corrupt).
My own solution is read source file as stream, convert it to base64 encode, and serve it via HTTP API protocol.
finput = new FileInputStream(sPath);
byte[] bFile = Base64.getEncoder().encode(IOUtils.toByteArray(finput));
String sFile = new String(bFile);
inside client side, i received it as body string, decode the base64 string, convert it to InputStream and Finally execute the report with InputStream.
byte[] bBody = Base64.getDecoder().decode(sBody);
InputStream mainReport = new ByteArrayInputStream(bBody);
return JasperFillManager.fillReport(mainReport, params);

Error when I launch SPARQL query endpoint on the browser

I have a question:
I have two RDF files that I load on Jena TDB using this Java Code:
public void store() {
String directory = "C:\\tdb";
Dataset dataset = openTDB(directory);
String source = "C:\\file1.rdf";
String source1 = "C:\\file2.rdf";
Model tdb = loadModel(source, dataset);
dataset.addNamedModel("C://File1", tdb);
Model tdb1 = loadModel(source1, dataset);
dataset.addNamedModel("C://File2", tdb1);
tdb.close();
tdb1.close();
dataset.close();
}
public Dataset openTDB(String directory) {
// open TDB dataset
Dataset dataset = TDBFactory.createDataset(directory);
return dataset;
}
public Model loadModel(String source, Dataset dataset) {
Model model = ModelFactory.createDefaultModel();
FileManager.get().readModel(model, source, "RDF/XML");
return model;
}
As was suggested in this post https://stackoverflow.com/questions/24798024/how-i-can-use-fuseki-with-jena-tdb, I launch this command on CMD:
fuseki-server --update --loc C:\tdb /ds
On the localhost:3030 I see different page. In particular, I see "Control Panel" page where I can choose the dataset and I can execute a query.
Now, I'm reading this documentation http://jena.apache.org/documentation/serving_data/ and I see that if I want to launch the SPARQL query endpoint I can write http://host/dataset/query path in the browser.
But, If I launch this path (
http://localhost:3030/ds/query
), I get this error:
Error 404: Service Description: /ds/query
Fuseki - version 1.0.2 (Build date: 2014-06-02T10:57:10+0100)
Why?
I'm doing this research to find a Java method to launch Fuseki server in Java Code. Is it possible?

mysql error with GWT

i am trying to create an sample apps using GWT and my code is below
public void onModuleLoad() {
VerticalPanel panel = new VerticalPanel();
MultiWordSuggestOracle oracle = new MultiWordSuggestOracle();
database data=new database();
Statement s1;
try {
s1 = data.conn.createStatement();
s1.executeQuery ("SELECT * FROM details LIMIT 10");
ResultSet rs = s1.getResultSet ();
while (rs.next ())
{
String name = rs.getString ("name");
oracle.add(name);
}
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
SuggestBox suggestbox = new SuggestBox(oracle);
panel.add(new Label("Enter Country"));
panel.add(suggestbox);
panel.addStyleName("demo-panel-padded");
RootPanel.get("demo").add(panel);
}
and i have added the mysql-bin.jar connector in war/WEB_INF/lib/ and now i am getting an compilation error
17:39:52.353 [ERROR] [a] Line 28: No source code is available for type java.sql.Statement; did you forget to inherit a required module?
i need to know why i am getting this error and how can i rectify it
You cannot use server-side code (java.sql.* in your case) in GWT client side modules.
You should make an RPC call to the server. The server callback should fetch the data from your database, and send it back to your GWT client.
Using Eclipse with the google plugin, you can create a new "Web Application Project". More information about the plugin can be found here: http://code.google.com/eclipse/
You will get a simple project that contains a GreetingService which receives a String from the client side and responds with "Hello" + string. For your example you would have to add the code that reads from the DB in the GreetingServiceImpl class and then use the response (which can be a String[] containing the name read from DB) on the client side to populate the SuggestionBox

Categories