example of stardog sparql insert query in java - java

Can somebody give one java example of sparql insert/Delete query in Stardog.
there is only queryExecution.execSelect() method available.
there is no queryExecution.execInsert() or queryExecution.execDelete() available.
Please give one working example.
EDIT
I've found this this from stardog docs page.
http://stardog.com/docs/#notes
As of 1.1.5, Stardog's SPARQL 1.1 support does not include: UPDATE query language
does that means no way out for editing a tuple once entered?

Stardog does not yet support SPARQL update, but as was pointed out to you on the mailing list, there are 5 ways you can modify the data once it's loaded. You can use our HTTP protocol directly, any of the 3 Java API's we support, or you can use the command line interface.

Below one is a sample program of inserting a graph and removing it.
package com.query;
import java.util.List;
import org.openrdf.model.Graph;
import org.openrdf.model.Statement;
import org.openrdf.model.URI;
import org.openrdf.model.impl.GraphImpl;
import org.openrdf.model.impl.ValueFactoryImpl;
import org.openrdf.query.QueryEvaluationException;
import com.clarkparsia.stardog.StardogDBMS;
import com.clarkparsia.stardog.StardogException;
import com.clarkparsia.stardog.api.Connection;
import com.clarkparsia.stardog.api.ConnectionConfiguration;
import com.clarkparsia.stardog.jena.SDJenaFactory;
import com.hp.hpl.jena.query.ParameterizedSparqlString;
import com.hp.hpl.jena.query.QueryExecution;
import com.hp.hpl.jena.query.QueryExecutionFactory;
import com.hp.hpl.jena.query.ResultSet;
import com.hp.hpl.jena.query.ResultSetFormatter;
import com.hp.hpl.jena.rdf.model.Model;
public class test {
public static void main(String[] args) throws StardogException, QueryEvaluationException {
String appDbName ="memDb";
String selectQuery="SELECT DISTINCT ?s ?p ?o WHERE { ?s ?p ?o }";
StardogDBMS dbms = StardogDBMS.toServer("snarl://localhost:5820/")
.credentials("admin", "admin".toCharArray()).login();
List<String> dbList = (List<String>) dbms.list();
if (dbList.contains(appDbName)) {
System.out.println("droping " + appDbName);
dbms.drop(appDbName);
}
dbms.createMemory(appDbName);
dbms.logout();
Connection aConn = ConnectionConfiguration
.to("memDb") // the name of the db to connect to
.credentials("admin", "admin") // credentials to use while connecting
.url("snarl://localhost:5820/")
.connect();
Model aModel = SDJenaFactory.createModel(aConn);
System.out.println("################ GRAPH IS EMPTY B4 SUBMITTING ="+aModel.getGraph()+ "################");
URI order = ValueFactoryImpl.getInstance().createURI("RDF:president1");
URI givenName = ValueFactoryImpl.getInstance().createURI("RDF:lincoln");
URI predicate = ValueFactoryImpl.getInstance().createURI("RDF:GivenNane");
Statement aStmt = ValueFactoryImpl.getInstance().createStatement(order,predicate,givenName);
Graph aGraph = new GraphImpl();
aGraph.add(aStmt);
insert(aConn, aGraph);
ParameterizedSparqlString paraQuery = new ParameterizedSparqlString(selectQuery);
QueryExecution qExecution = QueryExecutionFactory.create(paraQuery.asQuery(),aModel);
ResultSet queryResult = qExecution.execSelect();
System.out.println("############### 1 TUPPLE CAME AFTER INSERT ################");
ResultSetFormatter.out(System.out, queryResult);
aGraph.add(aStmt);
remove(aConn, aGraph);
paraQuery = new ParameterizedSparqlString(selectQuery);
qExecution = QueryExecutionFactory.create(paraQuery.asQuery(),aModel);
queryResult = qExecution.execSelect();
System.out.println("################ DB AGAIN EMPTY AFTER REMOVE ################");
ResultSetFormatter.out(System.out, queryResult);
System.out.println("closing connection and model");
aModel.close();
aConn.close();
}
private static void insert(final Connection theConn, final Graph theGraph) throws StardogException {
theConn.begin();
theConn.add().graph(theGraph);
theConn.commit();
}
private static void remove(final Connection theConn, final Graph theGraph) throws StardogException {
theConn.begin();
theConn.remove().graph(theGraph);
theConn.commit();
}
}

