NoSuchMethodException QueryDSL with Spring Boot & Spring Data Mongo - spring-boot

I am trying to implement Query DSL on my Spring Boot 2.0.4.RELEASE app that uses Spring Data Mongo 2.0.4.RELEASE & Gradle 4.10.
I am using Spring Tool Suite for running it locally.
Did the following steps which I found from multiple sources including Spring data documentation:
created gradle/querydsl.gradle which has below content to generate Q classes
apply plugin: "com.ewerk.gradle.plugins.querydsl"
sourceSets {
main {
java {
srcDir "$buildDir/generated/source/apt/main"
}
}
}
querydsl {
springDataMongo = true
querydslSourcesDir = "$buildDir/generated/source/apt/main"
}
dependencies {
compile "com.querydsl:querydsl-mongodb:4.1.4"
compileOnly "com.querydsl:querydsl-apt:4.1.4"
}
sourceSets.main.java.srcDirs = ['src/main/java']
Calling above gradle file from main build.gradle as shown below
buildscript {
ext { springBootVersion = "2.0.4.RELEASE" }
repositories { mavenCentral() }
dependencies {
classpath "org.springframework.boot:spring-boot-gradle-plugin:${springBootVersion}"
classpath "gradle.plugin.com.ewerk.gradle.plugins:querydsl-plugin:1.0.9"
}
}
plugins {
id "java"
id "eclipse"
id "org.springframework.boot" version "2.0.4.RELEASE"
id "io.spring.dependency-management" version "1.0.6.RELEASE"
}
sourceCompatibility = 1.8
repositories { mavenCentral() }
dependencies {
...
compile("org.springframework.boot:spring-boot-starter-web:${springBootVersion}")
compile("org.springframework.boot:spring-boot-starter-data-mongodb:${springBootVersion}")
...
}
apply from: 'gradle/querydsl.gradle'
/* Added this because Eclipse was not able to find generated classes */
sourceSets.main.java.srcDirs = ['build/generated/source/apt/main','src/main/java']
compileJava.dependsOn processResources
processResources.dependsOn cleanResources
After this updated the Repository annotated interface as below. Note: I also use Fragment Repository FragmentOrderRepository for some custom queries.
public interface OrderRepository<D extends OrderDAO>
extends EntityRepository<D>, PagingAndSortingRepository<D, String>, FragmentOrderRepository<D>, QuerydslPredicateExecutor<D> {}
Then in controller created a GET mapping as shown here
#RestController
public class OrderController {
#GetMapping(value="/orders/dsl", produces = { "application/json" })
public ResponseEntity<List> getOrdersDSL(#QuerydslPredicate(root = OrderDAO.class) Predicate predicate, Pageable pageable, #RequestParam final MultiValueMap<String, String> parameters) {
return (ResponseEntity<List>) orderService.getTools().getRepository().findAll(predicate, pageable);
}
}
Then in my runner class I added EnableSpringDataWebSupport annotation
#SpringBootApplication
#EnableSpringDataWebSupport
public class SampleApp {
public static void main(String[] args) {
SpringApplication.run(SampleApp.class, args);
}
}
With this my app starts up without any errors but when I try hitting the path http://localhost:5057/orders/dsl?email=test#test.com
I get a NoSuchMethodException with message No primary or default constructor found for interface com.querydsl.core.types.Predicate.
Can anyone please help with some pointers to solve this issue?
It seems that parameters are not getting resolved to a type.
---- UPDATE 09/19/19 ----
While debugging I found that a class HandlerMethodArgumentResolverComposite which finds ArgumentResolver for given MethodParameter from a List of argumentResolvers(of type HandlerMethodArgumentResolver). This list does not contain QuerydslPredicateArgumentResolver. Hence it is not able to resolve the arguments.
This means QuerydslWebConfiguration which adds above resolver for Predicate type is not getting called, which in turn indicates that some AutoConfiguration is not happening.
Probably I am missing some annotation here.

