Access Prolog predicate through java - java

Error is occurred while executing the code.
Variable X = new Variable();
Term goal= new Compound("parent", new Term []{new Atom("ali"),X});
Query q = new Query(goal);
while (q.hasMoreElements()) {
Hashtable binding = (Hashtable) q.nextElement();
Term t = (Term) binding.get(X);
System.out.println(t);
}
and Error is
Exception in thread "main" java.lang.ClassCastException: java.util.HashMap cannot be cast to java.util.Hashtable
at newProj.MyMain.main(MyMain.java:18)
Prolog Predicates are
parent(ali, rabia).
parent(shomaila, mubashir).
parent(shomaila, rabia).
parent(nadia, ali).
parent(sumiya, shomaila).
parent(raheel, ali).
parent(anwar, shomaila).
parent(sara, anwar).
parent(anwar, sana).
parent(sana,naveed).

Try this
Query q =new Query("parent("ali",X)")
java.util.Hashtable solution;
while ( q.hasMoreSolutions() ){
solution = q.nextSolution();
System.out.println( "X = " + solution.get(X));
}

Related

Class cast Exception: java.lang.ClassCastException: java.util.ArrayList cannot be cast to java.lang.Long

while compiling the code I got the above exception. The code is:
IPAMEmailManagerBean.java-
DAOFactory daoFactory = DAOFactory.getInstance();
PropertyDAO propertyDAO = (PropertyDAO) daoFactory.getDAO("org.hc.cbl.dao.property.PropertyDAO");
StringBuilder aaCategoryCode = new StringBuilder();
PropertyAACategoryCodesTO propertyAACategoryCodesTO = null;
List<String> ahrCategoryCodeList = new ArrayList<String>(Arrays.asList(applicantSavedSearchTO.getAccHousingCatIdStr().split(",")));
List<Long> list = new ArrayList<Long>();
for (String s : ahrCategoryCodeList)
list.add(Long.valueOf(s));
System.out.println(list);
List list1 = propertyDAO.findAHRCategoryCodesByPartnerIdAndCodeList1(applicantSavedSearchTO.getPartnerId(), list); //This line showing class cast exception java.util.ArrayList cannot be cast to java.lang.Long
if(list1!=null ){
for(int i=0;i<list1.size();i++){
propertyAACategoryCodesTO=(PropertyAACategoryCodesTO)list1.get(i);
aaCategoryCode.append(propertyAACategoryCodesTO.getAaCategoryCodeDesc()+",");
}
}
}
PropertyDAO.java-
public List findAHRCategoryCodesByPartnerIdAndCodeList1(Long partnerId, List strAHRCategoryCode)throws CBLException {
List AHRCategoryCodesList = null;
try {
log.debug("Entering PropertyAACategoryCodeDAO public List findAHRCategoryCodesByPartnerIdAndCodeList()throws CBLException");
Query query = HibernateUtil.getSession().createQuery("from PropertyAACategoryCodesTO as propertyAACategoryCodesTO "
+ "where propertyAACategoryCodesTO.partnerTO.partnerId=:partnerId and propertyAACategoryCodesTO.aaCategoryId "
+ "in(:strPropertyTypes) order by propertyAACategoryCodesTO.aaCategoryCodeDesc asc");
query.setLong("partnerId",partnerId);
query.setParameter("strPropertyTypes", strAHRCategoryCode);
query.setCacheable(true);
AHRCategoryCodesList=query.list();
HibernateUtil.commitTransaction();
HibernateUtil.closeSession();
} catch (Exception ce) {
ce.printStackTrace();
}
log.debug("Exit PropertyAACategoryCodeDAO public List findAHRCategoryCodesByPartnerIdAndCodeList()throws CBLException");
return AHRCategoryCodesList;
}
I already cast the list value as long, so what might be the cause please. Thanks in advance.
The reason it is showing the exception is that PropertyDAO.findAHRCategoryCodesByPartnerIdAndCodeList1() or one of the methods it is calling is attempting to cast a List into a Long.

SWI Prolog Java jpl.PrologException Query not working

