weblogic 12.1.2 and spring-security 4.0.3 publishing issue - spring-security

I am work on a project with spring 4.23, spring-security 4.03. The project work fine with weblogic maven plugin, I can deploy to the weblogic with the plugin or use maven to package it into war and manual deploy at admin console.
But when I use the publishing function weird thing happen and the publishing failed, I am pretty sure I have #EnableWebSecurity and #Configuration in my SecurityConfig file
Kindly help me to figure out whats going wrong, thank you.
below is the error:
weblogic.application.ModuleException: java.lang.IllegalStateException: org.springframework.security.config.annotation.ObjectPostProcessor is a required bean. Ensure you have used #EnableWebSecurity and #Configuration
java.lang.Exception: Exception received from deployment driver. See Error Log view for more detail.
at oracle.eclipse.tools.weblogic.server.internal.DeploymentProgressListener.watch(DeploymentProgressListener.java:189)
at oracle.eclipse.tools.weblogic.server.internal.WlsJ2EEDeploymentHelper.redeploy(WlsJ2EEDeploymentHelper.java:644)
at oracle.eclipse.tools.weblogic.server.internal.WlsJ2EEDeploymentHelper.deploy(WlsJ2EEDeploymentHelper.java:474)
at oracle.eclipse.tools.weblogic.server.internal.WeblogicServerBehaviour.publishWeblogicModules(WeblogicServerBehaviour.java:1455)
at oracle.eclipse.tools.weblogic.server.internal.WeblogicServerBehaviour.publishToServer(WeblogicServerBehaviour.java:913)
at oracle.eclipse.tools.weblogic.server.internal.WeblogicServerBehaviour.publishOnce(WeblogicServerBehaviour.java:704)
at oracle.eclipse.tools.weblogic.server.internal.WeblogicServerBehaviour.publish(WeblogicServerBehaviour.java:555)
at org.eclipse.wst.server.core.model.ServerBehaviourDelegate.publish(ServerBehaviourDelegate.java:774)
at org.eclipse.wst.server.core.internal.Server.publishImpl(Server.java:3172)
at org.eclipse.wst.server.core.internal.Server$PublishJob.run(Server.java:345)
at org.eclipse.core.internal.jobs.Worker.run(Worker.java:55)
Caused by: weblogic.application.ModuleException: java.lang.IllegalStateException: org.springframework.security.config.annotation.ObjectPostProcessor is a required bean. Ensure you have used #EnableWebSecurity and #Configuration
at weblogic.application.internal.ExtensibleModuleWrapper.start(ExtensibleModuleWrapper.java:140)
at weblogic.application.internal.flow.ModuleListenerInvoker.start(ModuleListenerInvoker.java:124)
at weblogic.application.internal.flow.ModuleStateDriver$3.next(ModuleStateDriver.java:213)
at weblogic.application.internal.flow.ModuleStateDriver$3.next(ModuleStateDriver.java:208)
at weblogic.application.utils.StateMachineDriver.nextState(StateMachineDriver.java:42)
at weblogic.application.internal.flow.ModuleStateDriver.start(ModuleStateDriver.java:70)
at weblogic.application.internal.flow.StartModulesFlow.activate(StartModulesFlow.java:24)
at weblogic.application.internal.BaseDeployment$2.next(BaseDeployment.java:729)
at weblogic.application.utils.StateMachineDriver.nextState(StateMachineDriver.java:42)
at weblogic.application.internal.BaseDeployment.activate(BaseDeployment.java:258)
at weblogic.application.internal.SingleModuleDeployment.activate(SingleModuleDeployment.java:48)
at weblogic.application.internal.DeploymentStateChecker.activate(DeploymentStateChecker.java:165)
at weblogic.deploy.internal.targetserver.AppContainerInvoker.activate(AppContainerInvoker.java:80)
at weblogic.deploy.internal.targetserver.operations.AbstractOperation.activate(AbstractOperation.java:586)
at weblogic.deploy.internal.targetserver.operations.ActivateOperation.activateDeployment(ActivateOperation.java:148)
at weblogic.deploy.internal.targetserver.operations.ActivateOperation.doCommit(ActivateOperation.java:114)
at weblogic.deploy.internal.targetserver.operations.AbstractOperation.commit(AbstractOperation.java:339)
at weblogic.deploy.internal.targetserver.DeploymentManager.handleDeploymentCommit(DeploymentManager.java:846)
at weblogic.deploy.internal.targetserver.DeploymentManager.activateDeploymentList(DeploymentManager.java:1275)
at weblogic.deploy.internal.targetserver.DeploymentManager.handleCommit(DeploymentManager.java:442)
at weblogic.deploy.internal.targetserver.DeploymentServiceDispatcher.commit(DeploymentServiceDispatcher.java:176)
at weblogic.deploy.service.internal.targetserver.DeploymentReceiverCallbackDeliverer.doCommitCallback(DeploymentReceiverCallbackDeliverer.java:195)
at weblogic.deploy.service.internal.targetserver.DeploymentReceiverCallbackDeliverer.access$100(DeploymentReceiverCallbackDeliverer.java:13)
at weblogic.deploy.service.internal.targetserver.DeploymentReceiverCallbackDeliverer$2.run(DeploymentReceiverCallbackDeliverer.java:68)
at weblogic.work.SelfTuningWorkManagerImpl$WorkAdapterImpl.run(SelfTuningWorkManagerImpl.java:550)
at weblogic.work.ExecuteThread.execute(ExecuteThread.java:295)
at weblogic.work.ExecuteThread.run(ExecuteThread.java:254)
Caused by: java.lang.IllegalStateException: org.springframework.security.config.annotation.ObjectPostProcessor is a required bean. Ensure you have used #EnableWebSecurity and #Configuration
at org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter$1.postProcess(WebSecurityConfigurerAdapter.java:79)
at org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter.getHttp(WebSecurityConfigurerAdapter.java:172)
at org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter.init(WebSecurityConfigurerAdapter.java:290)
at com.gammon.pcms.config.SecurityConfig.init(SecurityConfig.java:0)
at org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter.init(WebSecurityConfigurerAdapter.java:67)
at com.gammon.pcms.config.SecurityConfig.init(SecurityConfig.java:0)
at com.gammon.pcms.config.SecurityConfig$$EnhancerBySpringCGLIB$$66e1b5df.init(<generated>:0)
at org.springframework.security.config.annotation.AbstractConfiguredSecurityBuilder.init(AbstractConfiguredSecurityBuilder.java:370)
at org.springframework.security.config.annotation.AbstractConfiguredSecurityBuilder.doBuild(AbstractConfiguredSecurityBuilder.java:324)
at org.springframework.security.config.annotation.AbstractSecurityBuilder.build(AbstractSecurityBuilder.java:41)
at org.springframework.security.config.annotation.web.configuration.WebSecurityConfiguration.springSecurityFilterChain(WebSecurityConfiguration.java:105)
at org.springframework.security.config.annotation.web.configuration.WebSecurityConfiguration$$EnhancerBySpringCGLIB$$d9c7728c.CGLIB$springSecurityFilterChain$2(<generated>:0)
at org.springframework.security.config.annotation.web.configuration.WebSecurityConfiguration$$EnhancerBySpringCGLIB$$d9c7728c$$FastClassBySpringCGLIB$$d5f1163a.invoke(<generated>:0)
at org.springframework.cglib.proxy.MethodProxy.invokeSuper(MethodProxy.java:228)
at org.springframework.context.annotation.ConfigurationClassEnhancer$BeanMethodInterceptor.intercept(ConfigurationClassEnhancer.java:318)
at org.springframework.security.config.annotation.web.configuration.WebSecurityConfiguration$$EnhancerBySpringCGLIB$$d9c7728c.springSecurityFilterChain(<generated>:0)
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:606)
at org.springframework.beans.factory.support.SimpleInstantiationStrategy.instantiate(SimpleInstantiationStrategy.java:162)
at org.springframework.beans.factory.support.ConstructorResolver.instantiateUsingFactoryMethod(ConstructorResolver.java:588)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.instantiateUsingFactoryMethod(AbstractAutowireCapableBeanFactory.java:1123)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBeanInstance(AbstractAutowireCapableBeanFactory.java:1018)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:510)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:482)
at org.springframework.beans.factory.support.AbstractBeanFactory$1.getObject(AbstractBeanFactory.java:306)
at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:230)
at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:302)
at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:197)
at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:296)
at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:197)
at org.springframework.beans.factory.support.DefaultListableBeanFactory.preInstantiateSingletons(DefaultListableBeanFactory.java:772)
at org.springframework.context.support.AbstractApplicationContext.finishBeanFactoryInitialization(AbstractApplicationContext.java:838)
at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:537)
at org.springframework.web.context.ContextLoader.configureAndRefreshWebApplicationContext(ContextLoader.java:446)
at org.springframework.web.context.ContextLoader.initWebApplicationContext(ContextLoader.java:328)
at org.springframework.web.context.ContextLoaderListener.contextInitialized(ContextLoaderListener.java:107)
at weblogic.servlet.internal.EventsManager$FireContextListenerAction.run(EventsManager.java:661)
at weblogic.security.acl.internal.AuthenticatedSubject.doAs(AuthenticatedSubject.java:321)
at weblogic.security.service.SecurityManager.runAs(SecurityManager.java:120)
at weblogic.servlet.provider.WlsSubjectHandle.run(WlsSubjectHandle.java:57)
at weblogic.servlet.internal.EventsManager.executeContextListener(EventsManager.java:241)
at weblogic.servlet.internal.EventsManager.notifyContextCreatedEvent(EventsManager.java:198)
at weblogic.servlet.internal.EventsManager.notifyContextCreatedEvent(EventsManager.java:186)
at weblogic.servlet.internal.WebAppServletContext.preloadResources(WebAppServletContext.java:1783)
at weblogic.servlet.internal.WebAppServletContext.start(WebAppServletContext.java:2807)
at weblogic.servlet.internal.WebAppModule.startContexts(WebAppModule.java:1661)
at weblogic.servlet.internal.WebAppModule.start(WebAppModule.java:822)
at weblogic.application.internal.ExtensibleModuleWrapper$StartStateChange.next(ExtensibleModuleWrapper.java:360)
at weblogic.application.internal.ExtensibleModuleWrapper$StartStateChange.next(ExtensibleModuleWrapper.java:356)
at weblogic.application.utils.StateMachineDriver.nextState(StateMachineDriver.java:42)
at weblogic.application.internal.ExtensibleModuleWrapper.start(ExtensibleModuleWrapper.java:138)

