Spring 4 - Autowire Generic - spring

I create an generic interface CRUDService to generate multiple entity service classes with all implement the same CRUD Methods.
interface CRUDService<T> {
public abstract T saveEntity(T entity)
public abstract T getEntity(T entity)
public abstract long getCount()
}
Then I implemented from my entity Hypervisor an service class HypervisorService which implements my CRUDService
#Service
class HypervisorService implements CRUDService<Hypervisor> {
#Autowired
private HypervisorRepository hypervisorRepository
#Override
#Transactional
public Hypervisor saveEntity(Hypervisor entity) {
return hypervisorRepository.saveAndFlush(entity)
}
#Override
public Hypervisor getEntity(Hypervisor entity) {
return hypervisorRepository.findOne(entity.getId())
}
#Override
public long getCount() {
return hypervisorRepository.count()
}
}
But when i try to autowire it with
#Autowired
private CRUDService<Hypervisor> hypervisorService
I got an "java.lang.ClassCastException: com.sun.proxy.$Proxy68 cannot be cast to net.ifis.ites.hermes.services.HypervisorService" exception.
I don't understand why Spring sayes it has an classcastexception but when i changed my Service code to
#Service
class HypervisorService<Hypervisor> implements CRUDService<Hypervisor> {
...
}
My code works and i can use my generic interface but i don't think this is a good practice to use it.
Stack Trace :
java.lang.ClassCastException: com.sun.proxy.$Proxy68 cannot be cast to net.ifis.ites.hermes.services.HypervisorService
at net.ifis.ites.hermes.services.HypervisorService$saveEntity.call(Unknown Source)
at org.codehaus.groovy.runtime.callsite.CallSiteArray.defaultCall(CallSiteArray.java:45)
at org.codehaus.groovy.runtime.callsite.AbstractCallSite.call(AbstractCallSite.java:110)
at org.codehaus.groovy.runtime.callsite.AbstractCallSite.call(AbstractCallSite.java:122)
at net.ifis.ites.hermes.ui.MyVaadinUI.init(MyVaadinUI.groovy:38)
at com.vaadin.ui.UI.doInit(UI.java:646)
at net.ifis.ites.hermes.ui.MyVaadinUI.doInit(MyVaadinUI.groovy)
at com.vaadin.server.communication.UIInitHandler.getBrowserDetailsUI(UIInitHandler.java:214)
at com.vaadin.server.communication.UIInitHandler.synchronizedHandleRequest(UIInitHandler.java:74)
at com.vaadin.server.SynchronizedRequestHandler.handleRequest(SynchronizedRequestHandler.java:41)
at com.vaadin.server.VaadinService.handleRequest(VaadinService.java:1408)
at com.vaadin.server.VaadinServlet.service(VaadinServlet.java:350)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:729)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:291)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:206)
at org.apache.catalina.core.ApplicationDispatcher.invoke(ApplicationDispatcher.java:721)
at org.apache.catalina.core.ApplicationDispatcher.processRequest(ApplicationDispatcher.java:466)
at org.apache.catalina.core.ApplicationDispatcher.doForward(ApplicationDispatcher.java:358)
at org.apache.catalina.core.ApplicationDispatcher.forward(ApplicationDispatcher.java:318)
at org.springframework.web.servlet.mvc.ServletForwardingController.handleRequestInternal(ServletForwardingController.java:128)
at org.springframework.web.servlet.mvc.AbstractController.handleRequest(AbstractController.java:146)
at org.springframework.web.servlet.mvc.SimpleControllerHandlerAdapter.handle(SimpleControllerHandlerAdapter.java:50)
at org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:959)
at org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:893)
at org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:966)
at org.springframework.web.servlet.FrameworkServlet.doPost(FrameworkServlet.java:868)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:648)
at org.springframework.web.servlet.FrameworkServlet.service(FrameworkServlet.java:842)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:729)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:291)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:206)
at org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:52)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:239)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:206)
at org.springframework.web.filter.HiddenHttpMethodFilter.doFilterInternal(HiddenHttpMethodFilter.java:77)
at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:239)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:206)
at org.springframework.web.filter.CharacterEncodingFilter.doFilterInternal(CharacterEncodingFilter.java:85)
at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:239)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:206)
at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:219)
at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:106)
at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:502)
at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:142)
at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:79)
at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:88)
at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:518)
at org.apache.coyote.http11.AbstractHttp11Processor.process(AbstractHttp11Processor.java:1091)
at org.apache.coyote.AbstractProtocol$AbstractConnectionHandler.process(AbstractProtocol.java:668)
at org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.doRun(NioEndpoint.java:1521)
at org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.run(NioEndpoint.java:1478)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1142)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:617)
at org.apache.tomcat.util.threads.TaskThread$WrappingRunnable.run(TaskThread.java:61)
at java.lang.Thread.run(Thread.java:745)
In my VaadinUI i autowire only my service class and generate an hypervisor and try to save it to my database and visualize the current database counts from all hypervisors as an label.
#Component
#SpringUI
class MyVaadinUI extends UI {
#Autowired
private CRUDService<Hypervisor> hypervisorService
#Override
protected void init(VaadinRequest vaadinRequest) {
VerticalLayout layout = new VerticalLayout()
Hypervisor hypervisor = hypervisorService.saveEntity(new Hypervisor("KVM"))
layout.addComponent(new Label("Hypervisors : " + hypervisorService.getCount()))
setContent(layout)
}
}
I will try to use CGLIB for my application now.

I use in my configuration
#EnableAspectJAutoProxy(proxyTargetClass=true) and now my code works with
class HypervisorService implements CRUDService<Hypervisor> {
...
}

Related

Spring Boot Webapplication File Upload (.war)