I have two Prolog files. Clauses and Rules as follows:
clauses.pl
get(mary,milk).
go(sandra,kitchen,1).
get(john,football).
go(john,hallway,1).
go(mary,garden,1).
go(john,kitchen,2).
rules.pl
/* X = person Y=location T,T2= time
This rule finds last location of a person */
isAt(X,Y) :- go(X, Y, T), \+ (go(X,_,T2), T2 > T).
/* This rule finds the last location of an object */
whereIs(Q,R) :- findall(R,(get(P,Q,I),go(P,R,_)),L), last(L,R),!.
When I create a Query to find out where John is in Java via the following:
//include the prolog file with clauses to test
File clauseFile = new File ("clauses_qa2.pl");
File ruleFile = new File ("rules.pl");
String clausePath = clauseFile.getAbsolutePath();
String rulePath = ruleFile.getAbsolutePath();
System.out.println("Clause file path: " + clausePath);
System.out.println("Rule file path: " + rulePath);
String t1 = "consult('" + clausePath + "').";
String t2 = "consult('" + rulePath + "').";
jpl.JPL.init();
Query q1 = new Query(t1);
Query q2 = new Query(t2);
Variable X = new Variable("_");
Variable Y = new Variable();
Query q = new Query("isAt",new Term[]{new Atom("john"),X,Y});
while (q.hasMoreElements()) {
Hashtable binding = (Hashtable) q.nextElement();
Term t = (Term) binding.get(X);
System.out.println(t);
}
System.out.println(q.toString());
I get the following error:
Exception in thread "main" jpl.PrologException: PrologException: error(existence_error(procedure, /(isAt, 3)), context(:(system, /('$c_call_prolog', 0)), _1))
at jpl.Query.get1(Query.java:336)
at jpl.Query.hasMoreSolutions(Query.java:258)
at jpl.Query.hasMoreElements(Query.java:472)
However, if I remove that while loops and simply print out the query, I get the following response from Prolog:
Clause file path: G:\Natural Language Final Project\PrologTest\clauses_qa2.pl
Rule file path: G:\Natural Language Final Project\PrologTest\rules.pl
isAt( john, _, _0 )
So I know that at least the query is getting to Prolog from Java. Any ideas about what could be causing the error?
Note:
Turns out that my file paths were not correct.
Changing the code to create the Query as follows:
static void
test_1()
{
Variable X = new Variable();
Term args[] = {
new Atom( "john" ),
X
};
Query query =
new Query(
"isAt",
args );
System.out.println( "iSAt(john, X) = " + query.query() );
}
public static void main(String[] args) throws IOException {
//include the prolog file with clauses to test
File clauseFile = new File ("G:\\Natural Language Final Project\\PrologTest\\src\\clauses_qa2.pl");
File ruleFile = new File ("G:\\Natural Language Final Project\\PrologTest\\src\\rules.pl");
String clausePath = clauseFile.getAbsolutePath();
String rulePath = ruleFile.getAbsolutePath();
System.out.println("Clause file path: " + clausePath);
System.out.println("Rule file path: " + rulePath);
String t1 = "consult('" + "G:\\Natural Language Final Project\\PrologTest\\src\\clauses_qa2.pl"+"').";
String t2 = "consult('" + "G:\\Natural Language Final Project\\PrologTest\\src\\rules.pl"+"').";
/*Scanner scan = new Scanner(ruleFile);
while (scan.hasNextLine()){
System.out.println(scan.nextLine());
}*/
jpl.JPL.init();
Term consult_arg[] = {
new Atom( "G:\\Natural Language Final Project\\PrologTest\\src\\clauses_qa2.pl")
};
Query consult_query =
new Query(
"consult",
consult_arg );
Term consult_arg2[] = {
new Atom( "G:\\Natural Language Final Project\\PrologTest\\src\\rules.pl")
};
Query consult_query2 =
new Query(
"consult",
consult_arg2);
boolean consulted = consult_query.query()&& consult_query2.query();
if ( !consulted ){
System.err.println( "Consult failed" );
System.exit( 1 );
}
test_1();
Variable X = new Variable("_");
Variable Y = new Variable();
Query q = new Query("isAt",new Term[]{new Atom("john"),X});
while (q.hasMoreElements()) {
Hashtable binding = (Hashtable) q.nextElement();
Term t = (Term) binding.get(X);
System.out.println(t);
}
System.out.println(q.toString());
}
results in the following output:
iSAt(john, X) = true
null
isAt( john, _ )
Which is better than the compiler errors, but the answer should be:
isAt(john,X)
X= kitchen
I don't have enough reputation, or I'd leave this as a comment...
I suspect the problem is that the arity of isAt() is 2, but the query is using isAt() with arity 3: isAt(john, X, Y).

