OkHttp MockWebServer as standalone mock server - okhttp

I already have OkHttp MockWebServer running with my Espresso UI tests for Android. Everything is working fine.
Now I want to have MockWebServer standalone running on my localhost to other clients to be able to connect to it. Clients like Appium, internet browser etc. which will get mocked response from the server. I want to reuse already prepared mocking code and not using something like Wiremock.
My approach is to build standalone jar artifact in separate Java/Kotlin project which will run on my machine using cmd line. The sample code is below.
The problem is I'm not able to connect to shown URL address of the server. I'm trying ping commands etc. But the server is not found. Don't know what to try or setup next.
Thanks
Error message:
ping http://kubernetes.docker.internal:62037
Ping request could not find host http://kubernetes.docker.internal:62037. Please check the name and try again.
MockServer:
object MockServer {
fun init() {
GlobalScope.launch(Dispatchers.IO) {
val mockWebServer = MockWebServer()
mockWebServer.start()
println("Server url: " + mockWebServer.url("").toString())
}
}
Main class:
fun main(args: Array<String>) {
MockServer.init()
println("MockServer running")
Thread.sleep(30000) // main thread is sleeping but server is running in different thread
println("MockServer exit")
exitProcess(0)
}

Related

How to deploy and interact with a rust websocket?

I'm a beginner in Rust and WebSockets and I'm trying to deploy on Heroku a little chat backend I wrote (everything works on localhost). The build went well and I can see the app is running, and I'm now trying to connect to the WebSocket from a local HTML/Javascript frontend, but it is not working.
Here is my code creating the WebSocket on my rust server on Heroku (using the tungstenite WebSocket crate):
async fn main() -> Result<(), IoError> {
let port = env::var("PORT").unwrap_or_else(|_| "8080".to_string());
let addr = format!("0.0.0.0:{}", port);
// Create the event loop and TCP listener we'll accept connections on.
let try_socket = TcpListener::bind(&addr).await;
let listener = try_socket.expect("Failed to bind");
println!("Listening on: {}", addr);
and here is the code in my Javascript file that tries to connect to that WebSocket:
var ws = new WebSocket("wss://https://myappname.herokuapp.com/");
My web client gets the following error in the console:
WebSocket connection to 'wss://https//rocky-wave-51234.herokuapp.com/' failed
I searched to find the answer to my issue but unfortunately didn't find a fix so far. I've found hints that I might have to create an HTTP server first in my backend and then upgrade it to a WebSocket, but I can't find a resource on how to do that and don't even know if this is in fact the answer to my problem. Help would be greatly appreciated, thanks!
I think your mistake is the URL you use:
"wss://https://myappname.herokuapp.com/"
A URL usually starts with <protocol>://. The relevant protocols here are:
http - unencrypted hypertext
https - encrypted hypertext
ws - unencrypted websocket
wss - encrypted websocket
So if your URL is an encrypted websocket, it should start only with wss://, a connection cannot have multiple protocols at once:
"wss://myappname.herokuapp.com/"

Spring Data Couchbase - Connection problem with single server

I am getting started with Spring Boot and Spring Data Couchbase and I am having problems to connect to my couchbase server.
I using IntelliJ and I have used the Spring Initialzr to create my project.
Here's my configuration (I am using Kotlin):
#Configuration
class Config : AbstractCouchbaseConfiguration() {
override fun getBootstrapHosts(): List<String> = Collections.singletonList("10.0.0.10")
override fun getBucketName(): String = "cwp"
override fun getBucketPassword(): String = "password"
}
But instead of "just connecting" to the given ip there seems to be some reverse dns and so on in place which resolves wrong ips (due to routers and vpn) and so I am getting the following errors:
[CWSRV.fritz.box:8091][ConfigEndpoint]: Socket connect took longer than specified timeout: connection timed out: CWSRV.fritz.box/10.0.0.112:8091
The name of my server is CWSRV and I am using a vpn between my routers (Fritzboxes)
To omit such problems I want to use just the ip without any mishmash.
Any help would be appreciated!
I figured it out myself:
It seems that the Java SDK does a reverse DNS lookup if it gets an IP address. Since I had not reverse zone created in my DNS server it resolved to the router on the server side which return cwsrv.fritz.box. That resolved to 10.0.0.112 (instead of 10.0.0.10 - my server could have had this ip address assigned from the router any time in the past) and there no Couchbase server responded).
I created an entry of the server in my DNS and it works.
Resolution: Since the Couchbase (Java) SDK seems to rely on properly configured DNS make sure that Forward and Reverse lookups work as expected! :)

Getting error 504 in test server but not locally

