Error creating bean with name 'springSecurityFilterChain' defined in class path resource - spring-security-oauth2

I am new to Spring Security. I am using okta OIDC application to secure my Resource Server.
I have the following application.yml
okta:
oauth2:
client-id: {client-id}
issuer: https://{okta-domain}.okta.com
I have the following security configuration :
#Configuration
#EnableWebSecurity
public class SecurityConfiguration extends WebSecurityConfigurerAdapter{
#Override
protected void configure(HttpSecurity http) throws Exception{
http.authorizeRequests().antMatchers("/").permitAll();
}
#Autowired
public void configureGlobal(AuthenticationManagerBuilder auth) throws Exception {
auth
.inMemoryAuthentication()
.withUser("user").password("user_pwd").roles("USER").and()
.withUser("admin").password("admin_pwd").roles("USER", "ADMIN");
}
}
I am getting the following error after adding the above piece of code:
org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'springSecurityFilterChain' defined in class path resource [org/springframework/security/config/annotation/web/configuration/WebSecurityConfiguration.class]: Bean instantiation via factory method failed; nested exception is org.springframework.beans.BeanInstantiationException: Failed to instantiate [javax.servlet.Filter]: Factory method 'springSecurityFilterChain' threw exception; nested exception is java.lang.IllegalStateException: Can't configure anyRequest after itself
at org.springframework.beans.factory.support.ConstructorResolver.instantiate(ConstructorResolver.java:655) ~[spring-beans-5.2.9.RELEASE.jar:5.2.9.RELEASE]
at org.springframework.beans.factory.support.ConstructorResolver.instantiateUsingFactoryMethod(ConstructorResolver.java:483) ~[spring-beans-5.2.9.RELEASE.jar:5.2.9.RELEASE]
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.instantiateUsingFactoryMethod(AbstractAutowireCapableBeanFactory.java:1336) ~[spring-beans-5.2.9.RELEASE.jar:5.2.9.RELEASE]
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBeanInstance(AbstractAutowireCapableBeanFactory.java:1176) ~[spring-beans-5.2.9.RELEASE.jar:5.2.9.RELEASE]
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:556) ~[spring-beans-5.2.9.RELEASE.jar:5.2.9.RELEASE]
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:516) ~[spring-beans-5.2.9.RELEASE.jar:5.2.9.RELEASE]
at org.springframework.beans.factory.support.AbstractBeanFactory.lambda$doGetBean$0(AbstractBeanFactory.java:324) ~[spring-beans-5.2.9.RELEASE.jar:5.2.9.RELEASE]
at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:234) ~[spring-beans-5.2.9.RELEASE.jar:5.2.9.RELEASE]
at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:322) ~[spring-beans-5.2.9.RELEASE.jar:5.2.9.RELEASE]
at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:202) ~[spring-beans-5.2.9.RELEASE.jar:5.2.9.RELEASE]
at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:311) ~[spring-beans-5.2.9.RELEASE.jar:5.2.9.RELEASE]
at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:202) ~[spring-beans-5.2.9.RELEASE.jar:5.2.9.RELEASE]
at org.springframework.beans.factory.support.DefaultListableBeanFactory.preInstantiateSingletons(DefaultListableBeanFactory.java:897) ~[spring-beans-5.2.9.RELEASE.jar:5.2.9.RELEASE]
at org.springframework.context.support.AbstractApplicationContext.finishBeanFactoryInitialization(AbstractApplicationContext.java:879) ~[spring-context-5.2.9.RELEASE.jar:5.2.9.RELEASE]
at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:551) ~[spring-context-5.2.9.RELEASE.jar:5.2.9.RELEASE]
at org.springframework.boot.web.servlet.context.ServletWebServerApplicationContext.refresh(ServletWebServerApplicationContext.java:143) ~[spring-boot-2.3.4.RELEASE.jar:2.3.4.RELEASE]
at org.springframework.boot.SpringApplication.refresh(SpringApplication.java:758) [spring-boot-2.3.4.RELEASE.jar:2.3.4.RELEASE]
at org.springframework.boot.SpringApplication.refresh(SpringApplication.java:750) [spring-boot-2.3.4.RELEASE.jar:2.3.4.RELEASE]
at org.springframework.boot.SpringApplication.refreshContext(SpringApplication.java:397) [spring-boot-2.3.4.RELEASE.jar:2.3.4.RELEASE]
at org.springframework.boot.SpringApplication.run(SpringApplication.java:315) [spring-boot-2.3.4.RELEASE.jar:2.3.4.RELEASE]
at org.springframework.boot.SpringApplication.run(SpringApplication.java:1237) [spring-boot-2.3.4.RELEASE.jar:2.3.4.RELEASE]
at org.springframework.boot.SpringApplication.run(SpringApplication.java:1226) [spring-boot-2.3.4.RELEASE.jar:2.3.4.RELEASE]
at com.symbiose.OAuthResourceServerApplication.main(OAuthResourceServerApplication.java:13) [classes/:na]
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) ~[na:1.8.0_241]
at sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source) ~[na:1.8.0_241]
at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source) ~[na:1.8.0_241]
at java.lang.reflect.Method.invoke(Unknown Source) ~[na:1.8.0_241]
at org.springframework.boot.devtools.restart.RestartLauncher.run(RestartLauncher.java:49) [spring-boot-devtools-2.3.4.RELEASE.jar:2.3.4.RELEASE]
Caused by: org.springframework.beans.BeanInstantiationException: Failed to instantiate [javax.servlet.Filter]: Factory method 'springSecurityFilterChain' threw exception; nested exception is java.lang.IllegalStateException: Can't configure anyRequest after itself
at org.springframework.beans.factory.support.SimpleInstantiationStrategy.instantiate(SimpleInstantiationStrategy.java:185) ~[spring-beans-5.2.9.RELEASE.jar:5.2.9.RELEASE]
at org.springframework.beans.factory.support.ConstructorResolver.instantiate(ConstructorResolver.java:650) ~[spring-beans-5.2.9.RELEASE.jar:5.2.9.RELEASE]
... 27 common frames omitted
Caused by: java.lang.IllegalStateException: Can't configure anyRequest after itself
at org.springframework.util.Assert.state(Assert.java:76) ~[spring-core-5.2.9.RELEASE.jar:5.2.9.RELEASE]
at org.springframework.security.config.annotation.web.AbstractRequestMatcherRegistry.anyRequest(AbstractRequestMatcherRegistry.java:74) ~[spring-security-config-5.3.4.RELEASE.jar:5.3.4.RELEASE]
at org.springframework.security.oauth2.config.annotation.web.configuration.ResourceServerConfigurerAdapter.configure(ResourceServerConfigurerAdapter.java:30) ~[spring-security-oauth2-2.3.4.RELEASE.jar:na]
at org.springframework.security.oauth2.config.annotation.web.configuration.ResourceServerConfiguration.configure(ResourceServerConfiguration.java:154) ~[spring-security-oauth2-2.3.4.RELEASE.jar:na]
at org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter.getHttp(WebSecurityConfigurerAdapter.java:231) ~[spring-security-config-5.3.4.RELEASE.jar:5.3.4.RELEASE]
at org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter.init(WebSecurityConfigurerAdapter.java:322) ~[spring-security-config-5.3.4.RELEASE.jar:5.3.4.RELEASE]
at org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter.init(WebSecurityConfigurerAdapter.java:94) ~[spring-security-config-5.3.4.RELEASE.jar:5.3.4.RELEASE]
at org.springframework.security.oauth2.config.annotation.web.configuration.ResourceServerConfiguration$$EnhancerBySpringCGLIB$$4941180f.init(<generated>) ~[spring-security-oauth2-2.3.4.RELEASE.jar:na]
at org.springframework.security.config.annotation.AbstractConfiguredSecurityBuilder.init(AbstractConfiguredSecurityBuilder.java:370) ~[spring-security-config-5.3.4.RELEASE.jar:5.3.4.RELEASE]
at org.springframework.security.config.annotation.AbstractConfiguredSecurityBuilder.doBuild(AbstractConfiguredSecurityBuilder.java:324) ~[spring-security-config-5.3.4.RELEASE.jar:5.3.4.RELEASE]
at org.springframework.security.config.annotation.AbstractSecurityBuilder.build(AbstractSecurityBuilder.java:41) ~[spring-security-config-5.3.4.RELEASE.jar:5.3.4.RELEASE]
at org.springframework.security.config.annotation.web.configuration.WebSecurityConfiguration.springSecurityFilterChain(WebSecurityConfiguration.java:104) ~[spring-security-config-5.3.4.RELEASE.jar:5.3.4.RELEASE]
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) ~[na:1.8.0_241]
at sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source) ~[na:1.8.0_241]
at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source) ~[na:1.8.0_241]
at java.lang.reflect.Method.invoke(Unknown Source) ~[na:1.8.0_241]
at org.springframework.beans.factory.support.SimpleInstantiationStrategy.instantiate(SimpleInstantiationStrategy.java:154) ~[spring-beans-5.2.9.RELEASE.jar:5.2.9.RELEASE]
... 28 common frames omitted
Also, how do I validate the user and password dynamically without hard coding the values as above in the "InMemoryAuthentication". For ex: I have created few people and added them in User and Admin groups as per my requirement in Okta, added the user and admin groups to my OIDC SPA App.
In that case, the users with specific user or admin role will be logging in which I need to capture and restrict access to few APIs in case of user ROLE. How do I configure the above code to dynamically verify the logged in user?

