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>
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
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"
},
...
}
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'm trying to return xml from my #RestController method -
#RestController
public class MCSController {
.
.
#RequestMapping(value = "/encoders", method = { RequestMethod.GET }, produces = { MediaType.APPLICATION_JSON,
MediaType.APPLICATION_XML })
public List<EncoderVO> getEncoders() {
List<EncoderVO> encoders = null;
try {
encoders = infoService.listEncoders();
} catch (MCSException e) {
logger.error("Error in listing encoders : " + e.getMessage());
}
return encoders;
}
Here is my EncoderVO.java -
#XmlRootElement
public class EncoderVO {
#XmlElement
private Long id;
#XmlElement
private String name;
#XmlElement
private Boolean flagActive;
public EncoderVO() {
}
public EncoderVO(Long id, String name, Boolean flagActive) {
super();
this.id = id;
this.name = name;
this.flagActive = flagActive;
}
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Boolean getFlagActive() {
return flagActive;
}
public void setFlagActive(Boolean flagActive) {
this.flagActive = flagActive;
}
}
This is my 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>com.test</groupId>
<artifactId>mcs</artifactId>
<version>0.0.1-SNAPSHOT</version>
<packaging>war</packaging>
<!-- Inherit defaults from Spring Boot -->
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>1.3.0.RELEASE</version>
</parent>
<properties>
<aws.sdk-version>1.9.1</aws.sdk-version>
<liquibase.version>3.3.0</liquibase.version>
</properties>
<!-- Add typical dependencies for a web application -->
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
<exclusions>
<exclusion>
<artifactId>jackson-annotations</artifactId>
<groupId>com.fasterxml.jackson.core</groupId>
</exclusion>
</exclusions>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-tomcat</artifactId>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-actuator</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-aop</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-rest</artifactId>
<exclusions>
<exclusion>
<artifactId>jackson-annotations</artifactId>
<groupId>com.fasterxml.jackson.core</groupId>
</exclusion>
</exclusions>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-test</artifactId>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-jms</artifactId>
</dependency>
<dependency>
<groupId>org.apache.activemq</groupId>
<artifactId>activemq-broker</artifactId>
</dependency>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<scope>test</scope>
</dependency>
<!-- Aws SDK Dependencies -->
<dependency>
<groupId>com.amazonaws</groupId>
<artifactId>aws-java-sdk-s3</artifactId>
<version>${aws.sdk-version}</version>
</dependency>
<dependency>
<groupId>com.amazonaws</groupId>
<artifactId>aws-java-sdk-elastictranscoder</artifactId>
<version>${aws.sdk-version}</version>
</dependency>
<dependency>
<groupId>com.amazonaws</groupId>
<artifactId>aws-java-sdk-sqs</artifactId>
<version>${aws.sdk-version}</version>
</dependency>
<dependency>
<groupId>com.amazonaws</groupId>
<artifactId>aws-java-sdk-sns</artifactId>
<version>${aws.sdk-version}</version>
</dependency>
<dependency>
<groupId>com.amazonaws</groupId>
<artifactId>aws-java-sdk-datapipeline</artifactId>
<version>${aws.sdk-version}</version>
</dependency>
<dependency>
<groupId>com.amazonaws</groupId>
<artifactId>aws-java-sdk-cloudfront</artifactId>
<version>${aws.sdk-version}</version>
</dependency>
</dependencies>
</project>
Below is my Application class -
#SpringBootApplication(exclude = { SpringBootWebSecurityConfiguration.class, LiquibaseAutoConfiguration.class })
#ComponentScan(basePackages = { "com.test.ott.mcs" })
#EnableAspectJAutoProxy
#EnableJms
#EntityScan("com.test.ott.mcs.entities")
#EnableJpaRepositories("com.test.ott.mcs.repository")
public class MCSApplication {
#Bean
JmsListenerContainerFactory<?> jmsContainerFactory(ConnectionFactory connectionFactory) {
DefaultJmsListenerContainerFactory factory = new DefaultJmsListenerContainerFactory();
factory.setConnectionFactory(connectionFactory);
// A core poll size of 3 threads and a maximum pool size of 10 threads
factory.setConcurrency("3-10");
return factory;
}
// Using factory pattern with spring annotation
#Bean
public FactoryBean serviceLocatorFactoryBean() {
ServiceLocatorFactoryBean factoryBean = new ServiceLocatorFactoryBean();
factoryBean.setServiceLocatorInterface(EncodingAPIFactory.class);
return factoryBean;
}
public static void main(String args[]) {
SpringApplication.run(MCSApplication.class, args);
}
}
When I hit the url /encoders in browser, i get the below error -
There was an unexpected error (type=Not Acceptable, status=406). Could
not find acceptable representation
The jackson related jars in my calsspath are -
jackson-core-asl : 1.9.13
jackson-jaxrs : 1.9.13
jackson-mapper-asl : 1.9.13
jackson-annotations : 2.6.3
jackson-core : 2.6.3
jackson-module-jaxb-annotations : 2.2.3
jackson-jaxrs-json-provider : 2.2.3
jackson-jaxrs-base : 2.5.4
jackson-databind : 2.6.3
So, I have MappingJackson2HttpMessageConverter in my classpath.
Please suggest. Thanks in advance.
There is a solution that will work out-of-the-box, similarly to JAX-RS but with a bit worse output. The solution uses jackson-dataformat-xml. Add dependency to your project:
<dependency>
<groupId>com.fasterxml.jackson.dataformat</groupId>
<artifactId>jackson-dataformat-xml</artifactId>
</dependency>
Response will look like this:
<?xml version="1.0" encoding="UTF-8"?>
<List>
<item>
<id>1</id>
<name>testEncoder1</name>
<flagActive>true</flagActive>
</item>
<item>
<id>2</id>
<name>testEncoder2</name>
<flagActive>true</flagActive>
</item>
<item>
<id>3</id>
<name>testEncoder3</name>
<flagActive>true</flagActive>
</item>
</List>
For further details please look at Spring MVC Way (jackson-dataformat-xml)
try
http://localhost:8080/mcs-0.0.1-SNAPSHOT/encoders.
mcs is the name of the application and
0.0.1-SNAPSHOT the version.
If it doesn't works you have to add a global path into the RequestController. Something like:
#RestController
#RequestMapping(value = "/mcs")
public class MCSController {
.
.
#RequestMapping(value = "/encoders", method = { RequestMethod.GET }, produces = { MediaType.APPLICATION_JSON,
MediaType.APPLICATION_XML })
public List<EncoderVO> getEncoders() {
and this request:
http://localhost:8080/mcs-0.0.1-SNAPSHOT/mcs/encoders
i hope it helps you.
Cheers
Add this dependecy in you POM.xml
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-databind</artifactId>
<version>2.8.8</version>
problem is with version of this jar. so please try out this solution
I am developing a little demo project with Spring MVC on a Tomcat with hibernate and JSPs. The application was working with thymeleaf as a view resolver but I need to rewrite my thymeleaf template as a .JSP. So I needed to reconfig everything. I am also trying to only use annotation configuration files without any xml.
The problem is that I am seeing the source code of my JSP-File without resolving.
The Request-Mapping and the program logic already worked with thymeleaf + spring. I am getting no error messages in the log files. I tried a lot of changes so my config files may be inconsistent at the moment. Any pointers or advice is appreciated.
My config files are below:
MyWebAppInitializer:
public class MyWebAppInitializer implements WebApplicationInitializer {
private static final String CONFIG_LOCATION = "MvcConfiguration";
private static final String MAPPING_URL = "/";#Override
public void onStartup(ServletContext servletContext) throws ServletException {
WebApplicationContext context = getContext();
servletContext.addListener(new ContextLoaderListener(context));
ServletRegistration.Dynamic dispatcher = servletContext.addServlet("DispatcherServlet", new DispatcherServlet(context));
dispatcher.setLoadOnStartup(1);
dispatcher.addMapping(MAPPING_URL);
}
private AnnotationConfigWebApplicationContext getContext() {
AnnotationConfigWebApplicationContext context = new AnnotationConfigWebApplicationContext();
context.setConfigLocation(CONFIG_LOCATION);
return context;
}
}
MvcConfiguration:
class MvcConfiguration extends WebMvcConfigurerAdapter {
#Bean
public ViewResolver viewResolver() {
InternalResourceViewResolver viewResolver = new InternalResourceViewResolver();
viewResolver.setViewClass(JstlView.class);
viewResolver.setPrefix("/WEB-INF/");
viewResolver.setSuffix(".jsp");
return viewResolver;
}
#Override
public void addResourceHandlers(ResourceHandlerRegistry registry) {
registry.addResourceHandler("/resources/**").addResourceLocations("/resources/");
}
#Override
public void configureDefaultServletHandling(DefaultServletHandlerConfigurer configurer) {
configurer.enable();
}
}
BenutzerController:
#Controller
public class BenutzerController {
#Autowired
BenutzerRepository repository;
#ModelAttribute("Benutzer")
public Benutzer loadEmptyModelBean() {
return new Benutzer();
}
#ModelAttribute("userList")
public List < Benutzer > userList() {
return toList(repository.findAll());
}
#RequestMapping("/verwaltung")
public String verwaltung(#RequestParam(value = "message", required = false, defaultValue = "Defaultvalue") String message, ModelMap model) {
model.addAttribute("message", message);
return "verwaltung";
}
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>
<name>benutzerverwaltung</name>
<description>Demo project for Spring Boot</description>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>1.3.0.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-data-jpa</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>com.zaxxer</groupId>
<artifactId>HikariCP</artifactId>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<scope>runtime</scope>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.11</version>
</dependency>
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-entitymanager</artifactId>
</dependency>
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>jstl</artifactId>
<version>1.2</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-webmvc</artifactId>
<version>4.2.3.RELEASE</version>
</dependency>
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>javax.servlet-api</artifactId>
<version>3.1.0</version>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build>
</project>
EDIT: SOLUTION
editing the pom.xml:
<dependency>
<groupId>org.apache.tomcat.embed</groupId>
<artifactId>tomcat-embed-jasper</artifactId>
<version>8.0.29</version>
</dependency>
Are you using Spring Boot's embedded Tomcat? According to the answer to this question, you may need to add a dependency: compile("org.apache.tomcat.embed:tomcat-embed-jasper"). However, I've never got JSPs to work properly with an embedded tomcat - you can create a war file instead, as it says in the docs.