Issue with eclipse: Potential null pointed analysis - eclipse

May be, This has been discussed many times. But, I am not clear on how #javax.annotation.nullable and notnull works in Eclipse. I have the below code in eclipse.
if(null != getApplicant()){
name = getApplicant().getName(); //Potential null pointer access
}
Wherein, getApplication() is annotated with #Nullable.
In the above code, I have verified against null before accessing it. But, still I get error here by compiler. The same code works fine Intellij. (Most of the developers in my team use this :().
Kindly tell me how can I get this #javax.annotation.Nullable and #javax.annotation.Notnull worked in eclipse in similar way to Intellij. I dont want to change my IDE just for this different behavior.

There's no assurance to the compiler that calling getApplication() the second time returns a non-null result as it did the first time. Store it in a local for the test and then use that within the if block.

Eclipse warns you, that the second method access could potentially return null. Example code to reproduce nullpointer:
public class A {
int numberCalls;
Applicant getApplicant() {
if (numberCalls++ > 3)
return null;
else
return new Applicant();
}
}
I would suggest to implement your call like this:
Applicant applicant = getApplicant();
if(null != applicant){
name = applicant.getName(); //not anymore Potential null pointer access
}

Related

Why does calling AutoFake.Provide() wipe out fakes already configured with A.CallTo()?

Why does calling fake.Provide<T>() wipe out fakes already configured with A.CallTo()? Is this a bug?
I'm trying to understand a problem I've run into with Autofac.Extras.FakeItEasy (aka AutoFake). I have a partial solution, but I don't understand why my original code doesn't work. The original code is complicated, so I've spent some time simplifying it for the purposes of this question.
Why does this test fail? (working DotNetFiddle)
public interface IStringService { string GetString(); }
public static void ACallTo_before_Provide()
{
using (var fake = new AutoFake())
{
A.CallTo(() => fake.Resolve<IStringService>().GetString())
.Returns("Test string");
fake.Provide(new StringBuilder());
var stringService = fake.Resolve<IStringService>();
string result = stringService.GetString();
// FAILS. The result should be "Test string",
// but instead it's an empty string.
Console.WriteLine($"ACallTo_before_Provide(): result = \"{result}\"");
}
}
If I swap the order of the calls to fake.Provide<T>() and A.CallTo(), it works:
public static void Provide_before_ACallTo()
{
// Same code as above, but with the calls to
// fake.Provide<T>() and A.CallTo() swapped
using (var fake = new AutoFake())
{
fake.Provide(new StringBuilder());
A.CallTo(() => fake.Resolve<IStringService>().GetString())
.Returns("Test string");
var stringService = fake.Resolve<IStringService>();
string result = stringService.GetString();
// SUCCESS. The result is "Test string" as expected
Console.WriteLine($"Provide_before_ACallTo(): result = \"{result}\"");
}
}
I know what is happening, sort of, but I'm not sure if it's intentional behavior or if it's a bug.
What is happening is, the call to fake.Provide<T>() is causing anything configured with A.CallTo() to be lost. As long as I always call A.CallTo() after fake.Provide<T>(), everything works fine.
But I don't understand why this should be.
I can't find anything in the documentation stating that A.CallTo() cannot be called before Provide<T>().
Likewise, I can't find anything suggesting Provide<T>() cannot be used with A.CallTo().
It seems the order in which you configure unrelated dependencies shouldn't matter.
Is this a bug? Or is this the expected behavior? If this is the expected behavior, can someone explain why it works like this?
It isn't that the Fake's configuration is being changed. In the first test, Resolve is returning different Fakes each time it's called. (Check them for reference equality; I did.)
Provide creates a new scope and pushes it on a stack. The topmost scope is used by Resolve when it finds an object to return. I think this is why you're getting different Fakes in ACallTo_before_Provide.
Is this a bug? Or is this the expected behavior? If this is the expected behavior, can someone explain why it works like this?
It's not clear to me. I'm not an Autofac user, and don't understand why an additional scope is introduced by Provide. The stacked scope behaviour was introduced in PR 18. Perhaps the author can explain why.
In the meantime, if possible, I'd Provide all you need to before Resolveing, if you can manage it.

Cookie return undefined in GWT

I have created cookie for user name. Its working fine.
But my problem is:
when i clear cookie and try Cookies.getCookie("uname"); then it will return undefined insted of null.
so how to deal with undefined value ?
I am trying that if uname is not set then goes to else part;
please help me.
Yes, it is like this. Failure by design, please see here
https://code.google.com/p/google-web-toolkit/issues/detail?id=2994
The recommended workaround works:
String val = Cookies.getCookie("uname");
if (val == null || "undefined".equals(val)) {
...
} else {
...
}
But normally it seems to work even without this workaround. In my case I got the 'undefined' on JavaScript level, but in Java code it was sufficient to check for null. The real problem which let crash the code was a few lines later and didn't have anything to do with the getCookie() method. So have a look if you really identified the line with the problem.

FindBugs skipping various bugs

I've got findbugs in eclipse enabled with everything and at the lowest setting. It is only finding some of the bugs instead of all of them.
String b = "bob";
b.trim();
b.replace('b', 'p');
In the above code, I thought findbugs should flag the issue of not using the return value (a case which plenty of other websites show findbugs detecting) but it doesn't flag this case.
I also figured it would find a null bug or possible out of bounds.
ArrayList<String> test=getList();
String c=test.get(10);
private ArrayList<String> getList() {
return null;
}
Why aren't these being detected?
For the second issue, you must annotate the method getList with #CheckForNull so FB knows the method may return null.

Suppress Errors in JavaScript validation

I'm currently developing an eclipse plugin. This plugin contains a project nature which depends on the javaScript nature of jsdt.
Now at a few details the JavaScripts that the projects of my nature can contain are somewhat special.
They can contain "compiler hints" which are basicly statements beginning with #
They can contain return statements outside of functions
But at this two points the standard validation of jsdt come in and marks them as errors (which is normally right). I already managed to get this errors filtered out in the properties of the JavaScript validator (manually).
My question is, how can i exclude these errors from the validation of jsdt automatically for the projects with my nature?
JSDT uses concrete syntax parser which generates syntax errors.
You can't disable this. Only semantics error or warnings can be configured.
However you can disable entire validation of JSDT.
Below solution will suppress errors ands warnings which are generated while we save some changes on java script files. (Auto Build, Build)
Open Properties Dialog of Your Project.
Choose Builders item.
Uncheck "JavaScript Validator". And Press OK button.
Remove current errors and warnings from Problems View
This solution can't eliminate error or warning annotations in editor while you edit. They will show up on editor temporarily only when you edit it.
After a lot of research, hours of deleting markers and debugging i finally managed to delete the errors i wanted. In a bad bad way of course but i've come to a point where i just wanted this to work no matter how it's done.
If you ever want to delete existing problems that had been created during the validation process of jsdt you need to do the following (and you must not ommit anything):
Create a class extending org.eclipse.wst.jsdt.core.compiler.ValidationParticipant
Override isActive(), buildStarting() and reconcile() methods.
So there are two things you basicly have to care about.
The actual problem markers that will be created or had already been created at the end of the validation process.
The Problems created by the validation process. They are of the type CategorizedProblem and can be obtained by the ReconcileContext object that is passed to the reconcile() method.
It seems to me that the CategorizedProblems will be translated to problem markers after the validation process.
So what you need to do is:
Delete all unwanted problem markers of all files in buildStarting (this removes problem markers from all files in your project that are about to be validated)
Iterate the CategorizedProblem objects of the ReconcileContext (getProblems())
Create a new Array containing only the CategorizedProblems you want to keep
Set this new Array to the ReconcileContext with putProblems()
Delete the unwanted markers again for that file (i don't know why this is needed, please don't ask, i don't care anymore :-/)
An example implementation of such a validationParticipant could look like this: (this one will filter out problems complaining about return statements outside of methods:
[...ommited imports ...]
public class MyValidationParticipant extends org.eclipse.wst.jsdt.core.compiler.ValidationParticipant{
#Override
public boolean isActive(IJavaScriptProject project) {
return true;
}
#Override
public void buildStarting(BuildContext[] files, boolean isBatch) {
super.buildStarting(files, isBatch);
for(BuildContext context : files){
IFile file = context.getFile();
deleteUnwantedMarkers(file);
}
}
#Override
public void reconcile(ReconcileContext context) {
IResource resource = context.getWorkingCopy().getResource();
CategorizedProblem[] newProblems = new CategorizedProblem[0];
ArrayList<CategorizedProblem> newProblemList = new ArrayList<CategorizedProblem>();
CategorizedProblem[] probs = context.getProblems("org.eclipse.wst.jsdt.core.problem");
if(probs != null){
for(CategorizedProblem p : probs){
if(!(p.getMessage().equals("Cannot return from outside a function or method."))){
newProblemList.add(p);
}
}
}
}
context.putProblems("org.eclipse.wst.jsdt.core.problem", newProblemList.toArray(newProblems));
deleteUnwantedMarkers(resource);
}
public static void deleteUnwantedMarkers(IResource resource){
if(resource.isSynchronized(IResource.DEPTH_INFINITE)){
try {
IMarker[] markers = resource.findMarkers(IMarker.PROBLEM, true, IResource.DEPTH_INFINITE);
if(markers != null && markers.length > 0){
for(IMarker m : markers){
Object message = m.getAttribute(IMarker.MESSAGE);
if(message.equals("Cannot return from outside a function or method.")){
m.delete();
}
}
}
}catch (CoreException e) {
e.printStackTrace();
}
}
}
}
As i said, this is kind of a bad solution since the code relies on the String of the error message. There should be better ways to identify the problems you don't want to have.
Don't forget to add a proper extension in your plugin.xml for the ValidationParticipant.

Entity Framework 4 Code First - Virtual properties not updating when changed to null

So I have a model in my domain similar to this:
public class Product
{
public virtual Tag Methodology { get; set; }
}
Then in an webform project I update it like so:
if (!string.IsNullOrWhiteSpace(ddlMethodology.SelectedValue))
product.Methodology = TagRepo.GetTagById(int.Parse(ddlMethodology.SelectedValue));
else
product.Methodology = null;
But this wasn't updating when product.Methodology was previously set to an object and I wanted to change it back to nothing. I.e. the product.Methodology = null; line didn't seem to work as expected.
When I ran it in the debugger I found that sometimes it would work and sometimes it wouldn't. After a small amount of hair pulling, I realised it was due to the proxy type that the entity framework was creating for that property at runtime and it was working when I inspected it in the debugger.
So to fix the issue, I created this hack which works well: (NOTE: now an else if)
if (!string.IsNullOrWhiteSpace(ddlMethodology.SelectedValue))
product.Methodology = TagRepo.GetTagById(int.Parse(ddlMethodology.SelectedValue));
else if (product.Methodology != null)
product.Methodology = null;
So I guess my questions are:
Am I doing something wrong?
Is there another way it can be done remembering to do a hack everytime?
Could it be considered a bug in the entity framework code first CTP?
Cheers,
Charles