i have a problem. I made a small Application for getting in Spring Boot.
I added a File-Upload function which was working for my .jar. Now I wanted to deploy the application on a Tomcat 8 and the file upload is not working anymore.
I guess the problem is the directory of the upload folder.
This:
#GetMapping("/uploadForm")
public String listUploadedFiles(Model model) throws IOException {
model.addAttribute("files", fileSystemStorageService.loadAll().map(
path -> MvcUriComponentsBuilder.fromMethodName(FileUploadController.class,
"serveFile", path.getFileName().toString()).build().toString())
.collect(Collectors.toList()));
This seems to be the problem. In the .jar file it was possible to find the upload-dir folder.
But I dont know how to convert it to work as a .war.
Where Spring Boot needs the upload folder in the WAR?
Thank you...
Here are more informations.
This is my Stacktrace:
hello.storage.StorageException: Failed to read stored files
at hello.storage.FileSystemStorageService.loadAll(FileSystemStorageService.java:50) ~[FileSystemStorageService.class:?]
at hello.controller.FileUploadController.listUploadedFiles(FileUploadController.java:33) ~[FileUploadController.class:?]
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) ~[?:1.8.0_111]
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62) ~[?:1.8.0_111]
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43) ~[?:1.8.0_111]
at java.lang.reflect.Method.invoke(Method.java:498) ~[?:1.8.0_111]
at org.springframework.web.method.support.InvocableHandlerMethod.doInvoke(InvocableHandlerMethod.java:205) ~[spring-web-4.3.10.RELEASE.jar:4.3.10.RELEASE]
at org.springframework.web.method.support.InvocableHandlerMethod.invokeForRequest(InvocableHandlerMethod.java:133) ~[spring-web-4.3.10.RELEASE.jar:4.3.10.RELEASE]
at org.springframework.web.servlet.mvc.method.annotation.ServletInvocableHandlerMethod.invokeAndHandle(ServletInvocableHandlerMethod.java:97) ~[spring-webmvc-4.3.10.RELEASE.jar:4.3.10.RELEASE]
at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.invokeHandlerMethod(RequestMappingHandlerAdapter.java:827) ~[spring-webmvc-4.3.10.RELEASE.jar:4.3.10.RELEASE]
at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.handleInternal(RequestMappingHandlerAdapter.java:738) ~[spring-webmvc-4.3.10.RELEASE.jar:4.3.10.RELEASE]
at org.springframework.web.servlet.mvc.method.AbstractHandlerMethodAdapter.handle(AbstractHandlerMethodAdapter.java:85) ~[spring-webmvc-4.3.10.RELEASE.jar:4.3.10.RELEASE]
at org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:967) ~[spring-webmvc-4.3.10.RELEASE.jar:4.3.10.RELEASE]
at org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:901) ~[spring-webmvc-4.3.10.RELEASE.jar:4.3.10.RELEASE]
at org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:970) ~[spring-webmvc-4.3.10.RELEASE.jar:4.3.10.RELEASE]
at org.springframework.web.servlet.FrameworkServlet.doGet(FrameworkServlet.java:861) ~[spring-webmvc-4.3.10.RELEASE.jar:4.3.10.RELEASE]
at javax.servlet.http.HttpServlet.service(HttpServlet.java:622) ~[servlet-api.jar:?]
at org.springframework.web.servlet.FrameworkServlet.service(FrameworkServlet.java:846) ~[spring-webmvc-4.3.10.RELEASE.jar:4.3.10.RELEASE]
at javax.servlet.http.HttpServlet.service(HttpServlet.java:729) ~[servlet-api.jar:?]
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:291) ~[catalina.jar:8.0.23]
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:206) ~[catalina.jar:8.0.23]
at org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:52) ~[tomcat-websocket.jar:8.0.23]
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:239) ~[catalina.jar:8.0.23]
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:206) ~[catalina.jar:8.0.23]
at org.springframework.web.filter.RequestContextFilter.doFilterInternal(RequestContextFilter.java:99) ~[spring-web-4.3.10.RELEASE.jar:4.3.10.RELEASE]
at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107) ~[spring-web-4.3.10.RELEASE.jar:4.3.10.RELEASE]
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:239) ~[catalina.jar:8.0.23]
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:206) ~[catalina.jar:8.0.23]
at org.springframework.web.filter.HttpPutFormContentFilter.doFilterInternal(HttpPutFormContentFilter.java:105) ~[spring-web-4.3.10.RELEASE.jar:4.3.10.RELEASE]
at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107) ~[spring-web-4.3.10.RELEASE.jar:4.3.10.RELEASE]
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:239) ~[catalina.jar:8.0.23]
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:206) ~[catalina.jar:8.0.23]
at org.springframework.web.filter.HiddenHttpMethodFilter.doFilterInternal(HiddenHttpMethodFilter.java:81) ~[spring-web-4.3.10.RELEASE.jar:4.3.10.RELEASE]
at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107) ~[spring-web-4.3.10.RELEASE.jar:4.3.10.RELEASE]
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:239) ~[catalina.jar:8.0.23]
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:206) ~[catalina.jar:8.0.23]
at org.springframework.web.filter.CharacterEncodingFilter.doFilterInternal(CharacterEncodingFilter.java:197) ~[spring-web-4.3.10.RELEASE.jar:4.3.10.RELEASE]
at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107) ~[spring-web-4.3.10.RELEASE.jar:4.3.10.RELEASE]
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:239) ~[catalina.jar:8.0.23]
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:206) ~[catalina.jar:8.0.23]
at org.springframework.boot.web.support.ErrorPageFilter.doFilter(ErrorPageFilter.java:115) [spring-boot-1.5.6.RELEASE.jar:1.5.6.RELEASE]
at org.springframework.boot.web.support.ErrorPageFilter.access$000(ErrorPageFilter.java:59) [spring-boot-1.5.6.RELEASE.jar:1.5.6.RELEASE]
at org.springframework.boot.web.support.ErrorPageFilter$1.doFilterInternal(ErrorPageFilter.java:90) [spring-boot-1.5.6.RELEASE.jar:1.5.6.RELEASE]
at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107) [spring-web-4.3.10.RELEASE.jar:4.3.10.RELEASE]
at org.springframework.boot.web.support.ErrorPageFilter.doFilter(ErrorPageFilter.java:108) [spring-boot-1.5.6.RELEASE.jar:1.5.6.RELEASE]
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:239) [catalina.jar:8.0.23]
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:206) [catalina.jar:8.0.23]
at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:219) [catalina.jar:8.0.23]
at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:106) [catalina.jar:8.0.23]
at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:502) [catalina.jar:8.0.23]
at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:142) [catalina.jar:8.0.23]
at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:79) [catalina.jar:8.0.23]
at org.apache.catalina.valves.AbstractAccessLogValve.invoke(AbstractAccessLogValve.java:617) [catalina.jar:8.0.23]
at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:88) [catalina.jar:8.0.23]
at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:518) [catalina.jar:8.0.23]
at org.apache.coyote.http11.AbstractHttp11Processor.process(AbstractHttp11Processor.java:1091) [tomcat-coyote.jar:8.0.23]
at org.apache.coyote.AbstractProtocol$AbstractConnectionHandler.process(AbstractProtocol.java:668) [tomcat-coyote.jar:8.0.23]
at org.apache.tomcat.util.net.AprEndpoint$SocketProcessor.doRun(AprEndpoint.java:2463) [tomcat-coyote.jar:8.0.23]
at org.apache.tomcat.util.net.AprEndpoint$SocketProcessor.run(AprEndpoint.java:2452) [tomcat-coyote.jar:8.0.23]
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1142) [?:1.8.0_111]
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:617) [?:1.8.0_111]
at org.apache.tomcat.util.threads.TaskThread$WrappingRunnable.run(TaskThread.java:61) [tomcat-util.jar:8.0.23]
at java.lang.Thread.run(Thread.java:745) [?:1.8.0_111]
Caused by: java.nio.file.NoSuchFileException: src\upload-dir
at sun.nio.fs.WindowsException.translateToIOException(WindowsException.java:79) ~[?:1.8.0_111]
at sun.nio.fs.WindowsException.rethrowAsIOException(WindowsException.java:97) ~[?:1.8.0_111]
at sun.nio.fs.WindowsException.rethrowAsIOException(WindowsException.java:102) ~[?:1.8.0_111]
at sun.nio.fs.WindowsFileAttributeViews$Basic.readAttributes(WindowsFileAttributeViews.java:53) ~[?:1.8.0_111]
at sun.nio.fs.WindowsFileAttributeViews$Basic.readAttributes(WindowsFileAttributeViews.java:38) ~[?:1.8.0_111]
at sun.nio.fs.WindowsFileSystemProvider.readAttributes(WindowsFileSystemProvider.java:193) ~[?:1.8.0_111]
at java.nio.file.Files.readAttributes(Files.java:1737) ~[?:1.8.0_111]
at java.nio.file.FileTreeWalker.getAttributes(FileTreeWalker.java:219) ~[?:1.8.0_111]
at java.nio.file.FileTreeWalker.visit(FileTreeWalker.java:276) ~[?:1.8.0_111]
at java.nio.file.FileTreeWalker.walk(FileTreeWalker.java:322) ~[?:1.8.0_111]
at java.nio.file.FileTreeIterator.<init>(FileTreeIterator.java:72) ~[?:1.8.0_111]
at java.nio.file.Files.walk(Files.java:3574) ~[?:1.8.0_111]
at hello.storage.FileSystemStorageService.loadAll(FileSystemStorageService.java: 46) ~[FileSystemStorageService.class:?]
... 62 more
This my StorageProperties
package hello.storage;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Configuration;
#ConfigurationProperties("storage")
#Configuration
public class StorageProperties {
/**
* Folder location for storing files
*/
private String location = "src/upload-dir";
public void setLocation(String location) {
this.location = location;
}
public String getLocation() {
return location;
}
}
This is my FileSystemStorageService
package hello.storage;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.io.Resource;
import org.springframework.core.io.UrlResource;
import org.springframework.stereotype.Service;
import org.springframework.util.FileSystemUtils;
import org.springframework.web.multipart.MultipartFile;
import java.io.File;
import java.io.IOException;
import java.net.MalformedURLException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Stream;
#Service
public class FileSystemStorageService implements StorageService {
private final Path rootLocation;
#Autowired
public FileSystemStorageService(StorageProperties properties) {
this.rootLocation = Paths.get(properties.getLocation());
}
#Override
public void store(MultipartFile file) {
try {
if (file.isEmpty()) {
throw new StorageException("Failed to store empty file " + file.getOriginalFilename());
}
Files.copy(file.getInputStream(), this.rootLocation.resolve(file.getOriginalFilename()));
} catch (IOException e) {
throw new StorageException("Failed to store file " + file.getOriginalFilename(), e);
}
}
#Override
public Stream<Path> loadAll() {
try {
return Files.walk(this.rootLocation, 1)
.filter(path -> !path.equals(this.rootLocation))
.map(path -> this.rootLocation.relativize(path));
} catch (IOException e) {
throw new StorageException("Failed to read stored files", e);
}
}
#Override
public Path load(String filename) {
return rootLocation.resolve(filename);
}
#Override
public Resource loadAsResource(String filename) {
try {
Path file = load(filename);
Resource resource = new UrlResource(file.toUri());
if(resource.exists() || resource.isReadable()) {
return resource;
}
else {
throw new StorageFileNotFoundException("Could not read file: " + filename);
}
} catch (MalformedURLException e) {
throw new StorageFileNotFoundException("Could not read file: " + filename, e);
}
}
#Override
public void deleteAll() {
List<File> files = Arrays.asList(rootLocation.toFile().listFiles());
for (File file:files) {
FileSystemUtils.deleteRecursively(file);
}
}
#Override
public void init() {
try {
Files.createDirectory(rootLocation);
} catch (IOException e) {
throw new StorageException("Could not initialize storage", e);
}
}
}
This is my StorageException
package hello.storage;
public class StorageException extends RuntimeException {
public StorageException(String message) {
super(message);
}
public StorageException(String message, Throwable cause) {
super(message, cause);
}
}
This is my StorageFileNotFoundException
package hello.storage;
public class StorageFileNotFoundException extends StorageException {
public StorageFileNotFoundException(String message) {
super(message);
}
public StorageFileNotFoundException(String message, Throwable cause) {
super(message, cause);
}
}
And this is my FileUploadController
package hello.controller;
import hello.storage.FileSystemStorageService;
import hello.storage.StorageFileNotFoundException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.io.Resource;
import org.springframework.http.HttpHeaders;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.mvc.method.annotation.MvcUriComponentsBuilder;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;
import java.io.IOException;
import java.util.stream.Collectors;
#Controller
public class FileUploadController {
private final FileSystemStorageService fileSystemStorageService;
#Autowired
public FileUploadController (FileSystemStorageService fileSystemStorageService) {
this.fileSystemStorageService = fileSystemStorageService;
}
#GetMapping("/uploadForm")
public String listUploadedFiles(Model model) throws IOException {
model.addAttribute("files", fileSystemStorageService.loadAll().map(
path -> MvcUriComponentsBuilder.fromMethodName(FileUploadController.class,
"serveFile", path.getFileName().toString()).build().toString())
.collect(Collectors.toList()));
if (model.asMap().size() > 0) {
return "uploadForm";
}
return null;
}
#GetMapping("/files/{filename:.+}")
#ResponseBody
public ResponseEntity<Resource> serveFile(#PathVariable String filename){
Resource file = fileSystemStorageService.loadAsResource(filename);
return ResponseEntity.ok().header(HttpHeaders.CONTENT_DISPOSITION,
"attachment;filename=\"" + file.getFilename() + "\"").body(file);
}
#PostMapping("/uploadForm")
public String handleFileUpload (#RequestParam("file")MultipartFile file,
RedirectAttributes redirectAttributes) {
try{
fileSystemStorageService.store(file);
// redirectAttributes.addFlashAttribute("message", "You successfully uploaded " + file.getOriginalFilename() + "!");
}
catch (Exception exc){
exc.printStackTrace();
}
return "redirect:/uploadForm";
}
#RequestMapping("/delete")
public String deleteAllFiles (){
fileSystemStorageService.deleteAll();
return "redirect:/uploadForm";
}
#ExceptionHandler(StorageFileNotFoundException.class)
public ResponseEntity<?> handleStorageFileNotFound(StorageFileNotFoundException exc){
return ResponseEntity.notFound().build();
}
}
How I said, it works fine with the .jar packaging but I get a 500 if I use it as a .war on a Tomcat...

