ClassCastException (String to Long) when running a subquery with Criteria - java

First my setups :
mysql-connector-java 5.1.24
hibernate-core 4.1.10.Final
I've got an ClassCastException when running this criteria query :
Criteria sellableItemsCriteria = session.createCriteria(MarketData.class, "md");
sellableItemsCriteria.add(Restrictions.in("region", regions));
sellableItemsCriteria.add(Restrictions.in("itemTypeId", items));
DetachedCriteria sellOrderSizeCriteria = DetachedCriteria.forClass(MarketOrder.class);
sellOrderSizeCriteria.add(Restrictions.eq("marketDataId", "md.id"));
sellOrderSizeCriteria.add(Restrictions.eq("bid", false));
sellOrderSizeCriteria.setProjection(Projections.count("marketDataId"));
sellableItemsCriteria.add(Subqueries.lt(0L, sellOrderSizeCriteria));
The exception :
Caused by: java.lang.ClassCastException: java.lang.String cannot be cast to java.lang.Long
The problem is from this line (first i tried with 0 instead of 0L and i got Integer cannot be cast to Long so that why i switched to a Long) :
sellableItemsCriteria.add(Subqueries.lt(0L, sellOrderSizeCriteria));
And this is the mysql query i want to run :
SELECT md.* FROM `marketdata` md
WHERE md.region IN (:regions)
AND md.item_typeID IN (:items)
AND (SELECT COUNT(marketData_id) FROM `marketorder` WHERE marketData_id = md.id AND bid = 0) > 0
How can i resolve the cast problem ?
Or maybe there is a better way to do this with Criteria ?
Thanks

I'm pretty sure you'll find that the exception comes in fact from this line:
sellOrderSizeCriteria.add(Restrictions.eq("marketDataId", "md.id"));
This line tries to compare the marketDataId property of MarketOrder to the String "md.id". That's not what you want to do. What you want to do is to compare the marketDataId property of MarketOrder to the id property of md. And you thus need to use eqProperty() instead:
sellOrderSizeCriteria.add(Restrictions.eqProperty("marketDataId", "md.id"));

Related

Using Lookback API - Query Error: incomplete intersection - Release Scope Change

I am tring to use Lookback API. I want to get all features change during a release.
What I tried :
LookbackQuery query = lookbackApi.newSnapshotQuery();
query.addFindClause("_TypeHierarchy", "PortfolioItem");
query.addFindClause("ObjectID", "280075838440");
Map previousValue = new HashMap();
previousValue.put("$exists", "true");
query.addFindClause("_PreviousValues.Release", previousValue);
query.requireFields("_SnapshotDate", "_SnapshotNumber", "FormattedID",
"Name", "Release","_PreviousValues.Release").hydrateFields("Release, _PreviousValues.Release");
LookbackResult resultSet = query.execute();
I have this exception :
Exception in thread "main" com.rallydev.lookback.LookbackException:
Query Error: incomplete intersection between 'hydrate' clause of
[Release, _PreviousValues.Release] with 'fields' clause of
[_SnapshotNumber, _PreviousValues.Release, _SnapshotDate, FormattedID,
Release, Name] at
com.rallydev.lookback.LookbackResult.validate(LookbackResult.java:101)
at
com.rallydev.lookback.LookbackApi.executeQuery(LookbackApi.java:233)
at
com.rallydev.lookback.LookbackQuery.validateAndRun(LookbackQuery.java:243)
at com.rallydev.lookback.LookbackQuery.execute(LookbackQuery.java:59)
at fr.mipih.rally.TestLoockback.main(TestLoockback.java:38)
But when I tried directly via: https://eu1.rallydev.com/analytics/v2.0/service/rally/workspace/9396539899/artifact/snapshot/query.js?hydrate=["Release","_PreviousValues.Release"]&start=1&pagesize=2000&find={$and: [{"ObjectID": 280075838440},{"_PreviousValues.Release": {"$exists":true}}]}&fields=["_SnapshotDate","_SnapshotNumber","FormattedID","Name","Release","_PreviousValues.Release"]
then I get some results!
Could you help me please and show me what I did wrong ?
The issue is in query - please wrap each field quote:
query.requireFields("_SnapshotDate", "_SnapshotNumber", "FormattedID",
"Name", "Release","_PreviousValues.Release").hydrateFields("Release", "_PreviousValues.Release");

JPA QL issue with IS NULL filter for MongoDB in Hibernate OGM

