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

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/

Related

Java with TestNG lose initialized variable

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

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'
}

I have an error but dependencies include in gradle root and gradle module config, why?

I have root config gradle.build
plugins {
id 'org.springframework.boot' version '2.3.5.RELEASE'
id 'io.spring.dependency-management' version '1.0.10.RELEASE'
id 'java'
id 'idea'
}
idea {
project {
languageLevel = 14
}
module {
downloadJavadoc = true
downloadSources = true
}
}
allprojects {
group "ru.otus"
repositories {
mavenCentral()
maven { url 'https://repo.spring.io/milestone' }
maven { url 'https://repo.spring.io/snapshot' }
}
apply plugin: "io.spring.dependency-management"
dependencyManagement {
dependencies {
imports {
mavenBom("org.springframework.boot:spring-boot-dependencies:2.3.5.RELEASE")
}
dependency("org.projectlombok:lombok:1.18.16")
dependency("org.springframework.shell:spring-shell-starter:2.0.1.RELEASE")
dependency("org.springframework.boot:spring-boot-starter-data-jpa:2.3.5.RELEASE")
dependency("org.flywaydb:flyway-core:6.4.4")
dependency("org.postgresql:postgresql:42.2.16")
dependency("org.hamcrest:hamcrest-core:1.3")
dependency("org.springframework.boot:spring-boot-starter-test:2.3.5.RELEASE")
}
}
configurations.all {
resolutionStrategy {
failOnVersionConflict()
}
resolutionStrategy {
force("javax.servlet:servlet-api:2.4")
force("commons-logging:commons-logging:1.1.1")
force("commons-lang:commons-lang:2.5")
force("org.codehaus.jackson:jackson-core-asl:1.8.8")
force("org.codehaus.jackson:jackson-mapper-asl:1.8.3")
force("org.codehaus.jettison:jettison:1.1")
force("org.javassist:javassist:3.24.0-GA")
force("org.apiguardian:apiguardian-api:1.1.0")
force("org.opentest4j:opentest4j:1.2.0")
}
}
}
and have build.gradle in module
plugins {
id 'java'
}
version = '0.0.1-SNAPSHOT'
dependencies {
implementation group: 'org.springframework.shell', name: 'spring-shell-starter', version: '2.0.1.RELEASE'
implementation group: 'org.springframework.boot', name: 'spring-boot-starter', version: '2.3.5.RELEASE'
implementation group: 'org.flywaydb', name: 'flyway-core', version: '6.4.4'
testCompile group: 'org.hamcrest', name: 'hamcrest-core', version: '1.3'
testImplementation group: 'org.springframework.boot', name: 'spring-boot-starter-test', version: '2.3.5.RELEASE'
}
After download dependencies and add in models annotations like #Entity, #Table #Id and etc. i have an error: cannot find symbol
#Entity
^
symbol: class Entity
But i have spring-boot-starter-jpa in dependencies, i don't know why in module i can't use dependencies.
With dependencyManagement you only manage dependencies like version, overrides etc. you don't actually add dependencies to a project. For that use dependencies like you use in the other places.

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 :) :)

Running Spring Boot Application on WebSphere 9

