Pact Test -consumer connection refused error - pact

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)

Related

JCA Remote Queue Wildfly Artemis

I have EJB deployed on a WildFly 18 server. I want to send message to a queue deployed on a remote WildFly 18 server (through ActiveMQ Artemis). Is that possible using injection and JCA and a poole-connection-factory?
Connection factory and queue are configured in the remote Wildfly as below:
<subsystem xmlns="urn:jboss:domain:messaging-activemq:8.0">
...
<pooled-connection-factory name="remote-artemis" entries="java:/jms/remoteCF" connectors="remote-http-connector"/>
...
</subsystem>
On the remote server, the queue is configured as below:
<subsystem xmlns="urn:jboss:domain:messaging-activemq:8.0">
...
<jms-queue name="WildFlyCookbookQueue" entries="java:/jms/queue/test java:jboss/exported/jms/queue/test"/>
...
</subsystem>
UPDATE
Here is my EJB trying to send message to the remote Artermis (inside remote wildfly):
#Stateless
public class MessageSender {
#Inject
#JMSConnectionFactory("java:/jms/remoteCF")
#JMSPasswordCredential(userName = "jmsuser", password = "jmsuser2020")
private JMSContext context;
#Resource(lookup = "java:/jms/queue/test")
private Queue queue;
public void sendMessage(String message) {
context.createProducer().send(queue, message);
}
}
When I try to deploy the war containing this EJB, I get the error saying that the queue does not exist.
Thank you
Yes. It is possible to inject a JCA-based pooled-connection-factory into your EJB running on WildFly 18 and send a JMS message to a remote WildFly server.

Started stub server for project [] on port -1

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.

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.

SpringBoot Async requests throwing 503 Service Unavailable

I was experimenting with springboots async controllers when I came around with this issue.
I set the number of threads for the servlet container to 10 by setting the following
#Bean
public JettyEmbeddedServletContainerFactory jettyEmbeddedServletContainerFactory(#Value("${server.port:8080}") final String port,
#Value("${jetty.threadPool.maxThreads:10}") final String maxThreads,
#Value("${jetty.threadPool.minThreads:8}") final String minThreads,
#Value("${jetty.threadPool.idleTimeout:60000}") final String idleTimeout) {
final JettyEmbeddedServletContainerFactory factory = new JettyEmbeddedServletContainerFactory(Integer.valueOf(port));
factory.addServerCustomizers(new JettyServerCustomizer() {
#Override
public void customize(final Server server) {
final QueuedThreadPool threadPool = server.getBean(QueuedThreadPool.class);
threadPool.setMaxThreads(Integer.valueOf(maxThreads));
threadPool.setMinThreads(Integer.valueOf(minThreads));
threadPool.setIdleTimeout(Integer.valueOf(idleTimeout));
}
});
return factory;
}
I then configured the async thread pool to also start with 10 but set the max thread poolsize to 200.
#Bean
public Executor asyncExecutor() {
ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();
executor.setCorePoolSize(10);
executor.setMaxPoolSize(200);
executor.setQueueCapacity(500);
executor.setThreadNamePrefix("asyncthread-");
executor.initialize();
return executor;
}
When I submit 20 concurrent requests I get the below error consistently on the client code. The server side doesn't seem to show any issues.
08:06:12.550 [pool-1-thread-1] DEBUG
org.springframework.web.client.RestTemplate - GET request for
"http://localhost:8080/time/basicasync" resulted in 503 (Service
Unavailable); invoking error handler
java.util.concurrent.ExecutionException:
org.springframework.web.client.HttpServerErrorException: 503 Service
Unavailable at
java.util.concurrent.FutureTask.report(FutureTask.java:122) at
java.util.concurrent.FutureTask.get(FutureTask.java:192) at
Main.main(Main.java:64) Caused by:
org.springframework.web.client.HttpServerErrorException: 503 Service
Unavailable at
org.springframework.web.client.DefaultResponseErrorHandler.handleError(DefaultResponseErrorHandler.java:94)
at
org.springframework.web.client.RestTemplate.handleResponse(RestTemplate.java:641)
at
org.springframework.web.client.RestTemplate.doExecute(RestTemplate.java:597)
at
org.springframework.web.client.RestTemplate.execute(RestTemplate.java:557)
at
org.springframework.web.client.RestTemplate.getForEntity(RestTemplate.java:289)
at Main.lambda$main$1(Main.java:32) at
java.util.concurrent.FutureTask.run(FutureTask.java:266) 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:748)
My Client code hangs because I use CompletionService to submit all tasks. If I increase the async threadpool on the server to 50 the issue doesn't seem to occur. Can someone throw some light on this behavior ?

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