Hibernate query language like operator not working - java

cmTDsquery = createQuery("from CmTxnDetailStage cstg where cstg.statusCd=:err" +
" and (cstg.id.batchName like :batchname or cstg.id.batchName like :batchname1)"+
" and cstg.prodTypeBlfd like :search1 "+
" and trunc(cstg.tranUploadDttm)=:uploadDt");
cmTDsquery.bindStringProperty("search1", CmTxnDetailStage.properties.prodTypeBlfd, search);
I declared the search parameter as
search = "MON%";
If I replace the :search1 with 'MON%' ,It works fine and query returns result.
Only above code does not work and returns NULL.
Thanks
----------------Edit 1
cmTDsquery.bindStringProperty("batchname",CmTxnDetailStage.properties.batchName,batchNamePattern);
cmTDsquery.bindStringProperty("batchname1",CmTxnDetailStage.properties.batchName,batchNamePattern1);
Sorry to mention this late , but above bindStringProperty methods works like a charm.
batchname and batchname1 contains "CR_STLM_UBROL%" and "%RMB_PINDBT%".

Do like this while setting parameter
"%"+search+"%"

I can't understand exactly the line
cmTDsquery.bindStringProperty("search1", CmTxnDetailStage.properties.prodTypeBlfd, search);
Do you set the correct value - "MON%" and not for example "MON"?
I have used HQL like query.setParameter("search1","MON%") and it worked fine with like operators.

My code is almost the same :
whereClause = whereClause + (whereClause.length() > 0 ? "AND " : "") + "ac.name LIKE :name ";
And further in my code :
if (searchCriteria.getNameSearchOperator() == SQL_STRING_SEARCH_OPERATORS.CONTAINS) {
value = "%" + value + "%";
}
if (searchCriteria.getNameSearchOperator() == SQL_STRING_SEARCH_OPERATORS.START_WITH) {
value = value + "%";
}
query.setParameter("name", value);
Try using setParameter instead of bindStringProperty.

Related

LDAP with Jacob-ADO-Wrapper

after a little bit of trying I managed to get results from the ldap-server at my company. Now I have a little problem and I seem to be too dump to find any documentation about it.
Command objCmd = new Command();
Recordset RS = new Recordset();
objCmd.setActiveConnection(conn);
objCmd.setCommandText("<LDAP://scdldap.siemens.net:389>;(&(objectClass=scdInternetPerson)(mail=" + email + "));" +searchKeyword+";subTree");
RS = objCmd.Execute();
if (RS.getBOF())
System.out.printf(email + ";" + "null" + "\n");
else {
RS.MoveFirst();
System.out.printf(email + ";" + RS.getFields().getItem(0).getValue() + "\n");
}
This works fine as long as I print the result out to the console. But I would need to get the value as a String (it is always a String), but I can't make it. Can somebody tell me what I am missing? I know this is some VariableType Error, because the result is of type Variant, but
Variant.toString() or anything else is not possible.
Try to convert Variant to Object and then to String, for example:
Variant From = new Variant(1);
Variant To = new Variant(6);
Object[] args = new Object[]{From, To};
String From1 = args[0].toString();
String To1 = args[1].toString();

Siddhi (as a libary) many queries for the Same Stream

