Error while Deployment of spring application on JBoss - mysql

When I am trying to run my application on jboss, I am getting following stack trace, My application needs database connection at the start of application I am using hibernate, spring integration and my database is mysql. my database details correct. is there anything I am missing ?
2017-01-06 12:12:23,933 ERROR [org.jboss.msc.service.fail] (ServerService Thread Pool -- 70) MSC000001:
Failed to start service jboss.undertow.deployment.default-server.default-host./ZealWay:
org.jboss.msc.service.StartException in service jboss.undertow.deployment.default-server.default-host./ZealWay:
java.lang.RuntimeException: org.springframework.beans.factory.UnsatisfiedDependencyException:
Error creating bean with name 'webController': Unsatisfied dependency expressed through field 'transactionManagerService':
Error creating bean with name 'transactionManagerServiceImpl': Unsatisfied dependency expressed through field 'gatewayFacade':
Error creating bean with name 'gatewayFacade': Unsatisfied dependency expressed through field 'gatewayRouter':
Error creating bean with name 'gatewayRouterImpl': Unsatisfied dependency expressed through field 'gatewayAquirers':
Error creating bean with name 'gatewayAquirers' defined in class path resource [com/iz/zw/configuration/GatewayAquirerConfig.class]:
Bean instantiation via factory method failed; nested exception is org.springframework.beans.BeanInstantiationException:
Failed to instantiate [java.util.HashMap]: Factory method 'gatewayAquirers' threw exception;
nested exception is org.springframework.transaction.CannotCreateTransactionException: Could not open Hibernate Session for transaction;
nested exception is org.hibernate.exception.GenericJDBCException: Unable to acquire JDBC Connection;
Datasource configuration code
#Bean
public DataSource dataSource() throws IllegalStateException, PropertyVetoException {
ComboPooledDataSource dataSource = new ComboPooledDataSource();
dataSource.setDriverClass(environment.getRequiredProperty("jdbc.driverClassName"));
dataSource.setJdbcUrl(environment.getRequiredProperty("jdbc.url"));
dataSource.setUser(environment.getRequiredProperty("jdbc.username"));
dataSource.setPassword(environment.getRequiredProperty("jdbc.password"));
dataSource.setInitialPoolSize(Integer.parseInt(environment.getProperty("jdbc.initial.pool.size")));
dataSource.setMinPoolSize(Integer.parseInt(environment.getProperty("jdbc.min.pool.size")));
dataSource.setMaxPoolSize(Integer.parseInt(environment.getProperty("jdbc.max.pool.size")));
return dataSource;
}

In your GatewayAquirerConfig you have not defined the bean gatewayAquirers. You probably have:
#Autowired
GatewayAquirers gatewayAquirers;
Somewhere but GatewayAquirers does not have a #Component or #Service or is not being picked up in the package scan.

Related

Failed to connect jira api: failed to access class BasicHttpCache from class CachingHttpAsyncClient