There are a few questions in here, so I'll attempt to answer them.
First, you are configuring both Basic Auth and an OAuth resource server.
My suggestion is to keep it simple and JUST use OAuth. You can configure them both, but you will need to explicitly do so in your WebSecurityConfigurerAdapter
i.e. in configure() add:
// require authentication for ALL endpoints
http.authorizeRequests().anyRequest().authenticated();
// enable resource server to process JWTs
http.oauth2ResourceServer().jwt();
One issue you have is you have this line:
http.authorizeRequests().antMatchers("/").permitAll();
This allows ALL unauthenticated requests.
If you do NOT define a WebSecurityConfigurerAdapter at all, the default is the first code block I posted.
I usually recommend to start with the defaults. The default is a secure application :)
Once you have that working, you can add a custom WebSecurityConfigurerAdapter. but start with a similar default configuration.
Next, start allowing any unauthenticated paths, something like:
http.authorizeRequests()
// Allow anon access to the root application
.antMatchers("/", "/index.html").permitAll()
// Require authentication for ALL other requests
.anyRequest().authenticated();
// enable resource server, process JWTs
http.oauth2ResourceServer().jwt();
Finally, add other authentication sources (in your case basic auth if needed).
For role-based security you have a couple of options too, you can either add them via annotations or in your WebSecurityConfigurerAdapter.
This post should walk you through everything in a bit more detail: https://developer.okta.com/blog/2019/06/20/spring-preauthorize

