I am using Spring 4 and Hibernate 4. I am using java jpa to use hibernate. I want to load few data lazily. And I have also configured Jackson mapper to convert my java object to json and vice versa. But it's throwing exception while converting the java to json. I have created custom object mapper but still it's not working.
Please see the following classes and see what I am missing here
I am using annotations. Hibernate configuration file:
MvcConfiguration.java
package com.ampdev.platform.module.common.config;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.converter.HttpMessageConverter;
import org.springframework.http.converter.json.MappingJackson2HttpMessageConverter;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.transaction.annotation.EnableTransactionManagement;
import org.springframework.web.servlet.ViewResolver;
import org.springframework.web.servlet.config.annotation.EnableWebMvc;
import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter;
import org.springframework.web.servlet.view.InternalResourceViewResolver;
import com.ampdev.platform.framework.dataaccess.config.HibernateAwareObjectMapper;
import com.ampdev.platform.framework.rest.security.AuthenticationService;
import com.ampdev.platform.framework.rest.security.AuthenticationServiceDefault;
import com.ampdev.platform.module.user.util.EncryptionUtil;
import com.fasterxml.jackson.databind.ObjectMapper;
#Configuration
#ComponentScan(basePackages = "com.ampdev")
#EnableWebMvc
#EnableTransactionManagement
public class MvcConfiguration extends WebMvcConfigurerAdapter
{
#Bean
public ViewResolver getViewResolver()
{
InternalResourceViewResolver resolver = new InternalResourceViewResolver();
resolver.setPrefix("/WEB-INF/views/");
resolver.setSuffix(".jsp");
return resolver;
}
#Override
public void addResourceHandlers(ResourceHandlerRegistry registry)
{
registry.addResourceHandler("/resources/**").addResourceLocations("/resources/");
}
#Autowired
#Bean(name = "authenticationService")
public AuthenticationService getAuthencticaionService()
{
return new AuthenticationServiceDefault();
}
#Autowired
#Bean(name = "passwordEncoder")
public PasswordEncoder getPasswordEncoder()
{
return new BCryptPasswordEncoder();
}
#Autowired
#Bean(name = "encrypyionUtil")
public EncryptionUtil getEncryptionUtil(PasswordEncoder passwordEncoder)
{
return new EncryptionUtil(passwordEncoder);
}
#Autowired
#Bean(name = "objectMapper")
public ObjectMapper getObjectMapper()
{
return new HibernateAwareObjectMapper();
}
#Autowired
#Bean(name = "jsonMessageConverter")
public MappingJackson2HttpMessageConverter getMessageConvertor()
{
return new MappingJackson2HttpMessageConverter();
}
#Autowired
private ObjectMapper objectMapper;
#Autowired
private MappingJackson2HttpMessageConverter jsonMessageConverter;
#Override
public void configureMessageConverters(List<HttpMessageConverter<?>> converters)
{
jsonMessageConverter.setObjectMapper(objectMapper);
converters.add(jsonMessageConverter);
}
}
I have created a custom object mapper to include Hibernate4Module
HibernateAwareObjectMapper.java
package com.ampdev.platform.framework.dataaccess.config;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.datatype.hibernate4.Hibernate4Module;
public class HibernateAwareObjectMapper extends ObjectMapper
{
/**
*
*/
private static final long serialVersionUID = -4013528320937607847L;
public HibernateAwareObjectMapper()
{
Hibernate4Module hibernateModule = new Hibernate4Module();
registerModule(hibernateModule);
}
}
Here is my Data object in which I am using the lazy loading:
UserMovieReviewData .java
package com.ampdev.platform.module.movie.review.user.dataobject;
import java.util.Date;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.FetchType;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.NamedQueries;
import javax.persistence.NamedQuery;
import javax.persistence.OneToOne;
import javax.persistence.Table;
import javax.persistence.Temporal;
import javax.persistence.TemporalType;
import com.ampdev.platform.module.common.dataobject.PersistedDataObject;
import com.ampdev.platform.module.movie.dataobject.MovieData;
import com.ampdev.platform.module.movie.review.constants.ReviewConstants;
import com.ampdev.platform.module.user.dataobject.UserData;
import com.fasterxml.jackson.annotation.JsonInclude;
import com.fasterxml.jackson.annotation.JsonInclude.Include;
#Entity
#Table(name = "movie_review_user")
#JsonInclude(Include.NON_NULL)
public class UserMovieReviewData extends PersistedDataObject
{
/**
*
*/
private static final long serialVersionUID = -5644749600929596177L;
#Id
#GeneratedValue
#Column(name = "review_id")
private long id;
#OneToOne(fetch = FetchType.LAZY)
#JoinColumn(name = "movie_id")
private MovieData movieData;
#OneToOne(fetch = FetchType.LAZY)
#JoinColumn(name = "user_id")
private UserData userData;
#Column(name = "rating")
private int rating;
#Column(name = "title")
private String title;
#Column(name = "review")
private String review;
#Column(name = "create_date")
#Temporal(TemporalType.TIMESTAMP)
private Date createDate;
#Column(name = "update_date")
#Temporal(TemporalType.TIMESTAMP)
private Date updateDate;
#Override
public long getId()
{
return id;
}
public void setId(long id)
{
this.id = id;
}
public MovieData getMovieData()
{
return movieData;
}
public void setMovieData(MovieData movieData)
{
this.movieData = movieData;
}
public UserData getUserData()
{
return userData;
}
public void setUserData(UserData userData)
{
this.userData = userData;
}
public int getRating()
{
return rating;
}
public void setRating(int rating)
{
this.rating = rating;
}
public String getTitle()
{
return title;
}
public void setTitle(String title)
{
this.title = title;
}
public String getReview()
{
return review;
}
public void setReview(String review)
{
this.review = review;
}
public Date getCreateDate()
{
return createDate;
}
public void setCreateDate(Date createDate)
{
this.createDate = createDate;
}
public Date getUpdateDate()
{
return updateDate;
}
public void setUpdateDate(Date updateDate)
{
this.updateDate = updateDate;
}
}
Here is my web service resource which I am using as rest resource:
ReviewResource.java
package com.ampdev.platform.module.movie.review.resource;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.config.ConfigurableBeanFactory;
import org.springframework.context.annotation.Scope;
import org.springframework.http.RequestEntity;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import com.ampdev.platform.framework.rest.BaseExecutor;
import com.ampdev.platform.framework.rest.RestBaseResource;
import com.ampdev.platform.module.common.constants.URIConstants;
import com.ampdev.platform.module.movie.review.constants.ReviewConstants;
import com.ampdev.platform.module.movie.review.user.dataobject.UserMovieReviewData;
#Controller
#RequestMapping(value = "/ws/movie/review")
#Scope(value = ConfigurableBeanFactory.SCOPE_PROTOTYPE)
public class ReviewResource extends RestBaseResource
{
#Autowired
private BaseExecutor<UserMovieReviewData, UserMovieReviewData> createMovieReviewExecutor;
#Autowired
private BaseExecutor<String, List<UserMovieReviewData>> getMovieReviewExecutor;
#RequestMapping(value = ReviewConstants.ADD, method = RequestMethod.POST)
public ResponseEntity<UserMovieReviewData> createMovieReview(
#RequestParam(value = ReviewConstants.TYPE, required = true) String type,
RequestEntity<UserMovieReviewData> requestEntity)
{
createMovieReviewExecutor.setAttribute(ReviewConstants.TYPE, type);
return performTask(requestEntity, createMovieReviewExecutor);
}
#RequestMapping(value = URIConstants.GET_IDS, method = RequestMethod.GET)
public ResponseEntity<List<UserMovieReviewData>> getReview(
#RequestParam(value = ReviewConstants.TYPE, required = true) String type, #PathVariable(value = "ids") String reviewIds)
{
getMovieReviewExecutor.setAttribute(ReviewConstants.TYPE, type);
getMovieReviewExecutor.setAttribute(ReviewConstants.REVIEW_IDS, reviewIds);
return performTask(null, getMovieReviewExecutor);
}
}
I am using spring 4 + hibernate 4.
I am getting the following error when I am trying to get data from Rest web service call:
I am getting the following error when I am trying to fetch the data from Rest web service:
org.springframework.http.converter.json.AbstractJackson2HttpMessageConverter.writeInternal(AbstractJackson2HttpMessageConverter.java:238)
org.springframework.http.converter.AbstractHttpMessageConverter.write(AbstractHttpMessageConverter.java:208)
org.springframework.web.servlet.mvc.method.annotation.AbstractMessageConverterMethodProcessor.writeWithMessageConverters(AbstractMessageConverterMethodProcessor.java:161)
org.springframework.web.servlet.mvc.method.annotation.HttpEntityMethodProcessor.handleReturnValue(HttpEntityMethodProcessor.java:144)
org.springframework.web.method.support.HandlerMethodReturnValueHandlerComposite.handleReturnValue(HandlerMethodReturnValueHandlerComposite.java:71)
org.springframework.web.servlet.mvc.method.annotation.ServletInvocableHandlerMethod.invokeAndHandle(ServletInvocableHandlerMethod.java:128)
org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.invokeHandleMethod(RequestMappingHandlerAdapter.java:781)
org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.handleInternal(RequestMappingHandlerAdapter.java:721)
org.springframework.web.servlet.mvc.method.AbstractHandlerMethodAdapter.handle(AbstractHandlerMethodAdapter.java:83)
org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:943)
org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:877)
org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:966)
org.springframework.web.servlet.FrameworkServlet.doGet(FrameworkServlet.java:857)
javax.servlet.http.HttpServlet.service(HttpServlet.java:621)
org.springframework.web.servlet.FrameworkServlet.service(FrameworkServlet.java:842)
javax.servlet.http.HttpServlet.service(HttpServlet.java:722)
org.springframework.security.web.FilterChainProxy.doFilterInternal(FilterChainProxy.java:186)
org.springframework.security.web.FilterChainProxy.doFilter(FilterChainProxy.java:160)
org.springframework.web.filter.DelegatingFilterProxy.invokeDelegate(DelegatingFilterProxy.java:344)
org.springframework.web.filter.DelegatingFilterProxy.doFilter(DelegatingFilterProxy.java:261)
root cause
com.fasterxml.jackson.databind.JsonMappingException: could not initialize proxy - no Session (through reference chain: java.util.ArrayList[0]->com.ampdev.platform.module.movie.review.user.dataobject.UserMovieReviewData["movieData"]->com.ampdev.platform.module.movie.dataobject.MovieData_$$_jvst49f_5["id"])
com.fasterxml.jackson.databind.JsonMappingException.wrapWithPath(JsonMappingException.java:232)
com.fasterxml.jackson.databind.JsonMappingException.wrapWithPath(JsonMappingException.java:197)
com.fasterxml.jackson.databind.ser.std.StdSerializer.wrapAndThrow(StdSerializer.java:187)
com.fasterxml.jackson.databind.ser.std.BeanSerializerBase.serializeFields(BeanSerializerBase.java:652)
com.fasterxml.jackson.databind.ser.BeanSerializer.serialize(BeanSerializer.java:152)
com.fasterxml.jackson.databind.ser.BeanPropertyWriter.serializeAsField(BeanPropertyWriter.java:541)
com.fasterxml.jackson.databind.ser.std.BeanSerializerBase.serializeFields(BeanSerializerBase.java:644)
com.fasterxml.jackson.databind.ser.BeanSerializer.serialize(BeanSerializer.java:152)
com.fasterxml.jackson.databind.ser.impl.IndexedListSerializer.serializeContents(IndexedListSerializer.java:100)
com.fasterxml.jackson.databind.ser.impl.IndexedListSerializer.serializeContents(IndexedListSerializer.java:21)
com.fasterxml.jackson.databind.ser.std.AsArraySerializerBase.serialize(AsArraySerializerBase.java:183)
com.fasterxml.jackson.databind.ser.DefaultSerializerProvider.serializeValue(DefaultSerializerProvider.java:114)
com.fasterxml.jackson.databind.ObjectMapper.writeValue(ObjectMapper.java:1837)
org.springframework.http.converter.json.AbstractJackson2HttpMessageConverter.writeInternal(AbstractJackson2HttpMessageConverter.java:231)
org.springframework.http.converter.AbstractHttpMessageConverter.write(AbstractHttpMessageConverter.java:208)
org.springframework.web.servlet.mvc.method.annotation.AbstractMessageConverterMethodProcessor.writeWithMessageConverters(AbstractMessageConverterMethodProcessor.java:161)
org.springframework.web.servlet.mvc.method.annotation.HttpEntityMethodProcessor.handleReturnValue(HttpEntityMethodProcessor.java:144)
org.springframework.web.method.support.HandlerMethodReturnValueHandlerComposite.handleReturnValue(HandlerMethodReturnValueHandlerComposite.java:71)
org.springframework.web.servlet.mvc.method.annotation.ServletInvocableHandlerMethod.invokeAndHandle(ServletInvocableHandlerMethod.java:128)
org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.invokeHandleMethod(RequestMappingHandlerAdapter.java:781)
org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.handleInternal(RequestMappingHandlerAdapter.java:721)
org.springframework.web.servlet.mvc.method.AbstractHandlerMethodAdapter.handle(AbstractHandlerMethodAdapter.java:83)
org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:943)
org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:877)
org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:966)
org.springframework.web.servlet.FrameworkServlet.doGet(FrameworkServlet.java:857)
javax.servlet.http.HttpServlet.service(HttpServlet.java:621)
org.springframework.web.servlet.FrameworkServlet.service(FrameworkServlet.java:842)
javax.servlet.http.HttpServlet.service(HttpServlet.java:722)
org.springframework.security.web.FilterChainProxy.doFilterInternal(FilterChainProxy.java:186)
org.springframework.security.web.FilterChainProxy.doFilter(FilterChainProxy.java:160)
org.springframework.web.filter.DelegatingFilterProxy.invokeDelegate(DelegatingFilterProxy.java:344)
org.springframework.web.filter.DelegatingFilterProxy.doFilter(DelegatingFilterProxy.java:261)
root cause
org.hibernate.LazyInitializationException: could not initialize proxy - no Session
org.hibernate.proxy.AbstractLazyInitializer.initialize(AbstractLazyInitializer.java:165)
org.hibernate.proxy.AbstractLazyInitializer.getImplementation(AbstractLazyInitializer.java:286)
org.hibernate.proxy.pojo.javassist.JavassistLazyInitializer.invoke(JavassistLazyInitializer.java:185)
com.ampdev.platform.module.movie.dataobject.MovieData_$$_jvst49f_5.getId(MovieData_$$_jvst49f_5.java)
sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source)
sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source)
java.lang.reflect.Method.invoke(Unknown Source)
com.fasterxml.jackson.databind.ser.BeanPropertyWriter.get(BeanPropertyWriter.java:726)
com.fasterxml.jackson.databind.ser.BeanPropertyWriter.serializeAsField(BeanPropertyWriter.java:506)
com.fasterxml.jackson.databind.ser.std.BeanSerializerBase.serializeFields(BeanSerializerBase.java:644)
com.fasterxml.jackson.databind.ser.BeanSerializer.serialize(BeanSerializer.java:152)
com.fasterxml.jackson.databind.ser.BeanPropertyWriter.serializeAsField(BeanPropertyWriter.java:541)
com.fasterxml.jackson.databind.ser.std.BeanSerializerBase.serializeFields(BeanSerializerBase.java:644)
com.fasterxml.jackson.databind.ser.BeanSerializer.serialize(BeanSerializer.java:152)
com.fasterxml.jackson.databind.ser.impl.IndexedListSerializer.serializeContents(IndexedListSerializer.java:100)
com.fasterxml.jackson.databind.ser.impl.IndexedListSerializer.serializeContents(IndexedListSerializer.java:21)
com.fasterxml.jackson.databind.ser.std.AsArraySerializerBase.serialize(AsArraySerializerBase.java:183)
com.fasterxml.jackson.databind.ser.DefaultSerializerProvider.serializeValue(DefaultSerializerProvider.java:114)
com.fasterxml.jackson.databind.ObjectMapper.writeValue(ObjectMapper.java:1837)
org.springframework.http.converter.json.AbstractJackson2HttpMessageConverter.writeInternal(AbstractJackson2HttpMessageConverter.java:231)
org.springframework.http.converter.AbstractHttpMessageConverter.write(AbstractHttpMessageConverter.java:208)
org.springframework.web.servlet.mvc.method.annotation.AbstractMessageConverterMethodProcessor.writeWithMessageConverters(AbstractMessageConverterMethodProcessor.java:161)
org.springframework.web.servlet.mvc.method.annotation.HttpEntityMethodProcessor.handleReturnValue(HttpEntityMethodProcessor.java:144)
org.springframework.web.method.support.HandlerMethodReturnValueHandlerComposite.handleReturnValue(HandlerMethodReturnValueHandlerComposite.java:71)
org.springframework.web.servlet.mvc.method.annotation.ServletInvocableHandlerMethod.invokeAndHandle(ServletInvocableHandlerMethod.java:128)
org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.invokeHandleMethod(RequestMappingHandlerAdapter.java:781)
org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.handleInternal(RequestMappingHandlerAdapter.java:721)
org.springframework.web.servlet.mvc.method.AbstractHandlerMethodAdapter.handle(AbstractHandlerMethodAdapter.java:83)
org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:943)
org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:877)
org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:966)
org.springframework.web.servlet.FrameworkServlet.doGet(FrameworkServlet.java:857)
javax.servlet.http.HttpServlet.service(HttpServlet.java:621)
org.springframework.web.servlet.FrameworkServlet.service(FrameworkServlet.java:842)
javax.servlet.http.HttpServlet.service(HttpServlet.java:722)
org.springframework.security.web.FilterChainProxy.doFilterInternal(FilterChainProxy.java:186)
org.springframework.security.web.FilterChainProxy.doFilter(FilterChainProxy.java:160)
org.springframework.web.filter.DelegatingFilterProxy.invokeDelegate(DelegatingFilterProxy.java:344)
org.springframework.web.filter.DelegatingFilterProxy.doFilter(DelegatingFilterProxy.java:261)
org.hibernate.LazyInitializationException: could not initialize proxy - no Session
You're trying to access a lazy collection outside of the hibernate session. There are a few ways to solve this, the most clear is to access the size() of each collection you're going to be serializing in your service class, which causes the collection to be loaded and therefore available outside the session.
Another alternative is to annotate the collection with FetchType.EAGER, but this will affect all uses of your model, which might not be what you want. Finally, you can use the OpenSessionInView pattern, which maintains an open hibernate session for the duration of the request (and therefore allows you to load lazy collections outside where the session boundary would otherwise be). This last alternative is generally considered an anti-pattern.
Related
I am making simple program that have to get some info from OpenWeatherMap API and save it in MySQL database:
package com.example.restTemplate;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.annotation.Bean;
import org.springframework.web.client.RestTemplate;
#SpringBootApplication
public class RestTemplateApplication {
public static void main(String[] args) {
SpringApplication.run(RestTemplateApplication.class, args);
}
#Bean
public RestTemplate getRestTemplate() {
return new RestTemplate();
}
}
package com.example.restTemplate.Model;
import lombok.*;
import javax.persistence.Entity;
import javax.persistence.Id;
#NoArgsConstructor
#AllArgsConstructor
#Entity
#javax.persistence.Table(name="Weather")
#Getter
#Setter
#ToString
public class WeatherScore {
#Id
private int id;
private String city;
private double temperature;
private int pressure;
private long currentDate;
}
package com.example.restTemplate.Controller;
import com.example.restTemplate.Model.WeatherScore;
import org.springframework.data.repository.CrudRepository;
import org.springframework.stereotype.Repository;
#Repository
public interface WeatherCRUDRepository
extends CrudRepository<WeatherScore, Long> {
WeatherScore save (WeatherScore score);
}
package com.example.restTemplate.Controller;
import com.example.restTemplate.Model.WeatherScore;
import org.springframework.context.ApplicationContext;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpMethod;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;
import java.util.Arrays;
import java.util.Random;
#RestController
public class ConsumeWebService {
#Autowired
RestTemplate restTemplate;
WeatherCRUDRepository repository;
ApplicationContext context;
#RequestMapping(value = "/weather")
public void printWeather() {
HttpHeaders headers = new HttpHeaders();
headers.setAccept(Arrays.asList(MediaType.APPLICATION_JSON));
HttpEntity<String> entity = new HttpEntity<String>(headers);
String text = restTemplate.exchange("http://api.openweathermap.org/data/2.5/weather?q=London,uk&APPID=mykey",
HttpMethod.GET, entity, String.class).getBody();
int pressureStartIndex = text.indexOf("pressure")+10;
int pressureEndIndex = text.indexOf(",", pressureStartIndex);
int tempStartIndex = text.indexOf("temp")+6;
int tempEndIndex = text.indexOf(",", tempStartIndex);
int pressure = Integer.parseInt(text.substring(pressureStartIndex, pressureEndIndex));
double temperature = Double.parseDouble(text.substring(tempStartIndex, tempEndIndex));
WeatherScore score = new WeatherScore();
score.setCity("London");
score.setPressure(pressure);
score.setTemperature(temperature);
Random generator = new Random();
score.setId(generator.nextInt(1000));
score.setCurrentDate(System.currentTimeMillis());
WeatherCRUDRepository repo = context.getBean(WeatherCRUDRepository.class);
repository.save(score);
}
}
When i tap http://localhost:8080/weather i get an error:
Cannot invoke
"org.springframework.context.ApplicationContext.getBean(java.lang.Class)"
because "this.context" is null
Blockquote
How i could fix that?
You have to autowire all the beans within controller, like so:
#Autowired
RestTemplate restTemplate;
#Autowired
WeatherCRUDRepository repository;
#Autowired
ApplicationContext context;
I'm trying to upload excel file content to mysql using Spring boot with the help of upload file UI. Need help with that.
But i'm facing Whitelabel Error Page. I've tried couple of things but no luck yet.
Project View
ReadFileApplication.java
package com.springboot.file.parsefiles;
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;
import org.springframework.stereotype.Component;
#Configuration
#EnableAutoConfiguration
#ComponentScan(basePackages= {"com.springboot.file.parsefiles.controller"})
#SpringBootApplication
#Component
public class ReadFileApplication {
public static void main(String[] args) {
SpringApplication.run(ReadFileApplication.class, args);
}
}
ReadFileConrtroller.java
package com.springboot.file.parsefiles.controller;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import com.springboot.file.parsefiles.service.ReadFileService;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;
import com.springboot.file.parsefiles.model.User;
#RestController
public class ReadFileController
{
#Autowired private ReadFileService readFileService;
#GetMapping(value="/ ")
public String home(Model model)
{
model.addAttribute("user", new User());
List<User> users = ReadFileService.findAll();
model.addAttribute("users", users);
return "view/users";
}
#PostMapping(value="/fileupload")
public String uploadFile(#ModelAttribute User user, RedirectAttributes redirectAttributes)
{
#SuppressWarnings("unused")
boolean isFlag = readFileService.saveDataFromUploadFile(user.getFile());
return "redirect:/";
}
}
ReadFileRepository.java
package com.springboot.file.parsefiles.repository;
import org.springframework.data.repository.CrudRepository;
import org.springframework.stereotype.Repository;
import com.springboot.file.parsefiles.model.User;
#Repository
public interface ReadFileRepository extends CrudRepository<User, Long>
{
}
ReadFileService.java
package com.springboot.file.parsefiles.service;
import java.util.List;
import org.springframework.web.multipart.MultipartFile;
import com.springboot.file.parsefiles.model.User;
public interface ReadFileService
{
List<User> findAll = null;
static List<User> findAll()
{
return null;
}
boolean saveDataFromUploadFile(MultipartFile file);
}
ReadFileServiceImpl.java
package com.springboot.file.parsefiles.service;
import java.util.List;
import com.springboot.file.parsefiles.service.ReadFileService;
import org.apache.commons.io.FilenameUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;
import com.springboot.file.parsefiles.model.User;
import com.springboot.file.parsefiles.repository.ReadFileRepository;
#Service
#Transactional
public class ReadFileServiceImpl implements ReadFileService
{
#Autowired private ReadFileRepository readFileRepository;
public List<User> findAll()
{
return (List<User>) readFileRepository.findAll();
}
#Override
public boolean saveDataFromUploadFile(MultipartFile file) {
#SuppressWarnings("unused")
boolean isFlag = false;
String extension = FilenameUtils.getExtension(file.getOriginalFilename());
if(extension.equalsIgnoreCase("json"))
{
isFlag = realDataFromJson(file);
}else if(extension.equalsIgnoreCase("csv"))
{
isFlag = realDataFromCsv(file);
}
return false;
}
private boolean realDataFromCsv(MultipartFile file)
{
return false;
}
private boolean realDataFromJson(MultipartFile file)
{
return false;
}
}
Applicatiopn.properties
spring.datasource.url = jdbc:mysql://localhost:3306/sampledatabase
spring.datasource.username = root
spring.datasource.password = root
spring.datasource.testWhileIdle = true
spring.datasource.validationQuery = SELECT 1
spring.jpa.show-sql = true
spring.jpa.hibernate.ddl-auto = update
spring.jpa.hibernate.naming-strategy = org.hibernate.cfg.ImprovedNamingStrategy
spring.jpa.properties.hibernate.dialect = org.hibernate.dialect.MySQL5Dialect
spring.servlet.multipart.max-file-size=100MB
spring.servlet.multipart.max-request-size=500MB
Edit:
***************************
APPLICATION FAILED TO START
***************************
Description:
Field readFileService in com.springboot.file.parsefiles.controller.ReadFileController required a bean of type 'com.springboot.file.parsefiles.service.ReadFileService' that could not be found.
The injection point has the following annotations:
- #org.springframework.beans.factory.annotation.Autowired(required=true)
Action:
Consider defining a bean of type 'com.springboot.file.parsefiles.service.ReadFileService' in your configuration.
Update your controller as below
#PostMapping(value="/fileupload")
public String uploadFile(#RequestParam MultipartFile file, RedirectAttributes redirectAttributes)
{
#SuppressWarnings("unused")
boolean isFlag = readFileService.saveDataFromUploadFile(file);
return "redirect:/";
}
Next i used apache-poi library to convert excel file to list of model object in service class. So my service method is as below
#Autowired
private IPoiji poijiImpl;
#Override
public boolean saveDataFromUploadFile(MultipartFile file) {
List<UserDTO> uploadedUserList = = poijiImpl.fromExcel(file.getOriginalFilename(), file.getInputStream(),UserDTO.class);
// here i can call repository methods to save data in database
}
I have created a Spring Boot REST API with inbuilt Apache Derby database. It worked fine. Now I have to integrate it with MySQL. I have updated POM.XML and configured the driver.
Expense.java
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.Table;
#Entity
#Table(name = "vendor")
public class Expense {
#Id
#Column
#GeneratedValue(strategy = GenerationType.IDENTITY)
private String vendorId;
#Column
private String vendorName;
#Column
private int vendorPhone;
#Column
private int vendorBalance;
#Column
private int vendorChequeAmount;
public String getVendorId() {
return vendorId;
}
public void setVendorId(String vendorId) {
this.vendorId = vendorId;
}
public String getVendorName() {
return vendorName;
}
public void setVendorName(String vendorName) {
this.vendorName = vendorName;
}
public int getVendorPhone() {
return vendorPhone;
}
public void setVendorPhone(int vendorPhone) {
this.vendorPhone = vendorPhone;
}
public int getVendorBalance() {
return vendorBalance;
}
public void setVendorBalance(int vendorBalance) {
this.vendorBalance = vendorBalance;
}
public int getVendorChequeAmount() {
return vendorChequeAmount;
}
public void setVendorChequeAmount(int vendorChequeAmount) {
this.vendorChequeAmount = vendorChequeAmount;
}
public Expense(String vendorId, String vendorName, int vendorPhone, int vendorBalance, int vendorChequeAmount) {
super();
this.vendorId = vendorId;
this.vendorName = vendorName;
this.vendorPhone = vendorPhone;
this.vendorBalance = vendorBalance;
this.vendorChequeAmount = vendorChequeAmount;
}
application.properties
server.port = 8087
server.contextPath=/expense-tracker
spring.datasource.url=jdbc:mysql://localhost:3306/web_customer_tracker
spring.datasource.username=springstudent
spring.datasource.password=springstudent
spring.datasource.driver-class-name=com.mysql.jdbc.Driver
spring.jpa.show-sql=true
spring.jpa.hibernate.ddl-auto=update
spring.jpa.hibernate.naming.implicit-strategy=org.hibernate.boot.model.naming.ImplicitNamingStrategyLegacyHbmImpl
spring.jpa.hibernate.naming.physical-strategy=org.springframework.boot.orm.jpa.hibernate.SpringPhysicalNamingStrategy
Please click for the MySQL details
When I run using Postman, I am getting 404 error. Something is wrong with MySQL configuration. Please help to identify it. Thanks
[EDIT]
ExpenseController.Java
package com.shef.expensetracker.expense;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
#CrossOrigin(origins = "http://localhost:4200", maxAge = 3600)
#RestController
#RequestMapping("/vendors")
public class ExpenseController {
#Autowired
private ExpenseService expenseService;
#GetMapping
public List<Expense> getAllExpenses(){
return expenseService.findAll();
}
#GetMapping(path = {"/{vendorId}"})
public Expense getExpense(#PathVariable String vendorId){
return expenseService.getExpenseById(vendorId);
}
#PostMapping
public void addExpense(#RequestBody Expense expense){
expenseService.addExpense(expense);
}
#PutMapping(path = {"/{vendorId}"})
public void updateExpense(#RequestBody Expense expense, #PathVariable String vendorId){
expenseService.updateExpense(expense,vendorId );
}
#DeleteMapping(path = {"/{vendorId}"})
public void deleteExpense( #PathVariable String vendorId){
expenseService.deleteExpense(vendorId );
}
}
ExpenseService.Java
package com.shef.expensetracker.expense;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
#Service
public class ExpenseService {
#Autowired
private ExpenseRepository expenseRepository;
/*private List<Expense> expenses = new ArrayList<>(
Arrays.asList(new Expense("1","Chicken", 1234, 500, 100),
new Expense("2","Mutton", 1234, 600, 100),
new Expense("3","Beef", 1234, 700, 100)
));*/
public List<Expense> findAll(){
List<Expense> expenses = new ArrayList<>();
expenseRepository.findAll().forEach(expenses::add);
return expenses;
}
public void addExpense(Expense expense) {
//expenses.add(expense);
expenseRepository.save(expense);
}
public Expense getExpenseById(String vendorId){
return expenseRepository.findOne(vendorId);
}
public void updateExpense(Expense expense, String vendorId) {
// TODO Auto-generated method stub
expenseRepository.save(expense);
}
public void deleteExpense(String vendorId) {
expenseRepository.delete(vendorId);
}
}
ExpenseTrackerApplication.Java
package com.shef.expensetracker;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
#SpringBootApplication
public class ExpenseTrackerApplication {
public static void main(String[] args) {
SpringApplication.run(ExpenseTrackerApplication.class, args);
}
}
I have problem with persisting polish PL-pl locale characters in mysql db.
I know that is common issue, and out there in the internet is many solution to this. But I cant figure it out. I think I've tried everything.
All my web page correctly encode and display UTF-8 characters (static from html and from db)
Problem cames when I save somthing in db using form on my application. So I think it is tightly related to JDBC, JPA and hibernate.
Here is my configuration:
application.properties
#DB Properties:
# Mysql
db.driver=com.mysql.jdbc.Driver
db.url=jdbc:mysql://localhost:3300/derp?characterEncoding=UTF-8
hibernate.dialect=org.hibernate.dialect.MySQL5InnoDBDialect
db.username=root
db.password=motorolaa835
# H2
#db.driver=org.h2.Driver
#db.url=jdbc:h2:~/sts/derp/db/derp_db
#hibernate.dialect=org.hibernate.dialect.H2Dialect
#db.username=root
#Hibernate Configuration:
hibernate.show_sql=true
hibernate.hbm2ddl.auto=update
#hibernate.hbm2ddl.auto=create
hibernate.connection.CharSet=utf8
hibernate.connection.characterEncoding=utf8
hibernate.connection.useUnicode=true
services.entitymanager.packages.to.scan=com.derp
cms.entitymanager.packages.to.scan=com.derp.cms.model
common.entitymanager.packages.to.scan=com.derp.common.model
procedure.entitymanager.packages.to.scan=com.derp.procedure.model
Initializer
package com.derp.common.init;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.ServletRegistration.Dynamic;
import org.springframework.web.WebApplicationInitializer;
import org.springframework.web.context.ContextLoaderListener;
import org.springframework.web.context.support.AnnotationConfigWebApplicationContext;
import org.springframework.web.filter.CharacterEncodingFilter;
import org.springframework.web.filter.HiddenHttpMethodFilter;
import org.springframework.web.servlet.DispatcherServlet;
public class Initializer implements WebApplicationInitializer {
#Override
public void onStartup(ServletContext servletContext) throws ServletException {
AnnotationConfigWebApplicationContext ctx = new AnnotationConfigWebApplicationContext();
ctx.register(WebAppConfig.class);
ctx.register(ThymeleafConfig.class);
servletContext.addListener(new ContextLoaderListener(ctx));
ctx.setServletContext(servletContext);
Dynamic servlet = servletContext.addServlet("dispatcher", new DispatcherServlet(ctx));
servlet.addMapping("/");
servlet.setAsyncSupported(true);
servlet.setLoadOnStartup(1);
// Allow to use Put and Delete method for REST architecture
registerCharachterEncodingFilter(servletContext);
registerHiddenFieldFilter(servletContext);
}
private void registerCharachterEncodingFilter(ServletContext aContext) {
CharacterEncodingFilter cef = new CharacterEncodingFilter();
cef.setForceEncoding(true);
cef.setEncoding("UTF-8");
aContext.addFilter("charachterEncodingFilter", cef).addMappingForUrlPatterns(null ,true, "/*");
}
private void registerHiddenFieldFilter(ServletContext aContext) {
aContext.addFilter("hiddenHttpMethodFilter", new HiddenHttpMethodFilter()).addMappingForUrlPatterns(null ,true, "/*");
}
}
WebAppConfig
package com.derp.common.init;
import java.util.Properties;
import javax.annotation.Resource;
import javax.sql.DataSource;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.PropertySource;
import org.springframework.core.env.Environment;
import org.springframework.http.MediaType;
import org.springframework.jdbc.datasource.DriverManagerDataSource;
import org.springframework.orm.hibernate4.HibernateTransactionManager;
import org.springframework.orm.hibernate4.LocalSessionFactoryBean;
import org.springframework.transaction.annotation.EnableTransactionManagement;
import org.springframework.web.servlet.config.annotation.ContentNegotiationConfigurer;
import org.springframework.web.servlet.config.annotation.EnableWebMvc;
import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter;
//import com.derp.common.wicketView.HomePage;
#Configuration
#ComponentScan("com.derp")
#EnableWebMvc
#EnableTransactionManagement
#PropertySource("classpath:application.properties")
public class WebAppConfig extends WebMvcConfigurerAdapter {
private static final String PROPERTY_NAME_DATABASE_DRIVER = "db.driver";
private static final String PROPERTY_NAME_DATABASE_PASSWORD = "db.password";
private static final String PROPERTY_NAME_DATABASE_URL = "db.url";
private static final String PROPERTY_NAME_DATABASE_USERNAME = "db.username";
private static final String PROPERTY_NAME_HIBERNATE_DIALECT = "hibernate.dialect";
private static final String PROPERTY_NAME_HIBERNATE_SHOW_SQL = "hibernate.show_sql";
private static final String PROPERTY_NAME_HIBERNATE_HBM2DDL_AUTO = "hibernate.hbm2ddl.auto";
private static final String PROPERTY_NAME_HIBERNATE_CONNECTION_CHARSET = "hibernate.connection.CharSet";
private static final String PROPERTY_NAME_HIBERNATE_CONNECTION_CHARACTERENCODING = "hibernate.connection.characterEncoding";
private static final String PROPERTY_NAME_HIBERNATE_CONNECTION_USEUNICODE = "hibernate.connection.useUnicode";
private static final String PROPERTY_NAME_ENTITYMANAGER_PACKAGES_TO_SCAN_SERVICES = "services.entitymanager.packages.to.scan";
private static final String PROPERTY_NAME_ENTITYMANAGER_PACKAGES_TO_SCAN_COMMON = "common.entitymanager.packages.to.scan";
private static final String PROPERTY_NAME_ENTITYMANAGER_PACKAGES_TO_SCAN_CMS = "cms.entitymanager.packages.to.scan";
private static final String PROPERTY_NAME_ENTITYMANAGER_PACKAGES_TO_SCAN_PROCEDURE = "procedure.entitymanager.packages.to.scan";
#Resource
private Environment env;
#Bean
public DataSource dataSource() {
DriverManagerDataSource dataSource = new DriverManagerDataSource();
dataSource.setDriverClassName(env.getRequiredProperty(PROPERTY_NAME_DATABASE_DRIVER));
dataSource.setUrl(env.getRequiredProperty(PROPERTY_NAME_DATABASE_URL));
dataSource.setUsername(env.getRequiredProperty(PROPERTY_NAME_DATABASE_USERNAME));
dataSource.setPassword(env.getRequiredProperty(PROPERTY_NAME_DATABASE_PASSWORD));
return dataSource;
}
#Bean
public LocalSessionFactoryBean sessionFactory() {
LocalSessionFactoryBean sessionFactoryBean = new LocalSessionFactoryBean();
sessionFactoryBean.setDataSource(dataSource());
//sessionFactoryBean.setPackagesToScan(env.getRequiredProperty(PROPERTY_NAME_ENTITYMANAGER_PACKAGES_TO_SCAN));
sessionFactoryBean.setPackagesToScan(new String[] {
env.getRequiredProperty(PROPERTY_NAME_ENTITYMANAGER_PACKAGES_TO_SCAN_SERVICES),
env.getRequiredProperty(PROPERTY_NAME_ENTITYMANAGER_PACKAGES_TO_SCAN_COMMON),
env.getRequiredProperty(PROPERTY_NAME_ENTITYMANAGER_PACKAGES_TO_SCAN_CMS),
env.getRequiredProperty(PROPERTY_NAME_ENTITYMANAGER_PACKAGES_TO_SCAN_PROCEDURE)
});
sessionFactoryBean.setHibernateProperties(hibProperties());
return sessionFactoryBean;
}
private Properties hibProperties() {
Properties properties = new Properties();
properties.put(PROPERTY_NAME_HIBERNATE_DIALECT, env.getRequiredProperty(PROPERTY_NAME_HIBERNATE_DIALECT));
properties.put(PROPERTY_NAME_HIBERNATE_SHOW_SQL, env.getRequiredProperty(PROPERTY_NAME_HIBERNATE_SHOW_SQL));
properties.put(PROPERTY_NAME_HIBERNATE_HBM2DDL_AUTO, env.getRequiredProperty(PROPERTY_NAME_HIBERNATE_HBM2DDL_AUTO));
properties.put(PROPERTY_NAME_HIBERNATE_CONNECTION_CHARSET, env.getRequiredProperty(PROPERTY_NAME_HIBERNATE_CONNECTION_CHARSET));
properties.put(PROPERTY_NAME_HIBERNATE_CONNECTION_CHARACTERENCODING, env.getRequiredProperty(PROPERTY_NAME_HIBERNATE_CONNECTION_CHARACTERENCODING));
properties.put(PROPERTY_NAME_HIBERNATE_CONNECTION_USEUNICODE, env.getRequiredProperty(PROPERTY_NAME_HIBERNATE_CONNECTION_USEUNICODE));
properties.put("jadira.usertype.autoRegisterUserTypes", "true");
return properties;
}
#Bean
public HibernateTransactionManager transactionManager() {
HibernateTransactionManager transactionManager = new HibernateTransactionManager();
transactionManager.setSessionFactory(sessionFactory().getObject());
return transactionManager;
}
#Override
public void configureContentNegotiation(ContentNegotiationConfigurer configurer) {
// Simple strategy: only path extension is taken into account
configurer.favorPathExtension(true).
ignoreAcceptHeader(true).
useJaf(false).
defaultContentType(MediaType.TEXT_HTML).
mediaType("html", MediaType.TEXT_HTML).
mediaType("xml", MediaType.APPLICATION_XML).
mediaType("json", MediaType.APPLICATION_JSON);
}
#Override
public void addResourceHandlers(ResourceHandlerRegistry registry) {
registry.addResourceHandler("/img/**").addResourceLocations("/WEB-INF/img/*");
registry.addResourceHandler("/css/**").addResourceLocations("/WEB-INF/css/*");
registry.addResourceHandler("/js/**").addResourceLocations("/WEB-INF/js/*");
registry.addResourceHandler("/lib/**").addResourceLocations("/WEB-INF/lib/*");
}
}
ThymeleafConfig
package com.derp.common.init;
import nz.net.ultraq.thymeleaf.LayoutDialect;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.thymeleaf.spring4.SpringTemplateEngine;
import org.thymeleaf.spring4.view.ThymeleafViewResolver;
import org.thymeleaf.templateresolver.ServletContextTemplateResolver;
#Configuration
public class ThymeleafConfig {
#Bean
public ServletContextTemplateResolver templateResolver() {
ServletContextTemplateResolver resolver = new ServletContextTemplateResolver();
resolver.setPrefix("/WEB-INF/view/");
resolver.setSuffix(".html");
resolver.setTemplateMode("HTML5");
resolver.setOrder(1);
resolver.setCacheable(false);
return resolver;
}
#Bean
public SpringTemplateEngine templateEngine() {
SpringTemplateEngine templateEngine = new SpringTemplateEngine();
templateEngine.setTemplateResolver(templateResolver());
templateEngine.addDialect(new LayoutDialect());
//templateEngine.addDialect(new SpringStandardDialect());
return templateEngine;
}
#Bean
public ThymeleafViewResolver thymeleafViewResolver() {
ThymeleafViewResolver resolver = new ThymeleafViewResolver();
resolver.setTemplateEngine(templateEngine());
resolver.setCharacterEncoding("UTF-8");
return resolver;
}
}
Edit
There is no utf-8 characters when using this method on controller
controller
#RequestMapping(value="/test", method=RequestMethod.PUT)
#ResponseBody
public String ajaxTest() {
return "Characters test: ęółąśżźćń";
}
and the javasscript ajax method
$(document).ready(function() {
$('h1').click(function() {
$.ajax({
type: "PUT",
url: "/derp/procedury/test",
data: "none",
success: function (response, status, xhr) {
showNotifications(status, xhr.responseText);
},
error: function (response, status, xhr) {
showNotifications('error', JSON.stringify(response));
showNotifications('error', status);
showNotifications('error', xhr);
}
});
});
The result I get is:
Characters test: ?�???????
Please give some helpful suggestions. Thanks in advance.
I had the same problem, I've added the following filter config to my MyServletInitializer
and there's no more problem (in my case other configs don't work):
public class MyServletInitializer extends AbstractAnnotationConfigDispatcherServletInitializer {
....
#Override
protected Filter[] getServletFilters() {
CharacterEncodingFilter filter = new CharacterEncodingFilter();
filter.setEncoding("UTF-8");
filter.setForceEncoding(true);
return new Filter[]{filter};
}
....
}
Working solution:
Code to add in initializer class:
private void registerCharachterEncodingFilter(ServletContext aContext) {
CharacterEncodingFilter cef = new CharacterEncodingFilter();
cef.setForceEncoding(true);
cef.setEncoding("UTF-8");
aContext.addFilter("charachterEncodingFilter", cef).addMappingForUrlPatterns(null ,true, "/*");
}
and then call it in initializer in
onStartup method
with ServletContext:
registerCharachterEncodingFilter
I'm having some problems with my webservice -_-
I try to receive my movie list form the webservice, but there always this nasty error.
here is my model:
package de.hawhof.dm.kino.model;
import java.io.Serializable;
import java.util.List;
import java.util.Set;
import javax.persistence.CascadeType;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.Lob;
import javax.persistence.OneToMany;
import javax.xml.bind.annotation.XmlRootElement;
#Entity
#XmlRootElement(name="movie")
public class Movie implements Serializable {
/**
*
*/
private static final long serialVersionUID = 1L;
#Id
#GeneratedValue(strategy = GenerationType.AUTO)
int movieid;
String name;
String releaseDate;
#Lob
String critic;
String runtime;
#Lob
String synopsis;
String posterPath;
String thumbnail;
// user movie comment rating
#OneToMany(cascade = CascadeType.ALL, mappedBy = "movie")
List<User_Movie_CR> userMovieCR;
// cinema movie
#OneToMany(cascade = CascadeType.ALL, mappedBy = "movie")
List<Cinema_Movie> cinemaMovie;
// user film cinema table
#OneToMany(mappedBy = "movie")
Set<Cinema_Movie_User> cinema_movie_user;
public Movie() {
}
public Movie(String name, String releaseDate, String critic,
String runtime, String synopsis, String posterPath, String thumbnail) {
this.name = name;
this.releaseDate = releaseDate;
this.critic = critic;
this.runtime = runtime;
this.synopsis = synopsis;
this.posterPath = posterPath;
this.thumbnail = thumbnail;
}
// toString
public String toString() {
return "Movie [name=" + name + ", releaseDate=" + releaseDate
+ ", critic=" + critic + ", runtime=" + runtime + ", synopsis="
+ synopsis + ", posterPath=" + posterPath + "]";
}
// setter and getter
}
There is also a dao and a facade, but they are working fine!
here is my service:
package de.hawhof.dm.kino.ws;
import java.util.ArrayList;
import java.util.List;
import javax.ws.rs.GET;
import javax.ws.rs.Path;
import javax.ws.rs.PathParam;
import javax.ws.rs.Produces;
import javax.ws.rs.core.Context;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Request;
import javax.ws.rs.core.UriInfo;
import de.hawhof.dm.kino.facade.MovieFacade;
import de.hawhof.dm.kino.model.*;
#Path("/movies")
public class MoviesResource {
#Context
UriInfo uriInfo;
#Context
Request request;
MovieFacade movieFacade = new MovieFacade();
#GET
#Path("xml")
#Produces(MediaType.TEXT_XML)
public List<Movie> getMoviesBrowser() {
List<Movie> movies = new ArrayList<Movie>();
movies.addAll(movieFacade.listAll());
return movies;
}
#GET
#Path("XMLForApp")
#Produces({ MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON })
public List<Movie> getMovies() {
List<Movie> movies = new ArrayList<Movie>();
movies.addAll(movieFacade.listAll());
return movies;
}
#GET
#Path("onemovie")
public Movie getMovie() {
return new Movie("TEST!!!", "", "", "", "", "", "");
}
#GET
#Path("count")
#Produces(MediaType.TEXT_PLAIN)
public String getCount() {
int count = movieFacade.listAll().size();
return String.valueOf(count);
}
#Path("{movie}")
public MovieResource getMovie(#PathParam("movie") int movieid) {
return new MovieResource(uriInfo, request, movieid);
}
}
the methode "onemovie" and "count" works fine and i will get the xml displayed in my browser,but when i call "XMLForApp" then the server throw me exception.
my client is here:
import javax.ws.rs.client.Client;
import javax.ws.rs.client.ClientBuilder;
import javax.ws.rs.core.MediaType;
public class MovieWSClient {
Client client;
String movieList;
public MovieWSClient() {
client = ClientBuilder.newClient().register(getClass());
movieList = client.target("http://localhost:8080/kino").path("/rest/movies/XMLForApp").request(MediaType.APPLICATION_JSON).get(String.class);
}
public String getMovieList() {
return movieList;
}
}
the exception is:
SEVERE: Servlet.service() for servlet [Hello Servlet] in context with path [/kino] threw exception [An exception occurred processing JSP page /pages/public/hello.jsp at line 20
Stacktrace:] with root cause
javax.ws.rs.InternalServerErrorException: HTTP 500 Internal Server Error
at org.glassfish.jersey.client.JerseyInvocation.convertToException(JerseyInvocation.java:904)
at org.glassfish.jersey.client.JerseyInvocation.translate(JerseyInvocation.java:749)
at org.glassfish.jersey.client.JerseyInvocation.access$500(JerseyInvocation.java:88)
at org.glassfish.jersey.client.JerseyInvocation$2.call(JerseyInvocation.java:650)
at org.glassfish.jersey.internal.Errors.process(Errors.java:315)
at org.glassfish.jersey.internal.Errors.process(Errors.java:297)
at org.glassfish.jersey.internal.Errors.process(Errors.java:228)
at org.glassfish.jersey.process.internal.RequestScope.runInScope(RequestScope.java:421)
at org.glassfish.jersey.client.JerseyInvocation.invoke(JerseyInvocation.java:646)
at org.glassfish.jersey.client.JerseyInvocation$Builder.method(JerseyInvocation.java:375)
at org.glassfish.jersey.client.JerseyInvocation$Builder.get(JerseyInvocation.java:275)
at de.hawhof.dm.kino.ws.MovieWSClient.<init>(MovieWSClient.java:16)
at org.apache.jsp.pages.public_.hello_jsp._jspService(hello_jsp.java:77)
at org.apache.jasper.runtime.HttpJspBase.service(HttpJspBase.java:70)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:722)
at org.apache.jasper.servlet.JspServletWrapper.service(JspServletWrapper.java:419)
at org.apache.jasper.servlet.JspServlet.serviceJspFile(JspServlet.java:391)
at org.apache.jasper.servlet.JspServlet.service(JspServlet.java:334)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:722)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:304)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:210)
at org.apache.catalina.core.ApplicationDispatcher.invoke(ApplicationDispatcher.java:684)
at org.apache.catalina.core.ApplicationDispatcher.processRequest(ApplicationDispatcher.java:471)
at org.apache.catalina.core.ApplicationDispatcher.doForward(ApplicationDispatcher.java:402)
at org.apache.catalina.core.ApplicationDispatcher.forward(ApplicationDispatcher.java:329)
at de.hawhof.dm.kino.servlet.HelloServlet.doGet(HelloServlet.java:21)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:621)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:722)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:304)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:210)
at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:240)
at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:164)
at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:462)
at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:164)
at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:100)
at org.apache.catalina.valves.AccessLogValve.invoke(AccessLogValve.java:562)
at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:118)
at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:395)
at org.apache.coyote.http11.Http11Processor.process(Http11Processor.java:250)
at org.apache.coyote.http11.Http11Protocol$Http11ConnectionHandler.process(Http11Protocol.java:188)
at org.apache.coyote.http11.Http11Protocol$Http11ConnectionHandler.process(Http11Protocol.java:166)
at org.apache.tomcat.util.net.JIoEndpoint$SocketProcessor.run(JIoEndpoint.java:302)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1145)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:615)
at java.lang.Thread.run(Thread.java:722)
I had the same issue but with GAE( google app engine). It's seems related to Jersey MessageBodyWriter not able to serialize the JSON.
I solved it by adding genson.jar to my classpath. Genson is a JSON serializer/deserializer library that you can download on genson project page.
You can also use MOXy as your JSON provider (since it's the preferred way of supporting JSON binding with Jersey).
Don't forget to copy the jar into your WEB-INF/lib folder.
Try adding #RequestScoped to the REST service.