Ebean: is NOT an Entity Bean registered with this server?

I'm useing spring-boot and Ebean, I follow the demo from github and the pom is
https://github.com/ebean-orm-examples/example-springboot/blob/master/pom.xml
domain:
import com.avaje.ebean.Model;
import javax.persistence.Entity;
import javax.persistence.Id;
import javax.persistence.Table;
#Entity
#Table(name="udp_dmp_crowd")
public class Crowd extends Model{
#Id
Long crowd_id;
String crowd_name;
public String getCrowd_name() {
return crowd_name;
}
public void setCrowd_name(String crowd_name) {
this.crowd_name = crowd_name;
}
public Long getCrowd_id() {
return crowd_id;
}
public void setCrowd_id(Long crowd_id) {
this.crowd_id = crowd_id;
}
}
service:
package com.ump.dmp.service;
import com.avaje.ebean.EbeanServer;
import com.ump.dmp.domain.Crowd;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.util.List;
#Service
public class CrowdService {
#Autowired
EbeanServer server;
public List<Crowd> getCrowd() {
return server.find(Crowd.class).findList();
}
}
controller:
#Controller
public class WelcomeController {
#Autowired
private CrowdService crowdService;
#RequestMapping("/")
String index(Model model) {
System.out.println(">>>>>>>>>>>>>>> Crowd List <<<<<<<<<<<<<");
List<Crowd> crowdList = crowdService.getCrowd();
for (Crowd crowd : crowdList) {
System.out.println(crowd.getCrowd_name());
}
model.addAttribute("now", LocalDateTime.now());
return "index";
}
}
use command: mvn spring-boot:run to start the app, it works
but java -jar target/demo.jar it break:
javax.persistence.PersistenceException: com.ump.dmp.domain.Crowd is NOT an Entity Bean registered with this server?
at com.avaje.ebeaninternal.server.core.DefaultServer.createQuery(DefaultServer.java:920)
at com.avaje.ebeaninternal.server.core.DefaultServer.find(DefaultServer.java:888)
at com.ump.dmp.service.CrowdService.getCrowd(CrowdService.java:21)
at com.ump.dmp.controller.WelcomeController.index(WelcomeController.java:32)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:497)
at org.springframework.web.method.support.InvocableHandlerMethod.doInvoke(InvocableHandlerMethod.java:221)
at org.springframework.web.method.support.InvocableHandlerMethod.invokeForRequest(InvocableHandlerMethod.java:136)
at org.springframework.web.servlet.mvc.method.annotation.ServletInvocableHandlerMethod.invokeAndHandle(ServletInvocableHandlerMethod.java:114)
at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.invokeHandlerMethod(RequestMappingHandlerAdapter.java:827)
at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.handleInternal(RequestMappingHandlerAdapter.java:738)
at org.springframework.web.servlet.mvc.method.AbstractHandlerMethodAdapter.handle(AbstractHandlerMethodAdapter.java:85)
at org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:963)
at org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:897)
at org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:970)
at org.springframework.web.servlet.FrameworkServlet.doGet(FrameworkServlet.java:861)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:687)
at org.springframework.web.servlet.FrameworkServlet.service(FrameworkServlet.java:846)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:790)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:230)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:165)
at org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:52)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:192)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:165)
at org.springframework.boot.web.filter.ApplicationContextHeaderFilter.doFilterInternal(ApplicationContextHeaderFilter.java:55)
at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:192)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:165)
at org.springframework.boot.actuate.trace.WebRequestTraceFilter.doFilterInternal(WebRequestTraceFilter.java:105)
at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:192)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:165)
at org.springframework.web.filter.RequestContextFilter.doFilterInternal(RequestContextFilter.java:99)
at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:192)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:165)
at org.springframework.web.filter.HttpPutFormContentFilter.doFilterInternal(HttpPutFormContentFilter.java:87)
at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:192)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:165)
at org.springframework.web.filter.HiddenHttpMethodFilter.doFilterInternal(HiddenHttpMethodFilter.java:77)
at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:192)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:165)
at org.springframework.web.filter.CharacterEncodingFilter.doFilterInternal(CharacterEncodingFilter.java:197)
at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:192)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:165)
at org.springframework.boot.actuate.autoconfigure.MetricsFilter.doFilterInternal(MetricsFilter.java:107)
at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:192)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:165)
at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:198)
at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:108)
at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:522)
at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:140)
at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:79)
at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:87)
at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:349)
at org.apache.coyote.http11.Http11Processor.service(Http11Processor.java:1110)
at org.apache.coyote.AbstractProcessorLight.process(AbstractProcessorLight.java:66)
at org.apache.coyote.AbstractProtocol$ConnectionHandler.process(AbstractProtocol.java:785)
at org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.doRun(NioEndpoint.java:1425)
at org.apache.tomcat.util.net.SocketProcessorBase.run(SocketProcessorBase.java:49)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1142)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:617)
at org.apache.tomcat.util.threads.TaskThread$WrappingRunnable.run(TaskThread.java:61)
at java.lang.Thread.run(Thread.java:745)
currently using Ebean with spring,
i had a similar issue and managed to solve it succesfully and the only thing i had to do was to rebuild the project.
By the way there are several steps you need to respect to work with Ebean:
Make sure you have enabled the proper Ebean Enhancement plugin both in you IDE and in your build manager
Make sure all the models are annotated and extend base Ebean Model
Make sure the configuration you are using to create the Ebean server is aware of where your entity models are, and i do this by adding explicity the models package to the ServerConfig object that i use to create the Ebean server
About the last point, here is the Utils class that i use to retrieve and create the Ebean server:
public class EbeanServerUtils {
public final static String MODELS_PACKAGE="com.my.package.models";
/**
* Create and return an Ebean Server using the configurations contained in the File
*
* #param name The name of the db. This is the name followed by the key datasource in the
* properties file. Ex: datasource.NAME.username=test
* usually the name is db
* #param setDefault True if this server must be setted as the default server
* #return
*/
public static EbeanServer getServer(final String name, File propertiesFile, boolean setDefault) throws IOException {
Properties properties = new Properties();
properties.load(new FileInputStream(propertiesFile));
ServerConfig config = getServerConfig(name,properties,setDefault);
EbeanServer server = EbeanServerFactory.create(config);
return server;
}
public static EbeanServer getServer(final String name, Properties properties, boolean setDefault) {
ServerConfig config = getServerConfig(name,properties,setDefault);
EbeanServer server = EbeanServerFactory.create(config);
return server;
}
private static ServerConfig getServerConfig(final String name, Properties properties, boolean setDefault) {
ServerConfig config = new ServerConfig();
config.setName(name);
config.loadFromProperties(properties);
if (setDefault) {
config.setDefaultServer(true);
config.setRegister(true);
}
config.addPackage(MODELS_PACKAGE);
return config;
}
}
and here is a tipical config file for the test environment
datasource.default=db
ebean.db.migration.run=false
ebean.migration.run=false
ebean.db.ddl.generate=false
ebean.db.ddl.run=false
datasource.db.username=username
datasource.db.password=myusernamepwd
datasource.db.databaseUrl=jdbc:h2:tcp://testmachine:9092//path/to/test/db;MODE=DB2;INIT=CREATE SCHEMA IF NOT EXISTS TESTSCHEMANAME;
datasource.db.databaseDriver=org.h2.Driver
hope it helps you,
greetings
I faced this problem today and I found solution for this problem that you need to specify your entity package by adding the following line in ebean.properties
ebean.search.packages=your.entity.package
Detail: here
Adding entity package in ebeans.properties resolved the issue.
ebean.search.packages=com.example.entities

