How to ignore in Sonar OpenJpa methods pcSet / pcGet? - java

In my application we are using OpenJpa. By decompiling my classes, I can see some methods I haven´t typed, for instance pcGetid:
public long getId()
{
return pcGetid(this);
}
(...)
private static final long pcGetid(...)
My original java file looks like:
public long getId() {
return id;
}
I assume that is some internal OpenJpa procedure. The problem comes when Sonar analyzes my code. Many Unused private method major violations appears, because some of those methods are not used.
Is ther a way to ignore sonar in these cases? I can not use //NOSONAR because in my code those methods does not exist.
It might be usefull to know in which phase of the build process this methods are added, so I can analyze the content before it happens.
Any idea would be appreciated!
Thanks

If you're using SonarQube 4.0, you can use the issue exclusion mechanism to exclude all issues on this "Unused private method" for a set of java files :http://docs.sonarqube.org/display/SONAR/Narrowing+the+Focus#NarrowingtheFocus-patterns

Related

SonarQube giving unused private method issue for lambda usage

I have the following logic;
..
if(list.stream()
.filter(MyClass::isEnabled)
.filter(this::isActive)
.count() > 0) {
//do smth
}
..
private boolean isActive(MyClass obj) {
return bool;
}
As you see, isActive method is being used in the stream structure, but when I build this class on Jenkins, I get the unused private method issue from SonarQube, it says you should delete this redundant private method. Is this a bug? If not, why haven't they still included lambda logic in their analyze structure?
Only solution is, obviously, to do this;
.filter(obj -> isActive(obj)), but it destroys the uniformity, and even the readability (imo).
This is a known issue of SonarQube java analyzer : https://jira.sonarsource.com/browse/SONARJAVA-583
This is due to a lack of semantic analysis to resolve properly method reference (thus identify to which method this::isActive refers to).

Unclear inspection warning "NullableProblems" in IntelliJ

Why am I getting a warning from the "NullableProblems" inspection in IntelliJ on this:
public class Test implements Comparable<Test> {
#Override
public int compareTo(Test o) {
return 0;
}
}
I'm using IntelliJ 14.1.4 and compiling with Java 1.7
Screenshot:
Adding #NotNull before the argument doesn't help:
From Comparable.compareTo:
#throws NullPointerException if the specified object is null
So IntelliJ knows, that the object should not be null and adds a #NotNull annotation automatically:
IntelliJ IDEA will look carefully at SDK and libraries bytecode and will infer these annotations automatically so that they can later be used to analyze source code to spot places where you overlooked null.
Your overriden method doesn't include this annotation, so it overrides this behavior making the parameter nullable - against the contract of the Comparable interface.
You can solve this by adding #NotNull before the parameter.
You can also disable this inspection by pressing Alt + Enter, selecting the warning in the popup menu and selecting Disable inspection in the sub-menu.
Check out the Web Help and this thread for more information about #NotNull / #NonNull annotations.
This can be globally configured in IntelliJ IDEA easily and for me personally is the recommended way. If you want you can add your own annotations.
i.e. javax.validation.constraints.NotNull
Path to the setting:
Settings > Editor > Inspections > #NotNull/#Nullable problems > Configure annotations
Some screenshots:
Its because that you are overriding a method that does not have a #NotNull annotation.
IntelliJ IDEA warns you if the overriding method does not have a #NotNull annotation.

Append type level validation error message to specific field

