Getting error when running console application on eclipse : SLF4J: Failed to load class "org.slf4j.impl.StaticLoggerBinder" - spring

I am a beginner to Spring MVC, trying to get SLF4j logger to work when running the following app
package com.chris.springdemo;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import org.springframework.stereotype.Component;
import com.chris.springdemo.dao.OrganizationDao;
import com.chris.springdemo.daoimpl.OrganizationDaoImpl;
import com.chris.springdemo.domain.Organization;
#Component
public class LoggingApp {
#Autowired
private OrganizationDao dao;
#Autowired
private DaoUtils daoUtils;
public void actionMethod() {
// Creating seed data
daoUtils.createSeedData(dao);
// List organizations
List<Organization> orgs = dao.getAllOrganizations();
daoUtils.printOrganizations(orgs, daoUtils.readOperation);
// Create a new organization record
Organization org = new Organization("General electric", 1991, "", 28, "Howdy");
boolean isCreated = dao.create(org);
daoUtils.printSuccessFailure(daoUtils.createOperation, isCreated);
daoUtils.printOrganizations(dao.getAllOrganizations(), daoUtils.readOperation);
// Get a single organization
Organization org2 = dao.getOrganization(1);
daoUtils.printOrganization(org2, "getOrganization");
// Updating a slogan for an organization
Organization org3 = dao.getOrganization(2);
org3.setSlogan("We build **awesome** driving machines!");
boolean isUpdated = dao.update(org3);
daoUtils.printSuccessFailure(daoUtils.updateOperation, isUpdated);
daoUtils.printOrganization(dao.getOrganization(2), daoUtils.updateOperation);
// Delete an organization
boolean isDeleted = dao.delete(dao.getOrganization(3));
daoUtils.printSuccessFailure(daoUtils.deleteOperation, isDeleted);
daoUtils.printOrganizations(dao.getAllOrganizations(), daoUtils.deleteOperation);
// Clean up
dao.cleanup();
daoUtils.printOrganizationCount(dao.getAllOrganizations(), daoUtils.cleanupOperation);
}
public static void main(String[] args) {
// creating the application context
ApplicationContext ctx = new ClassPathXmlApplicationContext("beans-cp.xml");
LoggingApp mainApp = ctx.getBean(LoggingApp.class);
mainApp.actionMethod();
// close the application context
((ClassPathXmlApplicationContext) ctx).close();
// Create the bean
// OrganizationDao dao = (OrganizationDao) ctx.getBean("orgDao");
}
}
DaoUtils.java contains log statements with Logger
package com.chris.springdemo;
import java.util.ArrayList;
import java.util.List;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;
import com.chris.springdemo.dao.OrganizationDao;
import com.chris.springdemo.domain.Organization;
#Service
public class DaoUtils {
private static Logger LOGGER = LoggerFactory.getLogger("Logging Tester");
public final String createOperation = "CREATE";
public final String readOperation = "READ";
public final String updateOperation = "UPDATE";
public final String deleteOperation = "DELETE";
public final String cleanupOperation = "TRUNCATE";
public void printOrganizations(List<Organization> orgs, String operation){
LOGGER.info("\n********* printing organizations after " + operation + " operation *********");
for (Organization org : orgs) {
LOGGER.info(org.toString());
}
}
public void printOrganization( Organization org, String operation ) {
LOGGER.info("\n********* printing organization after invoking " + operation + " operation *********\n" + org);
}
public void printSuccessFailure(String operation, boolean param){
if(param)
LOGGER.info("\nOperation " + operation + " successful");
else
LOGGER.info("\nOperation " + operation + " failed");
}
public void createSeedData(OrganizationDao dao){
Organization org1 = new Organization("Amazon", 1994, "65656", 8765, "Work hard, have fun, make history");
Organization org2 = new Organization("BMW", 1929, "45454", 5501, "We build ultimate Driving machines");
Organization org3 = new Organization("Google", 1996, "57575", 4567, "Don't be evil");
List<Organization> orgs = new ArrayList<Organization>();
orgs.add(0, org1); orgs.add(1, org2); orgs.add(2, org3);
//int orgCount = orgs.size();
int createCount = 0;
for(Organization org : orgs){
boolean isCreated = dao.create(org);
if(isCreated)
createCount += 1;
}
LOGGER.info("Created "+ createCount + " organizations");
}
public void printOrganizationCount(List<Organization> orgs, String operation){
LOGGER.info("\n*********Currently we have " + orgs.size()+ " organizations after " + operation + " operation" + " *********");
}
}
My pom.xml is below.
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>com.chris</groupId>
<artifactId>spring-named-jdbc-template-demo-1</artifactId>
<version>0.0.1-SNAPSHOT</version>
<dependencies>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-core</artifactId>
<version>5.0.1.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context</artifactId>
<version>5.0.1.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-beans</artifactId>
<version>5.0.1.RELEASE</version>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>6.0.6</version>
</dependency>
<dependency>
<groupId>commons-dbcp</groupId>
<artifactId>commons-dbcp</artifactId>
<version>1.4</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-jdbc</artifactId>
<version>5.0.1.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-dao</artifactId>
<version>2.0.8</version>
</dependency>
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-api</artifactId>
<version>1.7.25</version>
</dependency>
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-log4j12</artifactId>
<version>1.7.25</version>
<scope>test</scope>
</dependency>
</dependencies>
</project>
When I run the app, I get the following error
SLF4J: Failed to load class "org.slf4j.impl.StaticLoggerBinder".
SLF4J: Defaulting to no-operation (NOP) logger implementation
SLF4J: See http://www.slf4j.org/codes.html#StaticLoggerBinder for further details.
When I click the URL in the error, it tells me
This warning message is reported when the
org.slf4j.impl.StaticLoggerBinder class could not be loaded into
memory. This happens when no appropriate SLF4J binding could be found
on the class path. Placing one (and only one) of slf4j-nop.jar
slf4j-simple.jar, slf4j-log4j12.jar, slf4j-jdk14.jar or
logback-classic.jar on the class path should solve the problem. SINCE
1.6.0 As of SLF4J version 1.6, in the absence of a binding, SLF4J will default to a no-operation (NOP) logger implementation.
But I only have one implementation of SLF4J on my pom.xml which is
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-log4j12</artifactId>
<version>1.7.25</version>
<scope>test</scope>
</dependency>
I deleted all repositories, updated maven project, cleaned the project etc none of this seem to resolve this issue. Would appreciate any help.
Thanks
Cris

