Spring Boot and Tomcat not finding JNDI resources - java

I'm using Spring Boot 1.4.2.RELEASE. I'm also using Tomcat 8.5.9 (NOT embedded) and Java 8.
In my application.properties file, I can manually configure my datasource using:
spring.datasource.url = jdbc:as400://blahblah....
spring.datasource.username = myuser
spring.datasource.password = password
spring.datasource.driver-class-name=com.ibm.as400.access.AS400JDBCDriver
This works just fine. But, we use Tomcat to host our connections. In Tomcat, we have:
<GlobalNamingResources>
<Resource name="jdbc/BLAH" ..... />
</GlobalNamingResources>
So I then changed application.properties to:
spring.datasource.jndi-name=java:comp/env/jdbc/BLAH
spring.jpa.database-platform=org.hibernate.dialect.DB2400Dialect
spring.jpa.show-sql=true
Now, I can't even build the application. I get the following exception:
o.s.w.c.s.GenericWebApplicationContext :
Exception encountered during context initialization - cancelling refresh attempt: org.springframework.beans.factory.UnsatisfiedDependencyException:
Error creating bean with name 'org.springframework.boot.autoconfigure.orm.jpa.HibernateJpaAutoConfiguration':
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/JndiDataSourceAutoConfiguration.class]:
Bean instantiation via factory method failed;
nested exception is org.springframework.beans.BeanInstantiationException:
Failed to instantiate [javax.sql.DataSource]:
Factory method 'dataSource' threw exception; nested exception is
org.springframework.jdbc.datasource.lookup.DataSourceLookupFailureException:
Failed to look up JNDI DataSource with name 'java:comp/env/jdbc/BLAH';
nested exception is javax.naming.NoInitialContextException:
Need to specify class name in environment or system property, or as an applet parameter,
or in an application resource file: java.naming.factory.initial
The NoInitialContextException leads me to believe that Spring Boot cannot find Tomcat running so it can't perform a JNDI lookup.
Keep in mind, the exact same setup worked for us using Spring Boot 1.2.5.RELEASE. We have another app that uses 1.2.5.RELEASE, Java 7 and Tomcat 7 and it works using JNDI resources. But using the newest Spring Boot, Java 8 and Tomcat 8 doesn't.
Any help is appreciated.
Some snippets from my pom.xml:
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>1.4.2.RELEASE</version>
<relativePath/>
</parent>
...
<dependencies>
<dependency>
<groupId>net.sf.jt400</groupId>
<artifactId>jt400</artifactId>
<version>6.7</version>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>com.vaadin</groupId>
<artifactId>vaadin-spring-boot-starter</artifactId>
<version>1.1.1</version>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-jpa</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-tomcat</artifactId>
<scope>provided</scope>
</dependency>
....
</dependencies>
Other code snippets:
#SpringBootApplication
public class MyApplication {
public static void main(String[] args) {
SpringApplication.run(MyApplication.class, args);
}
}
#SpringBootConfiguration
#EnableAutoConfiguration
#ComponentScan(basePackages = "com.company.myapp")
#EnableJpaRepositories(basePackages = "com.company.myapp.repository")
#EnableTransactionManagement
#EnableVaadin
#EnableVaadinServlet
public class AppConfiguration {
}
UPDATE
I've created the resources within Tomcat (external) using the GlobalNamingResources in our server.xml.
This works for other applications.
UPDATE 2
Forgot to mention that I have the following in a src/main/webapp/META-INF/context.xml file:
<?xml version="1.0" encoding="UTF-8"?>
<Context>
<ResourceLink global="jdbc/BLAH"
name="jdbc/BLAH"
type="com.mchange.v2.c3p0.ComboPooledDataSource"/>
</Context>
UPDATE 3
Also, I want to make it clear the problem happens during the maven package step.

If you are deploying on a standalone Tomcat (Not embedded), I'm fairly sure you need to define your JNDI resources on the Tomcat and not in application.properties, but in server.xml like this:
<GlobalNamingResources>
<Resource name="jdbc/serverdb" auth="Container" type="javax.sql.DataSource"
maxTotal="5" maxIdle="5" maxWaitMillis="30000"
validationQuery="select 1" testOnBorrow="true"
username="$AUTH_DB_USER" password="$AUTH_DB_PASSWORD" driverClassName="org.postgresql.Driver"
url="jdbc:postgresql://$AUTH_DB_HOST:5432/$AUTH_DB_NAME"/>
</GlobalNamingResources>

Related

Failed to determine a suitable driver class in CMD