Found the mistake I was doing, was missing EnableWebMvc annotation on my Configuration annotated class.
Details are in this documentation.

Related

Can't call AppEngine Image API getServingUrl method when using SpringBoot stack

Our project needs to serve scaled images. AppEngine ImageApi has a wonderful method called getServingUrl. But this API is only accessible from AppEngine.
Problem
I've created a PoC project with SpringBoot and gradle for AppEngine. And whenever I call a simple endpoint that should call getServingUrl I get the following error:
Can’t make API call blobstore.CreateEncodedGoogleStorageKey in a thread that is neither the original request thread nor a thread created by ThreadManage
But when I do a similar setup that is based on Servlets, it works as expected.
SpringBoot Setup
Here is an example of some files from my setup.
build.gradle:
;; https://github.com/GoogleCloudPlatform/app-gradle-plugin
buildscript {
repositories {
mavenCentral()
}
dependencies {
classpath 'com.google.cloud.tools:appengine-gradle-plugin:2.2.0'
}
}
plugins {
id 'org.springframework.boot' version '2.2.6.RELEASE'
id 'io.spring.dependency-management' version '1.0.9.RELEASE'
id 'java'
}
group = 'com.example'
version = '0.0.1-SNAPSHOT'
sourceCompatibility = '11'
apply plugin: 'com.google.cloud.tools.appengine' // App Engine tasks
repositories {
mavenCentral()
}
dependencies {
implementation 'org.springframework.boot:spring-boot-starter-web'
implementation "com.google.appengine:appengine-api-1.0-sdk:2.0.4"
testImplementation('org.springframework.boot:spring-boot-starter-test') {
exclude group: 'org.junit.vintage', module: 'junit-vintage-engine'
}
}
test {
useJUnitPlatform()
}
appengine { // App Engine tasks configuration
deploy { // deploy configuration
projectId = 'GCLOUD_CONFIG' // delegate to project in gcloud config
version = 'GCLOUD_CONFIG' // delegate to gcloud to generate a version
}
}
appengine/app.yml
runtime: java11
Controller
package com.example.demo.controller;
import com.google.appengine.api.images.ImagesServiceFactory;
import com.google.appengine.api.images.ServingUrlOptions;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
#RestController
public class ImageController {
#RequestMapping("/image-url")
public ImageUrlDto hello(#RequestParam String bucket, #RequestParam String image) {
ServingUrlOptions options = ServingUrlOptions.Builder
.withGoogleStorageFileName(String.format("/gs/%s/%s", bucket, image));
return new ImageUrlDto(ImagesServiceFactory.getImagesService().getServingUrl(options));
}
}
class ImageUrlDto {
String url;
public ImageUrlDto(String url) {
this.url = url;
}
}
Question
Servlet setup is working correctly, but spring setup no. I've read that Image API is accessible only within AppEngine standart environemnt and request thread/ThreadManager spawned thread.
Am I missing something for that Spring setup? Probably that requires some another form of deployment or thread configuration in order to work with Image API?

springboot thin jar, causing problems with injection

