Solved

Control Timeout in URLConnection

Posted on 2001-06-14
7
927 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
Free Tool: ZipGrep

ZipGrep is a utility that can list and search zip (.war, .ear, .jar, etc) archives for text patterns, without the need to extract the archive's contents.

One of a set of tools we're offering as a way to say thank you for being a part of the community.

 
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

Announcing the Most Valuable Experts of 2016

MVEs are more concerned with the satisfaction of those they help than with the considerable points they can earn. They are the types of people you feel privileged to call colleagues. Join us in honoring this amazing group of Experts.

Question has a verified solution.

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

Suggested Solutions

For beginner Java programmers or at least those new to the Eclipse IDE, the following tutorial will show some (four) ways in which you can import your Java projects to your Eclipse workbench. Introduction While learning Java can be done with…
Introduction This article is the first of three articles that explain why and how the Experts Exchange QA Team does test automation for our web site. This article explains our test automation goals. Then rationale is given for the tools we use to a…
Viewers will learn about the different types of variables in Java and how to declare them. Decide the type of variable desired: Put the keyword corresponding to the type of variable in front of the variable name: Use the equal sign to assign a v…
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…

827 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