Im developing spring boot Rest API, application,
In my VS code application is running without any runtime errors and working with postman too,
VS code runtime output
enter image description here
however, when i export the JAR file via VS code, and try to run cmd, that file pop up run time error,
ERROR
Blockquote
enter image description here
Blockquote
Error Msg in cmd
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
My POM XML
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-jpa</artifactId>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<scope>runtime</scope>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.springframework.security</groupId>
<artifactId>spring-security-test</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-tomcat</artifactId>
</dependency>
application.properties
## Server Properties
server.port= 8083
server.servlet.context-path= /TEST-API
spring.datasource.url= jdbc:mysql://localhost:3306/TEST?useSSL=false&useLegacyDatetimeCode=false&zerodatetimebehavior=Converttonull
spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver
spring.datasource.username= root
spring.datasource.password= 1234
spring.datasource.testWhileIdle = true
spring.datasource.timeBetweenEvictionRunsMillis = 60000
spring.datasource.validationQuery = SELECT 1
Could you please help me on this?
Option 1
Try use
spring.datasource.driver-class-name=com.mysql.jdbc.Driver
instead of
spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver
in your properties file, if you are using mysql version < 8
Option 2
Check if your driver of mysql (JAR file) was included in the library of WAR --> WEB-INF/lib.
Option 3
If you are not fix it yet, and you have other database in your machine like a postgres:
change this connection to this another database.
test inside of your editor/ide
export to war
if the problem happens the same way, you can be right that your export process is the problem. So try use the plugin of maven to generate the war: https://maven.apache.org/plugins/maven-war-plugin/usage.html
Thanks for your support
one of my friends help me to fix the issue
what they did is,
delete mvnw file from the project path.
Then paste apache-maven-3.6.0 in to C driver and then
did the maven install and package the project in vs code.
After that project jar generated.

Caused by: java.lang.IllegalArgumentException: jdbcUrl is required with driverClassName