I fixed this with the help of below link:
https://github.com/spring-projects/spring-loaded/issues/49
I override below method in my SecurityConfig:
#Override
#Autowired
public void setObjectPostProcessor(ObjectPostProcessor<Object> objectPostProcessor) {
super.setObjectPostProcessor(objectPostProcessor);
}
#Override
#Autowired
public void setApplicationContext(ApplicationContext context) {
super.setApplicationContext(context);
}
#Override
#Autowired
public void setAuthenticationConfiguration(AuthenticationConfiguration authenticationConfiguration) {
super.setAuthenticationConfiguration(authenticationConfiguration);
}
Look like the classloader of publish is work different via publishing and maven/manual deploy, some #Autowired is not working.
I have a base class for other controller to extend but the #Autowired is not working, I have to #Override the setter in child class...
public abstract class GWTSpringController extends PersistentRemoteService implements Controller, ServletContextAware {
#Override
#Autowired // <-- this not work
public void setBeanManager(PersistentBeanManager manager) {
super.setBeanManager(manager);
}
...
}
#Service
public class UserServiceController extends GWTSpringController implements UserServiceRemote{
#Override
#Autowired // I need to override the setter in all child class...
public void setBeanManager(PersistentBeanManager manager) {
super.setBeanManager(manager);
}
...
}