I've been trying to fix a really annoying problem in a Java Web project. We use Spring (3.1.4) with webflow (2.3.1), running over Wildfly 11.0 on a Amazon Server. In short, the remote server is giving 504 - Timeout error for a task that the local environment doesn't.
An specific page exports a .xls report which internally do a lot of work in consulting database and other aplication REST APIs. This functionality is inside a ManagedBean like so:
#org.springframework.stereotype.Component
#Scope(value = "request")
public class ReportMB {
...
public void export(){
try{
// code goes here
// generates HttpServletResponse containing the report file
} catch (...) {...}
}
This report is successfully generated in my development machine even if I choose too many data to be included, although it takes up to few minutes to complete. When it runs on the remote server, with the same Wildfly version and project deployment, we get 504 - Timeout with far less data in under 100 seconds.
I've already examined the logs and even debugged the proccess (locally), and both environments (local and remote) do not thow any exception. Do you have any clue why the local server waits until the function finishes and the file gets ready but the remote server doesn't, or at least do you have an idea on how to increase the Wildfly/Spring timeout tolerance for this request? (I have seen many examples of changing the deployment timeout but nothing related to the request timeout)
Thank you in advance.
The 504 will be being created by the loadbalancer not the app server. Increase the timeout on the loadbalancer

How to use Google Cloud PubSub with Proxy?

I'm working with an application that interacts with Google Cloud PubSub. It works fine in normal scenario but I want to enable proxy support so I was going through Publisher.Builder and Subscriber classes and their APIs to see if there are any APIs available to enable proxy support. I managed to find only the setChannelProvider but I'm not sure whether that will work or not.
The following code snippet is what I'm thinking of using but that doesn't seem to work.
ManagedChannel channel = ManagedChannelBuilder.forAddress(proxyHost, proxyPort).build();
TransportChannelProvider channelProvider = FixedTransportChannelProvider.create(GrpcTransportChannel.create(channel));
publisherBuilder.setChannelProvider(channelProvider);
I wasn't able to successfully publish or pull messages to the cloud service. I get the following error:
java.util.concurrent.ExecutionException: io.grpc.StatusRuntimeException: DEADLINE_EXCEEDED: deadline exceeded after 9978300322ns
So I wanted to know does the PubSub service support proxy through APIs or does it only support the proxy setting i.e. host and port to be provided in the environment path only.
You can specify the proxyHost/port directly using JVM args https.proxyHost, https.proxyPort
mvn clean install -Dhttps.proxyHost=localhost -Dhttps.proxyPort=3128 exec:java
then just directly create a client of your choice
TopicAdminSettings topicAdminSettings = TopicAdminSettings.newBuilder().build();
TopicAdminClient topicAdminClient = TopicAdminClient.create(topicAdminSettings);
FYI- Setting ManagedChannelBuilder.forAddress() here overrides the final target for pubsub (which should be pubsub.googleapis.com 443 (not the proxy)
Here is a medium post i put together as well as a gist specificlly for pubsub and pubsub+proxy that requires basic auth headers
finally, just note, its https.proxyHost even if you're using httpProxy, ref grpc#9561
Proxy authentication via HTTP is not supported by Google Pub/Sub, but it can be configured by using GRPC_PROXY_EXP environment variable.
I found the same error that you got here (that's why I assume you are using HTTP) and it got fixed by using what I said.
You need to set JVM args: https.proxyHost, https.proxyPort
for proxy authentication an additional configration is needed before any client creation:
Authenticator.setDefault(new Authenticator() {
protected PasswordAuthentication getPasswordAuthentication() {
return
new PasswordAuthentication(proxyUsername,proxyPassword).toCharArray());
}

Connecting two WebSocket servers to eachother

I have two WebSocket servers that can communicate wonderfully with a client. They are on two separate machines, implemented in Java and running inside WildFly8 webservers. What I need them to do now is communicate with each other. That means: client sends message to server 1, server 1 sends message to server 2, receives the reply and sends it back to client.
The servers run on different apps in OpenShift and I need them to use websockets. Or some other type of communication, but I haven't managed to find anything that actually works so far (RMI or normal socket connections won't work).
What I basically tried to do is use the same code from the client within the onMessage method of the first server. Something like this:
#OnMessage
public void message(Session session, String msg){
...
WebSocketContainer container = ContainerProvider.getWebSocketContainer();
Session NewSession = container.connectToServer(Client.class, URI.create(URL));
NewSession.getBasicRemote().sendText("Routed :" + input);
...
}
However, the server does not connect to the other server and I don't know why.
Any suggestions?
Thank you!
Put connectToServer inside a try {} catch, you might get an error. Log it.
I'm struggling to do exactly the same things (2 websocket servers, Wildfly 8), and I get a permission denied error. See my post here:
https://stackoverflow.com/questions/30966757/java-server-to-server-communication-with-websockets-permission-denied

Resources