Exception when getting Collection<Long> values using Hibernate - ClassCastException: java.math.BigDecimal cannot be cast to java.lang.Long

I've got List propertyIds. And I want to get propertyIds by Collections. This is my code:
Collection<Long> propertyIds = externalTaxManager.getPropertyIdsByTaxId(id); //Return type must be Collection<Long>
This is my DAOImpl,
public Collection<Long> getPropertyIdsByTaxId(Long externalTaxId) {
SQLQuery query = currentSession().createSQLQuery("select b.OMH_PROPERTY_ID from OMH_EXTERNAL_TAX a , " +
"OMH_EXTERNAL_TAX_PROP_XREF b\n" +
"where a.OMH_EXTERNAL_TAX_ID=b.OMH_EXTERNAL_TAX_ID and a.OMH_EXTERNAL_TAX_ID = :externalTaxId ")
.addScalar("OMH_PROPERTY_ID" , LongType.INSTANCE);
query.setParameter("externalTaxId", externalTaxId);
Collection<BigDecimal> propertyIdsList = (Collection<BigDecimal>) query.list();
Long val = null;
Collection<Long> expRes = new HashSet<Long>();
for(BigDecimal values : propertyIdsList){
val = values.longValue();
expRes.add(val);
}
return expRes;
}
above Query returns 500+ values in associating with externalTaxId.
Exception thrown is :
java.lang.ClassCastException: java.math.BigDecimal cannot be cast to java.lang.Long.
What's wrong ?
look at your expected return type:
Collection<Long>
but the DB returns :
Collection<BigDecimal>
so ,you should change your code to:
Collection<BigDecimal> propertyIdsList = query.list();
then try to cast BigDecimal to Long in other way;
^_^ forgive my poor English..
Following snippet worked for me as expected.
public Collection<Long> getPropertyIdsByTaxId(Long externalTaxId) {
SQLQuery query = currentSession().createSQLQuery("select b.OMH_PROPERTY_ID from OMH_EXTERNAL_TAX a , " +
"OMH_EXTERNAL_TAX_PROP_XREF b\n" +
"where a.OMH_EXTERNAL_TAX_ID=b.OMH_EXTERNAL_TAX_ID and a.OMH_EXTERNAL_TAX_ID = :externalTaxId ")
.addScalar("OMH_PROPERTY_ID", LongType.INSTANCE);
query.setParameter("externalTaxId", externalTaxId);
Collection<BigDecimal> propertyIdsList = (Collection<BigDecimal>) query.list();
Long propertyIdsListValue = null;
Collection<Long> propertyIds = new HashSet<Long>();
for (BigDecimal propertyId : propertyIdsList) {
propertyIdsListValue = propertyId.longValue();
propertyIds.add(propertyIdsListValue);
}
return propertyIds;
}

Getting a null-point exception in Neo4j data retrieval

