Jena TDB insert statement resulting in empty fields - java

I am using Jena APIs to insert and update triples in Jena TDB. My design is such that each of the insert operation is within the transaction control. For example:
dataset.begin (ReadWrite.WRITE)
try
{
// 1st insert operation
dataset.commit()
} finally {
dataset.end();
}
dataset.begin (ReadWrite.WRITE)
try
{
// 2nd insert operation
dataset.commit()
} finally {
dataset.end();
}
After this, when I query the TDB using the READ transaction , I notice that some of the entries (either subject, predicate, or object) are empty. Why does it behaves this way, even though I am not using nested transactions?
Insert Code
public class UpdateTDB2 {
String directory = "C://myTDB//";
Dataset dataset = TDBFactory.createDataset(directory);
public static final String RDFPrefix = "PREFIX rdf: <http://www.w3.org/1999/02/22-rdf-syntax-ns#>";
public static final String XSDPrefix = "PREFIX xsd: <http://www.w3.org/2001/XMLSchema#>";
public static final String MYPrefix = "PREFIX myprefix: <http://www.myexample.com/mySchema#>";
public static void main(String[] args) {
UpdateTDB2 obj = new UpdateTDB2();
obj.createActionInstance();
obj.createStateInstance();
}
public static void execUpdate(String sparqlUpdateString,
GraphStore graphStore) {
UpdateRequest request = UpdateFactory.create(sparqlUpdateString);
UpdateProcessor proc = UpdateExecutionFactory.create(request,
graphStore);
proc.execute();
}
private void updateTriple(String sparqlUpdateString) {
dataset.begin(ReadWrite.WRITE);
try {
GraphStore graphStore = GraphStoreFactory.create(dataset);
execUpdate(sparqlUpdateString, graphStore);
dataset.commit();
} finally {
dataset.end();
}
}
private void createActionInstance() {
String subject = new StringBuffer("myprefix:").append("LS_1_user")
.toString();
String predicate = "rdf:type";
String object = "myprefix:Action";
String insertString = createInsertString(subject, predicate, object);
String sparqlInsertString = createSparqlString(insertString);
updateTriple(sparqlInsertString);
}
private void createStateInstance() {
String subject = new StringBuffer("myprefix:").append("LS_1_user_LicState")
.toString();
String predicate = "rdf:type";
String object = "myprefix:State";
String insertString = createInsertString(subject, predicate, object);
String sparqlInsertString = createSparqlString(insertString);
updateTriple(sparqlInsertString);
}
private String createInsertString(String subject, String predicate,
String object) {
String insertString = new StringBuffer("INSERT DATA { ")
.append(subject).append(" ").append(predicate).append(" ")
.append(object).append(" }").toString();
return insertString;
}
private String createSparqlString(String str) {
String sparqlString = StrUtils.strjoinNL(UpdateTDB2.XSDPrefix,
UpdateTDB2.RDFPrefix, UpdateTDB2.MYPrefix, str);
System.out.println(sparqlString);
return sparqlString;
}
}
Query Code
public class QueryTDB3 {
public static void main(String[] args) {
String directory = "C://myTDB//" ;
Dataset dataset = TDBFactory.createDataset(directory) ;
dataset.begin(ReadWrite.READ) ;
try
{
// Do some queries
String sparqlQueryString1 = "SELECT (count(*) AS ?count) { ?s ?p ?o }" ;
String sparqlQueryString2 = "SELECT * { ?s ?p ?o }" ;
execQuery(sparqlQueryString2, dataset) ;
execQuery(sparqlQueryString1, dataset) ;
} finally
{
dataset.end() ;
}
}
public static void execQuery(String sparqlQueryString, Dataset dataset)
{
Query query = QueryFactory.create(sparqlQueryString) ;
QueryExecution qexec = QueryExecutionFactory.create(query, dataset) ;
try {
ResultSet results = qexec.execSelect() ;
ResultSetFormatter.out(results) ;
} finally { qexec.close() ; }
}
}

Which version of the code are you running?
If the code you show (first part) is really being run in two separate runs (hence two JVMs), then this might be due to a known-and-fixed bug in TDB. It was only present in relative recent versions.
Please try the development version of Jena 2.7.4-SNAPSHOT.

Related

Spring Boot output is No message available , error (status=500)

