Jena Location Mapping failed to find configuration - eclipse

i am working with Jena Text Search using SPARQL. It has succeed in compile time and run time but it doesn't show the desired result which is the result should show the URI and the intended text. It looks like error messages but i get the failed description below:
DEBUG org.apache.jena.util.LocationMapper - Failed to find configuration: file:location-mapping.rdf;file:location-mapping.n3;file:location-mapping.ttl;file:etc/location-mapping.rdf;file:etc/location-mapping.n3;file:etc/location-mapping.ttl
DEBUG org.apache.jena.riot.system.stream.JenaIOEnvironment - Failed to find configuration: location-mapping.ttl;location-mapping.rdf;location-mapping.n3;etc/location-mapping.rdf;etc/location-mapping.n3;etc/location-mapping.ttl
The full codes show below:
public class JenaTextSearch {
static {LogCtl.setLog4j();
BasicConfigurator.configure();}
static Logger log = LoggerFactory.getLogger("JenaTextSearch");
public static void main (String ...argv)
{
Dataset ds = createCode();
//loadData(ds, "data.ttl");
queryData(ds);
}
public static Dataset createCode()
{
//base data
Dataset ds1 = DatasetFactory.create();
Model defaultModel = ModelFactory.createDefaultModel();
defaultModel.read("to_index/data.ttl", "N-TRIPLES");
ds1.setDefaultModel(defaultModel);
//define the index mapping
EntityDefinition entDef = new EntityDefinition ("uri", "text", ResourceFactory.createProperty(App.URI_PREFIX,"content"));
Directory dir = null;
try {
dir = new SimpleFSDirectory(Paths.get("index")); //lucene index directory
}
catch (IOException e) {
e.printStackTrace();
}
//join together into a dataset
Dataset ds = TextDatasetFactory.createLucene(ds1, dir, new TextIndexConfig(entDef));
return ds1;
}
public static void queryData(Dataset dataset)
{
String prefix = "PREFIX email: <" + App.URI_PREFIX+">" +
"PREFIX text: <http://jena.apache.org/text#>";
long startTime = System.nanoTime();
System.out.println("Email's content contains 'good'");
String query = "SELECT * WHERE " +
"{?s text:query (email:content 'good')." +
"?s email:content ?text." +
"}" ;
dataset.begin(ReadWrite.READ);
try {
Query q = QueryFactory.create(prefix+"\n"+query);
QueryExecution qexec = QueryExecutionFactory.create(q, dataset);
QueryExecUtils.executeQuery(q, qexec);
}finally { dataset.end();}
long finishTime = System.nanoTime();
double time = (finishTime-startTime)/1.0e6;
System.out.println ("Query "+String.format("FINISH - %.2fms", time));
startTime = System.nanoTime();
System.out.println("Email's content contains 'bad'");
query = "SELECT * WHERE" +
"{(?s ?score ?lit) text:query (email:content 'bad' \"highlight:s:<em class='hiLite'> | e:</em>\")." +
"?s email:content ?text." +
"}" ;
dataset.begin(ReadWrite.READ);
try {
Query q = QueryFactory.create(prefix+"\n"+query);
QueryExecution qexec = QueryExecutionFactory.create(q, dataset);
QueryExecUtils.executeQuery(q, qexec);
} finally { dataset.end() ; }
finishTime = System.nanoTime();
time = (finishTime-startTime)/1.0e6;
System.out.println("Query "+String.format("FINISH - %.2fms", time));
}}
is that a library problem or something? i use Jena 3.9 and 3.13 because it can completely each other, i think. please devise me. thank you.

Related

Database update without data loss. FATAL EXCEPTION: ModernAsyncTask #1