Related

Spring JDBC session causes duplicate entry exception

In my Spring Boot project, there are REST and MVC controllers. Where the MVC part should have session. This part goes fine, but when you come from a MVC page with session and start using Swagger from the browser to the API I start to see these messages on the REST API endpoints:
org.springframework.dao.DuplicateKeyException: PreparedStatementCallback; SQL [INSERT INTO SPRING_SESSION_ATTRIBUTES(SESSION_PRIMARY_ID, ATTRIBUTE_NAME, ATTRIBUTE_BYTES) VALUES (?, ?, ?)Duplicate entry '7a69e3fe-dd7f-4a1d-85bb-2dcd617225dd-SPRING_SECURITY_SAVED_REQUE' for key 'PRIMARY'; nested exception is com.mysql.jdbc.exceptions.jdbc4.MySQLIntegrityConstraintViolationException: Duplicate entry '7a69e3fe-dd7f-4a1d-85bb-2dcd617225dd-SPRING_SECURITY_SAVED_REQUE' for key 'PRIMARY'
at org.springframework.jdbc.support.SQLErrorCodeSQLExceptionTranslator.doTranslate(SQLErrorCodeSQLExceptionTranslator.java:242)
at org.springframework.jdbc.support.AbstractFallbackSQLExceptionTranslator.translate(AbstractFallbackSQLExceptionTranslator.java:72)
at org.springframework.jdbc.core.JdbcTemplate.translateException(JdbcTemplate.java:1402)
at org.springframework.jdbc.core.JdbcTemplate.execute(JdbcTemplate.java:620)
at org.springframework.jdbc.core.JdbcTemplate.update(JdbcTemplate.java:850)
at org.springframework.jdbc.core.JdbcTemplate.update(JdbcTemplate.java:905)
at org.springframework.session.jdbc.JdbcOperationsSessionRepository.insertSessionAttributes(JdbcOperationsSessionRepository.java:515)
at org.springframework.session.jdbc.JdbcOperationsSessionRepository.access$300(JdbcOperationsSessionRepository.java:131)
at org.springframework.session.jdbc.JdbcOperationsSessionRepository$2.doInTransactionWithoutResult(JdbcOperationsSessionRepository.java:413)
at org.springframework.transaction.support.TransactionCallbackWithoutResult.doInTransaction(TransactionCallbackWithoutResult.java:36)
at org.springframework.transaction.support.TransactionTemplate.execute(TransactionTemplate.java:140)
at org.springframework.session.jdbc.JdbcOperationsSessionRepository.save(JdbcOperationsSessionRepository.java:393)
at org.springframework.session.jdbc.JdbcOperationsSessionRepository.save(JdbcOperationsSessionRepository.java:131)
at org.springframework.session.web.http.SessionRepositoryFilter$SessionRepositoryRequestWrapper.saveSession(SessionRepositoryFilter.java:377)
at org.springframework.session.web.http.SessionRepositoryFilter$SessionRepositoryRequestWrapper.commitSession(SessionRepositoryFilter.java:233)
at org.springframework.session.web.http.SessionRepositoryFilter$SessionRepositoryRequestWrapper.access$100(SessionRepositoryFilter.java:197)
at org.springframework.session.web.http.SessionRepositoryFilter.doFilterInternal(SessionRepositoryFilter.java:150)
at org.springframework.session.web.http.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:81)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166)
at org.apache.catalina.core.ApplicationDispatcher.invoke(ApplicationDispatcher.java:728)
at org.apache.catalina.core.ApplicationDispatcher.processRequest(ApplicationDispatcher.java:472)
at org.apache.catalina.core.ApplicationDispatcher.doForward(ApplicationDispatcher.java:395)
at org.apache.catalina.core.ApplicationDispatcher.forward(ApplicationDispatcher.java:316)
at org.apache.catalina.core.StandardHostValve.custom(StandardHostValve.java:395)
at org.apache.catalina.core.StandardHostValve.status(StandardHostValve.java:254)
at org.apache.catalina.core.StandardHostValve.throwable(StandardHostValve.java:349)
at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:175)
at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:81)
at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:87)
at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:342)
at org.apache.coyote.http11.Http11Processor.service(Http11Processor.java:803)
at org.apache.coyote.AbstractProcessorLight.process(AbstractProcessorLight.java:66)
at org.apache.coyote.AbstractProtocol$ConnectionHandler.process(AbstractProtocol.java:790)
at org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.doRun(NioEndpoint.java:1468)
at org.apache.tomcat.util.net.SocketProcessorBase.run(SocketProcessorBase.java:49)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1142)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:617)
at org.apache.tomcat.util.threads.TaskThread$WrappingRunnable.run(TaskThread.java:61)
at java.lang.Thread.run(Thread.java:745)
Caused by: com.mysql.jdbc.exceptions.jdbc4.MySQLIntegrityConstraintViolationException: Duplicate entry '7a69e3fe-dd7f-4a1d-85bb-2dcd617225dd-SPRING_SECURITY_SAVED_REQUE' for key 'PRIMARY'
at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)
at sun.reflect.NativeConstructorAccessorImpl.newInstance(NativeConstructorAccessorImpl.java:62)
at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(DelegatingConstructorAccessorImpl.java:45)
at java.lang.reflect.Constructor.newInstance(Constructor.java:423)
at com.mysql.jdbc.Util.handleNewInstance(Util.java:425)
at com.mysql.jdbc.Util.getInstance(Util.java:408)
at com.mysql.jdbc.SQLError.createSQLException(SQLError.java:936)
at com.mysql.jdbc.MysqlIO.checkErrorPacket(MysqlIO.java:3976)
at com.mysql.jdbc.MysqlIO.checkErrorPacket(MysqlIO.java:3912)
at com.mysql.jdbc.MysqlIO.sendCommand(MysqlIO.java:2530)
at com.mysql.jdbc.MysqlIO.sqlQueryDirect(MysqlIO.java:2683)
at com.mysql.jdbc.ConnectionImpl.execSQL(ConnectionImpl.java:2486)
at com.mysql.jdbc.PreparedStatement.executeInternal(PreparedStatement.java:1858)
at com.mysql.jdbc.PreparedStatement.executeUpdateInternal(PreparedStatement.java:2079)
at com.mysql.jdbc.PreparedStatement.executeUpdateInternal(PreparedStatement.java:2013)
at com.mysql.jdbc.PreparedStatement.executeLargeUpdate(PreparedStatement.java:5104)
at com.mysql.jdbc.PreparedStatement.executeUpdate(PreparedStatement.java:1998)
at com.zaxxer.hikari.pool.ProxyPreparedStatement.executeUpdate(ProxyPreparedStatement.java:61)
at com.zaxxer.hikari.pool.HikariProxyPreparedStatement.executeUpdate(HikariProxyPreparedStatement.java)
at org.springframework.jdbc.core.JdbcTemplate.lambda$update$0(JdbcTemplate.java:855)
at org.springframework.jdbc.core.JdbcTemplate.execute(JdbcTemplate.java:605)
... 36 common frames omitted
My security configuration looks like this:
#Configuration
#EnableResourceServer
public class ResourceServerConfiguration extends ResourceServerConfigurerAdapter {
#Override
public void configure(HttpSecurity http) throws Exception {
http
.sessionManagement().sessionCreationPolicy(SessionCreationPolicy.IF_REQUIRED)
.and()
.cors().and()
.authorizeRequests()
.antMatchers(
"/",
"/index.html",
"/oauth2-redirect.html",
"/favicon-*.png",
"/swagger-*",
"/swagger.json"
).permitAll()
.anyRequest().authenticated();
}
}
Appereantly there is a bug in delta session handling: https://github.com/spring-projects/spring-session/pull/1070
This should be fixed in version Spring Session 2.0.4.RELEASE, I worked on version Spring Session 2.0.3.RELEASE and have now downgraded to Spring Session 1.3.2.RELEASE which resolved my issues (which is in spring boot 1.5.13.RELEASE).
Will try again when version 2.0.4.RELEASE is out.
UPDATE: I tested the SNAPSHOT version, suggested here
<dependency>
<groupId>org.springframework.session</groupId>
<artifactId>spring-session-jdbc</artifactId>
<version>2.0.4.BUILD-SNAPSHOT</version>
</dependency>
This is resolving my issue.
Need to use sql query that will ignore duplicate. Spring already have the correct one, you just need to enable it:
#Configuration
class DatabaseConfig {
#Bean
public MySqlJdbcIndexedSessionRepositoryCustomizer sessionRepositoryCustomizer() {
return new MySqlJdbcIndexedSessionRepositoryCustomizer();
// or PostgreSqlJdbcIndexedSessionRepositoryCustomizer
}
}