#Slf4j
#RestController
#RequestMapping("/admin/app")
public class AppSessionController {
private OnlineSessionService onlineSessionService;
#Autowired
public void setOnlineSessionService(OnlineSessionServiceImpl onlineSessionService) {
log.info("AppSessionController{}",this);
log.info("inject{}",onlineSessionService);
this.onlineSessionService = onlineSessionService;
log.info("after inject{}",this.onlineSessionService);
}
#PreAuthorize("hasAuthority('app:user:getOnlineUserList')")
#PostMapping("/getOnlineUserList")
Result<PageInfo<AuthData<?>>> getOnlineUserList(#RequestBody PageRequest pageRequest) {
log.info("AppSessionController{}, {}",this, this.ss);
log.info("this.onlineSessionService :"+this.onlineSessionService);
log.info("onlineSessionService :"+onlineSessionService);
PageInfo<AuthData<?>> pageInfo = onlineSessionService.getOnlineUserList(pageRequest.getPageNum(), pageRequest.getPageSize());
PageInfoFixUtil.fixPageInfo(pageInfo);
return Result.ok(pageInfo);
}
}
The output:
INFO main (AppSessionController.java:32) - AppSessionControllercom.apex.app.admin.controller.AppSessionController#5a438c0a
INFO main (AppSessionController.java:33) - inject com.apex.app.common.service.impl.OnlineSessionServiceImpl#14cd8dfa
INFO main (AppSessionController.java:36) - after inject com.apex.app.common.service.impl.OnlineSessionServiceImpl#14cd8dfa
INFO http-nio-8100-exec-5 (AppSessionController.java:48) - AppSessionControllercom.apex.app.admin.controller.AppSessionController#5a438c0a, null
INFO http-nio-8100-exec-5 (AppSessionController.java:49) - this.onlineSessionService :null
INFO http-nio-8100-exec-5 (AppSessionController.java:50) - onlineSessionService :null
The code with the problem is as above, why the onlineSessionService is null after the jar is thinned, and other controllers in the same level directory do not have this problem.
If I change the onlineSessionService to static then the injection can be injected.
gradle thin jar method:
// Copy the dependencies to the lib directory
task copyJar(type: Copy) {
// delete lib directory
delete "$buildDir\\libs\\lib"
from configurations.runtimeClasspath
into "$buildDir\\libs\\lib"
from configurations.compileClasspath
into "$buildDir\\libs\\lib"
}
task copyConfigFile(type: Copy) {
delete "$buildDir\\libs\\config"
from('src/main/resources')
into 'build/libs/config'
}
// copy configuration file
bootJar {
//archiveBaseName = 'application'
enabled = true
archiveVersion = '1.0.0'
// exclude all jars
excludes = ["*.jar"]
dependsOn copyJar
dependsOn copyConfigFile
manifest {
attributes "Manifest-Version": 1.0,
'Class-Path': configurations.runtimeClasspath.files.collect { "lib/$it.name" }.join(' ')
}
}
You should inject OnlineSessionService in constructor or by #Autowired as field rather than inject in method:
public AppSessionController(OnlineSessionService onlineSessionService){
this.onlineSessionService = onlineSessionService;
}
//Or like this
#Autowired
private OnlineSessionService onlineSessionService;
And I think the gradle config is wired, maybe use org.springframework.boot plugin to generate jar file is better than your tasks, please reference https://start.spring.io/ for more detail.

Spring boot executable jar can not resolve freemarker template