I've a Spring Boot Application with main class:
#SpringBootApplication
public class MyApplication extends SpringBootServletInitializer{
public static void main(String[] args) {
SpringApplication.run(MyApplication .class, args);
}
#Override
protected SpringApplicationBuilder configure(SpringApplicationBuilder application){
return application.sources(applicationClass);
}
private static Class<MyApplication > applicationClass = MyApplication .class;
}
With gradle.build:
version '1.0'
// dependencies for command line
buildscript {
ext {
springBootVersion = '1.4.3.RELEASE'
dependencyManagementVersion = '0.6.0.RELEASE'
}
repositories {
jcenter()
}
dependencies {
classpath "org.springframework.boot:spring-boot-gradle-plugin:${springBootVersion}"
classpath "io.spring.gradle:dependency-management-plugin:${dependencyManagementVersion}"
}
}
apply plugin: "io.spring.dependency-management"
apply plugin: 'java'
apply plugin: 'org.springframework.boot'
apply plugin: 'war'
apply plugin: 'eclipse'
apply plugin: 'idea'
// JDK 8
sourceCompatibility = JavaVersion.VERSION_1_8
targetCompatibility = JavaVersion.VERSION_1_8
repositories {
jcenter()
}
ext {
springCloudVersion = 'Brixton.SR4'
springBootVersion = '1.4.3.RELEASE'
swaggerVersion = '2.4.0'
jodaTimeVersion = '2.9.4'
jacksonJodaVersion = '2.5.1'
junitVersion = '4.12'
springWsTestVersion = '2.2.3.RELEASE'
lombokVersion = '1.16.10'
jsonPathVersion = '2.2.0'
ehcacheVersion = '3.2.0'
javaxCacheVersion = '1.0.0'
}
dependencyManagement {
imports {
mavenBom "org.springframework.cloud:spring-cloud-dependencies:${springCloudVersion}"
mavenBom "org.springframework.boot:spring-boot-starter-parent:${springBootVersion}"
}
}
sourceSets {
test {
java {
srcDir 'src/test/unit/java'
}
resources {
srcDir 'src/test/unit/resources'
}
}
}
tasks.withType(JavaExec) {
if (System.getProperty("DEBUG", 'false') == 'true') {
jvmArgs '-Xdebug', '-Xrunjdwp:transport=dt_socket,server=y,suspend=y,address=5006'
}
}
dependencies {
// https://mvnrepository.com/artifact/javax/javaee-api
compile group: 'javax', name: 'javaee-api', version: '7.0'
/* core libraries */
compile('org.springframework.cloud:spring-cloud-starter-config') {
exclude group: 'org.springframework.boot', module: 'spring-boot-starter-logging'
}
compile('org.springframework.boot:spring-boot-starter-web') {
exclude group: 'org.springframework.boot', module: 'spring-boot-starter-logging'
}
compile("org.springframework.boot:spring-boot-starter-hateoas"){
exclude group: 'org.springframework.boot', module: 'spring-boot-starter-logging'
}
compile 'org.springframework.ws:spring-ws-core'
// tag::actuator[]; for #RefreshScope
compile("org.springframework.boot:spring-boot-starter-actuator"){
exclude group: 'org.springframework.boot', module: 'spring-boot-starter-logging'
}
// end::actuator[]
// logging
compile('org.springframework.boot:spring-boot-starter-log4j2')
compile('com.fasterxml.jackson.dataformat:jackson-dataformat-yaml')
compile('com.fasterxml.jackson.core:jackson-databind')
// embedded server
providedRuntime ('org.springframework.boot:spring-boot-starter-tomcat')
// https://mvnrepository.com/artifact/org.projectlombok/lombok-maven
compile "org.projectlombok:lombok:${lombokVersion}"
// https://mvnrepository.com/artifact/com.jayway.jsonpath/json-path
// A Java DSL for reading JSON documents
compile "com.jayway.jsonpath:json-path:${jsonPathVersion}"
//for EhCache
// https://mvnrepository.com/artifact/org.ehcache/ehcache
compile "org.ehcache:ehcache:${ehcacheVersion}"
// https://mvnrepository.com/artifact/javax.cache/cache-api
compile "javax.cache:cache-api:${javaxCacheVersion}"
// utilities
compile "io.springfox:springfox-swagger2:${swaggerVersion}"
compile "io.springfox:springfox-swagger-ui:${swaggerVersion}"
compile "joda-time:joda-time:${jodaTimeVersion}"
compile "com.fasterxml.jackson.datatype:jackson-datatype-joda:${jacksonJodaVersion}"
compile ("org.springframework.boot:spring-boot-starter-aop") {
exclude group: 'org.springframework.boot', module: 'spring-boot-starter-logging'
}
compile "org.aspectj:aspectjweaver:1.8.8"
/* plugins */
/* test libraries */
// unit
testCompile "junit:junit:${junitVersion}"
testCompile "org.springframework.boot:spring-boot-starter-test"
testCompile "org.springframework.ws:spring-ws-test:${springWsTestVersion}"
}
war {
archiveName = "${project.name}.war"
manifest {
attributes 'Main-Class': 'com..content.MyApplication'
}
}
When I try to deploy the war file on WebSphere Application Server 9.0 Traditional, it starts but takes very long time. Without war file, server starts and stops very normally, but with application, server hangs.
Am I missing something?
Thank you for help!!
The startup delay is probably caused by CDI's implicit bean archive scanning. If you are not using CDI, you can disable implicit bean archives with com.ibm.ws.cdi.enableImplicitBeanArchives=false.
You can find a much more detailed explanation in this tech note:
Custom Properties for improving application startup in WebSphere Application Server

Categories