connect to alfresco 2017 using alfresco-web-service-client

I am using alfresco-web-service-client 5.0.a, I am trying to login into alfresco-community 2017 which is deployed at : localhost:8081/alfresco.
This is what I've done so far :
import org.alfresco.webservice.authentication.AuthenticationFault;
import org.alfresco.webservice.util.AuthenticationUtils;
import org.alfresco.webservice.util.WebServiceFactory;
public class Main {
public static void main(String[] args) throws AuthenticationFault {
WebServiceFactory.setEndpointAddress("http://localhost:8081/alfresco/api");
AuthenticationUtils.startSession("admin", "admin");
}
}
This is what I get when I run the class :
Exception in thread "main" org.alfresco.webservice.util.WebServiceException: Error starting session.
at org.alfresco.webservice.util.AuthenticationUtils.startSession(AuthenticationUtils.java:99)
at com.lydec.Main.Main.main(Main.java:12)
Caused by: java.net.ConnectException: Connection refused: connect
at org.apache.axis.AxisFault.makeFault(AxisFault.java:101)
at org.apache.axis.transport.http.HTTPSender.invoke(HTTPSender.java:154)
at org.apache.axis.strategies.InvocationStrategy.visit(InvocationStrategy.java:32)
at org.apache.axis.SimpleChain.doVisiting(SimpleChain.java:118)
at org.apache.axis.SimpleChain.invoke(SimpleChain.java:83)
at org.apache.axis.client.AxisClient.invoke(AxisClient.java:165)
at org.apache.axis.client.Call.invokeEngine(Call.java:2784)
at org.apache.axis.client.Call.invoke(Call.java:2767)
at org.apache.axis.client.Call.invoke(Call.java:2443)
at org.apache.axis.client.Call.invoke(Call.java:2366)
at org.apache.axis.client.Call.invoke(Call.java:1812)
at org.alfresco.webservice.authentication.AuthenticationServiceSoapBindingStub.startSession(AuthenticationServiceSoapBindingStub.java:187)
at org.alfresco.webservice.util.AuthenticationUtils.startSession(AuthenticationUtils.java:84)
... 1 more
Caused by: java.net.ConnectException: Connection refused: connect
at java.net.DualStackPlainSocketImpl.waitForConnect(Native Method)
at java.net.DualStackPlainSocketImpl.socketConnect(Unknown Source)
at java.net.AbstractPlainSocketImpl.doConnect(Unknown Source)
at java.net.AbstractPlainSocketImpl.connectToAddress(Unknown Source)
at java.net.AbstractPlainSocketImpl.connect(Unknown Source)
at java.net.PlainSocketImpl.connect(Unknown Source)
at java.net.SocksSocketImpl.connect(Unknown Source)
at java.net.Socket.connect(Unknown Source)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source)
at java.lang.reflect.Method.invoke(Unknown Source)
at org.apache.axis.components.net.DefaultSocketFactory.create(DefaultSocketFactory.java:153)
at org.apache.axis.components.net.DefaultSocketFactory.create(DefaultSocketFactory.java:120)
at org.apache.axis.transport.http.HTTPSender.getSocket(HTTPSender.java:191)
at org.apache.axis.transport.http.HTTPSender.writeToSocket(HTTPSender.java:404)
at org.apache.axis.transport.http.HTTPSender.invoke(HTTPSender.java:138)
... 12 more
pom.xml
You cannot use the old (and unstable) 5.0.a web service client to talk to a modern version of Alfresco on the server.
This link provides information on the changes related to SOAP-based web services.
If you must use SOAP-based web services, use CMIS (sample code).
I would strongly recommend that you instead use REST instead of SOAP-based web services for just about anything. For Alfresco, you can use the new public REST API or you can use CMIS (either the Atom Pub binding or the Browser binding).

