Started stub server for project [] on port -1 - spring-cloud-contract

I am trying to create a single (fat) spring boot jar for consumer with producer's stub as a dependency to it. With this, when i start-up the consumer app, it should start the contract stub as well.
Here is what I have done so far:
I used this pom example (https://github.com/spring-cloud-samples/spring-cloud-contract-samples/blob/master/producer_with_external_contracts/pom.xml#L98) and created a fat jar for producer
producer.pom
<plugin>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-contract-maven-plugin</artifactId>
<version>${spring-cloud-contract.version}</version>
<configuration>
<baseClassMappings>
<baseClassMapping>
<contractPackageRegex>.*contract.*</contractPackageRegex>
</baseClassMapping>
</baseClassMappings>
<contractDependency>
<groupId>com.groupId</groupId>
<artifactId>producer</artifactId>
</contractDependency>
<contractsMode>LOCAL</contractsMode>
<classifier>stubs</classifier>
<basePackageForTests>com.groupId.producer</basePackageForTests>
<convertToYaml>true</convertToYaml>
</configuration>
</plugin>
This is then imported into my consumer.pom like below:
<dependency>
<groupId>com.groupId</groupId>
<artifactId>producer</artifactId>
<version>0.0.1-SNAPSHOT</version>
</dependency>
The application properties are as below:
producer - application.properties
server.port=8081
consumer - application.properties
stubrunner.ids=com.groupId:producer:+:stubs:8081
stubrunner.stubsMode=LOCAL
stubrunner.repositoryRoot=com.groupId.producer
stubrunner.minPort=8081
ControllerTests.java
#RunWith(SpringRunner.class)
#SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.MOCK)
#AutoConfigureMockMvc
#AutoConfigureJsonTesters
#AutoConfigureStubRunner( ids = "com.groupId:producer:+:stubs:8081",
stubsMode = StubRunnerProperties.StubsMode.LOCAL )
#DirtiesContext
public class ContractTests extends AbstractTest {
...
}
ConsumerApplication.java
#SpringBootApplication
#EnableWebMvc
#EnableStubRunnerServer
#Slf4j
public class ConsumerApplication {
...
}
ContractService.java
public class ContractService {
public #ResponseBody MockResponse verifyWithContract(SomeObj someObj) {
ResponseEntity<MockResponse> response = this.restTemplate.exchange(
RequestEntity
.post(URI.create( http://localhost:8081/someEndpoint ))
.contentType(MediaType.APPLICATION_JSON)
.body(someObj), MockResponse.class);
return response.getBody();
}
}
I have 2 issues:
When I run my test I get the below exception:
org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'org.springframework.cloud.contract.stubrunner.server.HttpStubsController': Unsatisfied dependency expressed through constructor parameter 0; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'batchStubRunner' defined in org.springframework.cloud.contract.stubrunner.spring.StubRunnerConfiguration: Bean instantiation via factory method failed; nested exception is org.springframework.beans.BeanInstantiationException: Failed to instantiate [org.springframework.cloud.contract.stubrunner.BatchStubRunner]: Factory method 'batchStubRunner' threw exception; nested exception is java.lang.IllegalStateException: Remote repositories for stubs are not specified and work offline flag wasn't passed
at org.springframework.beans.factory.support.ConstructorResolver.createArgumentArray(ConstructorResolver.java:769) ~[spring-beans-5.1.5.RELEASE.jar:5.1.5.RELEASE]
at org.springframework.beans.factory.support.ConstructorResolver.autowireConstructor(ConstructorResolver.java:218) ~[spring-beans-5.1.5.RELEASE.jar:5.1.5.RELEASE]
I have also tried the below in test but that didn't help:
#AutoConfigureStubRunner( ids = "com.groupId:producer:+:stubs:8081",
stubsMode = StubRunnerProperties.StubsMode.REMOTE, rootRepository="com.groupId.producer" )
Ignoring the test failures, when i start the application, it starts fine with the below log lines
2019-04-09 11:38:50.454 INFO 75383 --- [ main] o.s.c.contract.stubrunner.StubServer : Started stub server for project [com.groupId:producer:0.0.1-SNAPSHOT:stubs] on port -1
2019-04-09 11:38:50.454 INFO 75383 --- [ main] o.s.c.c.stubrunner.StubRunnerExecutor : All stubs are now running RunningStubs [namesAndPorts={com.gorupId:producer:0.0.1-SNAPSHOT:stubs=-1}]
2019-04-09 11:38:50.673 INFO 75383 --- [ main] o.s.b.w.embedded.tomcat.TomcatWebServer : Tomcat started on port(s): 8080 (https) with context path ''
but when i send a request to the rest URL: https://localhost:8080/someEndpoint
it returns the below error:
{
"timestamp": 1554837050058,
"status": 500,
"error": "Internal Server Error",
"message": "I/O error on POST request for \"http://localhost:8081/someEndpoint\": Connect to localhost:8081 [localhost/127.0.0.1, localhost/0:0:0:0:0:0:0:1] failed: Connection refused (Connection refused); nested exception is org.apache.http.conn.HttpHostConnectException: Connect to localhost:8081 [localhost/127.0.0.1, localhost/0:0:0:0:0:0:0:1] failed: Connection refused (Connection refused)",
"path": "/someEndpoint"
}
log lines:
2019-04-09 12:10:50.045 ERROR 75383 --- [nio-8080-exec-5] o.a.c.c.C.[.[.[/].[dispatcherServlet] : Servlet.service() for servlet [dispatcherServlet] in context with path [] threw exception [Request processing failed; nested exception is org.springframework.web.client.ResourceAccessException: I/O error on POST request for "http://localhost:8081/someEndpoint": Connect to localhost:8081 [localhost/127.0.0.1, localhost/0:0:0:0:0:0:0:1] failed: Connection refused (Connection refused); nested exception is org.apache.http.conn.HttpHostConnectException: Connect to localhost:8081 [localhost/127.0.0.1, localhost/0:0:0:0:0:0:0:1] failed: Connection refused (Connection refused)] with root cause
java.net.ConnectException: Connection refused (Connection refused)
at java.net.PlainSocketImpl.socketConnect(Native Method) ~[na:1.8.0_171]
at java.net.AbstractPlainSocketImpl.doConnect(AbstractPlainSocketImpl.java:350) ~[na:1.8.0_171]
at java.net.AbstractPlainSocketImpl.connectToAddress(AbstractPlainSocketImpl.java:206) ~[na:1.8.0_171]
at java.net.AbstractPlainSocketImpl.connect(AbstractPlainSocketImpl.java:188) ~[na:1.8.0_171]
at java.net.SocksSocketImpl.connect(SocksSocketImpl.java:392) ~[na:1.8.0_171]
at java.net.Socket.connect(Socket.java:589) ~[na:1.8.0_171]
at org.apache.http.conn.socket.PlainConnectionSocketFactory.connectSocket(PlainConnectionSocketFactory.java:75) ~[spring-cloud-contract-shade-2.1.1.RELEASE.jar:2.1.1.RELEASE]
I think i am missing some stubRunner configuration for stubrunner port.

Related

Pact Test -consumer connection refused error

I am trying to run the pact contract test on consumer side to generate the pact contract. But always getting a connection refused error.
#RunWith(SpringRunner.class)
#SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.NONE, properties =
"product-service.products.baseUrl:http://localhost:9001/svc-product-service/api/products")
public class ProductServiceContractTest {
#Autowired
private ProductService productService;
#Rule
public PactProviderRuleMk2 provider = new PactProviderRuleMk2("svc-product-service", "localhost", 9001, this);
#Pact(consumer = "svc-product-order-service")
public RequestResponsePact pactProductExists(PactDslWithProvider builder) {
return builder.given("Product 1001 exists").uponReceiving("A request to /1001").path("/1001").method("GET")
.willRespondWith().status(200)
.body(new PactDslJsonBody().integerType("id", 1001).stringType("name", "Laptop"))
.toPact();
}
#PactVerification(fragment = "pactProductExists")
#Test
public void productExists() {
final Product product = productService.fetchProductsById(1001);
assertThat(product.getId()).isEqualTo(1001);
assertThat(product.getName()).isEqualTo("Laptop");
}
}
POM dependency
<dependency>
<groupId>au.com.dius</groupId>
<artifactId>pact-jvm-consumer-java8_2.12</artifactId>
<version>3.5.24</version>
<scope>test</scope>
</dependency>
Stack trace:
[ERROR] com.example.product.order.service.ProductServiceContractTest.productExists Time elapsed: 0.034 s <<< ERROR!
org.springframework.web.client.ResourceAccessException: I/O error on GET request for "http://localhost:9001/svc-product-service/api/products/1001": Connect to localhost:9001 [localhost/127.0.0.1, localhost/0:0:0:0:0:0:0:1] failed: Connection refused: connect; nested exception is org.apache.http.conn.HttpHostConnectException: Connect to localhost:9001 [localhost/127.0.0.1, localhost/0:0:0:0:0:0:0:1] failed: Connection refused: connect
at com.example.product.order.service.ProductServiceContractTest.productExists(ProductServiceContractTest.java:79)
Caused by: org.apache.http.conn.HttpHostConnectException: Connect to localhost:9001 [localhost/127.0.0.1, localhost/0:0:0:0:0:0:0:1] failed: Connection refused: connect
at com.example.product.order.service.ProductServiceContractTest.productExists(ProductServiceContractTest.java:79)
Caused by: java.net.ConnectException: Connection refused: connect
at com.example.product.order.service.ProductServiceContractTest.productExists(ProductServiceContractTest.java:79)

Broken connection with MariaDB

I have a Wildly server connected to MariaDB Server on the same machine.
For some reason I get this error from time to time:
20:38:51,536 INFO [stdout] (default task-1) 20:38:51.535 [default task-1] WARN o.h.e.jdbc.spi.SqlExceptionHelper - SQL Error: 0, SQLState: 08
20:38:51,536 INFO [stdout] (default task-1) 20:38:51.536 [default task-1] ERROR o.h.e.jdbc.spi.SqlExceptionHelper - (conn=25) Connection reset by peer (Write failed)
20:38:51,549 INFO [stdout] (default task-1) 20:38:51.548 [default task-1] ERROR o.s.t.i.TransactionInterceptor - Application exception overridden by rollback exception
20:38:51,550 INFO [stdout] (default task-1) org.springframework.dao.DataAccessResourceFailureException: could not prepare statement; nested exception is org.hibernate.exception.JDBCConnectionException: could not prepare statement
20:38:51,550 INFO [stdout] (default task-1) at deployment.datalis_admin.war//org.springframework.orm.jpa.vendor.HibernateJpaDialect.convertHibernateAccessException(HibernateJpaDialect.java:275)
20:38:51,550 INFO [stdout] (default task-1) at deployment.datalis_admin.war//org.springframework.orm.jpa.vendor.HibernateJpaDialect.translateExceptionIfPossible(HibernateJpaDialect.java:253)
20:38:51,550 INFO [stdout] (default task-1) at deployment.datalis_admin.war//org.springframework.orm.jpa.AbstractEntityManagerFactoryBean.translateExceptionIfPossible(AbstractEntityManagerFactoryBean.java:527)
In MariaDB log I get: 2019-03-06 20:27:51 25 [Warning] Aborted connection 25 to db: 'production_gateway' user: 'wildfly' host: 'localhost' (Got timeout reading communication packets)
Do you know what might be the issue and how to fix it?
POM file:
https://pastebin.com/HUNy0ULy
application.properties:
spring.datasource.jndi-name=java:/global/production_gateway
spring.datasource.driver-class-name=org.mariadb.jdbc.Driver
spring.jpa.properties.hibernate.dialect=org.hibernate.dialect.MariaDBDialect
spring.jpa.show-sql = true
spring.jpa.hibernate.ddl-auto = update
JPA configuration:
import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.dao.annotation.PersistenceExceptionTranslationPostProcessor;
import org.springframework.orm.jpa.JpaTransactionManager;
import org.springframework.transaction.PlatformTransactionManager;
import org.springframework.transaction.annotation.EnableTransactionManagement;
#Configuration
#EnableTransactionManagement
public class ContextDatasource {
#Bean
public EntityManager entityManager(EntityManagerFactory emf) {
return emf.createEntityManager();
}
#Bean
public PlatformTransactionManager transactionManager(final EntityManagerFactory emf) {
final JpaTransactionManager transactionManager = new JpaTransactionManager();
transactionManager.setEntityManagerFactory(emf);
return transactionManager;
}
#Bean
public PersistenceExceptionTranslationPostProcessor exceptionTranslation() {
return new PersistenceExceptionTranslationPostProcessor();
}
}
JDBC driver:
mariadb-java-client-2.4.0.jar
MariaDB version:
mysql Ver 15.1 Distrib 10.3.13-MariaDB, for debian-linux-gnu (x86_64) using readline 5.2
Can you advice?
Please show us your pom.xml and watch out if your driver's version is compatible for your DB version as well. Some they have to update the driver web the DB developer make some change.

Spring Boot MVC Converter Cannot Autowire Neo4J Data Repositories

I'm needing to #Autowire a Spring Data Neo4J repository into a Spring MVC converter (in Spring Boot), but the MVC configuration gets started before the Data services get started. This results in an #Autowired not found problem. How do I get the Data Services to get started before the MVC so it finds an eligible bean?
I have a project I'm converting from XML Spring config to Spring Boot. Everything is working fine except for the MVC Converters. They are not able to #Autowire Neo4J Repository classes.
If remove the #Autowire of the Repository and hard code in a value, things work as expected with the hack. Other operations in services are using the Repositories just fine. It seems the MVC config is getting started before the Neo4J plumbing can get started and then can't find the right components to tie into. I've looked, but I can't figure out how to get the data config to start before the MVC config.
Here's my base config:
#Configuration
#ComponentScan
#EnableAutoConfiguration
public class Toyfiles {
public static void main(String[] args) throws Exception {
SpringApplication.run(Toyfiles.class, args);
}
}
My MVC Config:
#Configuration
public class MVCBeans extends WebMvcConfigurerAdapter {
#Autowired
private StringToBrand stringToBrand;
#Autowired
private BrandToString brandToString;
#Override
public void addFormatters(FormatterRegistry registry) {
registry.addConverter(stringToBrand);
registry.addConverter(brandToString);
super.addFormatters(registry);
}
}
The offending Converter:
#Component
public class StringToBrand implements Converter<String, Brand> {
#Autowired
BrandRepository brandRepository;
#Override
public Brand convert(String s) {
return brandRepository.findBrandByName(s);
}
}
The Data config:
#Configuration
#Profile("localEmbeddedDBServer")
#EnableTransactionManagement
#EnableNeo4jRepositories(basePackages = "com.toyfiles.dataservices.")
public class LocalDBConfig extends Neo4jConfiguration {
public LocalDBConfig() {
setBasePackage("com.toyfiles");
}
#Bean
public GraphDatabaseService graphDatabaseService() {
return new GraphDatabaseFactory().newEmbeddedDatabase("target/graph.db");
}
}
And the Repository:
public interface BrandRepository extends GraphRepository<Brand> {
#Query(value = "MATCH (brand:Brand {name:{0}})-[:PART_OF]->line RETURN line")
public List<Line> getLinesForBrand(String name);
#Query(value = "MATCH (brand:Brand {name:{0}}) DELETE brand")
public void deleteBrandByName(String name);
public Brand findBrandByName(String name);
}
The "interesting" part of the Exception:
Caused by: org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'brandRepository': Cannot resolve reference to bean 'neo4jTemplate' while setting bean property 'neo4jTemplate'; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'neo4jTemplate' defined in class path resource [com/toyfiles/configuration/LocalDBConfig.class]: Instantiation of bean failed; nested exception is org.springframework.beans.factory.BeanDefinitionStoreException: Factory method [public org.springframework.data.neo4j.support.Neo4jTemplate org.springframework.data.neo4j.config.Neo4jConfiguration.neo4jTemplate() throws java.lang.Exception] threw exception; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'neo4jMappingContext' defined in class path resource [com/toyfiles/configuration/LocalDBConfig.class]: Invocation of init method failed; nested exception is java.lang.IllegalStateException: ApplicationEventMulticaster not initialized - call 'refresh' before multicasting events via the context: org.springframework.boot.context.embedded.AnnotationConfigEmbeddedWebApplicationContext#4d49af10: startup date [Mon Sep 29 09:48:25 PDT 2014]; root of context hierarchy
at org.springframework.beans.factory.support.BeanDefinitionValueResolver.resolveReference(BeanDefinitionValueResolver.java:336)
at org.springframework.beans.factory.support.BeanDefinitionValueResolver.resolveValueIfNecessary(BeanDefinitionValueResolver.java:108)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.applyPropertyValues(AbstractAutowireCapableBeanFactory.java:1457)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.populateBean(AbstractAutowireCapableBeanFactory.java:1198)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:537)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:475)
at org.springframework.beans.factory.support.AbstractBeanFactory$1.getObject(AbstractBeanFactory.java:302)
at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:228)
at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:298)
at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:193)
at org.springframework.beans.factory.support.DefaultListableBeanFactory.findAutowireCandidates(DefaultListableBeanFactory.java:1021)
at org.springframework.beans.factory.support.DefaultListableBeanFactory.doResolveDependency(DefaultListableBeanFactory.java:964)
at org.springframework.beans.factory.support.DefaultListableBeanFactory.resolveDependency(DefaultListableBeanFactory.java:862)
at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor$AutowiredFieldElement.inject(AutowiredAnnotationBeanPostProcessor.java:481)
... 116 more
Caused by: org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'neo4jTemplate' defined in class path resource [com/toyfiles/configuration/LocalDBConfig.class]: Instantiation of bean failed; nested exception is org.springframework.beans.factory.BeanDefinitionStoreException: Factory method [public org.springframework.data.neo4j.support.Neo4jTemplate org.springframework.data.neo4j.config.Neo4jConfiguration.neo4jTemplate() throws java.lang.Exception] threw exception; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'neo4jMappingContext' defined in class path resource [com/toyfiles/configuration/LocalDBConfig.class]: Invocation of init method failed; nested exception is java.lang.IllegalStateException: ApplicationEventMulticaster not initialized - call 'refresh' before multicasting events via the context: org.springframework.boot.context.embedded.AnnotationConfigEmbeddedWebApplicationContext#4d49af10: startup date [Mon Sep 29 09:48:25 PDT 2014]; root of context hierarchy
at org.springframework.beans.factory.support.ConstructorResolver.instantiateUsingFactoryMethod(ConstructorResolver.java:597)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.instantiateUsingFactoryMethod(AbstractAutowireCapableBeanFactory.java:1095)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBeanInstance(AbstractAutowireCapableBeanFactory.java:990)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:504)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:475)
at org.springframework.beans.factory.support.AbstractBeanFactory$1.getObject(AbstractBeanFactory.java:302)
at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:228)
at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:298)
at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:193)
at org.springframework.beans.factory.support.BeanDefinitionValueResolver.resolveReference(BeanDefinitionValueResolver.java:328)
... 129 more
Caused by: org.springframework.beans.factory.BeanDefinitionStoreException: Factory method [public org.springframework.data.neo4j.support.Neo4jTemplate org.springframework.data.neo4j.config.Neo4jConfiguration.neo4jTemplate() throws java.lang.Exception] threw exception; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'neo4jMappingContext' defined in class path resource [com/toyfiles/configuration/LocalDBConfig.class]: Invocation of init method failed; nested exception is java.lang.IllegalStateException: ApplicationEventMulticaster not initialized - call 'refresh' before multicasting events via the context: org.springframework.boot.context.embedded.AnnotationConfigEmbeddedWebApplicationContext#4d49af10: startup date [Mon Sep 29 09:48:25 PDT 2014]; root of context hierarchy
at org.springframework.beans.factory.support.SimpleInstantiationStrategy.instantiate(SimpleInstantiationStrategy.java:188)
at org.springframework.beans.factory.support.ConstructorResolver.instantiateUsingFactoryMethod(ConstructorResolver.java:586)
... 138 more
Caused by: org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'neo4jMappingContext' defined in class path resource [com/toyfiles/configuration/LocalDBConfig.class]: Invocation of init method failed; nested exception is java.lang.IllegalStateException: ApplicationEventMulticaster not initialized - call 'refresh' before multicasting events via the context: org.springframework.boot.context.embedded.AnnotationConfigEmbeddedWebApplicationContext#4d49af10: startup date [Mon Sep 29 09:48:25 PDT 2014]; root of context hierarchy
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.initializeBean(AbstractAutowireCapableBeanFactory.java:1554)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:539)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:475)
at org.springframework.beans.factory.support.AbstractBeanFactory$1.getObject(AbstractBeanFactory.java:302)
at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:228)
at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:298)
at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:193)
at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:292)
at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:193)
at org.springframework.context.annotation.ConfigurationClassEnhancer$BeanMethodInterceptor.intercept(ConfigurationClassEnhancer.java:288)
at com.toyfiles.configuration.LocalDBConfig$$EnhancerBySpringCGLIB$$321222c6.mappingInfrastructure(<generated>)
at org.springframework.data.neo4j.config.Neo4jConfiguration.neo4jTemplate(Neo4jConfiguration.java:135)
at com.toyfiles.configuration.LocalDBConfig$$EnhancerBySpringCGLIB$$321222c6.CGLIB$neo4jTemplate$23(<generated>)
at com.toyfiles.configuration.LocalDBConfig$$EnhancerBySpringCGLIB$$321222c6$$FastClassBySpringCGLIB$$12e74a61.invoke(<generated>)
at org.springframework.cglib.proxy.MethodProxy.invokeSuper(MethodProxy.java:228)
at org.springframework.context.annotation.ConfigurationClassEnhancer$BeanMethodInterceptor.intercept(ConfigurationClassEnhancer.java:312)
at com.toyfiles.configuration.LocalDBConfig$$EnhancerBySpringCGLIB$$321222c6.neo4jTemplate(<generated>)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:483)
at org.springframework.beans.factory.support.SimpleInstantiationStrategy.instantiate(SimpleInstantiationStrategy.java:166)
... 139 more
Caused by: java.lang.IllegalStateException: ApplicationEventMulticaster not initialized - call 'refresh' before multicasting events via the context: org.springframework.boot.context.embedded.AnnotationConfigEmbeddedWebApplicationContext#4d49af10: startup date [Mon Sep 29 09:48:25 PDT 2014]; root of context hierarchy
at org.springframework.context.support.AbstractApplicationContext.getApplicationEventMulticaster(AbstractApplicationContext.java:346)
at org.springframework.context.support.AbstractApplicationContext.publishEvent(AbstractApplicationContext.java:333)
at org.springframework.data.mapping.context.AbstractMappingContext.addPersistentEntity(AbstractMappingContext.java:307)
at org.springframework.data.neo4j.support.mapping.Neo4jMappingContext.addPersistentEntity(Neo4jMappingContext.java:69)
at org.springframework.data.neo4j.support.mapping.Neo4jMappingContext.addPersistentEntity(Neo4jMappingContext.java:49)
at org.springframework.data.mapping.context.AbstractMappingContext.getPersistentEntity(AbstractMappingContext.java:181)
at org.springframework.data.neo4j.mapping.RelationshipInfo.<init>(RelationshipInfo.java:65)
at org.springframework.data.neo4j.mapping.RelationshipInfo.fromField(RelationshipInfo.java:79)
at org.springframework.data.neo4j.support.mapping.Neo4jPersistentPropertyImpl.extractRelationshipInfo(Neo4JPersistentPropertyImpl.java:128)
at org.springframework.data.neo4j.support.mapping.Neo4jPersistentPropertyImpl.<init>(Neo4JPersistentPropertyImpl.java:80)
at org.springframework.data.neo4j.support.mapping.Neo4jMappingContext.createPersistentProperty(Neo4jMappingContext.java:161)
at org.springframework.data.neo4j.support.mapping.Neo4jMappingContext.createPersistentProperty(Neo4jMappingContext.java:49)
at org.springframework.data.mapping.context.AbstractMappingContext$PersistentPropertyCreator.createAndRegisterProperty(AbstractMappingContext.java:449)
at org.springframework.data.mapping.context.AbstractMappingContext$PersistentPropertyCreator.doWith(AbstractMappingContext.java:427)
at org.springframework.util.ReflectionUtils.doWithFields(ReflectionUtils.java:606)
at org.springframework.data.mapping.context.AbstractMappingContext.addPersistentEntity(AbstractMappingContext.java:295)
at org.springframework.data.neo4j.support.mapping.Neo4jMappingContext.addPersistentEntity(Neo4jMappingContext.java:69)
at org.springframework.data.neo4j.support.mapping.Neo4jMappingContext.addPersistentEntity(Neo4jMappingContext.java:49)
at org.springframework.data.mapping.context.AbstractMappingContext.getPersistentEntity(AbstractMappingContext.java:181)
at org.springframework.data.neo4j.mapping.RelationshipInfo.<init>(RelationshipInfo.java:65)
at org.springframework.data.neo4j.mapping.RelationshipInfo.fromField(RelationshipInfo.java:79)
at org.springframework.data.neo4j.support.mapping.Neo4jPersistentPropertyImpl.extractRelationshipInfo(Neo4JPersistentPropertyImpl.java:128)
at org.springframework.data.neo4j.support.mapping.Neo4jPersistentPropertyImpl.<init>(Neo4JPersistentPropertyImpl.java:80)
at org.springframework.data.neo4j.support.mapping.Neo4jMappingContext.createPersistentProperty(Neo4jMappingContext.java:161)
at org.springframework.data.neo4j.support.mapping.Neo4jMappingContext.createPersistentProperty(Neo4jMappingContext.java:49)
at org.springframework.data.mapping.context.AbstractMappingContext$PersistentPropertyCreator.createAndRegisterProperty(AbstractMappingContext.java:449)
at org.springframework.data.mapping.context.AbstractMappingContext$PersistentPropertyCreator.doWith(AbstractMappingContext.java:427)
at org.springframework.util.ReflectionUtils.doWithFields(ReflectionUtils.java:606)
at org.springframework.data.mapping.context.AbstractMappingContext.addPersistentEntity(AbstractMappingContext.java:295)
at org.springframework.data.neo4j.support.mapping.Neo4jMappingContext.addPersistentEntity(Neo4jMappingContext.java:69)
at org.springframework.data.neo4j.support.mapping.Neo4jMappingContext.addPersistentEntity(Neo4jMappingContext.java:49)
at org.springframework.data.mapping.context.AbstractMappingContext.addPersistentEntity(AbstractMappingContext.java:257)
at org.springframework.data.mapping.context.AbstractMappingContext.initialize(AbstractMappingContext.java:373)
at org.springframework.data.neo4j.support.mapping.Neo4jMappingContext.initialize(Neo4jMappingContext.java:111)
at org.springframework.data.mapping.context.AbstractMappingContext.afterPropertiesSet(AbstractMappingContext.java:363)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.invokeInitMethods(AbstractAutowireCapableBeanFactory.java:1613)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.initializeBean(AbstractAutowireCapableBeanFactory.java:1550)
... 160 more
I used an #Lazy annotation for the repository to delay the reference to the repository since the repository was getting started correctly later in the startup. This allowed the repository reference to be delayed until it was needed and available.
#Autowired
#Lazy
BrandRepository brandRepository;