Im using Hibernate OGM with MongoDB. My JPA QL is below:
String checkquery = "SELECT p FROM pppoe_test p where p.sourceIP=:source_ip and p.login>:logentrytime and (p.logout>:logentrytime OR p.logout IS NULL)";
I get an error like:
no viable alternative at input 'NULL'
HQL000002: The query SELECT p FROM PPPoESession p where p.sourceIP=:source_ip and p.login>:logentrytime and (p.logout>:logentrytime OR p.logout IS NULL) is not valid
Exception in thread "main" org.hibernate.hql.ParsingException: HQL000002: The query SELECT p FROM PPPoESession p where p.sourceIP=:source_ip and p.login>:logentrytime and p.logout>:logentrytime OR p.logout IS NULL is not valid; Parser error messages: [[statement, statementElement, selectStatement, queryExpression, querySpec, whereClause, logicalExpression, expression, logicalOrExpression, logicalAndExpression, negatedExpression, equalityExpression]: line 1:144 state 0 (decision=51) no viable alt; token=[#51,144:147='NULL',<75>,1:144]].
at org.hibernate.hql.QueryParser.parseQuery(QueryParser.java:70)
at org.hibernate.ogm.datastore.mongodb.query.parsing.impl.MongoDBBasedQueryParserService.parseQuery(MongoDBBasedQueryParserService.java:40)
at org.hibernate.ogm.query.impl.OgmQueryTranslator.getQuery(OgmQueryTranslator.java:169)
at org.hibernate.ogm.query.impl.OgmQueryTranslator.getLoader(OgmQueryTranslator.java:134)
at org.hibernate.ogm.query.impl.OgmQueryTranslator.list(OgmQueryTranslator.java:128)
at org.hibernate.engine.query.spi.HQLQueryPlan.performList(HQLQueryPlan.java:216)
at org.hibernate.internal.SessionImpl.list(SessionImpl.java:1326)
at org.hibernate.internal.QueryImpl.list(QueryImpl.java:87)
at org.hibernate.jpa.internal.QueryImpl.list(QueryImpl.java:606)
at org.hibernate.jpa.internal.QueryImpl.getResultList(QueryImpl.java:483)
I have a native mongo query that works, but not able to get it working through this JPA route. Any pointers will help.
Here is the mongodb doc, that I had earlier inserted via the OGM.
{
"_id" : "cc88a708-c222-4e52-b151-c0f40556b27e",
"connectionTimeInSeconds" : NumberLong(100),
"location" : "MyCastle",
"datatransferIn" : NumberLong(7777777),
"sourceIP" : "172.168.10.123",
"packetsOut" : NumberLong(33333),
"login" : ISODate("2016-07-09T20:45:36.492Z"),
"logout" : null,
"user" : "dvinod#xyz.com",
"packetsIn" : NumberLong(22222),
"datatransferOut" : NumberLong(5555555)
}
I do have the attributes setup properly in the entity
#Entity (name="pppoe_test")
public class PPPoESession { ...
#Temporal(TemporalType.TIMESTAMP)
private Date logout;
#Basic(optional = false)
private String user;
#Basic(optional = false)
private String sourceIP;
Thanks.
UPDATE1 : Issue is not specific to Date type, but for Strings as well. Wondering if the support for IS NULL is in place for the MongoDB provider. Have posted on the Hibernate OGM Forum. Shall update when I hear back from them.
UPDATE2 : Apparently the issue is with the case-sensitivity of the parser for 'null', 'false' and 'true'. The issue is in the current latest release of OGM v5.0.1. A issue was raised in the bug tracker and is being worked-on (https://hibernate.atlassian.net/browse/OGM-1118)

Query for Edges in ArangoDB with Java throws Gson exception

I'm new to ArangoDB and trying to do a few very basic queries. I was successful to add vertices and edges, but the query retrieving edges always throws an exception. I tried a few different queries from the (very minimalistic) documentation and it always throws the same. Here is one of the queries:
CursorEntity<BaseDocument> r = arangoDriver.graphGetEdges("MyGraph", BaseDocument.class, "Person/1");
while (r.iterator().hasNext()){
BaseDocument d = r.iterator().next();
System.out.println(d.getDocumentHandle());
}
Or this one with the same exception:
String query = "for i in GRAPH_EDGES(#graphName, #vertexId, {direction: 'outbound', edgeCollectionRestriction: 'Friends'}) return i";
Map<String, Object> bindVars = new MapBuilder().put("graphName", "MyGraph").put("vertexId", "Person/1").get();
CursorEntity<PlainEdgeEntity> result;
try {
result = arangoDriver.executeQuery(query, bindVars, PlainEdgeEntity.class ,true, 10);
And here the exception:
Exception in thread "main" com.google.gson.JsonSyntaxException: java.lang.IllegalStateException: Expected BEGIN_OBJECT but was STRING
at com.google.gson.internal.bind.ReflectiveTypeAdapterFactory$Adapter.read(ReflectiveTypeAdapterFactory.java:176)
at com.google.gson.Gson.fromJson(Gson.java:803)
at com.google.gson.Gson.fromJson(Gson.java:868)
at com.google.gson.Gson$1.deserialize(Gson.java:126)
at com.arangodb.entity.EntityDeserializers$CursorEntityDeserializer.deserialize(EntityDeserializers.java:519)
at com.arangodb.entity.EntityDeserializers$CursorEntityDeserializer.deserialize(EntityDeserializers.java:488)
at com.google.gson.TreeTypeAdapter.read(TreeTypeAdapter.java:58)
at com.google.gson.Gson.fromJson(Gson.java:803)
at com.google.gson.Gson.fromJson(Gson.java:768)
at com.google.gson.Gson.fromJson(Gson.java:717)
at com.arangodb.entity.EntityFactory.createEntity(EntityFactory.java:109)
at com.arangodb.BaseArangoDriver.createEntityImpl(BaseArangoDriver.java:270)
at com.arangodb.BaseArangoDriver.createEntity(BaseArangoDriver.java:181)
at com.arangodb.BaseArangoDriver.createEntity(BaseArangoDriver.java:219)
at com.arangodb.impl.InternalCursorDriverImpl.executeQuery(InternalCursorDriverImpl.java:78)
at com.arangodb.ArangoDriver.executeQuery(ArangoDriver.java:1877)
at com.arangodb.ArangoDriver.graphGetEdges(ArangoDriver.java:4135)
at x.y.z.database.arangodb.Arango.main(Arango.java:34)
I almost think it is a bug? Maybe a problem with newest versions? Or do i miss something?
Using latest versions.. 2.6.8 and driver 2.5.7
Update: if I use a nonexistent ID it returns zero results without exception and if i use an existing ID the same exception is thrown. that tells me that i used the right parameters, and the problem is most likely a bug..
As stj pointed out, there's a driver release fixing the initial problem: http://github.com/arangodb/arangodb-java-driver/releases .
That should work fine with the following code:
CursorEntity<BaseDocument> r = driver.graphGetEdges("myGraph",
BaseDocument.class, "Person/1");
Iterator<BaseDocument> it = r.iterator();
while {
it.hasNext()) {
BaseDocument d = it.next();
System.out.println(d.getDocumentHandle());
}
}
The example code while (r.iterator().hasNext()) { ... } won't work because it will create a new Iterator object in each iteration and thus never finish
We added more examples howto work with ArangoDB graphs in java to the learn more section of the README

Using Arraylist in Mule to query Salesforce

We are trying to query Salesforce with an ArrayList in the where statement.
Below is is the error we ran into when we tried using the ArrayList in the where clause.
Query we used against Salesforce:
Select Id,Billing_Number__c from Call_Log__c where Id in #[flowVars.successlist]
successlist contains the values ['a1o90000001msXwAAI', 'a1o90000001msXxAAI'].
Error Message:
Message: Failed to invoke query. Message payload is of type: ArrayList
How do I resolve this error?
Unfortunately, you can't use ArrayLists as parameters in Salesforce (or Database) queries. You'll have to create the query dynamically with a script component.
Try this:
<scripting:script engine="Groovy">
<![CDATA[def sb = new StringBuilder()
sb.append('Select Id,Billing_Number__c from Call_Log__c')
if (flowVars.successlist != null && !flowVars.successlist.empty) {
sb.append(' where Id in (\'')
for (i in 0 .. flowVars.size()) {
if (i > 0) sb.append('\',\'')
sb.append(flowVars.successlist[i])
}
sb.append('\')')
}
flowVars.query = sb.toString()]]>
</scripting:script>
<sfdc:query query="#[flowVars.query]" doc:name="Salesforce - Query"/>
If you were using a Database, you would have to set the query type as dynamic:
<db:select doc:name="Database">
<db:dynamic-query><![CDATA[#[flowVars.query]]]></db:dynamic-query>
</db:select>
We have used a Java function string.join to convert the list as shown below:
SELECT id FROM User where Id in (#["'" + String.join("','", flowVars.fvCreatedbyIdList) + "'"])

MongoDb. Extracting integer from database. java.lang.Integer cannot be cast to java.lang.String

I am new to MongoDb. I was trying to retreive data from the db. Here is part of my code:
dbc(TABLENAME).find ( MongoDBObject (UID -> uid)).toList.foreach {s =>
val Rollno = s.getAs[String](ROLL).getOrElse ("?")
Apparently ROLL is set as integer, and I keep on getting the error java.lang.ClassCastException: java.lang.Integer cannot be cast to java.lang.String
Is there an easy solution to get it?
How about getting it as an integer and then using toString?
dbc(TABLENAME).find ( MongoDBObject (UID -> uid)).toList.foreach {s =>
val Rollno = s.getAs[Int](ROLL).map(_.toString).getOrElse("?")

Categories