I've got a simple class which get's validated using the boolean isValid() method, which works and of course the error message is at class/type level.
Here's my simple class:
public class NewPasswordDTO {
#NotNull
public String password;
#NotNull
public String confirmation;
#AssertTrue(message="Passwords must match.")
protected boolean isValid() {
return password.equals(confirmation);
}
}
But what I really want is something like that:
public class NewPasswordDTO {
#NotNull
#Equals("confirmation", message="...")
public String password;
#NotNull
public String confirmation;
}
So the error message would be set at field level and not at class/type level.
Is this possible somehow? Maybe using a custom Validator for that class?
Thanks in advance!
SOLUTION:
Thanks to Gunnar! I've just came up with a nice, universal solution :-). I simply used (means copy & paste) the code from Hibernates #ScriptAssert and ScriptAssertValidator and modified it slightly:
#ScriptAssert:
Add new String field(). (this is where the error message gets appended)
ScriptAssertValidator:
Inside the initialize method, make sure to also save the fieldName and message properties, because we need to access them in the next step
Add this snippet at the bottom of isValid method:
context.buildConstraintViolationWithTemplate(errorMessage)
.addPropertyNode(fieldName).addConstraintViolation();
Also add context.disableDefaultConstraintViolation(); somewhere inside the isValid method to not generate the default error message which else would get appended at class level.
And that's it. Now I can use it like that:
#FieldScriptAssert(lang="javascript", script="_this.password.equals(_this.confirmation)", field="password", message="...")
public class NewPasswordDTO { ... }
You either could use the #ScriptAssert constraint on the class (note that a constraint should always be side-effect free, so it's not a good idea to alter the state of the validated bean; instead you should just check whether the two fieldss match) or you implement a custom class-level constraint.
The latter also allows to point to a custom property path for the constraint violation, which it allows to mark the "confirmation" property as erroneous instead of the complete class.
Simple answer : It is not (unless you implement it) :http://docs.oracle.com/javaee/6/api/javax/validation/constraints/package-summary.html shows all annotation constraints.
Of course you could inject your string as a resource in your class by #producer and so on (which recently is discussed to be removed in jdk8), but you could not use this value for your assert. In reply to the comment:
This was asuming that the nature is a constant string which you would like to use as a string resource.And then of course it is possible to write your own class based on java.lang.string with a #Producer which is then #Inject - able. Though it is certainly not the way I personally would deal with constant strings.
If you’re using the Spring Framework, then as an alternative to the #ScriptAssert using a JSR 223 scripting, you can use the #SpELAssert that uses the Spring Expression Language (SpEL). The advantage is that it doesn’t need any JSR 223 compliant scripting engine which may not be available on some environments. See this answer for more information.

Java - Using Ant to automatically generate boilerplate code

Intro:
I'm asking this before I try, fail and get frustrated as I have 0 experience with Apache Ant. A simple 'yes this will work' may suffice, or if it won't please tell me what will.
Situation:
I'm working on a project that uses JavaFX to create a GUI. JavaFX relies on Java Bean-like objects that require a lot of boilerplate code for it's properties. For example, all functionality I want to have is a String called name with default value "Unnamed", or in a minimal Java syntax:
String name = "Unnamed";
In JavaFX the minimum amount of code increases a lot to give the same functionality (where functionality in this case means to me that I can set and get a certain variable to use in my program):
private StringProperty name = new StringProperty("Unnamed");
public final String getName() { return name.get(); }
public final void setName(String value) { name.set(value); }
Question: Can I use Ant to generate this boilerplate code?
It seems possible to make Ant scripts that function as (Java) preprocessors. For instance by using the regex replace (https://ant.apache.org/manual/Tasks/replaceregexp.html) functions. I'm thinking of lines of code similar to this in my code, which then will be auto-replaced:
<TagToSignifyReplaceableLine> StringProperty person "Unnamed"
Final remark: As I've said before I have never used Ant before, so I want to check with you if 1) this can be done and 2) if this is a good way to do it or if there are better ways.
Thanks!
Yes, possible. You can even implement your own Ant task, that does this job very easily.
Something like so in ant:
<taskdef name="codegen" classpath="bin/" classname="com.example.CodeGen" />
and then
<codegen className="Test.java">
<Property name="StringProperty.name" value="Unnamed"/>
</codegen>
The CodeGen.java then like so:
public class CodeGen extends Task {
private String className = null;
private List properties = new ArrayList();
public void setClassName(String className) {
this.className = className;
}
/**
* Called by ant for every <property> tag of the task.
*
* #param property The property.
*/
public void addConfiguredProperty(Property property) {
properties.add(property);
}
public void execute() throws BuildException {
// here we go!
}
}
I know it can be done because my previous firm used ant to generate model objects in java.
The approach they used was to define model objects in an XML file and run an ant task to generate the pojo and dto.
I quickly googled and saw that there are tools that allow you to generate java from XML. You could probably give your schema/default values etc in XML and have an nt task to run the tool.
I would look at JSR-269 specifically: genftw which makes JSR-269 easier...
And yes it will work with Ant with out even having to write a plugin and will work better than a brittle RegEx.
The other option if your really adventurous is to check out XText for code generation but it is rather complicated.
Yes, it can be done :-)
I once wrote a webservices adapter that used a WSDL document (XML file describing a SOAP based webservice) to generate the POJO Java class that implemented the functional interface to my product. What lead me to do this was the mindlessly repetitive Java code which was necessary to talk to our proprietary system.
The technical solution used an XSLT stylesheet to transform the input XML document into an output Java text file which was subsequently compiled by ANT.
<!-- Generate the implementation classes -->
<xslt force="true" style="${resources.dir}/javaServiceStub.xsl" in="${src.dir}/DemoService.wsdl" out="${build.dir}/DemoService/src/com/myspotontheweb/DemoServiceSkeleton.java" classpathref="project.path">
<param name="package" expression="com.myspotontheweb"/>
..
..
</xslt>
Unfortunately XSLT is the closest thing to a templating engine supported by native ANT.
Best of luck!