Spring beans injection into jax-ws services

So I already learnt that integration of spring and jax-ws is not an easy thing.
I want to inject a spring bean into jax-ws service, but for some reason I get an exception during the deployment:
Exception while loading the app : java.lang.IllegalStateException: ContainerBase.addChild: start: org.apache.catalina.LifecycleException: java.lang.IllegalArgumentException: javax.servlet.ServletException: com.sun.enterprise.container.common.spi.util.InjectionException: Error creating managed object for class: class org.springframework.web.context.ContextLoaderListener|#]
this is my jax-ws configuration:
<wss:binding url="/ws/users">
<wss:service>
<ws:service bean="#usersWs"/>
</wss:service>
</wss:binding>
<bean id="usersWs" class="love.service.endpoint.implementations.UserServiceImpl" />
And this is my service:
#WebService
public class UserServiceImpl implements UserService{
#EJB
private DBManager dbmanager;
#Override
#WebMethod
public boolean addUser(String name, String password, String email) {
return false;
}
#Override
#WebMethod
public boolean isUsernameAvailable(String username) {
return dbmanager.isLoginAvailable(username);
}
#Override
#WebMethod
public boolean isEmailAvailable(String email) {
return dbmanager.isEmailAvailable(email);
}
}
and finally my bean configuration:
<bean id="dbmanager" class="love.commons.database.DBManager" scope="request">
<aop:scoped-proxy/>
</bean>
I also tried injecting the bean into some controllers and then it works perfectly well.
If I replace #EJB with #Autowired, the application starts, but the service still doesn't work. When I tried sending a message to it, my only response was the following:
<S:Envelope xmlns:S="http://schemas.xmlsoap.org/soap/envelope/">
<S:Body>
<S:Fault xmlns:ns4="http://www.w3.org/2003/05/soap-envelope">
<faultcode>S:Server</faultcode>
<faultstring>Error creating bean with name 'scopedTarget.dbmanager': Scope 'request' is not active for the current thread; consider defining a scoped proxy for this bean if you intend to refer to it from a singleton; nested exception is java.lang.IllegalStateException: No thread-bound request found: Are you referring to request attributes outside of an actual web request, or processing a request outside of the originally receiving thread? If you are actually operating within a web request and still receive this message, your code is probably running outside of DispatcherServlet/DispatcherPortlet: In this case, use RequestContextListener or RequestContextFilter to expose the current request.</faultstring>
</S:Fault>
</S:Body>
</S:Envelope>

