I'm doing a CRUD for a collection named Schema and need to retrieve de _id as a hexadecimal string, but when i use the collection.find() i get the timestamp and date instead of the string.
I'm receving this structure:
{
"_id": {
"timestamp": 1604689898,
"date": "2020-11-06T19:11:38.000+00:00"
}
}
But i need something like this:
{
"_id": "5fa5a085a4b09b307d53ed57"
}
Here are my configurations
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>2.3.4.RELEASE</version>
<relativePath/> <!-- lookup parent from repository -->
</parent>
<groupId>co.com.itau</groupId>
<artifactId>crypto-mongodb-java-ms</artifactId>
<version>0.0.1-SNAPSHOT</version>
<name>crypto-mongodb-java-ms</name>
<description>Microservice to save and read data from mongoDB using CSFLE</description>
<properties>
<java.version>1.8</java.version>
<version.fabric8-maven-plugin>3.5.41</version.fabric8-maven-plugin>
<swagger.version>3.0.0</swagger.version>
</properties>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-mongodb</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-validation</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.plugin</groupId>
<artifactId>spring-plugin-core</artifactId>
<version>2.0.0.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-rest</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-web-services</artifactId>
</dependency>
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<optional>true</optional>
</dependency>
<dependency>
<groupId>com.google.code.gson</groupId>
<artifactId>gson</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-devtools</artifactId>
</dependency>
<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-boot-starter</artifactId>
<version>${swagger.version}</version>
</dependency>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-netflix-hystrix</artifactId>
<version>2.1.2.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework.plugin</groupId>
<artifactId>spring-plugin-core</artifactId>
<version>2.0.0.RELEASE</version>
</dependency>
<dependency>
<groupId>org.mongodb</groupId>
<artifactId>mongodb-crypt</artifactId>
<version>1.0.1</version>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
<exclusions>
<exclusion>
<groupId>org.junit.vintage</groupId>
<artifactId>junit-vintage-engine</artifactId>
</exclusion>
</exclusions>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build>
<profiles>
<profile>
<id>openshift</id>
<build>
<plugins>
<plugin>
<groupId>io.fabric8</groupId>
<artifactId>fabric8-maven-plugin</artifactId>
<version>${version.fabric8-maven-plugin}</version>
<executions>
<execution>
<id>fmp</id>
<phase>package</phase>
<goals>
<goal>resource</goal>
<goal>build</goal>
</goals>
</execution>
</executions>
<configuration>
<generator>
<config>
<spring-boot>
<fromMode>isTag</fromMode>
<from>redhat-openjdk18-openshift:1.2</from>
</spring-boot>
</config>
</generator>
</configuration>
</plugin>
</plugins>
</build>
</profile>
</profiles>
</project>
MongoClient configuration
CodecRegistry pojoCodecRegistry = fromProviders(PojoCodecProvider.builder().automatic(true).build());
CodecRegistry codecRegistry = fromRegistries(MongoClientSettings.getDefaultCodecRegistry(), pojoCodecRegistry);
MongoClient mongoAux = MongoClients.create(MongoClientSettings.builder()
.applyConnectionString(new ConnectionString(connectionString))
.codecRegistry(codecRegistry)
.build());
return mongoAux;
Schema Model
#Data
#AllArgsConstructor
#NoArgsConstructor
public class Schema {
#JsonProperty("_id")
#SerializedName("_id")
public ObjectId id;
public String db;
public String collection;
public Document schema;
}
** Repository **
#Repository
public class SchemaMongoRepository implements SchemaRepository{
#Value("${mongodb.schema.db}")
private String mongoDatabase;
#Value("${mongodb.schema.collection}")
private String mongoCollection;
private static final Logger logger = LoggerFactory.getLogger(SchemaMongoRepository.class);
#Autowired
private MongoClient mongoClient;
#Autowired
private DataKey datakey;
private MongoCollection<Schema> schemaCollection;
#PostConstruct
void init() {
schemaCollection = mongoClient.getDatabase(mongoDatabase).getCollection(mongoCollection, Schema.class);
}
#Override
public List<Schema> getSchemas() {
List<Schema> schemaList = new ArrayList<Schema>();
FindIterable<Schema> result = schemaCollection.find();
for(Schema currentSchema: result) {
schemaList.add(currentSchema);
}
return schemaList;
}
}
The problem you face is ObjectId becomes extended (Deserialized). we make it serialization.Add this dependency in pom
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-databind</artifactId>
<version>2.11.0.rc1</version>
</dependency>
Add the following method in main class.
#Bean
public Jackson2ObjectMapperBuilderCustomizer customizer()
{
return builder -> builder.serializerByType(ObjectId.class,new ToStringSerializer());
}
This will give you expected output.
In my case, using Kotlin it was so simple as to add a Jackson JSON serializer:
#JsonSerialize(using = ToStringSerializer::class)
val id: ObjectId = ObjectId.get(),
In order to get:
{
"id": "622b34af87c70514f6452363",
...
}
instead of:
{
"id": {
"timestamp": 1646998703,
"date": "2022-03-11T11:38:23.000+00:00"
},
...
}
Related
I have thought that it could be a dependency problem and I have looked at the pom.xml and I consider that I have everything I need
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.1</version>
<relativePath/> <!-- lookup parent from repository -->
</parent>
<groupId>com.home</groupId>
<artifactId>class</artifactId>
<version>0.0.1-SNAPSHOT</version>
<name>class</name>
<description>AquĆ estan las clases</description>
<properties>
<java.version>17</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-devtools</artifactId>
<scope>runtime</scope>
<optional>true</optional>
</dependency>
<dependency>
<groupId>com.oracle.database.jdbc</groupId>
<artifactId>ojdbc8</artifactId>
<scope>runtime</scope>
</dependency>
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<optional>true</optional>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>jstl</artifactId>
<version>1.2</version>
</dependency>
<dependency>
<groupId>org.modelmapper</groupId>
<artifactId>modelmapper</artifactId>
<version>3.1.1</version>
</dependency>
<dependency>
<groupId>org.jetbrains</groupId>
<artifactId>annotations</artifactId>
<version>RELEASE</version>
<scope>compile</scope>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
<version>3.0.1</version>
<configuration>
<excludes>
<exclude>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
</exclude>
</excludes>
</configuration>
</plugin>
</plugins>
</build>
</project>
Then I thought that it could be a problem with the controller that is not returning data or redirecting correctly but I can't think of what it could be
My controller
#RestController
public class PruebaController {
#Autowired
private PersonaService personaService;
#GetMapping(value="/index",produces = MediaType.APPLICATION_JSON_VALUE)
public ResponseEntity<Object> index(){
return ResponseEntity.ok(this.personaService.findAll());
}
}
The problem is that when I do the command -> "spring-boot:run" and go to the link I get -> Error 404
I am also sure that the connection to the database is made perfectly so I only have to rule out that the service is done wrong but I don't know what it could be
PersonaService.java
public interface PersonaService {
Page<PersonaDTO> findAll();
PersonaDTO findByNSS(String NSS);
PersonaDTO findByNumTarjeta(String numTarjeta);
void save(PersonaDTO paciente);
void saveAll(List<PersonaDTO> pacientes);
void deleteById(Long id);
}
and this is my file
PersonaImpl.java
package Services.Implementation;
import DTO.PersonaDTO;
import Repository.PersonaRepository;
import Services.Interfaces.PersonaService;
import Utils.MHelpers;
import com.example.demo.Persona;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.stereotype.Component;
import java.util.ArrayList;
import java.util.List;
import java.util.Optional;
#Component
public class PersonaImpl implements PersonaService {
#Autowired
private PersonaRepository PersonaRepository;
#Override
public Page<PersonaDTO> findAll() {
Page<Persona> personas = this.PersonaRepository.findAll();
return personas.map(this::convertToPersonaDTO);
}
#Override
public PersonaDTO findByNSS(String NSS) {
Optional<Persona> personas = this.PersonaRepository.findByNSS(NSS);
if (!personas.isPresent()){
return null;
}
return MHelpers.modelMapper().map(personas.get(),PersonaDTO.class);
}
#Override
public PersonaDTO findByNumTarjeta(String numTarjeta) {
Optional<Persona> personas = this.PersonaRepository.findByNumTarjeta(numTarjeta);
if (!personas.isPresent()){
return null;
}
return MHelpers.modelMapper().map(personas.get(),PersonaDTO.class);
}
#Override
public void save(PersonaDTO personaDTO) {
Persona persona = MHelpers.modelMapper().map(personaDTO, Persona.class);
this.PersonaRepository.save(persona);
}
#Override
public void saveAll(List<PersonaDTO> personas) {
List<Persona> p = new ArrayList<>();
for (PersonaDTO persona: personas) {
Persona pers = MHelpers.modelMapper().map(persona,Persona.class);
p.add(pers);
}
this.PersonaRepository.saveAll(p);
}
#Override
public void deleteById(Long id) {
this.PersonaRepository.deleteById(id);
}
private PersonaDTO convertToPersonaDTO(final Persona persona){
return MHelpers.modelMapper().map(persona,PersonaDTO.class);
}
}
If you need more information tell me
My application originally used only Hibernate and everything worked fine, but with Spring i'm getting an exception. It feels like Spring causes different behavior for Hibernate.
So with Spring & Hibernate i get this exception trace:
Stack trace photo_1
Stack trace photo_2
hibernate.cfg.xml
<?xml version='1.0' encoding='utf-8'?>
<!DOCTYPE hibernate-configuration PUBLIC
"-//Hibernate/Hibernate Configuration DTD//EN"
"http://www.hibernate.org/dtd/hibernate-configuration-3.0.dtd">
<hibernate-configuration>
<session-factory>
<!-- Database connection settings -->
<property name="connection.driver_class">com.mysql.cj.jdbc.Driver</property>
<property name="connection.url">jdbc:mysql://localhost:3306/IndexingAndSearching?
serverTimezone=UTC</property>
<property name="connection.CharSet">utf8</property>
<property name="connection.characterEncoding">utf8</property>
<property name="connection.useUnicode">true</property>
<property name="connection.username">test</property>
<property name="connection.password">test</property>
<property name="connection.pool_size">20</property>
<property name="dialect">org.hibernate.dialect.MySQL57Dialect</property>
<property name="current_session_context_class">thread</property>
<property name="cache.provider_class">org.hibernate.cache.NoCacheProvider</property>
<property name="show_sql">false</property>
<property name="hbm2ddl.auto">validate</property>
</session-factory>
</hibernate-configuration>
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>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.6.6</version>
<relativePath/> <!-- lookup parent from repository -->
</parent>
<groupId>IndexingAndSearching</groupId>
<artifactId>IndexingAndSearching</artifactId>
<version>1.0-SNAPSHOT</version>
<build>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<version>3.1</version>
<configuration>
<source>11</source>
<target>11</target>
</configuration>
</plugin>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build>
<properties>
<java.version>11</java.version>
</properties>
<dependencies>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.12</version>
<scope>test</scope>
</dependency>
<!-- Lucene -->
<dependency>
<groupId>org.apache.lucene</groupId>
<artifactId>lucene-core</artifactId>
<version>9.0.0</version>
</dependency>
<dependency>
<groupId>org.apache.lucene</groupId>
<artifactId>lucene-analyzers-common</artifactId>
<version>8.11.1</version>
</dependency>
<dependency>
<groupId>org.apache.lucene</groupId>
<artifactId>lucene-queryparser</artifactId>
<version>9.0.0</version>
</dependency>
<dependency>
<groupId>commons-io</groupId>
<artifactId>commons-io</artifactId>
<version>2.4</version>
</dependency>
<dependency>
<groupId>com.google.code.gson</groupId>
<artifactId>gson</artifactId>
<version>2.9.0</version>
</dependency>
<!-- Hibernate -->
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-core</artifactId>
<version>5.6.7.Final</version>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>8.0.28</version>
</dependency>
<dependency>
<groupId>org.jsoup</groupId>
<artifactId>jsoup</artifactId>
<version>1.14.3</version>
</dependency>
<!-- Logger -->
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-api</artifactId>
<version>1.7.36</version>
</dependency>
<!-- JUnit -->
<dependency>
<groupId>org.junit.jupiter</groupId>
<artifactId>junit-jupiter</artifactId>
<version>RELEASE</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>com.google.guava</groupId>
<artifactId>guava</artifactId>
<version>31.1-jre</version>
</dependency>
<!-- Spring -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-actuator</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>
<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-thymeleaf</artifactId>
</dependency>
All of my DAO methods for mysql are written with sessionFactory
Links - my only table
#Entity(name = "links")
#Table(name = "links")
#DynamicInsert // To set initial value of fields, otherwise doesn't work
public class Links implements Serializable {
#Id
private String link;
#Enumerated
#Column(columnDefinition = "smallint")
private Status status;
#Version
private int version;
private int depth;
private long owner;
public Links() {
} // hibernate requirement
public Links(String link, Status status, int depth) throws URISyntaxException {
assert depth >= 0;
assert !LinkParser.isBlank(link);
this.link = link;
this.status = status;
this.depth = depth;
this.owner = 0;
}
public String getLink() {
return link;
}
private void setLink(String link) {
this.link = link;
}
public int getVersion() {
return version;
}
private void setVersion(int version) {
this.version = version;
}
public Status getStatus() {
return status;
}
public void setStatus(Status status) {
this.status = status;
}
public int getDepth() {
return depth;
}
private void setDepth(int depth) {
this.depth = depth;
}
public long getOwner() {
return owner;
}
public void setOwner(long owner) {
assert owner >= 0;
this.owner = owner;
}
application.properties
server.port=8080
server.servlet.context-path=/webcrawler
Only difference is when i start application with Spring, i dont get these exceptions when i dont use Spring.
I think the issue is from the fact that you setter is private and should be public
private void setLink(String link) {
this.link = link;
}
Should be
public void setLink(String link) {
this.link = link;
}
Same for setVersion and setDepth
I found out, I commented these maven dependencies
<!-- <dependency>-->
<!-- <groupId>org.springframework.boot</groupId>-->
<!-- <artifactId>spring-boot-devtools</artifactId>-->
<!-- <scope>runtime</scope>-->
<!-- <optional>true</optional>-->
<!-- </dependency>-->
<!-- <dependency>-->
<!-- <groupId>org.springframework.boot</groupId>-->
<!-- <artifactId>spring-boot-starter-test</artifactId>-->
<!-- <scope>test</scope>-->
<!-- </dependency>-->
And everything started working... I guess devtools are the reason, dont want to check, I tried so many other stuff, and this is the reason...
I have a very simple CRUD in Java with SpringBoot, and locally it runs perfectly, but I need to upload the .war to a WildFly server. When I do this, it displays correctly, but when I try to consume a service from postman, or enter the context-root, I get "Forbbiden". What configuration should I do, or how can I call the URL?
REST CONTROLLER:
#RestController
#RequestMapping("/v1/ex-excepciones")
public class ExExcepcionesController {
private final ExExcepcionesService exExcepcionesService;
public ExExcepcionesController(ExExcepcionesService exExcepcionesService) {
this.exExcepcionesService = exExcepcionesService;
}
#GetMapping
public List<ExExcepcionesDto> findAll() {
return exExcepcionesService.findAll();
}
#GetMapping("/{id}")
ResponseEntity<ExExcepcionesDto> findById(#PathVariable long id) {
return new ResponseEntity<>(exExcepcionesService.findById(id), HttpStatus.OK);
}
#PostMapping
ResponseEntity<ExExcepcionesDto> create(#RequestBody ExExcepcionesRequest request) {
return new ResponseEntity<>(exExcepcionesService.save(request), HttpStatus.CREATED);
}
#PatchMapping("/{id}")
ResponseEntity<ExExcepcionesDto> update(#PathVariable Long id ,#RequestBody ExExcepcionesRequest request) {
return new ResponseEntity<>(exExcepcionesService.update(id,request), HttpStatus.OK);
}
Este es el Application:
#SpringBootApplication
public class SdmExcepcionesDeiApplication extends SpringBootServletInitializer {
#Override
protected SpringApplicationBuilder configure(SpringApplicationBuilder application) {
return application.sources(Application.class);
}
#Bean
public WebMvcConfigurer corsConfigurer() {
return new WebMvcConfigurer() {
public void addCorsMappings(CorsRegistry registry) {
registry.addMapping("/**")
.allowedMethods("GET", "POST", "PUT", "DELETE", "PATCH", "OPTIONS");
}
};
}
#Override
public void onStartup(ServletContext servletContext) throws ServletException {
}
public static void main(String[] args) {
SpringApplication.run(SdmExcepcionesDeiApplication.class, args);
}
}
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 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>2.5.10</version>
<relativePath/> <!-- lookup parent from repository -->
</parent>
<groupId>com.sdm.excepciones.dei</groupId>
<artifactId>SDM</artifactId>
<version>1</version>
<packaging>war</packaging>
<name>SDM</name>
<description>SDM</description>
<properties>
<java.version>1.8</java.version>
<org.mapstruct.version>1.4.2.Final</org.mapstruct.version>
</properties>
<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>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-jpa</artifactId>
</dependency>
<dependency>
<groupId>com.oracle.database.jdbc</groupId>
<artifactId>ojdbc8</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.projectlombok</groupId>
<artifactId>lombok</artifactId>
<version>1.18.22</version>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok-mapstruct-binding</artifactId>
<version>0.2.0</version>
</dependency>
<dependency>
<groupId>org.mapstruct</groupId>
<artifactId>mapstruct-processor</artifactId>
<version>1.4.2.Final</version>
</dependency>
<dependency>
<groupId>org.mapstruct</groupId>
<artifactId>mapstruct</artifactId>
<version>1.4.2.Final</version>
</dependency>
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>javax.servlet-api</artifactId>
<scope>provided</scope>
</dependency>
</dependencies>
<build>
<finalName>SDM</finalName>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<version>3.5.1</version>
<configuration>
<source>1.8</source>
<target>1.8</target>
<annotationProcessorPaths>
<path>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<version>1.18.22</version>
</path>
<path>
<groupId>org.mapstruct</groupId>
<artifactId>mapstruct-processor</artifactId>
<version>1.4.2.Final</version>
</path>
</annotationProcessorPaths>
</configuration>
</plugin>
</plugins>
</build>
</project>
Entering the context-root of the wildfly throws this:
https://i.stack.imgur.com/BZTSn.png
https://i.stack.imgur.com/uwkJ5.png
and When trying to build the URL and consume the rest api:
http://127.0.0.1:8080/SDM/v1/ex-excepciones/
For localhost, it's the same.
http://localhost:8080/SDM/v1/ex-excepciones/
https://i.stack.imgur.com/Mde4Z.png
https://i.stack.imgur.com/FBZ18.png
Many thanks to anyone who can help me with this.
I work with a Spring microservice and received the following errors,
2020-01-20 09:58:22.504 ERROR 13758 --- [nio-8080-exec-1] o.a.c.c.C.[.[localhost].[/].[jsp] : Servlet.service() for servlet [jsp] threw exception
java.lang.ClassNotFoundException: org.apache.tomcat.util.security.Escape
at java.net.URLClassLoader.findClass(URLClassLoader.java:382) ~[na:1.8.0_211]
at java.lang.ClassLoader.loadClass(ClassLoader.java:424) ~[na:1.8.0_211]
at sun.misc.Launcher$AppClassLoader.loadClass(Launcher.java:349) ~[na:1.8.0_211]
at java.lang.ClassLoader.loadClass(ClassLoader.java:357) ~[na:1.8.0_211]
at org.apache.jasper.compiler.JspUtil.getExprInXml(JspUtil.java:85) ~[tomcat-embed-jasper-9.0.29.jar:9.0.29]
at org.apache.jasper.compiler.PageDataImpl$SecondPassVisitor.printAttributes(PageDataImpl.java:736) ~[tomcat-embed-jasper-9.0.29.jar:9.0.29]
In the browser, its provided the error,
Whitelabel Error Page
This application has no explicit mapping for /error, so you are seeing this as a fallback.
Mon Jan 20 09:58:22 BDT 2020
There was an unexpected error (type=Internal Server Error, status=500).
org/apache/tomcat/util/security/Escape
I provide a few code snippets from the respective micro-service,
#SpringBootApplication
#EnableCircuitBreaker
#EnableDiscoveryClient
#EnableFeignClients
public class Application {
public static void main(String[] args) {
SpringApplication.run(Application.class, args);
}
#Bean
public RestTemplate restTemplate(RestTemplateBuilder builder) {
return builder.build();
}
}
The controller class,
#Controller
#Transactional
#RequestMapping("/website/vehicles")
public class VehicleController {
#Autowired
private VehicleRepository data;
#Autowired
private PositionTrackingExternalService externalService;
#PostMapping(value = "/newVehicle.html")
public String newVehicle(Vehicle vehicle) {
data.save(vehicle);
return "redirect:/website/vehicles/list.html";
}
#PostMapping(value = "/deleteVehicle.html")
public String deleteVehicle(#RequestParam Long id) {
data.delete(id);
return "redirect:/website/vehicles/list.html";
}
#GetMapping(value = "/newVehicle.html")
public ModelAndView renderNewVehicleForm() {
Vehicle newVehicle = new Vehicle();
return new ModelAndView("newVehicle", "form", newVehicle);
}
#GetMapping(value = "/list.html")
public ModelAndView vehicles() {
List<Vehicle> allVehicles = data.findAll();
return new ModelAndView("allVehicles", "vehicles", allVehicles);
}
...... ..... ...... ..... ...... .....
...... ..... ...... ..... ...... .....
}
The feign client,
#FeignClient(name = "fleetman-position-tracker")
public interface RemotePositionMicroserviceCalls {
#GetMapping(value = "/vehicles/{name}")
public Position getLatestPositionForVehicle(#PathVariable(value = "name") String name);
}
The service classes,
#Service
public class PositionTrackingExternalService {
#Autowired
private ObjectProvider<RemotePositionMicroserviceCalls> remoteService;
#Autowired
private VehicleRepository repository;
#HystrixCommand(fallbackMethod = "handleExternalServiceDown")
public Position getLatestPositionForVehicleFromRemoteMicroservice(String name) {
Position response = remoteService.getObject().getLatestPositionForVehicle(name);
response.setUpToDate(true);
return response;
}
public Position handleExternalServiceDown(String name) {
// Read the last known position for this vehicle
Position position = new Position();
Vehicle vehicle = repository.findByName(name);
position.setLat(vehicle.getLat());
position.setLongitude(vehicle.getLongitude());
position.setTimestamp(vehicle.getLastRecordedPosition());
position.setUpToDate(false);
return position;
}
}
The project structure,
As requested, the pom.xml file is provided below,
<?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.transport.visualizer</groupId>
<artifactId>transport-visualizer</artifactId>
<version>0.0.1-SNAPSHOT</version>
<packaging>jar</packaging>
<name>TransportVisualizer</name>
<description>Vehicle Transport Visualizer</description>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>1.3.3.RELEASE</version>
<relativePath/> <!-- lookup parent from repository -->
</parent>
<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<java.version>1.8</java.version>
</properties>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-jpa</artifactId>
</dependency>
<dependency>
<groupId>com.h2database</groupId>
<artifactId>h2</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.apache.tomcat.embed</groupId>
<artifactId>tomcat-embed-jasper</artifactId>
</dependency>
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>jstl</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-devtools</artifactId>
<optional>true</optional>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-security</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-eureka</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-ribbon</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-hystrix</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-feign</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-config</artifactId>
</dependency>
</dependencies>
<dependencyManagement>
<dependencies>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-dependencies</artifactId>
<version>Camden.RELEASE</version>
<type>pom</type>
<scope>import</scope>
</dependency>
</dependencies>
</dependencyManagement>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
<resources>
<resource>
<filtering>true</filtering>
<directory>src/main/resources</directory>
<includes>
<include>application.properties</include>
</includes>
</resource>
</resources>
</build>
</project>
What's the issue here and how do I solve it?
Change your jasper dependency as
<dependency>
<groupId>org.apache.tomcat.embed</groupId>
<artifactId>tomcat-embed-jasper</artifactId>
<scope>provided</scope>
</dependency>
The dependency should be configured as with scope provided:
<dependency>
<groupId>org.apache.tomcat.embed</groupId>
<artifactId>tomcat-embed-jasper</artifactId>
<scope>provided</scope>
</dependency>
I am getting a NullPointerException on an autowired bean in a service class. The class I'm trying to autowire is a Cassandra Repository.
My main class Application.java
#SpringBootApplication
#EnableAutoConfiguration
public class Application {
public static void main(String[] args) {
SpringApplication.run(Application.class, args);
}
}
My Cassandra configuration CassandraConfig.java
#Configuration
#EnableCassandraRepositories(basePackages = "com.myretail")
public class CassandraConfig extends AbstractCassandraConfiguration {
#Override
protected String getKeyspaceName() {
return "myretail";
}
#Bean
public CassandraClusterFactoryBean cluster() {
CassandraClusterFactoryBean cluster =
new CassandraClusterFactoryBean();
cluster.setContactPoints("127.0.0.1");
cluster.setPort(9042);
return cluster;
}
#Bean
public CassandraMappingContext cassandraMapping()
throws ClassNotFoundException {
return new BasicCassandraMappingContext();
}
#Bean
public ProductService productService() {
return new ProductService();
}
}
My repository (dao) ProductPriceRepository.java
public interface ProductPriceRepository extends CassandraRepository<ProductPrice> {
#Query("select * from productprice where productId = ?0")
ProductPrice findByProductId(String productId);
}
My service class ProductService.java
#Path("/product")
#Component
public class ProductService {
#Autowired
ProductPriceRepository productPriceRepository;
#GET
#Path("/{id}")
#Produces(MediaType.APPLICATION_JSON)
public Product getTargetProduct(#PathParam("id") String productId) {
String urlString = "https://api.vendor.com/products/v3/" + productId + "?fields=descriptions&id_type=TCIN&key=43cJWpLjH8Z8oR18KdrZDBKAgLLQKJjz";
JSONObject json = null;
try {
json = new JSONObject(JsonReader.getExternalJsonResponse(urlString));
} catch (JSONException e) {
e.printStackTrace();
}
Product product = new Product();
product.setId(productId);
try {
JSONObject productCompositeResponse = json.getJSONObject("product_composite_response");
JSONArray items = productCompositeResponse.getJSONArray("items");
JSONObject item = items.getJSONObject(0);
JSONObject onlineDescription = item.getJSONObject("online_description");
product.setName(onlineDescription.getString("value"));
} catch (JSONException e) {
e.printStackTrace();
}
ProductPrice productPrice = productPriceRepository.findByProductId(productId);
product.setProductPrice(productPrice);
return product;
}
}
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/maven-v4_0_0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>com.myretail</groupId>
<artifactId>MyRetail</artifactId>
<packaging>war</packaging>
<version>1.0-SNAPSHOT</version>
<name>MyRetail</name>
<dependencies>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.12</version>
</dependency>
<dependency>
<groupId>com.datastax.cassandra</groupId>
<artifactId>cassandra-driver-core</artifactId>
<version>2.1.5</version>
</dependency>
<dependency>
<groupId>org.springframework.data</groupId>
<artifactId>spring-data-cassandra</artifactId>
<version>1.4.2.RELEASE</version>
</dependency>
<dependency>
<groupId>org.cassandraunit</groupId>
<artifactId>cassandra-unit-spring</artifactId>
<version>2.1.9.2</version>
<scope>test</scope>
<exclusions>
<exclusion>
<groupId>org.cassandraunit</groupId>
<artifactId>cassandra-unit</artifactId>
</exclusion>
</exclusions>
</dependency>
<dependency>
<groupId>org.cassandraunit</groupId>
<artifactId>cassandra-unit-shaded</artifactId>
<version>2.1.9.2</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.hectorclient</groupId>
<artifactId>hector-core</artifactId>
<version>2.0-0</version>
</dependency>
<dependency>
<groupId>com.sun.jersey</groupId>
<artifactId>jersey-servlet</artifactId>
<version>1.18.3</version>
</dependency>
<dependency>
<groupId>com.sun.jersey</groupId>
<artifactId>jersey-json</artifactId>
<version>1.18.3</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-web</artifactId>
<version>4.3.1.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context</artifactId>
<version>4.3.1.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-autoconfigure</artifactId>
<version>1.3.6.RELEASE</version>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.apache.tomcat.maven</groupId>
<artifactId>tomcat7-maven-plugin</artifactId>
<version>2.2</version>
<configuration>
<url>http://localhost:8080/manager/text</url>
<server>my-tomcat</server>
<path>/myRetail</path>
</configuration>
</plugin>
</plugins>
</build>
</project>
It is my understanding that the annotations should pick up the repository and create the bean based off of the #EnableCassandraRepositories annotation. The #Autowired ProductPriceRepository in ProductService.java is always null though when I run this on tomcat. HOWEVER, if I run a junit test against the service call, the bean is properly created, the object is not null, and the tests pass (via #ContextConfiguration annotation).
I've looked at a couple different patterns that I thought might help, but none of them have worked. I can't create an implementation of my interface because Cassandra handles that internally and I'm forced to implement the Cassandra methods.
I feel like something is just slightly off with the annotations somewhere. Any ideas?
The problem is with your pom.xml
For spring-boot Cassandra application, you have to include below dependencies and parent pom in pom.xml
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>1.3.5.RELEASE</version>
</parent>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-jpa</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-cassandra</artifactId>
</dependency>
</dependencies>