Spring boot application - Tomcat deployment - Failed to determine a suitable driver class - java

While running from IDE everything looks fine
Getting a below-mentioned error while trying to deploy the application in the tomcat server.
Caused by: org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'org.springframework.boot.autoconfigure.orm.jpa.HibernateJpaConfiguration': Unsatisfied dependency expressed through constructor parameter 0; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'dataSource' defined in class path resource [org/springframework/boot/autoconfigure/jdbc/DataSourceConfiguration$Hikari.class]: Bean instantiation via factory method failed; nested exception is org.springframework.beans.BeanInstantiationException: Failed to instantiate [com.zaxxer.hikari.HikariDataSource]: Factory method 'dataSource' threw exception; nested exception is org.springframework.boot.autoconfigure.jdbc.DataSourceProperties$DataSourceBeanCreationException: Failed to determine a suitable driver class
Application.java
#SpringBootApplication
public class Application extends SpringBootServletInitializer {
#Override
protected SpringApplicationBuilder configure(SpringApplicationBuilder application) {
return application.sources(Application.class);
}
public static void main(String[] args) {
SpringApplication.run(Application.class, args);
}
}
build.gradle
plugins {
id 'java'
}
sourceCompatibility = 1.8
apply plugin: 'java'
apply plugin: 'war'
repositories {
mavenCentral()
maven { url "http://dayrhebfmi001.enterprisenet.org:8081/artifactory/libs-snapshot"}
}
dependencies {
compile group: 'org.springframework.boot', name: 'spring-boot-starter-web', version: '2.1.7.RELEASE'
compile group: 'org.springframework.boot', name: 'spring-boot-starter-data-jpa', version: '2.1.7.RELEASE'
compile group: 'org.postgresql', name: 'postgresql', version: '42.2.6'
compile group: 'org.projectlombok', name: 'lombok', version: '1.18.8'
annotationProcessor group: 'org.projectlombok', name: 'lombok', version: '1.18.8'
compile group: 'org.apache.commons', name: 'commons-lang3', version: '3.9'
compile group: 'org.slf4j', name: 'slf4j-api', version: '1.7.28'
testCompile group: 'junit', name: 'junit', version: '4.12'
providedRuntime group: 'org.springframework.boot', name: 'spring-boot-starter-tomcat', version: '2.1.8.RELEASE'
}
application.properties
spring.datasource.platform=xxxxx
spring.datasource.url=xxxxx
spring.datasource.username=xxxxx
spring.datasource.password=xxxxx
spring.jpa.show-sql=true
spring.datasource.driver-class-name=org.postgresql.Driver

