Injecting a singleton into JAX-RS (Jersey) resources, as a Tomcat servlet - rest

I'm trying to build a RESTful web service. This component is an addition to an existing Tomcat 7 web application that contains several Servlets already. I'm using Jersey 2.25.
I need to instantiate a few components (objects) that are related to the existing system. I wish to do that once, while the application loads - and than read them from each Resource.
My current classes are:
#ApplicationPath("resources")
public class MyApplication extends ResourceConfig {
public MyApplication() {
packages("plc_webservice.PersonResource");
register(new MyBinder());
}
}
public class MyBinder extends AbstractBinder{
#Override
protected void configure() {
bind(new MyService()).to(MyService.class);
}
}
This is the class that I want to use as a singleton:
public class MyService {
String name;
public MyService() {
name = "John";
}
public String getName() {
return name;
}
}
And a resource:
#Path("Person")
public class PersonResource {
#Inject
private MyService service;
#GET
public String test() {
String result = "Hello!";
return result;
}
}
I can't figure out why am I getting this exception:
javax.servlet.ServletException: A MultiException has 3 exceptions.
They are:
1. org.glassfish.hk2.api.UnsatisfiedDependencyException: There was no object available for injection at
SystemInjecteeImpl(requiredType=MyService,parent=PersonResource,qualifiers={},position=-1,optional=false,self=false,unqualified=null,1688478701)
2. java.lang.IllegalArgumentException: While attempting to resolve the dependencies of plc_webservice.PersonResource errors were found
3. java.lang.IllegalStateException: Unable to perform operation: resolve on plc_webservice.PersonResource
org.glassfish.jersey.servlet.WebComponent.serviceImpl(WebComponent.java:489)
org.glassfish.jersey.servlet.WebComponent.service(WebComponent.java:427)
org.glassfish.jersey.servlet.ServletContainer.service(ServletContainer.java:388)
org.glassfish.jersey.servlet.ServletContainer.service(ServletContainer.java:341)
org.glassfish.jersey.servlet.ServletContainer.service(ServletContainer.java:228)
org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:52)
org.netbeans.modules.web.monitor.server.MonitorFilter.doFilter(MonitorFilter.java:393)
root cause
A MultiException has 3 exceptions. They are:
1. org.glassfish.hk2.api.UnsatisfiedDependencyException: There was no object available for injection at
SystemInjecteeImpl(requiredType=MyService,parent=PersonResource,qualifiers={},position=-1,optional=false,self=false,unqualified=null,1688478701)
2. java.lang.IllegalArgumentException: While attempting to resolve the dependencies of plc_webservice.PersonResource errors were found
3. java.lang.IllegalStateException: Unable to perform operation: resolve on plc_webservice.PersonResource
org.jvnet.hk2.internal.Collector.throwIfErrors(Collector.java:89)
org.jvnet.hk2.internal.ClazzCreator.resolveAllDependencies(ClazzCreator.java:250)
org.jvnet.hk2.internal.ClazzCreator.create(ClazzCreator.java:358)
org.jvnet.hk2.internal.SystemDescriptor.create(SystemDescriptor.java:487)
org.glassfish.jersey.process.internal.RequestScope.findOrCreate(RequestScope.java:162)
org.jvnet.hk2.internal.Utilities.createService(Utilities.java:2022)
org.jvnet.hk2.internal.ServiceLocatorImpl.internalGetService(ServiceLocatorImpl.java:774)
org.jvnet.hk2.internal.ServiceLocatorImpl.internalGetService(ServiceLocatorImpl.java:737)
org.jvnet.hk2.internal.ServiceLocatorImpl.getService(ServiceLocatorImpl.java:707)
org.glassfish.jersey.internal.inject.Injections.getOrCreate(Injections.java:172)
org.glassfish.jersey.server.model.MethodHandler$ClassBasedMethodHandler.getInstance(MethodHandler.java:284)
org.glassfish.jersey.server.internal.routing.PushMethodHandlerRouter.apply(PushMethodHandlerRouter.java:74)
org.glassfish.jersey.server.internal.routing.RoutingStage._apply(RoutingStage.java:109)
org.glassfish.jersey.server.internal.routing.RoutingStage._apply(RoutingStage.java:112)
org.glassfish.jersey.server.internal.routing.RoutingStage._apply(RoutingStage.java:112)
org.glassfish.jersey.server.internal.routing.RoutingStage._apply(RoutingStage.java:112)
org.glassfish.jersey.server.internal.routing.RoutingStage.apply(RoutingStage.java:92)
org.glassfish.jersey.server.internal.routing.RoutingStage.apply(RoutingStage.java:61)
org.glassfish.jersey.process.internal.Stages.process(Stages.java:197)
org.glassfish.jersey.server.ServerRuntime$2.run(ServerRuntime.java:318)
org.glassfish.jersey.internal.Errors$1.call(Errors.java:271)
org.glassfish.jersey.internal.Errors$1.call(Errors.java:267)
org.glassfish.jersey.internal.Errors.process(Errors.java:315)
org.glassfish.jersey.internal.Errors.process(Errors.java:297)
org.glassfish.jersey.internal.Errors.process(Errors.java:267)
org.glassfish.jersey.process.internal.RequestScope.runInScope(RequestScope.java:317)
org.glassfish.jersey.server.ServerRuntime.process(ServerRuntime.java:305)
org.glassfish.jersey.server.ApplicationHandler.handle(ApplicationHandler.java:1154)
org.glassfish.jersey.servlet.WebComponent.serviceImpl(WebComponent.java:473)
org.glassfish.jersey.servlet.WebComponent.service(WebComponent.java:427)
org.glassfish.jersey.servlet.ServletContainer.service(ServletContainer.java:388)
org.glassfish.jersey.servlet.ServletContainer.service(ServletContainer.java:341)
org.glassfish.jersey.servlet.ServletContainer.service(ServletContainer.java:228)
org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:52)
org.netbeans.modules.web.monitor.server.MonitorFilter.doFilter(MonitorFilter.java:393)
root cause
org.glassfish.hk2.api.UnsatisfiedDependencyException: There was no
object available for injection at
SystemInjecteeImpl(requiredType=MyService,parent=PersonResource,qualifiers={},position=-1,optional=false,self=false,unqualified=null,1688478701) org.jvnet.hk2.internal.ThreeThirtyResolver.resolve(ThreeThirtyResolver.java:75)
org.jvnet.hk2.internal.ClazzCreator.resolve(ClazzCreator.java:212)
org.jvnet.hk2.internal.ClazzCreator.resolveAllDependencies(ClazzCreator.java:235)
org.jvnet.hk2.internal.ClazzCreator.create(ClazzCreator.java:358)
org.jvnet.hk2.internal.SystemDescriptor.create(SystemDescriptor.java:487)
org.glassfish.jersey.process.internal.RequestScope.findOrCreate(RequestScope.java:162)
org.jvnet.hk2.internal.Utilities.createService(Utilities.java:2022)
org.jvnet.hk2.internal.ServiceLocatorImpl.internalGetService(ServiceLocatorImpl.java:774)
org.jvnet.hk2.internal.ServiceLocatorImpl.internalGetService(ServiceLocatorImpl.java:737)
org.jvnet.hk2.internal.ServiceLocatorImpl.getService(ServiceLocatorImpl.java:707)
org.glassfish.jersey.internal.inject.Injections.getOrCreate(Injections.java:172)
org.glassfish.jersey.server.model.MethodHandler$ClassBasedMethodHandler.getInstance(MethodHandler.java:284)
org.glassfish.jersey.server.internal.routing.PushMethodHandlerRouter.apply(PushMethodHandlerRouter.java:74)
org.glassfish.jersey.server.internal.routing.RoutingStage._apply(RoutingStage.java:109)
org.glassfish.jersey.server.internal.routing.RoutingStage._apply(RoutingStage.java:112)
org.glassfish.jersey.server.internal.routing.RoutingStage._apply(RoutingStage.java:112)
org.glassfish.jersey.server.internal.routing.RoutingStage._apply(RoutingStage.java:112)
org.glassfish.jersey.server.internal.routing.RoutingStage.apply(RoutingStage.java:92)
org.glassfish.jersey.server.internal.routing.RoutingStage.apply(RoutingStage.java:61)
org.glassfish.jersey.process.internal.Stages.process(Stages.java:197)
org.glassfish.jersey.server.ServerRuntime$2.run(ServerRuntime.java:318)
org.glassfish.jersey.internal.Errors$1.call(Errors.java:271)
org.glassfish.jersey.internal.Errors$1.call(Errors.java:267)
org.glassfish.jersey.internal.Errors.process(Errors.java:315)
org.glassfish.jersey.internal.Errors.process(Errors.java:297)
org.glassfish.jersey.internal.Errors.process(Errors.java:267)
org.glassfish.jersey.process.internal.RequestScope.runInScope(RequestScope.java:317)
org.glassfish.jersey.server.ServerRuntime.process(ServerRuntime.java:305)
org.glassfish.jersey.server.ApplicationHandler.handle(ApplicationHandler.java:1154)
org.glassfish.jersey.servlet.WebComponent.serviceImpl(WebComponent.java:473)
org.glassfish.jersey.servlet.WebComponent.service(WebComponent.java:427)
org.glassfish.jersey.servlet.ServletContainer.service(ServletContainer.java:388)
org.glassfish.jersey.servlet.ServletContainer.service(ServletContainer.java:341)
org.glassfish.jersey.servlet.ServletContainer.service(ServletContainer.java:228)
org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:52)
org.netbeans.modules.web.monitor.server.MonitorFilter.doFilter(MonitorFilter.java:393)
Thank you.

