Solved

Control Timeout in URLConnection

Posted on 2001-06-14
7
922 Views
Last Modified: 2008-02-26
i just wanna to know it's there any possible method to control the timeout of my jsp which using URLConnection to grep a cgi program. cause i don't want the timeout takes too long as i want to catch the timout event by my code.

sp that can i use java code to control the timeout, or config it in web server or servlet engine..

the config as below :

Win2K
IIS 5
JRun 4.0
JDK1.2.2

i have tried to apply the HttpURLConnectionTimeout classes in my server, but it make the Jrun Server down everytime...
reminded that i am using JDK1.2.2....
0
Comment
Question by:hi_billy
7 Comments
 
LVL 7

Expert Comment

by:Ravindra76
ID: 6190456
I am not sure for URLConnection

Use Sockets instead of URLConnection and
use the method

 setSoTimeout

in java.net.Socket
0
 
LVL 35

Expert Comment

by:TimYates
ID: 6190515
Or you can set up a watcher thread that sleeps for a set number of milliseconds, and then checks if the URLConnection has returned...if not, stop it and throw an exception :-)

Good Luck!!!

Tim.
0
 
LVL 7

Expert Comment

by:Ravindra76
ID: 6190530
Got it

Try this link and enjoy

http://www.sirius.com/~merojo/sockets.html
0
PRTG Network Monitor: Intuitive Network Monitoring

Network Monitoring is essential to ensure that computer systems and network devices are running. Use PRTG to monitor LANs, servers, websites, applications and devices, bandwidth, virtual environments, remote systems, IoT, and many more. PRTG is easy to set up & use.

 
LVL 7

Accepted Solution

by:
Ravindra76 earned 200 total points
ID: 6190539
We derive 4 classes so as to preserve the symmetry with the java source code:

HttpURLConnectionTimeout extends sun.net.www.protocol.http.HttpURLConnection
HttpTimeoutHandler extends sun.net.www.protocol.http.Handler
HttpTimeoutFactory implements java.net.URLStreamHandlerFactory
HttpClientTimeout extends sun.net.www.http.HttpClient


On with the source code.



HttpURLConnectionTimeout
// whatever package you want
import sun.net.www.http.HttpClient;
import java.net.*;
import java.io.*;
public class HttpClientTimeout extends HttpClient
{
    public HttpClientTimeout(URL url, String proxy, int proxyPort) throws IOException
      {
            super(url, proxy, proxyPort);
      }
      
    public HttpClientTimeout(URL url) throws IOException
      {
            super(url, null, -1);
    }
      
      public void SetTimeout(int i) throws SocketException {
          serverSocket.setSoTimeout(i);
    }
      
    /* This class has no public constructor for HTTP.  This method is used to
     * get an HttpClient to the specifed URL.  If there's currently an
     * active HttpClient to that server/port, you'll get that one.
       *
       * no longer syncrhonized -- it slows things down too much
       * synchronize at a higher level
     */
    public static HttpClientTimeout GetNew(URL url)  
    throws IOException {
      /* see if one's already around */
      HttpClientTimeout ret = (HttpClientTimeout) kac.get(url);
      if (ret == null) {
          ret = new HttpClientTimeout (url);  // CTOR called openServer()
      } else {
          ret.url = url;
      }
      // don't know if we're keeping alive until we parse the headers
      // for now, keepingAlive is false
      return ret;
    }
      
      public void Close() throws IOException
      {
            serverSocket.close();
      }
      
      public Socket GetSocket()
      {
            return serverSocket;
      }
   
      
}



HttpTimeoutFactory
import java.net.*;

public class HttpTimeoutFactory implements URLStreamHandlerFactory
{
      int fiTimeoutVal;
      public HttpTimeoutFactory(int iT) { fiTimeoutVal = iT; }
      public URLStreamHandler createURLStreamHandler(String str)
      {
            return new HttpTimeoutHandler(fiTimeoutVal);
      }
      
}



HttpTimeoutHandler
import java.net.*;
import java.io.IOException;