Failed to instantiate [com.zaxxer.hikari.HikariDataSource]: Factory method 'dataSource' threw exception; nested exception is org.springframework.boot.autoconfigure.jdbc.DataSourceProperties$DataSourceBeanCreationException: Failed to determine a suitable driver class
There are a couple things that look suspicious about your properties. But I think you can solve this specific error by giving it the class name as requested.
spring.datasource.driver-class-name=oracle.jdbc.OracleDriver
(or whatever DB you're using)
Extra points for adding
spring.jpa.database-platform=org.hibernate.dialect.Oracle10gDialect
(again, or whatever DB you're using)
EDIT:
Of course unless you've put the database driver jar file in tomcat/lib, you'll need to add that to your dependencies such that it can get bundled into the war file.

You should add driver class configuration to application.properties:
spring.datasource.driver-class-name=org.postgresql.Driver

Related

Gradle build failed for empty project

I just created a project in spring boot, the project is clean (zero changes) just created and at first I wanted to build it with the command: ./gradlew clean build , but the build does not go through I get: BUILD FAILED (Task :test FAILED) What went wrong: Execution failed for task ':test'. java.lang.IllegalStateException: Failed to load ApplicationContext I have no idea why I'm getting an error in an application where I haven't modified anything yet. What could be the cause of this? How can I build this application?
SpringbootServerApplicationTests > contextLoads() FAILED
java.lang.IllegalStateException at DefaultCacheAwareContextLoaderDelegate.java:132
Caused by: org.springframework.beans.factory.UnsatisfiedDependencyException at ConstructorResolver.java:800
Caused by: org.springframework.beans.factory.BeanCreationException at ConstructorResolver.java:658
Caused by: org.springframework.beans.BeanInstantiationException at SimpleInstantiationStrategy.java:185
Caused by: org.springframework.boot.autoconfigure.jdbc.DataSourceProperties$DataSourceBeanCreationException at DataSourceProperties.java:182
gradle.build
plugins {
id 'org.springframework.boot' version '2.7.2'
id 'io.spring.dependency-management' version '1.0.12.RELEASE'
id 'java'
}
group = 'com.example'
version = '0.0.1-SNAPSHOT'
sourceCompatibility = '17'
configurations {
compileOnly {
extendsFrom annotationProcessor
}
}
repositories {
mavenCentral()
}
dependencies {
implementation 'org.springframework.boot:spring-boot-starter-data-jpa'
implementation 'org.springframework.boot:spring-boot-starter-web'
compileOnly 'org.projectlombok:lombok'
developmentOnly 'org.springframework.boot:spring-boot-devtools'
runtimeOnly 'org.postgresql:postgresql'
annotationProcessor 'org.projectlombok:lombok'
testImplementation 'org.springframework.boot:spring-boot-starter-test'
}
tasks.named('test') {
useJUnitPlatform()
}
ERROR:
Caused by: org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'dataSource' defined in class path resource [org/springframework/boot/autoconfigure/jdbc/DataSourceConfiguration$Hikari.class]: Bean instantiation via factory method failed; nested exception is org.springframework.beans.BeanInstantiationException: Failed to instantiate [com.zaxxer.hikari.HikariDataSource]: Factory method 'dataSource' threw exception; nested exception is org.springframework.boot.autoconfigure.jdbc.DataSourceProperties$DataSourceBeanCreationException: Failed to determine a suitable driver class
at app//org.springframework.beans.factory.support.ConstructorResolver.instantiate(ConstructorResolver.java:658)
at app//org.springframework.beans.factory.support.ConstructorResolver.instantiateUsingFactoryMethod(ConstructorResolver.java:638)
I think you have default test and you dont have main method that starts application. Maybe you can write some code to provide spring application to boot. Main method is enough for you. contextLoads() method test the application context be up or not. You need configure datasource as well. In your stacktrace I can see that driver is missing.

Upgrading from Springboot 2.1.4.Release to 2.5.0 is giving Illegal Runtime Exception on aws ECS deployment

I have upgraded our app from springboot 2.1.4.Release to 2.5.0 and updated relevant jars for running the application. But when I am trying to deploy and run the app in aws ECS , it is giving the following error.
But when I deploy the earlier commit it is able to deploy fine.
It is not able to read the aws Secrets manager to read the values from there.
On looking carefully, I found theres a difference in startup of the springboot. If anyone can point in the right direction, it will be of great help.
The error in the aws ECS logs:
Caused by: org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'cloudPlatformSecuirtyResourceServerConfig': Unsatisfied dependency expressed through field 'uaaResourceInfo'; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'UAAResourceInfoConfig': Injection of autowired dependencies failed; nested exception is java.lang.IllegalArgumentException: Could not resolve placeholder 'moa.aws.secrets.uaa.clientId' in value "${moa.aws.secrets.uaa.clientId}"
The failed startup log for the springboot is:
2021-08-24T18:24:42.232-04:00
' |____| .__|_| |_|_| |_\__, | / / / /
2021-08-24T18:24:42.232-04:00
=========|_|==============|___/=/_/_/_/
2021-08-24T18:24:42.236-04:00
:: Spring Boot :: (v2.5.0)
2021-08-24T18:24:42.854-04:00
2021-08-24 22:24:42 [main] INFO c.g.d.o.m.MoaApplication.logStarting - Starting MoaApplication using Java 1.8.0_212 on ip-10-228-213-136.ec2.internal with PID 1 (/app/bin/app.jar started by appuser in /app/bin)
2021-08-24T18:24:42.855-04:00
2021-08-24 22:24:42 [main] INFO c.g.d.o.m.MoaApplication.logStartupProfileInfo - The following profiles are active: aws,security
2021-08-24T18:24:50.749-04:00
2021-08-24 22:24:50 [main] INFO o.s.d.r.c.RepositoryConfigurationDelegate.registerRepositoriesIn - Bootstrapping Spring Data JPA repositories in DEFAULT mode.
2021-08-24T18:24:52.715-04:00
2021-08-24 22:24:52 [main] INFO o.s.d.r.c.RepositoryConfigurationDelegate.registerRepositoriesIn - Finished Spring Data repository scanning in 1900 ms. Found 29 JPA repository interfaces.
2021-08-24T18:24:53.919-04:00
2021-08-24 22:24:53 [main] INFO o.s.c.c.s.GenericScope.setSerializationId - BeanFactory id=ac4ea7b8-8e46-3560-bd24-f258beed7bb3
2021-08-24T18:24:54.857-04:00
2021-08-24 22:24:54 [main] INFO o.s.c.s.PostProcessorRegistrationDelegate$BeanPostProcessorChecker.postProcessAfterInitialization - Bean 'org.springframework.boot.autoconfigure.flyway.FlywayAutoConfiguration' of type [org.springframework.boot.autoconfigure.flyway.FlywayAutoConfiguration] is not eligible for getting processed by all BeanPostProcessors (for example: not eligible for auto-proxying)
2021-08-24T18:24:54.860-04:00
2021-08-24 22:24:54 [main] INFO o.s.c.s.PostProcessorRegistrationDelegate$BeanPostProcessorChecker.postProcessAfterInitialization - Bean 'stringOrNumberMigrationVersionConverter' of type [org.springframework.boot.autoconfigure.flyway.FlywayAutoConfiguration$StringOrNumberToMigrationVersionConverter] is not eligible for getting processed by all BeanPostProcessors (for example: not eligible for auto-proxying)
2021-08-24T18:24:54.914-04:00
2021-08-24 22:24:54 [main] INFO o.s.c.s.PostProcessorRegistrationDelegate$BeanPostProcessorChecker.postProcessAfterInitialization - Bean 'management.metrics-org.springframework.boot.actuate.autoconfigure.metrics.MetricsProperties' of type [org.springframework.boot.actuate.autoconfigure.metrics.MetricsProperties] is not eligible for getting processed by all BeanPostProcessors (for example: not eligible for auto-proxying)
2021-08-24T18:24:54.915-04:00
2021-08-24 22:24:54 [main] INFO o.s.c.s.PostProcessorRegistrationDelegate$BeanPostProcessorChecker.postProcessAfterInitialization - Bean 'org.springframework.boot.actuate.autoconfigure.metrics.data.RepositoryMetricsAutoConfiguration' of type [org.springframework.boot.actuate.autoconfigure.metrics.data.RepositoryMetricsAutoConfiguration] is not eligible for getting processed by all BeanPostProcessors (for example: not eligible for auto-proxying)
The startup log for the successful deployment is
The only difference I can see between the successful deployment and failed deployment is, the container is loading and initializing the PropertySourceBootstrapConfiguration bean by itself for successful deployment
This is linked to the same question asked by me in this post but didnt get any resposne
Upgrading from Springboot 2.1.4.RELEASE to 2.5.0 giving IllegalArgumentException on runtime
Below is the build.gradle:
buildscript {
ext {
springBootVersion = '2.5.0'
}
repositories {
mavenCentral()
jcenter()
maven {
url "https://xxxxxx/ARJLY"
credentials {
username = "${artifactory_user}"
password = "${artifactory_password}"
}
name = "xxxxxxx"
}
maven { url "https://repo.spring.io/plugins-release" }
maven { url "https://repo.spring.io/libs-release" }
}
dependencies {
classpath("org.springframework.boot:spring-boot-gradle-plugin:${springBootVersion}")
//docker
classpath('se.transmode.gradle:gradle-docker:1.2')
}
}
apply plugin: 'java'
apply plugin: 'eclipse'
apply plugin: 'org.springframework.boot'
apply plugin: 'io.spring.dependency-management'
apply plugin: 'maven-publish'
apply plugin: 'distribution'
apply plugin: 'application'
apply plugin: 'docker'
apply plugin: 'jacoco'
group = 'com.ge.digital.oa.moa'
archivesBaseName = 'moa-svc'
sourceCompatibility = 1.8
wrapper {
gradleVersion = '6.8'
}
//dependencyManagement {
// imports {
// mavenBom 'org.springframework.cloud:spring-cloud-aws:2.0.1.RELEASE'
// }
//}
repositories {
mavenCentral()
add buildscript.repositories.getByName("oa-publish-repo")
maven { url "https://repo.spring.io/libs-release" }
}
mainClassName = "com.ge.digital.oa.moa.MoaApplication"
eclipse {
classpath {
downloadSources = true
}
}
configurations {
developmentOnly
runtimeClasspath {
extendsFrom developmentOnly
}
}
sourceSets {
generated
}
sourceSets.generated.java.srcDirs = ['src/main/generated']
configurations{
querydslapt
}
dependencies {
implementation('com.ge.digital.oa.common:oa-common:3.0.0') {
exclude module: 'slf4j-log4j12'
exclude group: 'io.micrometer', module: 'micrometer-core'
exclude group: 'org.springframework.hateoas', module: 'spring-hateoas'
//exclude group: 'org.springframework.cloud', module: 'spring-cloud-context'
}
//implementation('org.springframework.security:spring-security-oauth2-client')
implementation('org.springframework.security.oauth.boot:spring-security-oauth2-autoconfigure:2.5.0')
implementation('org.springframework.boot:spring-boot-starter-web')
implementation('org.springframework.boot:spring-boot-starter-webflux')
implementation('org.springframework.boot:spring-boot-starter-data-jpa')
implementation('org.apache.commons:commons-lang3');
implementation('commons-fileupload:commons-fileupload:1.4')
implementation("com.h2database:h2")
implementation('org.postgresql:postgresql:42.2.13')
compileOnly('org.projectlombok:lombok')
annotationProcessor('org.projectlombok:lombok')
implementation('org.springframework.boot:spring-boot-starter-actuator')
implementation("org.flywaydb:flyway-core")
testImplementation("org.springframework.boot:spring-boot-starter-test")
testImplementation("org.junit.jupiter:junit-jupiter-engine")
developmentOnly("org.springframework.boot:spring-boot-devtools")
implementation('com.opencsv:opencsv:5.5')
compile ("org.apache.commons:commons-csv:1.5")
compile("com.querydsl:querydsl-core:4.2.1")
compile("com.querydsl:querydsl-jpa:4.2.1")
compile("com.querydsl:querydsl-apt:4.2.1:jpa")
annotationProcessor(
"javax.persistence:javax.persistence-api",
"com.querydsl:querydsl-apt:4.2.1:jpa"
)
implementation("org.hibernate:hibernate-envers:5.4.31.Final")
// https://mvnrepository.com/artifact/com.vladmihalcea/hibernate-types-52
implementation group: 'com.vladmihalcea', name: 'hibernate-types-52', version: '2.10.3'
//OSS Scan fix
// https://mvnrepository.com/artifact/org.springframework.boot/spring-boot-starter-validation
implementation group: 'org.springframework.boot', name: 'spring-boot-starter-validation', version: '2.5.0'
// https://mvnrepository.com/artifact/org.springframework.cloud/spring-cloud-context
implementation group: 'org.springframework.cloud', name: 'spring-cloud-context', version: '3.0.0'
// https://mvnrepository.com/artifact/commons-io/commons-io
implementation group: 'commons-io', name: 'commons-io', version: '2.7'
// https://mvnrepository.com/artifact/org.bouncycastle/bcprov-jdk15on
implementation group: 'org.bouncycastle', name: 'bcprov-jdk15on', version: '1.64'
// https://mvnrepository.com/artifact/com.google.guava/guava
implementation group: 'com.google.guava', name: 'guava', version: '30.0-jre'
// https://mvnrepository.com/artifact/org.springframework.security.oauth/spring-security-oauth2
//implementation group: 'org.springframework.security.oauth', name: 'spring-security-oauth2', version: '2.3.6.RELEASE'
// https://mvnrepository.com/artifact/com.fasterxml.jackson.core/jackson-databind
implementation group: 'com.fasterxml.jackson.core', name: 'jackson-databind', version: '2.12.0'
// https://mvnrepository.com/artifact/org.springframework.cloud/spring-cloud-starter-aws-secrets-manager-config
implementation group: 'org.springframework.cloud', name: 'spring-cloud-starter-aws-secrets-manager-config', version: '2.2.6.RELEASE'
compile group: 'com.amazonaws', name: 'aws-java-sdk-secretsmanager', version: '1.11.355'
// https://mvnrepository.com/artifact/org.springframework.cloud/spring-cloud-dependencies
//runtimeOnly group: 'org.springframework.cloud', name: 'spring-cloud-dependencies', version: '2020.0.3', ext: 'pom'
Update:
As suggested, I tried this option in application.yml too..but to no success
spring:
config:
activate:
on-profile: aws
use-legacy-processing: true
main:
allow-bean-definition-overriding: true

Spring Boot: Logback Issue with Owasp ESAPI version 2.2.3.1

I've recently started looking at how to sanitise any user inputs to my test api and I came across this tutorial
Before attempting the tutorial I had logging to console with GCP cloud as thats where I want to run my API.
Now after adding owasp esapi my application will not start when using version 2.2.3.1 of esapi. I just by sure luck attempted using a previous version and it works as in the application will start.
Below is the error I get from logback on application start up
SLF4J: Actual binding is of type [org.slf4j.impl.SimpleLoggerFactory]
Exception in thread "main" java.lang.IllegalArgumentException: LoggerFactory is not a Logback LoggerContext but Logback is on the classpath. Either remove Logback or the competing implementation (class org.slf4j.impl.SimpleLoggerFactory loaded from file:/Users/xxx/.gradle/caches/modules-2/files-2.1/org.slf4j/slf4j-simple/1.7.30/e606eac955f55ecf1d8edcccba04eb8ac98088dd/slf4j-simple-1.7.30.jar). If you are using WebLogic you will need to add 'org.slf4j' to prefer-application-packages in WEB-INF/weblogic.xml: org.slf4j.impl.SimpleLoggerFactory
Again, If I use version 2.2.2.0 I have no issues at all on startup. Can anyone with experience shed some light here. (PLEASE SEE EDIT)
Below is my gradle build file (note I'm also using GCP logging)
plugins {
id "org.springframework.boot" version "2.5.0"
id 'io.spring.dependency-management' version '1.0.11.RELEASE'
id 'java'
id "idea"
id 'com.google.cloud.tools.jib' version '3.0.0'
}
group 'network.thefullstack.search-service'
version '1.0'
java {
sourceCompatibility = JavaVersion.VERSION_14
targetCompatibility = JavaVersion.VERSION_14
}
jib.from.image = 'openjdk:15-jdk-buster'
repositories {
mavenCentral()
}
dependencies {
implementation 'org.springframework.boot:spring-boot-starter-web'
implementation group: 'org.springframework.boot', name: 'spring-boot-starter-security'
testImplementation group: 'org.springframework.security', name: 'spring-security-test'
implementation group: 'org.springframework.security', name: 'spring-security-oauth2-client'
implementation group: 'org.springframework.boot', name: 'spring-boot-starter-webflux'
implementation('org.springframework.boot:spring-boot-starter-data-elasticsearch')
implementation group: 'org.springframework.data', name: 'spring-data-elasticsearch'
implementation group: 'org.springframework.boot', name: 'spring-boot-starter-validation'
compile group: 'org.springframework.cloud', name: 'spring-cloud-gcp-starter-logging'
implementation group: 'org.springframework.cloud', name: 'spring-cloud-gcp-starter-logging', version: '1.2.8.RELEASE'
implementation group: 'io.springfox', name: 'springfox-swagger-ui', version: '3.0.0'
implementation group: 'io.springfox', name: 'springfox-boot-starter', version: '3.0.0'
implementation group: 'javax.validation', name: 'validation-api', version: '2.0.1.Final'
implementation group: 'com.fasterxml.jackson.datatype', name: 'jackson-datatype-jsr310', version: '2.11.2'
implementation group: 'org.openapitools', name: 'jackson-databind-nullable', version: '0.2.1'
implementation group: 'commons-io', name: 'commons-io', version: '2.6'
implementation group: 'org.json', name: 'json', version: '20210307'
implementation group: 'org.apache.commons', name: 'commons-collections4', version: '4.4'
implementation group: 'org.apache.commons', name: 'commons-lang3', version: '3.11'
implementation 'org.jsoup:jsoup:1.13.1'
implementation 'org.apache.commons:commons-lang3:3.12.0'
implementation 'org.owasp:dependency-check-gradle:6.1.6'
compile (group: 'org.owasp.esapi', name: 'esapi', version: '2.2.2.0')
compileOnly 'org.projectlombok:lombok:1.18.12'
annotationProcessor 'org.projectlombok:lombok:1.18.12'
testCompile group: 'junit', name: 'junit', version: '4.12'
testCompileOnly 'org.projectlombok:lombok:1.18.12'
testAnnotationProcessor 'org.projectlombok:lombok:1.18.12'
testImplementation('org.springframework.boot:spring-boot-starter-test') {
exclude group: 'org.junit.vintage', module: 'junit-vintage-engine'
}
jar {
manifest {
attributes(
'Main-Class': 'org.test.SearchServiceApplication'
)
}
from {
configurations.runtimeClasspath.collect { it.isDirectory() ? it : zipTree(it) }
}
}
}
Here is my ESAPI.properties file:
ESAPI.Logger=org.owasp.esapi.logging.slf4j.Slf4JLogFactory
Here is an example of where I am logging:
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.core.convert.converter.Converter;
import java.util.Arrays;
public class StringToEnumConverter implements Converter<String, Filters> {
private static Logger logger = LoggerFactory.getLogger(StringToEnumConverter.class);
#Override
public Filters convert(String source) {
try {
logger.info("Attempting to convert ENUM param to uppercase {}", source);
return Filters.valueOf(source.toUpperCase());
} catch (IllegalArgumentException e) {
logger.error("Failed to convert ENUM param to uppercase {}", source);
throw new BadFilterRequestException("Error: Filter provide must be one of: " + Arrays.asList(Filters.values()), "Search");
}
}
}
EDIT: Using the older version while it will allow the API to start, it will fire this error message when its envoked:
Caused by: java.lang.NoClassDefFoundError: Could not initialize class org.owasp.esapi.logging.slf4j.Slf4JLogFactory
at java.base/java.lang.Class.forName0(Native Method)
at java.base/java.lang.Class.forName(Class.java:340)
at org.owasp.esapi.util.ObjFactory.loadClassByStringName(ObjFactory.java:158)
at org.owasp.esapi.util.ObjFactory.make(ObjFactory.java:81)
at org.owasp.esapi.ESAPI.logFactory(ESAPI.java:139)
at org.owasp.esapi.ESAPI.getLogger(ESAPI.java:155)
at org.owasp.esapi.reference.DefaultEncoder.<init>(DefaultEncoder.java:83)
at org.owasp.esapi.reference.DefaultEncoder.getInstance(DefaultEncoder.java:67)
... 46 common frames omitted
Thank you for your time

Problem with Google Cloud App Engine and Spring Boot gradle Deploying

I have a problem..
I want to deploy my Spring Boot Gradle app to GC App Engine.
I use the command :
gradle appengineDeploy
It actually works but when i try to open the app in the browser it says :
Error: Server Error
The server encountered an error and could not complete your request.
Please try again in 30 seconds.
So the app was deployed successfully but it has a problem to start..
java.lang.RuntimeException: org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'cloudSqlDataSourceProperties' defined in class path resource [org/springframework/cloud/gcp/autoconfigure/sql/GcpCloudSqlAutoConfiguration$CloudSqlDataSourcePropertiesConfiguration.class]: Bean instantiation via factory method failed; nested exception is org.springframework.beans.BeanInstantiationException: Failed to instantiate [org.springframework.boot.autoconfigure.jdbc.DataSourceProperties]: Factory method 'cloudSqlDataSourceProperties' threw exception; nested exception is java.lang.IllegalStateException: Unable to set ApplicationName - SQLAdmin client already initialized.
at org.eclipse.jetty.annotations.ServletContainerInitializersStarter.doStart (ServletContainerInitializersStarter.java:68)
at org.eclipse.jetty.util.component.AbstractLifeCycle.start (AbstractLifeCycle.java:68)
at org.eclipse.jetty.servlet.ServletContextHandler.startContext (ServletContextHandler.java:330)
at org.eclipse.jetty.webapp.WebAppContext.startWebapp (WebAppContext.java:1406)
at com.google.apphosting.runtime.jetty9.AppEngineWebAppContext.startWebapp (AppEngineWebAppContext.java:175)
at org.eclipse.jetty.webapp.WebAppContext.startContext (WebAppContext.java:1368)
at org.eclipse.jetty.server.handler.ContextHandler.doStart (ContextHandler.java:778)
at org.eclipse.jetty.servlet.ServletContextHandler.doStart (ServletContextHandler.java:262)
at org.eclipse.jetty.webapp.WebAppContext.doStart (WebAppContext.java:522)
at com.google.apphosting.runtime.jetty9.AppEngineWebAppContext.doStart (AppEngineWebAppContext.java:120)
at org.eclipse.jetty.util.component.AbstractLifeCycle.start (AbstractLifeCycle.java:68)
at com.google.apphosting.runtime.jetty9.AppVersionHandlerMap.createHandler (AppVersionHandlerMap.java:240)
at com.google.apphosting.runtime.jetty9.AppVersionHandlerMap.getHandler (AppVersionHandlerMap.java:178)
at com.google.apphosting.runtime.jetty9.JettyServletEngineAdapter.serviceRequest (JettyServletEngineAdapter.java:120)
at com.google.apphosting.runtime.JavaRuntime$RequestRunnable.dispatchServletRequest (JavaRuntime.java:728)
at com.google.apphosting.runtime.JavaRuntime$RequestRunnable.dispatchRequest (JavaRuntime.java:691)
at com.google.apphosting.runtime.JavaRuntime$RequestRunnable.run (JavaRuntime.java:661)
at com.google.apphosting.runtime.JavaRuntime$NullSandboxRequestRunnable.run (JavaRuntime.java:853)
at com.google.apphosting.runtime.ThreadGroupPool$PoolEntry.run (ThreadGroupPool.java:270)
at java.lang.Thread.run (Thread.java:748)
Caused by: org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'cloudSqlDataSourceProperties' defined in class path resource [org/springframework/cloud/gcp/autoconfigure/sql/GcpCloudSqlAutoConfiguration$CloudSqlDataSourcePropertiesConfiguration.class]: Bean instantiation via factory method failed; nested exception is org.springframework.beans.BeanInstantiationException: Failed to instantiate [org.springframework.boot.autoconfigure.jdbc.DataSourceProperties]: Factory method 'cloudSqlDataSourceProperties' threw exception; nested exception is java.lang.IllegalStateException: Unable to set ApplicationName - SQLAdmin client already initialized.
at org.springframework.beans.factory.support.ConstructorResolver.instantiate (ConstructorResolver.java:627)
at org.springframework.beans.factory.support.ConstructorResolver.instantiateUsingFactoryMethod (ConstructorResolver.java:607)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.instantiateUsingFactoryMethod (AbstractAutowireCapableBeanFactory.java:1305)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBeanInstance (AbstractAutowireCapableBeanFactory.java:1144)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean (AbstractAutowireCapableBeanFactory.java:555)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean (AbstractAutowireCapableBeanFactory.java:515)
at org.springframework.beans.factory.support.AbstractBeanFactory.lambda$doGetBean$0 (AbstractBeanFactory.java:320)
at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton (DefaultSingletonBeanRegistry.java:222)
at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean (AbstractBeanFactory.java:318)
at org.springframework.beans.factory.support.AbstractBeanFactory.getBean (AbstractBeanFactory.java:199)
at org.springframework.beans.factory.support.DefaultListableBeanFactory.preInstantiateSingletons (DefaultListableBeanFactory.java:849)
at org.springframework.context.support.AbstractApplicationContext.finishBeanFactoryInitialization (AbstractApplicationContext.java:877)
at org.springframework.context.support.AbstractApplicationContext.refresh (AbstractApplicationContext.java:549)
at org.springframework.boot.web.servlet.context.ServletWebServerApplicationContext.refresh (ServletWebServerApplicationContext.java:142)
at org.springframework.boot.SpringApplication.refresh (SpringApplication.java:775)
at org.springframework.boot.SpringApplication.refreshContext (SpringApplication.java:397)
at org.springframework.boot.SpringApplication.run (SpringApplication.java:316)
at org.springframework.boot.web.servlet.support.SpringBootServletInitializer.run (SpringBootServletInitializer.java:157)
at org.springframework.boot.web.servlet.support.SpringBootServletInitializer.createRootApplicationContext (SpringBootServletInitializer.java:137)
at org.springframework.boot.web.servlet.support.SpringBootServletInitializer.onStartup (SpringBootServletInitializer.java:91)
at org.springframework.web.SpringServletContainerInitializer.onStartup (SpringServletContainerInitializer.java:171)
at org.eclipse.jetty.plus.annotation.ContainerInitializer.callStartup (ContainerInitializer.java:140)
at org.eclipse.jetty.annotations.ServletContainerInitializersStarter.doStart (ServletContainerInitializersStarter.java:63)
Caused by: org.springframework.beans.BeanInstantiationException: Failed to instantiate [org.springframework.boot.autoconfigure.jdbc.DataSourceProperties]: Factory method 'cloudSqlDataSourceProperties' threw exception; nested exception is java.lang.IllegalStateException: Unable to set ApplicationName - SQLAdmin client already initialized.
at org.springframework.beans.factory.support.SimpleInstantiationStrategy.instantiate (SimpleInstantiationStrategy.java:185)
at org.springframework.beans.factory.support.ConstructorResolver.instantiate (ConstructorResolver.java:622)
Caused by: java.lang.IllegalStateException: Unable to set ApplicationName - SQLAdmin client already initialized.
at com.google.cloud.sql.core.CoreSocketFactory.setApplicationName (CoreSocketFactory.java:341)
at org.springframework.cloud.gcp.autoconfigure.sql.GcpCloudSqlAutoConfiguration$CloudSqlDataSourcePropertiesConfiguration.cloudSqlDataSourceProperties (GcpCloudSqlAutoConfiguration.java:209)
at org.springframework.cloud.gcp.autoconfigure.sql.GcpCloudSqlAutoConfiguration$CloudSqlDataSourcePropertiesConfiguration$$EnhancerBySpringCGLIB$$bb6c42e.CGLIB$cloudSqlDataSourceProperties$0 (<generated>)
at org.springframework.cloud.gcp.autoconfigure.sql.GcpCloudSqlAutoConfiguration$CloudSqlDataSourcePropertiesConfiguration$$EnhancerBySpringCGLIB$$bb6c42e$$FastClassBySpringCGLIB$$a426c72d.invoke (<generated>)
at org.springframework.cglib.proxy.MethodProxy.invokeSuper (MethodProxy.java:244)
at org.springframework.context.annotation.ConfigurationClassEnhancer$BeanMethodInterceptor.intercept (ConfigurationClassEnhancer.java:363)
at org.springframework.cloud.gcp.autoconfigure.sql.GcpCloudSqlAutoConfiguration$CloudSqlDataSourcePropertiesConfiguration$$EnhancerBySpringCGLIB$$bb6c42e.cloudSqlDataSourceProperties (<generated>)
at sun.reflect.NativeMethodAccessorImpl.invoke0 (Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke (NativeMethodAccessorImpl.java:62)
at sun.reflect.DelegatingMethodAccessorImpl.invoke (DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke (Method.java:498)
at org.springframework.beans.factory.support.SimpleInstantiationStrategy.instantiate (SimpleInstantiationStrategy.java:154)
So it is caused by
Unable to set ApplicationName - SQLAdmin client already initialized.
my build.gradle looks like this
buildscript { // Configuration for building
repositories {
jcenter()
mavenCentral()
}
dependencies {
classpath 'com.google.cloud.tools:appengine-gradle-plugin:1.+' // Latest 1.x.x releas
}
}
plugins {
id 'org.springframework.boot' version '2.1.3.RELEASE'
id 'java'
}
apply plugin: 'io.spring.dependency-management'
apply plugin: 'java' // standard Java tasks
apply plugin: 'war' // standard Web Archive plugin
apply plugin: 'com.google.cloud.tools.appengine' // App Engine tasks
group = 'de.msm'
version = '0.0.1-SNAPSHOT'
sourceCompatibility = '1.8'
targetCompatibility = 1.8 // App Engine Flexible uses Java 8
configurations {
providedRuntime
compileOnly {
extendsFrom annotationProcessor
}
developmentOnly
runtimeClasspath {
extendsFrom developmentOnly
}
}
appengine { // App Engine tasks configuration
deploy { // deploy configuration
stopPreviousVersion = true // default - stop the current version
promote = true // default - & make this the current version
}
}
/*
Only for Run
configurations.all {
exclude group: 'org.slf4j', module: 'slf4j-log4j12'
exclude group: 'org.springframework.boot', module: 'spring-boot-starter-tomcat'
}*/
repositories {
mavenCentral()
jcenter()
jcenter{
url 'http://oss.jfrog.org/artifactory/oss-snapshot-local'
}
}
task getHomeDir { //To get actual homeDir
doLast {
println gradle.gradleHomeDir
}
}
dependencies {
compile('org.springframework.boot:spring-boot-starter-web') {
exclude group: 'org.springframework.boot', module: 'spring-boot-starter-tomcat'
}
compile('org.springframework.boot:spring-boot-starter-jetty')
compile group: 'org.springframework.boot', name: 'spring-boot-devtools', version: '2.1.6.RELEASE'
implementation 'org.springframework.boot:spring-boot-starter-data-jpa'
implementation 'org.springframework.boot:spring-boot-starter-security'
implementation 'org.springframework.boot:spring-boot-starter-thymeleaf'
compileOnly 'org.projectlombok:lombok'
annotationProcessor 'org.projectlombok:lombok'
testImplementation 'org.springframework.boot:spring-boot-starter-test'
testImplementation 'org.springframework.security:spring-security-test'
implementation 'com.github.javafaker:javafaker:0.17.2'
compile group: 'org.bouncycastle', name: 'bcprov-jdk15on', version: '1.56'
compile group: 'org.springframework.boot', name: 'spring-boot-configuration-processor', version: '2.1.4.RELEASE'
compile 'org.springframework.boot:spring-boot-starter-mail:2.1.5.RELEASE'
compile 'org.springframework:spring-context-support:5.1.7.RELEASE'
testCompile 'io.rest-assured:rest-assured:4.0.0'
compile 'io.rest-assured:xml-path:4.0.0'
compile 'io.rest-assured:json-path:4.0.0'
testCompile 'io.rest-assured:json-schema-validator:4.0.0'
compile group: 'joda-time', name: 'joda-time', version: '2.10.3'
testCompile group: 'org.junit.jupiter', name: 'junit-jupiter-api', version: '5.5.1'
testCompile group: 'org.mockito', name: 'mockito-all', version: '2.0.2-beta'
compile group: 'org.xhtmlrenderer', name: 'flying-saucer-pdf', version: '9.1.18'
compile "org.apache.pdfbox:pdfbox-tools:2.0.3"
compile "com.itextpdf:itextpdf:5.5.10"
compile "com.itextpdf.tool:xmlworker:5.5.10"
compile "org.apache.poi:poi-ooxml:3.15"
compile "org.apache.poi:poi-scratchpad:3.15"
compile "xerces:xercesImpl:2.8.0"
compile "org.slf4j:slf4j-nop:1.8.0-beta4"
compile group: 'commons-io', name: 'commons-io', version: '2.5'
compile group: 'com.google.cloud', name: 'google-cloud-storage', version: '1.91.0'
compile group: 'org.postgresql', name: 'postgresql', version: '42.1.4'
compile group: 'org.springframework.cloud', name: 'spring-cloud-gcp-starter-sql-postgresql', version: '1.1.3.RELEASE'
compile 'com.google.appengine:appengine-api-1.0-sdk:+'
compile group: 'commons-io', name: 'commons-io', version: '2.6'
}
```
I dont understand whats the problem..

ClassNotFoundException when building with gradle and trying to use com.google.code.gson

I'm new to Java projects and gradle. I'm trying to use Google's GSON to parse a JSON string.
When I navigate to my-project-name/build/classes/main/
I get the ClassNotFoundException when I run
$ java GetGroupMeMessages
Here is the stack trace (That's what it's called, right?):
Exception in thread "main" java.lang.NoClassDefFoundError: com/google/gson/Gson
at GetGroupMeMessages.main(GetGroupMeMessages.java:59)
Caused by: java.lang.ClassNotFoundException: com.google.gson.Gson
at java.net.URLClassLoader.findClass(URLClassLoader.java:381)
at java.lang.ClassLoader.loadClass(ClassLoader.java:424)
at sun.misc.Launcher$AppClassLoader.loadClass(Launcher.java:331)
at java.lang.ClassLoader.loadClass(ClassLoader.java:357)
... 1 more
My build.gradle file looks like this:
apply plugin: 'java'
apply plugin: 'eclipse'
sourceCompatibility = 1.8
version = '1.0'
jar {
manifest {
attributes 'Implementation-Title': 'gscc-groupme-logs',
'Implementation-Version': version
}
}
repositories {
mavenCentral()
}
dependencies {
compile group: 'com.fasterxml.jackson.core', name: 'jackson-databind', version: '2.8.6'
compile group: 'commons-collections', name: 'commons-collections', version: '3.2.2'
compile group: 'com.google.code.gson', name: 'gson', version: '2.8.0'
testCompile group: 'junit', name: 'junit', version: '4.+'
}
test {
systemProperties 'property': 'value'
}
uploadArchives {
repositories {
flatDir {
dirs 'repos'
}
}
}
I'm doing everything from the command line.
I've got my files saved under my-project-name/src/main/java/
Any help is much appreciated! I am stuck.
If you want to run single java file from command line, you need to provide gson jar as classpath using -cp jar_location in your command.
If you want to run build jar:
change dependencies from compile to runtime in your configuration.
dependencies {
runtime group: 'com.fasterxml.jackson.core', name: 'jackson-databind', version: '2.8.6'
runtime group: 'commons-collections', name: 'commons-collections', version: '3.2.2'
runtime group: 'com.google.code.gson', name: 'gson', version: '2.8.0'
testCompile group: 'junit', name: 'junit', version: '4.+'
}
Change your jar config like following:
jar {
manifest {
attributes(
'Implementation-Title': 'gscc-groupme-logs',
'Implementation-Version': version
'Class-Path': configurations.compile.collect { it.getName() }.join(' '),
'Main-Class': 'GetGroupMeMessages'
)
}
}
Then after creating the jar run it using java -jar jarname command.

Categories