Wiremock - Connection Refused - JUnit5 - junit

I have a stub that I can see under /__admin/ but when making any sort of rest calls nothing registers in either __admin/requests or __admin/requests/unmatched which I feel is strange. Is Wiremock failing to intercept the request?
Simplified code:
class MyTestClass {
#Test
void testStuff(){
WireMock.configureFor("localhost", 9050); // Running in docker with custom port
WireMock.reset();
stubFor(
get("/getStuff?include-archived=yes")
.withPort(<myServicePort>)
.willReturn(
aResponse()
.withHeader("Content-Type", "application/json")
.withStatus(200)
)
);
}
}
Error:
Error has been observed at the following site(s): *__checkpoint ⇢
Request to GET
http://localhost:<myServicePort>/getStuff?include-archived=yes
[DefaultWebClient]
...
[org.springframework.web.servlet.mvc.method.annotation.ExceptionHandlerExceptionResolver]
: Resolved
[org.springframework.web.reactive.function.client.WebClientRequestException:
Connection refused: no further information:
localhost/127.0.0.1:<myServicePort>; nested exception is
io.netty.channel.AbstractChannel$AnnotatedConnectException: Connection
refused: no further information: localhost/127.0.0.1:<myServicePort>]

Finally found the issue, the port that I was trying to intercept wasn't open in the container thus why I got no entries in either __admin/requests or __admin/requests/unmatched

Related

Vertx Failed Connection issue not catched JDBCClient (.getConnection)

