Welcome to the Java Programming Forums


The professional, friendly Java community. 21,500 members and growing!


The Java Programming Forums are a community of Java programmers from all around the World. Our members have a wide range of skills and they all have one thing in common: A passion to learn and code Java. We invite beginner Java programmers right through to Java professionals to post here and share your knowledge. Become a part of the community, help others, expand your knowledge of Java and enjoy talking with like minded people. Registration is quick and best of all free. We look forward to meeting you.


>> REGISTER NOW TO START POSTING


Members have full access to the forums. Advertisements are removed for registered users.

Results 1 to 4 of 4

Thread: Connection Time Out

  1. #1
    Junior Member
    Join Date
    Jun 2011
    Location
    Salt Lake City, Utah
    Posts
    15
    Thanks
    0
    Thanked 0 Times in 0 Posts

    Default Connection Time Out

    I have an application that will continually process an XML file called data.xml for up to 12 devices from a web service and parse the data for my client machine at another location. My dilemma is after usually after 20 hours or so I get a time out error and my server stops. I canít have this happen because my servers will be around the world at unmanned sites. Can someone help resolve my timeout issue?

    package seon.pems.server;
     
    import java.io.IOException;
    import java.io.InputStream;
    import java.net.HttpURLConnection;
    import java.net.MalformedURLException;
    import java.net.ProtocolException;
    import java.net.URL;
    import java.util.ArrayList;
    import java.util.List;
     
    import javax.jms.JMSException;
    import javax.naming.NamingException;
    import javax.xml.parsers.DocumentBuilder;
    import javax.xml.parsers.DocumentBuilderFactory;
    import javax.xml.parsers.ParserConfigurationException;
     
    import org.apache.log4j.Logger;
    import org.w3c.dom.Document;
    import org.xml.sax.SAXException;
     
    import seon.classlibrary.MessageHandler;
    import seon.classlibrary.MessageKind;
    import seon.pems.classlibrary.ConfigurationSettings;
    import seon.pems.classlibrary.Configurator;
    import seon.pems.classlibrary.OutletSettings;
    import seon.pems.classlibrary.PDUCompiledData;
    import seon.pems.classlibrary.PDUSettings;
    import seon.pems.classlibrary.SecurityInit;
    import seon.pems.security.PasswordService_AES256;
    import seon.pems.security.SecurityInfo;
     
    public class PDUServer {
     
    	private static final Logger logger = Logger.getLogger(PDUServer.class);
     
    	/*
    	 *  Following properties are used for each 
    	 *  to control what PDU is displayed.
    	 */
    	private String lastPDU;
    	private List<String> pduNames;
     
    	/*
    	 * The properties are used for security between the 
    	 * server and the PDU web service.  If the system
    	 * goes to a local firewall you can omit these.
    	 */
    	private SecurityInit userConfig;
    	private PasswordService_AES256 crypt;
     
    	/*
    	 * These properties are used to process each PDU
    	 * web service and retrieve their xml files.
    	 */
    	private URL url;
    	private HttpURLConnection connection;
    	private Document document;
     
    	/*
    	 * This property is used to gather all the default 
    	 * information for the PEMS system.
    	 */
    	private ConfigurationSettings configSettings;
     
    	/*
    	 * Properties for JBoss
    	 */
    //	private DataResponsePower databackPower;
    	private Object initConfig = new Object();
     
    	private PDUServerJBossManager pduJBoss;
     
    	public PDUServer() {
     
    		/*
    		 * First get the default setting from the
    		 * pems.properties file located in /seon/pems/
    		 */		
    		try {
    			configSettings = loadDefaultConfigurationSettings();
    			this.lastPDU = configSettings.getLastPDU();
    			this.pduNames = configSettings.getPduName();
    			for (String pduName : configSettings.getPduName()) {
    				System.out.println(pduName);
    			}
    		} catch (Exception e) {
    			logger.debug("Error occurred while setting the pdu names or last pdu", e);
    		}
     
    		/*
    		 * Create a JBoss listener for the PDU server
    		 */
    		DataResponsePower databackPower = createJBossListener(configSettings.getPduControlQueueName(), 
    				configSettings.getPduNotificationQueueName(), configSettings.getHostName());
     
    		try {
    			new PDUServerJBossManager(databackPower).start();
    		} catch (Exception e) {
    			// TODO Auto-generated catch block
    			e.printStackTrace();
    		}
     
    	}
     
    	/**
    	 * @param controlQueueName - 
    	 * @param notificationTopicName - 
    	 * @param hostname - This is the host name of the server located in the /etc/hosts file.
    	 * @return 
    	 */
    	private DataResponsePower createJBossListener(String controlQueueName, String notificationTopicName, String hostname) {
     
    		DataResponsePower databackPower = null;
     
    		synchronized (initConfig) {
     
    			boolean successCamera = false;
     
    			for (int i = 0; i < 20; i++) {
    				try {					
    					databackPower = DataResponsePower.getControlCommand(notificationTopicName, hostname);
    					successCamera = true;
    					break;
    				} catch (Exception e) 
    				{
    					logger.error("Exception caught and suppressed while attempting to get controlCommand for Power Data.", e);
    				}
    			}			
     
    			if (!successCamera) {
    				logger.fatal("Error trying to connect with JBoss");
    				System.exit(1);
    			}	
     
    			try {
    				@SuppressWarnings("unused")
    				MessageHandler messageHandler = new MessageHandler(hostname, controlQueueName,
    						(Object) this, MessageKind.QUEUE);
    			} catch (JMSException e1) {
    				logger.fatal("messageHandler init error: " + e1.getMessage());
    				System.exit(1);
    			} catch (NamingException e1) {
    				logger.fatal("messageHandler init error: " + e1.getMessage());
    				System.exit(1);
    			}
    		}
     
    		return databackPower;
    	}
     
    	/**
    	 * @return - returns an object of configuration settings.  These settings
    	 * will used throughout the PEMS system.
    	 */
    	private ConfigurationSettings loadDefaultConfigurationSettings() {
     
    		ConfigurationSettings configSettings = null;
     
    		if (configSettings == null) {
    			configSettings = Configurator.LoadConfigurationSettings();
    		}	
     
    		return configSettings;
    	}
     
    	public static void main(String[] args) {
    		new PDUServer();
    	}
     
    	protected class PDUServerJBossManager extends Thread {
     
    		private DataResponsePower databackPower;
    		private PDUCompiledData pwrData;
    		private Object pduLock = new Object();
     
    		public PDUServerJBossManager(DataResponsePower databackPower) {
    			this.databackPower = databackPower;
    		}
     
    		@Override
    		public void run() {
    			SecurityInfo si = null;
    			PDUSettings ps = null;
    			OutletSettings os = null;
    			Object pduLock = new Object();
    			PDUCompiledData cd = null;
    			ArrayList<PDUCompiledData> cdl = null;
     
    			try {
    				if (cdl == null) {
    					cdl = new ArrayList<PDUCompiledData>();
    				}
     
    				if (pduNames != null) {
    					/*
    					 * for each PDU name process the data.xml file
    					 * and first check for alarm thresholds, if any 
    					 * thresholds exceeded notify analyst. Otherwise, 
    					 * send back an object of just the pdu data requested
    					 * for the client tp display.
    					 */
    					for (String pdu : pduNames) {
    //						cdl.add(getXMLData(pdu));
    //						
    //						synchronized (pduLock) {
    //							System.out.println(cdl.toString());
    //							databackPower.setPDUCompiledData(cdl);
    //						}
    						processXMLFile(pdu, databackPower);
    					}
    				} else {
    					// if the pduNames are null you need to check the config settings again.
    				}
     
    			} catch (Exception e) {
    				logger.error("An error occurred PDUServerJBossManager class while trying to read the input object and calling the necessary methods.", e);
    			}
    		}
     
    		private void processXMLFile(String pduName, DataResponsePower databackPower2) {
     
    			DocumentBuilder builder = null;
    			boolean success = false;
     
    			while(true) {
    				ParseXMLFile pxf = null;
    				InputStream is = null;
     
    				try {
    					is = sendURLRequest(pduName);
    				} catch (Exception e1) {
    					logger.debug("Error creating input stream.", e1);
    				}
     
    				 /* This creates a DOM XML Parser, it is the DocumentBuilder instance that is
    				 * the DOM parser.
    				 */
    				DocumentBuilderFactory builderFactory = DocumentBuilderFactory.newInstance();
     
    				try {
    					builder = builderFactory.newDocumentBuilder();
    				} catch (ParserConfigurationException e) {
    					logger.error("Error trying to build the buildFactor for new document builder in ParseXMLFile", e);
    				}	
     
    				try {
    					document = builder.parse(is);
    					success = true;	
    				} catch (SAXException e) {
    					logger.error("Error creating trying to set document to parse input stream in ParseXMLFile", e);
    				} catch (IOException e) {
    					logger.error("IO error trying to set document to parse input stream in ParseXMLFile", e);
    				}
     
    				if (!success) {
    					logger.fatal("Error trying to connect with creating a document to process the XML file.");
    					System.exit(1);
    				}
     
    				if (pxf == null) {
    					pxf = new ParseXMLFile();
    				}
     
    				try {
    					pwrData = pxf.readXMLFile(document);
    					System.out.println(pduName + ", " + pwrData.toString());
    					synchronized (pduLock ) {
    						if (pduName.contains(lastPDU)) {
    							System.out.println(pduName + " data sent to client, " + pwrData.toString());
    							databackPower2.setPDUCompiledData(pwrData);
    						}
    					}
    				} catch (InterruptedException e) {
    					logger.debug("An itteruption occurred while reading the xml file for pdu: " + pduName, e);
    				}
    			}
    		}
     
     
     
    		private InputStream sendURLRequest(String pduName) {
    			InputStream is = null;
     
    			URL url = null;
    			HttpURLConnection connection = null;
     
    			try {
    				url = new URL("http://" + pduName + "/data.xml");
    			} catch (MalformedURLException e1) {
    				logger.error("Bad URL string in ParseXMLFile", e1);
    			}
     
    			try {
    				connection = (HttpURLConnection)url.openConnection();
    			} catch (IOException e1) {
    				logger.error("Error trying to connect with HTTPURLconnection in ParseXMLFile", e1);
    			}
    			try {
    				connection.setRequestMethod("GET" );
    			} catch (ProtocolException e1) {
    				logger.error("Error processing GET request in ParseXMLFile", e1);
    			}
    			connection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
    			connection.setRequestProperty("Content-Language", "en-US");
    			connection.setDoInput(true);
    			connection.setDoOutput(true);
    			connection.setUseCaches(false);
     
    			/*
    			 * If the getting of the input stream fails, just let
    			 * it try again!
    			 */
    			try {
    				is  = connection.getInputStream();
    			} catch (IOException e1) {	
    				e1.printStackTrace();
    				logger.debug("Error trying to get the input stream in ParseXMLFile", e1);
    //				System.exit(0);
    			}
     
    			return is;
    		}	
     
    	}
     
    }


  2. #2
    Super Moderator Sean4u's Avatar
    Join Date
    Jul 2011
    Location
    Tavistock, UK
    Posts
    637
    Thanks
    5
    Thanked 103 Times in 93 Posts

    Default Re: Connection Time Out

    I get a time out error
    Copy and paste the full error message and stack trace

  3. #3
    Junior Member
    Join Date
    Jun 2011
    Location
    Salt Lake City, Utah
    Posts
    15
    Thanks
    0
    Thanked 0 Times in 0 Posts

    Default Re: Connection Time Out

    Here is the error!
    [hightlight=java]
    java.net.ConnectException: Connection timed out
    at java.net.PlainSocketImpl.socketConnect(Native Method)
    at java.net.PlainSocketImpl.doConnect(Unknown Source)
    at java.net.PlainSocketImpl.connectToAddress(Unknown Source)
    at java.net.PlainSocketImpl.connect(Unknown Source)
    at java.net.SocksSocketImpl.connect(Unknown Source)
    at java.net.Socket.connect(Unknown Source)
    at java.net.Socket.connect(Unknown Source)
    at sun.net.NetworkClient.doConnect(Unknown Source)
    at sun.net.www.http.HttpClient.openServer(Unknown Source)
    at sun.net.www.http.HttpClient.openServer(Unknown Source)
    at sun.net.www.http.HttpClient.<init>(Unknown Source)
    at sun.net.www.http.HttpClient.New(Unknown Source)
    at sun.net.www.http.HttpClient.New(Unknown Source)
    at sun.net.http://www.protocol.http.HttpURLConn...Client(Unknown Source)
    at sun.net.http://www.protocol.http.HttpURLConn...onnect(Unknown Source)
    at sun.net.http://www.protocol.http.HttpURLConn...onnect(Unknown Source)
    at sun.net.http://www.protocol.http.HttpURLConn...Stream(Unknown Source)
    at seon.pems.server.PDUServer$PDUServerJBossManager.s endURLRequest(PDUServer.java:316)
    at seon.pems.server.PDUServer$PDUServerJBossManager.p rocessXMLFile(PDUServer.java:231)
    at seon.pems.server.PDUServer$PDUServerJBossManager.r un(PDUServer.java:210)

    [/highlight]

  4. #4
    Super Moderator Sean4u's Avatar
    Join Date
    Jul 2011
    Location
    Tavistock, UK
    Posts
    637
    Thanks
    5
    Thanked 103 Times in 93 Posts

    Default Re: Connection Time Out

    Are the origin servers you're requesting data.xml from reliable? Do you catch the socket timeout and retry the request? It would be optimistic to rely on a remote server being permanently available.

    If it's not the remote end that's the problem, you might be suffering from connection re-use in the JVM. I'm not sure how that would manifest itself as an issue of this kind, but you could consider explicitly closing (for example) the InputStream from the URL connection. That may possibly force the JVM to create a new connection for each request, but I'm indulging in hand-waving now. I have a Java project that queries a pool of origin servers - about a dozen of them - for updates to a feed at intervals of hours to days that has run for years without the JVM exiting, and I see in my code that I explicitly close the InputStream.

Similar Threads

  1. Replies: 0
    Last Post: May 10th, 2011, 08:02 AM
  2. Replies: 0
    Last Post: March 26th, 2011, 12:07 PM
  3. multiple tcp connection?
    By nasser in forum Java Networking
    Replies: 4
    Last Post: July 31st, 2010, 08:35 AM
  4. Thread and connection
    By Param in forum Threads
    Replies: 0
    Last Post: April 26th, 2010, 04:43 AM
  5. cant get rid of http connection
    By kartik in forum Java Networking
    Replies: 1
    Last Post: July 21st, 2009, 04:09 AM