I need to implement an update of the database lying in the assets. User data, namely, in the "favorite" record or not, should be saved.
I already asked a question and they helped me -https://stackoverflow.com/a/53827525/10261947
Everything worked in a test application. But when I transferred the code (exactly the same) to the real application, an error occurs - E/AndroidRuntime: FATAL EXCEPTION: ModernAsyncTask #1
Process: rodionova.lyubov.brodsky, PID: 4196
java.lang.RuntimeException: An error occurred while executing doInBackground()
at android.support.v4.content.ModernAsyncTask$3.done(ModernAsyncTask.java:161)
at java.util.concurrent.FutureTask.finishCompletion(FutureTask.java:383)
at java.util.concurrent.FutureTask.setException(FutureTask.java:252)
at java.util.concurrent.FutureTask.run(FutureTask.java:271)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1162)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:636)
at java.lang.Thread.run(Thread.java:784)
Caused by: java.lang.IllegalArgumentException: the bind value at index 4 is null
at android.database.sqlite.SQLiteProgram.bindString(SQLiteProgram.java:169)
at android.database.sqlite.SQLiteProgram.bindAllArgsAsStrings(SQLiteProgram.java:205)
at android.database.sqlite.SQLiteDirectCursorDriver.query(SQLiteDirectCursorDriver.java:47)
at android.database.sqlite.SQLiteDatabase.rawQueryWithFactory(SQLiteDatabase.java:1397)
at android.database.sqlite.SQLiteDatabase.queryWithFactory(SQLiteDatabase.java:1239)
at android.database.sqlite.SQLiteDatabase.query(SQLiteDatabase.java:1110)
at android.database.sqlite.SQLiteDatabase.query(SQLiteDatabase.java:1278)
at rodionova.lyubov.brodsky.db.PoemsDbHelper.insertCorePoem(PoemsDbHelper.java:121)
at rodionova.lyubov.brodsky.db.PoemsDbHelper.getNewPoems(PoemsDbHelper.java:90)
at rodionova.lyubov.brodsky.db.PoemsDbHelper.onUpgrade(PoemsDbHelper.java:41)
at com.readystatesoftware.sqliteasset.SQLiteAssetHelper.getWritableDatabase(SQLiteAssetHelper.java:197)
at com.readystatesoftware.sqliteasset.SQLiteAssetHelper.getReadableDatabase(SQLiteAssetHelper.java:254)
at rodionova.lyubov.brodsky.db.PoemsProvider.query(PoemsProvider.java:45)
at android.content.ContentProvider.query(ContentProvider.java:1057)
If you do not perform the update, the application is working properly, so I will post only the code DbHelper
public class PoemsDbHelper extends SQLiteAssetHelper {
public static final String DB_NAME = "brodsky.db";
public static final int DBVERSION = 3;
public static final String TBLNAME = "poems_table";
public static final String COL_ID = "id";
public static final String COL_TITLE = "title";
public static final String COl_POEM = "poem";
public static final String COL_SUBJECT = "subject";
public static final String COL_YEARS = "years";
public static final String COL_FAVOURITE = "favorite";
Context mContext;
public PoemsDbHelper(Context context) {
super(context, DB_NAME, null, DBVERSION);
mContext = context;
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
if(newVersion > oldVersion)
getNewPoems(mContext, db);
}
private void getNewPoems(Context context, SQLiteDatabase db) {
InputStream is;
OutputStream os;
final String tempNewDbName = "temp_brodsky.db";
int buffersize = 4096;
byte[] buffer = new byte[buffersize];
String newDBPath = mContext.getDatabasePath(tempNewDbName).getPath();
File newDBFile = new File(newDBPath);
if (newDBFile.exists()) {
newDBFile.delete();
}
File newDBFileDirectory = newDBFile.getParentFile();
if (!newDBFileDirectory.exists()) {
newDBFileDirectory.mkdirs();
}
try {
is = context.getAssets().open("databases/" + DB_NAME);
os = new FileOutputStream(newDBFile);
int bytes_read;
while ((bytes_read = is.read(buffer,0,buffersize)) > 0) {
os.write(buffer);
}
os.flush();
os.close();
is.close();
}catch (IOException e) {
e.printStackTrace();
throw new RuntimeException("Ouch updated database not copied - processing stopped - see stack-trace above.");
}
long id = maxid(db) + 1;
SQLiteDatabase newdb = SQLiteDatabase.openDatabase(newDBFile.getPath(),null,SQLiteDatabase.OPEN_READONLY);
Cursor csr = newdb.query(TBLNAME,null,null,null,null,null,null);
long insert_result;
db.beginTransaction();
while (csr.moveToNext()) {
insert_result = insertCorePoem(
db,
id,
csr.getString(csr.getColumnIndex(COL_TITLE)),
csr.getString(csr.getColumnIndex(COl_POEM)),
csr.getString(csr.getColumnIndex(COL_SUBJECT)),
csr.getString(csr.getColumnIndex(COL_YEARS)),
csr.getString(csr.getColumnIndex(COL_FAVOURITE))
);
if (insert_result > 0) {
id++;
}
}
db.setTransactionSuccessful();
db.endTransaction();
csr.close();
newDBFile.delete();
}
public long insertCorePoem(SQLiteDatabase db, long id, String title, String poem, String subject, String years, String favourite) {
String whereclause = COL_TITLE + "=? AND " + COl_POEM + "=? AND " + COL_SUBJECT + "=? AND " + COL_YEARS + "=?";
String[] whereargs = new String[]{
title,
poem,
subject,
years
};
Cursor csr = db.query(TBLNAME,null,whereclause,whereargs,null,null,null);
boolean rowexists = (csr.getCount() > 0);
csr.close();
if (rowexists) {
Log.d("INSERTCOREPOEM","Skipping insert of row");
return -2;
}
ContentValues cv = new ContentValues();
cv.put(COL_ID,id);
cv.put(COL_TITLE,title);
cv.put(COl_POEM,poem);
cv.put(COL_SUBJECT,subject);
cv.put(COL_YEARS,years);
cv.put(COL_FAVOURITE,favourite);
Log.d("INSERTCOREPOEM","Inserting new column with id " + String.valueOf(id));
return db.insert(TBLNAME, null, cv);
}
private long maxid(SQLiteDatabase db) {
long rv = 0;
String extractcolumn = "maxid";
String[] col = new String[]{"max(" + COL_ID + ") AS " + extractcolumn};
Cursor csr = db.query(TBLNAME,col,null,null,null,null,null);
if (csr.moveToFirst()) {
rv = csr.getLong(csr.getColumnIndex(extractcolumn));
}
csr.close();
return rv;
}
}
I do not understand what is wrong. Identical code works great friend application. I would be grateful for the help.
Your issue is that you likely have a value of null in the years column of a row or rows in the updated database that data is being copied from.
Although you could change the code to handle (skip insertion or use provide a year value) the end result may not be desired. So the most likely fix would be to amend the database to have valid/useful year values.