I can't handle case when connection failed in JDBCClient on vertx-jdbc-client - 3.3.9, example: no host to route, connection time out and etc. Because the method .getConnection() does not return failedFuture and failed is not called even on wrong hostname, username and passwords.
The method only gets executed successfully when all the provided parameters for a connection is valid else the block of code gets stuck and SQLConnection is never called. Even wrapping the code with try catch block gives no error in my case.
JDBCClient client = JDBCClient.createNonShared(Holder.getInstance().getVertx(), databaseConfig);
client.getConnection(connect -> {
if (connect.failed()){
client.close();
return;
}
/* Create connection on success */
SQLConnection connection = connect.result();
/* Execute Query */
Related: Vertx connection timeout not catched JDBCClient (.getConnection)
If you use the C3P0 connection pool, try this:
databaseConfig.put("acquire_retry_attempts", 1).put("break_after_acquire_failure", true);
Otherwise the pool keeps trying to establish a connection.

java.net.ConnectException: Connection refused: connect. Data Grip [duplicate]

I'm trying to implement a TCP connection, everything works fine from the server's side but when I run the client program (from client computer) I get the following error:
java.net.ConnectException: Connection refused
at java.net.PlainSocketImpl.socketConnect(Native Method)
at java.net.PlainSocketImpl.doConnect(PlainSocketImpl.java:351)
at java.net.PlainSocketImpl.connectToAddress(PlainSocketImpl.java:213)
at java.net.PlainSocketImpl.connect(PlainSocketImpl.java:200)
at java.net.SocksSocketImpl.connect(SocksSocketImpl.java:432)
at java.net.Socket.connect(Socket.java:529)
at java.net.Socket.connect(Socket.java:478)
at java.net.Socket.<init>(Socket.java:375)
at java.net.Socket.<init>(Socket.java:189)
at TCPClient.main(TCPClient.java:13)
I tried changing the socket number in case it was in use but to no avail, does anyone know what is causing this error & how to fix it.
The Server Code:
//TCPServer.java
import java.io.*;
import java.net.*;
class TCPServer {
public static void main(String argv[]) throws Exception {
String fromclient;
String toclient;
ServerSocket Server = new ServerSocket(5000);
System.out.println("TCPServer Waiting for client on port 5000");
while (true) {
Socket connected = Server.accept();
System.out.println(" THE CLIENT" + " " + connected.getInetAddress()
+ ":" + connected.getPort() + " IS CONNECTED ");
BufferedReader inFromUser = new BufferedReader(
new InputStreamReader(System.in));
BufferedReader inFromClient = new BufferedReader(
new InputStreamReader(connected.getInputStream()));
PrintWriter outToClient = new PrintWriter(
connected.getOutputStream(), true);
while (true) {
System.out.println("SEND(Type Q or q to Quit):");
toclient = inFromUser.readLine();
if (toclient.equals("q") || toclient.equals("Q")) {
outToClient.println(toclient);
connected.close();
break;
} else {
outToClient.println(toclient);
}
fromclient = inFromClient.readLine();
if (fromclient.equals("q") || fromclient.equals("Q")) {
connected.close();
break;
} else {
System.out.println("RECIEVED:" + fromclient);
}
}
}
}
}
The Client Code:
//TCPClient.java
import java.io.*;
import java.net.*;
class TCPClient {
public static void main(String argv[]) throws Exception {
String FromServer;
String ToServer;
Socket clientSocket = new Socket("localhost", 5000);
BufferedReader inFromUser = new BufferedReader(new InputStreamReader(
System.in));
PrintWriter outToServer = new PrintWriter(
clientSocket.getOutputStream(), true);
BufferedReader inFromServer = new BufferedReader(new InputStreamReader(
clientSocket.getInputStream()));
while (true) {
FromServer = inFromServer.readLine();
if (FromServer.equals("q") || FromServer.equals("Q")) {
clientSocket.close();
break;
} else {
System.out.println("RECIEVED:" + FromServer);
System.out.println("SEND(Type Q or q to Quit):");
ToServer = inFromUser.readLine();
if (ToServer.equals("Q") || ToServer.equals("q")) {
outToServer.println(ToServer);
clientSocket.close();
break;
} else {
outToServer.println(ToServer);
}
}
}
}
}
This exception means that there is no service listening on the IP/port you are trying to connect to:
You are trying to connect to the wrong IP/Host or port.
You have not started your server.
Your server is not listening for connections.
On Windows servers, the listen backlog queue is full.
I would check:
Host name and port you're trying to connect to
The server side has managed to start listening correctly
There's no firewall blocking the connection
The simplest starting point is probably to try to connect manually from the client machine using telnet or Putty. If that succeeds, then the problem is in your client code. If it doesn't, you need to work out why it hasn't. Wireshark may help you on this front.
You have to connect your client socket to the remote ServerSocket. Instead of
Socket clientSocket = new Socket("localhost", 5000);
do
Socket clientSocket = new Socket(serverName, 5000);
The client must connect to serverName which should match the name or IP of the box on which your ServerSocket was instantiated (the name must be reachable from the client machine). BTW: It's not the name that is important, it's all about IP addresses...
I had the same problem, but running the Server before running the Client fixed it.
One point that I would like to add to the answers above is my experience-
"I hosted on my server on localhost and was trying to connect to it through an android emulator by specifying proper URL like http://localhost/my_api/login.php . And I was getting connection refused error"
Point to note - When I just went to browser on the PC and use the same URL (http://localhost/my_api/login.php) I was getting correct response
so the Problem in my case was the term localhost which I replaced with the IP for my server (as your server is hosted on your machine) which made it reachable from my emulator on the same PC.
To get IP for your local machine, you can use ipconfig command on cmd
you will get IPv4 something like 192.68.xx.yy
Voila ..that's your machine's IP where you have your server hosted.
use it then instead of localhost
http://192.168.72.66/my_api/login.php
Note - you won't be able to reach this private IP from any node outside this computer. (In case you need ,you can use Ngnix for that)
I had the same problem with Mqtt broker called vernemq.but solved it by adding the following.
$ sudo vmq-admin listener show
to show the list o allowed ips and ports for vernemq
$ sudo vmq-admin listener start port=1885 -a 0.0.0.0 --mountpoint /appname --nr_of_acceptors=10 --max_connections=20000
to add any ip and your new port. now u should be able to connect without any problem.
Hope it solves your problem.
Hope my experience may be useful to someone. I faced the problem with the same exception stack trace and I couldn't understand what the issue was. The Database server which I was trying to connect was running and the port was open and was accepting connections.
The issue was with internet connection. The internet connection that I was using was not allowed to connect to the corresponding server. When I changed the connection details, the issue got resolved.
In my case, I gave the socket the name of the server (in my case "raspberrypi"), and instead an IPv4 address made it, or to specify, IPv6 was broken (the name resolved to an IPv6)
In my case, I had to put a check mark near Expose daemon on tcp://localhost:2375 without TLS in docker setting (on the right side of the task bar, right click on docker, select setting)
i got this error because I closed ServerSocket inside a for loop that try to accept number of clients inside it (I did not finished accepting all clints)
so be careful where to close your Socket
I had same problem and the problem was that I was not closing socket object.After using socket.close(); problem solved.
This code works for me.
ClientDemo.java
public class ClientDemo {
public static void main(String[] args) throws UnknownHostException,
IOException {
Socket socket = new Socket("127.0.0.1", 55286);
OutputStreamWriter os = new OutputStreamWriter(socket.getOutputStream());
os.write("Santosh Karna");
os.flush();
socket.close();
}
}
and
ServerDemo.java
public class ServerDemo {
public static void main(String[] args) throws IOException {
System.out.println("server is started");
ServerSocket serverSocket= new ServerSocket(55286);
System.out.println("server is waiting");
Socket socket=serverSocket.accept();
System.out.println("Client connected");
BufferedReader reader=new BufferedReader(new InputStreamReader(socket.getInputStream()));
String str=reader.readLine();
System.out.println("Client data: "+str);
socket.close();
serverSocket.close();
}
}
I changed my DNS network and it fixed the problem
You probably didn't initialize the server or client is trying to connect to wrong ip/port.
Change local host to your ip address
localhost
//to you local ip
192.168.xxxx
I saw the same error message ""java.net.ConnectException: Connection refused" in SQuirreLSQL when it was trying to connect to a postgresql database through an ssh tunnel.
Example of opening tunel:
Example of error in Squirrel with Postgresql:
It was trying to connect to the wrong port. After entering the correct port, the process execution was successful.
See more options to fix this error at: https://stackoverflow.com/a/6876306/5857023
In my case, with server written in c# and client written in Java, I resolved it by specifying hostname as 'localhost' in the server, and '[::1]' in the client. I don't know why that is, but specifying 'localhost' in the client did not work.
Supposedly these are synonyms in many ways, but apparently, not not a 100% match. Hope it helps someone avoid a headache.
For those who are experiencing the same problem and use Spring framework, I would suggest to check an http connection provider configuration. I mean RestTemplate, WebClient, etc.
In my case there was a problem with configured RestTemplate (it's just an example):
public RestTemplate localRestTemplate() {
Proxy proxy = new Proxy(Proxy.Type.HTTP, new InetSocketAddress("localhost", <some port>));
SimpleClientHttpRequestFactory clientHttpReq = new SimpleClientHttpRequestFactory();
clientHttpReq.setProxy(proxy);
return new RestTemplate(clientHttpReq);
}
I just simplified configuration to:
public RestTemplate restTemplate() {
return new RestTemplate(new SimpleClientHttpRequestFactory());
}
And it started to work properly.
There is a service called MySQL80 that should be running to connect to the database
for windows you can access it by searching for services than look for MySQL80 service and make sure it is running
It could be that there is a previous instance of the client still running and listening on port 5000.

Rethrowing an exception out of Scatter-Gather flow in Mule ESB

I have a very specific question, and i really searched the answer all over the place...
Here is a situation: i have a Scatter-Gather component with a custom aggregation strategy.
http://clip2net.com/s/j66jK8 - Image of a subflow
Semantic of this process is rather simple. Request comes with Basic Authentication Header, the upper road calls just empty java processor, which returns original payload, the lower road authenticates user over LDAP, and returns Boolean result of this authentication process. Custom aggregation class checks result and if authentication was OK, then returns original payload, which results from the road #1. If not OK, then throws exception. Nothing wrong here, it works.
There is a bit tricky thing. If a user passed wrong authentication data then exception occurs in ldap:bind module. According to documentation exception is propagated to the Scatter-Gather so i'm trying to catch it using this:
#Override
public MuleEvent aggregate(AggregationContext context) throws MuleException {
for (MuleEvent event: context.collectEventsWithExceptions()) {
event.getMessage().getExceptionPayload().getException().printStackTrace();
throw new RuntimeException(event.getMessage().getExceptionPayload().getException());
}
MuleEvent result = DefaultMuleEvent.copy(context.getEvents().get(0));
if (!(Boolean) context.getEvents().get(1).getMessage().getPayload()) {
throw new SecurityException();
}
return result;
}
BUT!
As a result i see exception which stacktrace does not have javax.naming.AuthenticationException which was rased by ldap:bind component, and was printed to log automaticaly (see below).
So, my question is: how can i reach and rethrow this javax.naming.AuthenticationException exception out of Custom Aggregation Class?
I'd appreciate all you ideas and help. Thank you in advance.
WARN 2014-10-15 20:51:18,552 [[minkult].ScatterGatherWorkManager.02] org.mule.module.ldap.api.jndi.LDAPJNDIConnection: Bind failed.
ERROR 2014-10-15 20:51:18,559 [[minkult].ScatterGatherWorkManager.02] org.mule.retry.notifiers.ConnectNotifier: Failed to connect/reconnect: Work Descriptor. Root Exception was: javax.naming.AuthenticationException: [LDAP: error code 49 - INVALID_CREDENTIALS: Bind failed: Attempt to lookup non-existant entry: cn=sim,ou=people,dc=example,dc=com]; resolved object com.sun.jndi.ldap.LdapCtx#5de37d66. Type: class javax.naming.AuthenticationException
COUNT: 1
org.mule.api.transport.DispatchException: route number 1 failed to be executed. Failed to route event via endpoint: InterceptingChainLifecycleWrapper 'wrapper for processor chain 'null''
[
ScriptComponent{CheckAuth.component.553657235},
org.mule.module.ldap.processors.BindMessageProcessor#647af13d,
org.mule.module.ldap.processors.SearchMessageProcessor#2aac6fa7,
InvokerMessageProcessor [name=ldapUtils, object=com.at.mkrf.aggregate.LDAPUtils#5714c7da, methodName=findGroupByName, argExpressions=[#[payload], #[systemName]], argTypes=[Ljava.lang.Class;#5af349a6]
]. Message payload is of type: NullPayload
On a CompositeRoutingException, you can call:
exception.getExceptions().values()
to get an Array of Throwables thrown from within the scatter-gather. Then just re-throw the appropriate exception.

Also log every exception at error level

Using Groovy / Grails and log4j is there any way to ensure every exception thrown in the code is logged at error level.
Rather than having to find every catch block and explictly log it?
If not groovy / grails - a java suggestion will suffice.
Thanks
I don't believe there's any way to do this for handled exceptions, but you can do it for unhandled exceptions by adding the following to UrlMappings.groovy
"500"(controller: 'error')
Then create an ErrorController.groovy under grails-app/controllers
class ErrorController {
def index() {
Throwable exception = request?.exception?.cause
log.error 'something bad happened', exception
}
}

grails service dead-locking with mysql

I'm trying to add a long list of file into mysql and use spring ACL service with grails to attach permission.
So, in my controller i have:
Files.withTransaction {
Files file = new Files(dataStore:ds,created:new Date(),path:target,name:fileName,contentType:contentType,contentLength:contentLength,isFolder:false).save(flush:true)
file = Files.lock(file.id)
filesService.addPermission(file, username ,BasePermission.ADMINISTRATION)
}
the i have no worries with the Files domain object, it supports huge amount of data ,(specially since i 've disabled versioning in mysql), the problem is on filesService which uses aclUtilService,
#Transactional
#PreAuthorize("hasRole('ROLE_ADMIN') or hasRole('ROLE_USER') or hasRole('ROLE_GROUP_OWNER')")
def addPermission(Files f, String username,Permission permission) {
aclUtilService.addPermission f,username,permission
}
Randomly i have the following deadlock (optmistic?)error :
Deadlock found when trying to get lock; try restarting transaction.
Stacktrace follows:
com.mysql.jdbc.exceptions.jdbc4.MySQLTransactionRollbackException:
Deadlock found when trying to get lock; try restarting transaction at
com.mysql.jdbc.Util.handleNewInstance(Util.java:406) at
com.mysql.jdbc.Util.getInstance(Util.java:381) at
com.mysql.jdbc.SQLError.createSQLException(SQLError.java:1045) at
com.mysql.jdbc.SQLError.createSQLException(SQLError.java:956) at
com.mysql.jdbc.MysqlIO.checkErrorPacket(MysqlIO.java:3558) at
com.mysql.jdbc.MysqlIO.checkErrorPacket(MysqlIO.java:3490) at
com.mysql.jdbc.MysqlIO.sendCommand(MysqlIO.java:1959) at
com.mysql.jdbc.MysqlIO.sqlQueryDirect(MysqlIO.java:2109) at
com.mysql.jdbc.ConnectionImpl.execSQL(ConnectionImpl.java:2648) at
com.mysql.jdbc.PreparedStatement.executeInternal(PreparedStatement.java:2077)
at
com.mysql.jdbc.PreparedStatement.executeUpdate(PreparedStatement.java:2362)
at
com.mysql.jdbc.PreparedStatement.executeUpdate(PreparedStatement.java:2280)
at
com.mysql.jdbc.PreparedStatement.executeUpdate(PreparedStatement.java:2265)
at
org.grails.plugins.springsecurity.service.acl.AclService.save(AclService.groovy:330)
at
org.grails.plugins.springsecurity.service.acl.AclService.createEntries(AclService.groovy:198)
at
org.grails.plugins.springsecurity.service.acl.AclService.updateAcl(AclService.groovy:176)
at
GrailsMelodyGrailsPlugin$_closure5_closure18_closure19.doCall(GrailsMelodyGrailsPlugin.groovy:170)
at
org.grails.plugins.springsecurity.service.acl.AclUtilService.addPermission(AclUtilService.groovy:90)
at
org.grails.plugins.springsecurity.service.acl.AclUtilService.addPermission(AclUtilService.groovy:67)
at
GrailsMelodyGrailsPlugin$_closure5_closure18_closure19.doCall(GrailsMelodyGrailsPlugin.groovy:170)
at
xxxxxxxxxxxxx.FilesService.addPermission(FilesService.groovy:34)
at
GrailsMelodyGrailsPlugin$_closure5_closure18_closure19.doCall(GrailsMelodyGrailsPlugin.groovy:170)
at
xxxxxxxxxxxxxQuantumController$_uploadToS3_closure1$$ENzPdDAW.doCall(QuantumController.groovy:87)
at
org.grails.datastore.gorm.GormStaticApi.withTransaction(GormStaticApi.groovy:686)
at
xxxxxxxxxxxxx.QuantumController$$ENzPdDAW.uploadToS3(QuantumController.groovy:84)
at
grails.plugin.cache.web.filter.PageFragmentCachingFilter.doFilter(PageFragmentCachingFilter.java:195)
at
grails.plugin.cache.web.filter.AbstractFilter.doFilter(AbstractFilter.java:63)
at net.bull.javamelody.JspWrapper.invoke(JspWrapper.java:149) at
net.bull.javamelody.JdbcWrapper$DelegatingInvocationHandler.invoke(JdbcWrapper.java:259)
at
net.bull.javamelody.MonitoringFilter.doFilter(MonitoringFilter.java:202)
at
net.bull.javamelody.MonitoringFilter.doFilter(MonitoringFilter.java:175)
at
java.util.concurrent.ThreadPoolExecutor$Worker.runTask(ThreadPoolExecutor.java:895)
at
java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:918)
at java.lang.Thread.run(Thread.java:680)
Any help please ?
just encapsulated the transaction in controller and use #Transactional in the service to solve the issue:
Files.withTransaction {
Files file = new Files(
...
if (file.validate()) {
file.save()
filesService.addPermission(file,username,BasePermission.ADMINISTRATION)
...}
}