undertow + Spring WebApplicationInitializer - Double initialization

I am migrating an old web app. It was written with old web.xml-style, now we want to programmatically build the servlet.
This is a Spring MVC app, deployed as a WAR module in an EAR under Wildfly 10.0.0.Final.
I wrote my implementation of Spring's WebApplicationInitializer (still using Spring XML config at the moment, to preceed step by step - next step will be to migrate to JavaConfig). Though I'm stuck here because the servlet is initialized twice, and the second time the initilization fails due to a filter's name conflict - NullPointerException after filter creation.
This is my initilizer:
public class MyWebApplicationInitializer implements WebApplicationInitializer {
private static final Logger log = LoggerFactory.getLogger(MyWebApplicationInitializer.class);
/**
* #see org.springframework.web.WebApplicationInitializer#onStartup(javax.servlet.ServletContext)
*/
#Override
public void onStartup(ServletContext container) throws ServletException {
log.debug("******* Initializing Web App *******");
XmlWebApplicationContext rootContext = new XmlWebApplicationContext();
rootContext.setConfigLocation("classpath:META-INF/spring/application-context.xml");
XmlWebApplicationContext webContext = new XmlWebApplicationContext();
webContext.setConfigLocation("classpath:META-INF/spring/mvc-context.xml");
container.addListener(new ContextLoaderListener(rootContext));
ServletRegistration.Dynamic dispatcher = container.addServlet("dispatcher", new DispatcherServlet(webContext));
dispatcher.setLoadOnStartup(1);
dispatcher.addMapping("/");
container.addFilter("log4jEnhancementFilter", Log4jEnhancementFilter.class);
log.info("******* Web App correctly initialized *******");
}
}
A bit of log below:
[ServerService Thread Pool -- 74]:[INFO] # 2016-04-19 07:19:27,725: io.undertow.servlet.spec.ServletContextImpl.log:313: Spring WebApplicationInitializers detected on classpath: [com.xyz.web.servlet.MyWebApplicationInitializer#6356dd91]
[ServerService Thread Pool -- 74]:[DEBUG] # 2016-04-19 07:19:27,725: com.xyz.web.servlet.MyWebApplicationInitializer.onStartup:44: ******* Initializing Web App *******
...
[ServerService Thread Pool -- 74]:[INFO] # 2016-04-19 07:19:27,796: com.xyz.web.servlet.MyWebApplicationInitializer.onStartup:59: ******* Web App correctly initialized *******
...
[ServerService Thread Pool -- 74]:[INFO] # 2016-04-19 07:19:27,797: io.undertow.servlet.spec.ServletContextImpl.log:313: Spring WebApplicationInitializers detected on classpath: [com.xyz.web.servlet.MyWebApplicationInitializer#427d3c64]
[ServerService Thread Pool -- 74]:[DEBUG] # 2016-04-19 07:19:27,797: com.xyz.web.servlet.MyWebApplicationInitializer.onStartup:44: ******* Initializing Web App *******
07:19:27,800 ERROR [org.jboss.msc.service.fail] (ServerService Thread Pool -- 74) MSC000001: Failed to start service jboss.undertow.deployment.default-server.default-host./www: org.jboss.msc.service.StartException in service jboss.undertow.deployment.default-server.default-host./www: java.lang.RuntimeException: java.lang.NullPointerException
at org.wildfly.extension.undertow.deployment.UndertowDeploymentService$1.run(UndertowDeploymentService.java:85)
at java.util.concurrent.Executors$RunnableAdapter.call(Executors.java:511)
at java.util.concurrent.FutureTask.run(FutureTask.java:266)
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)
at org.jboss.threads.JBossThread.run(JBossThread.java:320)
Caused by: java.lang.RuntimeException: java.lang.NullPointerException
at io.undertow.servlet.core.DeploymentManagerImpl.deploy(DeploymentManagerImpl.java:231)
at org.wildfly.extension.undertow.deployment.UndertowDeploymentService.startContext(UndertowDeploymentService.java:100)
at org.wildfly.extension.undertow.deployment.UndertowDeploymentService$1.run(UndertowDeploymentService.java:82)
... 6 more
Caused by: java.lang.NullPointerException
at com.xyz.web.servlet.MyWebApplicationInitializer.onStartup(MyWebApplicationInitializer.java:54)
at org.springframework.web.SpringServletContainerInitializer.onStartup(SpringServletContainerInitializer.java:175)
at io.undertow.servlet.core.DeploymentManagerImpl.deploy(DeploymentManagerImpl.java:184)
... 8 more
As you can see there is a double servlet's initilization; the first succeeds, the second fails due to the NPE.
What am I doing wrong and how can I fix it?