Spring Social Facebook UncategorizedApiException: (#3) Application does not have the capability to make this API call

I have developed a simple web application that accesses Facebook data through Spring Boot (v1.2.6.RELEASE) and Spring Social Facebook (v2.0.2.RELEASE) similar to the example given here
I have created a new App in Facebook which use Graph API version 2.5.
According to this example i have modified facebookConnect.html putting this different scope to the method POST request:
<html>
<head>
<title>Facebook Extractor</title>
</head>
<body>
<h3>Connect to Facebook</h3>
<form action="/recommender/connect/facebook" method="POST">
<input type="hidden" name="scope" value="public_profile, user_friends, email, user_likes" />
<div class="formInfo">
<p>You aren't connected to Facebook yet. Click the button to connect this application with your Facebook account.</p>
</div>
<p><button type="submit">Connect to Facebook</button></p>
</form>
</body>
handled by ConnectController which kick off the OAuth authorization code flow...
After OAuth success (with permission granted) and connection is done, i get the following error:
(#3) application does not have the capability to make this api call.
Here the main part of the controller which handle the redirect from Facebook App:
#Controller
#Scope(value="session")
public class FacebookExtractor {
private Logger logger = Logger.getLogger(FacebookExtractor.class);
private Facebook facebook;
#Autowired
GraphDatabase graphDatabase;
#Autowired
PersonRepository personRepository;
#Autowired
UserProfileRepository userProfileRepository;
#Autowired
AttributeDefinitionRepository attributeDefinitionRepository;
#Autowired
AttributeRepository attributeRepository;
#Autowired
ConceptRepository conceptRepository;
#Autowired
RecommenderGovConsumerRepository recGovRepository;
#Autowired
GovConsumerInfluencedByGovConsumerRelationshipRepository influenceRepository;
#Autowired
ExtractorListener listener;
private String userBind;
#Inject
public FacebookExtractor(Facebook facebook) {
this.facebook = facebook;
}
#RequestMapping(method = RequestMethod.GET, value = "/facebookExtractor")
public ModelAndView FacebookDataUserExtraction() {
if (!facebook.isAuthorized()) {
return new ModelAndView("redirect:/recommender/connect/facebook");
}
String account=userBind;
Long netId = null;
Transaction tx = graphDatabase.beginTx();
try {
User user = facebook.userOperations().getUserProfile();
Person p = savePerson(user);
UserProfile up = saveUserProfile(user);
up.setUser(p);
userProfileRepository.save(up);
p.setProfile(up);
saveSocialInteractions(up);
saveSocialPreferences(up);
personRepository.save(p);
netId=p.getId();
tx.success();
} finally {
tx.close();
}
if (account != null) {
/*
* Binding di Facebook riuscito.
*/
listener.onProfileDataCompleted(netId, SNAccountType.Facebook);
listener.onInteractionsCompleted(netId, InteractionType.Friendship, SNAccountType.Facebook);
return new ModelAndView("redirect:http://localhost:8080/portal",
"accountF", account);
} else {
//vista opportuna per estrazione avvenuta senza bind
return new ModelAndView("facebookNoBindExtraction");
}
}
Watching the stack trace error, seems i'm getting error at this line in controller:
User user = facebook.userOperations().getUserProfile();
but it is strange because I should have permission to get basic user profile data by default.
Note: the same code with an older App in Facebook which use Graph API version 2.3 works perfectly, but i need a new one for different purpose and can't force a new App in Facebook to use that version...
Here the stack error i get....
12:01:16.953 [http-nio-9080-exec-5] ERROR
o.a.c.c.C.[.[.[.[dispatcherServlet] - Servlet.service() for servlet
[dispatcherServlet] in context with path [] threw exception [Request
processing failed; nested exception is
org.springframework.social.UncategorizedApiException: (#3) Application
does not have the capability to make this API call.] with root cause
org.springframework.social.UncategorizedApiException: (#3) Application
does not have the capability to make this API call. at
org.springframework.social.facebook.api.impl.FacebookErrorHandler.handleFacebookError(FacebookErrorHandler.java:91)
~[spring-social-facebook-2.0.2.RELEASE.jar:2.0.2.RELEASE] at
org.springframework.social.facebook.api.impl.FacebookErrorHandler.handleError(FacebookErrorHandler.java:59)
~[spring-social-facebook-2.0.2.RELEASE.jar:2.0.2.RELEASE] at
org.springframework.web.client.RestTemplate.handleResponse(RestTemplate.java:614)
~[spring-web-4.1.7.RELEASE.jar:4.1.7.RELEASE] at
org.springframework.web.client.RestTemplate.doExecute(RestTemplate.java:570)
~[spring-web-4.1.7.RELEASE.jar:4.1.7.RELEASE] at
org.springframework.web.client.RestTemplate.execute(RestTemplate.java:545)
~[spring-web-4.1.7.RELEASE.jar:4.1.7.RELEASE] at
org.springframework.web.client.RestTemplate.getForObject(RestTemplate.java:253)
~[spring-web-4.1.7.RELEASE.jar:4.1.7.RELEASE] at
org.springframework.social.facebook.api.impl.FacebookTemplate.fetchObject(FacebookTemplate.java:214)
~[spring-social-facebook-2.0.2.RELEASE.jar:2.0.2.RELEASE] at
org.springframework.social.facebook.api.impl.FacebookTemplate.fetchObject(FacebookTemplate.java:209)
~[spring-social-facebook-2.0.2.RELEASE.jar:2.0.2.RELEASE] at
org.springframework.social.facebook.api.impl.UserTemplate.getUserProfile(UserTemplate.java:53)
~[spring-social-facebook-2.0.2.RELEASE.jar:2.0.2.RELEASE] at
org.springframework.social.facebook.api.impl.UserTemplate.getUserProfile(UserTemplate.java:49)
~[spring-social-facebook-2.0.2.RELEASE.jar:2.0.2.RELEASE] at
it.cerict.recommender.extractor.controllers.FacebookExtractor.FacebookDataUserExtraction(FacebookExtractor.java:89)
~[classes/:na] at sun.reflect.NativeMethodAccessorImpl.invoke0(Native
Method) ~[na:1.8.0_60] at
sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
~[na:1.8.0_60] at
sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
~[na:1.8.0_60] at java.lang.reflect.Method.invoke(Method.java:497)
~[na:1.8.0_60] at
org.springframework.web.method.support.InvocableHandlerMethod.doInvoke(InvocableHandlerMethod.java:221)
~[spring-web-4.1.7.RELEASE.jar:4.1.7.RELEASE] at
org.springframework.web.method.support.InvocableHandlerMethod.invokeForRequest(InvocableHandlerMethod.java:137)
~[spring-web-4.1.7.RELEASE.jar:4.1.7.RELEASE] at
org.springframework.web.servlet.mvc.method.annotation.ServletInvocableHandlerMethod.invokeAndHandle(ServletInvocableHandlerMethod.java:110)
~[spring-webmvc-4.1.7.RELEASE.jar:4.1.7.RELEASE] at
org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.invokeHandleMethod(RequestMappingHandlerAdapter.java:776)
~[spring-webmvc-4.1.7.RELEASE.jar:4.1.7.RELEASE] at
org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.handleInternal(RequestMappingHandlerAdapter.java:705)
~[spring-webmvc-4.1.7.RELEASE.jar:4.1.7.RELEASE] at
org.springframework.web.servlet.mvc.method.AbstractHandlerMethodAdapter.handle(AbstractHandlerMethodAdapter.java:85)
~[spring-webmvc-4.1.7.RELEASE.jar:4.1.7.RELEASE] at
org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:959)
~[spring-webmvc-4.1.7.RELEASE.jar:4.1.7.RELEASE] at
org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:893)
~[spring-webmvc-4.1.7.RELEASE.jar:4.1.7.RELEASE] at
org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:967)
~[spring-webmvc-4.1.7.RELEASE.jar:4.1.7.RELEASE] at
org.springframework.web.servlet.FrameworkServlet.doGet(FrameworkServlet.java:858)
~[spring-webmvc-4.1.7.RELEASE.jar:4.1.7.RELEASE] at
javax.servlet.http.HttpServlet.service(HttpServlet.java:622)
~[tomcat-embed-core-8.0.26.jar:8.0.26] at
org.springframework.web.servlet.FrameworkServlet.service(FrameworkServlet.java:843)
~[spring-webmvc-4.1.7.RELEASE.jar:4.1.7.RELEASE] at
javax.servlet.http.HttpServlet.service(HttpServlet.java:729)
~[tomcat-embed-core-8.0.26.jar:8.0.26] at
org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:291)
~[tomcat-embed-core-8.0.26.jar:8.0.26] at
org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:206)
~[tomcat-embed-core-8.0.26.jar:8.0.26] at
org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:52)
~[tomcat-embed-websocket-8.0.26.jar:8.0.26] at
org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:239)
~[tomcat-embed-core-8.0.26.jar:8.0.26] at
org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:206)
~[tomcat-embed-core-8.0.26.jar:8.0.26] at
it.cerict.recommender.config.CORSFilter.doFilter(CORSFilter.java:22)
~[classes/:na] at
org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:239)
~[tomcat-embed-core-8.0.26.jar:8.0.26] at
org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:206)
~[tomcat-embed-core-8.0.26.jar:8.0.26] at
org.springframework.web.filter.HiddenHttpMethodFilter.doFilterInternal(HiddenHttpMethodFilter.java:77)
~[spring-web-4.1.7.RELEASE.jar:4.1.7.RELEASE] at
org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107)
~[spring-web-4.1.7.RELEASE.jar:4.1.7.RELEASE] at
org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:239)
~[tomcat-embed-core-8.0.26.jar:8.0.26] at
org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:206)
~[tomcat-embed-core-8.0.26.jar:8.0.26] at
org.springframework.web.filter.CharacterEncodingFilter.doFilterInternal(CharacterEncodingFilter.java:85)
~[spring-web-4.1.7.RELEASE.jar:4.1.7.RELEASE] at
org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107)
~[spring-web-4.1.7.RELEASE.jar:4.1.7.RELEASE] at
org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:239)
~[tomcat-embed-core-8.0.26.jar:8.0.26] at
org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:206)
~[tomcat-embed-core-8.0.26.jar:8.0.26] at
org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:219)
~[tomcat-embed-core-8.0.26.jar:8.0.26] at
org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:106)
[tomcat-embed-core-8.0.26.jar:8.0.26] at
org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:502)
[tomcat-embed-core-8.0.26.jar:8.0.26] at
org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:142)
[tomcat-embed-core-8.0.26.jar:8.0.26] at
org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:79)
[tomcat-embed-core-8.0.26.jar:8.0.26] at
org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:88)
[tomcat-embed-core-8.0.26.jar:8.0.26] at
org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:518)
[tomcat-embed-core-8.0.26.jar:8.0.26] at
org.apache.coyote.http11.AbstractHttp11Processor.process(AbstractHttp11Processor.java:1091)
[tomcat-embed-core-8.0.26.jar:8.0.26] at
org.apache.coyote.AbstractProtocol$AbstractConnectionHandler.process(AbstractProtocol.java:673)
[tomcat-embed-core-8.0.26.jar:8.0.26] at
org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.doRun(NioEndpoint.java:1526)
[tomcat-embed-core-8.0.26.jar:8.0.26] at
org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.run(NioEndpoint.java:1482)
[tomcat-embed-core-8.0.26.jar:8.0.26] at
java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1142)
[na:1.8.0_60] at
java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:617)
[na:1.8.0_60] at
org.apache.tomcat.util.threads.TaskThread$WrappingRunnable.run(TaskThread.java:61)
[tomcat-embed-core-8.0.26.jar:8.0.26] at
java.lang.Thread.run(Thread.java:745) [na:1.8.0_60]
The problem is with PROFILE_FILEDS in
public User getUserProfile(String facebookId) {
return graphApi.fetchObject(facebookId, User.class, PROFILE_FIELDS);
}
Array PROFILE_FIELDS contains many many fields and as I understang correctly spring-social docs, Facebook returned only this fields you have rights to view.
But now something changed:
$curl "https://graph.facebook.com/v2.5/me?access_token=[access_tokens]&fields=[all_the_fields_from_PROFILE_FIELDS]
{"error":{"message":"(#3) Application does not have the capability to make this API call.","type":"OAuthException","code":3,"fbtrace_id":"Antivssjj1d"}}
$ curl "https://graph.facebook.com/v2.3/me?access_token=[access_token]&fields=id,about"
{"id":"1135898619755433"}
In the meantime I've found sollution. Instead
User profile = facebook.userOperations().getUserProfile()
we can use
User profile = facebook.fetchObject("me", User.class, "id", "name", "link", "email");
//Note: facebook = org.springframework.social.facebook.api.Facebook
//Note: User.class = org.springframework.social.facebook.api.User.class
Or wait the update of spring-social-facebook, there is a pull request pending on the repository: https://github.com/spring-projects/spring-social-facebook/pull/171
UPDATE: Fix for me with the 2.0.3.RELEASE version.
I continued to get this error, even after adding the publish_actions scope that my app needed. The issue in my case was that I needed Facebook to review my app. This is the case if your app was created after April 30th, 2014 and one or more of the following is true:
You want your App to be listed in the Facebook App Center
You want to create new, or edit existing, Open Graph actions and stories
Your app asks people for any extended permissions including publish_actions
Have a look at the Facebook Login Review FAQs for more info on the review process.