Issue with EJB - Stateful Session Bean and Servlet

I have a servlet code which calls a ejb stateful session bean code as follows,
public class UsesBeansSF extends HttpServlet {
protected void processRequest(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
response.setContentType("text/html;charset=UTF-8");
PrintWriter out = response.getWriter();
try {
// do something
}
finally {}
}
private SessionBeanSFRemote lookupSessionBeanSFRemote() {
try {
Context c = new InitialContext();
return (SessionBeanSFRemote) c.lookup("java:global/MyEJBSF/SessionBeanSF!ejbSF.SessionBeanSFRemote");
} catch (NamingException ne) {
Logger.getLogger(getClass().getName()).log(Level.SEVERE, "exception caught", ne);
throw new RuntimeException(ne);
}
}
}
This code works well without the line between * marks. However, when I am adding SessionBeanSFRemote sessionBeanSF = lookupSessionBeanSFRemote() this line (means calling a Stateful Session Bean), the code is giving error. Actually, I have to call the stateless session bean in order to perform some job. Can anybody help me why it is happening ? Thanks in advance.
Error message is following:
type Exception report message
descriptionThe server encountered an internal error () that prevented it from fulfilling this request.
exception
javax.servlet.ServletException: PWC1392: Error instantiating servlet class websSF.comsSF.UsesBeansSF
root cause
com.sun.enterprise.container.common.spi.util.InjectionException:
Error creating managed object for class websSF.comsSF.UsesBeansSF
root cause
java.lang.reflect.InvocationTargetException
root cause
java.lang.RuntimeException: javax.naming.NamingException:
Lookup failed for 'java:global/MyEJBSF/SessionBeanSF!ejbSF.SessionBeanSFRemote' in SerialContext
[Root exception is javax.naming.NamingException:
ejb ref resolution error for remote business interfaceejbSF.SessionBeanSFRemote [Root exception is java.lang.NullPointerException]]
root cause
javax.naming.NamingException:
Lookup failed for 'java:global/MyEJBSF/SessionBeanSF!ejbSF.SessionBeanSFRemote' in SerialContext
[Root exception is javax.naming.NamingException:
ejb ref resolution error for remote business interfaceejbSF.SessionBeanSFRemote
[Root exception is java.lang.NullPointerException]]
root cause
javax.naming.NamingException: ejb ref resolution error for remote business
interfaceejbSF.SessionBeanSFRemote [Root exception is java.lang.NullPointerException]
root cause
java.lang.NullPointerException
note The full stack traces of the exception and its root causes are available in the GlassFish Server Open Source Edition 3.0.1 logs.
Server: GlassFish Server Open Source Edition 3.0.1
I'm not sure if you have properly set up your Stateful bean. You can try this:
#Stateful(mappedName = "ejb/myStatefulBean")
public class MyStatefulBean implements MyStatefulRemoteInterface {
// Your implementation
}
then you can look it up with:
InitialContext context = new InitialContext();
MyStatefulRemoteInterface myStatefulBean = (MyStatefulRemoteInterface) context.lookup("ejb/myStatefulBean");
Besides, this stateful bean should be saved into each client's session for re-using:
HttpSession clientSession = request.getSession(false);
clientSession.setAttribute("myStatefulBean", myStatefulBean);
In future requests, you can try to get the bean from the client' session first before creating a new one for him.

Resources