When using Spring Retry #Recover method (which works ok) IntelliJ always marking method as unused and suggest to safe delete
#Recover
public void recover(RetryableException e, String param1) {
//recover
}
#Retryable(include = RetryableException.class, maxAttempts = 2)
public void retryable(String param1) {
//execute
throw new RetryableException();
}
Method 'recover(com.gth.common.exceptions.RetryableException, java.lang.String)' is never used
How can it be avoided? how can IntelliJ be aware of the recover method usage?
I don't want IntelliJ to stop warn about Unused declaration, only the false positive warnings
Method declarations looks ok but as you haven't shared any further details, it is mostly because you are not throwing RetryableException from your retryable method.
To invoke recovery after retries, your retry must throw type of exception which you have defined as recover method's argument. Please check about that , if that is not case, please share some more details.
Edit:
Spring's recovery method gets called internally after retry & hence after scanning code, intellij didn't find any reference where your recover is getting called.
This is just warning from intellij & don't pose any issue. You can disable this behaviour from Preferences > Editor > Inspections > Unused Declaration >Java > Unused declaration .
Other option is to use #SuppressWarnings("unused") above your recover.
Related
These "resource leak" warnings I'm getting in Eclipse for AutoCloseables seem to be a life-saver.
However, how do I get them to work for factory created instances?
For example (a works, but b doesn't):
public static void main(String[] args) {
// a) This emits a warning
new AutoCloseable() {
#Override
public void close() throws Exception {}
};
// b) But this doesn't!
newResource();
}
public static AutoCloseable newResource() {
return new AutoCloseable() {
#Override
public void close() throws Exception {}
};
}
Is there an annotation I can stick on newResource() or something I can do to let the compiler (or is it Eclipse?) know of the ownership change?
The Neon Eclipse documentation on "resource leak" detection explains what is going on; see "avoiding resource leaks". It states:
Ownership / responsibility
The above diagnostics basically assume that a method that creates an
instance of a resource type is also responsible for closing this
resource. However, some resources will be shared among several
methods. Here the analysis makes the following assumptions:
If a method returns a resource to its caller, it is not responsible for closing; no problem is reported.
If a resource is stored in a field, no single method is considered as responsible for closing; no problem is reported.
If a method obtains a resource via a method call rather than by a new expression, it may or may not be responsible; any problems are
only flagged as potential resource leaks.
If a resource is passed as an argument in a method call or constructor call, the current method may or may not be responsible;
any problems are only flagged as potential resource leaks.
Point #1 explains why there is no "resource leak" warning for the return statement in the newResource method.
Point #3 explains why there is no "resource leak" warning for the newResource() call. At best, it would be a "potential resource leak" warning. Either you have those warnings disabled, or the previous warning is inhibiting it.
Q: Is there an annotation to tell Eclipse about transfer of resource ownership?
A: The Neon Eclipse documentation doesn't mention any such annotation. (And it does go into detail about the annotations for null checking!)
I am currently implementing a system in which I am using aspectJ to check whether a user is allowed to call a method or not. My methods look something like this:
#Constrained(
mayUsers = {Constrained.Types.ADMIN,
Constrained.Types.SELLER, Constrained.Types.ORGANIZER}
)
public boolean save() {
/* code */
}
I am able to use AspectJ to intercept the message call and do the check, but if the call is not allowed I want to throw an exception. If I just throw the Exception the user of the method is not informed about the Exception which might be thrown.
Now my question is:
Is it possible to enforce that the every method that has the #Constrained Annotation throws a specific Exception?
Is it possible to enforce that the every method that has the
#Constrained Annotation throws a specific Exception?
No it is not possible to do that right now. But what you can do is that at runtime you can check that all the methods that have this annotation must throw exception. If any of method does not declare throws clause, you can throw some Illegal*Exception to tell the developer that each method must declare throws clause.
You have two solutions:
Compile time annotation checking using APT (Annotation Processing Tool)
Runtime checks (pre-conditions)
I hate functions that declare to throw exceptions that are not thrown by this functions in any case. This happens in refactorings if throw statements are removed in the function body without removing it from the throws definitions.
Thats why I activated the setting Java -> Compiler -> Errors/Warnings -> Unnecessary code -> Unnecessary declaration of thrown exception.
This leads to false positive warnings if exceptions are defined in interfaces or super methods. If implementation A of the interface does not throw one exception type, but implementation B does, eclipse warns about the unnecessary declaration in implemantation A. Thats equally for super and overriden methods. Thats why I activate the suboption "Ignore in overriding and implementing methods".
Perfeclty fine till here. But I have the oposite case. The overridden method throws a exception type, that is not used in the super method. See this minimal example:
class Vehicle {
protected int getStatus() throws GeneralException, StatusException {
throw new GeneralException("One exception type in super type only");
}
}
class Car extends Vehicle {
#Override
protected int getStatus() throws GeneralException, StatusException {
throw new StatusException("Special case, that gets special handling");
}
}
Now StatusException in Vehicle is warned in eclipse.
Of course one could argue that this is bad design etc., but from a pragmatic point of view this will happen again and most probably one can accept to not change the architecture, but to simply add the new exception type to the super type. But howto get rid of the false positive warning in this case? Of course one could use the suboption with the javadoc, but this would also ignore most real positive hits. Another option is to add the SuppressWarning annotation "unused", but other users could get unneeded warnings for that suppression.
Personally I'd activate the second option under the warning setting: "Ignore exceptions documented..." and just document those:
/**
* #throws GeneralException when general stuff goes wrong
* #throws StatusException when status stuff goes wrong
*/
protected int getStatus() throws GeneralException, StatusException {
throw new GeneralException("One exception type in super type only");
}
Maybe include a slightly more useful explanation, but it'll basically boild down to this.
I am using Findbugs integerated with eclipse.
When I run findbugs on my project the below code is not captured for possible null pointer exception.
In the below snippet the object test is prone to null pointer exception which is not identified by findbugs.
#Override
public boolean saveIrr(TestObject test) throws DuplicateRecordException {
boolean status = false
try {
test.getAddDate();
status = adhocMaintPopupMapper.saveIrr(IRRPopupMaint);
} catch (DataIntegrityViolationException e) {
logger.error("Error in Saving!", e);
throw new TransactionDataException("Error in Saving!", e);
}
return status;
}
Is there any configuration change required to make findbugs to identify this?
If you add #Nonnull to the parameter declaration, FindBugs will highlight anywhere you're passing a value that isn't checked for null. If you mark it #CheckForNull, FindBugs will highlight anywhere in the method that you access it without checking for null.
Which you do depends on the method's contract: does it tolerate null or not? Looking at its implementation it does not allow for null without throwing an unexpected exception. Therefore, test should be marked #Nonnull so you can spot incorrect calls.
Update
FindBugs will only check fields, parameters, method return values that are annotated with either #Nonnull or #CheckForNull. Anything without an annotation is assumed #Nullable which tells FindBugs to ignore it.
public boolean saveIrr(#Nonnull TestObject test) { ... }
public void dontCareAboutNull(TestObject value) {
saveIrr(value); // no bug
}
public void mightBeNull(#CheckForNull TestObject value) {
saveIrr(value); // bug
}
For this reason, we apply #Nonnull to all three types of values at the package level. Any value that needs to allow null must be annotated with #CheckForNull. We do not allow the use of #Nullable except in very few corner cases (e.g. #Autowired fields which Spring enforces).
I noticed that you're missing a ; in your code after "boolean status = false", this could be the reason why findbug has problems to parse your code.
OK from what I understood : you want to identify that test has not beeing tested for null. As far as I know there is no way to configure findbugs for doing this. Findbugs can warn you in 2 other cases :
- NP_ARGUMENT_MIGHT_BE_NULL : if you call your method saveIrr with a and argument that has not been tested for null before.
- NP_NULL_INSTANCEOF : if findbug identified that your value is guaranteed to be null at a point.
You can check all the Null Pointer warnings here they are identified with NP: http://findbugs.sourceforge.net/bugDescriptions.html
I think that such a warning would result in a too huge amount of bugs detected : all methods with arguments would give warnings for arguments that would be used before beeing tested.
What you can do is use the annotions of findbugs/jsr305. So if you add #Nullable to the getDate() method in TestObject it may trigger a NP warning. If you want to use those annotions be sure that the jsr305.jar is in your classpath...
I am using PMD Plug-in 3.2.6.v2009033006 . But the default rulesets in pmd is not captured possible null pointer exception .
Java Code
public class SignUp extends HttpServlet{
public void doGet(HttpServletRequest req , HttpServletResponse res){
String user = req.getParameter("user");
user.trim();
}
}
user.trim(); if the user variable is null it will be prone to null pointer exception . I checked my code with pmd but it will not indicate this ?
How can i capture this ? . Is there any custom pmd ruleset is available?
Is there any custom rulesets available for capturing this ?
PMD isn't the right tool for this. You should use FindBugs to catch such problems.
But even with FindBugs, you won't catch anything because the above code is perfectly reasonable, and doesn't have any bug, unless you know that getParameter("user") can return null, and that there is something better to do than throwing a NullPointerException in this case.
If such code triggered an error, basically every line of code which calls a method on an object returned by another method would trigger an error. FindBugs supports annotations that allows declaring that the caller of a method should always check for null on the result returned by this method. See http://findbugs.sourceforge.net/manual/annotations.html. But of course, for third-party code, you can't do anything (other than writing your own rules).