Java with TestNG lose initialized variable - java

There is surprising situation, which I can't understand. I have test automation with RestAssured (pet project). I want to prepare RequestSpecification spec variable in #BeforeSuite method, in parent class. Then I want to use spec variable in tests of child class. Here is code of parent class
public class BaseTest {
private String baseUrl = "https://api.thecatapi.com/v1/";
protected RequestSpecification spec;
#BeforeSuite
public void beforeSuite() {
String apiKey = System.getProperty("api_key");
spec = new RequestSpecBuilder()
.setContentType(ContentType.JSON)
.setBaseUri(baseUrl)
.addHeader("x-api-key", apiKey)
.addFilter(new ResponseLoggingFilter())
.addFilter(new RequestLoggingFilter())
.addFilter(new AllureRestAssured())
.build();
}
}
And here is a test in child class'
public class OurLittleTest extends BaseTest {
#Test
public void test() {
//1
String id = Breeds.search(spec, "Scottish Fold").then().extract().body().jsonPath().get("[0].id");
problem is that spec variable in test is null, while I was waiting it won't be null...
Why it happens? Why spec is null ?
I've recordered a screencast where you can see my problem
UPDATE
Everything is fine with Junit 5. The spec variable is not null in child classes anymore. So here are me build.gradle files:
With TestNG:
buildscript {
repositories {
jcenter()
}
dependencies {
classpath "io.qameta.allure:allure-gradle:2.8.1"
}
}
plugins {
id 'java'
id 'io.qameta.allure' version '2.8.1'
}
sourceCompatibility = JavaVersion.VERSION_1_8
allure {
configuration = 'testImplementation'
version = '2.7.0'
allureJavaVersion = '2.7.0'
}
group 'org.example'
version '1.0-SNAPSHOT'
repositories {
mavenCentral()
}
dependencies {
implementation group: 'com.fasterxml.jackson.core', name: 'jackson-databind', version: '2.9.5'
implementation 'org.projectlombok:lombok:1.18.20'
annotationProcessor 'org.projectlombok:lombok:1.18.20'
implementation 'io.rest-assured:rest-assured:4.4.0'
implementation group: 'io.qameta.allure', name: 'allure-rest-assured', version: '2.14.0'
implementation "io.qameta.allure:allure-testng:2.14.0"
testImplementation group: 'org.testng', name: 'testng', version: '7.3.0'
}
test {
useTestNG() {
parallel = 'methods'
threadCount = 2
}
if (project.hasProperty("api_key")) {
systemProperties.put("api_key", "$api_key")
}
}
With Junit 5:
plugins {
id 'io.qameta.allure' version '2.5'
id 'java'
}
allure {
configuration = 'testImplementation'
version = '2.7.0'
useJUnit5 {
version = '2.7.0'
}
}
sourceCompatibility = JavaVersion.VERSION_1_8
group 'org.example'
version '1.0-SNAPSHOT'
repositories {
jcenter()
mavenCentral()
}
dependencies {
implementation group: 'com.fasterxml.jackson.core', name: 'jackson-databind', version: '2.9.5'
implementation 'org.projectlombok:lombok:1.18.20'
annotationProcessor 'org.projectlombok:lombok:1.18.20'
implementation 'io.rest-assured:rest-assured:4.4.0'
implementation group: 'io.qameta.allure', name: 'allure-rest-assured', version: '2.14.0'
implementation group: 'io.qameta.allure', name: 'allure-junit5', version: '2.14.0'
testImplementation 'org.junit.jupiter:junit-jupiter-api:5.2.0'
testRuntimeOnly 'org.junit.jupiter:junit-jupiter-engine:5.2.0'
}
test {
useJUnitPlatform{
systemProperty 'junit.jupiter.testinstance.lifecycle.default' , 'per_class'
systemProperty 'junit.jupiter.execution.parallel.enabled', 'true'
systemProperty 'junit.jupiter.execution.parallel.mode.default', 'same_thread'
systemProperty 'junit.jupiter.execution.parallel.mode.classes.default', 'concurrent'
}
if (project.hasProperty("api_key")) {
systemProperties.put("api_key", "$api_key")
}
}
What's wrong with TestNG ?

The problem is usage of #BeforeSuite. It is meant to be used only once per suite and ignored in following runs.
For initializing the spec you can either do it directly inline in the field like protected RequestSpecification spec = new RequestSpecBuilder()... or use #BeforeClass.

I tested your code, no error. The problem might be in OurLittleTest class you use Junit, and you use testNG in BaseTest class

Related

#GrpcClient is null spring boot 3

I am making grpc client using net.devh.grpc-client-spring-boot-starter
Client:
#Service
public class SystemService {
#GrpcClient("handyman-client")
StatusServiceGrpc.StatusServiceBlockingStub handymanClient;
public VersionResponse getHandymanVersion() {
return handymanClient.getVersion(Empty.newBuilder().build());
}
}
application.yaml:
grpc:
client:
handyman-client:
address: static://localhost:8080
negotiationType: plaintext
In runtime handymanClient is null. Tried spring boot versions from 3.0.0 to 3.0.2. Lowering the spring boot version to 2.7.0 solves the problem - the client is being created now.
Is there a workaround to make it work on spring boot 3?
build.gradle:
plugins {
id 'java'
id 'org.springframework.boot' version '3.0.0'
id 'io.spring.dependency-management' version '1.1.0'
id "com.google.protobuf" version "0.9.2"
}
group = 'hello.grpc'
version = '0.0.1-SNAPSHOT'
sourceCompatibility = '17'
configurations {
compileOnly {
extendsFrom annotationProcessor
}
}
repositories {
mavenCentral()
}
dependencies {
implementation 'org.springframework.boot:spring-boot-starter-actuator'
implementation 'org.springframework.boot:spring-boot-starter-web'
compileOnly 'org.projectlombok:lombok'
annotationProcessor 'org.projectlombok:lombok'
testImplementation 'org.springframework.boot:spring-boot-starter-test'
implementation 'io.micrometer:micrometer-registry-prometheus'
implementation 'javax.annotation:javax.annotation-api:1.3.2'
implementation group: 'net.devh', name: 'grpc-client-spring-boot-starter', version: '2.13.0.RELEASE'
implementation group: 'io.grpc', name: 'grpc-stub', version: '1.53.0'
implementation group: 'io.grpc', name: 'grpc-protobuf', version: '1.53.0'
}
sourceSets {
main {
java {
srcDirs 'build/generated/source/proto/main/grpc'
srcDirs 'build/generated/source/proto/main/java'
}
}
}
protobuf {
protoc {
artifact = 'com.google.protobuf:protoc:4.0.0-rc-2'
}
plugins {
grpc {
artifact = 'io.grpc:protoc-gen-grpc-java:1.53.0'
}
}
generateProtoTasks {
all()*.plugins {
grpc {}
}
}
}
tasks.named('test') {
useJUnitPlatform()
}
springBoot {
buildInfo()
}

gradle build failed with jooq configuration: java.lang.ClassNotFoundException: com.mysql.jdbc.Driver

guys.
I'm building a spring boot service. Right now I'm setting it up to query a local MySQL instance with jooq.
However, ./gradlew build gives error Unable to load class 'com.mysql.jdbc.Driver'.
Am I missing anything?
More Info
I'm able to see the com.mysql.jdbc.Driver class in Intellij.
Here is my gradle script.
import nu.studer.gradle.jooq.JooqEdition
plugins {
id 'org.springframework.boot' version '2.6.2'
id 'io.spring.dependency-management' version '1.0.11.RELEASE'
id 'nu.studer.jooq' version '3.0.2'
id 'java'
}
if(JavaVersion.current() != JavaVersion.VERSION_11){
throw new GradleException("This build must be run with java 11")
}
java {
toolchain {
languageVersion = JavaLanguageVersion.of(11)
}
}
repositories {
mavenCentral()
}
group = 'snorlax'
version = '0.0.1-SNAPSHOT'
sourceCompatibility = '11'
//create a fat Jar with all dependencies
jar {
duplicatesStrategy(DuplicatesStrategy.EXCLUDE)
from {
configurations.compileClasspath.collect { it.isDirectory() ? it : zipTree(it) }
}
manifest {
attributes "Main-Class": "com.snorlax.userservice.MainApplication"
}
}
configurations {
compileOnly {
extendsFrom annotationProcessor
}
}
dependencies {
// Spring boot
implementation 'org.springframework.boot:spring-boot-starter-actuator'
implementation 'org.springframework.boot:spring-boot-starter-web'
developmentOnly 'org.springframework.boot:spring-boot-devtools'
testImplementation 'org.springframework.boot:spring-boot-starter-test'
// Swagger
implementation group: 'io.springfox', name: 'springfox-swagger2', version: '2.9.2'
implementation group: 'io.springfox', name: 'springfox-swagger-ui', version: '2.9.2'
// Lombok
compileOnly 'org.projectlombok:lombok'
annotationProcessor 'org.projectlombok:lombok'
// RDS Connection
implementation 'org.springframework.boot:spring-boot-starter-data-jpa'
runtimeOnly 'mysql:mysql-connector-java:8.0.27'
implementation 'com.amazonaws.secretsmanager:aws-secretsmanager-jdbc:1.0.6'
// JOOQ
implementation 'org.springframework.boot:spring-boot-starter-jooq:2.6.2'
implementation 'org.jooq:jooq-meta:3.15.5'
implementation 'org.jooq:jooq-codegen:3.15.5'
}
test {
useJUnitPlatform()
}
/************************
jooq code generation
*************************/
import org.jooq.codegen.GenerationTool
import org.jooq.meta.jaxb.*
GenerationTool.generate(new Configuration()
.withJdbc(new Jdbc()
.withDriver('com.mysql.jdbc.Driver')
.withUrl('jdbc:mysql://127.0.0.1:3306/SnorlaxRds')
.withUser('root')
.withPassword('123456'))
.withGenerator(new Generator()
.withDatabase(new Database())
.withGenerate(new Generate()
.withPojos(true)
.withDaos(true))
.withTarget(new Target()
.withPackageName('com.snorlax.userservice')
.withDirectory('src/main/java/jooq'))))
My bad.
I missed the buildscript { } block mentioned here: https://www.jooq.org/doc/latest/manual/code-generation/codegen-gradle.
After adding below section, now my gradle build works.
buildscript {
repositories {
mavenLocal()
mavenCentral()
}
dependencies {
classpath 'org.jooq:jooq-codegen:3.16.2'
classpath 'mysql:mysql-connector-java:8.0.27'
}
}
Full version
buildscript {
repositories {
mavenLocal()
mavenCentral()
}
dependencies {
classpath 'org.jooq:jooq-codegen:3.16.2'
classpath 'mysql:mysql-connector-java:8.0.27'
}
}
plugins {
id 'org.springframework.boot' version '2.6.2'
id 'io.spring.dependency-management' version '1.0.11.RELEASE'
id 'java'
}
if(JavaVersion.current() != JavaVersion.VERSION_11){
throw new GradleException("This build must be run with java 11")
}
repositories {
mavenCentral()
}
group = 'snorlax'
version = '0.0.1-SNAPSHOT'
sourceCompatibility = '11'
//create a fat Jar with all dependencies
jar {
duplicatesStrategy(DuplicatesStrategy.EXCLUDE)
from {
configurations.compileClasspath.collect { it.isDirectory() ? it : zipTree(it) }
}
manifest {
attributes "Main-Class": "com.snorlax.userservice.MainApplication"
}
}
configurations {
compileOnly {
extendsFrom annotationProcessor
}
}
dependencies {
// Spring boot
implementation 'org.springframework.boot:spring-boot-starter-actuator'
implementation 'org.springframework.boot:spring-boot-starter-web'
developmentOnly 'org.springframework.boot:spring-boot-devtools'
testImplementation 'org.springframework.boot:spring-boot-starter-test'
// Swagger
implementation group: 'io.springfox', name: 'springfox-swagger2', version: '2.9.2'
implementation group: 'io.springfox', name: 'springfox-swagger-ui', version: '2.9.2'
// Lombok
compileOnly 'org.projectlombok:lombok'
annotationProcessor 'org.projectlombok:lombok'
// RDS Connection
implementation 'org.springframework.boot:spring-boot-starter-data-jpa'
runtimeOnly 'mysql:mysql-connector-java:8.0.27'
// AWS secretes manager
implementation 'com.amazonaws.secretsmanager:aws-secretsmanager-jdbc:1.0.6'
// JOOQ
implementation 'org.springframework.boot:spring-boot-starter-jooq'
implementation 'org.jooq:jooq-meta:3.16.2'
compileOnly 'org.jooq:jooq-codegen:3.16.2'
}
test {
useJUnitPlatform()
}
/************************
jooq code generation
*************************/
import org.jooq.codegen.GenerationTool;
import org.jooq.meta.jaxb.*;
task generate {
def outputDirectory = projectDir.toString() + '/src/main/java'
println outputDirectory
def configuration = new Configuration()
.withJdbc(new Jdbc()
.withDriver('com.mysql.cj.jdbc.Driver')
.withUrl('jdbc:mysql://127.0.0.1:3306/snorlaxRds')
.withUser('root')
.withPassword('123456'))
.withGenerator(new Generator()
.withDatabase(new Database().withInputSchema("snorlaxRds"))
.withGenerate(new Generate()
.withPojos(true)
.withDaos(true))
.withTarget(new Target()
.withPackageName('snorlax.userservice.database')
.withDirectory(outputDirectory)));
doLast {
GenerationTool.generate(configuration)
}
}

Issue with HTML character escaping in JAVA spring boot deployed on weblogic server. It works in TEST environment but not in PRODUCTION

In my spring boot application I have below code which has AnnotationConfigWebApplicationContext and i included FrameworkWebconfig class (from jar file) in that AnnotationConfigWebApplicationContext which is used for escaping special charaters in JSON response. But for some issues I had to remove that framework web config class and after that special charaters were not escaping in JSON response (as expected, in TEST environment). Same code when i run in PROD its not working it is still escaping those special characters. This application is deployed on Weblogic servers. I am not getting whats the issue here. Can someone please help me understand why this is happening?
#Configuration
public class Application implements WebApplicationInitializer {
....
private AnnotationConfigWebApplicationContext getContext() {
logger.info("Entering method : getContext");
AnnotationConfigWebApplicationContext context = new AnnotationConfigWebApplicationContext();
context.register(FrameworkPropertySourcesConfig.class);
//context.register(FrameworkWebConfig.class); //this line, after removing its working in TEST but not in prod
context.register(AppConfig.class);
logger.info("Exiting method : getContext");
return context;
}
.....
}
#EnableWebMvc
#Configuration
public class FrameworkWebConfig extends WebMvcConfigurerAdapter {
private MappingJackson2HttpMessageConverter buildHtmlEscapingJsonConverter() {
MappingJackson2HttpMessageConverter htmlEscapingConverter = new MappingJackson2HttpMessageConverter();
ObjectMapper objectMapper = new ObjectMapper();
objectMapper.getJsonFactory().setCharacterEscapes(new HTMLCharacterEscapes());
htmlEscapingConverter.setObjectMapper(objectMapper);
return htmlEscapingConverter;
}
public void configureDefaultServletHandling(DefaultServletHandlerConfigurer configurer) {
configurer.enable();
}
public void configureMessageConverters(List<HttpMessageConverter<?>> converters) {
super.configureMessageConverters(converters);
converters.add(this.buildHtmlEscapingJsonConverter());
}
#Bean
CommonsMultipartResolver multipartResolver() {
return new CommonsMultipartResolver();
}
}
Below is build.gradle file
buildscript {
ext {
springBootVersion = '1.2.5.RELEASE'
}
repositories {
mavenCentral()
}
dependencies {
classpath("org.springframework.boot:spring-boot-gradle-plugin:${springBootVersion}")
classpath("io.spring.gradle:dependency-management-plugin:0.5.2.RELEASE")
}
}
plugins {
//id "org.sonarqube" version "2.5"
//gradle sonarqube
}
apply plugin: 'java'
apply plugin: 'eclipse-wtp'
apply plugin: 'spring-boot'
apply plugin: 'io.spring.dependency-management'
apply plugin: 'war'
//apply plugin: 'org.sonarqube'
war {
baseName = 'CServices'
webInf { from 'WEB-INF' }
}
sourceCompatibility = 1.7
targetCompatibility = 1.7
repositories {
mavenCentral()
}
configurations {
providedRuntime
providedCompile
exclude
jar
}
dependencies {
compile files('WEB-INF/lib/framework.jar')
compile files('WEB-INF/lib/wsclient.jar')
compile("org.springframework.boot:spring-boot-starter-redis")
compile("org.springframework.boot:spring-boot-starter-security")
compile("org.springframework.security.oauth:spring-security-oauth2:2.0.7.RELEASE")
compile("org.springframework.boot:spring-boot-starter-thymeleaf"){
exclude module: 'spring-boot-starter-tomcat'
}
compile("org.springframework.boot:spring-boot-starter-web"){
exclude module: 'spring-boot-starter-tomcat'
}
compile("org.springframework.ws:spring-ws-core")
compile("org.springframework:spring-tx")
compile("org.springframework:spring-jdbc")
compile("org.mybatis:mybatis:3.2.8")
compile("org.mybatis:mybatis-spring:1.2.3")
compile('org.springframework.boot:spring-boot-starter-mail')
compile("org.apache.poi:poi:3.9")
compile("org.apache.poi:poi-ooxml:3.9")
compile('commons-httpclient:commons-httpclient:3.1')
compile("org.apache.commons:commons-lang3:3.1")
compile('org.hsqldb:hsqldb:2.0.0')
compile('commons-fileupload:commons-fileupload:1.2')
compile('commons-io:commons-io:1.4')
compile('com.google.code.gson:gson:2.2.4')
compile('com.google.guava:guava:r05')
compile("org.apache.oltu.oauth2:org.apache.oltu.oauth2.client:1.0.1");
compile('org.json:json:20090211')
compile('org.projectlombok:lombok:1.18.10')
// https://mvnrepository.com/artifact/com.microsoft.sqlserver/mssql-jdbc
compile group: 'com.microsoft.sqlserver', name: 'mssql-jdbc', version: '6.1.0.jre7'
compile group: 'com.fasterxml.jackson.core', name: 'jackson-core', version: '2.9.0'
//compile "com.fasterxml.jackson.dataformat:jackson-dataformat-xml:2.9.0"
testCompile("org.springframework.boot:spring-boot-starter-test")
providedCompile 'javax.servlet:javax.servlet-api:3.0.1'
compile group: 'org.springframework', name: 'spring-mock', version: '2.0.8'
compile group: 'org.springframework.boot', name: 'spring-boot-starter-aop', version: '1.2.5.RELEASE'
compile('commons-beanutils:commons-beanutils:1.9.2')
// https://mvnrepository.com/artifact/io.springfox/springfox-swagger-ui
compile group: 'io.springfox', name: 'springfox-swagger-ui', version: '2.9.2'
// https://mvnrepository.com/artifact/io.springfox/springfox-swagger2
compile group: 'io.springfox', name: 'springfox-swagger2', version: '2.9.2'
// https://mvnrepository.com/artifact/com.google.guava/guava
compile group: 'com.google.guava', name: 'guava', version: '27.0-jre'
testCompile group: 'org.mockito', name: 'mockito-all', version: '1.8.4'
}
eclipse {
classpath {
containers.remove('org.eclipse.jdt.launching.JRE_CONTAINER')
containers 'org.eclipse.jdt.launching.JRE_CONTAINER/org.eclipse.jdt.internal.debug.ui.launcher.StandardVMType/JavaSE-1.8'
}
wtp {
component {
contextPath = '/cs'
}
}
project{
natures 'org.springsource.ide.eclipse.gradle.core.nature'
}
}
//task afterEclipseImport { dependsOn ':cs-java-framework:jar' }
//compileJava.dependsOn ':cs-java-framework:jar'
task wrapper(type: Wrapper) {
gradleVersion = '2.7'
}

Spring Boot doesn't pick the values from application.yml

I am using spring-boot-starter-web latest version 2.2.6.RELEASE. But my application always returns null for a variable with #value annotation.
My build.gradle,
plugins {
id 'com.google.cloud.tools.jib' version '2.1.0'
id 'org.springframework.boot' version '2.2.6.RELEASE'
id 'io.spring.dependency-management' version '1.0.8.RELEASE'
id 'java'
id 'eclipse'
id 'idea'
id 'maven-publish'
}
jar {
archiveBaseName = 'my-project'
project.version = '1.0.0'
}
repositories {
jcenter()
mavenCentral()
mavenLocal()
}
sourceCompatibility = JavaVersion.VERSION_1_8
targetCompatibility = JavaVersion.VERSION_1_8
dependencies {
implementation group: 'org.apache.commons', name: 'commons-lang3', version: '+'
implementation('org.springframework.boot:spring-boot-starter-web:+') {
exclude module: 'spring-boot-starter-tomcat'
}
implementation("org.springframework.boot:spring-boot-starter-jetty:+")
implementation group: 'io.springfox', name: 'springfox-swagger2', version: '2.8.0'
implementation group: 'io.springfox', name: 'springfox-swagger-ui', version: '2.8.0'
implementation group: 'io.kubernetes', name: 'client-java', version: '+'
implementation group: 'com.google.cloud', name: 'google-cloud-dataproc', version: '+'
implementation(project(':my-project-1')) {
exclude group: 'org.yaml'
}
implementation project(':my-project2')
}
tasks.withType(JavaCompile) {
options.compilerArgs << '-Xlint:unchecked'
options.deprecation = true
}
My Java code,
#Component
public class MyClass {
#Value("${dataproc.host}")
private static String dataprocEndpoint;
My application.yml
dataproc:
host: dataproc.googleapis.com:443
My Application.java,
#SpringBootApplication
#EnableSwagger2
#Configuration
public class Application {
private static final Logger LOGGER = LoggerFactory.getLogger(Application.class);
private transient String PATTERNS_TO_HIDE = "^/(?!error|autoconfig|beans|profile|info|health|pause|env|refresh|resume|restart|actuator|dump|mappings|trace|metrics|heapdump|archaius|configprops|features|liquibase|loggers|auditevents).*$";
public static void main(String[] args) {
SpringApplication.run(Application.class, args);
}
#Bean
public Docket api() {
ApiInfo apiInfo = new ApiInfoBuilder().license("Proprietary").title("My Application")
.description("My Application").build();
return new Docket(DocumentationType.SWAGGER_2).select().apis(RequestHandlerSelectors.any())
.paths(PathSelectors.regex(PATTERNS_TO_HIDE)).build().pathMapping("/").apiInfo(apiInfo)
.useDefaultResponseMessages(false)
.globalResponseMessage(RequestMethod.GET, newArrayList(new ResponseMessageBuilder().code(500)
.message("500 message").responseModel(new ModelRef("Error")).build()));
}
}
Always getting null when I starting the server,
dataprocEndpoint: null
What configuration am I missing here?
Kindly provide your inputs here.
surround your property in quotes:
dataproc:
host: 'dataproc.googleapis.com:443'
Yml processor interprets your config property name as dataproc.host.dataproc.googleapis.com.443
Remove static from your field declaration.
#Value("${dataproc.host}")
private String dataprocEndpoint;
Static fields are initialized with class load. Spring bean post processors can’t inject values at so early phase. You can use setter injection if you want to inject value to static field anyway.
Ref https://mkyong.com/spring/spring-inject-a-value-into-static-variables/

NullPointer exception while generating code using swagger codegen for openapi 3.0

Facing issue of NullPointer while generating code through swagger codegen.
I am new to gradle and have updated build.gradle to reflect latest changes required to generate the code for the given API spec.
Please provide your valuable inputs.
My build.gradle is as shown below:
import io.swagger.codegen.v3.CodegenConfigLoader
import io.swagger.codegen.v3.DefaultGenerator
import io.swagger.codegen.v3.ClientOptInput
import io.swagger.codegen.v3.ClientOpts
import io.swagger.v3.parser.OpenAPIV3Parser
buildscript {
ext {
springBootVersion = '2.0.5.RELEASE'
jacocoWorkspaceDirectory = "/jacoco/"
}
repositories {
mavenLocal()
maven { url "http://repo.maven.apache.org/maven2" }
}
dependencies {
classpath "org.springframework.boot:spring-boot-gradle-plugin:$springBootVersion"
classpath group: "io.spring.gradle", name: "dependency-management-plugin", version: "1.0.6.RELEASE"
classpath 'co.bambo.sonar:bambo-sonar-gradle-plugin:2.7.1.RELEASE'
classpath group: "org.unbroken-dome.gradle-plugins", name: "gradle-testsets-plugin", version: "1.4.2"
classpath('io.swagger.codegen.v3:swagger-codegen-maven-plugin:3.0.16')
classpath("io.swagger.core.v3:swagger-core:2.1.1")
}
}
apply plugin: 'java'
apply plugin: 'maven'
apply plugin: 'maven-publish'
apply plugin: "io.spring.dependency-management"
apply plugin: "org.springframework.boot"
apply plugin: 'bambo-sonar'
apply plugin: "jacoco"
apply plugin: "findbugs"
apply plugin: "checkstyle"
apply plugin: "pmd"
apply plugin: 'org.unbroken-dome.test-sets'
project.buildDir = 'target'
ext {
appName = 'school-management'
apiPackage = 'co.bambo.school.management.generated.api'
modelPackage = 'co.bambo.school.management.generated.model'
swaggerFile = "${rootDir}/src/main/resources/schoolmanagement.v1.yaml"
swaggerBuildDir = "${project.buildDir}/" + appName
}
// NOTE :-> Following are to be included as and when required.
// These variables are defined for the purpose of exclusion from the sonar scan. Packages mentioned will be exluded
// from Sonar Scans.
def excludeschoolmanagementConstants = "src/main/java/co/bambo/school/management/constants/schoolmanagementConstants.java"
def excludeCaasConstants = "src/main/java/co/bambo/school/management/pcf/constants/CaasConstants.java"
sourceCompatibility = 1.8
targetCompatibility = 1.8
group = 'co.bambo.schoolmanagement'
version = '1.0.0-SNAPSHOT'
tasks.withType(JavaCompile) {
options.encoding = 'UTF-8'
}
repositories {
mavenLocal()
maven { url "http://repo.maven.apache.org/maven2" }
}
configurations {
testUtilCompile.extendsFrom testImplementation
testUtilRuntime.extendsFrom testRuntime
}
sourceSets {
testUtil {
java {
srcDir 'src/test-util/java'
}
}
}
testSets {
funcTest { dirName = "func-test" }
}
// PLUGIN CONFIGs
springBoot {
mainClassName = 'co.bambo.school.management.schoolmanagementApplication'
buildInfo()
}
bootJar {
baseName = 'school-management'
destinationDir = project.buildDir
archiveName = 'school-management.jar'
}
// FIXME - IN FUTURE WE NEED TO MAKE THIS to Zero.
checkstyle {
maxErrors = 70
maxWarnings = 70
toolVersion = 8.17
}
[checkstyleMain, checkstyleTest].each { task ->
task.logging.setLevel(LogLevel.LIFECYCLE)
// FIXME - This is to be updated with False.
task.ignoreFailures = true
}
findbugs {
toolVersion = "3.0.1"
sourceSets = [sourceSets.main]
// FIXME - Make this false.
ignoreFailures = true
effort = "max"
reportLevel = "medium"
excludeFilter = file("$rootDir/config/findbugs/exclude.xml")
}
pmd {
toolVersion = "5.6.1"
ignoreFailures = true
sourceSets = [sourceSets.main]
reportsDir = file("${project.buildDir}/reports/pmdTest")
ruleSets = [
'java-basic'
]
}
tasks.withType(FindBugs) {
reports {
xml.enabled = false
html.enabled = true
}
}
tasks.withType(Pmd) {
reports {
xml.enabled = false
html.enabled = true
}
}
sonarqube {
properties {
property "sonar.projectName", "school-management"
property "sonar.projectKey", "school-management"
property "sonar.jacoco.reportPath", "build/jacoco/test.exec"
property "sonar.junit.reportPaths", "build/test-results/test"
property "sonar.host.url", "https://fusion.bambo.int/sonar"
property "sonar.gateId", "307"
property "sonar.projectDescription", "school management microservice."
property "sonar.skip.qualityGate", "false"
property "sonar.exclusions", [excludeschoolmanagementConstants, excludeCaasConstants]
}
}
// Actual task for generating the server
task generateServer {
doLast {
def openAPI = new OpenAPIV3Parser().read(rootProject.swaggerFile.toString(), null, null)
def clientOptInput = new ClientOptInput().openAPI(openAPI)
def codeGenConfig = CodegenConfigLoader.forName('spring')
codeGenConfig.setApiPackage(rootProject.ext.apiPackage) // Package to be used for the API interfaces
codeGenConfig.setModelPackage(rootProject.ext.modelPackage) // Package to be used for the API models
codeGenConfig.setInputSpec(rootProject.ext.swaggerFile.toString()) // The swagger API file
codeGenConfig.setOutputDir(rootProject.ext.swaggerBuildDir)
// The output directory, user-service-contract/build/user-service-server/
// codegenConfig.addSystemProperty("models", "");
// codegenConfig.addSystemProperty("apis", "");
def clientOps = new ClientOpts()
clientOps.setProperties([
'dateLibrary' : 'java8', // Date library to use
'useTags' : 'true', // Use tags for the naming
'interfaceOnly': 'false'// Generating the Controller API interface and the models only
])
clientOptInput.setOpts(clientOps)
def generator = new DefaultGenerator().opts(clientOptInput)
generator.generate() // Executing the generation
}
}
compileJava {
dependsOn generateServer
}
build {
dependsOn generateServer
}
// ---- PLUGIN CONFIG ENDs
dependencyManagement {
imports {
mavenBom "org.springframework.boot:spring-boot-dependencies:$springBootVersion"
}
}
funcTest {
doFirst {
jacoco {
destinationFile = file("${buildDir}" + jacocoWorkspaceDirectory + "test.exec")
}
}
dependsOn cleanTest
dependsOn compileTestUtilJava
dependsOn cleanJacocoTestReport
dependsOn cleanJacocoTestCoverageVerification
finalizedBy jacocoTestReport
finalizedBy jacocoTestCoverageVerification
environment SPRING_PROFILES_ACTIVE: environment.SPRING_PROFILES_ACTIVE ?: "local"
}
dependencies {
// Spring specific dependencies
implementation('org.springframework:spring-tx')
implementation('org.springframework:spring-core')
implementation('org.springframework:spring-context')
implementation('org.springframework:spring-beans')
implementation('org.springframework:spring-expression')
implementation group: 'org.springframework.boot', name: 'spring-boot-starter-actuator'
implementation group: 'org.springframework.boot', name: 'spring-boot-starter-aop'
implementation group: 'org.springframework.retry', name: 'spring-retry'
implementation group: 'org.springframework.boot', name: "spring-boot-starter-data-jpa"
// Spring cloud
// Upgraded springcloud-starter-vault from 2.0.0.RC1 to 2.0.1.RELEASE.
implementation group: 'org.springframework.cloud', name: 'spring-cloud-starter-vault-config', version: '2.0.1.RELEASE'
implementation group: 'io.pivotal.spring.cloud', name: 'spring-cloud-services-starter-config-client', version: '2.0.1.RELEASE'
// Upgraded "spring-cloud-starter-bus-amqp" following from 2.0.0.RC1 to 2.0.1.RELEASE
implementation group: 'org.springframework.cloud', name: 'spring-cloud-starter-bus-amqp', version: '2.0.1.RELEASE'
// SWagger dependencies
implementation group: 'io.swagger', name: 'swagger-parser', version: '1.0.23'
implementation group: 'io.springfox', name: 'springfox-swagger2', version: '2.9.2'
implementation group: 'io.springfox', name: 'springfox-swagger-ui', version: '2.9.2'
implementation group: 'com.atlassian.oai', name: 'swagger-request-validator-core', version: '1.3.9'
// Apache - Commons
implementation group: 'commons-io', name: 'commons-io', version: '2.6'
// Oracle dependencies
implementation group: 'com.oracle', name: 'ojdbc7', version: '12.1.0'
//2nd level cache dependency
implementation group: 'org.hibernate', name: 'hibernate-ehcache'
// Logback
implementation group: 'ch.qos.logback', name: 'logback-classic', version: '1.2.3'
implementation group: 'ch.qos.logback', name: 'logback-core', version: '1.2.3'
implementation group: 'org.apache.camel', name: 'camel-jsonpath', version: '2.22.0'
implementation group: 'com.google.gdata', name: 'core', version: '1.47.1'
implementation group: 'com.google.guava', name: 'guava', version: '20.0'
// FIXME - Eventually phase - out this Mapper
implementation group: 'ma.glasnost.orika', name: 'orika-core', version: '1.5.4'
// JSON
implementation group: 'com.fasterxml.jackson.dataformat', name: 'jackson-dataformat-xml', version: '2.8.10'
implementation group: 'com.googlecode.json-simple', name: 'json-simple', version: '1.1.1'
// Mapstruct
implementation 'org.mapstruct:mapstruct:1.3.0.Final'
implementation 'org.mapstruct:mapstruct-processor:1.3.0.Final'
implementation group: 'ch.qos.logback.contrib', name: 'logback-json-classic', version: '0.1.5'
implementation group: 'ch.qos.logback.contrib', name: 'logback-jackson', version: '0.1.5'
testImplementation "junit:junit:4.12"
testImplementation group: "org.springframework.boot", name: "spring-boot-starter-test"
testImplementation group: 'com.github.tomakehurst', name: 'wiremock', version: '2.21.0'
testUtilCompile sourceSets.main.output
funcTestCompile sourceSets.testUtil.output
}
I am facing issue of NullPointer on this line def generator = new DefaultGenerator().opts(clientOptInput).
Update-1
I understand the question seems fairly easy for NullPointer exception in java. but trust me, I am not able to figure out in build.gradle why it is failing as it is not even showing proper error message that what is missing. Below shown message is all I am getting. Even the debugging of groovy script isn't helping me.
Execution failed for task ':generateServer'.
> java.lang.NullPointerException (no error message)
Update-2
I just got to see in the DefaultGenerator.java on line number 77, found this line.
This is where I am getting NullPointerException this.config.additionalProperties().putAll(opts.getOpts().getProperties());
I am not sure what is missing in parameters. I am passing opts and getOpts() is also populating properties file.
Using gradle version 4.9.
Okay I figured it out, it was a silly mistake in understanding and in code as well.
I got to know this mistake just after debugging and browsing through the swagger-codegen code. I realized that the config is required to generate code, based on this config specified it is generating code. I was generating the spring based CodeGenConfiguration but I was not passing it into the clientOptInput. My understanding was wrong, I assumed it will load the class for CodeGenConfig (Which it does load) and that's it. however you also need to pass it to the clientOptInput variable.
def codeGenConfig = CodegenConfigLoader.forName('spring')
clientOptInput.setConfig(codeGenConfig)
Since, the code for DefaultGenerator.java as per below:
#Override
public Generator opts(ClientOptInput opts) {
this.opts = opts;
this.openAPI = opts.getOpenAPI();
this.config = opts.getConfig();
I need to set it to the ClientOptInput instance. This is the reason. Posting for others like me who makes mistakes :) :)

Categories