I faced an issue durring connecting to jira api by existing code on ear application using application server wildfly19.0.1.Final :
1- the added code :
AsynchronousJiraRestClientFactory factory = new AsynchronousJiraRestClientFactory();
IssueRestClient client= factory.createWithBasicHttpAuthentication(URI.create("https://jiralink.com"), "username", "password");
dependencies
org.apache.httpcomponents:httpasyncclient-cache:4.1.4
org.apache.httpcomponents:httpclient-cache:4.5.5
the issue:
Caused by: java.lang.IllegalAccessError: failed to access class org.apache.http.impl.client.cache.BasicHttpCache from class org.apache.http.impl.client.cache.CachingHttpAsyncClient (org.apache.http.impl.client.cache.BasicHttpCache is in unnamed module of loader 'deployment.MegaPack.ear.httpclient-cache-4.5.5.jar' #51bff63e; org.apache.http.impl.client.cache.CachingHttpAsyncClient is in unnamed module of loader 'deployment.MegaPack.ear.httpasyncclient-cache-4.1.4.jar' #1746dc55) at org.apache.http.impl.client.cache.CachingHttpAsyncClient.(CachingHttpAsyncClient.java:174) ~[httpasyncclient-cache-4.1.4.jar:4.1.4] at com.atlassian.httpclient.apache.httpcomponents.ApacheAsyncHttpClient.

Pooling Profile Errors in Mule FTP 1.4.1 Connector

I'm using an FTP connector to read a CSV file. The application is an example app out of Exchange at ftp.devrel.mulesoft.com.
It all works fine when the "Pooling profile" in the FTP Config is set to "use default connection pool configuration". Test Connection returns successfully.
If I change the "Pool profile" to Edit inline, and keep all default settings, the connection test fails with the following error:
org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'FTP_Config':
Cannot create inner bean '(inner bean)#3393fd09' of type [org.mule.runtime.module.extension.internal.config.dsl.connection.ConnectionProviderObjectFactory$$EnhancerByCGLIB$$fc09cb67] while setting bean property 'connectionProviderResolver';
nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name '(inner bean)#3393fd09': Cannot create inner bean '(inner bean)#52e62e2e' of type [org.mule.runtime.api.config.PoolingProfile] while setting bean property 'poolingProfile';
nested exception is org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name '(inner bean)#52e62e2e': Unsatisfied dependency expressed through constructor parameter 3: Could not convert argument value of type [null] to required type [int]: Failed to convert value of type 'null' to required type 'int';
nested exception is java.lang.IllegalArgumentException: Cannot convert value of type 'null' to required type 'int': PropertyEditor [org.springframework.beans.propertyeditors.CustomNumberEditor] returned inappropriate value of type 'null'
org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'FTP_Config': Cannot create inner bean '(inner bean)#3393fd09' of type [org.mule.runtime.module.extension.internal.config.dsl.connection.ConnectionProviderObjectFactory$$EnhancerByCGLIB$$fc09cb67] while setting bean property 'connectionProviderResolver';
nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name '(inner bean)#3393fd09': Cannot create inner bean '(inner bean)#52e62e2e' of type [org.mule.runtime.api.config.PoolingProfile] while setting bean property 'poolingProfile';
nested exception is org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name '(inner bean)#52e62e2e': Unsatisfied dependency expressed through constructor parameter 3: Could not convert argument value of type [null] to required type [int]: Failed to convert value of type 'null' to required type 'int';
nested exception is java.lang.IllegalArgumentException: Cannot convert value of type 'null' to required type 'int': PropertyEditor [org.springframework.beans.propertyeditors.CustomNumberEditor] returned inappropriate value of type 'null'
at

Spring retry connection until datasource is available

I have a docker-compose setup to start my SpringBoot application and a MySQL database. If the database starts first, then my application can connect successfully. But if my application starts first, no database exists yet, so the application throws the following exception and exits:
app_1 | 2018-05-27 14:15:03.415 INFO 1 --- [ main]
com.zaxxer.hikari.HikariDataSource : HikariPool-1 - Starting...
app_1 | 2018-05-27 14:15:06.770 ERROR 1 --- [ main]
com.zaxxer.hikari.pool.HikariPool : HikariPool-1 - Exception during pool initialization
app_1 | com.mysql.jdbc.exceptions.jdbc4.CommunicationsException:
Communications link failure
I could edit my docker-compose file to make sure the database is always up before the application starts up, but I want the application to be able to handle this case on its own, and not immediately exit when it cannot reach the database address.
There are ways to configure the datasource in the application.properties file to make the application reconnect to the database, as answered here and here. But that doesn't work for a startup connection to the datasource.
How can I make my SpringBoot application retry the connection at startup to the database at a given interval until it successfully connects to the database?
Set HikariCP's initializationFailTimeout property to 0 (zero), or a negative number. As documented here:
⌚initializationFailTimeout
This property controls whether the pool will "fail fast" if the pool cannot be seeded with an initial connection successfully. Any positive number is taken to be the number of milliseconds to attempt to acquire an initial connection; the application thread will be blocked during this period. If a connection cannot be acquired before this timeout occurs, an exception will be thrown. This timeout is applied after the connectionTimeout period. If the value is zero (0), HikariCP will attempt to obtain and validate a connection. If a connection is obtained, but fails validation, an exception will be thrown and the pool not started. However, if a connection cannot be obtained, the pool will start, but later efforts to obtain a connection may fail. A value less than zero will bypass any initial connection attempt, and the pool will start immediately while trying to obtain connections in the background. Consequently, later efforts to obtain a connection may fail. Default: 1
There is an alternative way to do this, which doesn't rely on a specific Connection Pool library or a specific database. Note that you will need to use spring-retry to achieve the desired behaviour with this approach
First you need to add spring-retry to your dependencies :
<dependency>
<groupId>org.springframework.retry</groupId>
<artifactId>spring-retry</artifactId>
<version>${spring-retry.version}</version>
</dependency>
Then you can create a decorator over DataSource that will extends AbstractDataSource like bellow :
#Slf4j
#RequiredArgsConstructor
public class RetryableDataSource extends AbstractDataSource {
private final DataSource dataSource;
#Override
#Retryable(maxAttempts = 5, backoff = #Backoff(multiplier = 1.3, maxDelay = 10000))
public Connection getConnection() throws SQLException {
log.info("getting connection ...");
return dataSource.getConnection();
}
#Override
#Retryable(maxAttempts = 5, backoff = #Backoff(multiplier = 2.3, maxDelay = 10000))
public Connection getConnection(String username, String password) throws SQLException {
log.info("getting connection by username and password ...");
return dataSource.getConnection(username, password);
}
}
Then you will need to inject this custom DataSource decorator into Spring context by creating a custom BeanPostProcessor :
#Slf4j
#Order(value = Ordered.HIGHEST_PRECEDENCE)
#Component
public class RetryableDatabasePostProcessor implements BeanPostProcessor {
#Override
public Object postProcessBeforeInitialization(Object bean, String beanName) throws BeansException {
if(bean instanceof DataSource) {
log.info("-----> configuring a retryable datasource for beanName = {}", beanName);
return new RetryableDataSource((DataSource) bean);
}
return bean;
}
#Override
public Object postProcessAfterInitialization(Object bean, String beanName) throws BeansException {
return bean;
}
}
Last but not least you will need to enable Spring retry by adding #EnableRetry annotation to spring main class, example :
#EnableRetry
#SpringBootApplication
public class RetryableDbConnectionApplication {
public static void main(String[] args) {
SpringApplication.run(RetryableDbConnectionApplication.class, args);
}
}

Problems customizing SendErrorFilter

The Spring Cloud Netflix documentation states that the default forwarding path (/error) for SendErrorFilter can be changed by setting the error.path property. When I do this, I encounter the following error:
org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'requestMappingHandlerMapping' defined in class path resource [org/springframework/boot/autoconfigure/web/WebMvcAutoConfiguration$EnableWebMvcConfiguration.class]: Invocation of init method failed; nested exception is java.lang.IllegalStateException: Ambiguous mapping. Cannot map 'basicErrorController' method
public org.springframework.http.ResponseEntity> org.springframework.boot.autoconfigure.web.BasicErrorController.error(javax.servlet.http.HttpServletRequest)
to {[/proxyServiceError]}: There is already 'proxyServiceErrorController' bean method
public org.springframework.http.ResponseEntity com.acme.controller.ProxyServiceErrorController.error(javax.servlet.http.HttpServletRequest) mapped.
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.initializeBean(AbstractAutowireCapableBeanFactory.java:1628)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:555)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:483)
at org.springframework.beans.factory.support.AbstractBeanFactory$1.getObject(AbstractBeanFactory.java:306)
at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:230)
at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:302)
at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:197)
at org.springframework.beans.factory.support.DefaultListableBeanFactory.preInstantiateSingletons(DefaultListableBeanFactory.java:761)
at org.springframework.context.support.AbstractApplicationContext.finishBeanFactoryInitialization(AbstractApplicationContext.java:866)
at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:542)
at org.springframework.boot.context.embedded.EmbeddedWebApplicationContext.refresh(EmbeddedWebApplicationContext.java:122)
at org.springframework.boot.SpringApplication.refresh(SpringApplication.java:737)
at org.springframework.boot.SpringApplication.refreshContext(SpringApplication.java:370)
at org.springframework.boot.SpringApplication.run(SpringApplication.java:314)
at org.springframework.boot.SpringApplication.run(SpringApplication.java:1162)
at org.springframework.boot.SpringApplication.run(SpringApplication.java:1151)
at com.acme.service.ProxyServiceBootstrap.main(ProxyServiceBootstrap.java:25)
I modeled my error controller off of BasicErrorController. What am I missing?
Your ProxyServiceErrorController must implement org.springframework.boot.autoconfigure.web.ErrorController. In spring boot, BasicErrorController will not be registered only if there is already an implementation of ErrorController.
Spring boot source
Changing error.path will also affect BasicErrorController. BasicErrorController and your ProxyServiceErrorController are trying to register controllers on the same path - /proxyServiceError now.