Related

Customizing OpenSaml4AuthenticationProvider in Spring Security SAML2

I need to use a legacy UserDetailsService with Spring Security SAML2, so I'm following these instructions from Spring. However, I get an error when I just try to replace the AuthenticationProvider with the supposedly "default" one according to that documentation:
public class WigWebSecurityConfiguration extends WebSecurityConfigurerAdapter {
#Override
protected void configure(HttpSecurity httpSecurity) throws Exception {
OpenSaml4AuthenticationProvider authenticationProvider = new OpenSaml4AuthenticationProvider();
// I've tried removing these 2 lines and I get the same error
authenticationProvider.setAssertionValidator(OpenSaml4AuthenticationProvider.createDefaultAssertionValidator());
authenticationProvider.setResponseAuthenticationConverter(OpenSaml4AuthenticationProvider.createDefaultResponseAuthenticationConverter());
httpSecurity.authorizeRequests(authz -> authz.anyRequest().authenticated())
.saml2Login(saml2 -> saml2.authenticationManager(new ProviderManager(authenticationProvider)));
}
}
When I do this, I get the following error when I try to authenticate:
java.lang.NoSuchMethodError: org.opensaml.saml.saml2.assertion.SAML20AssertionValidator.<init>(Ljava/util/Collection;Ljava/util/Collection;Ljava/util/Collection;Lorg/opensaml/saml/saml2/assertion/AssertionValidator;Lorg/opensaml/xmlsec/signature/support/SignatureTrustEngine;Lorg/opensaml/xmlsec/signature/support/SignaturePrevalidator;)V
at org.springframework.security.saml2.provider.service.authentication.OpenSaml4AuthenticationProvider$SAML20AssertionValidators$3.<init>(OpenSaml4AuthenticationProvider.java:732)
at org.springframework.security.saml2.provider.service.authentication.OpenSaml4AuthenticationProvider$SAML20AssertionValidators.<clinit>(OpenSaml4AuthenticationProvider.java:731)
at org.springframework.security.saml2.provider.service.authentication.OpenSaml4AuthenticationProvider.lambda$createDefaultAssertionSignatureValidator$8(OpenSaml4AuthenticationProvider.java:572)
at org.springframework.security.saml2.provider.service.authentication.OpenSaml4AuthenticationProvider.lambda$createAssertionValidator$11(OpenSaml4AuthenticationProvider.java:654)
at org.springframework.security.saml2.provider.service.authentication.OpenSaml4AuthenticationProvider.process(OpenSaml4AuthenticationProvider.java:495)
at org.springframework.security.saml2.provider.service.authentication.OpenSaml4AuthenticationProvider.authenticate(OpenSaml4AuthenticationProvider.java:448)
at org.springframework.security.authentication.ProviderManager.authenticate(ProviderManager.java:182)
at org.springframework.security.saml2.provider.service.servlet.filter.Saml2WebSsoAuthenticationFilter.attemptAuthentication(Saml2WebSsoAuthenticationFilter.java:113)
at org.springframework.security.web.authentication.AbstractAuthenticationProcessingFilter.doFilter(AbstractAuthenticationProcessingFilter.java:222)
at org.springframework.security.web.authentication.AbstractAuthenticationProcessingFilter.doFilter(AbstractAuthenticationProcessingFilter.java:212)
at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:336)
But when I use the same code without setting the authenticationManager, then the SAML authentication works fine. (Any page that wants to use my custom UserDetails fails of course, because it's not being populated, but all the SAML authentication steps are working fine.):
public class WigWebSecurityConfiguration extends WebSecurityConfigurerAdapter {
#Override
protected void configure(HttpSecurity httpSecurity) throws Exception {
httpSecurity.authorizeRequests(authz -> authz.anyRequest().authenticated())
.saml2Login();
}
}
It turns out that I was using org.opensaml:opensaml-api 3.4.6, and you need to be using 4.x to use the class OpenSaml4AuthenticationProvider. If you're using 3.x you need to use the deprecated class OpenSamlAuthenticationProvider. I wasn't able to upgrade the opensaml dependency because I'm using Java 8, so this is the code that works for me:
public class WigWebSecurityConfiguration extends WebSecurityConfigurerAdapter {
#Override
protected void configure(HttpSecurity httpSecurity) throws Exception {
// This class is deprecated, but you have to use it if you're using OpenSAML < 4.0
OpenSamlAuthenticationProvider authenticationProvider = new OpenSamlAuthenticationProvider();
authenticationProvider.setAssertionValidator(OpenSamlAuthenticationProvider.createDefaultAssertionValidator());
authenticationProvider.setResponseAuthenticationConverter(OpenSamlAuthenticationProvider.createDefaultResponseAuthenticationConverter());
httpSecurity.authorizeRequests(authz -> authz.anyRequest().authenticated())
.saml2Login(saml2 -> saml2.authenticationManager(new ProviderManager(authenticationProvider)));
}
}
I finally found the answer when I discovered that that is what Saml2LoginConfigurer does internally.

Spring elasticsearch java.net.UnknownHostException

Trying to update a small experimental Spring Elasticsearch project to reflect changes in the 3.2.6 release reference guide.
As noted: TransportClient is deprecated as of Elasticsearch 7 and will be removed in 8. Trying to reconfig to High Level Rest Client.
But getting the following errors
Application run failed
org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'elasticDatasource' defined in file [/Users/erichuang/Desktop/JE/00-Development/dev/lab/lab-elastic-search/lab-elastic-search/target/classes/com/elastic/labelasticsearch/config/ElasticDatasource.class]: Unsatisfied dependency expressed through constructor parameter 0; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'carElasticRepo': Invocation of init method failed; nested exception is org.springframework.beans.BeanInstantiationException: Failed to instantiate [org.springframework.data.elasticsearch.repository.support.SimpleElasticsearchRepository]: Constructor threw exception; nested exception is org.springframework.data.elasticsearch.ElasticsearchException: Error while for indexExists request: org.elasticsearch.action.admin.indices.get.GetIndexRequest#b5d8ebb
org.springframework.boot.web.servlet.context.ServletWebServerApplicationContext.refresh(ServletWebServerApplicationContext.java:141)
com.elastic.labelasticsearch.LabElasticSearchApplication.main(LabElasticSearchApplication.java:15)
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:564)
at org.springframework.boot.devtools.restart.RestartLauncher.run(RestartLauncher.java:49)
Caused by: org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'carElasticRepo': Invocation of init method failed; nested exception is org.springframework.beans.BeanInstantiationException: Failed to instantiate [org.springframework.data.elasticsearch.repository.support.SimpleElasticsearchRepository]: Constructor threw exception; nested exception is org.springframework.data.elasticsearch.ElasticsearchException: Error while for indexExists request: org.elasticsearch.action.admin.indices.get.GetIndexRequest#b5d8ebb
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.initializeBean(AbstractAutowireCapableBeanFactory.java:1796)
... 24 common frames omitted
Caused by: java.net.UnknownHostException: localhost/<unresolved>: nodename nor servname provided, or not known
at java.base/java.net.Inet6AddressImpl.lookupAllHostAddr(Native Method)
at java.base/java.net.InetAddress$PlatformNameService.lookupAllHostAddr(InetAddress.java:932)
at java.base/java.net.InetAddress.getAddressesFromNameService(InetAddress.java:1505)
at java.base/java.net.InetAddress$NameServiceAddresses.get(InetAddress.java:851)
at java.base/java.net.InetAddress.getAllByName0(InetAddress.java:1495)
at java.base/java.net.InetAddress.getAllByName(InetAddress.java:1354)
at java.base/java.net.InetAddress.getAllByName(InetAddress.java:1288)
...
... 63 common frames omitted
Old setup (works)
ElasticSearchConfig
#Configuration
#EnableElasticsearchRepositories(basePackages = "com.elastic.labelasticsearch.repo")
public class ElasticSearchConfig {
private static final String esHost = "localhost";
private static final int esPort = 9300;
#Bean
public Client client() throws UnknownHostException {
var transportClient = new PreBuiltTransportClient(Settings.EMPTY);
transportClient.addTransportAddress(new TransportAddress(InetAddress.getByName(esHost), esPort));
return transportClient;
}
#Bean(name ={"elasticsearchOperations", "elasticsearchTemplate"})
public ElasticsearchOperations esTemplate() throws UnknownHostException {
return new ElasticsearchTemplate(client());
}
#Bean
public RestTemplate restTemplate(){
return new RestTemplate();
}
}
New Setup
#Configuration
#EnableElasticsearchRepositories(basePackages = "com.elastic.labelasticsearch.repo")
public class RestClientConfig extends AbstractElasticsearchConfiguration {
#Override
#Bean
public RestHighLevelClient elasticsearchClient() {
final ClientConfiguration clientConfiguration = ClientConfiguration.builder()
.connectedTo("localhost:9300")
.build();
return RestClients.create(clientConfiguration).rest();
}
}
What am I missing?
This is a bug resulting from as change in Java 14 in the java.net.InetSocketAddress.toString() method. This has been fixed in 4.0.RC2 (released yesterday).
Edit: I will backport this into the 3.2 branch as well
You will need to configure your bean using this way that allow to separate the host port and http protocol used:
#Configuration
#EnableElasticsearchRepositories(basePackages = "*")
public class ElasticsearchClientConfig {
#Value("${elasticsearch.host}")
private String host;
#Value("${elasticsearch.port}")
private int port;
#Value("${elasticsearch.protocol}")
private String protocol;
#Value("${elasticsearch.username}")
private String userName;
#Value("${elasticsearch.password}")
private String password;
#Bean(destroyMethod = "close")
public RestHighLevelClient restClient() {
final CredentialsProvider credentialsProvider = new BasicCredentialsProvider();
credentialsProvider.setCredentials(AuthScope.ANY, new UsernamePasswordCredentials(userName, password));
RestClientBuilder builder = RestClient.builder(new HttpHost(host, port, protocol)).setHttpClientConfigCallback(httpClientBuilder -> httpClientBuilder.setDefaultCredentialsProvider(credentialsProvider));
RestHighLevelClient client = new RestHighLevelClient(builder);
return client;
}
}