Spring boot and #SessionAttributes

I'm working on an app with Spring Boot 1.2.5 RELEASE and having a problem that's difficult to replicate, and seems to be related to my session. Doing lots of research indicates that when using the #SessionAttribute annotation my session will end when my web page accesses another controller. Although I also found some information that indicates this is no longer true with the most recent Spring Boot. Also, the other controller does not use the same template or session identifier as this controller.
Alternatively I think my session may be expiring, but I can't seem to find any information talking about a default time out.
The app is straightforward, just a web page to edit form data. Sometimes when the save button is clicked an exception is thrown saying something to the effect that "adminForm" is not valid model data. I'm sorry I have been unable to replicate the exception and had not saved it.
The code is below, thanks in advance for your comments.
#SessionAttributes("adminForm")
#Controller
public class Admin_FormController
{
final static protected long INDEX_RA = 1L;
#Autowired
private AdminDataRepository rep;
#RequestMapping(value="/admin", method=RequestMethod.GET)
public String adminForm(Model model)
{
AdminData ad = rep.findById(INDEX_RA);
// If there is no configuration record, create one and assign the primary key
if(ad == null)
{
ad = new AdminData();
ad.setId(INDEX_RA);
}
model.addAttribute("adminForm", ad);
return "adminForm";
}
#RequestMapping(value="/admin", method=RequestMethod.POST)
public #ResponseBody AdminData adminSubmit(#ModelAttribute("adminForm") AdminData ad, Model model)
{
rep.save(ad);
model.addAttribute("adminForm", ad);
return ad;
}
}
UPDATE:
Here is the exception that is thrown:
2015-07-28 11:12:16.564 ERROR 52963 --- [nio-8080-exec-3] o.a.c.c.C.[.[.[/].[dispatcherServlet] : Servlet.service() for servlet [dispatcherServlet] in context with path [] threw exception [Expected session attribute 'adminForm'] with root cause
org.springframework.web.HttpSessionRequiredException: Expected session attribute 'adminForm'
at org.springframework.web.method.annotation.ModelFactory.initModel(ModelFactory.java:115)
at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.invokeHandleMethod(RequestMappingHandlerAdapter.java:753)
at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.handleInternal(RequestMappingHandlerAdapter.java:705)
at org.springframework.web.servlet.mvc.method.AbstractHandlerMethodAdapter.handle(AbstractHandlerMethodAdapter.java:85)
at org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:959)
at org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:893)
at org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:967)
at org.springframework.web.servlet.FrameworkServlet.doPost(FrameworkServlet.java:869)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:648)
at org.springframework.web.servlet.FrameworkServlet.service(FrameworkServlet.java:843)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:729)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:291)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:206)
at org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:52)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:239)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:206)
at org.springframework.web.filter.HiddenHttpMethodFilter.doFilterInternal(HiddenHttpMethodFilter.java:77)
at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:239)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:206)
at org.springframework.web.filter.CharacterEncodingFilter.doFilterInternal(CharacterEncodingFilter.java:85)
at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:239)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:206)
at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:219)
at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:106)
at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:502)
at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:142)
at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:79)
at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:88)
at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:518)
at org.apache.coyote.http11.AbstractHttp11Processor.process(AbstractHttp11Processor.java:1091)
at org.apache.coyote.AbstractProtocol$AbstractConnectionHandler.process(AbstractProtocol.java:668)
at org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.doRun(NioEndpoint.java:1521)
at org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.run(NioEndpoint.java:1478)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1142)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:617)
at org.apache.tomcat.util.threads.TaskThread$WrappingRunnable.run(TaskThread.java:61)
at java.lang.Thread.run(Thread.java:745)
I was able to solve this problem by specifying that the session should never time out. This is fine in our case since this app is secured behind a single sign on appl. Here is what I added to the application.properties file:
server.session-timeout=-1

