Solved

Control Timeout in URLConnection

Posted on 2001-06-14
7
909 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
Better Security Awareness With Threat Intelligence

See how one of the leading financial services organizations uses Recorded Future as part of a holistic threat intelligence program to promote security awareness and proactively and efficiently identify threats.

 
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

Free Trending Threat Insights Every Day

Enhance your security with threat intelligence from the web. Get trending threat insights on hackers, exploits, and suspicious IP addresses delivered to your inbox with our free Cyber Daily.

Join & Write a Comment

Suggested Solutions

Title # Comments Views Activity
topping3 challenge 14 50
HashMap Vs TreeMap 12 49
recursion example 16 69
Java / Linux and Regular Expressions 11 47
By the end of 1980s, object oriented programming using languages like C++, Simula69 and ObjectPascal gained momentum. It looked like programmers finally found the perfect language. C++ successfully combined the object oriented principles of Simula w…
Basic understanding on "OO- Object Orientation" is needed for designing a logical solution to solve a problem. Basic OOAD is a prerequisite for a coder to ensure that they follow the basic design of OO. This would help developers to understand the b…
Viewers learn about the third conditional statement “else if” and use it in an example program. Then additional information about conditional statements is provided, covering the topic thoroughly. Viewers learn about the third conditional statement …
Viewers will learn about basic arrays, how to declare them, and how to use them. Introduction and definition: Declare an array and cover the syntax of declaring them: Initialize every index in the created array: Example/Features of a basic arr…

757 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

Need Help in Real-Time?

Connect with top rated Experts

23 Experts available now in Live!

Get 1:1 Help Now