sending mail using thymeleaf in Spring Schedular

I am trying to send email using thymeleaf template. But I am getting an error message as
org.thymeleaf.exceptions.TemplateProcessingException: Resource resolution by ServletContext with org.thymeleaf.resourceresolver.ServletContextResourceResolver can only be performed when context implements org.thymeleaf.context.IWebContext [current context: org.thymeleaf.context.Context]
at org.thymeleaf.resourceresolver.ServletContextResourceResolver.getResourceAsStream(ServletContextResourceResolver.java:74)
at org.thymeleaf.TemplateRepository.getTemplate(TemplateRepository.java:221)
at org.thymeleaf.TemplateEngine.process(TemplateEngine.java:1192)
at org.thymeleaf.TemplateEngine.process(TemplateEngine.java:1148)
at org.thymeleaf.TemplateEngine.process(TemplateEngine.java:1095)
at org.thymeleaf.TemplateEngine.process(TemplateEngine.java:1008)
at org.thymeleaf.TemplateEngine.process(TemplateEngine.java:982)
at in.coep.vlabteam.leap.implementations.ScheduleNotificationImpl.sendNotification(ScheduleNotificationImpl.java:205)
at in.coep.vlabteam.leap.implementations.ScheduleNotificationImpl.sendScheduleNotificationMail(ScheduleNotificationImpl.java:105)
at in.coep.vlabteam.leap.services.ScheduleNotificationService.sendScheduleNotificationByMail(ScheduleNotificationService.java:47)
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.scheduling.support.ScheduledMethodRunnable.run(ScheduledMethodRunnable.java:64)
at org.springframework.scheduling.support.DelegatingErrorHandlingRunnable.run(DelegatingErrorHandlingRunnable.java:53)
at org.springframework.scheduling.concurrent.ReschedulingRunnable.run(ReschedulingRunnable.java:81)
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.ScheduledThreadPoolExecutor$ScheduledFutureTask.access$301(ScheduledThreadPoolExecutor.java:98)
at java.util.concurrent.ScheduledThreadPoolExecutor$ScheduledFutureTask.run(ScheduledThreadPoolExecutor.java:206)
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)
10936 [taskScheduler-1] ERROR org.thymeleaf.TemplateEngine - [THYMELEAF][taskScheduler-1] Exception processing template "scheduleMail.html": Resource resolution by ServletContext with org.thymeleaf.resourceresolver.ServletContextResourceResolver can only be performed when context implements org.thymeleaf.context.IWebContext [current context: org.thymeleaf.context.Context]
I cant used WebContext() instead of Context(). Because for webContext I need HttpServletRequest object that I can't get here, because it is not in scope of request.
I am trying to send mail using context(), but I am getting an error.
Please anyone have solution on this. Thanks in advance
Here is my code,
final Context ctx = new Context();
ctx.setVariable("eagletId", user.getEagletId());
ctx.setVariable("name", user.getFirstName());
ctx.setVariable("setSentDate", new Date());
ctx.setVariable("department", user.getDepartment());
ctx.setVariable("batch", user.getBatch());
// ctx.setVariable("month" Constants.LeapConstants.UserType);
// Prepare message using a Spring helper
final MimeMessage mimeMessage = this.mailSender.createMimeMessage();
final MimeMessageHelper message =
new MimeMessageHelper(mimeMessage, true /* multipart */, "UTF-8");
message.setSubject("Create your report for month");
message.setFrom("leap#gmail.com");
message.setTo("vlab#gmail.com");
// Create the HTML body using Thymeleaf
final String htmlContent = this.templateEngine.process("scheduleMail.html", ctx);
message.setText(htmlContent, true /* isHtml */);
// Send mail
this.mailSender.send(mimeMessage);
Your template engine is configured with ServletContextTemplateResolver instead of either FileTemplateResolver or ClassLoaderTemplateResolver. This will be defined most likely in a spring config file somewhere. If configured in code, see the Thymeleaf user's guide on configuring the template engine and configuration of the templateResolver. It's good doc.
Via xml configuration, it should look something like this:
<beans:bean id="templateResolver"
class="org.thymeleaf.templateresolver.ClassLoaderTemplateResolver">
</beans:bean>