My spring boot test is throwing the below error during maven build.
"level":"ERROR","logger":"com.zaxxer.hikari.HikariConfig","msg":"HikariPool-1 - jdbcUrl is required with driverClassName."
Stacktrace:
Caused by: org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'schedulerFactoryBean' defined in class path resource
[com/pit/SchedulerConfig.class]: Invocation of init method failed; nested exception is java.lang.IllegalArgumentException: jdbcUrl is requir
ed with driverClassName.
Caused by: java.lang.IllegalArgumentException: jdbcUrl is required with driverClassName.
The method that throws an error in my MyApplicationTest.java
#SpringBootTest
#EnableAutoConfiguration(exclude = { DataSourceAutoConfiguration.class,
DataSourceTransactionManagerAutoConfiguration.class, HibernateJpaAutoConfiguration.class })
#EnableConfigurationProperties(value = MyConfig.class)
class MyApplicationTest {
#Test
void contextLoads() {
assertNotNull(myController);
}
}
My pom has these dependencies in classpath.
spring-boot-starter-web
spring-boot-starter-test
spring-integration-sftp
postgresql
junit
quartz-scheduler
My Datasource bean is configured as below
#Configuration
public class MyDataSourceCfg {
private DataSource appDataSource() {
return DataSourceBuilder.create()
.driverClassName("org.postgresql.Driver")
.url(env.getProperty("url") // values are set from Environment
.username(env.getProperty("user"))
.password(env.getProperty("password")
.build();
}
}
Please tell me what is happening and how I avoid this error. I read about configuring Datasource in different way in case you have multiple database but I just have one postgres database. Please share your thoughts.
Considering that you have all relevant dependencies.
as Connect to PostgreSQL Database with Spring Data JPA such as :-
<dependency>
<groupId>org.postgresql</groupId>
<artifactId>postgresql</artifactId>
<scope>runtime</scope>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-jpa</artifactId>
</dependency>
and in application.properties file:
spring.datasource.url=jdbc:postgresql://localhost:5432/dev
spring.datasource.username=dbuser
spring.datasource.password=dbpass
spring.datasource.driver-class-name=org.postgresql.Driver
spring.jpa.hibernate.ddl-auto=update
spring.jpa.show-sql=true
spring.jpa.properties.hibernate.format_sql=true
spring.jpa.properties.hibernate.dialect=org.hibernate.dialect.PostgreSQL81Dialect
With SpringBoot's powerful autoconfiguration, you don't need to explicitly create a DataSource bean and if in case you want, use these properties values.

Cannot register spring microservice with netflix eureka

I have the maven spring microservice with main class.
#EnableEncryptableProperties
#SpringBootApplication
#EnableDiscoveryClient
public class AccountService {
private static ApplicationContext applicationContext;
public static void main(String[] args) {
applicationContext = SpringApplication.run(AccountService.class, args);
}
}
In my pom.xml I added following dependencies for registering app.
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-config</artifactId>
<version>2.2.6.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-eureka</artifactId>
<version>1.3.5.RELEASE</version>
</dependency>
During startup I get the following error.
[WARN ] 2021-01-11 22:05:50 [main] AnnotationConfigServletWebServerApplicationContext - Exception encountered during context initialization - cancelling refresh attempt: org.springframework.beans.factory.BeanDefinitionStoreException: Failed to process import candidates for configuration class [com.microservices.accountservice.AccountService]; nested exception is java.io.FileNotFoundException: class path resource [org/springframework/boot/autoconfigure/web/ServerPropertiesAutoConfiguration.class] cannot be opened because it does not exist
[ERROR] 2021-01-11 22:05:50 [main] SpringApplication - Application run failed
org.springframework.beans.factory.BeanDefinitionStoreException: Failed to process import candidates for configuration class [com.microservices.accountservice.AccountService]; nested exception is java.io.FileNotFoundException: class path resource [org/springframework/boot/autoconfigure/web/ServerPropertiesAutoConfiguration.class] cannot be opened because it does not exist
The project has defined the following spring version.
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.2.6.RELEASE</version>
<relativePath/> <!-- lookup parent from repository -->
</parent>
Moreover microservice during startup communicates using bootstrap.properties with spring-cloud-config-server to fetch application.properties. What could be the issue related with this error ?
The dependencies in your pom.xml are not compatible with each other. You should use spring-cloud-starter-netflix-eureka-client:2.2.6.RELEASE.
It is even better if you don't specify the versions for each of your dependencies but you use the BOM (spring-cloud-dependencies), see the official guide.

Error when trying to connect to Azure Eventhub: AzureTokenCredentials / IllegalArgumentException: name

I am following a tutorial on how to setup a connection to Azure EventHub in Spring Boot: [1]
When starting the spring boot app, I get the following error:
2021-01-07 13:37:25.447 WARN 16444 --- [ main] ConfigServletWebServerApplicationContext :
Exception encountered during context initialization - cancelling refresh attempt:
org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name
'resourceManagerProvider' defined in class path resource
[com/microsoft/azure/spring/cloud/autoconfigure/context/AzureContextAutoConfiguration.class]: Unsatisfied
dependency expressed through method 'resourceManagerProvider' parameter 0; nested exception is
org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'azure'
defined in class path resource
[com/microsoft/azure/spring/cloud/autoconfigure/context/AzureContextAutoConfiguration.class]: Unsatisfied
dependency expressed through method 'azure' parameter 0; nested exception is
org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'credentials'
defined in class path resource
[com/microsoft/azure/spring/cloud/autoconfigure/context/AzureContextAutoConfiguration.class]: Bean
instantiation via factory method failed; nested exception is
org.springframework.beans.BeanInstantiationException: Failed to instantiate
[com.microsoft.azure.credentials.AzureTokenCredentials]: Factory method 'credentials' threw exception;
nested exception is java.lang.IllegalArgumentException: name
my.azureauth looks like analogous to the on in [1].
I am using Java 11. Here is the relevant part of my pom:
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>com.microsoft.azure</groupId>
<artifactId>spring-cloud-azure-eventhubs-stream-binder</artifactId>
<version>1.2.7</version>
</dependency>
<dependency>
<groupId>com.microsoft.azure</groupId>
<artifactId>azure-servicebus-jms-spring-boot-starter</artifactId>
<version>2.3.5</version>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
<!-- Workaround. -->
<!-- Apparently com.microsoft.azure:spring-cloud-azure-eventhubs-stream-binder:1.2.7 has a transitive -->
<!-- dependency to the following package. However, it seems that the version is not pinned correctly, so -->
<!-- we have to pin the version to a compatible one as a workaround. -->
<!-- 7.5 is apparently the latest version in which com.nimbusds.oauth2.sdk.http.CommonContentTypes is available. -->
<!-- For a similar (but different) issue see also https://github.com/microsoft/azure-spring-boot/issues/650 -->
<dependency>
<groupId>com.nimbusds</groupId>
<artifactId>oauth2-oidc-sdk</artifactId>
<version>7.5</version>
</dependency>
Note the workaround regarding the dependency com.nimbusds.
I tried navigating to the relevant code. However, for some reason the code of AzureContextAutoConfiguration.credentials
is not available in the disassembled code of my IDE.
Is the version I used in the workaround in my pom.xml appropriate?
Does anyone have an idea what the error means and how to fix it?
Can anyone report, that this tutorial still works?
[1] https://learn.microsoft.com/en-us/azure/developer/java/spring-framework/configure-spring-cloud-stream-binder-java-app-azure-event-hub
So here the root issue is
"Failed to instantiate
[com.microsoft.azure.credentials.AzureTokenCredentials]: Factory method 'credentials' threw exception;
nested exception is java.lang.IllegalArgumentException: name"
I would suggest you to verify your my.azureauth and application.properties files again against the guide.
Also, as the guide suggests, if you're using JDK version 9 or greater (you are using 11 here), add the following dependencies
<dependency>
<groupId>javax.xml.bind</groupId>
<artifactId>jaxb-api</artifactId>
<version>2.3.1</version>
</dependency>
<dependency>
<groupId>org.glassfish.jaxb</groupId>
<artifactId>jaxb-runtime</artifactId>
<version>2.3.1</version>
<scope>runtime</scope>
</dependency>

Spring boot 2 (spring batch app) fails to start. Fails with BeanCreationException: Error creating bean with name 'h2Console'

I am trying to run a Spring Batch app that reads data from a SQL Server DB and writes to a csv file. Below is the DatabaseConfiguration file for the SQL Server DB:-
#Configuration
#EnableTransactionManagement
#EnableJpaRepositories(
basePackages = {"com.sample.repository"},
entityManagerFactoryRef = "sampleEntityManagerFactory",
transactionManagerRef = "transManager"
)
public class CompensationConfiguration
{
#Primary
#Bean(name="cmpnDS")
#ConfigurationProperties(prefix = "sample.datasource.compensation")
public DataSource sampleDataSource() {
return DataSourceBuilder.create().build();
}
#Primary
#Bean(name = "sampleEntityManagerFactory")
public LocalContainerEntityManagerFactoryBean sampleEntityManagerFactory(EntityManagerFactoryBuilder builder,
#Qualifier("cmpnDS") DataSource dataSource) {
return builder
.dataSource(dataSource)
.packages("com.opencodez.entity")
.build();
}
#Primary
#Bean(name = "transManager")
public PlatformTransactionManager hrprdTransactionManager(#Qualifier("sampleEntityManagerFactory")
EntityManagerFactory entityManagerFactoryBean) {
return new JpaTransactionManager(entityManagerFactoryBean);
}
}
Following is a snippet from the pom file:-
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.2.1.RELEASE</version>
<relativePath/> <!-- lookup parent from repository -->
</parent>
<groupId>com.example</groupId>
<artifactId>mybat</artifactId>
<version>0.0.1-SNAPSHOT</version>
<packaging>jar</packaging>
<name>mybat</name>
<description>Demo project for Spring Boot</description>
<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
<java.version>1.8</java.version>
<maven-jar-plugin.version>2.6</maven-jar-plugin.version>
<spring-cloud.version>Hoxton.RC2</spring-cloud.version>
</properties>
<dependency>
<groupId>com.h2database</groupId>
<artifactId>h2</artifactId>
<scope>runtime</scope>
</dependency>
and the following in the properties file:-
spring:
datasource:
url: jdbc:h2:mem:testdb
username: sa
password:
driver-class-name: org.h2.Driver
When I try to launch the app it is failing to start with the below error:-
Caused by: org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'h2Console' defined in class path resource [org/springframework/boot/autoconfigure/h2/H2ConsoleAutoConfiguration.class]: Bean instantiation via factory method failed; nested exception is org.springframework.beans.BeanInstantiationException: Failed to instantiate [org.springframework.boot.web.servlet.ServletRegistrationBean]: Factory method 'h2Console' threw exception; nested exception is java.lang.IllegalArgumentException: dataSource or dataSourceClassName or jdbcUrl is required.
This app reads a SQL Server DB for processing records. The spring batch uses in memory DB H2Database. Is this a multi-datasource scenario? I didn't do any coding for the datasource configuration of H2 as it should be autoconfigured. I have all the required dependencies included in the pom - sprign-batch-core, devtools, h2 database, jpa etc.
I got around this by setting
spring.h2.console.enabled=false
in my spring boot application.properties file.
The doc for that property says that you could get rid of this by instead removing the pom dependency for spring-boot-devtools (detailed here).
You have to delete h2's related jar files in .m2 maven local repository, It's must be corrupted.
After that, you have to run "mvn spring-boot:run" again, Maybe more that one jar was corrupted so check it and reapet recipe (every time you need to run that command after delete that jar).
I created two Datasource Configuration classes, one for each database, and marked the h2 datasource as primary. The app started fine after this change.

Categories