apache beam: accessing metrics during pipeline processing

Using the WordCount.java example to test metrics. The PrintMetricsFn function (see below) prints the metrics correctly once the pipeline is finished, but fails when called while the pipeline is processing. DirectRunner and FlinkRunner both throw exceptions (null input), while SparkRunner prints only the header line (similar to "* Metric Values *").
private static void PrintMetricsFn(final MetricsFilter inputFilter) {
final MetricResults metrics = result.metrics();
final MetricQueryResults returns = metrics.queryMetrics(inputFilter);
final Iterable<MetricResult<Long>> counters = returns.getCounters();
System.out.println("*** Metric Values ***");
for(final MetricResult<Long> s: counters){
System.out.println(s.getName().getNamespace() + ":" +
s.getName().getName() + ":" + s.getStep() + ": count=" +
s.getAttempted()) ;
}
final Iterable<MetricResult<DistributionResult>> dist = returns.getDistributions();
for (final MetricResult<DistributionResult> d: dist) {
System.out.println(d.getName().getNamespace() + ":" +
d.getName().getName() + ":" + d.getStep() + ": sum=" +
d.getAttempted().getSum() + ", count=" +
d.getAttempted().getCount() + ", min=" +
d.getAttempted().getMin() + ", max=" +
d.getAttempted().getMax() + ", mean=" +
d.getAttempted().getMean());
}
final Iterable<MetricResult<GaugeResult>> gauge = returns.getGauges();
for (final MetricResult<GaugeResult> g: gauge) {
System.out.println(g.getName().getNamespace() + ":" +
g.getName().getName() + ":" + g.getStep() + ": gauge=" +
g.getAttempted().getValue());
}
return;
}
Here are the declarations for the external variables:
private static PipelineResult result;
private static MetricQueryResults returns;
private static MetricsFilter mFilter;
And here's where the mFilter and result variables are set:
mFilter = MetricsFilter.builder()
.addNameFilter(MetricNameFilter.named("ExtractWordsFn", "emptyLines"))
.addNameFilter(MetricNameFilter.named("ExtractWordsFn", "lineLenDistro"))
.addNameFilter(MetricNameFilter.named("ExtractWordsFn", "maxLineLen"))
.build();
result = p.run();
Finally, here's the function that calls PrintMetricsFN without success:
#ProcessElement
public void processElement(#Element final String element, final OutputReceiver<String> receiver) {
lineLen = element.length();
lineLenDist.update(lineLen);
if (element.trim().isEmpty()) {
emptyLines.inc();
}
if (lineLen > localMax) {
localMax = lineLen;
maxLineLen.set(localMax);
}
if((lineCnt++ % 10) == 0) {
PrintMetricsFn(mFilter);
}
// Split the line into words.
final String[] words = element.split(ExampleUtils.TOKENIZER_PATTERN, -1);
// Output each word encountered into the output PCollection.
for (final String word : words) {
if (!word.isEmpty()) {
receiver.output(word);
}
}
}
And for completeness, here's the error I get from DirectRunner:
Caused by: java.lang.NullPointerException
at org.apache.beam.examples.WordCount.PrintMetricsFn(WordCount.java:158)
at org.apache.beam.examples.WordCount.access$1(WordCount.java:157)
at org.apache.beam.examples.WordCount$ExtractWordsFn.processElement(WordCount.java:132)

