I tried to integrate Spring Cloud Contract Verifier Stub Runner’s messaging module with Spring AMQP. I created SimpleMessageListenerContainer with MessageListener and it works fine.
But I have another approach. I use a AMQP support for Spring Integration with Inbound Channel Adapter to receive a message from a queue.
Is it possible to use Spring Cloud Contract Verifier Stub Runner’s messaging module for AmqpInboundChannelAdapter?
CONTRACT
Contract.make {
description 'insert new message'
label 'test.queue.insert'
input {
triggeredBy('insertMessage()')
}
outputMessage {
sentTo 'test.exchange'
headers {
header('contentType': 'application/json')
header('__TypeId__': 'sk.bulalak.messaging.demospringcloudcontractmessaging.Person')
}
body('''{"firstName": "Janko", "lastName": "Hrasko"}''')
}
}
APPLICATION
#SpringBootApplication
#EnableIntegration
public class DemoSpringCloudContractMessagingApplication {
private Log logger = LogFactory.getLog(getClass());
public static void main(String[] args) {
SpringApplication.run(DemoSpringCloudContractMessagingApplication.class, args);
}
#Bean
public Queue testQueue() {
return QueueBuilder.durable("test.queue").build();
}
#Bean
public Exchange testExchange() {
return ExchangeBuilder
.topicExchange("test.exchange")
.durable(true)
.build();
}
#Bean
public Binding testBinding() {
return BindingBuilder
.bind(testQueue())
.to(testExchange())
.with("#")
.noargs();
}
#Bean
public MessageConverter messageConverter(ObjectMapper objectMapper) {
return new Jackson2JsonMessageConverter(objectMapper);
}
#Bean
public IntegrationFlow amqpInbound(ConnectionFactory connectionFactory, MessageConverter messageConverter) {
return IntegrationFlows.from(Amqp.inboundAdapter(connectionFactory, testQueue()).messageConverter(messageConverter))
.handle(p -> logger.info(p.getPayload()))
.get();
}
}
TEST
#RunWith(SpringRunner.class)
#SpringBootTest
#AutoConfigureStubRunner(ids = "org.example:test-service")
public class DemoSpringCloudContractMessagingApplicationTests {
#Autowired
private StubTrigger stubTrigger;
#Test
public void contextLoads() {
boolean result = stubTrigger.trigger("test.queue.insert");
assertTrue(result);
}
}
EXCEPTION
java.lang.ClassCastException: org.springframework.integration.amqp.inbound.AmqpInboundChannelAdapter$Listener cannot be cast to org.springframework.amqp.core.MessageListener
at org.springframework.cloud.contract.verifier.messaging.amqp.SpringAmqpStubMessages.send(SpringAmqpStubMessages.java:100)
at org.springframework.cloud.contract.verifier.messaging.amqp.SpringAmqpStubMessages.send(SpringAmqpStubMessages.java:89)
at org.springframework.cloud.contract.stubrunner.StubRunnerExecutor.sendMessage(StubRunnerExecutor.java:235)
at org.springframework.cloud.contract.stubrunner.StubRunnerExecutor.triggerForDsls(StubRunnerExecutor.java:192)
at org.springframework.cloud.contract.stubrunner.StubRunnerExecutor.trigger(StubRunnerExecutor.java:178)
at org.springframework.cloud.contract.stubrunner.StubRunner.trigger(StubRunner.java:146)
at org.springframework.cloud.contract.stubrunner.BatchStubRunner.trigger(BatchStubRunner.java:131)
at sk.bulalak.messaging.demospringcloudcontractmessaging.DemoSpringCloudContractMessagingApplicationTests.contextLoads(DemoSpringCloudContractMessagingApplicationTests.java:24)
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:498)
at org.junit.runners.model.FrameworkMethod$1.runReflectiveCall(FrameworkMethod.java:50)
at org.junit.internal.runners.model.ReflectiveCallable.run(ReflectiveCallable.java:12)
at org.junit.runners.model.FrameworkMethod.invokeExplosively(FrameworkMethod.java:47)
at org.junit.internal.runners.statements.InvokeMethod.evaluate(InvokeMethod.java:17)
at org.springframework.test.context.junit4.statements.RunBeforeTestExecutionCallbacks.evaluate(RunBeforeTestExecutionCallbacks.java:73)
at org.springframework.test.context.junit4.statements.RunAfterTestExecutionCallbacks.evaluate(RunAfterTestExecutionCallbacks.java:83)
at org.springframework.test.context.junit4.statements.RunBeforeTestMethodCallbacks.evaluate(RunBeforeTestMethodCallbacks.java:75)
at org.springframework.test.context.junit4.statements.RunAfterTestMethodCallbacks.evaluate(RunAfterTestMethodCallbacks.java:86)
at org.springframework.test.context.junit4.statements.SpringRepeat.evaluate(SpringRepeat.java:84)
at org.junit.runners.ParentRunner.runLeaf(ParentRunner.java:325)
at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.runChild(SpringJUnit4ClassRunner.java:251)
at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.runChild(SpringJUnit4ClassRunner.java:97)
at org.junit.runners.ParentRunner$3.run(ParentRunner.java:290)
at org.junit.runners.ParentRunner$1.schedule(ParentRunner.java:71)
at org.junit.runners.ParentRunner.runChildren(ParentRunner.java:288)
at org.junit.runners.ParentRunner.access$000(ParentRunner.java:58)
at org.junit.runners.ParentRunner$2.evaluate(ParentRunner.java:268)
at org.springframework.test.context.junit4.statements.RunBeforeTestClassCallbacks.evaluate(RunBeforeTestClassCallbacks.java:61)
at org.springframework.test.context.junit4.statements.RunAfterTestClassCallbacks.evaluate(RunAfterTestClassCallbacks.java:70)
at org.junit.runners.ParentRunner.run(ParentRunner.java:363)
at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.run(SpringJUnit4ClassRunner.java:190)
at org.junit.runner.JUnitCore.run(JUnitCore.java:137)
at com.intellij.junit4.JUnit4IdeaTestRunner.startRunnerWithArgs(JUnit4IdeaTestRunner.java:68)
at com.intellij.rt.execution.junit.IdeaTestRunner$Repeater.startRunnerWithArgs(IdeaTestRunner.java:47)
at com.intellij.rt.execution.junit.JUnitStarter.prepareStreamsAndStart(JUnitStarter.java:242)
at com.intellij.rt.execution.junit.JUnitStarter.main(JUnitStarter.java:70)
Disable the AMQP stub runner support stubrunner.amqp.enabled=false and just use the Spring INtegration one.
Custom route:
<beans:beans xmlns="http://www.springframework.org/schema/integration"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:beans="http://www.springframework.org/schema/beans"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/integration
http://www.springframework.org/schema/integration/spring-integration.xsd">
<!-- REQUIRED FOR TESTING -->
<bridge input-channel="output"
output-channel="outputTest"/>
<channel id="outputTest">
<queue/>
</channel>
</beans:beans>
and run the test with that context
#ContextConfiguration(classes = Config, loader = SpringBootContextLoader)
#ImportResource("classpath*:integration-context.xml")
#AutoConfigureStubRunner
class IntegrationStubRunnerSpec extends Specification {
Related
I'm moving a Spring MVC servlet 3.1 application over to Spring Boot 1.3.0 and when I add the #EnableGlobalMethodSecurity annotation to one of my Java configuration classes I get an exception on startup (in full below).
I'm subclassing WebSecurityConfigurerAdapter for my spring security support (which has previously worked fine for me)
#Configuration
#EnableWebSecurity
#EnableGlobalMethodSecurity(prePostEnabled = true)
public class SecurityAuthorisationConfig extends WebSecurityConfigurerAdapter {
#Override
protected void configure(final HttpSecurity http) throws Exception {
http.csrf()...
Even with no other dependencies #Autowired into the class the startup will fail. Startup will succeed if I remove the #EnableGlobalMethodSecurity annotation, but obviously there's no method security. Most other web security SO posts seem to be due to the security config being unable to start before the dispatcher servlet but with no other dependencies in my security config I can't see why this would be happening.
I've tried quite a number of ways to start the application up and changed the #Order of the security config but to no avail.
My current Application entry point looks like this, though I've also tried initialising with the auto-magical dispatcher and I had the same issue:
#Configuration
#EnableAutoConfiguration
#ComponentScan(basePackages = { "com.myapp.config.web", "com.myapp.config.app" })
public class Application extends SpringBootServletInitializer {
private static Class<Application> applicationClass = Application.class;
public static void main(final String[] args) throws Exception {
SpringApplication.run(applicationClass, args);
}
#Autowired
private AuditLogger auditLogger;
#Override
public void onStartup(final ServletContext container) throws ServletException {
final AnnotationConfigWebApplicationContext rootContext = createRootContext(container);
setUpSessionConfig(container);
setUpMdcLoggingFilter(container);
setAllUndefinedRequestsToUtf8(container);
setUpAuditLogging(container);
addSecurityFilter(container);
addUpdateExpiredPasswordFilter(container);
createDispatcher(container, rootContext);
}
private void setUpSessionConfig(final ServletContext container) {
container.getSessionCookieConfig().setHttpOnly(true);
container.setSessionTrackingModes(asSet(SessionTrackingMode.COOKIE));
}
private void setUpMdcLoggingFilter(final ServletContext container) {
final Dynamic mdcFilter = container.addFilter("mdcInsertingFilter",
new DelegatingFilterProxy(mdcInsertingFilter()));
mdcFilter.addMappingForUrlPatterns(null, true, "/*");
}
private void addUpdateExpiredPasswordFilter(final ServletContext container) {
final Dynamic filter = container.addFilter("updateExpiredPasswordFilter",
new DelegatingFilterProxy(updateExpiredPasswordFilter()));
filter.addMappingForUrlPatterns(null, true, "/*");
}
private void setUpAuditLogging(final ServletContext container) {
final Dynamic auditLoggingFilter = container.addFilter("auditLogFilter",
new DelegatingFilterProxy(auditLogFilter()));
auditLoggingFilter.addMappingForUrlPatterns(null, true, "/*");
}
private void addSecurityFilter(final ServletContext container) {
final Dynamic securityFilter =
container.addFilter(AbstractSecurityWebApplicationInitializer.DEFAULT_FILTER_NAME,
DelegatingFilterProxy.class);
securityFilter.addMappingForUrlPatterns(null, true, "/*");
}
private AnnotationConfigWebApplicationContext createRootContext(final ServletContext servletContext) {
final AnnotationConfigWebApplicationContext rootContext = new AnnotationConfigWebApplicationContext();
rootContext.register(AppConfig.class);
rootContext.setServletContext(servletContext);
servletContext.addListener(new ContextLoaderListener(rootContext));
servletContext.setInitParameter("spring.profiles.default", "production");
return rootContext;
}
private void setAllUndefinedRequestsToUtf8(final ServletContext container) {
final FilterRegistration filter = container.addFilter("encodingFilter", OrderedCharacterEncodingFilter.class);
filter.setInitParameter("encoding", "UTF-8");
filter.addMappingForUrlPatterns(null, true, "/*");
}
private void createDispatcher(final ServletContext container,
final AnnotationConfigWebApplicationContext rootContext) {
final DispatcherServlet dispatcherServlet = new DispatcherServlet(rootContext);
final ServletRegistration.Dynamic dispatcher =
container.addServlet("myServlet", dispatcherServlet);
dispatcher.setLoadOnStartup(1);
dispatcher.addMapping("/");
}
#Bean
public AuditLogFilter auditLogFilter() {
final AuditLogFilter auditLogFilter = new AuditLogFilter();
auditLogFilter.setAuditLogger(auditLogger);
auditLogFilter.setIgnoredPaths("/resources,/webjars");
return auditLogFilter;
}
#Bean
public UpdateExpiredPasswordFilter updateExpiredPasswordFilter() {
final UpdateExpiredPasswordFilter filter = new UpdateExpiredPasswordFilter();
filter.setPasswordUpdateFormPath("/user/change_password");
filter.setPasswordUpdatePath("user/change_password");
filter.setLogoutPath("/logout");
filter.setIgnoredPaths("/resources,/webjars");
return filter;
}
#Bean(name = "mdcInsertingFilter")
public MDCInsertingServletFilter mdcInsertingFilter() {
return new MDCInsertingServletFilter();
}
}
While I'm not necessarily expecting to receive a comprehensive solution to this it would be very useful to know where to start looking for the cause of the problem. Is it a bug? Could it be to do with the way I'm creating the application?
Stack Trace:
2015-11-20 17:18:02.337 ERROR 80806 --- [ main] o.s.boot.SpringApplication : Application startup failed
org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'defaultServletHandlerMapping' defined in class path resource [org/springframework/boot/autoconfigure/web/WebMvcAutoConfiguration$EnableWebMvcConfiguration.class]: Bean instantiation via factory method failed; nested exception is org.springframework.beans.BeanInstantiationException: Failed to instantiate [org.springframework.web.servlet.HandlerMapping]: Factory method 'defaultServletHandlerMapping' threw exception; nested exception is java.lang.IllegalArgumentException: A ServletContext is required to configure default servlet handling
at org.springframework.beans.factory.support.ConstructorResolver.instantiateUsingFactoryMethod(ConstructorResolver.java:599) ~[spring-beans-4.2.3.RELEASE.jar:4.2.3.RELEASE]
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.instantiateUsingFactoryMethod(AbstractAutowireCapableBeanFactory.java:1123) ~[spring-beans-4.2.3.RELEASE.jar:4.2.3.RELEASE]
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBeanInstance(AbstractAutowireCapableBeanFactory.java:1018) ~[spring-beans-4.2.3.RELEASE.jar:4.2.3.RELEASE]
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:510) ~[spring-beans-4.2.3.RELEASE.jar:4.2.3.RELEASE]
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:482) ~[spring-beans-4.2.3.RELEASE.jar:4.2.3.RELEASE]
at org.springframework.beans.factory.support.AbstractBeanFactory$1.getObject(AbstractBeanFactory.java:306) ~[spring-beans-4.2.3.RELEASE.jar:4.2.3.RELEASE]
at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:230) ~[spring-beans-4.2.3.RELEASE.jar:4.2.3.RELEASE]
at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:302) ~[spring-beans-4.2.3.RELEASE.jar:4.2.3.RELEASE]
at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:197) ~[spring-beans-4.2.3.RELEASE.jar:4.2.3.RELEASE]
at org.springframework.beans.factory.support.DefaultListableBeanFactory.preInstantiateSingletons(DefaultListableBeanFactory.java:772) ~[spring-beans-4.2.3.RELEASE.jar:4.2.3.RELEASE]
at org.springframework.context.support.AbstractApplicationContext.finishBeanFactoryInitialization(AbstractApplicationContext.java:838) ~[spring-context-4.2.3.RELEASE.jar:4.2.3.RELEASE]
at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:537) ~[spring-context-4.2.3.RELEASE.jar:4.2.3.RELEASE]
at org.springframework.boot.context.embedded.EmbeddedWebApplicationContext.refresh(EmbeddedWebApplicationContext.java:118) ~[spring-boot-1.3.0.RELEASE.jar:1.3.0.RELEASE]
at org.springframework.boot.SpringApplication.refresh(SpringApplication.java:752) [spring-boot-1.3.0.RELEASE.jar:1.3.0.RELEASE]
at org.springframework.boot.SpringApplication.doRun(SpringApplication.java:347) [spring-boot-1.3.0.RELEASE.jar:1.3.0.RELEASE]
at org.springframework.boot.SpringApplication.run(SpringApplication.java:295) [spring-boot-1.3.0.RELEASE.jar:1.3.0.RELEASE]
at org.springframework.boot.SpringApplication.run(SpringApplication.java:1112) [spring-boot-1.3.0.RELEASE.jar:1.3.0.RELEASE]
at org.springframework.boot.SpringApplication.run(SpringApplication.java:1101) [spring-boot-1.3.0.RELEASE.jar:1.3.0.RELEASE]
at com.amberhill.web.Application.main(Application.java:51) [bin/:na]
Caused by: org.springframework.beans.BeanInstantiationException: Failed to instantiate [org.springframework.web.servlet.HandlerMapping]: Factory method 'defaultServletHandlerMapping' threw exception; nested exception is java.lang.IllegalArgumentException: A ServletContext is required to configure default servlet handling
at org.springframework.beans.factory.support.SimpleInstantiationStrategy.instantiate(SimpleInstantiationStrategy.java:189) ~[spring-beans-4.2.3.RELEASE.jar:4.2.3.RELEASE]
at org.springframework.beans.factory.support.ConstructorResolver.instantiateUsingFactoryMethod(ConstructorResolver.java:588) ~[spring-beans-4.2.3.RELEASE.jar:4.2.3.RELEASE]
... 18 common frames omitted
Caused by: java.lang.IllegalArgumentException: A ServletContext is required to configure default servlet handling
at org.springframework.util.Assert.notNull(Assert.java:115) ~[spring-core-4.2.3.RELEASE.jar:4.2.3.RELEASE]
at org.springframework.web.servlet.config.annotation.DefaultServletHandlerConfigurer.(DefaultServletHandlerConfigurer.java:53) ~[spring-webmvc-4.2.3.RELEASE.jar:4.2.3.RELEASE]
at org.springframework.web.servlet.config.annotation.WebMvcConfigurationSupport.defaultServletHandlerMapping(WebMvcConfigurationSupport.java:450) ~[spring-webmvc-4.2.3.RELEASE.jar:4.2.3.RELEASE]
at org.springframework.boot.autoconfigure.web.WebMvcAutoConfiguration$EnableWebMvcConfiguration$$EnhancerBySpringCGLIB$$5204f0e6.CGLIB$defaultServletHandlerMapping$34() ~[spring-boot-autoconfigure-1.3.0.RELEASE.jar:1.3.0.RELEASE]
at org.springframework.boot.autoconfigure.web.WebMvcAutoConfiguration$EnableWebMvcConfiguration$$EnhancerBySpringCGLIB$$5204f0e6$$FastClassBySpringCGLIB$$7ec661f1.invoke() ~[spring-boot-autoconfigure-1.3.0.RELEASE.jar:1.3.0.RELEASE]
at org.springframework.cglib.proxy.MethodProxy.invokeSuper(MethodProxy.java:228) ~[spring-core-4.2.3.RELEASE.jar:4.2.3.RELEASE]
at org.springframework.context.annotation.ConfigurationClassEnhancer$BeanMethodInterceptor.intercept(ConfigurationClassEnhancer.java:318) ~[spring-context-4.2.3.RELEASE.jar:4.2.3.RELEASE]
at org.springframework.boot.autoconfigure.web.WebMvcAutoConfiguration$EnableWebMvcConfiguration$$EnhancerBySpringCGLIB$$5204f0e6.defaultServletHandlerMapping() ~[spring-boot-autoconfigure-1.3.0.RELEASE.jar:1.3.0.RELEASE]
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) ~[na:1.8.0_11]
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62) ~[na:1.8.0_11]
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43) ~[na:1.8.0_11]
at java.lang.reflect.Method.invoke(Method.java:483) ~[na:1.8.0_11]
at org.springframework.beans.factory.support.SimpleInstantiationStrategy.instantiate(SimpleInstantiationStrategy.java:162) ~[spring-beans-4.2.3.RELEASE.jar:4.2.3.RELEASE]
... 19 common frames omitted
I finally managed to get this working by moving the #EnableGlobalMethodSecurity(prePostEnabled = true) annotation from the WebSecurityConfigurerAdapter implementation to it's own config class and extending GlobalMethodSecurityConfiguration to configure an authentication manager.
I have a feeling this is a work-around fix but at least it's fixed.
#Configuration
#EnableGlobalMethodSecurity(prePostEnabled = true)
public class MethodSecurityConfig extends GlobalMethodSecurityConfiguration {
#Override
public void configure(final AuthenticationManagerBuilder auth) throws Exception {
auth.authenticationProvider(authenticationProvider());
}
#Bean
public DaoAuthenticationProvider authenticationProvider() {
final DaoAuthenticationProvider authProvider = new DaoAuthenticationProvider();
authProvider.setPasswordEncoder(new StandardPasswordEncoder());
authProvider.setUserDetailsService(userDetailsService());
return authProvider;
}
#Bean
public MyUserDetailsService userDetailsService() {
return new MyUserDetailsService(...);
}
}
Spring data neo4j 4.0.0 Release
In spring mvc project i am trying to save a node by repository.save() method i am getting error.
#NodeEntity
public class Category
{
#GraphId
public Long id;
public String categoryName;
public Category()
{
}
public Category( Long id, String categoryName )
{
this.id = id;
this.categoryName = categoryName;
}
}
#Configuration
#EnableNeo4jRepositories("org.neo4j.example.northwind.repository")
#EnableTransactionManagement
public class AppContext extends Neo4jConfiguration
{
public static final String NEO4J_HOST = "http://localhost:";
public static final int NEO4J_PORT = 7474;
#Override
public SessionFactory getSessionFactory() {
System.setProperty("username", "neo4j");
System.setProperty("password","12345");
return new SessionFactory("org.neo4j.example.northwind.model");
}
#Bean
#Override
public Neo4jServer neo4jServer() {
return new RemoteServer(NEO4J_HOST + NEO4J_PORT);
}
#Bean
#Override
//#Scope(value = "session", proxyMode = ScopedProxyMode.TARGET_CLASS)
public Session getSession() throws Exception {
return super.getSession();
}
}
Here is the stacktrace
[org.neo4j.ogm.session.Neo4jSession] (default task-5) org.neo4j.example.northwind.model.Category is not an instance of a persistable class
07:25:55,724 INFO [stdout] (default task-5) org.neo4j.example.northwind.model.Category#54c0a7da
07:25:56,064 ERROR [io.undertow.request] (default task-5) UT005023: Exception handling request to /test: org.springframework.web.util.NestedServletException: Request processing failed; nested exception is org.neo4j.ogm.session.result.ResultProcessingException: Failed to execute request:
at org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:973)
at org.springframework.web.servlet.FrameworkServlet.doGet(FrameworkServlet.java:852)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:687)
at org.springframework.web.servlet.FrameworkServlet.service(FrameworkServlet.java:837)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:790)
at io.undertow.servlet.handlers.ServletHandler.handleRequest(ServletHandler.java:86)
at io.undertow.servlet.handlers.security.ServletSecurityRoleHandler.handleRequest(ServletSecurityRoleHandler.java:62)
at io.undertow.servlet.handlers.ServletDispatchingHandler.handleRequest(ServletDispatchingHandler.java:36)
at org.wildfly.extension.undertow.security.SecurityContextAssociationHandler.handleRequest(SecurityContextAssociationHandler.java:78)
at io.undertow.server.handlers.PredicateHandler.handleRequest(PredicateHandler.java:43)
at io.undertow.servlet.handlers.security.SSLInformationAssociationHandler.handleRequest(SSLInformationAssociationHandler.java:131)
at io.undertow.servlet.handlers.security.ServletAuthenticationCallHandler.handleRequest(ServletAuthenticationCallHandler.java:57)
at io.undertow.server.handlers.PredicateHandler.handleRequest(PredicateHandler.java:43)
at io.undertow.security.handlers.AbstractConfidentialityHandler.handleRequest(AbstractConfidentialityHandler.java:46)
at io.undertow.servlet.handlers.security.ServletConfidentialityConstraintHandler.handleRequest(ServletConfidentialityConstraintHandler.java:64)
at io.undertow.security.handlers.AuthenticationMechanismsHandler.handleRequest(AuthenticationMechanismsHandler.java:58)
at io.undertow.servlet.handlers.security.CachedAuthenticatedSessionHandler.handleRequest(CachedAuthenticatedSessionHandler.java:72)
at io.undertow.security.handlers.NotificationReceiverHandler.handleRequest(NotificationReceiverHandler.java:50)
at io.undertow.security.handlers.SecurityInitialHandler.handleRequest(SecurityInitialHandler.java:76)
at io.undertow.server.handlers.PredicateHandler.handleRequest(PredicateHandler.java:43)
at org.wildfly.extension.undertow.security.jacc.JACCContextIdHandler.handleRequest(JACCContextIdHandler.java:61)
at io.undertow.server.handlers.PredicateHandler.handleRequest(PredicateHandler.java:43)
at io.undertow.server.handlers.PredicateHandler.handleRequest(PredicateHandler.java:43)
at io.undertow.servlet.handlers.ServletInitialHandler.handleFirstRequest(ServletInitialHandler.java:282)
at io.undertow.servlet.handlers.ServletInitialHandler.dispatchRequest(ServletInitialHandler.java:261)
at io.undertow.servlet.handlers.ServletInitialHandler.access$000(ServletInitialHandler.java:80)
at io.undertow.servlet.handlers.ServletInitialHandler$1.handleRequest(ServletInitialHandler.java:172)
at io.undertow.server.Connectors.executeRootHandler(Connectors.java:199)
at io.undertow.server.HttpServerExchange$1.run(HttpServerExchange.java:774)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1142)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:617)
at java.lang.Thread.run(Thread.java:745)
Caused by: org.neo4j.ogm.session.result.ResultProcessingException: Failed to execute request:
at org.neo4j.ogm.session.transaction.TransactionManager.executeRequest(TransactionManager.java:128)
at org.neo4j.ogm.session.transaction.TransactionManager.commit(TransactionManager.java:86)
at org.neo4j.ogm.session.transaction.LongTransaction.commit(LongTransaction.java:37)
at org.springframework.data.neo4j.transaction.Neo4jTransactionManager.commit(Neo4jTransactionManager.java:49)
at org.springframework.transaction.interceptor.TransactionAspectSupport.commitTransactionAfterReturning(TransactionAspectSupport.java:521)
at org.springframework.transaction.interceptor.TransactionAspectSupport.invokeWithinTransaction(TransactionAspectSupport.java:291)
at org.springframework.transaction.interceptor.TransactionInterceptor.invoke(TransactionInterceptor.java:96)
at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:179)
at org.springframework.aop.framework.CglibAopProxy$DynamicAdvisedInterceptor.intercept(CglibAopProxy.java:644)
at org.neo4j.example.northwind.controller.IndexController$$EnhancerBySpringCGLIB$$c48f93ec.cat(<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:497)
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:690)
at org.springframework.web.servlet.mvc.method.AbstractHandlerMethodAdapter.handle(AbstractHandlerMethodAdapter.java:83)
at org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:945)
at org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:876)
at org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:961)
... 31 more
Caused by: org.apache.http.client.HttpResponseException: Not Found
at org.neo4j.ogm.session.transaction.TransactionManager.executeRequest(TransactionManager.java:106)
... 53 more
You should extend Neo4jConfiguration to your config file and override below method:
#Override
public SessionFactory getSessionFactory() {
return new SessionFactory("com.neo.entity.neo");
}
Note, com.neo.entity.neo is package name of entity.
I suggest you to provide credentials thru RemoteServer object
public Neo4jServer neo4jServer() {
return new RemoteServer(NEO4J_HOST + NEO4J_PORT, "neo4j", "12345");
}
Adding just #EntityScan to my configurtion and specifying the packages to scan worked for me.
I am using Spring Boot 1.4.0 along with Neo4j 2.0.4.
I am new to Spring and I would like to protect my API with Spring Security. But even after two days of reading tutorials I can't get it working.
If I do a POST to j_spring_security_check I get the following response:
{
"timestamp": 1407420906360,
"status": 500,
"error": "Internal Server Error",
"exception": "java.lang.NullPointerException",
"message": null,
"path": "/j_spring_security_check"
}
caused by the following Java-Exception:
java.lang.NullPointerException: null
at org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter.attemptAuthentication(UsernamePasswordAuthenticationFilter.java:94)
at org.springframework.security.web.authentication.AbstractAuthenticationProcessingFilter.doFilter(AbstractAuthenticationProcessingFilter.java:211)
at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:342)
at org.springframework.security.web.authentication.logout.LogoutFilter.doFilter(LogoutFilter.java:110)
at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:342)
at org.springframework.security.web.header.HeaderWriterFilter.doFilterInternal(HeaderWriterFilter.java:57)
at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107)
at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:342)
at org.springframework.security.web.context.SecurityContextPersistenceFilter.doFilter(SecurityContextPersistenceFilter.java:87)
at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:342)
at org.springframework.security.web.context.request.async.WebAsyncManagerIntegrationFilter.doFilterInternal(WebAsyncManagerIntegrationFilter.java:50)
at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107)
at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:342)
at org.springframework.security.web.FilterChainProxy.doFilterInternal(FilterChainProxy.java:192)
at org.springframework.security.web.FilterChainProxy.doFilter(FilterChainProxy.java:160)
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:501)
at org.apache.catalina.valves.RemoteIpValve.invoke(RemoteIpValve.java:683)
at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:171)
at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:102)
at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:116)
at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:408)
at org.apache.coyote.http11.AbstractHttp11Processor.process(AbstractHttp11Processor.java:1040)
at org.apache.coyote.AbstractProtocol$AbstractConnectionHandler.process(AbstractProtocol.java:607)
at org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.doRun(NioEndpoint.java:1720)
at org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.run(NioEndpoint.java:1679)
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)
Line 94 in UsernamePasswordAuthenticationFilter is the following. The exception is thrown because getAuthenticationManager() returns null.
return this.getAuthenticationManager().authenticate(authRequest);
I REALLY don't get why this method returns null.
This is my security config:
#Configuration
#EnableWebMvcSecurity
#EnableGlobalMethodSecurity(prePostEnabled = true)
public class SecurityConfig extends WebSecurityConfigurerAdapter {
#Autowired
AuthenticationProvider authentificationProvider;
#Autowired
AuthenticationEntryPoint restAuthenticationEntryPoint;
#Autowired
AuthenticationSuccessHandler successHandler;
#Override
protected void configure(AuthenticationManagerBuilder auth)
throws Exception {
auth.authenticationProvider(authentificationProvider);
}
#Bean
#Override
public AuthenticationManager authenticationManagerBean() throws Exception {
return super.authenticationManagerBean();
}
#Override
protected void configure(HttpSecurity http) throws Exception {
http.csrf().disable().httpBasic()
.authenticationEntryPoint(restAuthenticationEntryPoint).and()
.addFilter(getSuccessFilter()).anonymous()
.authorities(UserRightsProvider.getAnonymousAuthorities())
.and().authorizeRequests().anyRequest().authenticated();
}
protected Filter getSuccessFilter() {
UsernamePasswordAuthenticationFilter authenticationFilter = new UsernamePasswordAuthenticationFilter();
authenticationFilter.setAuthenticationSuccessHandler(successHandler);
return authenticationFilter;
}
}
The application is started the following way:
#Order(1)
public class WebAppSecurityInitializer extends AbstractSecurityWebApplicationInitializer {}
and
#Configuration
#EnableAutoConfiguration
#ComponentScan({ "my.packet" })
#PropertySource("classpath:myProperties.properties")
#Order(2)
public class Application extends SpringBootServletInitializer {
#Override
protected SpringApplicationBuilder configure(SpringApplicationBuilder application) {
application.showBanner(false);
application.sources(getClass());
return application;
}
public static void main(String[] args) {
SpringApplication app = new SpringApplication(Application.class);
app.setShowBanner(false);
app.run(args);
}
}
Any help is appreciated! :-)
in getSuccessFilter you need to have
filter.setAuthenticationManager(this.authenticationManagerBean());
You aren't using spring autowiring/DI to make that thing so you have to do everything by hand. Spring Security Filters (generally) need a handle to auth manager
While I was configuring my beans od spring3.0+thymeleaf+tiles2 i get the following error:
org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'templateResolver' defined in class com.spr.init.WebAppConfig: Instantiation of bean failed; nested exception is org.springframework.beans.factory.BeanDefinitionStoreException: Factory method [public org.thymeleaf.templateresolver.ServletContextTemplateResolver com.spr.init.WebAppConfig.templateResolver()] threw exception; nested exception is java.lang.IncompatibleClassChangeError
at org.springframework.beans.factory.support.ConstructorResolver.instantiateUsingFactoryMethod(ConstructorResolver.java:581)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.instantiateUsingFactoryMethod(AbstractAutowireCapableBeanFactory.java:1031)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBeanInstance(AbstractAutowireCapableBeanFactory.java:927)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:490)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:461)
at org.springframework.beans.factory.support.AbstractBeanFactory$1.getObject(AbstractBeanFactory.java:295)
at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:223)
at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:292)
at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:194)
at org.springframework.beans.factory.support.DefaultListableBeanFactory.preInstantiateSingletons(DefaultListableBeanFactory.java:626)
at org.springframework.context.support.AbstractApplicationContext.finishBeanFactoryInitialization(AbstractApplicationContext.java:932)
at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:479)
at org.springframework.web.context.ContextLoader.configureAndRefreshWebApplicationContext(ContextLoader.java:389)
at org.springframework.web.context.ContextLoader.initWebApplicationContext(ContextLoader.java:294)
at org.springframework.web.context.ContextLoaderListener.contextInitialized(ContextLoaderListener.java:112)
at org.apache.catalina.core.StandardContext.listenerStart(StandardContext.java:4797)
at org.apache.catalina.core.StandardContext.startInternal(StandardContext.java:5291)
at org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:150)
at org.apache.catalina.core.ContainerBase.addChildInternal(ContainerBase.java:901)
at org.apache.catalina.core.ContainerBase.addChild(ContainerBase.java:877)
at org.apache.catalina.core.StandardHost.addChild(StandardHost.java:633)
at org.apache.catalina.startup.HostConfig.deployWAR(HostConfig.java:977)
at org.apache.catalina.startup.HostConfig$DeployWar.run(HostConfig.java:1655)
at java.util.concurrent.Executors$RunnableAdapter.call(Executors.java:441)
at java.util.concurrent.FutureTask$Sync.innerRun(FutureTask.java:303)
at java.util.concurrent.FutureTask.run(FutureTask.java:138)
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)
Caused by: org.springframework.beans.factory.BeanDefinitionStoreException: Factory method [public org.thymeleaf.templateresolver.ServletContextTemplateResolver com.spr.init.WebAppConfig.templateResolver()] threw exception; nested exception is java.lang.IncompatibleClassChangeError
at org.springframework.beans.factory.support.SimpleInstantiationStrategy.instantiate(SimpleInstantiationStrategy.java:181)
at org.springframework.beans.factory.support.ConstructorResolver.instantiateUsingFactoryMethod(ConstructorResolver.java:570)
... 28 more
Caused by: java.lang.IncompatibleClassChangeError
at org.apache.xerces.parsers.XMLParser.<init>(Unknown Source)
at org.apache.xerces.parsers.AbstractXMLDocumentParser.<init>(Unknown Source)
at org.apache.xerces.parsers.AbstractDOMParser.<init>(Unknown Source)
at org.apache.xerces.parsers.DOMParser.<init>(Unknown Source)
at org.thymeleaf.templateparser.html.AbstractHtmlTemplateParser$HtmlTemplateParserFactory.createResource(AbstractHtmlTemplateParser.java:227)
at org.thymeleaf.util.ResourcePool.<init>(ResourcePool.java:79)
at org.thymeleaf.templateparser.html.AbstractHtmlTemplateParser$NekoBasedHtmlParser.<init>(AbstractHtmlTemplateParser.java:136)
at org.thymeleaf.templateparser.html.AbstractHtmlTemplateParser.<init>(AbstractHtmlTemplateParser.java:75)
at org.thymeleaf.templateparser.html.LegacyHtml5TemplateParser.<init>(LegacyHtml5TemplateParser.java:45)
at org.thymeleaf.templatemode.StandardTemplateModeHandlers.<clinit>(StandardTemplateModeHandlers.java:103)
at org.thymeleaf.templateresolver.TemplateResolver.<clinit>(TemplateResolver.java:68)
at com.spr.init.WebAppConfig.templateResolver(WebAppConfig.java:104)
at com.spr.init.WebAppConfig$$EnhancerByCGLIB$$c91bdc02.CGLIB$templateResolver$4(<generated>)
at com.spr.init.WebAppConfig$$EnhancerByCGLIB$$c91bdc02$$FastClassByCGLIB$$75d7ea47.invoke(<generated>)
at org.springframework.cglib.proxy.MethodProxy.invokeSuper(MethodProxy.java:228)
at org.springframework.context.annotation.ConfigurationClassEnhancer$BeanMethodInterceptor.intercept(ConfigurationClassEnhancer.java:286)
at com.spr.init.WebAppConfig$$EnhancerByCGLIB$$c91bdc02.templateResolver(<generated>)
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 org.springframework.beans.factory.support.SimpleInstantiationStrategy.instantiate(SimpleInstantiationStrategy.java:160)
... 29 more
and my WebAppConfig.java is given below
WebAppConfig.java
#Configuration
#EnableWebMvc
#EnableTransactionManagement
#ComponentScan("com.spr")
#PropertySource("classpath:application.properties")
#EnableJpaRepositories("com.spr.repository")
public class WebAppConfig extends WebMvcConfigurerAdapter{
private static final String PROPERTY_NAME_DATABASE_DRIVER = "db.driver";
private static final String PROPERTY_NAME_DATABASE_PASSWORD = "db.password";
private static final String PROPERTY_NAME_DATABASE_URL = "db.url";
private static final String PROPERTY_NAME_DATABASE_USERNAME = "db.username";
private static final String PROPERTY_NAME_HIBERNATE_DIALECT = "hibernate.dialect";
private static final String PROPERTY_NAME_HIBERNATE_SHOW_SQL = "hibernate.show_sql";
private static final String PROPERTY_NAME_ENTITYMANAGER_PACKAGES_TO_SCAN = "entitymanager.packages.to.scan";
#Resource
private Environment env;
#Bean
public DataSource dataSource() {
DriverManagerDataSource dataSource = new DriverManagerDataSource();
dataSource.setDriverClassName(env.getRequiredProperty(PROPERTY_NAME_DATABASE_DRIVER));
dataSource.setUrl(env.getRequiredProperty(PROPERTY_NAME_DATABASE_URL));
dataSource.setUsername(env.getRequiredProperty(PROPERTY_NAME_DATABASE_USERNAME));
dataSource.setPassword(env.getRequiredProperty(PROPERTY_NAME_DATABASE_PASSWORD));
return dataSource;
}
#Bean
public LocalContainerEntityManagerFactoryBean entityManagerFactory() {
LocalContainerEntityManagerFactoryBean entityManagerFactoryBean = new LocalContainerEntityManagerFactoryBean();
entityManagerFactoryBean.setDataSource(dataSource());
entityManagerFactoryBean.setPersistenceProviderClass(HibernatePersistence.class);
entityManagerFactoryBean.setPackagesToScan(env.getRequiredProperty(PROPERTY_NAME_ENTITYMANAGER_PACKAGES_TO_SCAN));
entityManagerFactoryBean.setJpaProperties(hibProperties());
return entityManagerFactoryBean;
}
private Properties hibProperties() {
Properties properties = new Properties();
properties.put(PROPERTY_NAME_HIBERNATE_DIALECT, env.getRequiredProperty(PROPERTY_NAME_HIBERNATE_DIALECT));
properties.put(PROPERTY_NAME_HIBERNATE_SHOW_SQL, env.getRequiredProperty(PROPERTY_NAME_HIBERNATE_SHOW_SQL));
return properties;
}
#Bean
public JpaTransactionManager transactionManager() {
JpaTransactionManager transactionManager = new JpaTransactionManager();
transactionManager.setEntityManagerFactory(entityManagerFactory().getObject());
return transactionManager;
}
//Configuring a TemplateResolver
#Bean
public ServletContextTemplateResolver templateResolver(){
ServletContextTemplateResolver resolver = new ServletContextTemplateResolver();
resolver.setPrefix("/WEB-INF/templates/");
resolver.setSuffix(".html");
resolver.setTemplateMode("HTML5");
resolver.setOrder(1);
return resolver;
}
#Bean
public ThymeleafTilesConfigurer tilesConfigurer(){
ThymeleafTilesConfigurer configurer = new ThymeleafTilesConfigurer();
String[] tilepath = {"/WEB-INF/thymeleaftiles.xml"};
configurer.setDefinitions(tilepath);
return configurer;
}
#Bean
public SpringTemplateEngine templateEngine() {
SpringTemplateEngine engine = new SpringTemplateEngine();
Set tileset = new HashSet();
tileset.add(TilesDialect.class);
engine.setTemplateResolver(templateResolver());
engine.setAdditionalDialects(tileset);
return engine;
}
#Bean
public ThymeleafViewResolver thymeleafViewResolver(){
ThymeleafViewResolver resolver = new ThymeleafViewResolver();
resolver.setViewClass(ThymeleafTilesView.class);
resolver.setTemplateEngine(templateEngine());
return resolver;
}
#Bean
public ResourceBundleMessageSource messageSource() {
ResourceBundleMessageSource source = new ResourceBundleMessageSource();
source.setBasename(env.getRequiredProperty("message.source.basename"));
source.setUseCodeAsDefaultMessage(true);
return source;
}
}
I couldnt figure out where have i gone wrong and this is driving me crazy.Can anyone help me sort this thing out..
not sure whats wrong here, please assist.
this is the exception :
SEVERE: Exception starting filter com.bannerplay.beans.LoginFilter
java.lang.IllegalAccessException: Class org.apache.catalina.core.DefaultInstanceManager can not access a member of class com.bannerplay.beans.LoginFilter with modifiers ""
at sun.reflect.Reflection.ensureMemberAccess(Unknown Source)
at java.lang.Class.newInstance0(Unknown Source)
at java.lang.Class.newInstance(Unknown Source)
at org.apache.catalina.core.DefaultInstanceManager.newInstance(DefaultInstanceManager.java:134)
at org.apache.catalina.core.ApplicationFilterConfig.getFilter(ApplicationFilterConfig.java:256)
at org.apache.catalina.core.ApplicationFilterConfig.setFilterDef(ApplicationFilterConfig.java:382)
at org.apache.catalina.core.ApplicationFilterConfig.<init>(ApplicationFilterConfig.java:103)
at org.apache.catalina.core.StandardContext.filterStart(StandardContext.java:4650)
at org.apache.catalina.core.StandardContext.startInternal(StandardContext.java:5306)
at org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:150)
at org.apache.catalina.core.ContainerBase$StartChild.call(ContainerBase.java:1559)
at org.apache.catalina.core.ContainerBase$StartChild.call(ContainerBase.java:1549)
at java.util.concurrent.FutureTask$Sync.innerRun(Unknown Source)
at java.util.concurrent.FutureTask.run(Unknown Source)
at java.util.concurrent.ThreadPoolExecutor.runWorker(Unknown Source)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(Unknown Source)
at java.lang.Thread.run(Unknown Source)
login.xhtml
<h:form>
Username : <h:inputText value="#{loginBean.username}" />
Password : <h:inputSecret value="#{loginBean.password}" />
<h:commandButton value="Login" action="#{loginBean.checkLogin}" />
</h:form>
web.xml
<filter>
<filter-name>LoginFilter</filter-name>
<filter-class>com.bannerplay.beans.LoginFilter</filter-class>
</filter>
<filter-mapping>
<filter-name>LoginFilter</filter-name>
<servlet-name>FacesServlet</servlet-name>
<url-pattern>/admin/*</url-pattern>
</filter-mapping>
<welcome-file-list>
<welcome-file>/login.xhtml</welcome-file>
</welcome-file-list>
<servlet>
<servlet-name>FacesServlet</servlet-name>
<servlet-class>javax.faces.webapp.FacesServlet</servlet-class>
<load-on-startup>1</load-on-startup>
</servlet>
...
and LoginFilter.java
import java.io.IOException;
import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
#WebFilter("/admin/*")
class LoginFilter implements Filter {
#Override
public void doFilter(ServletRequest request , ServletResponse response , FilterChain chain) throws ServletException, IOException {
HttpSession session = ((HttpServletRequest) request).getSession();
UserBean userBean = (UserBean) session.getAttribute("userBean");
if (userBean != null) {
User user = userBean.getUser();
if (user == null) {
((HttpServletResponse) response).sendRedirect("/login.xhtml");
} else
chain.doFilter(request, response);
} else
((HttpServletResponse) response).sendRedirect("/login.xhtml");
}
public void init(FilterConfig fc) {
}
public void destroy() {
}
}
I have no idea where this exception comes from,please shade some light on this issue. Thanks!
EDIT1: adding UserBean.java code :
import java.io.Serializable;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.SessionScoped;
#ManagedBean
#SessionScoped
class UserBean implements Serializable {
/**
*
*/
private static final long serialVersionUID = 1L;
public User getUser() {
return user;
}
public void setUser(User user) {
this.user = user;
}
private User user;
}
BTW, SEVERE: Context [/projectName] startup failed due to previous errors
Change :
class LoginFilter implements Filter {
to
public class LoginFilter implements Filter {
For me the issue was that of the 'constructor' not being public.