Related

Using play with existing database ( models )

Can i use play framework linked to an existing database (Example SAP DBB) to only display :
Dashboards (Queries)
Charts (Queries)
I developped an authentication page, suddenly, i did not tought about how to extract data from an existing database without declaring models!
What is the good way to only extract with many queries data and display it on views scala (Play framework JAVA) ?
Thank you so much
We also have many existing databases, without having a complete model of each table in Play applications. I create a case class in the Play application for all necessary fields, also a subset of all columns. It's Scala code, but also possible with Java, of course.
case class Positionstext(akt_abnr: Int
, akt_text_art: Int
, akt_text_pos: Int
, akt_text: String) {
}
The carefully assembled SQL command retrieves rows from one or more tables.
def positionstexte(x: Int) : List[Positionstext] = {
DB.withConnection{ connection =>
val select =
""" select plr_ak_texte.akt_abnr
, plr_ak_texte.akt_text_art
, plr_ak_texte.akt_text_pos
, plr_ak_texte.akt_text
from plrv11.plr_ak_texte
, plrv11.plr_auftr_status
where plr_ak_texte.akt_abnr = plr_auftr_status.as_abnr
and plr_ak_texte.akt_aend_ix = plr_auftr_status.as_aend_ix
and plr_ak_texte.akt_abnr = ?
and plr_ak_texte.akt_text_art = 7
and plr_auftr_status.as_aend_ix <> 99
"""
val prepareStatement = connection.prepareStatement(select)
prepareStatement.setInt(1, x)
val rs = prepareStatement.executeQuery
var list: ListBuffer[Positionstext] = scala.collection.mutable.ListBuffer()
while (rs.next) {
list += new Positionstext(rs.getInt("akt_abnr")
, rs.getInt("akt_text_art")
, rs.getInt("akt_text_pos")
, rs.getString("akt_text"))
}
rs.close()
prepareStatement.close()
list.toList
}
And that's it! The SQL command already does most of the work by using sub-queries, joins etc.
All desired objects are in the list now and can display in the view.
Thank you for your return,
This is what i did and it works pretty fine :
package controllers;
import models.Sysuser;
import models.DataI;
import models.DataII;
import play.mvc.Controller;
import play.mvc.Result;
import play.mvc.Security;
import views.html.sitemap.index;
import javax.inject.*;
import java.util.concurrent.CompletionStage;
import play.libs.concurrent.HttpExecutionContext;
import static java.util.concurrent.CompletableFuture.supplyAsync;
import io.ebean.*;
import play.Logger;
import java.util.List;
import play.libs.Json;
import java.util.*;
import java.util.stream.*;
#Security.Authenticated(Secured.class)
public class SiteMap extends Controller {
private final HttpExecutionContext httpExecutionContext;
private static final Logger.ALogger logger = Logger.of(SiteMap.class);
#Inject
public SiteMap(HttpExecutionContext httpExecutionContext) {
this.httpExecutionContext = httpExecutionContext;
}
public CompletionStage<Result> index() {
return supplyAsync(() -> {
return ok(views.html.sitemap.index.render(Sysuser.findByUserName(request().username()), QueryI(), QueryII() ));
}, httpExecutionContext.current());
}
/**
* Custom Query 1
*/
public List<DataI> QueryI() {
final String sql = "SELECT sysuser_id, role_id "
+"from sysuser_role "
+"where sysuser_id = '1' "
+"and role_id in ('1','2','3','4','5') ";
final RawSql rawSql = RawSqlBuilder.parse(sql).create();
Query<DataI> query = Ebean.find(DataI.class);
query.setRawSql(rawSql);
List<DataI> L = query.findList();
return(L);
}
/**
* Custom Query 2
*/
public List<DataII> QueryII() {
final String sql = "SELECT sysuser.name, sysuser.active, department.description "
+"from sysuser "
+"left join department on department.id = sysuser.department_id "
+"where sysuser.id = '2' ";
final RawSql rawSql = RawSqlBuilder.parse(sql).create();
Query<DataII> query = Ebean.find(DataII.class);
query.setRawSql(rawSql);
List<DataII> L = query.findList();
return(L);
}
}
I am using Java instead of Scala, however, i don't think that there is a need of these codes such as :
1- DB.withConnection{ connection =>
2- val prepareStatement = connection.prepareStatement(select)
....and what else...
What do you think about my code? is it optimal ? I am going to use complexe queries to fill some dashboards in this template : https://adminlte.io/themes/v3/index.html

How to take input for a web service in java

I am trying to write a simple web service that must take a number as input and return details corresponding to it.
Here is my code that I have written till now.
package webserviceapp;
import java.sql.Statement;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.HashMap;
import java.util.Map;
import javax.jws.WebService;
import javax.jws.WebMethod;
#WebService
public class WebServiceApp {
/**
* #param args the command line arguments
*/
static final String JDBC_DRIVER = "com.mysql.jdbc.Driver";
static final String DB_URL = "jdbc:mysql://10.100.66.28:3306/dbname";
// Database credentials
static final String USER = "user";
static final String PASS = "pass";
static Map<Integer, String> map = new HashMap<Integer, String>();
public static void main(String[] args) {
// TODO code application logic here
Connection conn;
Statement stmt;
try{
Class.forName(JDBC_DRIVER);
conn = DriverManager.getConnection(DB_URL, USER, PASS);
stmt = (Statement) conn.createStatement();
String sql = "Select * from table";
ResultSet rs;
rs = stmt.executeQuery(sql);
while(rs.next()){
//do something
}
}catch(ClassNotFoundException | SQLException e){
System.out.println(e);
}
}
#WebMethod(action = "returnDetails")
public static String[] returnDetails(int k) throws notFoundException{
//do the work
//returns String[]
}
private static class notFoundException extends Exception {
public notFoundException(String s) {
System.out.println(s);
System.err.println(s);
}
}
}
I do not know how to take input for the above web service. I have a html page that has a text box and submit button for which I get values through a php code. I want to tunnel this number as input to my web service. Can anyone tell me how can I proceed.
Also, I want the output String[] to be returned to php code so it can be displayed on the html page.
Thanks in advance.
you can pass it in the URL and from the url you can get the values in java
Working off the assumption that you are looking to invoke a RESTful service, there are multiple ways of obtaining input parameters. You can refer to the below article for the ways to achieve this -
http://www.java4s.com/web-services/how-restful-web-services-extract-input-parameters
Code examples for each are available at http://www.java4s.com/web-services/
Another good article you can refer to is - https://vrsbrazil.wordpress.com/2013/08/07/passing-parameters-to-a-restful-web-service/

Execution engine not printing results

I have a simple Query method that runs cypher queries as noted below. If I run the EXACT same query in the web console (yes, same db instance, correct path), I get a non-empty iterator in the console. Shouldn't I 1) not get that message and 2) get the results I see in my database?
This class has other methods that add data to the database and that functionality works well. This query method is not working...
Class:
import org.neo4j.cypher.javacompat.ExecutionEngine;
import org.neo4j.cypher.javacompat.ExecutionResult;
import org.neo4j.graphdb.Direction;
import org.neo4j.graphdb.GraphDatabaseService;
import org.neo4j.graphdb.Node;
import org.neo4j.graphdb.Relationship;
import org.neo4j.graphdb.RelationshipType;
import org.neo4j.graphdb.Transaction;
import org.neo4j.graphdb.factory.GraphDatabaseFactory;
import org.neo4j.helpers.collection.IteratorUtil;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.sql.*;
public class NeoProcessor {
//private GraphDatabaseService handle;
private static final String DB_PATH = "/usr/local/Cellar/neo4j/2.0.1/libexec/data/new_graph.db";
static GraphDatabaseService graphDb = new GraphDatabaseFactory().newEmbeddedDatabase( DB_PATH );
public NeoProcessor()
{
}
public void myQuery(String cypherText)
{
//System.out.println("executing the above query");
cypherText = "MATCH (n:Phone{id:'you'}) MATCH n-[r:calling]->m WHERE n<>m RETURN n, r, m";
ExecutionEngine engine = new ExecutionEngine( this.graphDb );
ExecutionResult result;
try ( Transaction ignored = graphDb.beginTx() )
{
result = engine.execute( cypherText + ";");
System.out.println(result);
ignored.success();
}
}
}
Below is a pic showing how the query rreturns results from the DB:
result = engine.execute(cypherText + ";");
System.out.println(result.dumpToString());
Specified by:
http://api.neo4j.org/2.0.3/org/neo4j/cypher/javacompat/ExecutionResult.html#dumpToString()
To consume the result you need to use the iterator. If you just want a string representation use the ExecutionResult.dumpToString(). Be aware this method exhausts the iterator.
You should be calling:
System.out.println(result.dumpToString)
Which will prettify it for you. Of course, there is always the possibility that your match returns no results. You shouuld also close the transaction in a finally block, although that won't matter much here.
EDIT: Taking a second look at this, your Cypher query is wrongly formed, It should be
MATCH (n:Phone) - [r:calling] -> (m)
WHERE n.id = `you'
RETURN n, r, m

Using Jena ARQ to access remote repo with basic auth - preemptive

I am trying to use Jena ARQ with a PreemptiveBasicAuthenticator, without success, can anyone help?
Im always getting a 401, although the same request through a rest client, or using openrdf works. Could it be something to do with apache http client and having to set an AuthScope?
import com.hp.hpl.jena.query.Query;
import com.hp.hpl.jena.query.QueryExecution;
import com.hp.hpl.jena.query.QueryExecutionFactory;
import com.hp.hpl.jena.query.QueryFactory;
import com.hp.hpl.jena.query.ResultSet;
import org.apache.jena.atlas.web.auth.HttpAuthenticator;
import org.apache.jena.atlas.web.auth.PreemptiveBasicAuthenticator;
import org.apache.jena.atlas.web.auth.ScopedAuthenticator;
import java.net.URI;
public class JenaConnect {
private final static String SPARQLR_ENDPOINT = "https://repo-eh-01.sparqlr.com/repositories/examples-repo";
private final static String SPARQLR_USERNAME = "examples-repo";
private final static String SPARQLR_PASSWORD = "XXXX";
public static void main(String[] args) throws Exception {
String queryString = "SELECT * WHERE {?s ?p ?o}";
Query query = QueryFactory.create(queryString);
HttpAuthenticator authenticator = new PreemptiveBasicAuthenticator(
new ScopedAuthenticator(new URI(SPARQLR_ENDPOINT), SPARQLR_USERNAME, SPARQLR_PASSWORD.toCharArray())
);
QueryExecution queryExecution = QueryExecutionFactory.sparqlService(SPARQLR_ENDPOINT, query, authenticator);
try {
ResultSet results = queryExecution.execSelect();
int i = 0;
while(results.hasNext()) {
results.next();
i++;
}
System.out.println(i);
} finally {
queryExecution.close();
}
}
}
Asked and answered in this thread: http://mail-archives.apache.org/mod_mbox/jena-users/201401.mbox/%3CF6F103F1-7205-4E6B-94EB-FEB67129A39A%40sparqlr.com%3E

How to read a ARRAY of types returned from a stored proc using java?

This is a continuation of the question posted under the following location:
Java program to pass List of Bean to a oracle stored procedure - Pass entire list at one shot rather than appending objects one after the other
I have been trying to enhance the stored procedure mentioned in the above link location and am confused in the implementation. Rather than VARCHAR2 as a output from the procedure i now want to return NUM_ARRAY as the output from the procedure. Can you please help me in implementing the logic to read the NUM_ARRAY in my java code. Normally output is returned using Map out = super.execute(inParams); How can i now extract the NUM_ARRAY to my bean?
The source code implementation is as follows.
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import java.util.HashMap;
import java.util.Map;
import javax.sql.DataSource;
import oracle.jdbc.OracleTypes;
import oracle.sql.ARRAY;
import oracle.sql.ArrayDescriptor;
import org.apache.log4j.Logger;
import org.springframework.jdbc.core.SqlOutParameter;
import org.springframework.jdbc.core.SqlParameter;
import org.springframework.jdbc.core.SqlTypeValue;
import org.springframework.jdbc.object.StoredProcedure;
public class RevPrdBrkDwnSP extends StoredProcedure{
private final Logger log = Logger.getLogger(this.getClass().getName());
public RevPrdBrkDwnSP(DataSource dataSource, String storeProcName) {
// Run the Parent
super(dataSource, storeProcName);
// Declare the Parameter Details
declareParameter(new SqlParameter("IN_ARRAY", OracleTypes.ARRAY, "****.PROD_PRCT_BRKDWN_TYPE_ARRAY"));
declareParameter(new SqlOutParameter("OUT_ARRAY", OracleTypes.ARRAY, "****.PROD_PRCT_BRKDWN_TYPE_ARRAY"));
// Compile the SP
compile();
}
public boolean execute(final RevAppViewBean appViewBean$Session, final DataSource dataSource) throws Exception {
boolean returnVal = false;
Map<String, Object> inParams = new HashMap<String, Object>();
log.info("Setting up the Store Procedure Params");
inParams.put("IN_ARRAY", new SqlTypeValue() {
public void setTypeValue(PreparedStatement cs, int index, int sqlType, String typeName) throws SQLException {
Connection con = cs.getConnection();
ArrayDescriptor des = ArrayDescriptor.createDescriptor("****.PROD_PRCT_BRKDWN_TYPE_ARRAY", con);
ARRAY a = new ARRAY(des, con, appViewBean$Session.getExcelRecLst().toArray());
cs.setObject(1, (Object)a);
}
});
inParams.put("OUT_ARRAY", identifier); // what should the identifier be ?????????
if (log.isDebugEnabled()) {
log.debug("Executing the **** Store Procedure ");
}
Map out = super.execute(inParams); // how to get the same array as value ??????
log.info("output size is --------------------->>>>>>>>>> "+out.size());
for(Object o : out.keySet()){
log.info((String)out.get(o));
returnVal = Boolean.parseBoolean((String)out.get(o));
}
if (log.isDebugEnabled()) {
log.info("Output from **** Store Procedure :" + out);
}
return returnVal;
}
}
Update:
After making use of the Spring Data JDBC Extension the source code had to be changed to accommodate the the new response which is pasted below, but the problem of connection still exists when the bean.getAttributes() method is called. Looks like a way needs to be found to not close the connection or access the values before the connection gets closed.
Map out = super.execute(inParams);
log.info("output size is --------------------->>>>>>>>>> "+out.size()); //prints the actual value
Object[] idOutArraz = (Object[])out.get("OUT_ARRAY");
log.info("size of returnValue is "+idOutArraz.length); //prints the right number of results
for(int i= 0; i<idOutArraz.length;i++){
Object[] attrs = null;
Struct bean = (Struct) idOutArraz[i];
attrs = bean.getAttributes();
if (attrs != null) {
System.out.println(Arrays.asList(attrs));
}
}
Answered after lot many trial and errors with different approaches.
After trying to implement lot many solutions the Callable statement worked for me. Looks like a workaround, but any solution to resolve the actual implementation is welcome.
Please find below the working copy of the implementation.
import java.math.BigDecimal;
import java.sql.Array;
import java.sql.CallableStatement;
import java.sql.Connection;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;
import javax.sql.DataSource;
import oracle.jdbc.OracleTypes;
import oracle.sql.ARRAY;
import oracle.sql.ArrayDescriptor;
import oracle.sql.STRUCT;
import org.apache.log4j.Logger;
import org.springframework.jdbc.core.SqlOutParameter;
import org.springframework.jdbc.core.SqlParameter;
import org.springframework.jdbc.object.StoredProcedure;
import com.****.****.****.ExcelListenerBean;
import com.****.****.****.RevAppViewBean;
public class RevPrdBrkDwnSP extends StoredProcedure{
private final Logger log = Logger.getLogger(this.getClass().getName());
private Connection con = null;
private DataSource ds = null;
public RevPrdBrkDwnSP(DataSource dataSource, String storeProcName) throws SQLException {
// Run the Parent
super(dataSource, storeProcName);
con = dataSource.getConnection();
ds = dataSource;
if (log.isInfoEnabled()) {
log.info("Stored Procedure Name : "+ storeProcName);
}
// Declare the Parameter Details
declareParameter(new SqlParameter("IN_ARRAY", OracleTypes.ARRAY, "****.PROD_PRCT_BRKDWN_TYPE_ARRAY"));
declareParameter(new SqlOutParameter("OUT_ARRAY", OracleTypes.ARRAY, "****.PROD_PRCT_BRKDWN_TYPE_ARRAY"));
// Compile the SP
compile();
}
public List<ExcelListenerBean> execute(final RevAppViewBean appViewBean$Session, DataSource dataSource) throws Exception {
dataSource = ds;
List<ExcelListenerBean> beans = new ArrayList<ExcelListenerBean>();
log.info("Setting up the Store Procedure Params");
String getDBUSERByUserIdSql = "{call ****.PRCS_PROD_PRCT_BRKDWN_ENTRIES(?,?)}";
CallableStatement cs = con.prepareCall(getDBUSERByUserIdSql);
ArrayDescriptor des = ArrayDescriptor.createDescriptor("PBAREV.PROD_PRCT_BRKDWN_TYPE_ARRAY", con);
ARRAY a = new ARRAY(des, con, appViewBean$Session.getExcelRecLst().toArray());
cs.setObject(1, (Object)a);
cs.registerOutParameter(2, OracleTypes.ARRAY, "****.PROD_PRCT_BRKDWN_TYPE_ARRAY");
if (log.isDebugEnabled()) {
log.debug("Executing the PBAREV Store Procedure ");
}
cs.execute();
log.info("Executed ****.PRCS_PROD_PRCT_BRKDWN_ENTRIES... Processing values to beans");
Array arr = cs.getArray(2);
Object[] objArr = (Object[]) arr.getArray();
for(int i=0; i<objArr.length;i++){
STRUCT st = (STRUCT)objArr[i];
ExcelListenerBean bean = new ExcelListenerBean();
Object[] obj = st.getAttributes();
bean.setPrntGdwIdN(((BigDecimal)obj[1]).longValue());
bean.setChldGdwIdN(((BigDecimal)obj[2]).longValue());
bean.setChldAsetPrcntN(Double.valueOf(String.valueOf(obj[4])));
bean.setStatus(String.valueOf(obj[8]));
bean.setStatusMessage(String.valueOf(obj[9]));
beans.add(bean);
}
if (log.isDebugEnabled()) {
log.info("Finised processing SP output values to ExcelListenerBeans");
}
return beans;
}
}
On the Oracle side, your code could look like this:
Global type delcration:
CREATE OR REPLACE TYPE NUM_ARRAY AS TABLE OF NUMBER;
Stored procedure:
CREATE OR REPLACE PROCEDURE PROD_PRCT_BRKDWN_TYPE_ARRAY (
in_array IN NUM_ARRAY,
out_status OUT VARCHAR2)
IS
...
Plain JDBC code (with some Oracle specific parts):
Connection con = ...;
CallableStatementcs = con.prepareCall(" ... ");
ArrayDescriptor des = ArrayDescriptor.createDescriptor("PBAREV.PROD_PRCT_BRKDWN_TYPE_ARRAY", con);
Integer[] idArray = new Integer[50000];
// fill the array of integers here
for (int i = 0; i < idArray.length; i++)
idArray[i] = ....;
ARRAY a = new ARRAY(des, con, idArray);
cs.setObject(1, (Object)a);
cs.registerOutParameter(2, OracleTypes.ARRAY, "PBAREV.PROD_PRCT_BRKDWN_TYPE_ARRAY");
cs.execute();
ARRAY outArray = (ARRAY)cs.getArray(2);
Integer[] idOutArraz = (Integer[])outArray.getArray();
I haven't tested the code. But it should give you an idea.
Update:
For the conversion to the Spring Framework, you might want to look at the Spring Data JDBC Extension project that contains the class org.springframework.data.jdbc.support.oracle.SqlReturnArray and declare you parameter like this:
declareParameter(new SqlOutParameter("OUT_ARRAY", Types.ARRAY,
"PBAREV.PROD_PRCT_BRKDWN_TYPE_ARRAY", new SqlReturnArray()));
I wonder what the Map of the execute method contains for the out array because the documentation doesn't say anything.

Categories