(I'm jumping from Esper to Siddhi)
I'm trying to deploy several queries in the same stream. The example here https://docs.wso2.com/display/CEP400/Using+Siddhi+as+a+Library shows how to deploy a query in a stream, altogether in one ExecutionPlan. So what if I want to add a query to the same execution plan, o same stream?
I'm interest to do this grammatically, Java code.
UPDATE
I want to add queries in an existing execution plan. This means while streams are arriving, and not before.
Using an example posted as answer:
SiddhiManager siddhiManager = new SiddhiManager();
String executionPlan = "" +
"#Plan:name('demo') " +
"" +
"define stream cseEventStream (symbol string, price float, volume long);" +
"" +
"from cseEventStream[symbol==\"WSO2\"] " +
"insert into wso2Stream;" +
"" +
"from cseEventStream[symbol==\"ABC\"] " +
"insert into abcStream;";
ExecutionPlanRuntime executionPlanRuntime = siddhiManager.createExecutionPlanRuntime(executionPlan);
StreamCallback streamCallback = new StreamCallback() {
#Override
public void receive(Event[] events) {
EventPrinter.print(events);
}
};
executionPlanRuntime.addCallback("wso2Stream", streamCallback);
//Similarly, we can add another call back for abcStream
streamCallback.startProcessing();
InputHandler inputHandler = executionPlanRuntime.getInputHandler("cseEventStream");
executionPlanRuntime.start();
// HERE: ADD new query <---------------------------------------------
inputHandler.send(new Object[]{"WSO2", 700f, 100l});
inputHandler.send(new Object[]{"ABC", 60.5f, 200l});
inputHandler.send(new Object[]{"WSO2", 60.5f, 200l});
streamCallback.stopProcessing();
executionPlanRuntime.shutdown();
Following sample adds multiple Queries, for same Stream (cseEventStream), within the same Execution Plan.
SiddhiManager siddhiManager = new SiddhiManager();
String executionPlan = "" +
"#Plan:name('demo') " +
"" +
"define stream cseEventStream (symbol string, price float, volume long);" +
"" +
"from cseEventStream[symbol==\"WSO2\"] " +
"insert into wso2Stream;" +
"" +
"from cseEventStream[symbol==\"ABC\"] " +
"insert into abcStream;";
ExecutionPlanRuntime executionPlanRuntime = siddhiManager.createExecutionPlanRuntime(executionPlan);
StreamCallback streamCallback = new StreamCallback() {
#Override
public void receive(Event[] events) {
EventPrinter.print(events);
}
};
executionPlanRuntime.addCallback("wso2Stream", streamCallback);
//Similarly, we can add another call back for abcStream
streamCallback.startProcessing();
InputHandler inputHandler = executionPlanRuntime.getInputHandler("cseEventStream");
executionPlanRuntime.start();
inputHandler.send(new Object[]{"WSO2", 700f, 100l});
inputHandler.send(new Object[]{"ABC", 60.5f, 200l});
inputHandler.send(new Object[]{"WSO2", 60.5f, 200l});
streamCallback.stopProcessing();
executionPlanRuntime.shutdown();
I've used Siddhi version 3.0.6-beta2.
This code sample is a modification made to one of the Siddhi Passthrough test cases (PassThroughTest4).
Update:
Looking at ExecutionPlanRuntime class, it does not seem like it is possible to add queries "on the run".
So, to my understanding, you will have to shutdown current execution plan runtime, add those new queries and start it back.

criteria query is not getting data when adding or condition

I have a Java file that query data and I'm trying to add a filtering function. By using criteria builder and criteria query, I manage to get data that I want to filter.
As starter, this is the column to display my data:
Name Host
Fikrie ubuntu
Fikrie2 unix
Fikrie3 ulalala
Fikrie4 ugagaga
There are 3 variable used here. The Name column, is displaying data from name. For the Host column, it is a bit tricky. It will display the hostname, but if there is a logAsHost display, this data will overwrite the hostname.
So this is how my data really look like:
Name Host
Fikrie ubuntu <-- hostname = 1, logAsHost = ubuntu
Fikrie2 unix <-- hostname = 123, logAsHost = unix
Fikrie3 ulala <-- hostname = ulala, logAsHost = no value
Fikrie4 ugaga <-- hostname = ugaga, logAsHost = no value
When I try to filter just 1 variable, I manage to do so. (Eg. filter by Name). When I try to filter out 2 variable, then a problem happen. I didnt manage to get any data.
This is the code that I use:
public List<Connection> retrieveAll(String nameFilter, String hostFilter,
int start, int length) {
ServiceUtil.requireAdmin();
CriteriaBuilder cb = em.getCriteriaBuilder();
CriteriaQuery<Connection> q = cb.createQuery(Connection.class);
Root<Connection> c = q.from(Connection.class);
q.select(c);
logger.info("nameFilter = [" + nameFilter + "]");
logger.info("hostFilter = [" + hostFilter + "]");
//This is the line that I use to query data.
//when I replace Connection_.hostname with Connection_.logAsHost, or Connection_.name
//It works just fine. So I use either one of these line to query.
//q.where(cb.like(c.get(Connection_.hostname), "%" + hostFilter + "%"));
//q.where(cb.like(c.get(Connection_.logAsHost), "%" + hostFilter + "%"));
//q.where(cb.like(c.get(Connection_.name), "%" + nameFilter + "%"));
//This is the problem part.
//When I add cb.or, it cannot get any data.
//From the documentation, it should just be q.where(cb.or(A, B))
//Where A is the first expression and B is the second.
// I have confirm both the expression are working by calling it separately
q.where(cb.or(cb.like(c.get(Connection_.hostname), "%" + hostFilter + "%")), cb.like(c.get(Connection_.logAsHost), "%" + hostFilter + "%"));
List<Connection> results = em.createQuery(q).setFirstResult(start)
.setMaxResults(length).getResultList();
for (Connection conn : results) {
logger.info("Name=" + conn.getName() + ", hostname=["
+ conn.getHostname() + "]" + ", logAsHost =["
+ conn.getLogAsHost() + "]");
}
return results;
}
This the log to show that the data is available or not:
I used c.get(Connection_.hostname), and passed u to hostFilter,
INFO nameFilter = []
INFO hostFilter = [u]
INFO Name=fikrie3, hostname=[ulala], logAsHost =[]
INFO Name=testt, hostname=[ugaga], logAsHost =[]
I used c.get(Connection_.logAsHost), and passed u to hostFilter,
INFO nameFilter = []
INFO hostFilter = [u]
INFO Name=fikrie, hostname=[192.168.56.90], logAsHost =[ubuntu]
INFO Name=fikrie2, hostname=[192.168.56.90], logAsHost =[unix]
I combine both and passed u to hostFilter,
INFO nameFilter = []
INFO hostFilter = [u]
I'm assuming the cb.or() is causing this error. If so, how do I use OR condition properly in criteriaquery? I'm following this part
or(Expression<java.lang.Boolean> x, Expression<java.lang.Boolean> y) from the documentation.
For me it looks like only a problem with your parenthesis. Your predicates are not parameter to the or method
you have
q.where(
cb.or(
cb.like(c.get(Connection_.hostname), "%" + hostFilter + "%")
),
cb.like(c.get(Connection_.logAsHost), "%" + hostFilter + "%")
);
Which lead to an AND of both predicates.
It should rather be
q.where(
cb.or(
cb.like(c.get(Connection_.hostname), "%" + hostFilter + "%"),
cb.like(c.get(Connection_.logAsHost), "%" + hostFilter + "%")
)
);

riak mapreduce with limit on response size in java

I'm trying to run a mapReduce query on Riak 1.4 that queries by secondary index, sorts the records by date, and then limits the results to the first record.
I've got the secondary index query working. The sort doesn't seem to do anything. No errors on the sort, just returns the results unsorted. The limit on the number of records returned yields a 'bad_json' error returned by the server.
Here's what I have. It is suppose to query the "cars" bucket for the most recent car owned by "john_doe". (some names have been changed to protect the innocent;) :
JSSourceFunction dateSortFunction = new JSSourceFunction(
"function(v) {" +
"return v.sort(function(a, b) {" +
"return a.issueDate - b.issueDate ;" +
"}" +
");" +
"}");
IndexQuery iq = new BinValueQuery(BinIndex.named("person"), "cars", "john_doe");
MapReduceResult response = session.mapReduce(iq)
.addMapPhase(NamedErlangFunction.MAP_OBJECT_VALUE)
.addReducePhase(dateSortFunction)
.addReducePhase(new NamedJSFunction("Riak.reduceLimit"), 1)
.execute();
I've seen a number of posts on sorting and am hoping to figure it out eventually. However, I haven't seen any help on how the LIMIT function might work.
Thanks in advance!
Update:
Thanks to Joe, he put me on the right track. Here's what ended up working for me. My date format is ISO 8601 (eg. 2011-05-18T17:00:00-07:00). So, I can lexically compare for the correct sorting. Also, I found javascript's array shortening method and updated the code to return up-to the first 5 objects.
JSSourceFunction sortLimitFunction = new JSSourceFunction(
"function(v) {" +
"v.sort(function(a, b) {" +
"return a.issueDate < b.issueDate" +
"}" +
");" +
"if (v.length > " + "5" + ") { " +
"v.length = " + "5" + ";" +
"}" +
"return v;" +
"}");
IndexQuery iq = new BinValueQuery(BinIndex.named("person"), "cars", "john_doe");
MapReduceResult response = session.mapReduce(iq)
.addMapPhase(new NamedJSFunction("Riak.mapValuesJson"))
.addReducePhase(sortLimitFunction)
.execute();
For the sorting, there is a mailing list post that covers this topic. The main difference I see between that implementation and yours is the use of the JavaScript Riak.mapValuesJson function in the map phase.
For the limiting, if you want just the first item from the sorted list, try having your sort function return only the first element. While the reduce function can (and probably is) called multiple times as partial result sets arrive from the various vnodes, the first element in the consolidated list must also be the first element in the partial list where it originated, so this should give you what you are looking for:
JSSourceFunction dateSortFunction = new JSSourceFunction(
"function(v) {" +
"var arr = v.sort(function(a, b) {" +
"return a.issueDate - b.issueDate ;" +
"}" +
");" +
"if (arr.length == 0) { " +
"return [];" +
"} else {"
"return arr[0];" +
"}"
"}"
);

Idea Live Template to Log Method Args

I would like to be able to create a live template in Jetbrain's Idea that will log the method's arguments. Let's call it "larg". It would work like:
public void get(String one, String two) {
larg<tab>
to create
public void get(String one, String two) {
log.info("get: one = " + one + " two = " + two);
I'm fine with getting the method name in, but have not figured out how to pull in the method arguments. Any ideas?
I'm 4 years late, but the predefined template soutp pretty much does this using a groovyscript variable.
Here's the groovy script that does what you're looking for
groovyScript("'\"' + _1.collect { it + ' = [\" + ' + it + ' + \"]'}.join(', ') + '\"'", methodParameters())
Looks like it is not currently possible with a live template.
From the Jetbrain's forum:
There is no predefined live template function to do this for you automatically.
You can write a plugin that would provide such a function.
this is my groovy script
groovyScript("import com.intellij.psi.*;import com.intellij.psi.util.PsiTreeUtil; def file = PsiDocumentManager.getInstance(_editor.project).getPsiFile(_editor.document); PsiMethod method = PsiTreeUtil.findElementOfClassAtOffset(file, _editor.caretModel.offset, PsiMethod.class, false); PsiParameter[] parameters = method == null ? PsiParameter.EMPTY_ARRAY : method.parameterList.parameters; return parameters.size() == 0 ? '' : '\"' + method.name + ' : ' + parameters.collect { def prefix = it.name + ' = '; def type = it.type; return type instanceof PsiArrayType ? type.componentType instanceof PsiPrimitiveType ? prefix + '\" + java.util.Arrays.toString(' + it.name + ')' : prefix + '\" + java.util.Arrays.deepToString(' + it.name + ')' : prefix + '\" + ' + it.name }.join(' + \", ')", methodParameters())
In Android Studio in Kotlin I use this to log classname, methodname and parameters.
I use my name as tag to easily filter in logcat. I use these mainly for debugging, I don't commit these messages with my name.
Log.d("MYNAME", "$CLASS_NAME$:$METHOD_NAME$: $PARAMETERS$")
And then the parameters are defined as follows.
CLASS_NAME : kotlinClassName()
METHOD_NAME : kotlinFunctionName()
PARAMETERS : groovyScript("'' + _1.collect { it + ' = $' + it}.join(', ') ", functionParameters())
This would be the result if used in the main activity
fun aFunctionWithParameters( first: Int, second: String, third: ArrayList<String>){
Log.d("MYNAME", "MainActivity:aFunctionWithParameters: first = $first, second = $second, third = $third")
}
I based my solution on Rob's answer and edited it to my needs.

Categories