how to set the userPrincipal() to null in java junit - struts2

i want to set the UserPrincipal() to null from junit of my application. For that i have tried to set the request to null but i got null pointer exception. Please help me to resolve the problem.
Below is my code
if(request.getUserPrincipal()!=null){
username=request.getUserPrincipal().getName();
}
i want to get the condition false.

i have found the solution...
get MockHttpServletRequest from junit and set userprinciple to null
MockHttpServletRequest httpServletRequest = new MockHttpServletRequest();
httpServletRequest.setUserPrincipal(null);

Related

Throwing null pointer exception when accessing property of the domain object

Inside a controller i just test these two lines. RaceRegistration domain has a property compositeEvent. So, i access the Registration domain first and then access the compositeevent using .compositeEvent.
println (RaceRegistration.get(r.toLong()))
println (RaceRegistration.get(r.toLong())).compositeEvent
The following error is thrown. As you can see the first print succeeds i.e it gets the Registration domain but the second println fails. My question is why is it throwing null pointer when we are certain that the RaceRegistration domain was accessed successfully.
com.runnercard.registration.RaceRegistration : 8
ERROR errors.GrailsExceptionResolver: NullPointerException occurred when processing request: [POST] /roadrace/message/sendEmail - parameters:
I appreciate any help. Thanks!
Null is null. Don't doubt this: it is true.
The 'void' println expression evaluates to null and the failing code is roughly equivalent to the following:
x = println (RaceRegistration.get(r.toLong()))
// x is null - so the following results in a NullPointerException
x.compositeEvent
It is probable that the parenthesis is merely in the wrong spot (or even over-specified):
println (RaceRegistration.get(r.toLong()).compositeEvent)
// -or
println RaceRegistration.get(r.toLong()).compositeEvent

Grails wrong evaluation of expression