How to configure cloud datasource for MySQL on Bluemix?

How do I create a datasource for cloud in MySQL when running on Bluemix? If there are any Java configuration examples available, please share. How do I make Hibernate create tables and why do I get this error?
Error creating bean with name 'entityManagerFactory' defined in
com.covenant.app.config.root.DatabaseConfig: Unsatisfied dependency
expressed through constructor argument with index 0 of type
[org.springframework.jdbc.datasource.DriverManagerDataSource]: : No
qualifying bean of type
[org.springframework.jdbc.datasource.DriverManagerDataSource] found
for dependency: expected at least 1 bean which qualifies as autowire
candidate for this dependency. Dependency annotations: {}; nested
exception is
org.springframework.beans.factory.NoSuchBeanDefinitionException: No
qualifying bean of type
[org.springframework.jdbc.datasource.DriverManagerDataSource] found
for dependency: expected at least 1 bean which qualifies as autowire
candidate for this dependency. Dependency annotations: {}
My database Config class
#Configuration
#Profile("cloud")
#EnableTransactionManagement
public class CloudDatabaseConfig extends AbstractCloudConfig {
#Bean
public DataSource inventoryDataSource() {
return connectionFactory().dataSource("mysql");
}
#Bean(name = "namingStrategy")
public ImprovedNamingStrategy getNamingStrategy(){
ImprovedNamingStrategy namingStrategy = new CDCustomNamingStrategy();
return namingStrategy;
}
#Bean(name="dataSource")
public BasicDataSource dataSource() throws PropertyVetoException {
BasicDataSource bean = new BasicDataSource();
bean.setDriverClassName("com.mysql.jdbc.Driver");
bean.setUrl("jdbc:mysql://localhost:3306/bluemix?useUnicode=true&characterEncoding=UTF-8");
bean.setUsername("root");
bean.setPassword("root");
return bean;
}
#Bean(name = "entityManagerFactory")
public LocalContainerEntityManagerFactoryBean entityManagerFactory(DataSource dataSource, ImprovedNamingStrategy ins) {
LocalContainerEntityManagerFactoryBean entityManagerFactoryBean = new LocalContainerEntityManagerFactoryBean();
entityManagerFactoryBean.setDataSource(dataSource);
entityManagerFactoryBean.setPackagesToScan(new String[]{"com.covenant.app.model"});
entityManagerFactoryBean.setLoadTimeWeaver(new InstrumentationLoadTimeWeaver());
entityManagerFactoryBean.setJpaVendorAdapter(new HibernateJpaVendorAdapter());
Map<String, Object> jpaProperties = new HashMap<String, Object>();
jpaProperties.put("database", "mysql");
jpaProperties.put("hibernate.hbm2ddl.auto", "update");
jpaProperties.put("hibernate.show_sql", "true");
jpaProperties.put("hibernate.format_sql", "true");
jpaProperties.put("hibernate.use_sql_comments", "true");
jpaProperties.put("hibernate.dialect", "org.hibernate.dialect.MySQLDialect");
jpaProperties.put("hibernate.ejb.naming_strategy", ins);
entityManagerFactoryBean.setJpaPropertyMap(jpaProperties);
return entityManagerFactoryBean;
}
}
My manifest.yml file on Bluemix:
---
applications:
- name: lordthankyou
path: target/ideals.war
services:
- mysql
env:
SPRING_PROFILES_ACTIVE: cloud
I get the following errors:
Error creating bean with name 'userService': Injection of autowired
dependencies failed; nested exception is
org.springframework.beans.factory.BeanCreationException: Could not
autowire field: private com.covenant.app.dao.UserRepository
com.covenant.app.services.UserService.userRepository; nested exception
is org.springframework.beans.factory.BeanCreationException: Error
creating bean with name 'userRepository': Injection of persistence
dependencies failed; nested exception is
org.springframework.beans.factory.NoSuchBeanDefinitionException: No
qualifying bean of type [javax.persistence.EntityManagerFactory] is
defined
Finally I got It working I just added an environment variable to activate cloud profile in manifest.yml and removed extends AbstractCloudConfig as it was also searching for mongodb .After these changes It Started working and now I can run spring mvc on blue mix.