public class HttpTimeoutHandler extends sun.net.www.protocol.http.Handler
{
      int fiTimeoutVal;
      HttpURLConnectionTimeout fHUCT;
      public HttpTimeoutHandler(int iT) { fiTimeoutVal = iT; }
      
    protected java.net.URLConnection openConnection(URL u) throws IOException {
            return fHUCT = new HttpURLConnectionTimeout(u, this, fiTimeoutVal);
    }

    String GetProxy() { return proxy; }            // breaking encapsulation
    int GetProxyPort() { return proxyPort; }    // breaking encapsulation
      
      public void Close() throws Exception
      {
            fHUCT.Close();
      }
      
      public Socket GetSocket()
      {
            return fHUCT.GetSocket();
      }
}



HttpURLConnectionTimeout
import java.net.*;
import java.io.*;
import sun.net.www.http.HttpClient;

public class HttpURLConnectionTimeout extends sun.net.www.protocol.http.HttpURLConnection
{
      int fiTimeoutVal;
    HttpTimeoutHandler fHandler;
      HttpClientTimeout fClient;
        public HttpURLConnectionTimeout(URL u, HttpTimeoutHandler handler, int iTimeout) throws IOException
      {  
          super(u, handler);
            fiTimeoutVal = iTimeout;
      }
   
      public HttpURLConnectionTimeout(URL u,  String host, int port) throws IOException
      {  
          super(u, host, port);
      }
      
    public void connect() throws IOException {
      if (connected) {
          return;
      }
      try {
          if ("http".equals(url.getProtocol()) /* && !failedOnce <- PRIVATE */ ) {
            // for safety's sake, as reported by KLGroup
            synchronized (url)
            {
                  http = HttpClientTimeout.GetNew(url);
            }
            fClient = (HttpClientTimeout)http;
               ((HttpClientTimeout)http).SetTimeout(fiTimeoutVal);
          } else {
            // make sure to construct new connection if first
            // attempt failed
            http = new HttpClientTimeout(url, fHandler.GetProxy(), fHandler.GetProxyPort());
          }
          ps = (PrintStream)http.getOutputStream();
      } catch (IOException e) {
          throw e;  }
            // this was missing from the original version
            connected = true;
      }

    /**
     * Create a new HttpClient object, bypassing the cache of
     * HTTP client objects/connections.
     *
     * @param url      the URL being accessed
     */
    protected HttpClient getNewClient (URL url)
    throws IOException {
            HttpClientTimeout client = new HttpClientTimeout (url, (String)null, -1);
            try {
            client.SetTimeout(fiTimeoutVal);
            } catch (Exception e)
            { System.out.println("Unable to set timeout value"); }
      return (HttpClient)client;
    }

    /**
     * opens a stream allowing redirects only to the same host.
     */
    public static InputStream openConnectionCheckRedirects(URLConnection c)
      throws IOException
    {
        boolean redir;
        int redirects = 0;
        InputStream in = null;

        do {
            if (c instanceof HttpURLConnectionTimeout) {
                ((HttpURLConnectionTimeout) c).setInstanceFollowRedirects(false);
            }
 
            // We want to open the input stream before
            // getting headers, because getHeaderField()
            // et al swallow IOExceptions.
            in = c.getInputStream();
            redir = false;
 
            if (c instanceof HttpURLConnectionTimeout) {
                HttpURLConnectionTimeout http = (HttpURLConnectionTimeout) c;
                int stat = http.getResponseCode();
                if (stat >= 300 && stat <= 305 &&
                        stat != HttpURLConnection.HTTP_NOT_MODIFIED) {
                    URL base = http.getURL();
                    String loc = http.getHeaderField("Location");
                    URL target = null;
                    if (loc != null) {
                        target = new URL(base, loc);
                    }
                    http.disconnect();
                    if (target == null
                        || !base.getProtocol().equals(target.getProtocol())
                        || base.getPort() != target.getPort()
                        || !HostsEquals(base, target)
                        || redirects >= 5)
                    {
                        throw new SecurityException("illegal URL redirect");
                }
                    redir = true;
                    c = target.openConnection();
                    redirects++;
                }
            }
        } while (redir);
        return in;
    }

    // Same as java.net.URL.hostsEqual