I have the following code.
GraphDatabaseFactory dbFactory = new GraphDatabaseFactory();
GraphDatabaseService db= dbFactory.newEmbeddedDatabase("C:/Users/shadid/Documents/Neo4j/DB");
ExecutionEngine execEngine = new ExecutionEngine(db, null);
ExecutionResult execResult = execEngine.execute("MATCH (mat:TheMatrix) RETURN mat");
String results = execResult.dumpToString();
System.out.println(results);
I am getting a null point exception. I have tried running the command in the neo4j command line. So the data do exist. I am not quite sure where is the error. Quite a noob in neo4j so could someone please help me out
Here's the error I am getting by the way
Exception in thread "main" java.lang.NullPointerException
at org.neo4j.cypher.internal.CypherCompiler.(CypherCompiler.scala:69)
at org.neo4j.cypher.ExecutionEngine.createCompiler(ExecutionEngine.scala:237)
at org.neo4j.cypher.ExecutionEngine.(ExecutionEngine.scala:64)
at App.Main.main(Main.java:53)
Just found a more intuitive way of doing the same thing and it works yay!!!
try ( Transaction ignored = db.beginTx();
Result result = db.execute( "MATCH (n:TheIronGiant) RETURN n.`title: `" ) )
{
String rows ="";
while ( result.hasNext() )
{
Map<String,Object> row = result.next();
for ( Entry<String,Object> column : row.entrySet() )
{
rows += column.getKey() + ": " + column.getValue() + "; ";
}
rows += "\n";
}
System.out.println(rows);
}
You are using the ExecutionEngine constructor that takes a LogProvider as the second parameter, but passing a null value for it. If you called the single-parameter constructor instead, which does not take a LogProvider, you may not get the exception.
Also, ExecutionEngine class is now deprecated, and you should use GraphDatabaseService.execute() instead.

Querying Prolog variables with JPL

I want to make a query to use Prolog in java through JPL, I read the documentation (http://www.swi-prolog.org/packages/jpl/java_api/getting_started.html)
The prolog predicates are these:
child_of(joe, ralf).
child_of(mary, joe).
child_of(steve, joe).
child_of(steve, ralf).
descendent_of(X, Y) :-
child_of(X, Y).
descendent_of(X, Y) :-
child_of(Z, Y),
descendent_of(X, Z).
My code looks like this
Variable X = new Variable();
Query q4 =
new Query(
"descendent_of",
new Term[] {X,new Atom("joe")}
);
java.util.Hashtable solution;
while ( q4.hasMoreSolutions() ){
solution = q4.nextSolution();
System.out.println( "X = " + solution.get(X));
}
According to my prolog predicates, my java code should retrieve 'mary' and 'steve', but I get this:
X = null
X = null
What I'm doing wrong? thanks in advance
EDIT: this is my entire testing
Query q1 =
new Query(
"consult",
new Term[] {new Atom("C:\\Users\\cardozo\\Documents\\fer\\info2\\lore\\test.pl")}
);
return q1;
System.out.println( "consult " + (q.query() ? "succeeded" : "failed"));
Query q2 =
new Query(
"child_of",
new Term[] {new Atom("joe"),new Atom("X")}
);
Boolean resp= q2.query();
System.out.println("child_of(joe,X) is " + resp.toString()
);
Query q3 =
new Query(
"descendent_of",
new Term[] {new Atom("steve"),new Atom("ralf")}
);
System.out.println(
"descendent_of(joe,ralf) is " +
( q3.query() ? "provable" : "not provable" )
);
Variable X = new Variable();
Query q4 =
new Query(
"descendent_of",
new Term[] {X,new Atom("joe")}
);
java.util.Hashtable solution;
q4.query();
while ( q4.hasMoreSolutions() ){
solution = q4.nextSolution();
System.out.println( "X = " + solution.get("X"));
}
And this is what I get in my java console as result
run:
% C:\Users\cardozo\Documents\fer\info2\lore\test.pl compiled 0.00 sec, 8 clauses
consult succeeded
child_of(joe,X) is false
descendent_of(joe,ralf) is provable
X = null
X = null
BUILD SUCCESSFUL (total time: 0 seconds)
I found the solution, I have to use the class Compound (included in jpl) like this
Query q4 = new Query(new Compound("descendent_of", new Term[] { new Variable("X"), new Atom("joe")}));
while ( q4.hasMoreSolutions() ){
solution = q4.nextSolution();
System.out.println( "X = " + solution.get("X"));
}
And I get the solution
X = mary
X = steve
I would try to get variable by name:
solution.get("X")
edit
with a literal query like
Query q4 = new Query("descendent_of(X,joe)")

Categories