Spring data neo4j repositories not working since DATAGRAPH-939

I'm using:
Spring-data-neo4j 4.2.0-SNAPSHOT (tried with 4.2.0.RC1 too)
and since the DATAGRAPH-939 commit, I'm not able to work with repositories anymore.
#Repository
public interface MyEventRepository extends GraphRepository<Event> {}
The error:
Caused by: org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'myEventRepository': Unsatisfied dependency expressed through constructor parameter 0; nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type 'java.lang.Class<org.springframework.data.repository.Repository<?, ?>>' available: expected at least 1 bean which qualifies as autowire candidate. Dependency annotations: {}
at org.springframework.beans.factory.support.ConstructorResolver.createArgumentArray(ConstructorResolver.java:749)
at org.springframework.beans.factory.support.ConstructorResolver.autowireConstructor(ConstructorResolver.java:189)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.autowireConstructor(AbstractAutowireCapableBeanFactory.java:1148)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBeanInstance(AbstractAutowireCapableBeanFactory.java:1050)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:512)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:482)
at org.springframework.beans.factory.support.AbstractBeanFactory$1.getObject(AbstractBeanFactory.java:306)
at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:230)
at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:302)
at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:197)
at org.springframework.beans.factory.support.DefaultListableBeanFactory.preInstantiateSingletons(DefaultListableBeanFactory.java:735)
at org.springframework.context.support.AbstractApplicationContext.finishBeanFactoryInitialization(AbstractApplicationContext.java:866)
at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:542)
at org.springframework.test.context.support.AbstractGenericContextLoader.loadContext(AbstractGenericContextLoader.java:128)
at org.springframework.test.context.support.AbstractGenericContextLoader.loadContext(AbstractGenericContextLoader.java:60)
at org.springframework.test.context.cache.DefaultCacheAwareContextLoaderDelegate.loadContextInternal(DefaultCacheAwareContextLoaderDelegate.java:98)
at org.springframework.test.context.cache.DefaultCacheAwareContextLoaderDelegate.loadContext(DefaultCacheAwareContextLoaderDelegate.java:116)
... 25 common frames omitted
Caused by: org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type 'java.lang.Class<org.springframework.data.repository.Repository<?, ?>>' available: expected at least 1 bean which qualifies as autowire candidate. Dependency annotations: {}
at org.springframework.beans.factory.support.DefaultListableBeanFactory.raiseNoMatchingBeanFound(DefaultListableBeanFactory.java:1466)
at org.springframework.beans.factory.support.DefaultListableBeanFactory.doResolveDependency(DefaultListableBeanFactory.java:1097)
at org.springframework.beans.factory.support.DefaultListableBeanFactory.resolveDependency(DefaultListableBeanFactory.java:1059)
at org.springframework.beans.factory.support.ConstructorResolver.resolveAutowiredArgument(ConstructorResolver.java:835)
at org.springframework.beans.factory.support.ConstructorResolver.createArgumentArray(ConstructorResolver.java:741)
... 41 common frames omitted
Here is an example of my failing test:
#RunWith(SpringJUnit4ClassRunner.class)
#ContextConfiguration(loader = AnnotationConfigContextLoader.class, classes = { SimpleTest.TestConfiguration.class })
public class SimpleTest {
#Configuration
#EnableNeo4jRepositories("com.nagra.ml.sp.cpm.core.repositories.test")
public static class TestConfiguration {
#Bean
public org.neo4j.ogm.config.Configuration configuration() {
org.neo4j.ogm.config.Configuration config = new org.neo4j.ogm.config.Configuration();
config .driverConfiguration()
.setDriverClassName("org.neo4j.ogm.drivers.embedded.driver.EmbeddedDriver");
return config;
}
#Bean
public SessionFactory sessionFactory() {
return new SessionFactory(configuration(), "com.nagra.ml.sp.cpm.model");
}
#Bean
public Neo4jTransactionManager transactionManager() {
return new Neo4jTransactionManager(sessionFactory());
}
}
#Test
public void test() {
assertTrue(true);
}
}
According to documentation, the way of declaring repositories seems to be correct, am I doing something wrong ?
Thanks
I no longer have issues with repositories. I'm now using SDN 4.2.0.RELEASE with Spring boot 1.5.1 and I no longer extends GraphRepository as explained in SDN4.2.0 documentation.