I am learning web application building with spring boot and java. I've got my app working when I run it through Spring Tool Suite but after I build executable jar using bootRepackage and run it, It's not able to resolve the freemarker views.
I am not sure what's wrong. Any help would be appreciated.
Following is my application.properties related to freemarker,
spring.http.encoding.charset=UTF-8
spring.freemarker.cache=false
spring.freemarker.charset=utf-8
spring.freemarker.check-template-location=true
spring.freemarker.content-type=text/html
spring.freemarker.enabled=true
spring.freemarker.suffix=.html
spring.freemarker.template-loader-path=classpath:/templates/,classpath:/templates/web/
My jar structure,
BOOT-INF
classes
com
scss
static
templates
web
story.html
app
application.properties
log4j2.xml
META-INF
org
my controller,
#Controller
public class HomeController {
#Autowired
private AppLog appLogger;
#RequestMapping("/")
public ModelAndView Index(HttpServletRequest request) {
appLogger.log(Level.ERROR,AppLogSource.Web, "Reached Controller", null);
String testAttribute = request.getAttribute("com.demo.test").toString();
Map<String, String> vm = new HashMap<String, String>();
vm.put("testAttribute", testAttribute);
return new ModelAndView("/web/story", vm);
}
}
I verified that I am hitting the log step so I think issue is in resolving the view but I could be wrong and missing something else. So let me know if you need more info.
Thanks again!
Best,
Mrunal
edit
Gradle File,
buildscript {
ext {
springBootVersion = '1.4.1.RELEASE'
}
repositories {
mavenCentral()
maven {
url "https://plugins.gradle.org/m2/"
}
}
dependencies {
classpath("org.springframework.boot:spring-boot-gradle-plugin:${springBootVersion}")
classpath("com.moowork.gradle:gradle-node-plugin:1.2.0")
}
}
apply plugin: 'java'
apply plugin: 'eclipse'
apply plugin: 'spring-boot'
apply plugin: 'com.moowork.node'
apply plugin: 'com.moowork.grunt'
jar {
baseName = 'testDemo'
version = '0.0.1'
}
sourceCompatibility = 1.8
targetCompatibility = 1.8
repositories {
mavenCentral()
}
node {
version = '6.11.3'
npmVersion = '3.10.10'
download = true
}
task gruntMinifyJs(type: GruntTask){
args=['minifyJs', '--debug']
}
task gruntMinifyCss(type: GruntTask){
args=['minifyCss', '--debug']
}
task buildFrontEnd(type: GruntTask) {
args = ['default', '--debug']
}
npmInstall.dependsOn(nodeSetup)
buildFrontEnd.dependsOn(npmInstall)
gruntMinifyCss.dependsOn(npmInstall)
gruntMinifyJs.dependsOn(npmInstall)
build.dependsOn(buildFrontEnd)
configurations {
all*.exclude group: 'ch.qos.logback', module:'logback-classic'
all*.exclude group: 'ch.qos.logback', module:'logback-core'
}
dependencies {
compile('org.springframework.boot:spring-boot-devtools')
compile('org.springframework.boot:spring-boot-starter-freemarker')
compile('org.springframework.boot:spring-boot-starter-security')
compile('org.springframework.boot:spring-boot-starter-web')
compile('org.springframework.boot:spring-boot-starter:1.4.1.RELEASE'){
exclude group:'org.springframework.boot', module:'spring-boot-starter-logging'
}
compile('org.springframework.boot:spring-boot-starter-jdbc'){
exclude group:'org.apache.tomcat', module:'tomcat-jdbc'
}
compile('mysql:mysql-connector-java')
compile('com.zaxxer:HikariCP-java6:2.3.13')
compile('org.springframework.boot:spring-boot-starter-log4j2:1.4.1.RELEASE')
compile('com.fasterxml.jackson.datatype:jackson-datatype-jsr310:2.8.8')
compile('com.google.zxing:core:3.3.0')
compile('org.antlr:antlr4-runtime:4.5')
testCompile('org.springframework.boot:spring-boot-starter-test')
}
edit 3,
further updates,
So I attached remote debugger and I found that spring is using ContentNegotiatingViewResolver to resolve the view as InternalResourceView but when I execute through spring tool suite it resolves properly to FreemarkerView.
I hope this helps someone to narrow down my issue. I'll see if I can get anywhere else in mean time by stepping through debugger.
Perhaps the freemarker jar file is not specified as a dependency in your spring boot application module. Unsure if you are running maven or gradle but do make sure you have the freemarker library included in your build.
See downloads # https://mvnrepository.com/artifact/org.freemarker/freemarker

Spock test fails when using JPA Composite Key on Groovy/Gradle build

