I am trying to create a web application with spring boot web that needs geoserver to deserve GeoJSON layers.
I succed to launch geoserver in the same tomcat that my spring-boot application. But there is a problem when GeoServer is trying to access postgresql/postgis database. Geoserver said:
Error occurred getting featuresUnable to obtain connection: Cannot create PoolableConnectionFactory
Due to:
java.lang.ClassCastException: class org.postgis.PGbox2d
at java.lang.Class.asSubclass(Class.java:3404) ~[na:1.8.0_151]
at org.postgresql.jdbc.PgConnection.initObjectTypes(PgConnection.java:645) ~[postgresql-42.1.1.jar:42.1.1]
at org.postgresql.jdbc.PgConnection.<init>(PgConnection.java:296) ~[postgresql-42.1.1.jar:42.1.1]
at org.postgresql.Driver.makeConnection(Driver.java:450) ~[postgresql-42.1.1.jar:42.1.1]
at org.postgresql.Driver.connect(Driver.java:252) ~[postgresql-42.1.1.jar:42.1.1]
...
I can access to data stored in postgresql/postgis via spring application.
Here there is my pom.xml
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>1.5.9.RELEASE</version>
<relativePath/>
</parent>
<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
<java.version>1.8</java.version>
</properties>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-jpa</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-jdbc</artifactId>
</dependency>
<dependency>
<groupId>net.postgis</groupId>
<artifactId>postgis-jdbc</artifactId>
<version>2.2.0</version>
<exclusions>
<exclusion>
<groupId>org.postgresql</groupId>
<artifactId>postgresql</artifactId>
</exclusion>
</exclusions>
</dependency>
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-spatial</artifactId>
<version>5.2.12.Final</version>
</dependency>
<dependency>
<groupId>com.bedatadriven</groupId>
<artifactId>jackson-datatype-jts</artifactId>
<version>2.2</version>
</dependency>
<dependency>
<groupId>org.apache.tomcat.embed</groupId>
<artifactId>tomcat-embed-jasper</artifactId>
<version>9.0.2</version>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-devtools</artifactId>
<scope>runtime</scope>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build>
There is also Application:
package fr.app;
import fr.app.dao.GreffeRepository;
import fr.app.util.TomcatDeployer;
import org.springframework.boot.CommandLineRunner;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.context.embedded.EmbeddedServletContainerFactory;
import org.springframework.context.annotation.Bean;
import java.util.logging.Logger;
#SpringBootApplication
public class GroLocApplication
{
private static final Logger LOGGER = Logger.getLogger(GroLocApplication.class.getName());
public static void main(String... args)
{
SpringApplication.run(GroLocApplication.class, args);
}
#Bean
public EmbeddedServletContainerFactory servletContainerFactory()
{
return new TomcatDeployer();
}
}
The TomcatDeployer, that deploy war in war folder in resources:
package fr.app.util;
import org.apache.catalina.Context;
import org.apache.catalina.loader.WebappLoader;
import org.apache.catalina.startup.Tomcat;
import org.springframework.boot.context.embedded.tomcat.TomcatEmbeddedServletContainer;
import org.springframework.boot.context.embedded.tomcat.TomcatEmbeddedServletContainerFactory;
import javax.servlet.ServletException;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.nio.file.Files;
import java.nio.file.StandardCopyOption;
import java.util.logging.Logger;
final public class TomcatDeployer extends TomcatEmbeddedServletContainerFactory
{
private static final Logger LOGGER = Logger.getLogger(TomcatDeployer.class.getName());
private static final String WAR_TO_DEPLOY = "war/geoserver.war";
private String copyResourceToTmp() throws IllegalStateException
{
try (InputStream resourceStream = getClass().getClassLoader().getResourceAsStream(WAR_TO_DEPLOY))
{
File tmpWar = File.createTempFile("geoserver", ".war");
Files.copy(resourceStream, tmpWar.toPath(), StandardCopyOption.REPLACE_EXISTING);
return tmpWar.getAbsolutePath();
}
catch (IOException e)
{
throw new IllegalStateException("Cannot copy geoserver.war resource", e);
}
}
#Override
protected TomcatEmbeddedServletContainer getTomcatEmbeddedServletContainer(Tomcat tomcat)
throws IllegalStateException
{
if (!new File(tomcat.getServer().getCatalinaBase(), "webapps").mkdirs())
{
throw new IllegalStateException("Cannot create a webapps directory on tomcat");
}
try
{
final String pathToWar = copyResourceToTmp();
LOGGER.info(pathToWar);
final Context context = tomcat.addWebapp("/geoserver", pathToWar);
final WebappLoader loader = new WebappLoader(Thread.currentThread().getContextClassLoader());
context.setLoader(loader);
}
catch (ServletException e)
{
throw new IllegalStateException("Failed to add geoserver", e);
}
return super.getTomcatEmbeddedServletContainer(tomcat);
}
}
Greffe entity:
package fr.app.entity;
import com.bedatadriven.jackson.datatype.jts.serialization.GeometryDeserializer;
import com.bedatadriven.jackson.datatype.jts.serialization.GeometrySerializer;
import com.fasterxml.jackson.databind.annotation.JsonDeserialize;
import com.fasterxml.jackson.databind.annotation.JsonSerialize;
import com.vividsolutions.jts.geom.Geometry;
import javax.persistence.Entity;
import javax.persistence.Id;
#Entity
public class Greffe
{
#Id
private String id;
#JsonSerialize(using = GeometrySerializer.class)
#JsonDeserialize(using = GeometryDeserializer.class)
private Geometry coord;
// getters...
}
And dao is a classic CrudRepository<Greffe,String> extends.
So is it possible to really embed GeoServer in the same tomcat that the spring-boot application's tomcat? (it's possible because I did so, but is it really a good idea?)
And if so, how can I avoid this kind of trouble?!
Thanks by advance :)
I would not embed GeoServer in the same Tomcat your application is using. Yes, it is possible, yes; but not a really good idea.
Reasoning: During Tomcat startup, GeoServer and your application is not running (yet) - but if your application needs GeoServer during startup it must fail.
Solution: Put GeoServer in a serparat Tomcat that starts up before your application is starting.
And to your trouble (and the ClassCastException):
Make sure to use a postgres and postgis driver version matching each other and the database version you are using.
The error you get seems related to https://github.com/brettwooldridge/HikariCP/issues/1476 - maybe the information there can help you.
I personally never heard of com.bedatadriven.jackson.datatype.jts - make sure the depending JTS version of that library matches the versions used in your GeoServer.
And as you are using HibernateSpatial: make sure to configure HibernateSpatial correct. I did not see a configuration.
Maybe using hibernate-spatial for postgis is a solution:
<groupId>org.hibernatespatial</groupId>
<artifactId>hibernate-spatial-postgis</artifactId>
Related
I'm not able to solve the problem with the version of Jaybird's libs package: jaybird-jdk17:3.0.10 where the antlr4-runtime:4.7 is conflicting with the hibernate-core6.1.5Final lib where there is another antlr4:4.10 .1
https://uploaddeimagens.com.br/imagens/vSObP0s
I've tried to change several other Jaybird dependencies but without success, I tried to change the hibernate libs and without success.
Entity
package com.aula.restiapi.entidade;
import jakarta.persistence.Entity;
import jakarta.persistence.GeneratedValue;
import jakarta.persistence.GenerationType;
import jakarta.persistence.Id;
import jakarta.persistence.Table;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
#Entity
#NoArgsConstructor
#AllArgsConstructor
#Data
#Table(name = "tb_users")
public class Usuario {
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
private String name;
private String email;
private Double salary;
}
repository
package com.aula.restiapi.repository;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.Query;
import org.springframework.stereotype.Repository;
import com.aula.restiapi.entidade.Usuario;
#Repository
public interface UsuarioRepository extends JpaRepository<Usuario, Long>{
#Query("SELECT obj FROM User obj WHERE obj.salary >= :minSalary AND
obj.salary <= :maxSalary")
Page<Usuario> searchBySalary(Double minSalary, Double maxSalary, Pageable pageable);
}
controller
package com.aula.restiapi.controller;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import com.aula.restiapi.entidade.Usuario;
import com.aula.restiapi.repository.UsuarioRepository;
#RestController
#RequestMapping(value = "/users")
public class UserController {
#Autowired
private UsuarioRepository repository;
#GetMapping
public ResponseEntity<List<Usuario>> findAll() {
List<Usuario> result = repository.findAll();
return ResponseEntity.ok(result);
}
#GetMapping(value = "/page")
public ResponseEntity<Page<Usuario>> findAll(Pageable pageable) {
Page<Usuario> result = repository.findAll(pageable);
return ResponseEntity.ok(result);
}
#GetMapping(value = "/search-salary")
public ResponseEntity<Page<Usuario>> searchBySalary(#RequestParam(defaultValue = "0") Double minSalary, #RequestParam(defaultValue = "1000000000000") Double maxSalary, Pageable pageable) {
Page<Usuario> result = repository.searchBySalary(minSalary, maxSalary, pageable);
return ResponseEntity.ok(result);
}
}
application.properties
spring.datasource.url:jdbc:firebirdsql:localhost/3050:C:/DB/BD_ARTISTS.FDB?
sql_dialect=3&charSet=utf-8
spring.datasource.username:SYSDBA
spring.datasource.password:masterkey
spring.datasource.driver-class-name=org.firebirdsql.jdbc.FBDriver
spring.jpa.database-platform=org.hibernate.community.dialect.FirebirdDialect
spring.jpa.show-sql: true
spring.jpa.properties.hibernate.format_sql=true
#logging.level.org.springframework=DEBUG
app.path.arquivos=/Users/Paulo/Pictures/SavedPictures
spring.servlet.multipart.max-file-size=30MB
spring.servlet.multipart.max-request-size=30MB
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 https://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>3.0.0</version>
<relativePath /> <!-- lookup parent from repository -->
</parent>
<groupId>com.aula</groupId>
<artifactId>restiapi</artifactId>
<version>0.0.1-SNAPSHOT</version>
<name>restiapi</name>
<description>Demo project for Spring Boot</description>
<properties>
<java.version>17</java.version>
</properties>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-rest</artifactId>
</dependency>
<dependency>
<groupId>org.firebirdsql.jdbc</groupId>
<artifactId>jaybird-jdk17</artifactId>
<version>3.0.10</version>
</dependency>
<dependency>
<groupId>org.hibernate.orm</groupId>
<artifactId>hibernate-community-dialects</artifactId>
</dependency>
<dependency>
<groupId>net.java.dev.jna</groupId>
<artifactId>jna</artifactId>
<version>5.5.0</version>
</dependency>
<dependency>
<groupId>com.mysql</groupId>
<artifactId>mysql-connector-j</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.boot</groupId>
<artifactId>spring-boot-starter-data-jpa</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter</artifactId>
</dependency>
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<optional>true</optional>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
<configuration>
<excludes>
<exclude>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
</exclude>
</excludes>
</configuration>
</plugin>
</plugins>
</build>
</project>
You need to switch to using Jaybird 4.0.8. The problem is that Jaybird 4.0.7 and earlier used a grammar generated with ANTLR 4.7.2 (or earlier). Hibernate 6 upgraded to ANTLR 4.10 (or higher), and there was an incompatible change in ANTLR 4.10, which means the grammar of Jaybird cannot be loaded when ANTLR 4.10 or higher is on the classpath, and vice versa, grammars from libraries using ANTLR 4.10 or higher (like Hibernate) cannot be loaded if ANTLR 4.7.x is on the classpath.
Jaybird 4.0.8 fixed that by removing the reliance on ANTLR 4.7.2 by replacing it with a dependency-less parser.
As an aside, normally you should let Spring Boot handle the dependency version of Jaybird, but Spring Boot 3.0.0 currently defines version 4.0.7.java11.
In any case, remove your current Jaybird dependency (as you're depending on the deprecated artifactId jaybird-jdk17, which is for Java 1.7, not Java 17!) and add:
<dependency>
<groupId>org.firebirdsql.jdbc</groupId>
<artifactId>jaybird</artifactId>
<version>4.0.8.java11</version>
</dependency>
I do recommend you check the Jaybird 4 release notes if there are any relevant or breaking changes for you.
If you upgrade to Spring Boot 3.0.1 or higher, you can use:
<dependency>
<groupId>org.firebirdsql.jdbc</groupId>
<artifactId>jaybird</artifactId>
</dependency>
and let Spring Boot manage the dependency version.
As an aside, I notice that you have a dependency on net.java.dev.jna:jna listed. If you added that because of Jaybird, then you should remove it. Jaybird only needs JNA when you use native or embedded connections, but your code uses a pure-java JDBC URL for Firebird, so there is no need to add JNA.
My Spring beans are not getting initialized in Spring Java Config which I am using to create a sample Spring REST Application(As No Web.xml is required I have deleted it) . And also getting 404 while calling the REST endpoint /dest/types.
Can anyone please help. Project Structure
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/maven-v4_0_0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>com.travel</groupId>
<artifactId>patcyyRestApp</artifactId>
<packaging>war</packaging>
<version>0.0.1-SNAPSHOT</version>
<name>patcyyRestApp Maven Webapp</name>
<url>http://maven.apache.org</url>
<properties>
<springframework.version>5.0.9.RELEASE</springframework.version>
<jackson.library>2.9.6</jackson.library>
<maven.compiler.source>1.8</maven.compiler.source>
<maven.compiler.target>1.8</maven.compiler.target>
<hibernate.core.version>5.3.6.Final</hibernate.core.version>
<javax.servlet.api.version>3.1.0</javax.servlet.api.version>
<lombok.version>1.18.12</lombok.version>
<apache.commons.version>3.9</apache.commons.version>
<failOnMissingWebXml>false</failOnMissingWebXml>
</properties>
<dependencies>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-core</artifactId>
<version>${springframework.version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-webmvc</artifactId>
<version>${springframework.version}</version>
</dependency>
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>javax.servlet-api</artifactId>
<version>${javax.servlet.api.version}</version>
</dependency>
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-databind</artifactId>
<version>${jackson.library}</version>
</dependency>
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-core</artifactId>
<version>${hibernate.core.version}</version>
</dependency>
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<version>${lombok.version}</version>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-lang3</artifactId>
<version>${apache.commons.version}</version>
</dependency>
</dependencies>
<build>
<finalName>patcyyRestApp</finalName>
</build>
</project>
Dispatch Initializer :
package com.patcyy.rest.config;
import org.springframework.web.servlet.support.AbstractAnnotationConfigDispatcherServletInitializer;
public class PatcyyDispatcherServletInitializer extends
AbstractAnnotationConfigDispatcherServletInitializer {
#Override
protected Class<?>[] getRootConfigClasses() {
return null;
}
#Override
protected Class<?>[] getServletConfigClasses() {
System.out.println("Inside getServletConfigClasses");
return new Class[] { PatcyyConfig.class };
}
#Override
protected String[] getServletMappings() {
System.out.println("Inside mapping");
return new String[] { "/patcyy" };
}
}
Config :
package com.patcyy.rest.config;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.EnableWebMvc;
#Configuration
#EnableWebMvc
#ComponentScan("com.patcyy.rest")
public class PatcyyConfig {
}
Controller :
package com.patcyy.rest.controller;
import java.util.List;
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.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import com.patcyy.rest.response.DestinationTypes;
import com.patcyy.rest.service.IDestinationService;
#RestController
#RequestMapping(path = "/dest", consumes = MediaType.APPLICATION_JSON_UTF8_VALUE, produces =
MediaType.APPLICATION_JSON_UTF8_VALUE)
public class DestinationController extends BaseController {
private final IDestinationService iDestinationService;
/**
* #param iDestinationService
*/
public DestinationController(#Autowired IDestinationService iDestinationService) {
super();
this.iDestinationService = iDestinationService;
}
#GetMapping("/types")
public ResponseEntity<List<DestinationTypes>> getDestinationTypes() {
List<DestinationTypes> destTypes = iDestinationService.getDestinationTypes();
return new ResponseEntity<List<DestinationTypes>>(destTypes, HttpStatus.OK);
}
}
I had to do two modifications to resolve the issue.
As i am using Java Config only, I had deleted the Web.xml. So i had to make changes in server.xml for Tomcat as :
<Context path="/patcyyRestApp" reloadable="true" docBase="D:\battleGround\patcyyRestApp\target\patcyyRestApp"/></Host>
I had to update the servlet mapping in the Dispatcher Intializer as :
return new String[] { "/patcyy/*" };
After making this two changes, It is working fine now.
Please take a look into this Tomcat without web xml
Please share console log for further investigation. As per my understanding after seeing above code , you can replace
"/patcyy" with only "/"
in getServletMappings() method.
your requested resource url will be like:
http://{hostname:port}/patcyyRestApp/dest/types
It's occurring due to invalid url servlet mapping.
i think the problem is in ComponentScan().
#ComponentScan annotation along with #Configuration annotation to specify the packages that we want to be scanned. #ComponentScan without arguments tells Spring to scan the current package and all of its sub-packages.
in your case you need to add basepackages="com.patcyy.rest"
I'm trying to write a simple unit test. This test function will call my service, which grabs info from the database, pushes it to a list and returns it. I've looked high and low in the debug logs to find what could be causing, but it seems nothing on the web is helping me out. I'm not too familiar with Spring Boot, but it seems surprising that all this effort and I am unable to get a simple unit test to pass.
Error Logs
http://text-share.com/view/fb0369c3
Error creating bean with name 'entityManagerFactory' defined in class path resource [org/springframework/boot/autoconfigure/orm/jpa/HibernateJpaAutoConfiguration.class]: Invocation of init method failed;
Example Test
package com.algoq.algoq;
import com.algoq.algoq.models.Subscriber;
import com.algoq.algoq.respositories.SubscriberRepository;
import com.algoq.algoq.services.AlgorithmService;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.boot.test.context.TestConfiguration;
import org.springframework.boot.test.mock.mockito.MockBean;
import org.springframework.context.annotation.Bean;
import org.springframework.test.context.junit4.SpringRunner;
import java.util.ArrayList;
import static org.assertj.core.api.Assertions.assertThat;
#RunWith(SpringRunner.class)
#TestConfiguration
#SpringBootTest(classes = {
AlgoQApplication.class,
})
public class ExampleTest extends AlgoQApplicationTests {
#Autowired
private AlgorithmService aService;
#MockBean
private SubscriberRepository employeeRepository;
#Bean
public AlgorithmService aService() {
return new AlgorithmService();
}
#Test
public void subscriberListNull() throws Exception {
ArrayList<Subscriber> subs = aService.getSubscribers();
assertThat(subs).isEmpty();
}
}
Service
package com.algoq.algoq.services;
import com.algoq.algoq.models.Subscriber;
import com.algoq.algoq.respositories.SubscriberRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.stereotype.Service;
import java.lang.reflect.Array;
import java.util.ArrayList;
import java.util.List;
#Service
public class AlgorithmService {
#Autowired
private SubscriberRepository subRep;
/**
* Gets a list of subscribers to return to the API
* #return
*/
public ArrayList<Subscriber> getSubscribers() {
ArrayList<Subscriber> subscribers = new ArrayList<>();
subRep.findAll()
.forEach(subscribers::add);
return subscribers;
}
/**
* Adds a new subscriber to the database
* #param sub
* #return
*/
public void addSubscriber(Subscriber sub) {
subRep.save(sub);
}
/**
* Finds a single user id
* #param email
* #return
*/
public List<Subscriber> getSubscriber(String email) {
return subRep.findByEmailAddress(email);
}
}
Application
package com.algoq.algoq;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
#SpringBootApplication
//#EnableScheduling
public class AlgoQApplication {
public static void main(String[] args) {
SpringApplication.run(AlgoQApplication.class, args);
}
}
POM
<?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>com.algoQ</groupId>
<artifactId>algo-q</artifactId>
<version>0.0.1-SNAPSHOT</version>
<packaging>jar</packaging>
<name>algo-q</name>
<description>An algorithm a day keeps the brain up to date</description>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>1.5.9.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>
</properties>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-rest</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
</dependency>
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-core</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-mail</artifactId>
</dependency>
<dependency>
<groupId>com.itextpdf</groupId>
<artifactId>itextpdf</artifactId>
<version>5.5.12</version>
</dependency>
<dependency>
<groupId>com.itextpdf.tool</groupId>
<artifactId>xmlworker</artifactId>
<version>5.5.12</version>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-thymeleaf</artifactId>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
</dependency>
<dependency>
<groupId>org.python</groupId>
<artifactId>jython-standalone</artifactId>
<version>2.5.3</version>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-jpa</artifactId>
<version>1.5.2.RELEASE</version>
</dependency>
<!--<dependency>-->
<!--<groupId>com.h2database</groupId>-->
<!--<artifactId>h2</artifactId>-->
<!--<version>1.4.194</version>-->
<!--</dependency>-->
<dependency>
<groupId>org.pygments</groupId>
<artifactId>pygments</artifactId>
<version>1.5</version>
<scope>runtime</scope>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build>
</project>
The real cause of the exception is
java.lang.ClassNotFoundException: javax.xml.bind.JAXBException
So I believe you need to add JAXBE library to your classpath (it was removed from JDK in java9 and I guess you are using java9)
Try to add this to your pom file
<!-- https://mvnrepository.com/artifact/javax.xml.bind/jaxb-api -->
<dependency>
<groupId>javax.xml.bind</groupId>
<artifactId>jaxb-api</artifactId>
<version>2.3.0</version>
</dependency>
JDK
/Library/Java/JavaVirtualMachines/jdk-9.0.1.jdk/Contents/Home/bin/java
pom.xml
1.8
Are you using java 8 or 9 ?
org.springframework.beans.factory.BeanCreationException: Error
creating bean with name 'entityManagerFactory' defined in class path
resource
[org/springframework/boot/autoconfigure/orm/jpa/HibernateJpaAutoConfiguration.class]:
Invocation of init method failed; nested exception is
java.lang.NoClassDefFoundError: javax/xml/bind/JAXBException
Issue with java.lang.NoClassDefFoundError: javax/xml/bind/JAXBException ,
Run the application with Java 8 environement or Include the JAXB library for Java 9, JAXB API are not included in JAVA SE 9. Refer Deprecated, for removal: This API element is subject to removal in a future version.. Use --add-modules ( --add-modules java.xml.bind ) to add module in classpath. Jave has only deprecated and does not add javax.xml.bind module on classpath by default.
Otherwise include as dependency through maven.
<dependency>
<groupId>javax.xml.bind</groupId>
<artifactId>jaxb-api</artifactId>
<version>2.3.0</version>
</dependency>
I tried to configure EhCache programmatically, but I have some problems... Firstly, I tried to use the newest version, where I just created config class with just one method and then I get the error java.lang.ClassNotFoundException: com.google.common.cache.CacheBuilderSpec.
I tried with lower version, which is 2.10.4, which is already in Spring Boot, but now I'm getting an error that CacheManager must not be null and I have no idea what is the problem... Probably I'm missing something, but I don't know what...
Current code with Ehcache 2.X:
import org.springframework.cache.CacheManager;
import org.springframework.cache.annotation.CachingConfigurer;
import org.springframework.cache.annotation.EnableCaching;
import org.springframework.cache.ehcache.EhCacheCacheManager;
import org.springframework.cache.interceptor.CacheErrorHandler;
import org.springframework.cache.interceptor.CacheResolver;
import org.springframework.cache.interceptor.KeyGenerator;
import org.springframework.cache.interceptor.SimpleCacheErrorHandler;
import org.springframework.cache.interceptor.SimpleCacheResolver;
import org.springframework.cache.interceptor.SimpleKeyGenerator;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import net.sf.ehcache.config.CacheConfiguration;
#Configuration
#EnableCaching
public class EhCacheConfiguration implements CachingConfigurer {
#Bean(destroyMethod = "shutdown")
public net.sf.ehcache.CacheManager ehCacheManager() {
CacheConfiguration cacheConfiguration = new CacheConfiguration();
cacheConfiguration.setName("myCacheName");
cacheConfiguration.setMemoryStoreEvictionPolicy("LRU");
cacheConfiguration.setMaxEntriesLocalHeap(1000);
net.sf.ehcache.config.Configuration config = new net.sf.ehcache.config.Configuration();
config.addCache(cacheConfiguration);
return net.sf.ehcache.CacheManager.newInstance(config);
}
#Bean
#Override
public CacheManager cacheManager() {
return new EhCacheCacheManager(ehCacheManager());
}
#Bean
#Override
public KeyGenerator keyGenerator() {
return new SimpleKeyGenerator();
}
#Bean
#Override
public CacheResolver cacheResolver() {
return new SimpleCacheResolver();
}
#Bean
#Override
public CacheErrorHandler errorHandler() {
return new SimpleCacheErrorHandler();
}
}
Previous version of code with Ehcache 3.X:
import static org.ehcache.config.builders.CacheConfigurationBuilder.newCacheConfigurationBuilder;
import static org.ehcache.config.builders.CacheManagerBuilder.newCacheManagerBuilder;
import static org.ehcache.config.builders.ResourcePoolsBuilder.newResourcePoolsBuilder;
import java.util.concurrent.TimeUnit;
import org.ehcache.CacheManager;
import org.ehcache.config.units.EntryUnit;
import org.ehcache.config.units.MemoryUnit;
import org.ehcache.expiry.Duration;
import org.ehcache.expiry.Expirations;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.cache.annotation.EnableCaching;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
#Configuration
#EnableCaching
public class EhCacheConfiguration {
private static final Logger log = LoggerFactory.getLogger(EhCacheConfiguration.class);
#Bean
public CacheManager ehCacheManager() {
log.info("Creating cache manager programmatically");
try (CacheManager cacheManager = newCacheManagerBuilder()
.withCache("sessionCache",
newCacheConfigurationBuilder(Long.class, String.class,
newResourcePoolsBuilder().heap(2000, EntryUnit.ENTRIES).offheap(1, MemoryUnit.GB))
.withExpiry(Expirations.timeToLiveExpiration(Duration.of(30, TimeUnit.MINUTES)))
.withExpiry(Expirations.timeToIdleExpiration(Duration.of(5, TimeUnit.MINUTES))))
.build(true)) {
return cacheManager;
}
}
The class is in the subpackage of package where is the MyApplication class.
MyApplication class:
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.builder.SpringApplicationBuilder;
import org.springframework.boot.web.support.SpringBootServletInitializer;
import org.springframework.data.jpa.repository.config.EnableJpaRepositories;
import org.springframework.web.WebApplicationInitializer;
#SpringBootApplication
#EnableJpaRepositories
public class MyApplication extends SpringBootServletInitializer implements WebApplicationInitializer {
#Override
protected SpringApplicationBuilder configure(SpringApplicationBuilder application) {
return application.sources(MyApplication.class);
}
public static void main(String[] args) {
SpringApplication.run(MyApplication.class, args);
}
}
Application is using Spring Boot and is running on WebLogic server...
Edit:
Added pom.xml:
<?xml version="1.0"?>
<project
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"
xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
<modelVersion>4.0.0</modelVersion>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>1.5.3.RELEASE</version>
<relativePath /> <!-- lookup parent from repository -->
</parent>
<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
</properties>
<groupId>com.app.lui.serviceweb</groupId>
<artifactId>lui-serviceWeb</artifactId>
<packaging>war</packaging>
<name>lui-serviceWeb</name>
<description>Lui Project</description>
<dependencies>
<dependency>
<groupId>com.app.lui.drools</groupId>
<artifactId>lui-drools</artifactId>
<version>0.0.1-SNAPSHOT</version>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-aop</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-cache</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-devtools</artifactId>
<scope>runtime</scope>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-configuration-processor</artifactId>
<optional>true</optional>
</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-tomcat</artifactId>
<scope>provided</scope>
</dependency>
<!-- Apache CXF -->
<dependency>
<groupId>org.apache.cxf</groupId>
<artifactId>cxf-spring-boot-starter-jaxws</artifactId>
<version>3.1.11</version>
</dependency>
<!-- DB -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-jdbc</artifactId>
</dependency>
<!-- Ehcache -->
<dependency>
<groupId>net.sf.ehcache</groupId>
<artifactId>ehcache</artifactId>
</dependency>
</dependencies>
<build>
<finalName>lui-serviceWeb</finalName>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-war-plugin</artifactId>
<configuration>
<failOnMissingWebXml>false</failOnMissingWebXml>
<archive>
<manifest>
<addDefaultImplementationEntries>false</addDefaultImplementationEntries>
</manifest>
</archive>
</configuration>
</plugin>
</plugins>
</build>
</project>
EDIT 2:
Added project:
Ehcache project
Logs:
Ehcache 2.X stack trace
Ehcache 3.X stack trace
You need the cacheResolver to know the cacheManager.
So, in your current code, just replace the cacheResolver bean with:
#Bean
#Override
public CacheResolver cacheResolver() {
return new SimpleCacheResolver(cacheManager());
}
And it is done. Might be the same for EhCache 3.X but I didn't test it.
Hope it helps.
We will need a fully working project to answer wit certainty. Right now, I tried your code and had to hack around to make it compile. CacheBuilderSpec is indeed a guava thing. So it seems Spring is picking Guava as its cache implementation, not Ehcache.
You might want to debug CacheAutoConfiguration and GuavaCacheConfiguration. The latter will be initialized at some point by Spring.
Netty server instantiation in Arjen Poutsma's blog post and Josh Long's video example is done by creating an reactor.ipc.netty.http.HttpServer instance and then calling it's start or startAndAwait method with an ReactorHttpHandlerAdapter instance as an argument.
However the API seems to have changed as now start and startAndAwait methods now expect a lambda with the following signature:
java.util.function.Function<? super reactor.ipc.netty.http.HttpChannel,? extends org.reactivestreams.Publisher<java.lang.Void>>
Project dependencies and their versions are the same as in Arjen Poutsma's example project
<dependency>
<groupId>org.reactivestreams</groupId>
<artifactId>reactive-streams</artifactId>
<version>1.0.0</version>
</dependency>
<dependency>
<groupId>io.projectreactor</groupId>
<artifactId>reactor-core</artifactId>
<version>3.0.3.RELEASE</version>
</dependency>
<dependency>
<groupId>io.projectreactor.ipc</groupId>
<artifactId>reactor-netty</artifactId>
<version>0.5.2.RELEASE</version>
</dependency>
<dependency>
<groupId>org.apache.tomcat.embed</groupId>
<artifactId>tomcat-embed-core</artifactId>
<version>8.5.4</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-web-reactive</artifactId>
<version>5.0.0.BUILD-SNAPSHOT</version>
</dependency>
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-databind</artifactId>
<version>2.8.2</version>
</dependency>
What is the new/proper way of instantiating a netty server with spring reactor support?
The recommended way to set up project for now is to use http://start.spring.io/ as Josh Long suggests in his video. This is because spring reactive is only release candidate now and we need compatible versions to run samples.This is achieved via adding this piece to code:
<dependencyManagement>
<dependencies>
<dependency>
<groupId>org.springframework.boot.experimental</groupId>
<artifactId>spring-boot-dependencies-web-reactive</artifactId>
<version>0.1.0.BUILD-SNAPSHOT</version>
<type>pom</type>
<scope>import</scope>
</dependency>
</dependencies>
</dependencyManagement>
According your question about HttpServer interface change, the minimal working example is the following:
import org.reactivestreams.Publisher;
import org.springframework.http.server.reactive.HttpHandler;
import org.springframework.http.server.reactive.ReactorHttpHandlerAdapter;
import org.springframework.web.reactive.function.RouterFunction;
import org.springframework.web.reactive.function.ServerRequest;
import org.springframework.web.reactive.function.ServerResponse;
import reactor.core.publisher.Mono;
import reactor.ipc.netty.http.server.HttpServer;
import java.io.IOException;
import static org.springframework.web.reactive.function.RequestPredicates.GET;
import static org.springframework.web.reactive.function.RouterFunctions.route;
import static org.springframework.web.reactive.function.RouterFunctions.toHttpHandler;
public class FunctionalReactiveServer {
public static final String HOST = "localhost";
public static final int PORT = 8080;
public static void main(String[] args) throws InterruptedException, IOException {
RouterFunction<?> route = route(GET("/sayHello"), FunctionalReactiveServer::sayHelloHandler);
HttpHandler httpHandler = toHttpHandler(route);
ReactorHttpHandlerAdapter adapter = new ReactorHttpHandlerAdapter(httpHandler);
HttpServer server = HttpServer.create(HOST, PORT);
server.newHandler(adapter).block();
System.out.println("Press ENTER to exit.");
System.in.read();
}
public static ServerResponse<Publisher<String>> sayHelloHandler(ServerRequest request) {
return ServerResponse.ok().body(Mono.just("Hello!"), String.class);
}
}