Query in OrientDB

I try to print a query through the java console but nothing comes out. this is my code someone could help me.
I'm new to OrientDB and I'm just learning.
The query I need is to know the shortest path between two nodes and print this query on the Java console. It does not give me any errors but nothing comes out.
public class Graph {
private static final String DB_PATH = "C:/OrientDataBase/shortest_path";
static OrientGraphNoTx DBGraph;
static OrientGraphFactory factory;
public static void main(String[] args) {
factory = new OrientGraphFactory("plocal:"+DB_PATH);
DBGraph = factory.getNoTx();
HashMap<String, Vertex> nodes = new HashMap<String, Vertex>();
for(int i = 0; i <= 1000; i++)
{
Vertex v = DBGraph.addVertex("class:V");
v.setProperty("vertexID", i+"");
nodes.put(i+"", v);
}
try(BufferedReader br = new BufferedReader(new FileReader("C:/OrientDataBase/sp1.csv"))) {
int i=0;
for(String line; (line = br.readLine()) !=null ; ) {
if(i==0){
i++;
}
else{
String[] vertices = line.split(",");
String vertex1 = vertices[0];
String vertex2 = vertices[1];
String weight= vertices[2];
vertex2 = vertex2.replaceAll(" ", "");
Vertex v1 = nodes.get(vertex1);
Vertex v2 = nodes.get(vertex2);
Edge eLives = DBGraph.addEdge(null, v1, v2, "belongs");
eLives.setProperty("weight", weight);
System.out.println(v1+","+v2+","+weight);
String query = "select expand(shortestPath) from (select shortestPath(#10:0,#10:2,BOTH))";
Iterable<OrientVertex> res = DBGraph.command(new OCommandSQL(query)).execute();
while(res.iterator().hasNext()){
OrientVertex v = res.iterator().next();
System.out.println("rid: "+v.getId().toString()+"\tn:"+v.getProperty("n"));
}
}
}
}
catch (IOException e) {
e.printStackTrace();
}
}
}
I tried your code and you have to put the ticks when you do the query so, it becomes:
String query = "select expand(shortestPath) from (select shortestPath(#10:0,#10:2,'BOTH'))";
I used this csv file.
Hope it helps.
Regards

Print the shortest path to the java console using orientdb

I want to print in the Java console shortestpath between two vertices. I can not print anything or if you have any way to do that would appreciate it.
String subquery = "Select shortestpath(17:10, 17:14, BOTH) ";
Iterable<OrientVertex> result = orientDBGraph.command(new OSQLSynchQuery<OrientVertex>(subquery)).execute();
Assert.assertTrue(result.iterator().hasNext());
System.out.println(result);
for (OrientVertex d : result) {
System.out.println("Shortest path from " + ((OrientVertex) d.getProperty("$current")).getProperty("name") + " and "
+ ((Iterable<OrientVertex>) d.getProperty("$target")).iterator().next().getProperty("name") + " is: "
+ d.getProperty("path"));
}
Code:
import com.orientechnologies.orient.core.sql.OCommandSQL;
import com.tinkerpop.blueprints.impls.orient.OrientGraph;
import com.tinkerpop.blueprints.impls.orient.OrientGraphFactory;
import com.tinkerpop.blueprints.impls.orient.OrientVertex;
public class test {
public static void main(String[] args) {
// TODO Auto-generated method stub
String dbName = "ytrewa";
OrientGraphFactory dbfactory = new OrientGraphFactory("remote:127.0.0.1:2424/"+dbName, "root", "root").setupPool(1, 50);
OrientGraph g = dbfactory.getTx();
try {
String query = "select expand(shortestPath) from (select shortestPath(#9:0,#9:1,BOTH))";
Iterable<OrientVertex> res = g.command(new OCommandSQL(query)).execute();
while(res.iterator().hasNext()){
OrientVertex v = res.iterator().next();
System.out.println("rid: "+v.getId().toString());
}
} finally {
g.shutdown();
}
}
}
Output:
rid: #9:0
rid: #10:0
rid: #12:0
rid: #9:1

GWT-RPC method returns empty list on success

