I have this piece of code and PMD reports two rule violations:
AbstractExceptionHandler has no constructor (AtLeastOneConstructor)
And the field uriInfo is a unused private field (UnusedPrivateField)
#NoArgsConstructor
public class AbstractExceptionHandler { // PMD AtLeastOneConstructor warning here
/** the uriInfo injection. */
#Getter
#Context
private UriInfo uriInfo; // PMD UnusedPrivateField warning here
both warnings are okay, but we use annotations to generate code. So the warning is useless for us.
We have created following suppressions:
AtLeastOneConstructor
<rule ref="rulesets/java/controversial.xml/AtLeastOneConstructor">
<properties>
<property name="violationSuppressXPath"
value="//ClassOrInterfaceDeclaration[//ImportDeclaration//Name[#Image='lombok.NoArgsConstructor'] | //TypeDeclaration//MarkerAnnotation//Name[#Image='NoArgsConstructor']]" />
</properties>
</rule>
UnusedPrivateField
<rule ref="rulesets/java/unusedcode.xml/UnusedPrivateField">
<properties>
<property name="violationSuppressXPath"
value="//ClassOrInterfaceBodyDeclaration//FieldDeclaration[//TypeDeclaration//MarkerAnnotation//Name[#Image='Getter'] | //TypeDeclaration//MarkerAnnotation//Name[#Image='Setter']]"/>
</properties>
</rule>
And the PMD xpath Designer tells us it is the exact used lines with the violation, but still PMD reports a error.
Can someone help me out of the dark?
Related
I'm specifying skipAnnotations with value true for the default PMD strings.xml ruleset:
<rule ref="rulesets/java/strings.xml">
<properties>
<property name="skipAnnotations" value="true"/>
</properties>
</rule>
It is ignored in a simple case like
public class NewMain {
#SuppressWarnings("PMD.UnusedFormalParameter")
private void method1(Object arg1) {
System.out.println("method1");
}
#SuppressWarnings("PMD.UnusedFormalParameter")
private void method2(Object arg1) {
System.out.println("method2");
}
#SuppressWarnings("PMD.UnusedFormalParameter")
private void method3(Object arg1) {
System.out.println("method3");
}
#SuppressWarnings("PMD.UnusedFormalParameter")
private void method4(Object arg1) {
System.out.println("method4");
}
}
i.e. mvn validate fails due to Failed to execute goal org.apache.maven.plugins:maven-pmd-plugin:3.8:check (pmd-check) on project pmd-skip-annotations-demo: You have 1 PMD violation. [...].
A MCVE is at https://github.com/krichter722/pmd-skip-annotations-demo.
I'm using maven-pmd-plugin 3.8.
The property corresponds to a given rule, not to the whole ruleset. Therefore, your configuration is invalid, you should write:
<rule ref="rulesets/java/strings.xml/AvoidDuplicateLiterals">
<properties>
<property name="skipAnnotations" value="true"/>
</properties>
</rule>
To include the whole strings ruleset, but have this property, you should write
<rule ref="rulesets/java/strings.xml">
<exclude name="AvoidDuplicateLiterals"/>
</rule>
<rule ref="rulesets/java/strings.xml/AvoidDuplicateLiterals">
<properties>
<property name="skipAnnotations" value="true"/>
</properties>
</rule>
I want to make a filterable list of my UserTask entity with the QueryDslPredicateExecutor interface, so the parameters given in the query string will be autoprocessed into a Predicate.
I have the following classes/interfaces
public interface UserTaskQuerydslRepository extends CrudRepository<UserTask, String>,
QueryDslPredicateExecutor<UserTask>, QuerydslBinderCustomizer<QUserTask> {
#Override
default void customize(QuerydslBindings bindings, QUserTask userTask) {
...
}
}
UserTask is my class that represents the (couchbase) model
#QueryEntity
#Document(expiry = 0)
public class UserTask {
#Id
private String id;
...
}
If i annotate this class with #QueryEntity then Maven generates the QUserTask class for me
#Generated("com.mysema.query.codegen.EntitySerializer")
public class QUserTask extends EntityPathBase<UserTask> {
private static final long serialVersionUID = 493434469L;
public static final QUserTask userTask = new QUserTask("userTask");
public final StringPath id = createString("id");
...
public QUserTask(String variable) {
super(UserTask.class, forVariable(variable));
}
public QUserTask(Path<? extends UserTask> path) {
super(path.getType(), path.getMetadata());
}
public QUserTask(PathMetadata<?> metadata) {
super(UserTask.class, metadata);
}
}
To generate QUserTask i added the following lines to pom.xml
<plugin>
<groupId>com.mysema.maven</groupId>
<artifactId>apt-maven-plugin</artifactId>
<version>1.1.3</version>
<executions>
<execution>
<goals>
<goal>process</goal>
</goals>
<configuration>
<outputDirectory>target/generated-sources/apt</outputDirectory>
<processor>com.mysema.query.apt.jpa.JPAAnnotationProcessor</processor>
<processor>com.mysema.query.apt.QuerydslAnnotationProcessor</processor>
</configuration>
</execution>
</executions>
<dependencies>
<dependency>
<groupId>com.mysema.querydsl</groupId>
<artifactId>querydsl-apt</artifactId>
<version>3.4.3</version>
</dependency>
</dependencies>
</plugin>
In the project we have both JPA entities and couchbase entities, that's why i have the JPAAnnotationProcessor there.
If i run the application like this i get the following error:
org.springframework.data.mapping.PropertyReferenceException: No
property findAll found for type UserTask!
I tried to annotate my UserTaskQuerydslRepository with #NoRepositoryBean, it solved my findAll problem, but when i tries to #Inject this repository to a Resource (or controller, JHipster calls it Resource) i get the following error
No qualifying bean of type [.UserTaskQuerydslRepository]
found for dependency: expected at least 1 bean which qualifies as
autowire candidate for this dependency. Dependency annotations:
{#javax.inject.Inject()}
Can anyone help me what did I do wrong?
As #mp911de said in his comment, Spring Data Couchbase doesn't have support for QueryDsl, which explains why the bean cannot be created.
I can see where your confusion comes from when reading the doc. Chapter 5 is the content common to all Spring Data store implementations. All store documentations have one chapter with that same content, which generically talk about the repository basics. So it can mention things that are not in a particular implementation.
The first sentence of the section you linked even hints at it:
Several Spring Data modules offer integration with Querydsl via QueryDslPredicateExecutor.
Several, but not the Spring Data Couchbase module unfortunately.
2016. 07. 11. : After some research, and according to answers by #mp911de, and #simon-baslé we know that Spring Data Couchbase doesn't have support for QueryDsl yet.
I found a workaround for the problem that i wanted to solve (dynamic querying, aka. filters on a list and make it pageable)
https://github.com/TeamWanari/couchbase-query-executor
We're using Spring 3.2.11.RELEASE and Maven 3.0.3. I'm trying to set up validation of a parameter being passed into a service method. The method is below. Notice the #Valid annotation.
package org.mainco.subco.mypck.service;
#Service
#RemoteProxy
#Transactional
public class MypckServiceImpl implements MypckService {
#RemoteMethod
#Override
public String myMethod(#Valid final MyObjectDto request) {
// ...
}
}
Here is the aspect I have set up to help validate the object:
#Aspect
#Component
public class MyObjectValidatingAspect extends AbstractDWRAspectValidator<MyObjectDto>
{
#Before("execution(* org.mainco.subco.mypck.service.MypckService.myMethod(..))")
public void validateBefore(JoinPoint jp)
{
errors = new ArrayList<String>();
final MyObjectDto request = validate(jp);
validateMyObject(request);
throwErrors();
} // validateBefore
This is in included in my application context file:
<global-method-security pre-post-annotations="enabled">
</global-method-security>
<aop:aspectj-autoproxy/>
And this is what I've included in the Maven pom.xml file:
<dependency>
<groupId>org.aspectj</groupId>
<artifactId>aspectjweaver</artifactId>
<version>1.8.2</version>
</dependency>
<dependency>
<groupId>org.aspectj</groupId>
<artifactId>aspectjrt</artifactId>
<version>1.8.2</version>
</dependency>
Unfortunately when the method is invoked, the aspectj's validateBefore is never called. What else do I need to do so that this gets invoked?
Since Spring 3.1 there is the MethodValidationInterceptor which basically does what you want to achieve yourself. To have this interceptor applied the only thing you need to do is to register a MethodValidationPostProcessor in your application context.
By default it will check for the #Validated annotation from Spring but you can instruct it to scan for the #Valid annotation.
<bean class="org.springframework.validation.beanvalidation.MethodValidationPostProcessor">
<property name="validatedAnnotationType" value="javax.validation.Valid" />
<property name="validator" ref="refToYOurLocalValidatorFactoryBean" />
</bean>
If you don't specify a validator the default JSR-303 validator mechanism will be used (or the more hibernate specific one if that is available). But I can imagine you want to reuse the already configured instance.
I am trying to use the globalBindings element to add serializable + a default UID to my WSDL stub classes so I can get rid of a bunch of annoying warnings from Eclipse.
I am trying to follow the suggestions in this answer, but no luck. Still get all the warnings in Eclipse.
Am I missing something in the pom file perhaps?
I am OK with upgrading to a newer version of the jaxws plugin, or even moving to a different plugin, if required.
Here's my bindings file:
<bindings xmlns="http://java.sun.com/xml/ns/jaxb" xmlns:xsi="http://www.w3.org/2000/10/XMLSchema-instance"
xmlns:xs="http://www.w3.org/2001/XMLSchema" version="2.1"
xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:xjc="http://java.sun.com/xml/ns/jaxb/xjc">
<globalBindings>
<xjc:serializable uid="1" />
</globalBindings>
<bindings
schemaLocation="../resources/com/satorisoftware/ws/infuseiac/intladdresscorrection/intladdresscorrection.wsdl#types?schema3"
version="1.0">
<schemaBindings>
<package name="com.satorisoftware.ws.infuseiac-intladdresscorrection" />
</schemaBindings>
<!-- Tell JAXB to generate Java class specifically named CorrectRequestElement
for this element, to avoid the name clash that automatic naming causes. -->
<bindings node="//xsd:element[#name='CorrectRequest']">
<class name="CorrectRequestElement" />
</bindings>
</bindings>
</bindings>
And here's the relevant part of my pom.xml file:
<plugin>
<groupId>org.codehaus.mojo</groupId>
<artifactId>jaxws-maven-plugin</artifactId>
<version>1.12</version>
<executions>
<execution>
<id>import-iac-wsdl</id>
<phase>generate-sources</phase>
<goals>
<goal>wsimport</goal>
</goals>
<inherited>false</inherited>
<configuration>
<packageName>com.satorisoftware.ws.infuseiac.intladdresscorrection</packageName>
<wsdlLocation>com/satorisoftware/ws/infuseiac/intladdresscorrection/intladdresscorrection.wsdl</wsdlLocation>
<staleFile>${project.build.directory}/jaxws/stale/wsdl.intladdresscorrection.done</staleFile>
<sourceDestDir>${project.build.directory}/generated/jaxws-infuseiac-intladdresscorrection</sourceDestDir>
<wsdlDirectory>src/main/resources/com/satorisoftware/ws/infuseiac/intladdresscorrection</wsdlDirectory>
<bindingFiles>
<!-- See http://www.jroller.com/gmazza/entry/enhancing_jaxb_artifacts#BindingFile
for an end-to-end-example of doing bindings files for WSDL files. -->
<bindingFile>${basedir}/src/main/bindings/bindings-intladdresscorrection.xjb</bindingFile>
</bindingFiles>
<!-- <wsdlUrls> <value>https://infuseiac.satorisoftware.com/wsdl/IntlAddressCorrection.2012.12.wsdl</value>
</wsdlUrls> -->
<!-- Generate JAX-WS 2.0 compatible stubs -->
<target>2.0</target>
</configuration>
</execution>
</executions>
</plugin>
Here's an example of a generated class without the UID
package com.satorisoftware.ws.infuseiac.intladdresscorrection;
import javax.xml.ws.WebFault;
/**
* This class was generated by the JAX-WS RI.
* JAX-WS RI 2.1.7-b01-
* Generated source version: 2.0
*
*/
#WebFault(name = "DuplicateFieldFaultContract", targetNamespace = "infuse.satorisoftware.com/2012/08")
public class IntlAddressCorrectionCorrectDuplicateFieldFaultContractOfInfuseSingleFieldFaultFaultMessage
extends Exception
{
/**
* Java type that goes as soapenv:Fault detail element.
*
*/
private DuplicateFieldFaultContract faultInfo;
/**
*
* #param message
* #param faultInfo
*/
public IntlAddressCorrectionCorrectDuplicateFieldFaultContractOfInfuseSingleFieldFaultFaultMessage(String message, DuplicateFieldFaultContract faultInfo) {
super(message);
this.faultInfo = faultInfo;
}
/**
*
* #param message
* #param faultInfo
* #param cause
*/
public IntlAddressCorrectionCorrectDuplicateFieldFaultContractOfInfuseSingleFieldFaultFaultMessage(String message, DuplicateFieldFaultContract faultInfo, Throwable cause) {
super(message, cause);
this.faultInfo = faultInfo;
}
/**
*
* #return
* returns fault bean: com.satorisoftware.ws.infuseiac.intladdresscorrection.DuplicateFieldFaultContract
*/
public DuplicateFieldFaultContract getFaultInfo() {
return faultInfo;
}
}
Here's a little bit of the WSDL as requested:
<xsd:complexType name="DuplicateFieldFaultContract">
<xsd:annotation>
<xsd:appinfo>
<GenericType xmlns="http://schemas.microsoft.com/2003/10/Serialization/"
Name="DuplicateFieldFaultContract" Namespace="infuse.satorisoftware.com/2012/08">
<GenericParameter Name="InfuseField"
Namespace="http://schemas.datacontract.org/2004/07/Satori.Infuse.Single" />
</GenericType>
</xsd:appinfo>
</xsd:annotation>
<xsd:complexContent mixed="false">
<xsd:extension base="tns:InfuseFaultContract">
<xsd:sequence>
<xsd:element
xmlns:q4="http://schemas.datacontract.org/2004/07/Satori.Infuse.Single"
name="DuplicateFields" nillable="true" type="q4:ArrayOfInfuseField" />
</xsd:sequence>
</xsd:extension>
</xsd:complexContent>
</xsd:complexType>
<xsd:element name="DuplicateFieldFaultContract" nillable="true"
type="tns:DuplicateFieldFaultContract" />
Anders
This is what i understood from the post for WSimport
By default JAXB generated code isn't serializable
We need to add a mechanism to generate a UID which for POjos
It will not create serialVersionUID for Exception classes
wsdl2java, by default the generated exception class will have a serialVersionUID
please try wsdl2java , hope this will solve your issue
Andres
are you not seeing this
private static final long serialVersionUID="1L" ?
Every class generated will be serializable and have the specified uid: a limitation of this process is that each of your generated class will have the same uid.
I'm creating a RESTful API that returns JSON or XML depending on the Accept header (application/json vs text/xml). I have this working fine for JSON but can't seem to get it working when for XML. I am testing using the Poster plugin client for Firefox.
I was under the impression that I just needed to add the Jackson and JAXB libraries to the app's classpath. Again, it works for JSON but not XML.
Originally I was getting 406 error when sending the Accept "text/xml" header. Then I added #XmlRootElement(name="contact") to my entity and now I'm getting a 500 error. Should I need to put #XmlRootElement on every entity?
Although the response is a 500 error, I don't see any errors reported in the console. I'm testing in Eclipse running Tomcat 7. Shouldn't i see some error in the console when i receive a 500 error?
My "mvc-dispatcher-servlet.xml" has <mvc:annotation-driven />
Here's the relevant code from my controller:
#Controller
#RequestMapping("/contacts")
public class ContactsController {
#Autowired
ContactsService contactsService;
#RequestMapping(value="/{id}",
method=RequestMethod.GET,
headers = {"Accept=application/json, text/xml"})
public #ResponseBody Contact getContact(#PathVariable("id") int id) {
Contact queryContact = new Contact(id);
Contact result = contactsService.getContact(queryContact);
return result;
}
}
The "mvc-dispatcher-servlet.xml" is really simple. Do I need anything other than:
<context:component-scan base-package="contactsapp.web.controller" />
<mvc:annotation-driven />
<mvc:resources mapping="/resources/**" location="/resources/"/>
I'm using Spring 3.1 and the following:
<dependency org="com.sun.xml.bind" name="jaxb-impl" rev="2.2.5-b10" conf="runtime->default"/>
<dependency org="org.codehaus.jackson" name="jackson-mapper-asl" rev="1.7.1" conf="runtime->default"/>
You should put
#XmlRootElement on Contact class to tell jackson how to parse.
It turns out I had it configured correctly. Once I enabled more verbose logging I realized I had circular dependencies in my entity classes and had to add #XmlTransient on those fields