Related

#Valid annotation not working on Dto class - Spring Boot

I want validate my CustomerDTO using #Valid annotation.but also being validated at the same time using the #Valid annotation but it doesn't work, please help me.
This is my controller:
import lk.navishka.loginWithSecuruty.dto.CustomerDto;
import lk.navishka.loginWithSecuruty.entity.Customer;
import lk.navishka.loginWithSecuruty.service.CustomerService;
import lk.navishka.loginWithSecuruty.util.StandradResponse;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import javax.validation.Valid;
#RestController
#CrossOrigin
public class CustomerController {
#Autowired
CustomerService customerService;
#RequestMapping(value = {"/register"})
public ResponseEntity saveCustomer(#Valid #RequestBody CustomerDto customer){
customerService.saveCustomer(customer);
StandradResponse success = new StandradResponse(200, "success", null);
return new ResponseEntity(success, HttpStatus.OK);
}
}
this is My CustomerDTO class
import lombok.*;
import javax.persistence.Column;
import javax.validation.constraints.NotNull;
import javax.validation.constraints.Size;
import java.util.ArrayList;
#AllArgsConstructor
#NoArgsConstructor
#Getter
#Setter
#ToString
public class CustomerDto {
#NotNull
#Size(min = 9, message = "Nic have at least 9 characters ")
private String nic;
private String address;
#NotNull
#Size(min = 5, message = "FirstName have at least 5 characters ")
private String firstName;
#NotNull
#Size(min = 5, message = "LastName have at least 5 characters ")
private String lastName;
private ArrayList<UserDto> user = new ArrayList<>();
}
this is my ErrorDetails class
import java.util.Date;
public class ErrorDetails {
private Date timestamp;
private String message;
private String details;
public ErrorDetails(Date timestamp, String message, String details) {
super();
this.timestamp = timestamp;
this.message = message;
this.details = details;
}
public Date getTimestamp() {
return timestamp;
}
public void setTimestamp(Date timestamp) {
this.timestamp = timestamp;
}
public String getMessage() {
return message;
}
public void setMessage(String message) {
this.message = message;
}
public String getDetails() {
return details;
}
public void setDetails(String details) {
this.details = details;
}
}
this my ExceptionHandler class
import lk.navishka.loginWithSecuruty.util.ErrorDetails;
import lk.navishka.loginWithSecuruty.util.StandradResponse;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import java.util.Date;
#ControllerAdvice
public class ExceptionHandler {
//handling custom validation error
#ExceptionHandler(MethodArgumentNotValidException.class)
public ResponseEntity<?> customValidationErrorHandling(MethodArgumentNotValidException exception){
ErrorDetails errorDetails = new ErrorDetails(new Date(),"Validator Error", exception.getBindingResult().getFieldError().getDefaultMessage());
return new ResponseEntity<>(errorDetails, HttpStatus.BAD_REQUEST);
}
}
i use meven this is Pom.xml file
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>lk.navishka</groupId>
<artifactId>LoginWithSecuruty</artifactId>
<version>1.0.0</version>
<packaging>jar</packaging>
<properties>
<maven.compiler.source>1.8</maven.compiler.source>
<maven.compiler.target>1.8</maven.compiler.target>
</properties>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.4.2</version>
</parent>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter</artifactId>
<version>2.4.2</version>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
<version>2.4.2</version>
</dependency>
<!-- https://mvnrepository.com/artifact/org.springframework.boot/spring-boot-starter-data-jpa -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-jpa</artifactId>
<version>2.4.2</version>
</dependency>
<!-- https://mvnrepository.com/artifact/mysql/mysql-connector-java -->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>8.0.23</version>
</dependency>
<!-- https://mvnrepository.com/artifact/org.springframework.boot/spring-boot-starter-test -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<version>2.4.2</version>
<scope>test</scope>
</dependency>
<!-- https://mvnrepository.com/artifact/org.projectlombok/lombok -->
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<version>1.18.18</version>
<scope>provided</scope>
</dependency>
<!-- https://mvnrepository.com/artifact/org.modelmapper/modelmapper -->
<dependency>
<groupId>org.modelmapper</groupId>
<artifactId>modelmapper</artifactId>
<version>2.3.9</version>
</dependency>
<!-- https://mvnrepository.com/artifact/javax.validation/validation-api -->
<dependency>
<groupId>javax.validation</groupId>
<artifactId>validation-api</artifactId>
<version>2.0.1.Final</version>
</dependency>
<!-- https://mvnrepository.com/artifact/org.hibernate/hibernate-validator -->
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-validator</artifactId>
<version>7.0.1.Final</version>
</dependency>
<!--security-->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-security</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.security</groupId>
<artifactId>spring-security-test</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>io.jsonwebtoken</groupId>
<artifactId>jjwt</artifactId>
<version>0.9.1</version>
</dependency>
<dependency>
<groupId>javax.xml.bind</groupId>
<artifactId>jaxb-api</artifactId>
<version>2.3.1</version>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build>
</project>
This is the JSON value that i use with postman
{
"nic" : "656v",
"address" : "polpitiya",
"firstName" : "nn",
"lastName" : "",
"user": [{
"userName":"username1",
"email":"sample#gmail.com",
"password":"1234"
}]
}
Try the 6.2.0.final version of hibernate-validator, it will work.
<dependency>
<groupId>org.hibernate.validator</groupId>
<artifactId>hibernate-validator</artifactId>
<version>6.2.0.Final</version>
</dependency>

