Unable to connect to CloudSQL from SpringBoot - spring-boot

Assumptions
We are developing a WebAPI with SpringBoot on GoogleCloud's GCE.
We have confirmed that the Spring project starts successfully.
Java 11
Spring 2.7.6
mysql 5.7
What we want to achieve
I want to connect to CloudSQL from SpringBoot and get data from DB.
Problem
I get the following error and cannot connect.
SQLException: Access denied for user 'root'#'cloudsqlproxy~192.168.0.5' (using password: YES)
What I tried
Connecting in local environment
 Installed MySQL in local environment and connected.
Deploy to GCE, request with Postman, check response (without using DB) → received response with Postman, OK
SSH to GCE, connect to MySQL using mysql command→Connected and was able to check table contents, OK
Response using DB -> connection did not work and NG  
Configuration file
build.gradle
Java
plugins {
id 'java'
id 'org.springframework.boot' version '2.7.6'
id 'io.spring.dependency-management' version '1.0.15.RELEASE'
}
group = 'com.example'
version = '0.0.1-SNAPSHOT'
sourceCompatibility = '11'
configurations {
compileOnly {
extendsFrom annotationProcessor
}
}
repositories {
mavenCentral()
}
dependencies {
// implementation 'org.springframework.boot:spring-boot-starter-security'
// implementation 'org.springframework.boot:spring-boot-starter-thymeleaf'
implementation 'org.springframework.boot:spring-boot-starter-web'
// implementation 'org.thymeleaf.extras:thymeleaf-extras-springsecurity5'
compileOnly 'org.projectlombok:lombok'
developmentOnly 'org.springframework.boot:spring-boot-devtools'
annotationProcessor 'org.projectlombok:lombok'
testImplementation 'org.springframework.boot:spring-boot-starter-test'
// testImplementation 'org.springframework.security:spring-security-test'
implementation 'org.mybatis.spring.boot:mybatis-spring-boot-starter:2.3.0'
runtimeOnly 'mysql:mysql-connector-java'
runtimeOnly 'com.google.cloud.sql:mysql-socket-factory-connector-j-8:1.0.15'
}
tasks.named('test') {
useJUnitPlatform()
}
application.properties
database=mysql
spring.datasource.driverClassName=com.mysql.jdbc.Driver
spring.datasource.url=jdbc:mysql://google/<DB-Name>?cloudSqlInstance=<CONNECTION NAME>&socketFactory=com.google.cloud.sql.mysql.SocketFactory
spring.datasource.username=root
spring.datasource.password=<PASSWORD>
error log
2022-12-21 13:49:25.022 ERROR 1576 --- [nio-8080-exec-1] o.a.c.c.C.[.[.[/].[dispatcherServlet] : Servlet.service() for servlet [dispatcherServlet] in context with path [] threw exception [Request processing failed; nested exception is org.mybatis.spring.MyBatisSystemException: nested exception is org.apache.ibatis.exceptions.PersistenceException:
### Error querying database. Cause: org.springframework.jdbc.CannotGetJdbcConnectionException: Failed to obtain JDBC Connection; nested exception is java.sql.SQLException: Access denied for user 'root'#'cloudsqlproxy~192.168.0.5' (using password: YES)

I was able to connect with the following settings.
spring.datasource.driverClassName=com.mysql.cj.jdbc.Driver
spring.datasource.url=jdbc:mysql://CloudSQLIPAddress/DBname
spring.datasource.username=test_user
spring.datasource.password=Password

Related

java.lang.ClassNotFoundException: jakarta.servlet.http.HttpSessionContext with Spring Boot 3 and Jetty server

I community, I'm trying to run a small example with Spring boot 3 and Jetty server before upgrading the production code but I'm getting this error java.lang.ClassNotFoundException: jakarta.servlet.http.HttpSessionContext and the services does not start. This is my Gradle config.
plugins {
id 'java'
id 'idea'
id 'org.springframework.boot' version '3.0.1'
id 'io.spring.dependency-management' version '1.1.0'
}
idea {
module {
downloadJavadoc = false
downloadSources = false
}
}
group = 'com.example'
version = '0.0.1-SNAPSHOT'
sourceCompatibility = '17'
configurations {
compileOnly {
extendsFrom annotationProcessor
}
}
repositories {
mavenCentral()
}
dependencies {
implementation 'org.springframework.boot:spring-boot-starter-security'
implementation 'org.springframework.boot:spring-boot-starter-jetty'
implementation('org.springframework.boot:spring-boot-starter-web') {
exclude group: 'org.springframework.boot', module: 'spring-boot-starter-tomcat'
}
compileOnly 'org.projectlombok:lombok'
annotationProcessor 'org.projectlombok:lombok'
testImplementation 'org.springframework.boot:spring-boot-starter-test'
}
tasks.named('test') {
useJUnitPlatform()
}
and the dependeincies.
HttpSessionContext class no longer exists but somehow, the latest version Jetty still depends on it.
I'm expecting to make it run with Jetty without migrating to another server.
As Jaokim Erdfelt already mentioned, Spring Boot 3 rely on Jakarta Servlet 6.0.0 (see https://github.com/spring-projects/spring-boot/wiki/Spring-Boot-3.0-Release-Notes) and the spring-boot-starter-jetty includes Jetty 11 which is build on Jakarta Servlet 5.0.0 (see https://java.libhunt.com/jetty-project-changelog/11.0.0). So this is an Issue in the starter itself.
To use jetty you have to downgrade the jakarta-servlet version (see https://github.com/spring-projects/spring-boot/wiki/Spring-Boot-3.0-Migration-Guide#jetty) setting
ext["jakarta-servlet.version"] = "5.0.0"
Spring 3 is for Servlet 6 which is available in Jetty 12+

Error creating bean with name org.springframework.boot.autoconfigure.orm.jpa.HibernateJpaConfiguration (Using Gradle)

Building jar file works through the terminal computer path % ./gradlew build, and application runs computer path % java -jar name.jar.
Why not through IntelliJ?
*Secondary Issue -
When I try to upload the jar file built through the terminal to AWS Beanstalk I get a validation error.
*Primary Issue -
The application runs in IntelliJ.
After I have completed the Project Structure setup, and the Build Artifacts execution. The new .jar file fails to run,
throwing the exception below.
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
build.gradle:
plugins {
id 'org.springframework.boot' version '2.6.2'
id 'io.spring.dependency-management' version '1.0.11.RELEASE'
id 'java'
id 'application'
}
group = 'com.example'
version = 'api'
sourceCompatibility = '17'
repositories {
mavenCentral()
}
dependencies {
implementation 'org.springframework.boot:spring-boot-starter-data-jpa'
implementation 'org.springframework.boot:spring-boot-starter-web'
implementation 'org.springframework.boot:spring-boot-starter-validation'
developmentOnly 'org.springframework.boot:spring-boot-devtools'
testImplementation 'org.springframework.boot:spring-boot-starter-test'
runtimeOnly 'mysql:mysql-connector-java'
}
test {
useJUnitPlatform()
}
mainClassName = 'com.example.name.applicationame'
task fatJar(type: Jar) {
bootJar {
launchScript()
}
manifest {
attributes 'Main-Class': "${mainClassName}"
duplicatesStrategy = 'include'
}
archiveBaseName = "name"
from { configurations.compileClasspath.collect { it.isDirectory() ? it : zipTree(it) } }
with jar
}
application.properties:
spring.datasource.url=jdbc:mysql://localhost:3306/name?useSSL=true
spring.datasource.username=root
spring.datasource.password=password
spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver
spring.jpa.database-platform=org.hibernate.dialect.MySQL8Dialect
spring.jpa.hibernate.ddl-auto=update
spring.jpa.hibernate.naming.physical-strategy=org.hibernate.boot.model.naming.PhysicalNamingStrategyStandardImpl
Thanks!

Quarkus - Unsatisfied dependency for type org.eclipse.microprofile.jwt

I was trying to implement the JWT token for one my Quarkus application but somehow getting an exception - Unsatisfied dependency for type org.eclipse.microprofile.jwt.JsonWebToken and qualifiers [#Default]
My Quarkus application is fairly simple and having one rest endpoint -
#Path("/jwt")
#RequestScoped
public class JWTRestController {
#Inject
JsonWebToken jwt;
#GET()
#Path("permit-all")
#PermitAll
#Produces(MediaType.TEXT_PLAIN)
public String hello(#Context SecurityContext ctx) {
Principal caller = ctx.getUserPrincipal();
String name = caller == null ? "anonymous" : caller.getName();
String helloReply = String.format("hello + %s, isSecure: %s, authScheme: %s", name, ctx.isSecure(), ctx.getAuthenticationScheme());
return helloReply;
}
}
But when i try to run my quarkus application -
gradlew quarkusDev
Log stacktrace
> Task :quarkusDev
Port 5005 in use, not starting in debug mode
2020-04-05 15:57:49,789 INFO [org.jbo.threads] (main) JBoss Threads version 3.0.1.Final
2020-04-05 15:57:50,158 ERROR [io.qua.dev.DevModeMain] (main) Failed to start Quarkus: java.lang.RuntimeException: io.quarkus.builder.BuildException: Build failure: Build failed due to errors
[error]: Build step io.quarkus.arc.deployment.ArcProcessor#validate threw an exception: javax.enterprise.inject.spi.DeploymentException: javax.enterprise.inject.UnsatisfiedResolutionException: Unsatisfied dependency for type org.eclipse.microprofile.jwt.JsonWebToken and qual
ifiers [#Default]
- java member: com.jhooq.JWTRestController#jwt
- declared on CLASS bean [types=[com.jhooq.JWTRestController, java.lang.Object], qualifiers=[#Default, #Any], target=com.jhooq.JWTRestController]
at io.quarkus.arc.processor.BeanDeployment.processErrors(BeanDeployment.java:910)
at io.quarkus.arc.processor.BeanDeployment.init(BeanDeployment.java:232)
at io.quarkus.arc.processor.BeanProcessor.initialize(BeanProcessor.java:130)
at io.quarkus.arc.deployment.ArcProcessor.validate(ArcProcessor.java:291)
at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
Am i really missing something here?
Here is my build.gradle
plugins {
id 'java'
id 'io.quarkus'
}
repositories {
mavenLocal()
mavenCentral()
}
dependencies {
implementation enforcedPlatform("${quarkusPlatformGroupId}:${quarkusPlatformArtifactId}:${quarkusPlatformVersion}")
implementation 'io.quarkus:quarkus-resteasy'
testImplementation 'io.quarkus:quarkus-junit5'
testImplementation 'io.rest-assured:rest-assured'
testImplementation 'io.quarkus:quarkus-smallrye-jwt'
testImplementation 'io.quarkus:quarkus-resteasy-jsonb'
implementation 'org.eclipse.microprofile.jwt:microprofile-jwt-auth-api:1.1.1'
}
group 'com.jhooq'
version '1.0.0-SNAPSHOT'
compileJava {
options.compilerArgs << '-parameters'
}
java {
sourceCompatibility = JavaVersion.VERSION_1_8
targetCompatibility = JavaVersion.VERSION_1_8
}
The problem lies here:
testImplementation 'io.quarkus:quarkus-smallrye-jwt'
testImplementation 'io.quarkus:quarkus-resteasy-jsonb'
implementation 'org.eclipse.microprofile.jwt:microprofile-jwt-auth-api:1.1.1'
The quarkus-smallrye-jwt and quarkus-resteasy-jsonb dependencies are part of the application, not part of tests. These must be implementation, not testImplementation.
At the same time, you can remove implementation 'org.eclipse.microprofile.jwt:microprofile-jwt-auth-api:1.1.1', this it's brought in transitively by quarkus-smallrye-jwt.

Cloud client config application do not get properties from Config Server Spring boot

I have a web application and I want to use Server Configuration from Spring Boot.
Both applications are located on localhost machine. I have made first two applications from scratch and they worked together, but when i use the client that has many dependencies in it (not just the cloud-config and web dependency) it is not working anymore. How do I know? I have a variable in properties file in server and i try to use it in my client with #Value("${atena}")
and error appears java.lang.IllegalArgumentException: Could not resolve placeholder 'atena' in value "${atena}".
The following image is my server config application.
The main class from server has the following annotation #EnableConfigServer
In atena-config.yml I have only the variable name:
atena: 'Hellllloooooo'
bootstrap.yml content
server:
port: 9000
spring:
profiles:
active: native
and build.gradle dependencies:
dependencies {
implementation 'org.springframework.cloud:spring-cloud-config-server'
runtimeOnly 'org.springframework.boot:spring-boot-devtools'
testImplementation 'org.springframework.boot:spring-boot-starter-test'
}
I am sure the server it is correct, something is wrong with my client.
--------------------> Client side
I have a restcontroller:
#RestController
#RequestMapping("/songs")
public class SongController {
#Value("${atena}")
String variable;
#GetMapping(value="/check-from")
public String viewVariable(){
return variable;
}
}
in which I am trying to get the variable from server config.
bootstrap.yml from client
spring:
application:
name: atena-config
cloud:
config:
uri: http://localhost:9000
And lastly the build.gradle from client:
plugins {
id 'org.springframework.boot' version '2.1.3.RELEASE'
id 'java'
}
apply plugin: 'io.spring.dependency-management'
group = 'com'
version = '0.0.1-SNAPSHOT'
sourceCompatibility = '1.8'
repositories {
mavenCentral()
}
dependencies {
compile 'com.google.apis:google-api-services-youtube:v3-rev206-1.25.0'
implementation 'org.springframework.boot:spring-boot-starter'
implementation('org.apache.tomcat:tomcat-jdbc:9.0.10')
implementation 'org.springframework.boot:spring-boot-starter-web'
implementation('org.mybatis:mybatis:3.4.6')
implementation('org.mybatis:mybatis-spring:1.3.2')
implementation('org.springframework.boot:spring-boot-starter-jdbc')
implementation('org.springframework.cloud:spring-cloud-starter-config')
compile group: 'org.postgresql', name: 'postgresql', version: '42.2.5'
runtimeOnly 'org.springframework.boot:spring-boot-devtools'
testImplementation 'org.springframework.boot:spring-boot-starter-test'
}
I really don't know what happen, I am pretty sure that these dependencies are the problem, but I have not figured out which one, i can not exclude any of them, because I am using them in project.
Never mind. I have fixed it. Indeed the problem was from my dependencies, my gradle.build was with problem. I have created a new project with spring initializer having all the dependencies and copied the new gradle.build from there and now is it working.
This is the new build.gradle from client
plugins {
id 'org.springframework.boot' version '2.1.3.RELEASE'
id 'java'
}
apply plugin: 'io.spring.dependency-management'
group = 'com'
version = '0.0.1-SNAPSHOT'
sourceCompatibility = '1.8'
repositories {
mavenCentral()
maven { url 'https://repo.spring.io/milestone' }
}
ext {
set('springCloudVersion', 'Greenwich.RELEASE')
}
dependencies {
compile 'com.google.apis:google-api-services-youtube:v3-rev206-1.25.0'
implementation 'org.springframework.boot:spring-boot-starter-web'
implementation 'org.mybatis.spring.boot:mybatis-spring-boot-starter:2.0.0'
implementation 'org.springframework.cloud:spring-cloud-starter-config'
runtimeOnly 'org.springframework.boot:spring-boot-devtools'
runtimeOnly 'org.postgresql:postgresql'
testImplementation 'org.springframework.boot:spring-boot-starter-test'
}
dependencyManagement {
imports {
mavenBom "org.springframework.cloud:spring-cloud-dependencies:${springCloudVersion}"
}
}

java.lang.IllegalStateException: Error processing condition on org.springframework.boot.autoconfigure.jdbc.JndiDataSourceAutoConfiguration

I am trying to write a standalone executable jar (fat jar) . I am using spring boot gradle plugin and writing a SpringBoot App to do this.
Here is my Application.java file
#Configuration
#EnableAutoConfiguration
#EnableRabbit
#EntityScan("persistence.domain")
#EnableJpaRepositories("persistence.repository")
#ComponentScan(basePackages = {"common","service"})
public class Application {
public static void main(final String[] args) {
final SpringApplicationBuilder appBuilder = new SpringApplicationBuilder(
Application.class);
appBuilder.profiles("common", "common_db").run(args);
}
#Bean
#Primary
#ConfigurationProperties(prefix = "spring.datasource")
public DataSource primaryDataSource() {
return DataSourceBuilder.create().build();
}
}
I have specified properties in yml files. For ex application-common etc . While running Application.java I am getting error :
[2015-09-24 14:40:22.304] boot - 32791 INFO [main] ---AnnotationConfigEmbeddedWebApplicationContext: Refreshing org.springframework.boot.context.embedded.AnnotationConfigEmbeddedWebApplicationContext#51a282af: startup date [Thu Sep 24 14:40:22 IST 2015]; root of context hierarchy
[2015-09-24 14:40:23.194] boot - 32791 WARN [main] --- AnnotationConfigEmbeddedWebApplicationContext: Exception encountered during context initialization - cancelling refresh attempt
org.springframework.beans.factory.BeanDefinitionStoreException: Failed to load bean class: ; nested exception is java.lang.IllegalStateException: Error processing condition on org.springframework.boot.autoconfigure.jdbc.JndiDataSourceAutoConfiguration
at org.springframework.context.annotation.ConfigurationClassParser.processDeferredImportSelectors(ConfigurationClassParser.java:392)
at org.springframework.context.annotation.ConfigurationClassParser.parse(ConfigurationClassParser.java:165)
at org.springframework.context.annotation.ConfigurationClassPostProcessor.processConfigBeanDefinitions(ConfigurationClassPostProcessor.java:305)
at org.springframework.context.annotation.ConfigurationClassPostProcessor.postProcessBeanDefinitionRegistry(ConfigurationClassPostProcessor.java:243)
at org.springframework.context.support.PostProcessorRegistrationDelegate.invokeBeanDefinitionRegistryPostProcessors(PostProcessorRegistrationDelegate.java:254)
at org.springframework.context.support.PostProcessorRegistrationDelegate.invokeBeanFactoryPostProcessors(PostProcessorRegistrationDelegate.java:94)
at org.springframework.context.support.AbstractApplicationContext.invokeBeanFactoryPostProcessors(AbstractApplicationContext.java:611)
at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:464)
at org.springframework.boot.context.embedded.EmbeddedWebApplicationContext.refresh(EmbeddedWebApplicationContext.java:109)
at org.springframework.boot.SpringApplication.refresh(SpringApplication.java:691)
at org.springframework.boot.SpringApplication.run(SpringApplication.java:320)
at org.springframework.boot.builder.SpringApplicationBuilder.run(SpringApplicationBuilder.java:142)
at storm.Application.main(Application.java:28)
Caused by: java.lang.IllegalStateException: Error processing condition on org.springframework.boot.autoconfigure.jdbc.JndiDataSourceAutoConfiguration
at org.springframework.boot.autoconfigure.condition.SpringBootCondition.matches(SpringBootCondition.java:58)
at org.springframework.context.annotation.ConditionEvaluator.shouldSkip(ConditionEvaluator.java:92)
at org.springframework.context.annotation.ConfigurationClassParser.processConfigurationClass(ConfigurationClassParser.java:190)
at org.springframework.context.annotation.ConfigurationClassParser.processImports(ConfigurationClassParser.java:435)
at org.springframework.context.annotation.ConfigurationClassParser.processDeferredImportSelectors(ConfigurationClassParser.java:389)
... 12 more
Caused by: java.lang.NullPointerException
at org.springframework.boot.autoconfigure.condition.OnPropertyCondition.getMatchOutcome(OnPropertyCondition.java:61)
at org.springframework.boot.autoconfigure.condition.SpringBootCondition.matches(SpringBootCondition.java:45)
... 16 more
Here is my build.gradle
def projects= [
":common",
":persistence",
":adapter"
]
buildscript {
repositories {
mavenCentral()
maven { url 'http://repo.spring.io/snapshot' }
maven { url 'http://repo.spring.io/milestone' }
}
dependencies { classpath group: 'org.springframework.boot', name: 'spring-boot-gradle-plugin', version: springBootVersion }
}
apply plugin: 'spring-boot'
apply plugin: 'maven-publish'
apply from: "${rootDir}/deployTasks.gradle"
springBoot {
mainClass = "storm.Application"
}
dependencies {
compile project(':common')
compile project(':adapter')
compile project(':persistence')
compile group: 'org.springframework.boot', name: 'spring-boot-starter-actuator', version: '1.1.8.RELEASE'
compile group : 'org.springframework.boot',name: 'spring-boot-autoconfigure', version : '1.1.8.RELEASE'
compile group: 'org.springframework.boot', name: 'spring-boot-starter-data-jpa', version: '1.1.8.RELEASE'
}
Database specification as in application-common_db.yml
database:
host: localhost
port: 3306
schema: subscriptions
username: root
password: root
autoconnect:
maxReconnects: 3
initialTimeout: 2
timeout:
connectTimeout: 0
socketTimeout: 0
failover:
host: localhost
port: 3306
queriesBeforeRetryMaster: 50
secondsBeforeRetryMaster: 30
spring:
datasource:
driverClassName: com.mysql.jdbc.Driver
url: jdbc:mysql://${database.host}:${database.port},${database.failover.host}:${database.failover.port}/${database.schema}?${database.properties}
username: ${database.username}
password: ${database.password}
continueOnError: true
initialize: false
initialSize: 0
timeBetweenEvictionRunsMillis: 5000
minEvictableIdleTimeMillis: 5000
removeAbandonedTimeout: 60
removeAbandoned: true
minIdle: 0
I am not sure how to resolve this error . Can nybody suggest what is going wrong here and why am i getting nullPointerException.
Help is appreciated .
Thanks
This is caused by non-matching Spring Boot dependencies. Check your classpath to find the offending resources. You have explicitly included version 1.1.8.RELEASE, but you have also included 3 other projects. Those likely contain different Spring Boot versions, leading to this error.
I know this is quite an old one, but I faced similar issue and resolved it in a different way. The actuator-autoconfigure pom somehow was invalid and so it was throwing IllegalStateException. I removed the actuator* dependencies from my maven repo and did a Maven update in eclipse, which then downloaded the correct/valid dependencies and resolved my issue.
In my case I had created a SB app from the SB Initializer and had included a fair number of deps in it to other things. I went in and commented out the refs to them in the build.gradle file and so was left with:
implementation 'org.springframework.boot:spring-boot-starter-hateoas'
compileOnly 'org.projectlombok:lombok'
developmentOnly 'org.springframework.boot:spring-boot-devtools'
runtimeOnly 'org.hsqldb:hsqldb'
runtimeOnly 'org.postgresql:postgresql'
annotationProcessor 'org.springframework.boot:spring-boot-configuration-processor'
annotationProcessor 'org.projectlombok:lombok'
testImplementation 'org.springframework.boot:spring-boot-starter-test'
testImplementation 'org.springframework.restdocs:spring-restdocs-mockmvc'
as deps. Then my bare-bones SB app was able to build and get running successfully. As I go to try to do things that may need those commented-out libs I will add them back and see what breaks.
This error is because of multiple projects having the offending resources.
Try out adding the dependencies projects another way around. (like in pom.xml or external dependencies)
I had the same its because of hibernate-core version issue when you remove the version so it resolve the problem you should try it.
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-core</artifactId>
<version>4.1.4.Final</version>
</dependency>
If it's a new project, make sure you remembered to add spring starter web dependency
I had the same its because of version incompatibility check for version or remove version if using spring boot

Resources