Exception Handler not working on a spring boot app

I have created a spring boot application defined like this :
#Configuration
#EnableAutoConfiguration
#ComponentScan
public class Application {
public static void main(String[] args) {
ApplicationContext ctx = SpringApplication.run(Application.class, args);
}
}
I have also created a RestController for this application with a request mapping
I have then created a specific exception :
public class MyOwnException extends Exception {
public MyOwnException (String message) {
super(message);
}
}
And then defined a class for globalling handling all of my exception
#ControllerAdvice(annotations = RestController.class)
public class MyOwnExceptionHandler extends ResponseEntityExceptionHandler {
#ExceptionHandler(MyOwnException.class)
#ResponseStatus(value = HttpStatus.NOT_FOUND, reason = "File or folder is unwrittable")
public #ResponseBody
ExceptionJSONInfo handleMyOwnException(
HttpServletRequest request, Exception ex) {
ExceptionJSONInfo response = new ExceptionJSONInfo();
response.setUrl(request.getRequestURL().toString());
response.setMessage(ex.getMessage());
return response;
}
Here is my controller code :
#RestController
#RequestMapping(value="/you/should")
public class MyOwnController {
#RequestMapping(value="/try/this", method=RequestMethod.GET, produces = "application/pdf")
public FileSystemResource processSomething(HttpServletResponse response) throws MyOwnException {
FileSystemResource afileRessource = new FileSystemResource();
if (true)
throw new MyOwnException("File not readable: " + finalFileWithEncryptedName);
return afileRessource
}
}
Unfortunately the handler is never been called instead I get following stacktrace :
2015-02-26 17:37:34.914 ERROR 6512 --- [nio-9050-exec-5] .a.c.c.C.[.[.[.p.k.p.[dispatcherServlet] : Servlet.service() for servlet [dispatcherServlet] in context with path [/myOwnContext] threw exception [Request processing failed; nested exception is MyOwnException: My onw exception message] with root cause MyOwnException: MyOwnExceptionMessage
at MyOwnController.myOwnCOntrollerMethod(MyOwnController.java:164)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:601)
at org.springframework.web.method.support.InvocableHandlerMethod.invoke(InvocableHandlerMethod.java:215)
at org.springframework.web.method.support.InvocableHandlerMethod.invokeForRequest(InvocableHandlerMethod.java:132)
at org.springframework.web.servlet.mvc.method.annotation.ServletInvocableHandlerMethod.invokeAndHandle(ServletInvocableHandlerMethod.java:104)
at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.invokeHandleMethod(RequestMappingHandlerAdapter.java:749)
at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.handleInternal(RequestMappingHandlerAdapter.java:689)
at org.springframework.web.servlet.mvc.method.AbstractHandlerMethodAdapter.handle(AbstractHandlerMethodAdapter.java:83)
at org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:938)
at org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:870)
at org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:961)
at org.springframework.web.servlet.FrameworkServlet.doGet(FrameworkServlet.java:852)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:620)
at org.springframework.web.servlet.FrameworkServlet.service(FrameworkServlet.java:837)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:727)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:303)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:208)
at org.springframework.boot.actuate.trace.WebRequestTraceFilter.doFilterInternal(WebRequestTraceFilter.java:110)
at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:241)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:208)
at org.springframework.boot.actuate.autoconfigure.EndpointWebMvcAutoConfiguration$ApplicationContextHeaderFilter.doFilterInternal(EndpointWebMvcAutoConfiguration.java:280)
at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:241)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:208)
at org.springframework.web.filter.HiddenHttpMethodFilter.doFilterInternal(HiddenHttpMethodFilter.java:77)
at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:241)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:208)
at org.springframework.boot.actuate.autoconfigure.MetricFilterAutoConfiguration$MetricsFilter.doFilterInternal(MetricFilterAutoConfiguration.java:90)
at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:241)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:208)
at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:220)
at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:122)
at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:503)
at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:170)
at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:103)
at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:116)
at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:421)
at org.apache.coyote.http11.AbstractHttp11Processor.process(AbstractHttp11Processor.java:1070)
at org.apache.coyote.AbstractProtocol$AbstractConnectionHandler.process(AbstractProtocol.java:611)
at org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.doRun(NioEndpoint.java:1736)
at org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.run(NioEndpoint.java:1695)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1110)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:603)
at org.apache.tomcat.util.threads.TaskThread$WrappingRunnable.run(TaskThread.java:61)
at java.lang.Thread.run(Thread.java:722)
Can anybody please help me find why my ControllerAdvise is never being called?
Try adding #EnableWebMvc annotation to your configuration class and make sure your controller advice is being scanned.
If anyone has the same problem and "adding #EnableWebMvc annotation to your configuration class" didn't solve the problem, the solution can be in correctly naming your package. If your package is wrongly named it won't be scanned and therefore exception handler will never be triggered.
More about packages here: https://www.baeldung.com/java-packages
Basically your package and directory structure should be the same...
#EnableAspectJAutoProxy
works for me,
#EnableWebMvc does not.
Spring boot 2.0

Resources