Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to simulate a site down in Java?

My app accesses info on the web, during my development how do I simulate a site is down in Java ? If the url gets me the page my app processes it, but if a site for some reason is temporarily down, or even if the site is up, but the url returns invalid info or it could be the Internet connection is disabled, how can a Java app distinguish those situations ? And be able to tell which is occurring ?

Edit : I'm trying to write my Java app so that when it encounters different url accesses, it knows which case it is dealing with and tell user accordingly.

like image 552
Frank Avatar asked Jan 29 '11 18:01

Frank


2 Answers

The connect() method from the java.net.URLConnection class throws a SocketTimeoutException if it cannot connect to the given URL. You can set a timeout via the setConnectTimeout(int) method and react on the SocketTimeoutException exception which is thrown in this case.

like image 73
Progman Avatar answered Nov 10 '22 03:11

Progman


For the purposes of testing or simulating different error conditions, here are a few additional suggestions:

  • Ensure that the URL's domain is unreachable (domain resolves to an ip address, but the ip address is not reachable). You can fake this by adding an entry in your /etc/hosts file (if unix like)
  • Ensure that the URL's domain is not resolvable, i.e. a fake domain address that does not exist
  • Unplug your client's network cable/wireless: what happens?
  • Unplug your client's network cable while in the middle of a transfer: what happens?
  • Unplug your test server's network cable in the middle of a transfer? What does the client see?
  • kill the test server's web server while in the middle of a transfer? What happens to the client's URL connection?
  • Shutdown the test server's web server and what does the client see when it tries to connect?

As you test these different scenarios you will be surprised to learn what happens to your client. If you are lucky you will get exceptions. Sometimes the client may hang forever. But that's the real world. Good luck.

like image 33
Missaka Wijekoon Avatar answered Nov 10 '22 05:11

Missaka Wijekoon