I developed a Spring Boot WebApplication that receives a soap request with some data and save it to database.
As I am a kind of beginner on Spring Boot and JPA, I used a commonly found configuration for JPA where the primary key is an Id managed by JPA.
#Table(
name="MyEntity",
uniqueConstraints=#UniqueConstraint(columnNames=["channel", "service"])
)
public class MyEntity {
#Id
#GeneratedValue(strategy=GenerationType.AUTO)
Long id
String channel
String service
I developed a set of Spock test about saving, searching and modifying entity and everything runs smoothly.
Specifically I have a Spring Boot application smoke test to be sure that configuration load correctly
#ContextConfiguration
#SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT)
class ApplicationContextSpec extends Specification {
#Autowired
WebApplicationContext context
def "should boot up without errors"() {
expect: "(web) application context exists"
context != null
}
}
As the natural key is channel and service, I tried to define a composite key
#Table(name="MyEntity")
#IdClass(MyEntityPk.class)
public class MyEntity {
#Id
String channel
#Id
String service
along with the primary key class (excerpt)
public class MyEntityPk implements Serializable {
String channel
String service
#ContextConfiguration
#SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT)
class ApplicationContextSpec extends Specification {
#Autowired
WebApplicationContext context
def "should boot up without errors"() {
expect: "(web) application context exists"
context != null
}
}
After this change, Spring Boot application smoke test fails with
java.lang.IllegalStateException: Failed to load ApplicationContext
...
Caused by: org.springframework.context.ApplicationContextException: Unable to start embedded container; nested exception is org.springframework.context.ApplicationContextException: Unable to start EmbeddedWebApplicationContext due to missing EmbeddedServletContainerFactory bean.
...
Caused by: org.springframework.context.ApplicationContextException: Unable to start EmbeddedWebApplicationContext due to missing EmbeddedServletContainerFactory bean.
along with all other jpa related tests.
As a further information, I picked Spring Boot gs-accessing-data-jpa-master sample and adapter it to use gradle and spock. Then I modified to use a composite key and Spring Boot application smoke test is successful as expected.
On my Ws Web Application (uses dependency spring-boot-starter-web-services) there is something that causes failure. I would like to point out that the only changes were moving from auto generated key to composite key.
This causes failure to find EmbeddedServletContainerFactory. Do you have any suggestion on the matter ?
I am posting also che build script, quite complex so I added some comments to clarify implementation
buildscript {
ext {
springBootVersion = '1.5.2.RELEASE'
}
repositories {
mavenCentral()
}
dependencies {
classpath("org.springframework.boot:spring-boot-gradle-plugin:${springBootVersion}")
}
}
apply plugin: 'groovy'
apply plugin: 'org.springframework.boot'
// I am using a mixed environment with some java generated source code
// and mainly groovy classes. This sourceSets definition forces to compile
// everything with groovy compiler so that java classes see groovy classes
sourceSets {
main {
groovy {
srcDirs = ['src/main/groovy', 'src/main/java']
}
java {
srcDirs = []
}
}
test {
groovy {
srcDirs = ['src/test/groovy','src/test/java']
}
java {
srcDirs = []
}
}
}
repositories {
mavenCentral()
}
// This task defines a jaxb task that takes xsd schema definition
// and generates java classes used when mapping soap requests
task genJaxb {
ext.sourcesDir = "${buildDir}/generated-sources/jaxb"
ext.classesDir = "${buildDir}/classes/jaxb"
ext.schema = "src/main/resources/myws.xsd"
outputs.dir classesDir
doLast() {
project.ant {
taskdef name: "xjc", classname: "com.sun.tools.xjc.XJCTask",
classpath: configurations.jaxb.asPath
mkdir(dir: sourcesDir)
mkdir(dir: classesDir)
xjc(destdir: sourcesDir, schema: schema) {
arg(value: "-wsdl")
produces(dir: sourcesDir, includes: "**/*.java")
}
javac(destdir: classesDir, source: 1.6, target: 1.6, debug: true,
debugLevel: "lines,vars,source",
classpath: configurations.jaxb.asPath) {
src(path: sourcesDir)
include(name: "**/*.java")
include(name: "*.java")
}
copy(todir: classesDir) {
fileset(dir: sourcesDir, erroronmissingdir: false) {
exclude(name: "**/*.java")
}
}
}
}
}
configurations {
jaxb
}
sourceCompatibility = 1.8
targetCompatibility = 1.8
dependencies {
compile("org.springframework.boot:spring-boot-starter-data-jpa")
compile("org.springframework.boot:spring-boot-starter-web-services")
compile('org.springframework.boot:spring-boot-starter-actuator')
compile("org.codehaus.groovy:groovy-all:2.4.7")
compile("wsdl4j:wsdl4j:1.6.1")
compile(files(genJaxb.classesDir).builtBy(genJaxb))
runtime('com.h2database:h2')
jaxb("org.glassfish.jaxb:jaxb-xjc:2.2.11")
testCompile 'org.springframework.boot:spring-boot-starter-test'
testCompile 'org.spockframework:spock-spring:1.0-groovy-2.4'
testCompile 'cglib:cglib-nodep:3.2.5'
}
jar {
baseName = 'myws'
version = '0.7.1'
excludes = ['**/application.yml']
from sourceSets.main.output
// adding jaxb generated file to be included in jar
from('build/classes/jaxb') {
include '**'
}
}
// this defines a uber-jar so that I may launch spring server
// from command line using java -jar myws-spring-boot.jar
task('execJar', type:Jar, dependsOn: 'jar') {
baseName = 'myws'
version = '0.7.1'
classifier = 'spring-boot'
from sourceSets.main.output
from('build/classes/jaxb') {
include '**'
}
}
bootRepackage {
withJarTask = tasks['execJar']
}
Eventually, all I have to do is:
gradlew build
to build the jar and run the tests and then
java -jar myws-spring-boot.jar
to launch the spring boot server
Smoke test was not working because I did not perform all required changes when moving from the "Long id" field as primary key
#Id
#GeneratedValue(strategy=GenerationType.AUTO)
Long id
to
#Id
String channel
#Id
String service
I forgot to remove a method in the repository class that was referencing the "Long id" field. After moving to spring-spock 1.1 following Leonard Brünings' suggestion, I got a more detailed error message that pointed me to the right direction.
Error creating bean with name 'modelEntryRepository': Invocation of init method failed; nested exception is org.springframework.data.mapping.PropertyReferenceException: No property id found for type ModelEntryEntity!
So I removed the references (method declaration in repository interface) and smoke test ended successfully.
By the way, within build.gradle I had to add spock core explicitly, so instead of one line with reference to spring-spock 1.0 I had to put
testCompile 'org.spockframework:spock-core:1.1-groovy-2.4'
testCompile 'org.spockframework:spock-spring:1.1-groovy-2.4'

Enum annotations in Kotlin

I have an enumeration that is serialized/deserialized by Gson:
enum class PacketType {
NONE;
[SerializedName("request")]
REQUEST;
[SerializedName("response")]
RESPONSE;
[SerializedName("event")]
EVENT;
}
Unfortunately, I noticed that Gson ignores SerializedName annotations and uses upper case names for enum values. I decided to find out why serialization doesn't work as intended and found out that Kotlin drops all annotations for enum values. How can I make these annotations appear in generated bytecode?
Looks like a bug to me. Please report to the issue tracker.
As a temporary workaround, you can write this class in Java
The issue is now fixed, your code now works fine in Kotlin M9 (0.9.66). If you upgrade to that it'll work as you expect.
e.g.
app build.gradle
dependencies {
compile fileTree(dir: 'libs', include: ['*.jar'])
compile 'org.jetbrains.kotlin:kotlin-stdlib:0.9.66'
compile 'com.google.code.gson:gson:2.3'
}
top-level build.gradle
buildscript {
repositories {
jcenter()
}
dependencies {
classpath 'com.android.tools.build:gradle:0.13.2'
classpath 'org.jetbrains.kotlin:kotlin-gradle-plugin:0.9.+'
}
}
I confirmed this by making an enum with no relation between the enum names and SerializedName names, and it worked as expected.
If you need to use enum as #Query param in Retrofit you can override toString():
override fun toString(): String {
try {
val annotations = javaClass.getField(name).annotations
for (annotation in annotations) {
if (annotation is SerializedName) {
return annotation.value
}
}
} catch (e: NoSuchFieldException) {
throw RuntimeException(e)
}
return super.toString()
}

Resources