      static boolean HostsEquals(URL u1, URL u2)
    {
        final String h1 = u1.getHost();
        final String h2 = u2.getHost();

        if (h1 == null) {
            return h2 == null;
        } else if (h2 == null) {
            return false;
        } else if (h1.equalsIgnoreCase(h2)) {
            return true;
        }
            // Have to resolve addresses before comparing, otherwise
            // names like tachyon and tachyon.eng would compare different
        final boolean result[] = {false};

        java.security.AccessController.doPrivileged(
            new java.security.PrivilegedAction() {
            public Object run() {
            try {
                InetAddress a1 = InetAddress.getByName(h1);
                InetAddress a2 = InetAddress.getByName(h2);
                result[0] = a1.equals(a2);
            } catch(UnknownHostException e) {
            } catch(SecurityException e) {
            }
            return null;
            }
        });

        return result[0];
      }
      
      void Close() throws Exception
      {
            fClient.Close();
      }
      
      Socket GetSocket()
      {
            return fClient.GetSocket();
      }
}


Sample Usage #1
import java.net.*;
public class MainTest
{

      public static void main(String args[])
      {
          int i = 0;
          try {
                  URL theURL = new URL((URL)null, "http://www.snowball.com", new HttpTimeoutHandler(150)); // timeout value in milliseconds

              // the next step is optional
                  theURL.setURLStreamHandlerFactory(new HttpTimeoutFactory(150));

            
                  URLConnection theURLconn = theURL.openConnection();
              theURLconn.connect();
              i = theURLconn.getContentLength();
        }
        catch (InterruptedIOException e)
        {
              System.out.println("timeout on socket");
        }
        System.out.println("Done, Length:" + i);
      }
}



Sample Usage #2
            try
            {
                  HttpTimeoutHandler xHTH = new HttpTimeoutHandler(10);      // timeout value in milliseconds
              URL theURL = new URL((URL)null, "http://www.javasoft.com", xHTH);
              HttpURLConnection theUC = theURL.openConnection();
                  .
                  .
                  .
            }
            catch (InterruptedIOException e)
            {
                  // socket timed out

            }


0
 
LVL 7

Expert Comment

by:Sasha_Mapa
ID: 6190613
This is an open RFE on java.sun.com - http://developer.java.sun.com/developer/bugParade/bugs/4143518.html
The good news is that JDK1.4 introduces a system property "http.defaultSocketTimeout", which you can modify.

Sasha Maryanovsky.
0
 
LVL 3

Expert Comment

by:jerelw
ID: 6191017
You could try not closing your stream and writing a
out.println("<Script>updateStatus(\"Working\")</Script>"); every 30-45 seconds.

Which would use a JavaScript function to update a progress bar.

0
 
LVL 14

Expert Comment

by:sudhakar_koundinya
ID: 8950701


No comment has been added lately, so it's time to clean up this TA.
I will leave a recommendation in the Cleanup topic area that this question is:


--  points to ravindra76


Please leave any comments here within the next seven days.
 
PLEASE DO NOT ACCEPT THIS COMMENT AS AN ANSWER!
 
sudhakar_koundinya
EE Cleanup Volunteer
---------------------
If you feel that your question was not properly addressed, or that none of the comments received were appropriate answers, please post your concern in THIS thread.
0

Featured Post

3 Use Cases for Connected Systems

Our Dev teams are like yours. They’re continually cranking out code for new features/bugs fixes, testing, deploying, testing some more, responding to production monitoring events and more. It’s complex. So, we thought you’d like to see what’s working for us.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

After being asked a question last year, I went into one of my moods where I did some research and code just for the fun and learning of it all.  Subsequently, from this journey, I put together this article on "Range Searching Using Visual Basic.NET …
Java Flight Recorder and Java Mission Control together create a complete tool chain to continuously collect low level and detailed runtime information enabling after-the-fact incident analysis. Java Flight Recorder is a profiling and event collectio…
The viewer will learn how to implement Singleton Design Pattern in Java.
This tutorial explains how to use the VisualVM tool for the Java platform application. This video goes into detail on the Threads, Sampler, and Profiler tabs.

773 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question