Circular reference trying to configure custom permission evaluator in spring security

I'm trying to configure a custom permission evaluator but whenever the app starts up it's complaining of a circular reference.
The configuration code is:
#Configuration
#EnableGlobalMethodSecurity(prePostEnabled = true, proxyTargetClass = true)
public class MethodSecurityConfig extends GlobalMethodSecurityConfiguration {
private static Logger logger = LogManager.getLogger(MethodSecurityConfig.class.getName());
#Autowired
DataSource dataSource;
#Autowired
Environment env;
#Autowired
AuthenticationManager auth;
public MethodSecurityConfig() {
logger.debug("Loading method security config.");
}
#Override
protected AuthenticationManager authenticationManager() throws Exception {
return auth;
}
/**
* Override to set up the custom expression handler.
* #return The custom expression handler
*/
#Override
protected MethodSecurityExpressionHandler createExpressionHandler() {
return expressionHandler();
}
/**
* Defines a custom permission evaluator to evaluate the access permissions for Spring security.
* #return The default expression handler configured with a custom permission evaluator.
*/
#Bean
public DefaultMethodSecurityExpressionHandler expressionHandler(){
DefaultMethodSecurityExpressionHandler handler = new DefaultMethodSecurityExpressionHandler();
handler.setPermissionEvaluator(permissionEvaluator());
return handler;
}
/**
* Custom implementation of a permission evaluator
* #return An instance of {#link BasePermissionEvaluator}
*/
#Bean
public PermissionEvaluator permissionEvaluator() {
return new BasePermissionEvaluator();
}
}
When the app start up this exception occurs:
Caused by: org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'methodSecurityConfig': Injection of autowired dependencies failed; nested exception is org.springframework.beans.factory.BeanCreationException: Could not autowire method: public void org.springframework.security.config.annotation.method.configuration.GlobalMethodSecurityConfiguration.setPermissionEvaluator(java.util.List); nested exception is org.springframework.beans.factory.BeanCurrentlyInCreationException: Error creating bean with name 'permissionEvaluator': Requested bean is currently in creation: Is there an unresolvable circular reference?
at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor.postProcessPropertyValues(AutowiredAnnotationBeanPostProcessor.java:334) ~[AutowiredAnnotationBeanPostProcessor.class:4.2.1.RELEASE]
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.populateBean(AbstractAutowireCapableBeanFactory.java:1214) ~[AbstractAutowireCapableBeanFactory.class:4.2.1.RELEASE]
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:543) ~[AbstractAutowireCapableBeanFactory.class:4.2.1.RELEASE]
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:482) ~[AbstractAutowireCapableBeanFactory.class:4.2.1.RELEASE]
at org.springframework.beans.factory.support.AbstractBeanFactory$1.getObject(AbstractBeanFactory.java:305) ~[AbstractBeanFactory$1.class:4.2.1.RELEASE]
at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:230) ~[DefaultSingletonBeanRegistry.class:4.2.1.RELEASE]
at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:301) ~[AbstractBeanFactory.class:4.2.1.RELEASE]
at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:196) ~[AbstractBeanFactory.class:4.2.1.RELEASE]
at org.springframework.beans.factory.support.ConstructorResolver.instantiateUsingFactoryMethod(ConstructorResolver.java:368) ~[ConstructorResolver.class:4.2.1.RELEASE]
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.instantiateUsingFactoryMethod(A
What am I doing wrong here? I tried various things like adding the AuthenticationManager. Is there something else I need to override?
I had faced the same issue. In my case the reason was there was another security configuration class which has #EnableGlobalMethodSecurity annotation. Removing that annotation solved the issue.
The reason to have two security configuration classes is described here.
To my understanding this happens when Spring first processes the other configuration class, because of #EnableGlobalMethodSecurity permissionEvaluator and similar beans are registered that time and later when this configuration class is processed we got this error.
Also looks like this behaviour is arbitrary, depends on which configuration class is first processed based on classpath ordering.

Is it possible to use Neo4j OGM Converter as a Spring #Component?

I have a custom converter annotated as a #Component and it depends on MyBean which is injected by Spring via #Autowired at boot time.
MyEntity has a field MyObject to be converted by that converter. OGM will call toEntityAttribute from MyObjectToStringConverter as soon as I retrieve MyEntity from Neo4j. However, I'm getting a NPE. It seems OGM does not reuse my converter created by Spring and MyBean dependency is always NULL.
Should OGM be able to get my converter from Spring context?
Is there a way MyBean could be initialized by OGM?
If not, can I register a converter by myselft?
#NodeEntity
class MyEntity {
#Convert(MyObjectToStringConverter.class)
private MyObject myObject;
...
}
#Component
class MyObjectToStringConverter implements AttributeConverter<MyObject, String> {
#Autowired
private MyBean myBean;
#Override
public String toGraphProperty(MyObject value) {
return value.getName();
}
#Override
public MyObject toEntityAttribute(String value) {
return myBean.convert(value); // myBean is NULL
}
}
...
repository.find(myEntityID) // NPE from MyObjectToStringConverter
java.lang.NullPointerException: null
at org.myproject.mvc.converter.MyObjectToStringConverter.toEntityAttribute(MyObjectToStringConverter.java:25)
at org.myproject.mvc.converter.MyObjectToStringConverter.toEntityAttribute(MyObjectToStringConverter.java:12)
at org.neo4j.ogm.entityaccess.FieldWriter.write(FieldWriter.java:64)
at org.neo4j.ogm.mapper.GraphEntityMapper.writeProperty(GraphEntityMapper.java:162)
at org.neo4j.ogm.mapper.GraphEntityMapper.setProperties(GraphEntityMapper.java:127)
at org.neo4j.ogm.mapper.GraphEntityMapper.mapNodes(GraphEntityMapper.java:108)
at org.neo4j.ogm.mapper.GraphEntityMapper.mapEntities(GraphEntityMapper.java:92)
at org.neo4j.ogm.mapper.GraphEntityMapper.map(GraphEntityMapper.java:67)
at org.neo4j.ogm.session.response.SessionResponseHandler.loadById(SessionResponseHandler.java:161)
at org.neo4j.ogm.session.delegates.LoadOneDelegate.load(LoadOneDelegate.java:45)
at org.neo4j.ogm.session.delegates.LoadOneDelegate.load(LoadOneDelegate.java:36)
at org.neo4j.ogm.session.Neo4jSession.load(Neo4jSession.java:99)
at org.springframework.data.neo4j.repository.GraphRepositoryImpl.findOne(GraphRepositoryImpl.java:60)
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.data.repository.core.support.RepositoryFactorySupport$QueryExecutorMethodInterceptor.executeMethodOn(RepositoryFactorySupport.java:483)
at org.springframework.data.repository.core.support.RepositoryFactorySupport$QueryExecutorMethodInterceptor.doInvoke(RepositoryFactorySupport.java:468)
at org.springframework.data.repository.core.support.RepositoryFactorySupport$QueryExecutorMethodInterceptor.invoke(RepositoryFactorySupport.java:440)
at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:179)
at org.springframework.data.projection.DefaultMethodInvokingMethodInterceptor.invoke(DefaultMethodInvokingMethodInterceptor.java:61)
at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:179)
at org.springframework.transaction.interceptor.TransactionInterceptor$1.proceedWithInvocation(TransactionInterceptor.java:99)
at org.springframework.transaction.interceptor.TransactionAspectSupport.invokeWithinTransaction(TransactionAspectSupport.java:281)
at org.springframework.transaction.interceptor.TransactionInterceptor.invoke(TransactionInterceptor.java:96)
at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:179)
at org.springframework.dao.support.PersistenceExceptionTranslationInterceptor.invoke(PersistenceExceptionTranslationInterceptor.java:136)
at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:179)
at org.springframework.aop.interceptor.ExposeInvocationInterceptor.invoke(ExposeInvocationInterceptor.java:92)
at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:179)
at org.springframework.aop.framework.JdkDynamicAopProxy.invoke(JdkDynamicAopProxy.java:208)
at com.sun.proxy.$Proxy87.findOne(Unknown Source)
at org.myproject.mvc.service.AbstractService.find(AbstractService.java:40)
The OGM will not get the converter from the Spring context- it has no dependencies at all on Spring. Perhaps you can use Springs ConversionService?
http://docs.spring.io/spring-data/neo4j/docs/4.0.0.RELEASE/reference/html/#_spring_s_conversionservice

Resources