Spring boot application deployed in Wildfly "Failed to instantiate WebApplicationInitializer class"

I am using IntelliJ IDEA and building a spring boot application, i.e. a REST web service. Everything seems ok when running the application from the IDE. When I try to deploy it on WildFly 14, I get the following error:
{"WFLYCTL0080: Failed services" => {"jboss.deployment.unit.\".war\".undertow-deployment" => "java.lang.RuntimeException: javax.servlet.ServletException: Failed to instantiate WebApplicationInitializer class
Caused by: java.lang.RuntimeException: javax.servlet.ServletException: Failed to instantiate WebApplicationInitializer class
Caused by: javax.servlet.ServletException: Failed to instantiate WebApplicationInitializer class
Caused by: java.lang.NoSuchMethodException: com.foo.Application.()"}}
My pom.xml:
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>com.foo.<application-name></groupId>
<artifactId><application-name></artifactId>
<version>xxx</version>
<name>Application name</name>
<description>Application description
</description>
<properties>
<start-class>com.foo.Application</start-class>
</properties>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.0.5.RELEASE</version>
</parent>
<dependencies>
<dependency>
<groupId>org.glassfish.jaxb</groupId>
<artifactId>jaxb-runtime</artifactId>
<version>2.3.0.1</version>
</dependency>
<dependency>
<groupId>javax.activation</groupId>
<artifactId>activation</artifactId>
<version>1.1.1</version>
</dependency>
<dependency>
<groupId>javax.transaction</groupId>
<artifactId>jta</artifactId>
<version>1.1</version>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
<exclusions>
<exclusion>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-tomcat</artifactId>
</exclusion>
</exclusions>
</dependency>
<dependency>
<groupId>org.apache.maven</groupId>
<artifactId>maven-model</artifactId>
<version>3.5.4</version>
</dependency>
<dependency>
<groupId>org.modelmapper</groupId>
<artifactId>modelmapper</artifactId>
<version>2.2.0</version>
</dependency>
<dependency>
<groupId>com.h2database</groupId>
<artifactId>h2</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-validation</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-jpa</artifactId>
</dependency>
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<optional>true</optional>
</dependency>
<dependency>
<!-- update Hibernate dependency on Javassist to 3.23.1 for Java 11 compatibility -->
<groupId>org.javassist</groupId>
<artifactId>javassist</artifactId>
<version>3.23.1-GA</version>
</dependency>
<dependency>
<!-- update Mockito dependency for Java 11 compatibility -->
<groupId>org.mockito</groupId>
<artifactId>mockito-core</artifactId>
<version>2.22.0</version><!--$NO-MVN-MAN-VER$ -->
<scope>test</scope>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>8.0.12</version><!--$NO-MVN-MAN-VER$ -->
</dependency>
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>javax.servlet-api</artifactId>
<scope>provided</scope>
</dependency>
</dependencies>
<packaging>war</packaging>
<build>
<defaultGoal>install</defaultGoal>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
<!--<configuration>
<executable>true</executable>
<skipTests>true</skipTests>
</configuration>
<executions>
<execution>
<goals>
<goal>repackage</goal>
</goals>
</execution>
</executions>-->
</plugin>
</plugins>
</build>
<repositories>
<repository>
<id>spring-releases</id>
<url>https://repo.spring.io/libs-release</url>
</repository>
</repositories>
<pluginRepositories>
<pluginRepository>
<id>spring-releases</id>
<url>https://repo.spring.io/libs-release</url>
</pluginRepository>
</pluginRepositories>
My com.foo.Application class:
package com.foo;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.Arrays;
import java.util.Objects;
import java.util.Properties;
import javax.persistence.EntityManagerFactory;
import javax.sql.DataSource;
import org.apache.maven.model.Model;
import org.apache.maven.model.io.xpp3.MavenXpp3Reader;
import org.codehaus.plexus.util.xml.pull.XmlPullParserException;
import org.modelmapper.ModelMapper;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.CommandLineRunner;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.autoconfigure.domain.EntityScan;
import org.springframework.boot.builder.SpringApplicationBuilder;
import org.springframework.boot.web.servlet.support.SpringBootServletInitializer;
import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.PropertySource;
import org.springframework.core.env.Environment;
import org.springframework.data.jpa.repository.config.EnableJpaRepositories;
import org.springframework.jdbc.datasource.DriverManagerDataSource;
import org.springframework.orm.jpa.JpaTransactionManager;
import org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean;
import org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter;
import org.springframework.transaction.annotation.EnableTransactionManagement;
#SpringBootApplication
#Configuration
#EnableJpaRepositories("com.foo.repositories")
#EntityScan("com.foo.entities")
#EnableTransactionManagement
#ComponentScan({ "com.foo.services", "com.foo.controllers" })
#PropertySource("classpath:application.properties")
public class Application extends SpringBootServletInitializer {
private final Logger logger1 = LoggerFactory.getLogger(Application.class);
#Autowired
public Application(Environment env) {
this.env = env;
}
public static void main(String[] args) {
Logger log = LoggerFactory.getLogger(Application.class);
SpringApplication.run(Application.class, args);
log.trace("Application started");
}
#Override
protected SpringApplicationBuilder configure(SpringApplicationBuilder application) {
return application.sources(Application.class);
}
#Bean
public CommandLineRunner commandLineRunner(ApplicationContext ctx) {
return args -> {
logger1.trace("Let's inspect the beans provided by Spring Boot:");
String[] beanNames = ctx.getBeanDefinitionNames();
Arrays.sort(beanNames);
for (String beanName : beanNames) {
logger1.trace(beanName);
}
};
}
// Database initialization is organized according to the tutorial in https://www.baeldung.com/spring-jpa-test-in-memory-database
private final Environment env;
#Bean
public DataSource dataSource() {
DriverManagerDataSource dataSource = new DriverManagerDataSource();
dataSource.setDriverClassName(Objects.requireNonNull(env.getProperty("jdbc.driverClassName")));
dataSource.setUrl(env.getProperty("jdbc.url"));
dataSource.setUsername(env.getProperty("jdbc.user"));
dataSource.setPassword(env.getProperty("jdbc.pass"));
return dataSource;
}
#Bean
public LocalContainerEntityManagerFactoryBean entityManagerFactory() {
final LocalContainerEntityManagerFactoryBean em = new LocalContainerEntityManagerFactoryBean();
em.setDataSource(dataSource());
em.setPackagesToScan("com.foo.entities");
em.setJpaVendorAdapter(new HibernateJpaVendorAdapter());
em.setJpaProperties(additionalProperties());
return em;
}
#Bean
JpaTransactionManager transactionManager(EntityManagerFactory entityManagerFactory) {
JpaTransactionManager transactionManager = new JpaTransactionManager();
transactionManager.setEntityManagerFactory(entityManagerFactory);
return transactionManager;
}
Properties additionalProperties() {
final Properties hibernateProperties = new Properties();
hibernateProperties.setProperty("hibernate.hbm2ddl.auto", env.getProperty("hibernate.hbm2ddl.auto"));
hibernateProperties.setProperty("hibernate.dialect", env.getProperty("hibernate.dialect"));
/*hibernateProperties.setProperty("hibernate.show_sql", env.getProperty("hibernate.show_sql"));
hibernateProperties.setProperty("hibernate.cache.use_second_level_cache", env.getProperty("hibernate.cache.use_second_level_cache"));
hibernateProperties.setProperty("hibernate.cache.use_query_cache", env.getProperty("hibernate.cache.use_query_cache"));*/
return hibernateProperties;
}
#Bean
public ModelMapper modelMapper() {
ModelMapper mm = new ModelMapper();
mm.addConverter(new InteractionConverter());
return mm;
}
public static String getVersion() throws IOException, XmlPullParserException {
MavenXpp3Reader reader = new MavenXpp3Reader();
String version;
if ((new File("pom.xml")).exists()) {
try (FileReader pomFileReader = new FileReader("pom.xml")) {
Model model = reader.read(pomFileReader);
version = model.getVersion();
}
} else {
try (InputStream stream = Application.class.getResourceAsStream(
"/META-INF/maven/com.foo.application-name/application-name/pom.xml")) {
InputStreamReader pomFileReader = new InputStreamReader(stream);
Model model = reader.read(pomFileReader);
version = model.getVersion();
}
}
return version;
}
public static String getDescription() throws IOException, XmlPullParserException {
MavenXpp3Reader reader = new MavenXpp3Reader();
String description;
if ((new File("pom.xml")).exists()) {
try (FileReader pomFileReader = new FileReader("pom.xml")) {
Model model = reader.read(pomFileReader);
description = model.getDescription();
}
} else {
try (InputStream stream = Application.class.getResourceAsStream(
"/META-INF/maven/com.foo.application-name/application-name/pom.xml")) {
InputStreamReader pomFileReader = new InputStreamReader(stream);
Model model = reader.read(pomFileReader);
description = model.getDescription();
}
}
return description;
}
}
If I get it right, the spring application entry point is not visible, but I don't understand why. Is there something wrong with my pom.xml or my Application class?
Tracing the source codes and found that it basically uses the following codes to create an instance of SpringBootServletInitializer:
Constructor ctor = FooInitialializer.class.getDeclaredConstructor();
ctor.newInstance();
That means your SpringBootServletInitializer should have an no-args constructor. So try to add one :
public class Application extends SpringBootServletInitializer {
Application(){}
}

Spring Security - Facebook

I want to login to my web app by facebook. I have a form with normal login and i want to add login with facebook. I've added my app to developers facebook by link http://localhost:8080/. I followed the example of
Using Spring Security 5 to integrate with OAuth 2-secured services such as Facebook and GitHub
I wrote following files
SocialConfig.java
package pl.java.learning.todolist.infrastructure.config;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.oauth2.client.OAuth2AuthorizedClient;
import org.springframework.security.oauth2.client.OAuth2AuthorizedClientService;
import org.springframework.security.oauth2.client.authentication.OAuth2AuthenticationToken;
import org.springframework.web.context.annotation.RequestScope;
import pl.java.learning.todolist.infrastructure.social.Facebook;
#Configuration
public class SocialConfig {
#Bean
#RequestScope
public Facebook facebook(OAuth2AuthorizedClientService clientService) {
Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
String accessToken = null;
if (authentication.getClass().isAssignableFrom(OAuth2AuthenticationToken.class)) {
OAuth2AuthenticationToken oauthToken = (OAuth2AuthenticationToken) authentication;
String clientRegistrationId = oauthToken.getAuthorizedClientRegistrationId();
if (clientRegistrationId.equals("facebook")) {
OAuth2AuthorizedClient client = clientService.loadAuthorizedClient(clientRegistrationId, oauthToken.getName());
accessToken = client.getAccessToken().getTokenValue();
}
}
return new Facebook(accessToken);
}
}
ApiBinding.java
package pl.java.learning.todolist.infrastructure.social;
import java.io.IOException;
import org.springframework.http.HttpRequest;
import org.springframework.http.client.ClientHttpRequestExecution;
import org.springframework.http.client.ClientHttpRequestInterceptor;
import org.springframework.http.client.ClientHttpResponse;
import org.springframework.web.client.RestTemplate;
public abstract class ApiBinding {
protected RestTemplate restTemplate;
public ApiBinding(String accessToken) {
this.restTemplate = new RestTemplate();
if (accessToken != null) {
this.restTemplate.getInterceptors().add(getBearerTokenInterceptor(accessToken));
} else {
this.restTemplate.getInterceptors().add(getNoTokenInterceptor());
}
}
private ClientHttpRequestInterceptor getBearerTokenInterceptor(String accessToken) {
return new ClientHttpRequestInterceptor() {
#Override
public ClientHttpResponse intercept(HttpRequest request, byte[] bytes, ClientHttpRequestExecution execution) throws IOException {
request.getHeaders().add("Authorization", "Bearer " + accessToken);
return execution.execute(request, bytes);
}
};
}
private ClientHttpRequestInterceptor getNoTokenInterceptor() {
return new ClientHttpRequestInterceptor() {
#Override
public ClientHttpResponse intercept(HttpRequest request, byte[] bytes, ClientHttpRequestExecution execution) throws IOException {
throw new IllegalStateException("Can't access the Facebook API without an access token");
}
};
}
}
Facebook.java
package pl.java.learning.todolist.infrastructure.social;
public class Facebook extends ApiBinding {
private static final String GRAPH_API_BASE_URL = "https://graph.facebook.com/v2.12";
public Facebook(String accessToken) {
super(accessToken);
}
public Profile getProfile() {
return restTemplate.getForObject(GRAPH_API_BASE_URL + "/me", Profile.class);
}
}
Profile.java
package pl.java.learning.todolist.infrastructure.social;
import lombok.Data;
#Data
public class Profile {
private String id;
private String name;
}
In the file index.html i added following link to facebook
<img src="/image/facebook.png" class="imgsize img-fluid m-10 " margin="10px" alt="">
The file pom.xml
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>pl.java.learning</groupId>
<artifactId>todo-list</artifactId>
<version>0.0.1-SNAPSHOT</version>
<packaging>jar</packaging>
<name>todo-list</name>
<description>To-do list project</description>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.0.4.RELEASE</version>
<relativePath/> <!-- lookup parent from repository -->
</parent>
<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
<java.version>1.8</java.version>
<swagger.version>2.9.2</swagger.version>
</properties>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-actuator</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-mail</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-security</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-thymeleaf</artifactId>
</dependency>
<dependency>
<groupId>org.flywaydb</groupId>
<artifactId>flyway-core</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-devtools</artifactId>
<scope>runtime</scope>
</dependency>
<dependency>
<groupId>com.h2database</groupId>
<artifactId>h2</artifactId>
<scope>runtime</scope>
</dependency>
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<optional>true</optional>
</dependency>
<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-swagger2</artifactId>
<version>${swagger.version}</version>
</dependency>
<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-swagger-ui</artifactId>
<version>${swagger.version}</version>
</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>io.rest-assured</groupId>
<artifactId>rest-assured</artifactId>
<version>3.1.1</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.webjars</groupId>
<artifactId>bootstrap</artifactId>
<version>4.1.3</version>
</dependency>
<dependency>
<groupId>org.webjars</groupId>
<artifactId>jquery</artifactId>
<version>3.3.1</version>
</dependency>
<dependency>
<groupId>org.thymeleaf.extras</groupId>
<artifactId>thymeleaf-extras-springsecurity4</artifactId>
<version>3.0.2.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework.security</groupId>
<artifactId>spring-security-oauth2-client</artifactId>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build>
</project>
But it doesn't work and not redirect to facebook, maybe someone know how to fix this?
Regards
MyUserPrincipal
package pl.java.learning.todolist.infrastructure.security;
import java.util.Collection;
import lombok.RequiredArgsConstructor;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import pl.java.learning.todolist.domain.user.User;
#RequiredArgsConstructor
public class MyUserPrincipal implements UserDetails {
private final User user;
#Override
public Collection<? extends GrantedAuthority> getAuthorities() {
return user.getRoles();
}
public Long getUserId() {
return user.getId();
}
#Override
public String getPassword() {
return user.getPassword();
}
#Override
public String getUsername() {
return user.getLogin();
}
#Override
public boolean isAccountNonExpired() {
return true;
}
#Override
public boolean isAccountNonLocked() {
return true;
}
#Override
public boolean isCredentialsNonExpired() {
return true;
}
#Override
public boolean isEnabled() {
return user.getEnabled();
}
}

HikariCP starts when "mvn spring-boot:run" but not with a deployable war file

We have a spring boot application.
When we do "mvn spring-boot:run", the application uses HikariCP.
When we deploy a war file on tomcat, the CP is different and it crashes with connection closed after a few hours.
How can I force Hikari when deploying a war file?
This is our application.properties:
spring.datasource.url=jdbc:mysql://localhost:3306/xxx?
autoReconnect=true&useUnicode=true&characterEncoding=UTF-8&connectionCollation=utf8_general_ci&characterSetResults=utf8&autoDeserialize=true&useConfigs=maxPerformance
spring.datasource.username=root
spring.datasource.password=___
spring.datasource.driver-class-name=com.mysql.jdbc.Driver
spring.jpa.open-in-view=true
spring.jpa.show-sql=false
spring.jpa.database-platform=org.hibernate.dialect.MySQL5Dialect
spring.jpa.generate-ddl=true
spring.jpa.hibernate.ddl-auto=none
spring.jpa.hibernate.naming_strategy=org.hibernate.cfg.DefaultNamingStrategy
spring.jpa.properties.javax.persistence.sharedCache.mode=ENABLE_SELECTIVE
spring.jpa.properties.hibernate.hikari.dataSource.cachePrepStmts=true
spring.jpa.properties.hibernate.hikari.dataSource.prepStmtCacheSize=250
spring.jpa.properties.hibernate.hikari.dataSource.prepStmtCacheSqlLimit=2048
spring.jpa.properties.hibernate.hikari.dataSource.useServerPrepStmts=true
spring.jpa.properties.hibernate.generate_statistics=false
spring.jpa.properties.hibernate.cache.use_structured_entries=true
spring.jpa.properties.hibernate.archive.autodetection=class
spring.jpa.properties.hibernate.show_sql=false
spring.jpa.properties.hibernate.format_sql=true
spring.jpa.properties.hibernate.use_sql_comments=true
spring.jpa.properties.hibernate.dialect=org.hibernate.dialect.MySQL5Dialect
spring.jpa.properties.hibernate.jdbc.batch_size=50
spring.jpa.properties.hibernate.order_update=true
spring.jpa.properties.hibernate.connection.characterEncoding=utf-8
spring.jpa.properties.hibernate.connection.CharSet=utf-8
spring.jpa.properties.hibernate.connection.useUnicode=true
spring.jpa.properties.hibernate.connection.autocommit=true
spring.jpa.properties.hibernate.cache.use_second_level_cache=true
spring.jpa.properties.hibernate.cache.region.factory_class=com.hazelcast.hibernate.HazelcastLocalCacheRegionFactory
spring.jpa.properties.hibernate.cache.region_prefix=
spring.jpa.properties.hibernate.cache.use_query_cache=true
spring.jpa.properties.hibernate.cache.use_minimal_puts=true
# JTA
spring.jta.enabled=true
This is the Application class:
package site.app;
import com.zaxxer.hikari.HikariConfig;
import com.zaxxer.hikari.HikariDataSource;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.builder.SpringApplicationBuilder;
import org.springframework.boot.context.web.SpringBootServletInitializer;
import org.springframework.boot.orm.jpa.EntityScan;
import org.springframework.context.ConfigurableApplicationContext;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.jpa.repository.config.EnableJpaAuditing;
import org.springframework.data.jpa.repository.config.EnableJpaRepositories;
import org.springframework.data.web.config.EnableSpringDataWebSupport;
import org.springframework.transaction.annotation.EnableTransactionManagement;
import javax.sql.DataSource;
import java.util.Properties;
/**
* to make this deployable as war, this is necessary:
* http://docs.spring.io/spring-boot/docs/current/reference/html/howto-traditional-deployment.html
*/
#Configuration
#EnableAutoConfiguration
#ComponentScan(basePackages = "site")
#EnableTransactionManagement
#EnableJpaRepositories(basePackages = { "site.repository" } )
#EntityScan(basePackages="site.model")
#EnableJpaAuditing
#EnableSpringDataWebSupport
#SpringBootApplication//mist: so that it can be run as war file
public class Application extends SpringBootServletInitializer {
/** mist: so that it can be run as war file */
#Override
protected SpringApplicationBuilder configure(SpringApplicationBuilder application) {
return application.sources(Application.class);
}
public static void main(String[] args) {
ConfigurableApplicationContext context = SpringApplication.run(Application.class, args);
// System.out.println("Let's inspect the beans provided by Spring Boot:");
//
// String[] beanNames = ctx.getBeanDefinitionNames();
// Arrays.sort(beanNames);
// for (String beanName : beanNames) {
// System.out.println(beanName);
// }
// UserRepository repository = context.getBean(UserRepository.class);
// //example data
// User user = new User();
// user.setEmail("nov34#test.com");
// user.setFirstName("test");
// user.setLastName("test");
//
// repository.save(user);
// Iterable<User> allUsers = repository.findAll();
// for(User theUser : allUsers){
// System.out.println(theUser.getEmail());
// }
//
// SponsorRepository sponsorRepository = context.getBean(SponsorRepository.class);
//
// Sponsor sponsor = new Sponsor();
// sponsor.setEmail("test#test.com");
// sponsor.setSponsorPackage(SponsorPackage.DIAMOND);
//
// sponsorRepository.save(sponsor);
// Page page = new Page();
// page.setName("home");
// PageRepository pageRepository = context.getBean(PageRepository.class);
// pageRepository.save(page);
// Link link = new Link();
// link.setName("Registration");
// link.setUrl("/");
// LinkRepository linkRepository = context.getBean(LinkRepository.class);
// linkRepository.save(link);
// context.close();
}
// private DataSource dataSource() {
// final HikariDataSource ds = new HikariDataSource();
// ds.setMaximumPoolSize(100);
// ds.setDataSourceClassName("com.mysql.jdbc.jdbc2.optional.MysqlDataSource");
// ds.addDataSourceProperty("url", url);
// ds.addDataSourceProperty("user", username);
// ds.addDataSourceProperty("password", password);
// ds.addDataSourceProperty("cachePrepStmts", true);
// ds.addDataSourceProperty("prepStmtCacheSize", 250);
// ds.addDataSourceProperty("prepStmtCacheSqlLimit", 2048);
// ds.addDataSourceProperty("useServerPrepStmts", true);
// return ds;
// }
// #Value("${spring.datasource.username}")
// private String user;
//
// #Value("${spring.datasource.password}")
// private String password;
//
// #Value("${spring.datasource.url}")
// private String dataSourceUrl;
//
// #Value("${spring.datasource.driverClassName}")
// private String driverClassName;
//
//// #Value("${spring.datasource.connectionTestQuery}")
//// private String connectionTestQuery;
//
// #Bean
// public DataSource primaryDataSource() {
// Properties dsProps = new Properties();
// dsProps.setProperty("url", dataSourceUrl);
// dsProps.setProperty("user", user);
// dsProps.setProperty("password", password);
//
// Properties configProps = new Properties();
//// configProps.setProperty("connectionTestQuery", connectionTestQuery);
// configProps.setProperty("driverClassName", driverClassName);
// configProps.setProperty("jdbcUrl", dataSourceUrl);
//
// HikariConfig hc = new HikariConfig(configProps);
// hc.setDataSourceProperties(dsProps);
//// hc.setMetricRegistry(metricRegistry);
// return new HikariDataSource(hc);
// }
}
This is the pom.xml
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>org.bgjug</groupId>
<artifactId>site</artifactId>
<version>0.0.1-SNAPSHOT</version>
<packaging>war</packaging>
<name> web site</name>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>1.2.2.RELEASE</version>
</parent>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
<exclusions>
<exclusion>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-tomcat</artifactId>
</exclusion>
</exclusions>
<!--mist: exists in tomcat-->
<!--<scope>provided</scope>-->
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-aspects</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.data</groupId>
<artifactId>spring-data-jpa</artifactId>
</dependency>
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-entitymanager</artifactId>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
</dependency>
<!--TODO mist: hikariCP stays here. I couldn't make it use it (I'm missing something). Now it uses either tomcat's pool or commons' pool-->
<dependency>
<groupId>com.zaxxer</groupId>
<artifactId>HikariCP</artifactId>
<scope>compile</scope>
</dependency>
<!-- I need this to make entities auditable -->
<dependency>
<groupId>joda-time</groupId>
<artifactId>joda-time</artifactId>
</dependency>
<dependency>
<groupId>joda-time</groupId>
<artifactId>joda-time-jsptags</artifactId>
<version>1.1.1</version>
</dependency>
<dependency>
<groupId>org.jadira.usertype</groupId>
<artifactId>usertype.core</artifactId>
<version>${jadira.version}</version>
</dependency>
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>javax.servlet-api</artifactId>
<!--mist: exists in tomcat-->
<scope>provided</scope>
</dependency>
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>jstl</artifactId>
</dependency>
<!-- spring security -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-security</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.security</groupId>
<artifactId>spring-security-taglibs</artifactId>
</dependency>
<!-- email -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-mail</artifactId>
</dependency>
<dependency>
<groupId>com.hazelcast</groupId>
<artifactId>hazelcast-hibernate4</artifactId>
<version>${hazelcast.version}</version>
</dependency>
<!-- testing -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.hamcrest</groupId>
<artifactId>hamcrest-core</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>com.h2database</groupId>
<artifactId>h2</artifactId>
<version>1.4.186</version>
</dependency>
</dependencies>
<!--mist: a profile that has the spring-boot:run plugin and a couple of dependencies, so that-->
<!--spring-boot:run will work with an embedded tomcat. This profile is activated by default so that-->
<!--no extra conf is needed. when we deploy on the server, we deactivate the profile, because we don't-->
<!--want these dependencies in the war.-->
<profiles>
<profile>
<activation>
<activeByDefault>true</activeByDefault>
</activation>
<id>run.as.spring-boot.run</id>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.apache.tomcat.embed</groupId>
<artifactId>tomcat-embed-jasper</artifactId>
</dependency>
</dependencies>
</profile>
</profiles>
<properties>
<start-class>site.app.Application</start-class>
<spring.version>4.1.5.RELEASE</spring.version>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<spring-data-jpa.version>1.5.0.M1</spring-data-jpa.version>
<hibernate-entitymanager.version>4.3.0.Final</hibernate-entitymanager.version>
<jadira.version>3.1.0.CR10</jadira.version>
<hazelcast.version>3.4</hazelcast.version>
<rest-assured.version>2.4.0</rest-assured.version>
<h2-database.version>1.3.156</h2-database.version>
</properties>
<build>
<plugins>
<plugin>
<artifactId>maven-compiler-plugin</artifactId>
<configuration>
<source>1.8</source>
<target>1.8</target>
</configuration>
</plugin>
</plugins>
</build>
</project>
So I've been told in the comments, that it's not going to work implicitly, because Tomcat's db pool somehow takes precedence, which is weird for me.
One can configure it explicitly like this:
#Configuration
#ConfigurationProperties//: so that the conf properties are supplied here
#SpringBootApplication//: so that it can be run as war file
...
public class Application extends SpringBootServletInitializer {
#Value("${spring.datasource.username}")
private String user;
#Value("${spring.datasource.password}")
private String password;
#Value("${spring.datasource.url}")
private String dataSourceUrl;
#Value("${spring.datasource.driver-class-name}")
private String driverClassName;
#Bean
public DataSource primaryDataSource() {
Properties dsProps = new Properties();
dsProps.setProperty("url", dataSourceUrl);
dsProps.setProperty("user", user);
dsProps.setProperty("password", password);
Properties configProps = new Properties();
configProps.setProperty("driverClassName", driverClassName);
configProps.setProperty("jdbcUrl", dataSourceUrl);
HikariConfig hc = new HikariConfig(configProps);
hc.setDataSourceProperties(dsProps);
return new HikariDataSource(hc);
}
}
I also faced this problem and in the end it was just a minor issue. It definitely takes precedence only in case you make sure tomcat-jdbc.jar or commons-dbcp.jar never show up in your classpath. you can ensure this by excluding these dependencies if they are transitively downloaded ( that is what i did, just find out what dependency in pom transitively downloads these in your classpath). when you are done with this your application.properties should look something like this:
# hikariCP
spring.jpa.databasePlatform=org.hibernate.dialect.MySQLDialect
spring.datasource.url=jdbc:mysql://localhost:3306/exampledb
spring.datasource.username=root
spring.datasource.password=
spring.datasource.poolName=SpringBootHikariCP
spring.datasource.maximumPoolSize=5
spring.datasource.minimumIdle=3
spring.datasource.maxLifetime=2000000
spring.datasource.connectionTimeout=30000
spring.datasource.idleTimeout=30000
spring.datasource.pool-prepared-statements=true
spring.datasource.max-open-prepared-statements=2500
it will implicitly configure a HikariCP datasource. But one thing more, it will use the Driver instead of dataSourceClassName which is recommended. In that case you have to go with the Java Config after having spring.datasource.dataSourceClassName=com.mysql.jdbc.jdbc2.optional.MysqlDataSource in application.properties:
#Configuration
#ComponentScan
class DataSourceConfig {
#Value("${spring.datasource.username}")
private String user;
#Value("${spring.datasource.password}")
private String password;
#Value("${spring.datasource.url}")
private String dataSourceUrl;
#Value("${spring.datasource.dataSourceClassName}")
private String dataSourceClassName;
#Value("${spring.datasource.poolName}")
private String poolName;
#Value("${spring.datasource.connectionTimeout}")
private int connectionTimeout;
#Value("${spring.datasource.maxLifetime}")
private int maxLifetime;
#Value("${spring.datasource.maximumPoolSize}")
private int maximumPoolSize;
#Value("${spring.datasource.minimumIdle}")
private int minimumIdle;
#Value("${spring.datasource.idleTimeout}")
private int idleTimeout;
#Bean
public DataSource primaryDataSource() {
Properties dsProps = new Properties();
dsProps.put("url", dataSourceUrl);
dsProps.put("user", user);
dsProps.put("password", password);
dsProps.put("prepStmtCacheSize",250);
dsProps.put("prepStmtCacheSqlLimit",2048);
dsProps.put("cachePrepStmts",Boolean.TRUE);
dsProps.put("useServerPrepStmts",Boolean.TRUE);
Properties configProps = new Properties();
configProps.put("dataSourceClassName", dataSourceClassName);
configProps.put("poolName",poolName);
configProps.put("maximumPoolSize",maximumPoolSize);
configProps.put("minimumIdle",minimumIdle);
configProps.put("minimumIdle",minimumIdle);
configProps.put("connectionTimeout", connectionTimeout);
configProps.put("idleTimeout", idleTimeout);
configProps.put("dataSourceProperties", dsProps);
HikariConfig hc = new HikariConfig(configProps);
HikariDataSource ds = new HikariDataSource(hc);
return ds;
}
}
defining dataSourceClassName in application.properties for implicit auto-configuration with throw an exception :
Caused by: java.lang.IllegalStateException: both driverClassName and dataSourceClassName are specified, one or the other should be used.
As spring boot infers Driver from url property and you can't set Driver (inferred) and dataSourceClassName at the same time for implicit auto-configuration.

Override getSchemaFile and getSolrConfigFile

I'm migrating my Solr test project to Solr 4.1 and I can't override the methods getSchemaFile() and getSolrConfigFile().
I'm getting the following errors:
[ERROR] my_path/SolrConfigTest.java:[63,15] error: getSchemaFile() in SolrConfigTest cannot override getSchemaFile() in SolrTestCaseJ4
[ERROR] overridden method is static
[ERROR] my_path/SolrConfigTest.java:[62,1] error: method does not override or implement a method from a supertype
[ERROR] my_path/SolrConfigTest.java:[68,15] error: getSolrConfigFile() in SolrConfigTest cannot override getSolrConfigFile() in SolrTestCaseJ4
[ERROR] overridden method is static
[ERROR] my_path/SolrConfigTest.java:[67,1] error: method does not override or implement a method from a supertype
The file looks as follows:
import org.apache.log4j.Logger;
import org.apache.solr.client.solrj.SolrServer;
import org.apache.solr.client.solrj.SolrServerException;
import org.apache.solr.client.solrj.embedded.EmbeddedSolrServer;
import org.apache.solr.client.solrj.request.AbstractUpdateRequest;
import org.apache.solr.client.solrj.request.ContentStreamUpdateRequest;
import org.apache.solr.client.solrj.request.CoreAdminRequest;
import org.apache.solr.client.solrj.response.QueryResponse;
import org.apache.solr.common.params.ModifiableSolrParams;
import org.apache.solr.common.util.NamedList;
import org.apache.solr.core.CoreContainer;
import org.apache.solr.util.AbstractSolrTestCase;
public class SolrConfigTest extends AbstractSolrTestCase {
String container = "mycore";
#Override
public String getSolrHome() {
return System.getProperty("user.dir") + "/resources/";
}
#Override
public String getSchemaFile() {
return getSolrHome() + container + "/conf/schema.xml";
}
#Override
public String getSolrConfigFile() {
return getSolrHome() + container + "/conf/solrconfig.xml";
}
#Before
#Override
public void setUp() throws Exception {
super.setUp();
CoreContainer.Initializer initializer = new CoreContainer.Initializer();
coreContainer = initializer.initialize();
server = new EmbeddedSolrServer(coreContainer, "mycore");
}
}
And for maven, my pom.xml file has the following dependencies:
<dependencies>
<dependency>
<groupId>log4j</groupId>
<artifactId>log4j</artifactId>
<version>1.2.17</version>
</dependency>
<dependency>
<groupId>org.apache.lucene</groupId>
<artifactId>lucene-core</artifactId>
<version>4.1.0</version>
</dependency>
<dependency>
<groupId>org.apache.solr</groupId>
<artifactId>solr-core</artifactId>
<version>4.1.0</version>
</dependency>
<dependency>
<groupId>org.apache.solr</groupId>
<artifactId>solr-solrj</artifactId>
<version>4.1.0</version>
</dependency>
<dependency>
<groupId>org.apache.solr</groupId>
<artifactId>solr-test-framework</artifactId>
<version>4.1.0</version>
</dependency>
</dependencies>
Anybody has any idea about what I'm missing?
As far as I can see, AbstractSolrTestCase class at Solr 4.1 does not offer anymore methods getSchemaFile() and getSolrConfigFile() to override.
Once getSolrHome() points to the folder where Solr is defined (where you can find the solr.xml file), the schema.xml and solrconfig.xml files will be found at mycore/conf.
Or you can override initCore(String config, String schema, String solrHome) method of SolrTestCaseJ4 class instead so that you can set the config file and schema file as per your configuration.

Resources