I am creating a webpage having CellTable.I need to feed this table with data from hbase table.
I have written a method to retrieve data from hbase table and tested it.
But when I call that method as GWT asynchronous RPC method then rpc call succeeds but it returns nothing.In my case it returns empty list.The alert box show list's size as 0.
Following is the related code.
Please help.
greetingService.getDeviceIDData(new AsyncCallback<List<DeviceDriverBean>>(){
public void onFailure(Throwable caught) {
// Show the RPC error message to the user
System.out.println("RPC Call failed");
Window.alert("Data : RPC call failed");
}
public void onSuccess(List<DeviceDriverBean> result) {
//on success do something
Window.alert("Data : RPC call successful");
//deviceDataList.addAll(result);
Window.alert("Result size: " +result.size());
// Add a text column to show the driver name.
TextColumn<DeviceDriverBean> nameColumn = new TextColumn<DeviceDriverBean>() {
#Override
public String getValue(DeviceDriverBean object) {
Window.alert(object.getName());
return object.getName();
}
};
table.addColumn(nameColumn, "Name");
// Add a text column to show the device id
TextColumn<DeviceDriverBean> deviceidColumn = new TextColumn<DeviceDriverBean>() {
#Override
public String getValue(DeviceDriverBean object) {
return object.getDeviceId();
}
};
table.addColumn(deviceidColumn, "Device ID");
table.setRowCount(result.size(), true);
// more code here to add columns in celltable
// Push the data into the widget.
table.setRowData(0, result);
SimplePager pager = new SimplePager();
pager.setDisplay(table);
VerticalPanel vp = new VerticalPanel();
vp.add(table);
vp.add(pager);
// Add it to the root panel.
RootPanel.get("datagridContainer").add(vp);
}
});
Code to retrieve data from hbase (server side code)
public List<DeviceDriverBean> getDeviceIDData()
throws IllegalArgumentException {
List<DeviceDriverBean> deviceidList = new ArrayList<DeviceDriverBean>();
// Escape data from the client to avoid cross-site script
// vulnerabilities.
/*
* input = escapeHtml(input); userAgent = escapeHtml(userAgent);
*
* return "Hello, " + input + "!<br><br>I am running " + serverInfo +
* ".<br><br>It looks like you are using:<br>" + userAgent;
*/
try {
Configuration config = HbaseConnectionSingleton.getInstance()
.HbaseConnect();
HTable testTable = new HTable(config, "driver_details");
byte[] family = Bytes.toBytes("details");
Scan scan = new Scan();
int cnt = 0;
ResultScanner rs = testTable.getScanner(scan);
for (Result r = rs.next(); r != null; r = rs.next()) {
DeviceDriverBean deviceDriverBean = new DeviceDriverBean();
byte[] rowid = r.getRow(); // Category, Date, Sentiment
NavigableMap<byte[], byte[]> map = r.getFamilyMap(family);
Iterator<Entry<byte[], byte[]>> itrt = map.entrySet()
.iterator();
deviceDriverBean.setDeviceId(Bytes.toString(rowid));
while (itrt.hasNext()) {
Entry<byte[], byte[]> entry = itrt.next();
//cnt++;
//System.out.println("Count : " + cnt);
byte[] qual = entry.getKey();
byte[] val = entry.getValue();
if (Bytes.toString(qual).equalsIgnoreCase("account_number")) {
deviceDriverBean.setAccountNo(Bytes.toString(val));
} else if (Bytes.toString(qual).equalsIgnoreCase("make")) {
deviceDriverBean.setMake(Bytes.toString(val));
} else if (Bytes.toString(qual).equalsIgnoreCase("model")) {
deviceDriverBean.setModel(Bytes.toString(val));
} else if (Bytes.toString(qual).equalsIgnoreCase("driver_name")) {
deviceDriverBean.setName(Bytes.toString(val));
} else if (Bytes.toString(qual).equalsIgnoreCase("premium")) {
deviceDriverBean.setPremium(Bytes.toString(val));
} else if (Bytes.toString(qual).equalsIgnoreCase("year")) {
deviceDriverBean.setYear(Bytes.toString(val));
} else {
System.out.println("No match found");
}
/*
* System.out.println(Bytes.toString(rowid) + " " +
* Bytes.toString(qual) + " " + Bytes.toString(val));
*/
}
deviceidList.add(deviceDriverBean);
}
}
catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
catch (Exception e) {
// System.out.println("Message: "+e.getMessage());
e.printStackTrace();
}
return deviceidList;
}
Could this be lazy fetching on the server side by hbase. This means if you return the list hbase won't get a trigger to actually read the list and you will simple get an empty list. I don't know a correct solution, in the past I've seen a similar problem on GAE. This could by solved by simply asking the size of the list just before returning it to the client.
I don't have the exact answer, but I have an advise. In similar situation I put my own trace to check every step in my program.
On the server side before return put : System.out.println("size of table="+deviceidList.size());
You can put this trace in the loop for deviceidList;