I think this is a CDI question. Do you have beans.xml defined? Also, if you want MyService to be a singleton, I think you want to annotate it with #ApplicationScoped.

First of all injected resources(beans) and Jersey Endpoint class(point of injection) must be CDI-Aware. It must be detecteable by CDI. We can use bean-discovery-mode="all" - then CDI scan ALL classes or
bean-discovery-mode="annotated" and MARK our class with PROPER annotation: from here : Bean defining annotations. I prefer#Dependent or #RequestScoped
Then we must use Jersey Extension
<dependency>
<groupId>org.glassfish.jersey.ext.cdi</groupId>
<artifactId>jersey-cdi1x-servlet</artifactId>
<version>{version}</version>
<scope>runtime</scope>
</dependency>
`
to connect CDI with HK2 discovery mechanism.
Here is Official oracle Guideline

Related

Unable to use Jakarta EE 8 Security in WildFly 20

I'm trying to use Jakarta EE 8 Security in my application by defining a BasicAuthenticationMechanismDefinition in a CDI Bean:
#BasicAuthenticationMechanismDefinition(
realmName = "RealmUsersRoles")
#ApplicationScoped
public class ApplicationConfig{}
The Realm I'm using is a FileSystemRealm defined in Elytron. Next, I've specified the allowed Roles in the endpoint:
#WebServlet("/secured")
#DeclareRoles({"Administrator"})
#ServletSecurity(#HttpConstraint(rolesAllowed = { "Administrator" }))
public class SecuredServlet extends HttpServlet {
#Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
// Do something
}
}
I have added the following dependency to build and deploy the application on WildFly 20:
<dependency>
<groupId>jakarta.security.enterprise</groupId>
<artifactId>jakarta.security.enterprise-api</artifactId>
</dependency>
<dependency>
<groupId>org.glassfish.soteria</groupId>
<artifactId>javax.security.enterprise</artifactId>
<version>1.0</version>
</dependency>
Upon requesting the secured resource, the following error is returned:
java.lang.IllegalStateException: Could not find beans for Type=interface javax.security.enterprise.identitystore.IdentityStore
at org.glassfish.soteria#1.0.1-jbossorg-1//org.glassfish.soteria.cdi.CdiUtils.getBeanDefinitions(CdiUtils.java:194)
at org.glassfish.soteria#1.0.1-jbossorg-1//org.glassfish.soteria.cdi.CdiUtils.getBeanReferencesByType(CdiUtils.java:158)
at org.glassfish.soteria#1.0.1-jbossorg-1//org.glassfish.soteria.cdi.DefaultIdentityStoreHandler.init(DefaultIdentityStoreHandler.java:51)
at org.glassfish.soteria#1.0.1-jbossorg-1//org.glassfish.soteria.cdi.CdiExtension.lambda$afterBean$12(CdiExtension.java:215)
at org.glassfish.soteria#1.0.1-jbossorg-1//org.glassfish.soteria.cdi.CdiProducer.create(CdiProducer.java:80)
at org.jboss.weld.core#3.1.4.Final//org.jboss.weld.contexts.AbstractContext.get(AbstractContext.java:96)
at org.jboss.weld.core#3.1.4.Final//org.jboss.weld.bean.ContextualInstanceStrategy$DefaultContextualInstanceStrategy.get(ContextualInstanceStrategy.java:100)
at org.jboss.weld.core#3.1.4.Final//org.jboss.weld.bean.ContextualInstance.get(ContextualInstance.java:50)
at org.jboss.weld.core#3.1.4.Final//org.jboss.weld.bean.proxy.ContextBeanInstance.getInstance(ContextBeanInstance.java:102)
at org.jboss.weld.core#3.1.4.Final//org.jboss.weld.bean.proxy.ProxyMethodHandler.invoke(ProxyMethodHandler.java:105)
at deployment.http-basic.war//org.jboss.weldx.security.enterprise.identitystore.IdentityStoreHandler$1763020431$Proxy$_$$_WeldClientProxy.validate(Unknown Source)
at org.glassfish.soteria#1.0.1-jbossorg-1//org.glassfish.soteria.mechanisms.BasicAuthenticationMechanism.validateRequest(BasicAuthenticationMechanism.java:60)
at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
at java.base/jdk.internal.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.base/java.lang.reflect.Method.invoke(Method.java:566)
Did I miss any dependency in my application? or maybe wrong version for the glassfish.soteria dependency?
Any help is much appreciated
Thanks
You need to provide an implementation of javax.security.enterprise.identitystore.IdentityStore
You can use LdapIdentityStoreDefinition or DatabaseIdentityStoreDefinition or provide your own bean (ApplicationScoped) which implements IdentityStore.

JAX-RS with Kotlin MessageBodyWriter not found

I've implemented a JAX-RS resource (a) with Kotlin and (b) with Java. While the Java flavor works as expected, the Kotlin flavor fails with a
MessageBodyWriter not found for media type=application/json, type=class java.util.ArrayList, genericType=java.util.List<? extends ....Entry>.|#] exception.
This is my resource
#Path("demokotlin")
class DemoKotlinResource {
#GET
#Path("responseGenericEntityWithArrayList")
fun arrayList(): Response {
val list = arrayListOf(Entry("responseGenericEntityWithArrayList"))
val entity = object : GenericEntity<List<Entry>>(list) {}
return Response
.status(Response.Status.OK)
.entity(entity)
.type(MediaType.APPLICATION_JSON).build()
}
}
#XmlRootElement
#XmlAccessorType(XmlAccessType.FIELD)
open class Entry(val fieldName: String)
The integration test is essentially
private val client = ClientBuilder.newClient()
private val target = client.target("http://localhost:8080/xyz/resources/demokotlin")
#Test
fun responseGenericEntityWithArrayList() {
val response = target.path("responseGenericEntityWithArrayList").request(MediaType.APPLICATION_JSON).get()
assertThat("no ok status", response.status, equalTo(200))
val entity = response.readEntity(JsonArray::class.java)
assertThat(entity.getJsonObject(0).getString("fieldName"), equalTo("responseGenericEntityWithArrayList"))
assertThat(entity.toString(), equalTo("[{\"fieldName\":\"responseGenericEntityWithArrayList\"}]"))
}
The equivalent code in Java works fine while the shown code in Kotlin throws MessageBodyWriter not found for media type=application/json, type=class java.util.ArrayList, genericType=java.util.List<? extends ....Entry>.|#].
I am using Payara 4.1.2.172. Digging through some JAX-RS classes I found that the Java Code leads to
genericType=java.util.List<....Entry>
(without the ? extends) while the generic type info with Kotlin is
genericType=java.util.List<? extends ....Entry>
could that be the cause? If so, how can I fix this?
edit 2017-07-25 Here is the stack trace
#|2017-07-25T12:33:16.932+0000|INFO|Payara 4.1||_ThreadID=32;_ThreadName=http-thread-pool::http-listener-1(1);_TimeMillis=1500985996932;_LevelValue=800;|
javax.ws.rs.InternalServerErrorException: HTTP 500 Internal Server Error
at org.glassfish.jersey.server.internal.MappableExceptionWrapperInterceptor.aroundWriteTo(MappableExceptionWrapperInterceptor.java:90)
at org.glassfish.jersey.message.internal.WriterInterceptorExecutor.proceed(WriterInterceptorExecutor.java:162)
at org.glassfish.jersey.message.internal.MessageBodyFactory.writeTo(MessageBodyFactory.java:1130)
at org.glassfish.jersey.server.ServerRuntime$Responder.writeResponse(ServerRuntime.java:711)
at org.glassfish.jersey.server.ServerRuntime$Responder.processResponse(ServerRuntime.java:444)
at org.glassfish.jersey.server.ServerRuntime$Responder.process(ServerRuntime.java:434)
at org.glassfish.jersey.server.ServerRuntime$2.run(ServerRuntime.java:329)
at org.glassfish.jersey.internal.Errors$1.call(Errors.java:271)
at org.glassfish.jersey.internal.Errors$1.call(Errors.java:267)
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:267)
at org.glassfish.jersey.process.internal.RequestScope.runInScope(RequestScope.java:317)
at org.glassfish.jersey.server.ServerRuntime.process(ServerRuntime.java:305)
at org.glassfish.jersey.server.ApplicationHandler.handle(ApplicationHandler.java:1154)
at org.glassfish.jersey.servlet.WebComponent.serviceImpl(WebComponent.java:473)
at org.glassfish.jersey.servlet.WebComponent.service(WebComponent.java:427)
at org.glassfish.jersey.servlet.ServletContainer.service(ServletContainer.java:388)
at org.glassfish.jersey.servlet.ServletContainer.service(ServletContainer.java:341)
at org.glassfish.jersey.servlet.ServletContainer.service(ServletContainer.java:228)
at org.apache.catalina.core.StandardWrapper.service(StandardWrapper.java:1606)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:338)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:208)
at org.glassfish.tyrus.servlet.TyrusServletFilter.doFilter(TyrusServletFilter.java:305)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:250)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:208)
at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:256)
at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:160)
at org.apache.catalina.core.StandardPipeline.doInvoke(StandardPipeline.java:654)
at org.apache.catalina.core.StandardPipeline.invoke(StandardPipeline.java:593)
at com.sun.enterprise.web.WebPipeline.invoke(WebPipeline.java:99)
at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:155)
at org.apache.catalina.connector.CoyoteAdapter.doService(CoyoteAdapter.java:371)
at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:238)
at com.sun.enterprise.v3.services.impl.ContainerMapper$HttpHandlerCallable.call(ContainerMapper.java:466)
at com.sun.enterprise.v3.services.impl.ContainerMapper.service(ContainerMapper.java:169)
at org.glassfish.grizzly.http.server.HttpHandler.runService(HttpHandler.java:206)
at org.glassfish.grizzly.http.server.HttpHandler.doHandle(HttpHandler.java:180)
at org.glassfish.grizzly.http.server.HttpServerFilter.handleRead(HttpServerFilter.java:235)
at org.glassfish.grizzly.filterchain.ExecutorResolver$9.execute(ExecutorResolver.java:119)
at org.glassfish.grizzly.filterchain.DefaultFilterChain.executeFilter(DefaultFilterChain.java:284)
at org.glassfish.grizzly.filterchain.DefaultFilterChain.executeChainPart(DefaultFilterChain.java:201)
at org.glassfish.grizzly.filterchain.DefaultFilterChain.execute(DefaultFilterChain.java:133)
at org.glassfish.grizzly.filterchain.DefaultFilterChain.process(DefaultFilterChain.java:112)
at org.glassfish.grizzly.ProcessorExecutor.execute(ProcessorExecutor.java:77)
at org.glassfish.grizzly.nio.transport.TCPNIOTransport.fireIOEvent(TCPNIOTransport.java:539)
at org.glassfish.grizzly.strategies.AbstractIOStrategy.fireIOEvent(AbstractIOStrategy.java:112)
at org.glassfish.grizzly.strategies.WorkerThreadIOStrategy.run0(WorkerThreadIOStrategy.java:117)
at org.glassfish.grizzly.strategies.WorkerThreadIOStrategy.access$100(WorkerThreadIOStrategy.java:56)
at org.glassfish.grizzly.strategies.WorkerThreadIOStrategy$WorkerThreadRunnable.run(WorkerThreadIOStrategy.java:137)
at org.glassfish.grizzly.threadpool.AbstractThreadPool$Worker.doWork(AbstractThreadPool.java:593)
at org.glassfish.grizzly.threadpool.AbstractThreadPool$Worker.run(AbstractThreadPool.java:573)
at java.lang.Thread.run(Thread.java:748)
Caused by: org.glassfish.jersey.message.internal.MessageBodyProviderNotFoundException: MessageBodyWriter not found for media type=application/json, type=class java.util.ArrayList, genericType=java.util.List<? extends com.github.reproducer.boundary.Entry>.
at org.glassfish.jersey.message.internal.WriterInterceptorExecutor$TerminalWriterInterceptor.aroundWriteTo(WriterInterceptorExecutor.java:247)
at org.glassfish.jersey.message.internal.WriterInterceptorExecutor.proceed(WriterInterceptorExecutor.java:162)
at org.glassfish.jersey.server.internal.JsonWithPaddingInterceptor.aroundWriteTo(JsonWithPaddingInterceptor.java:106)
at org.glassfish.jersey.message.internal.WriterInterceptorExecutor.proceed(WriterInterceptorExecutor.java:162)
at org.glassfish.jersey.server.internal.MappableExceptionWrapperInterceptor.aroundWriteTo(MappableExceptionWrapperInterceptor.java:86)
... 52 more
|#]
edit #2: working Java Code - should be quite similar to Kotlin variant
#Path("demojava")
public class DemoJavaResource {
#GET
#Path("responseGenericEntityWithArrayList")
public Response arrayList() {
final List<JEntry> list = new ArrayList<>();
list.add(new JEntry("responseGenericEntityWithArrayList"));
final GenericEntity<List<JEntry>> entity = new GenericEntity<List<JEntry>>(list) {};
return Response
.status(Response.Status.OK)
.entity(entity)
.type(MediaType.APPLICATION_JSON).build();
}
}
and JEntry
#XmlRootElement
#XmlAccessorType(XmlAccessType.FIELD)
class JEntry {
private String fieldName;
JEntry() { this(""); }
JEntry(final String responseGenericEntityWithArrayList) {
fieldName = responseGenericEntityWithArrayList;
}
public String getFieldName() { return fieldName; }
}
Because JAX-RS cannot encode ArrayList to JSON Array.
MessageBodyWriter is a handler to convert Java data type to output format, e.g. XML, JSON. JAX-RS has built-in MessageBodyWriter for major data type (include JAXB), however those does not include for ArrayList. Thus you need to create a custom MessageBodyWriter to accept ArrayList and encode to JSON.
But in this case, any custom MessageBodyWriter is not need. Instead of, you need to re-create Entry class. I'm sorry that I can't write Kotlin sample, but if it write using Java, it's following;
#Path("demokotlin")
public class DemoKotlinResource {
#GET
#Path("responseGenericEntityWithArrayList")
public Response arrayList() {
Entry entity = new Entry();
entity.fieldName.add("responseGenericEntityWithArrayList");
return Response
.status(Response.Status.OK)
.entity(entity)
.type(MediaType.APPLICATION_JSON).build();
}
}
#XmlRootElement
#XmlAccessorType(XmlAccessType.FIELD)
public class Entry {
public List<String> fieldName = new ArrayList<>();
}
And it translate to Kotlin, then it's maybe completed.

How to use OAuth2RestTemplate + Spring 4?

I'm trying to understand how to use a OAuth2RestTemplate object to consume my OAuth2 secured REST service (which is running under a different project and let's assume also on a different server etc...)
f.e. my rest service is:
https://localhost:8443/rest/api/user
-> Accessing this URL generates an error as I am not authenticated
To request a token I would go to:
https://localhost:8443/rest/oauth/token?grant_type=password&client_id=test&client_secret=test&username=USERNAME&password=PASSWORD
After I receive the token I can then connect to the REST API by using the following URL (example token inserted)
https://localhost:8443/rest/api/user?access_token=06
I currently tried something with the following objects:
#EnableOAuth2Client
#Configuration
class MyConfig {
#Value("${oauth.resource:https://localhost:8443}")
private String baseUrl;
#Value("${oauth.authorize:https://localhost:8443/rest/oauth/authorize}")
private String authorizeUrl;
#Value("${oauth.token:https://localhost:8443/rest/oauth/token}")
private String tokenUrl;
#Bean
protected OAuth2ProtectedResourceDetails resource() {
ResourceOwnerPasswordResourceDetails resource = new ResourceOwnerPasswordResourceDetails();
List scopes = new ArrayList<String>(2);
scopes.add("write");
scopes.add("read");
resource.setAccessTokenUri(tokenUrl);
resource.setClientId("test");
resource.setClientSecret("test");
resource.setGrantType("password");
resource.setScope(scopes);
resource.setUsername("test");
resource.setPassword("test");
return resource;
}
#Bean
public OAuth2RestOperations restTemplate() {
CloseableHttpClient httpClient = HttpClients.custom().setSSLHostnameVerifier(new NoopHostnameVerifier())
.build();
HttpComponentsClientHttpRequestFactory requestFactory = new HttpComponentsClientHttpRequestFactory();
requestFactory.setHttpClient(httpClient);
AccessTokenRequest atr = new DefaultAccessTokenRequest();
OAuth2RestTemplate restTemplate = new OAuth2RestTemplate(resource(), new DefaultOAuth2ClientContext(atr));
AuthorizationCodeAccessTokenProvider provider = new AuthorizationCodeAccessTokenProvider();
provider.setRequestFactory(requestFactory);
restTemplate.setAccessTokenProvider(provider);
return restTemplate;
}
}
I am tried to get token in controller like below.
#Controller
public class TestController {
#Autowired
private OAuth2RestOperations restTemplate;
#RequestMapping(value="/", method= RequestMethod.GET)
public String TestForm() {
System.out.println("Token : " + restTemplate.getAccessToken().getValue());
}
}
But i got below exception
SEVERE: Servlet.service() for servlet [appServlet] in context with path [/web] threw exception [Request processing failed; nested exception is java.lang.ClassCastException: org.springframework.security.oauth2.client.token.grant.password.ResourceOwnerPasswordResourceDetails cannot be cast to org.springframework.security.oauth2.client.token.grant.code.AuthorizationCodeResourceDetails] with root cause
java.lang.ClassCastException: org.springframework.security.oauth2.client.token.grant.password.ResourceOwnerPasswordResourceDetails cannot be cast to org.springframework.security.oauth2.client.token.grant.code.AuthorizationCodeResourceDetails
at org.springframework.security.oauth2.client.token.grant.code.AuthorizationCodeAccessTokenProvider.obtainAccessToken(AuthorizationCodeAccessTokenProvider.java:190)
at org.springframework.security.oauth2.client.OAuth2RestTemplate.acquireAccessToken(OAuth2RestTemplate.java:221)
at org.springframework.security.oauth2.client.OAuth2RestTemplate.getAccessToken(OAuth2RestTemplate.java:173)
at com.divyshivglobalinvestor.web.controller.PersonalLoanController.PersonalLoanForm(PersonalLoanController.java:37)
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.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:624)
at org.springframework.web.servlet.FrameworkServlet.service(FrameworkServlet.java:846)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:731)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:303)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:208)
at org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:52)
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:218)
at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:122)
at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:505)
at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:169)
at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:103)
at org.apache.catalina.valves.AccessLogValve.invoke(AccessLogValve.java:956)
at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:116)
at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:442)
at org.apache.coyote.http11.AbstractHttp11Processor.process(AbstractHttp11Processor.java:1082)
at org.apache.coyote.AreadPoolExecutor$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)bstractProtocol$AbstractConnectionHandler.process(AbstractProtocol.java:623)
at org.apache.tomcat.util.net.JIoEndpoint$SocketProcessor.run(JIoEndpoint.java:316)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1110)
at java.util.concurrent.Th
From some blog I found that, if we need to grant password then, instead of ResourceOwnerPasswordResourceDetails, it should be used AccessTokenRequest (which is a Map and is ephemeral). It would be great if someone can help me in getting accessToken. :)
Thanks in advance !
You should use ResourceOwnerPasswordAccessTokenProvider instead of AuthorizationCodeAccessTokenProvider in restTemplate bean

Spring Rest MultiModule Project has ClassCastException in requestMappingHandlerMapping()

I am facing following issue. I have a multi module project for which I now want to design a Rest-Module for using Spring-Hateoas.
The underlaying modules works as expected. The modules are organized like follows:
app
rest
business
backend
All modules are build by spring-boot in current version 1.1.9.RELEASE.
When I start the Integration-Test as well runable Application class I get the stacktrace you find below. That stacktrace just come when I integrate the business module in application class of rest module.
====
TESTCLASS
#RunWith(SpringJUnit4ClassRunner.class)
#SpringApplicationConfiguration(classes = ApplicationRest.class)
#WebAppConfiguration
#ActiveProfiles("localhost")
public class ApplicationRestTest {
#Test
public void contextLoads() {
}
}
===
CONFIGURATION CLASS OF REST MODULE =>
RUNNING THAT CLASS ONLY WORKS WHEN COMMENTING #IMPORT!!!
#Configuration
#ComponentScan
#EnableAutoConfiguration
#Import(ApplicationBusiness.class) // WORKS WHEN COMMENTING THAT LINE!!!
#PropertySource({ "classpath:/config/application-localhost.properties" })
public class ApplicationRest {
public static void main(final String[] args) {
SpringApplication.run(ApplicationRest.class, args);
}
}
===
CONFIGURATION OF BUSINESS MODULE =>
RUNNING THAT CLASS WORKS!!!
#Configuration
#ComponentScan
#Import(Application.class)
#PropertySource({ "classpath:/config/application-localhost.properties" })
public class ApplicationBusiness {
public static void main(final String[] args) {
SpringApplication.run(ApplicationBusiness.class, args);
}
}
===
CONFIGURATION OF BACKEND MODULE =>
RUNNING THAT CLASS WORKS
#Configuration
#ComponentScan
#EnableAutoConfiguration
#EnableJpaRepositories
#ImportResource("classpath*:META-INF/spring/applicationContext-*.xml")
public class Application {
public static void main(final String[] args) {
final ConfigurableApplicationContext context = SpringApplication.run(Application.class, args);
final ContractService service = context.getBean(ContractService.class);
service.countAllContracts();
context.close();
}
}
====
STACKTRACE
CONSOLE OUTPUT OF MODULES BACKEND AND BUSINESS ARE OKAY
....
CONSOLE OUTPUT REST MODULE STARTS HERE ...
2014-11-15 13:39:21.125 INFO 7988 --- [ main] o.s.w.s.handler.SimpleUrlHandlerMapping : Mapped URL path [/**/favicon.ico] onto handler of type [class org.springframework.web.servlet.resource.ResourceHttpRequestHandler]
2014-11-15 13:39:21.346 WARN 7988 --- [ main] o.s.w.c.s.GenericWebApplicationContext : Exception encountered during context initialization - cancelling refresh attempt
2014-11-15 13:20:13.722 ERROR 3472 --- [ main] o.s.test.context.TestContextManager : Caught exception while allowing TestExecutionListener [org.springframework.test.context.web.ServletTestExecutionListener#29ae2517] to prepare test instance [at.compax.bbsng.app.rest.ApplicationRestTest#7a78d2aa]
java.lang.IllegalStateException: Failed to load ApplicationContext
at org.springframework.test.context.CacheAwareContextLoaderDelegate.loadContext(CacheAwareContextLoaderDelegate.java:103)
at org.springframework.test.context.DefaultTestContext.getApplicationContext(DefaultTestContext.java:98)
at org.springframework.test.context.web.ServletTestExecutionListener.setUpRequestContextIfNecessary(ServletTestExecutionListener.java:161)
at org.springframework.test.context.web.ServletTestExecutionListener.prepareTestInstance(ServletTestExecutionListener.java:101)
at org.springframework.test.context.TestContextManager.prepareTestInstance(TestContextManager.java:331)
at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.createTest(SpringJUnit4ClassRunner.java:213)
at org.springframework.test.context.junit4.SpringJUnit4ClassRunner$1.runReflectiveCall(SpringJUnit4ClassRunner.java:290)
at org.junit.internal.runners.model.ReflectiveCallable.run(ReflectiveCallable.java:12)
at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.methodBlock(SpringJUnit4ClassRunner.java:292)
at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.runChild(SpringJUnit4ClassRunner.java:233)
at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.runChild(SpringJUnit4ClassRunner.java:87)
at org.junit.runners.ParentRunner$3.run(ParentRunner.java:238)
at org.junit.runners.ParentRunner$1.schedule(ParentRunner.java:63)
at org.junit.runners.ParentRunner.runChildren(ParentRunner.java:236)
at org.junit.runners.ParentRunner.access$000(ParentRunner.java:53)
at org.junit.runners.ParentRunner$2.evaluate(ParentRunner.java:229)
at org.springframework.test.context.junit4.statements.RunBeforeTestClassCallbacks.evaluate(RunBeforeTestClassCallbacks.java:61)
at org.springframework.test.context.junit4.statements.RunAfterTestClassCallbacks.evaluate(RunAfterTestClassCallbacks.java:71)
at org.junit.runners.ParentRunner.run(ParentRunner.java:309)
at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.run(SpringJUnit4ClassRunner.java:176)
at org.eclipse.jdt.internal.junit4.runner.JUnit4TestReference.run(JUnit4TestReference.java:50)
at org.eclipse.jdt.internal.junit.runner.TestExecution.run(TestExecution.java:38)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:459)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:675)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.run(RemoteTestRunner.java:382)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.main(RemoteTestRunner.java:192)
Caused by: org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'requestMappingHandlerMapping' defined in class path resource [org/springframework/web/servlet/config/annotation/DelegatingWebMvcConfiguration.class]: Instantiation of bean failed; nested exception is org.springframework.beans.factory.BeanDefinitionStoreException: Factory method [public org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerMapping org.springframework.web.servlet.config.annotation.WebMvcConfigurationSupport.requestMappingHandlerMapping()] threw exception; nested exception is java.lang.ClassCastException: com.sun.proxy.$Proxy130 cannot be cast to org.springframework.format.support.FormattingConversionService
at org.springframework.beans.factory.support.ConstructorResolver.instantiateUsingFactoryMethod(ConstructorResolver.java:597)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.instantiateUsingFactoryMethod(AbstractAutowireCapableBeanFactory.java:1095)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBeanInstance(AbstractAutowireCapableBeanFactory.java:990)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:504)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:475)
at org.springframework.beans.factory.support.AbstractBeanFactory$1.getObject(AbstractBeanFactory.java:302)
at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:228)
at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:298)
at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:193)
at org.springframework.beans.factory.support.DefaultListableBeanFactory.preInstantiateSingletons(DefaultListableBeanFactory.java:706)
at org.springframework.context.support.AbstractApplicationContext.finishBeanFactoryInitialization(AbstractApplicationContext.java:762)
at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:482)
at org.springframework.boot.SpringApplication.refresh(SpringApplication.java:691)
at org.springframework.boot.SpringApplication.run(SpringApplication.java:320)
at org.springframework.boot.test.SpringApplicationContextLoader.loadContext(SpringApplicationContextLoader.java:107)
at org.springframework.test.context.CacheAwareContextLoaderDelegate.loadContextInternal(CacheAwareContextLoaderDelegate.java:69)
at org.springframework.test.context.CacheAwareContextLoaderDelegate.loadContext(CacheAwareContextLoaderDelegate.java:95)
... 25 common frames omitted
Caused by: org.springframework.beans.factory.BeanDefinitionStoreException: Factory method [public org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerMapping org.springframework.web.servlet.config.annotation.WebMvcConfigurationSupport.requestMappingHandlerMapping()] threw exception; nested exception is java.lang.ClassCastException: com.sun.proxy.$Proxy130 cannot be cast to org.springframework.format.support.FormattingConversionService
at org.springframework.beans.factory.support.SimpleInstantiationStrategy.instantiate(SimpleInstantiationStrategy.java:188)
at org.springframework.beans.factory.support.ConstructorResolver.instantiateUsingFactoryMethod(ConstructorResolver.java:586)
... 41 common frames omitted
Caused by: java.lang.ClassCastException: com.sun.proxy.$Proxy130 cannot be cast to org.springframework.format.support.FormattingConversionService
at org.springframework.web.servlet.config.annotation.DelegatingWebMvcConfiguration$$EnhancerBySpringCGLIB$$9d0e5a2e.mvcConversionService(<generated>)
at org.springframework.web.servlet.config.annotation.WebMvcConfigurationSupport.getInterceptors(WebMvcConfigurationSupport.java:230)
at org.springframework.web.servlet.config.annotation.WebMvcConfigurationSupport.requestMappingHandlerMapping(WebMvcConfigurationSupport.java:197)
at org.springframework.web.servlet.config.annotation.DelegatingWebMvcConfiguration$$EnhancerBySpringCGLIB$$9d0e5a2e.CGLIB$requestMappingHandlerMapping$17(<generated>)
at org.springframework.web.servlet.config.annotation.DelegatingWebMvcConfiguration$$EnhancerBySpringCGLIB$$9d0e5a2e$$FastClassBySpringCGLIB$$c90faea7.invoke(<generated>)
at org.springframework.cglib.proxy.MethodProxy.invokeSuper(MethodProxy.java:228)
at org.springframework.context.annotation.ConfigurationClassEnhancer$BeanMethodInterceptor.intercept(ConfigurationClassEnhancer.java:312)
at org.springframework.web.servlet.config.annotation.DelegatingWebMvcConfiguration$$EnhancerBySpringCGLIB$$9d0e5a2e.requestMappingHandlerMapping(<generated>)
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:483)
at org.springframework.beans.factory.support.SimpleInstantiationStrategy.instantiate(SimpleInstantiationStrategy.java:166)
... 42 common frames omitted
============
That Issues happens when I add the following dependency to the classpath:
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
When removing it, then it does not complain.
===============
Starting in Debug-Mode prints out following classpath dependencies, maybe that helps:
2014-11-15 16:18:48.758 INFO 8896 --- [ main] .b.l.ClasspathLoggingApplicationListener : Application failed to start with classpath: [file:/C:/Development/Projekte/bbsng/trunk/app/rest/target/classes/, file:/C:/Development/Projekte/bbsng/trunk/app/business/target/classes/, file:/C:/Development/Projekte/bbsng/trunk/app/backend/target/classes/, file:/C:/Users/hegnerM/.m2/repository/org/springframework/boot/spring-boot-starter-data-jpa/1.1.9.RELEASE/spring-boot-starter-data-jpa-1.1.9.RELEASE.jar, file:/C:/Users/hegnerM/.m2/repository/org/springframework/boot/spring-boot-starter-aop/1.1.9.RELEASE/spring-boot-starter-aop-1.1.9.RELEASE.jar, file:/C:/Users/hegnerM/.m2/repository/org/aspectj/aspectjrt/1.8.4/aspectjrt-1.8.4.jar, file:/C:/Users/hegnerM/.m2/repository/org/aspectj/aspectjweaver/1.8.4/aspectjweaver-1.8.4.jar, file:/C:/Users/hegnerM/.m2/repository/org/springframework/boot/spring-boot-starter-jdbc/1.1.9.RELEASE/spring-boot-starter-jdbc-1.1.9.RELEASE.jar, file:/C:/Users/hegnerM/.m2/repository/org/springframework/spring-jdbc/4.0.8.RELEASE/spring-jdbc-4.0.8.RELEASE.jar, file:/C:/Users/hegnerM/.m2/repository/org/apache/tomcat/tomcat-jdbc/7.0.56/tomcat-jdbc-7.0.56.jar, file:/C:/Users/hegnerM/.m2/repository/org/apache/tomcat/tomcat-juli/7.0.56/tomcat-juli-7.0.56.jar, file:/C:/Users/hegnerM/.m2/repository/org/springframework/spring-tx/4.0.8.RELEASE/spring-tx-4.0.8.RELEASE.jar, file:/C:/Users/hegnerM/.m2/repository/org/springframework/spring-orm/4.0.8.RELEASE/spring-orm-4.0.8.RELEASE.jar, file:/C:/Users/hegnerM/.m2/repository/org/springframework/data/spring-data-jpa/1.6.4.RELEASE/spring-data-jpa-1.6.4.RELEASE.jar, file:/C:/Users/hegnerM/.m2/repository/org/springframework/data/spring-data-commons/1.8.4.RELEASE/spring-data-commons-1.8.4.RELEASE.jar, file:/C:/Users/hegnerM/.m2/repository/org/springframework/spring-aspects/4.0.8.RELEASE/spring-aspects-4.0.8.RELEASE.jar, file:/C:/Users/hegnerM/.m2/repository/javax/validation/validation-api/1.1.0.Final/validation-api-1.1.0.Final.jar, file:/C:/Users/hegnerM/.m2/repository/org/postgresql/postgresql/9.3-1102-jdbc41/postgresql-9.3-1102-jdbc41.jar, file:/C:/Users/hegnerM/.m2/repository/org/hsqldb/hsqldb/2.3.2/hsqldb-2.3.2.jar, file:/C:/Users/hegnerM/.m2/repository/commons-collections/commons-collections/3.2.1/commons-collections-3.2.1.jar, file:/C:/Users/hegnerM/.m2/repository/commons-dbcp/commons-dbcp/1.4/commons-dbcp-1.4.jar, file:/C:/Users/hegnerM/.m2/repository/commons-pool/commons-pool/1.6/commons-pool-1.6.jar, file:/C:/Development/Projekte/bbsng/trunk/app/domain/target/classes/, file:/C:/Users/hegnerM/.m2/repository/org/hibernate/hibernate-entitymanager/4.3.6.Final/hibernate-entitymanager-4.3.6.Final.jar, file:/C:/Users/hegnerM/.m2/repository/org/jboss/logging/jboss-logging-annotations/1.2.0.Beta1/jboss-logging-annotations-1.2.0.Beta1.jar, file:/C:/Users/hegnerM/.m2/repository/org/hibernate/hibernate-core/4.3.6.Final/hibernate-core-4.3.6.Final.jar, file:/C:/Users/hegnerM/.m2/repository/antlr/antlr/2.7.7/antlr-2.7.7.jar, file:/C:/Users/hegnerM/.m2/repository/org/jboss/jandex/1.1.0.Final/jandex-1.1.0.Final.jar, file:/C:/Users/hegnerM/.m2/repository/dom4j/dom4j/1.6.1/dom4j-1.6.1.jar, file:/C:/Users/hegnerM/.m2/repository/xml-apis/xml-apis/1.0.b2/xml-apis-1.0.b2.jar, file:/C:/Users/hegnerM/.m2/repository/org/hibernate/common/hibernate-commons-annotations/4.0.5.Final/hibernate-commons-annotations-4.0.5.Final.jar, file:/C:/Users/hegnerM/.m2/repository/org/hibernate/javax/persistence/hibernate-jpa-2.1-api/1.0.0.Final/hibernate-jpa-2.1-api-1.0.0.Final.jar, file:/C:/Users/hegnerM/.m2/repository/org/jboss/spec/javax/transaction/jboss-transaction-api_1.2_spec/1.0.0.Final/jboss-transaction-api_1.2_spec-1.0.0.Final.jar, file:/C:/Users/hegnerM/.m2/repository/org/javassist/javassist/3.18.1-GA/javassist-3.18.1-GA.jar, file:/C:/Users/hegnerM/.m2/repository/com/mysema/querydsl/querydsl-jpa/3.4.3/querydsl-jpa-3.4.3.jar, file:/C:/Users/hegnerM/.m2/repository/com/mysema/querydsl/querydsl-core/3.4.3/querydsl-core-3.4.3.jar, file:/C:/Users/hegnerM/.m2/repository/com/google/guava/guava/14.0/guava-14.0.jar, file:/C:/Users/hegnerM/.m2/repository/com/google/code/findbugs/jsr305/1.3.9/jsr305-1.3.9.jar, file:/C:/Users/hegnerM/.m2/repository/com/mysema/commons/mysema-commons-lang/0.2.4/mysema-commons-lang-0.2.4.jar, file:/C:/Users/hegnerM/.m2/repository/com/infradna/tool/bridge-method-annotation/1.13/bridge-method-annotation-1.13.jar, file:/C:/Development/Projekte/bbsng/trunk/app/log/target/classes/, file:/C:/Users/hegnerM/.m2/repository/org/aspectj/aspectjtools/1.8.4/aspectjtools-1.8.4.jar, file:/C:/Users/hegnerM/.m2/repository/org/springframework/boot/spring-boot-starter/1.1.9.RELEASE/spring-boot-starter-1.1.9.RELEASE.jar, file:/C:/Users/hegnerM/.m2/repository/org/springframework/boot/spring-boot/1.1.9.RELEASE/spring-boot-1.1.9.RELEASE.jar, file:/C:/Users/hegnerM/.m2/repository/org/springframework/boot/spring-boot-autoconfigure/1.1.9.RELEASE/spring-boot-autoconfigure-1.1.9.RELEASE.jar, file:/C:/Users/hegnerM/.m2/repository/org/springframework/boot/spring-boot-starter-logging/1.1.9.RELEASE/spring-boot-starter-logging-1.1.9.RELEASE.jar, file:/C:/Users/hegnerM/.m2/repository/org/slf4j/jcl-over-slf4j/1.7.7/jcl-over-slf4j-1.7.7.jar, file:/C:/Users/hegnerM/.m2/repository/org/slf4j/jul-to-slf4j/1.7.7/jul-to-slf4j-1.7.7.jar, file:/C:/Users/hegnerM/.m2/repository/org/slf4j/log4j-over-slf4j/1.7.7/log4j-over-slf4j-1.7.7.jar, file:/C:/Users/hegnerM/.m2/repository/ch/qos/logback/logback-classic/1.1.2/logback-classic-1.1.2.jar, file:/C:/Users/hegnerM/.m2/repository/ch/qos/logback/logback-core/1.1.2/logback-core-1.1.2.jar, file:/C:/Users/hegnerM/.m2/repository/org/yaml/snakeyaml/1.13/snakeyaml-1.13.jar, file:/C:/Users/hegnerM/.m2/repository/org/projectlombok/lombok/1.14.8/lombok-1.14.8.jar, file:/C:/Users/hegnerM/.m2/repository/org/apache/commons/commons-collections4/4.0/commons-collections4-4.0.jar, file:/C:/Users/hegnerM/.m2/repository/org/apache/commons/commons-lang3/3.3.2/commons-lang3-3.3.2.jar, file:/C:/Users/hegnerM/.m2/repository/joda-time/joda-time/2.3/joda-time-2.3.jar, file:/C:/Users/hegnerM/.m2/repository/org/springframework/boot/spring-boot-starter-actuator/1.1.9.RELEASE/spring-boot-starter-actuator-1.1.9.RELEASE.jar, file:/C:/Users/hegnerM/.m2/repository/org/springframework/boot/spring-boot-actuator/1.1.9.RELEASE/spring-boot-actuator-1.1.9.RELEASE.jar, file:/C:/Users/hegnerM/.m2/repository/org/springframework/spring-core/4.0.8.RELEASE/spring-core-4.0.8.RELEASE.jar, file:/C:/Users/hegnerM/.m2/repository/org/springframework/boot/spring-boot-starter-web/1.1.9.RELEASE/spring-boot-starter-web-1.1.9.RELEASE.jar, file:/C:/Users/hegnerM/.m2/repository/org/springframework/boot/spring-boot-starter-tomcat/1.1.9.RELEASE/spring-boot-starter-tomcat-1.1.9.RELEASE.jar, file:/C:/Users/hegnerM/.m2/repository/org/apache/tomcat/embed/tomcat-embed-core/7.0.56/tomcat-embed-core-7.0.56.jar, file:/C:/Users/hegnerM/.m2/repository/org/apache/tomcat/embed/tomcat-embed-el/7.0.56/tomcat-embed-el-7.0.56.jar, file:/C:/Users/hegnerM/.m2/repository/org/apache/tomcat/embed/tomcat-embed-logging-juli/7.0.56/tomcat-embed-logging-juli-7.0.56.jar, file:/C:/Users/hegnerM/.m2/repository/org/apache/tomcat/embed/tomcat-embed-websocket/7.0.56/tomcat-embed-websocket-7.0.56.jar, file:/C:/Users/hegnerM/.m2/repository/org/hibernate/hibernate-validator/5.0.3.Final/hibernate-validator-5.0.3.Final.jar, file:/C:/Users/hegnerM/.m2/repository/org/jboss/logging/jboss-logging/3.1.1.GA/jboss-logging-3.1.1.GA.jar, file:/C:/Users/hegnerM/.m2/repository/com/fasterxml/classmate/1.0.0/classmate-1.0.0.jar, file:/C:/Users/hegnerM/.m2/repository/org/springframework/spring-web/4.0.8.RELEASE/spring-web-4.0.8.RELEASE.jar, file:/C:/Users/hegnerM/.m2/repository/org/springframework/spring-webmvc/4.0.8.RELEASE/spring-webmvc-4.0.8.RELEASE.jar, file:/C:/Users/hegnerM/.m2/repository/org/springframework/spring-expression/4.0.8.RELEASE/spring-expression-4.0.8.RELEASE.jar, file:/C:/Users/hegnerM/.m2/repository/org/springframework/hateoas/spring-hateoas/0.16.0.RELEASE/spring-hateoas-0.16.0.RELEASE.jar, file:/C:/Users/hegnerM/.m2/repository/org/springframework/spring-aop/4.0.8.RELEASE/spring-aop-4.0.8.RELEASE.jar, file:/C:/Users/hegnerM/.m2/repository/aopalliance/aopalliance/1.0/aopalliance-1.0.jar, file:/C:/Users/hegnerM/.m2/repository/org/springframework/spring-beans/4.0.8.RELEASE/spring-beans-4.0.8.RELEASE.jar, file:/C:/Users/hegnerM/.m2/repository/org/springframework/spring-context/4.0.8.RELEASE/spring-context-4.0.8.RELEASE.jar, file:/C:/Users/hegnerM/.m2/repository/org/objenesis/objenesis/2.1/objenesis-2.1.jar, file:/C:/Users/hegnerM/.m2/repository/org/slf4j/slf4j-api/1.7.7/slf4j-api-1.7.7.jar, file:/C:/Users/hegnerM/.m2/repository/org/springframework/plugin/spring-plugin-core/1.1.0.RELEASE/spring-plugin-core-1.1.0.RELEASE.jar, file:/C:/Users/hegnerM/.m2/repository/com/fasterxml/jackson/core/jackson-databind/2.3.4/jackson-databind-2.3.4.jar, file:/C:/Users/hegnerM/.m2/repository/com/fasterxml/jackson/core/jackson-annotations/2.3.4/jackson-annotations-2.3.4.jar, file:/C:/Users/hegnerM/.m2/repository/com/fasterxml/jackson/core/jackson-core/2.3.4/jackson-core-2.3.4.jar, file:/C:/Users/hegnerM/.m2/repository/com/jayway/jsonpath/json-path/0.9.1/json-path-0.9.1.jar, file:/C:/Users/hegnerM/.m2/repository/net/minidev/json-smart/1.2/json-smart-1.2.jar]
Okay I got the problem, but I really don't know why this is a problem or is it a spring bug.
I am using a module for Business-Method Logging, what I have centralized as aspect. This works with the modules backend and business, it just start that exception behavior when I use spring-mvc with spring-boot.
As you seen above my module backend has annotation #ImportResource("classpath*:META-INF/spring/applicationContext-*.xml"), so that spring can find the xml-config file what includes following (mentioned I use that xml-file for years to log service logger without any problems):
<bean id="serviceLogger" class="at.compax.bbsng.app.log.service.ServiceLogger" />
<aop:aspectj-autoproxy>
<aop:include name="serviceLogger" />
</aop:aspectj-autoproxy>
<!-- Trace all service methods -->
<bean id="debugInterceptor" class="org.springframework.aop.interceptor.DebugInterceptor">
<property name="useDynamicLogger" value="true" />
<property name="hideProxyClassNames" value="true" />
</bean>
<!-- Time-Logger -->
<bean id="performanceMonitorInterceptor"
class="org.springframework.aop.interceptor.PerformanceMonitorInterceptor">
<property name="useDynamicLogger" value="true" />
</bean>
<aop:config>
<aop:pointcut id="daoPointcut" expression="execution(* *..*Repository+.*(..))" />
<aop:advisor advice-ref="debugInterceptor" pointcut-ref="daoPointcut" />
</aop:config>
<aop:config>
<aop:pointcut id="servicePointcut" expression="execution(* *..*Service+.*(..))" />
<aop:advisor advice-ref="performanceMonitorInterceptor"
pointcut-ref="servicePointcut" />
</aop:config>
I don't know why spring-boot-mvc has problem with that and why. Does it have problem with annotation for importing xml-files or does it have problems with aspects. But I guess I will find out and I will report.
If someone knows what is the problem, please don't hesiate to post.
=======
As mentioned spring-web-starter seems to have problem when using aspect. But thats really stupid, it always worked when doing multi-module-project without spring-boot. If nobody knows answer on it, I guess it is a spring bug and I will create jira ticket. Ideas are welcome....
I regenerated serialVersionUID after changed of Class properties, and that is works for me.

'#{customer.all}' Error reading 'all' on type com.corejsf.CustomerBean] with root cause java.lang.NullPointerException

I googled but can't find a solution for this. It is from Core JSF 3rd.
I did:
1) Included JSF Mojarra in Build path.
2) Included MySQL JDBC driver in Build path.
3) Copied MySQL JDBC driver to Tomcat "lib" folder and "ext" JDK folder.
4) I tested JDBC driver with a small Java app and it succeeded.
CustomerBean from corejsf source code:
public class CustomerBean {
#Resource(name="jdbc/corejsf")
private DataSource source;
public ResultSet getAll() throws SQLException {
Connection conn = source.getConnection();
try {
Statement stmt = conn.createStatement();
ResultSet result = stmt.executeQuery("SELECT * FROM Customers");
// return ResultSupport.toResult(result);
CachedRowSet crs = new com.sun.rowset.CachedRowSetImpl();
// or use an implementation from your database vendor
crs.populate(result);
return crs;
} finally {
conn.close();
}
}
}
Error:
SEVERE: Servlet.service() for servlet [Faces Servlet] in context with path [/DatabaseTest] threw exception [/index.jsp(12,3) '#{customer.all}' Error reading 'all' on type com.corejsf.CustomerBean] with root cause
java.lang.NullPointerException
at com.corejsf.CustomerBean.getAll(CustomerBean.java:18)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25)
at java.lang.reflect.Method.invoke(Method.java:597)
at javax.el.BeanELResolver.getValue(BeanELResolver.java:87)
at javax.el.CompositeELResolver.getValue(CompositeELResolver.java:67)
at com.sun.faces.el.FacesCompositeELResolver.getValue(FacesCompositeELResolver.java:72)
at org.apache.el.parser.AstValue.getValue(AstValue.java:169)
at org.apache.el.ValueExpressionImpl.getValue(ValueExpressionImpl.java:189)
at org.apache.jasper.el.JspValueExpression.getValue(JspValueExpression.java:106)
at javax.faces.component.ComponentStateHelper.eval(ComponentStateHelper.java:190)
at javax.faces.component.ComponentStateHelper.eval(ComponentStateHelper.java:178)
at javax.faces.component.UIData.getValue(UIData.java:554)
at javax.faces.component.UIData.getDataModel(UIData.java:1248)
at javax.faces.component.UIData.setRowIndex(UIData.java:447)
at com.sun.faces.renderkit.html_basic.TableRenderer.encodeBegin(TableRenderer.java:81)
at javax.faces.component.UIComponentBase.encodeBegin(UIComponentBase.java:823)
at javax.faces.component.UIData.encodeBegin(UIData.java:937)
at javax.faces.component.UIComponent.encodeAll(UIComponent.java:1611)
at javax.faces.render.Renderer.encodeChildren(Renderer.java:168)
at javax.faces.component.UIComponentBase.encodeChildren(UIComponentBase.java:848)
at javax.faces.component.UIComponent.encodeAll(UIComponent.java:1613)
at javax.faces.component.UIComponent.encodeAll(UIComponent.java:1616)
at com.sun.faces.application.view.JspViewHandlingStrategy.doRenderView(JspViewHandlingStrategy.java:420)
at com.sun.faces.application.view.JspViewHandlingStrategy.renderView(JspViewHandlingStrategy.java:209)
at com.sun.faces.application.view.MultiViewHandler.renderView(MultiViewHandler.java:126)
at com.sun.faces.lifecycle.RenderResponsePhase.execute(RenderResponsePhase.java:127)
at com.sun.faces.lifecycle.Phase.doPhase(Phase.java:101)
at com.sun.faces.lifecycle.LifecycleImpl.render(LifecycleImpl.java:139)
at javax.faces.webapp.FacesServlet.service(FacesServlet.java:313)
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:563)
at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:118)
at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:399)
at org.apache.coyote.http11.Http11Processor.process(Http11Processor.java:317)
at org.apache.coyote.http11.Http11Protocol$Http11ConnectionHandler.process(Http11Protocol.java:204)
at org.apache.coyote.http11.Http11Protocol$Http11ConnectionHandler.process(Http11Protocol.java:182)
at org.apache.tomcat.util.net.JIoEndpoint$SocketProcessor.run(JIoEndpoint.java:311)
at java.util.concurrent.ThreadPoolExecutor$Worker.runTask(ThreadPoolExecutor.java:886)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:908)
at java.lang.Thread.run(Thread.java:662)
You need to configure a JNDI datasource with the name jdbc/corejsf in Tomcat.
I suspect that datasource is not injected, since nothing in your class path interprets the #Resource annotation. As far as I know, #Resource is an EJB annotation, but Tomcat is no EJB container. Try looking up the datasource programatically.