What is the relationship between Field 'SYSTEM_PROPERTIES_MODE_ENVIRONMENT' and PropertyPlaceHolderConfigurer?

I am using spring 3.0.6-RELEASE for a basic form based webapp and running into the following error on startup with PropertyPlaceHolderConfigurer. Not sure what's causing this as injecting the property pre-mvc3 was done through beans and now using annotation and it appears quite straight-forward atleast from the docs/other posts.
However the exception during tomcat server startup complains of org.springframework.core.ConstantException: Field 'SYSTEM_PROPERTIES_MODE_ENVIRONMENT' not found in class [org.springframework.beans.factory.config.PropertyPlaceholderConfigurer]
Here is what I have in spring-servlet.xml
<context:property-placeholder location="/WEB-INF/classes/spring.properties"/>
and my controller class
#Controller
#RequestMapping("/home")
public class HomeController {
// #Resource(name="broomManager")
#Autowired
private broomManager broomManager;
private #Value("${spring.broom.maxFileSize}") String inMemoryMaxFileSize;
private #Value("${spring.broom.fileDestination}") String destFilePath;
..
spring.properties
broom.maxFileSize=100000
broom.fileDestination=/Users/foobar/broom/files/
Exception during startup
2012-06-08 02:51:31,900 [ContainerBackgroundProcessor[StandardEngine[Catalina]]] ERROR org.springframework.web.servlet.DispatcherServlet - Context initialization failed
org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'org.springframework.beans.factory.config.PropertyPlaceholderConfigurer#0': Error setting property values; nested exception is org.springframework.beans.PropertyBatchUpdateException; nested PropertyAccessExceptions (1) are:
PropertyAccessException 1: org.springframework.beans.MethodInvocationException: Property 'systemPropertiesModeName' threw exception; nested exception is org.springframework.core.ConstantException: Field 'SYSTEM_PROPERTIES_MODE_ENVIRONMENT' not found in class [org.springframework.beans.factory.config.PropertyPlaceholderConfigurer]
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.applyPropertyValues(AbstractAutowireCapableBeanFactory.java:1361)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.populateBean(AbstractAutowireCapableBeanFactory.java:1086)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:517)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:456)
at org.springframework.beans.factory.support.AbstractBeanFactory$1.getObject(AbstractBeanFactory.java:293)
at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:222)
at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:290)
at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:196)
at org.springframework.context.support.AbstractApplicationContext.invokeBeanFactoryPostProcessors(AbstractApplicationContext.java:626)
at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:407)
at org.springframework.web.servlet.FrameworkServlet.createWebApplicationContext(FrameworkServlet.java:467)
at org.springframework.web.servlet.FrameworkServlet.createWebApplicationContext(FrameworkServlet.java:483)
at org.springframework.web.servlet.FrameworkServlet.initWebApplicationContext(FrameworkServlet.java:358)
at org.springframework.web.servlet.FrameworkServlet.initServletBean(FrameworkServlet.java:325)
at org.springframework.web.servlet.HttpServletBean.init(HttpServletBean.java:127)
at javax.servlet.GenericServlet.init(GenericServlet.java:212)
at org.apache.catalina.core.StandardWrapper.loadServlet(StandardWrapper.java:1139)
at org.apache.catalina.core.StandardWrapper.load(StandardWrapper.java:966)
at org.apache.catalina.core.StandardContext.loadOnStartup(StandardContext.java:3956)
at org.apache.catalina.core.StandardContext.start(StandardContext.java:4230)
at org.apache.catalina.core.ContainerBase.addChildInternal(ContainerBase.java:760)
at org.apache.catalina.core.ContainerBase.addChild(ContainerBase.java:740)
at org.apache.catalina.core.StandardHost.addChild(StandardHost.java:544)
at org.apache.catalina.startup.HostConfig.deployWAR(HostConfig.java:831)
at org.apache.catalina.startup.HostConfig.deployWARs(HostConfig.java:720)
at org.apache.catalina.startup.HostConfig.deployApps(HostConfig.java:490)
at org.apache.catalina.startup.HostConfig.check(HostConfig.java:1217)
at org.apache.catalina.startup.HostConfig.lifecycleEvent(HostConfig.java:293)
at org.apache.catalina.util.LifecycleSupport.fireLifecycleEvent(LifecycleSupport.java:120)
at org.apache.catalina.core.ContainerBase.backgroundProcess(ContainerBase.java:1306)
at org.apache.catalina.core.ContainerBase$ContainerBackgroundProcessor.processChildren(ContainerBase.java:1570)
at org.apache.catalina.core.ContainerBase$ContainerBackgroundProcessor.processChildren(ContainerBase.java:1579)
at org.apache.catalina.core.ContainerBase$ContainerBackgroundProcessor.run(ContainerBase.java:1559)
at java.lang.Thread.run(Thread.java:680)
Caused by: org.springframework.beans.PropertyBatchUpdateException; nested PropertyAccessExceptions (1) are:
PropertyAccessException 1: org.springframework.beans.MethodInvocationException: Property 'systemPropertiesModeName' threw exception; nested exception is org.springframework.core.ConstantException: Field 'SYSTEM_PROPERTIES_MODE_ENVIRONMENT' not found in class [org.springframework.beans.factory.config.PropertyPlaceholderConfigurer]
at org.springframework.beans.AbstractPropertyAccessor.setPropertyValues(AbstractPropertyAccessor.java:102)
at org.springframework.beans.AbstractPropertyAccessor.setPropertyValues(AbstractPropertyAccessor.java:58)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.applyPropertyValues(AbstractAutowireCapableBeanFactory.java:1358)
... 33 more
Probably the following is going on:
Your Spring config files are pointing at the 3.1 schemas.
You are using 3.0.6 JARs.
They need to match.

Resources