spring Boot project gives me No message available, null output! i know this error means i have an issue with my code but i am so new to the ontologies and TDB so please help! I am trying to bring all the individualsfrom my rdf file and store it in TDB and i can't find helpful answer!
Example.java
public class Example {
public static void main(String[] args) {
SpringApplication.run(Application.class, args);
}
ExampleController.java
#RestController
public class ExampleController {
File file;
Model model;
InfModel infModel;
Reasoner reasoner = ReasonerRegistry.getOWLReasoner();
Dataset dataset;
QueryExecution qe;
#RequestMapping("/getAll")
public List getAllIndiv() {
List list = new ArrayList();
try {
String directory = "tdb" ;
dataset = TDBFactory.createDataset(directory) ;
dataset.begin(ReadWrite.READ) ;
String uri ="http://example#";
model = dataset.getNamedModel(uri);
String source = "example.owl";
FileManager.get().readModel(model, source);
String a = "";
String queryString = "\r\n"
+ "PREFIX ns: <http://example#>"
+ "PREFIX rdf: <http://example-syntax-ns#>" + "SELECT ?Individuals " + "WHERE {"
+ "?Individuals rdf:type ns:Concept." + "}";
Query query = QueryFactory.create(queryString);
query.getQueryPattern();
qe = QueryExecutionFactory.create(query, dataset);
ResultSet results = qe.execSelect();
ResultSetFormatter.out(results);
while (results.hasNext()) {
QuerySolution result = (results.next());
RDFNode ind = result.get("Individuals");
a = ind.asResource().getLocalName() + "";
list.add(a);
qe.close();
}
return list;
} catch (Exception e) {
e.printStackTrace();
}finally {
if(model != null && dataset != null) {
qe.close();
dataset.commit();
model.close();
dataset.end();
}
}
return null;
}
}

Run a Cypher query from Spring to Neo4j

I have uploaded a CSV file and already have nodes and relationship defined on Neo4j. I've tried to create a program base on an example that basically run a cypher query from Spring that would generate the output from neo4j. However, I'm encountering this error:
Exception in thread "main" java.lang.NoSuchMethodError:org.neo4j.graphdb.factory.GraphDatabaseFactory.newEmbeddedDatabase(Ljava/io/File;)Lorg/neo4j/graphdb/GraphDatabaseService;
at org.neo4j.connection.Neo4j.run(Neo4j.java:43)
at org.neo4j.connection.Neo4j.main(Neo4j.java:37)
I'm wondering what could possibly be the error?
Here is my code:
public class Neo4j{
public enum NodeType implements Label{
Issues, Cost, Reliability, Timeliness;
}
public enum RelationType implements RelationshipType{
APPLIES_TO
}
String rows = "";
String nodeResult;
String resultString;
String columnString;
private static File DB_PATH = new File("/Users/phaml1/Documents/Neo4j/default.graphdb/import/");
public static void main(String[] args){
Neo4j test = new Neo4j();
test.run();
}
void run()
{
clear();
GraphDatabaseService db = new GraphDatabaseFactory().newEmbeddedDatabase(DB_PATH);
try(Transaction tx1 = db.beginTx();
Result result = db.execute("MATCH(b:Business)-[:APPLIES_TO]->(e:Time) RETURN b,e"))
{
while(result.hasNext())
{
while ( result.hasNext() )
{
Map<String,Object> row = result.next();
for ( Entry<String,Object> column : row.entrySet() )
{
rows += column.getKey() + ": " + column.getValue() + "; ";
}
rows += "\n";
}
}
try (Transaction something = db.beginTx();
Result result1 = db.execute("MATCH(b:Business)-[:APPLIES_TO]->(e:Time) RETURN b,e"))
{
Iterator<Node> n_column = result.columnAs("n");
for(Node node: Iterators.asIterable(n_column))
{
nodeResult = node + ": " + node.getProperties("Description");
}
List<String> columns = result.columns();
columnString = columns.toString();
resultString = db.execute("MATCH(b:Business)-[:APPLIES_TO]->(e:Time) RETURN b,e").resultAsString();
}
db.shutdown();
}
}
private void clear(){
try{
deleteRecursively(DB_PATH);
}
catch(IOException e){
throw new RuntimeException(e);
}
}
}
It looks like a Neo4j version conflict.
GraphDatabaseService db = new GraphDatabaseFactory().newEmbeddedDatabase(DB_PATH);
has a String as the argument in Neo4j 2x (https://neo4j.com/api_docs/2.0.3/org/neo4j/graphdb/factory/GraphDatabaseFactory.html#newEmbeddedDatabase(java.lang.String))
but a File in Neo4j 3x (http://neo4j.com/docs/java-reference/current/javadocs/org/neo4j/graphdb/factory/GraphDatabaseFactory.html#newEmbeddedDatabase-java.io.File-)
SDN is probably pulling in Neo4j 2.3.6 as a dependency- please check your dependency tree and override the Neo4j version

Jena queryParseException

I am new to Jena and SPAQL , trying to run jena in eclipse with below code , getting Query Parse Exception. This Query is executing fine on http://dbpedia.org/sparql
What I want is Birth Place
Exception
com.hp.hpl.jena.query.QueryParseException: Line 1, column 84: Unresolved prefixed name: dbpedia-owl:birthPlace
Query
PREFIX res: <http://dbpedia.org/resource/>
SELECT DISTINCT ?string
WHERE {
res:David_Cameron dbpedia-owl:birthPlace ?string .
}
Java Code
import org.apache.jena.atlas.logging.Log;
import com.hp.hpl.jena.query.QueryExecution;
import com.hp.hpl.jena.query.QueryExecutionFactory;
import com.hp.hpl.jena.query.QuerySolution;
import com.hp.hpl.jena.query.ResultSet;
import com.hp.hpl.jena.sparql.engine.http.QueryExceptionHTTP;
public class GetDateOfBirth {
private String service = null;
public GetDateOfBirth(String service)
{
this.service = service;
}
public void TestConnection(){
QueryExecution qe = QueryExecutionFactory.sparqlService(service, "ASK {}");
try{
if(qe.execAsk())
{
System.out.println(service + " is UP");
}
}catch(QueryExceptionHTTP e){
e.printStackTrace();
System.out.println(service + "is Down");
}
finally {
qe.close();
}
}
public ResultSet executeQuery(String queryString) throws Exception {
QueryExecution qe = QueryExecutionFactory.sparqlService(service, queryString);
return qe.execSelect();
}
public static void main(String[] args) {
Log.setCmdLogging() ;
String sparqlService = "http://dbpedia.org/sparql";
/*
* More query examples here:
* http://sparql.bioontology.org/examples
*/
String query = "PREFIX res: <http://dbpedia.org/resource/>" +
" SELECT ?dob WHERE { res:David_Cameron dbpedia-owl:birthPlace ?string .}";
try {
GetDateOfBirth con= new GetDateOfBirth(sparqlService);
ResultSet results = con.executeQuery(query);
for ( ; results.hasNext() ; ) {
QuerySolution soln = results.nextSolution() ;
System.out.println(soln.getResource("?dob").toString());
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
Just like you define the prefix PREFIX res: <http://dbpedia.org/resource/>, you need to specify a prefix for dbpedia-owl. Using DBPedia's Predefined Namespace Prefixes, I assume the updated query would look like this:
PREFIX res: <http://dbpedia.org/resource/>
PREFIX dbpedia-owl: <http://dbpedia.org/ontology/>
SELECT DISTINCT ?string
WHERE {
res:David_Cameron dbpedia-owl:birthPlace ?string .
}

Getting null value from table

i have a piece of jsp code . this code takes data from a table and displays it on a console
For integer values it is working good but for String values it displays null
the issue is not with the table . i have tried other tables also but same result
jsp code :
<%
int mots_id = 0 ;
String mots_name = "" ;
String accesstype = "" ;
GetAccess obj = new GetAccess();
List<GetAccessVO> accesslist = obj.access(attUID);
if(accesslist!=null)
{
Iterator<GetAccessVO> iter = accesslist.iterator();
while(iter.hasNext())
{
GetAccessVO getaccessVO = iter.next();
mots_id = getaccessVO.getmotsid();
String mots_name = getaccessVO.getmotsname();
String accesstype = getaccessVO.getaccess();
out.println(accesstype); // it displays null
}
}
%>
java code :
public class GetAccess{
final static DBConnection db=new DBConnection();
public List<GetAccessVO> access(String attuid)
{
List<GetAccessVO> accesslist = new ArrayList<GetAccessVO>();
try
{
Connection con = db.getConnection();
String query ="select mots_id ,mots_name,access_type from ENV_TEAM where userid = ?";
PreparedStatement pstmt = con.prepareStatement(query);
pstmt.setString(1, attuid);
ResultSet rs = pstmt.executeQuery();
while (rs.next())
{
GetAccessVO getaccessVO = new GetAccessVO();
getaccessVO.setmotsid(rs.getInt(1));
getaccessVO.setmotsname(rs.getString(2));
getaccessVO.setaccess(rs.getString(3));
accesslist.add(getaccessVO);
}
rs.close();
pstmt.close();
con.close();
}
catch (Exception e)
{
e.printStackTrace();
}
return accesslist;
}
}
the setter getter class :
public class GetAccessVO {
private int mots_id;
private String mots_name;
private String access;
public String getmotsname() {
return mots_name;
}
public void setmotsname(String mots_name) {
this.mots_name = mots_name;
}
public int getmotsid() {
return mots_id;
}
public void setmotsid(int mots_id) {
this.mots_id = mots_id;
}
public String getaccess() {
return access;
}
public void setaccess(String access) {
this.access = access;
}
}
i have tried almost everything but the String values always are null
SQL> select * from env_team ;
USERID MOTS_ID MOTS_NAME ACCESS_TYPE
------- ---------- ------------------------------ ------------------------------
as045e 7921 BDS external

How to intercept and change sql query dynamically in mybatis

I use mybatis to perform sql queries in my project. I need to intercept sql query before executing to apply some changed dynamically. I've read about #Interseptors like this:
#Intercepts({#Signature(type= Executor.class, method = "query", args = {...})})
public class ExamplePlugin implements Interceptor {
public Object intercept(Invocation invocation) throws Throwable {
return invocation.proceed();
}
public Object plugin(Object target) {
return Plugin.wrap(target, this);
}
public void setProperties(Properties properties) {
}
}
And it really intercepts executions, but there is no way to change sql query since appropriate field is not writable. Should I build new instance of whole object manually to just replace sql query? Where is the right place to intercept query execution to change it dynamically? Thank.
I hope it will help you:
#Intercepts( { #Signature(type = Executor.class, method = "query", args = {
MappedStatement.class, Object.class, RowBounds.class,
ResultHandler.class
})
})
public class SelectCountSqlInterceptor2 implements Interceptor
{
public static String COUNT = "_count";
private static int MAPPED_STATEMENT_INDEX = 0;
private static int PARAMETER_INDEX = 1;
#Override
public Object intercept(Invocation invocation) throws Throwable
{
processCountSql(invocation.getArgs());
return invocation.proceed();
}
#SuppressWarnings("rawtypes")
private void processCountSql(final Object[] queryArgs)
{
if (queryArgs[PARAMETER_INDEX] instanceof Map)
{
Map parameter = (Map) queryArgs[PARAMETER_INDEX];
if (parameter.containsKey(COUNT))
{
MappedStatement ms = (MappedStatement) queryArgs[MAPPED_STATEMENT_INDEX];
BoundSql boundSql = ms.getBoundSql(parameter);
String sql = ms.getBoundSql(parameter).getSql().trim();
BoundSql newBoundSql = new BoundSql(ms.getConfiguration(),
getCountSQL(sql), boundSql.getParameterMappings(),
boundSql.getParameterObject());
MappedStatement newMs = copyFromMappedStatement(ms,
new OffsetLimitInterceptor.BoundSqlSqlSource(newBoundSql));
queryArgs[MAPPED_STATEMENT_INDEX] = newMs;
}
}
}
// see: MapperBuilderAssistant
#SuppressWarnings({ "unchecked", "rawtypes" })
private MappedStatement copyFromMappedStatement(MappedStatement ms,
SqlSource newSqlSource)
{
Builder builder = new MappedStatement.Builder(ms.getConfiguration(), ms
.getId(), newSqlSource, ms.getSqlCommandType());
builder.resource(ms.getResource());
builder.fetchSize(ms.getFetchSize());
builder.statementType(ms.getStatementType());
builder.keyGenerator(ms.getKeyGenerator());
// setStatementTimeout()
builder.timeout(ms.getTimeout());
// setParameterMap()
builder.parameterMap(ms.getParameterMap());
// setStatementResultMap()
List<ResultMap> resultMaps = new ArrayList<ResultMap>();
String id = "-inline";
if (ms.getResultMaps() != null)
{
id = ms.getResultMaps().get(0).getId() + "-inline";
}
ResultMap resultMap = new ResultMap.Builder(null, id, Long.class,
new ArrayList()).build();
resultMaps.add(resultMap);
builder.resultMaps(resultMaps);
builder.resultSetType(ms.getResultSetType());
// setStatementCache()
builder.cache(ms.getCache());
builder.flushCacheRequired(ms.isFlushCacheRequired());
builder.useCache(ms.isUseCache());
return builder.build();
}
private String getCountSQL(String sql)
{
String lowerCaseSQL = sql.toLowerCase().replace("\n", " ").replace("\t", " ");
int index = lowerCaseSQL.indexOf(" order ");
if (index != -1)
{
sql = sql.substring(0, index);
}
return "SELECT COUNT(*) from ( select 1 as col_c " + sql.substring(lowerCaseSQL.indexOf(" from ")) + " ) cnt";
}
#Override
public Object plugin(Object target)
{
return Plugin.wrap(target, this);
}
#Override
public void setProperties(Properties properties)
{
}
}
You may consider using a string template library (eg Velocity, Handlebars, Mustache) to help you
As of to date, there is even MyBatis-Velocity (http://mybatis.github.io/velocity-scripting/) to help you to do scripting for the sql.
Depending on the changes you want to make, you may want to use the dynamic sql feature of mybatis 3

Categories