I wrote a function in my service class where I evaluate a passed parameters from controller but Grails is returning wrong evaluation results.
def list(String q,String qval,String srt,String ord){
log.debug("q==="+q)
log.debug("qval==="+qval)
log.debug("srt==="+srt)
log.debug("order==="+ord)
all these debug statements print null as expected. Now
boolean qvalbool=qval?.trim()
log.debug("qvalbool===>>"+qvalbool) prints true!!!
!StringUtils.isEmpty(q) && !StringUtils.isEmpty(qval) returns true!!
both statements should return false while they are returning true what is going on with this? any ideas?
I'm using grails 2.4.2
Evan Wong's comment is very likely correct that you're seeing a string containing the word null.
Often when Groovy prints out values it's not apparent what their type is.
groovy:000> null
===> null
groovy:000> 'null'
===> null
Also in Groovy the expression null + '' evaluates to the String 'null'.
That would be an easy way to change the value of this parameter so it contains the string 'null'.

Binary expression in return statement neo4jClient neo4j

I am trying to get the following Cypher query written out in GraphClient:
START agency=node(12345)
MATCH agency
-[:AGENCY_HAS_PEOPLE]-()
-[:AGENCY_HAS_PERSON]-person
,person-[?:PERSON_IS_CARER]-carer
,person-[?:PERSON_IS_CLIENT]-client
WHERE (person.UniqueId! = 18989)
RETURN person, carer is not null as IsCarer, client is not null as IsClient
The query works fine in the console and returns the results I expect:
person IsCarer IsClient
Node(1545421) True False
When I try to write that query using Neo4jClient, it throws the following exception.
Expression of type System.Linq.Expressions.LogicalBinaryExpression is not supported.
It is mainly due to the expression in the return statement:
.Start(...)
.Match(...)
.Where(...)
.Return((person, client, carer) => new
{
Person = person.As<Person>(),
IsClient = client != null
IsCarer = carer != null
});
Is anyone already working on a solution for this?
Is there a workaround for it?
Is there any other way to write this query to get the same result?
If I were to implement a solution for this, is there anything related to the internals of Neo4jClient (limitation, pitfalls) that I should know before I begin?
Thanks..
It's a bug in https://github.com/Readify/Neo4jClient/blob/master/Neo4jClient/Cypher/CypherReturnExpressionBuilder.cs
Fork the project
Clone it locally
Write a failing test that demonstrates the problem, in https://github.com/Readify/Neo4jClient/blob/master/Test/Cypher/CypherFluentQueryReturnTests.cs
Fix the issue
Commit and push your fix
Open a pull request
When I'm happy with the quality of the solution, I'll accept and merge the pull request. The fix will then be published to NuGet within a few minutes.

Strange behavior of gorm finder

In a controller I have this finder
User.findByEmail('test#test.com')
And works.
Works even if I write
User.findByEmail(null)
But if i write
User.findByEmail(session.email)
and session.email is not defined (ergo is null) it throw exception
groovy.lang.MissingMethodException: No signature of method: myapp.User.findByEmail() is applicable for argument types: () values: []
Is this behavior right?
If i evaluate "session.email" it give me null so I think it must work as it do when I write
User.findByEmail(null)
Even more strange....
If I run this code in groovy console:
import myapp.User
User.findByEmail(null)
It return a user that has null email but if I run the same code a second time it return
groovy.lang.MissingMethodException: No signature of method: myapp.User.findByEmail() is applicable for argument types: () values: []
You can't use standard findBySomething dynamic finders to search for null values, you need to use the findBySomethingIsNull version instead. Try
def user = (session.email ? User.findByEmail(session.email)
: User.findByEmailIsNull())
Note that even if User.findByEmail(null) worked correctly every time, it would not necessarily give you the correct results on all databases as a findBySomething(null) would translate to
WHERE something = null
in the underlying SQL query, and according to the SQL spec null is not equal to anything else (not even to null). You have to use something is null in SQL to match null values, which is what findBySomethingIsNull() translates to.
You could write a static utility method in the User class to gather this check into one place
public static User byOptEmail(val) {
if(val == null) {
return User.findByEmailIsNull()
}
User.findByEmail(val)
}
and then use User.byOptEmail(session.email) in your controllers.
Jeff Brown from grails nabble forum has identified my problem. It's a GORM bug. see jira
More info on this thread
This jira too
I tried with debugger and it looks it should be working, as you write. Maybe the groovy itself is a little bit confused here, try to help it this way:
User.findByEmail( session['email'] )

assertion/comparison of 2 unmatched string objects is logged as error instead of failure

I executed a simple test case (on jobss-ejb environment), which compares/asserts 2 strings. Unfortunately, the strings are not matching to each other (there's a bug).
But the problem is, when I execute the test case from eclipse it logs the result as failure which is correct because there's a mismatch between expected and actual objects;
whereas when I execute the same test case from ant, the result is logged as error.
This is really strange and surprising and to add more to it, this behaviour is noticed on junit 4 version only, when i execute the test case on junit 3.8, both ant and eclipse log the result as failure.
Any suggestion or pointers on what might be going wrong?
Thanks in advance :)
Ant-version: 1.6.1
Junit version: 4.10
Ok, i digged down further and found that this is not related to any specific application server. It can be reproduced on any app server.
Just create a sample (junit4) test case as mentioned below:
#Test
public void stringTest() {
org.junit.Assert.assertEquals("Comparing 2 string:", "abc", "xyz");
}
Now, run it from eclipse; you will see result as 1 failure.
Run the same via some app server, using an ant (or maven) target and you will get the result as error.
After going through the logs I think that this must be because the junit4 org.junit.Assert.assertEquals(String message, Object expected,Object actual) method throws ComparisonFailure instead of AssertionError.
My analysis on this is that junit4 assert() method (org.junit.Assert.assertEquals(String, Object, Object)) throws ComparisonFailure only for String instances.
Following is the code of org.junit.Assert.assertEquals (junit4 assert method):
static public void assertEquals(String message, Object expected, Object actual) {
if (expected == null && actual == null)
return;
if (expected != null && isEquals(expected, actual))
return;
else if (expected instanceof String && actual instanceof String) {
String cleanMessage= message == null ? "" : message;
throw new ComparisonFailure(cleanMessage, (String) expected,
(String) actual);
} else
failNotEquals(message, expected, actual);
}
And this is the code for junit.framework.Assert.assertEquals(String, Object, Object) (i.e. junit3 assert method)
static public void assertEquals(String message, Object expected, Object actual) {
if (expected == null && actual == null)
return;
if (expected != null && expected.equals(actual))
return;
failNotEquals(message, expected, actual);
}
It can be observed that in junit4 assertEquals() an extra check is added for unequal String instances which throws ComparisonFailure for two unequal strings. For all other unequal objects i.e Integer, Long,etc. the call goes to failNotEquals() method which throws an AssertionError.
Can anyone help me to understand the design significance of adding a String instance check in junit4's org.junit.Assert.assertEquals() method. Why is it really added and why only for String?
The differences in test result behavior as mentioned in question is because of ant version issue. For lower versions of ant, you'll get such type of behavior (may be because the lower ant versions consider ComparisonFailure as error instead of failure).
I found this behavior in ant version 1.7.1 (and lower). But this issue is solved in latest ant jar i.e. 1.8.4.
When I executed the above mentioned test case on latest ant version, the result was logged as failure and not error.
So, if you encounter such a problem just update your ant jar to 1.8.4 or other latest version available.

Resources