1 package org.testng.remote.adapter;
2 
3 import java.io.IOException;
4 import java.net.ServerSocket;
5 import java.net.Socket;
6 import java.util.Properties;
7 
8 import org.testng.ISuite;
9 import org.testng.internal.Utils;
10 import org.testng.remote.ConnectionInfo;
11 import org.testng.xml.XmlSuite;
12 
13 
14 /**
15  * Default Slave adapter, provides an adapter based on static port.
16  *
17  *
18  * @author	Guy Korland
19  * @since 	April 20, 2007
20  */
21 public class DefaultWorkerAdapter implements IWorkerAdapter
22 {
23 	public static final String SLAVE_PORT = "slave.port";
24 
25 	private ConnectionInfo m_connectionInfo;
26 	private int m_clientPort;
27 
28 	@Override
init( Properties prop)29   public void init( Properties prop) throws Exception
30 	{
31 		m_clientPort = Integer.parseInt( prop.getProperty(SLAVE_PORT, "0"));
32 		m_connectionInfo = resetSocket( m_clientPort, null);
33 	}
34 
35 	/*
36 	 * @see org.testng.remote.adapter.IWorkerApadter#getSuite(long)
37 	 */
38 	@Override
getSuite(long timeout)39   public XmlSuite getSuite(long timeout) throws InterruptedException, IOException
40 	{
41       try {
42         return (XmlSuite) m_connectionInfo.getOis().readObject();
43       }
44       catch (ClassNotFoundException e) {
45         e.printStackTrace(System.out);
46         throw new RuntimeException( e);
47       }
48       catch(IOException ex) {
49         log("Connection closed " + ex.getMessage());
50         m_connectionInfo = resetSocket(m_clientPort, m_connectionInfo);
51         throw ex;
52       }
53 	}
54 
55 	/*
56 	 * @see org.testng.remote.adapter.IWorkerApadter#returnResult(org.testng.ISuite)
57 	 */
58 	@Override
returnResult(ISuite result)59   public void returnResult(ISuite result) throws IOException
60 	{
61 		try
62 		{
63 			m_connectionInfo.getOos().writeObject(result);
64 		}
65 		catch(IOException ex) {
66 			log("Connection closed " + ex.getMessage());
67 			m_connectionInfo = resetSocket(m_clientPort, m_connectionInfo);
68 			throw ex;
69 		}
70 	}
71 
resetSocket(int clientPort, ConnectionInfo oldCi)72 	private static ConnectionInfo resetSocket(int clientPort, ConnectionInfo oldCi)
73 	throws IOException
74 	{
75 		ConnectionInfo result = new ConnectionInfo();
76 		ServerSocket serverSocket = new ServerSocket(clientPort);
77 		serverSocket.setReuseAddress(true);
78 		log("Waiting for connections on port " + clientPort);
79 		Socket socket = serverSocket.accept();
80 		result.setSocket(socket);
81 
82 		return result;
83 	}
84 
log(String string)85 	private static void log(String string) {
86 		Utils.log("", 2, string);
87 	}
88 }
89