Unnecessary #SuppressWarnings("unused")

I'm getting a compiler warning for the #SuppressWarnings annotation in eclipse for the code:
#Override
public boolean doSomething(#SuppressWarnings("unused") String whatever) throws AnException {
throw new AnException("I'm still in bed and can't do anything until I've had a shower!");
}
It looks like a yellow squiggle under the word "unused" and on mouse hover I get the tooltip Unnecessary #SuppressWarnings("unused").
I think another developer is being prompted to put in these annotations by eclipse and I'm basically being prompted to take them out. How can I configure eclipse to prompt me to put the #SuppressWarnings annotation in instead of it complaining about it?
If anyone would like to comment on best practice here then that would also be most welcome.
In the code in your question, the #SuppressWarnings("unused") annotation is unnecessary because the method is either overriding another method from a superclass or implementing an interface. Even if you don't actually use the whatever parameter it's mandatory to declare it, otherwise the #Override annotation will produce an error (you'd be changing the signature of the overridden method if you removed the parameter.)
In some older versions of Eclipse the code as shown would not cause a warning, but in more recent releases it does. I believe it's a valid warning, and I'd rather remove the #SuppressWarnings("unused") in this case.
Go to
Window → Preferences → Java → Compiler → Errors/Warnings → Annotations.
And select Ignore for Unused '#SuppressWarnings` token.
Alternatively, if you think it's more correct to delete the SuppressWarnings annotation:
Window -> Preferences -> Java -> Compiler -> Errors/Warnings -> Unnecessary code -> Value of parameter is not used
and select Ignore in overriding and implementing methods
In my code there's no inheritance defining the 3 methods with #SuppressWarnings("unused")
This code gives 'Unnecessary #SuppressWarnings("unused")' in Eclipse Juno (latest version), but if I remove the #SuppressWarnings("unused"), I get "Constructor/Method is never used" warnings in IntelliJ IDEA 11.1.3
The methods aren't directly used in the project, only by 3rd party products Jackson, JAXB & GSON, so IntelliJ is right, I would say ...
public class EmailUnsendable extends SkjemaError {
private NestedCommand command; // Can't be Command (interface) because of GSON!
#SuppressWarnings("unused") // Used by Jackson/JAXB/GSON
public EmailUnsendable() {
}
public EmailUnsendable(String referenceNumber, String stackTrace, NestedCommand command) {
super(referenceNumber, stackTrace);
this.command = command;
}
#SuppressWarnings("unused") // Used by Jackson/JAXB/GSON
public NestedCommand getCommand() {
return command;
}
#SuppressWarnings("unused") // Used by Jackson/JAXB/GSON
public void setCommand(NestedCommand command) {
this.command = command;
}
}
I believe this is an error in Eclipse.

Categories

Resources