/*
 * 
 * Copyright 2005 Sun Microsystems, Inc.
 * 
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 * 
 * 	http://www.apache.org/licenses/LICENSE-2.0
 * 
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 * 
 */
package com.sun.jini.compat.test;

import java.rmi.RemoteException;

import java.net.InetAddress;
import java.net.MulticastSocket;
import java.net.ServerSocket;
import java.net.Socket;
import java.net.DatagramPacket;
import java.net.UnknownHostException;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.EOFException;
import java.io.IOException;

import com.sun.jini.compat.harness.Status;
import com.sun.jini.compat.harness.DefaultTest;
import com.sun.jini.compat.harness.BasicAdmin;
import com.sun.jini.compat.harness.BasicServiceAdmin;
import com.sun.jini.compat.harness.Config;
import com.sun.jini.compat.harness.TestUtility;

import net.jini.discovery.Constants;

import net.jini.core.lookup.ServiceID;

/**
 * Tests whether a service responds to an announcement from a 
 * lookup service that it should respond to by connecting to 
 * the specified socket and sending a unicast request.
 */
public class AnnouncementResponseTest extends DefaultTest {

    private BasicAdmin admin;
    SocketThread st;
    Socket sock;

    /**
     * Sets up a socket-listening thread that listens on the port 
     * specified in the announcement packet. The test then sends 
     * out properly formatted announcement packets in
     * the appropriate multicast group and in the public lookup 
     * service group every second up to the failureTime. If 
     * the service connects to the socket and sends a unicast
     * request packet, the test decodes the packet and checks 
     * its formatting. If the service doesn't connect to the socket 
     * within the failureTime, or sends an improperly formatted 
     * unicast request packet, the service fails.
     *
     * @param args Command line arguments passed through
     * @return The status of this run (failed or passed
     *         and a comment)
     */
    public Status run(String[] args) {
	Config conf = getConfig();
	admin = conf.getAdmin();

	try {
	    TestUtility.log(Config.ALL,"Test: starting program");
	    admin.start();
	} catch (RemoteException re) {
            TestUtility.log(Config.ERROR,"Test: caught exception",re);
            return Status.failed(Status.ENV,"Problem starting program");
        }

	try {
	    st = new SocketThread(conf.getFailureTime());
	} catch (IOException ioe) {
	    TestUtility.log(Config.ERROR,"Test: caught exception",ioe);
	    return Status.failed(Status.ENV,"Could not construct a "
		+ "ServerSocket");
	}

	MulticastSocket ms = null;
	try {
	    TestUtility.log(Config.ALL,"Test: opening multicast "
		+ "announcement socket");
	    ms = new MulticastSocket(Constants.discoveryPort);
	    ms.joinGroup(Constants.getAnnouncementAddress());
	    ms.setSoTimeout(conf.getFailureTime());
	} catch (IOException ioe) {
	    TestUtility.log(Config.ERROR,"Test: caught exception",ioe);
	    return Status.failed(Status.ENV,"Could not construct or "
		+ "configure a MulticastSocket");
	}

	DatagramPacket sendPacket = null;
	try {
	    TestUtility.log(Config.ALL,"Test: creating lookup announcement "
		+ "containing host and port: " 
		+ InetAddress.getLocalHost().getHostAddress() + ":"
		+ st.getServerSocketPort());
	    ByteArrayOutputStream byteOut = new ByteArrayOutputStream();
	    DataOutputStream dataOut = new DataOutputStream(byteOut);
	    ServiceID sid = new ServiceID(42l, 42l);
	    dataOut.writeInt(1);
	    dataOut.writeUTF(InetAddress.getLocalHost().getHostAddress());
	    dataOut.writeInt(st.getServerSocketPort());
	    sid.writeBytes(dataOut);
	    dataOut.writeInt(1);
	    dataOut.writeUTF("");

	    byte[] buf = byteOut.toByteArray();
	    sendPacket = new DatagramPacket(buf, buf.length,
		Constants.getAnnouncementAddress(), 
		Constants.discoveryPort);
	} catch (UnknownHostException uhe) {
	    TestUtility.log(Config.ERROR,"Test: caught exception",uhe);
	    return Status.failed(Status.ENV,"Could not get local host "
		+ "address");
	} catch (IOException ioe) {
	    TestUtility.log(Config.ERROR,"Test: caught exception",ioe);
	    return Status.failed(Status.ENV,"Could not construct "
		+ "outgoing multicast announcement");
	}

	st.start();
	long startTime = System.currentTimeMillis();
	long duration = 0;
	try {
	    synchronized(st) {
		while ((sock == null) && (duration < conf.getFailureTime())) {
	    	    TestUtility.log(Config.ALL,"Test: sending announcement");
		    ms.send(sendPacket);
		    st.wait(1000);
	    	    TestUtility.log(Config.ALL,"Test: waiting for program "
			+ "to connect");
		    sock = st.getSocket();
		    duration = System.currentTimeMillis() - startTime;
		}
	    }
	    ms.leaveGroup(Constants.getAnnouncementAddress());
	} catch (IOException ioe) {
	    TestUtility.log(Config.ERROR,"Test: caught exception",ioe);
	    return Status.failed(Status.ENV,"Could not send "
		+ "multicast announcement");
	} catch (InterruptedException ie) {
	    TestUtility.log(Config.ERROR,"Test: caught exception",ie);
	    return Status.failed(Status.ENV,"Test interrupted");
	}

	if (sock == null) {
	    return Status.failed(Status.TEST, "Product did not "
		+ "respond to multicast announcement in "
		+ duration + " milliseconds"); 
	}

	try {
	    DataInputStream dis = new DataInputStream(sock.getInputStream());
	    TestUtility.log(Config.ALL,"Test: checking unicast request packet");
	    int protoVers = dis.readInt();
	    if (protoVers != 1) {
		return Status.failed(Status.TEST, "Unicast request packet "
		   + "contains the wrong protocol number: " + protoVers);
	    }
	} catch (EOFException eofe) {
	    TestUtility.log(Config.ERROR,"Test: caught exception",eofe);
	    return Status.failed(Status.TEST, "Unicast request packet "
		+ "ended unexpectedly");
	} catch (IOException ioe) {
	    TestUtility.log(Config.ERROR,"Test: caught exception",ioe);
	    return Status.failed(Status.TEST, "Unicast request packet "
		+ "improperly formatted");
	}    

	return Status.passed("OK");
    }

    public void tearDown() {
        super.tearDown();

	if (st != null) {
	    st.interrupt();
	}

	try {
	    if (sock != null) {
		sock.close();
	    }
	} catch (IOException ignore) {}

        try {
            if (admin != null) {
	    	TestUtility.log(Config.ALL,"Test: stopping program");
                admin.stop();
            }
        } catch (RemoteException ignore) {}
    }

    private class SocketThread extends Thread {
	private ServerSocket serv;
	private Socket sock = null;
        private boolean interrupted = false;

	SocketThread(int socketTimeout) throws IOException {
	    super();
	    serv = new ServerSocket(0);
	    serv.setSoTimeout(socketTimeout);
	}

        /**
         * Overrides Thread.interrupt().  This is a workaround for
         * Thread.interrupt not working on
         * ServerSocket.accept on all platforms.
         */
        public void interrupt() {
            interrupted = true;
	    try {
                serv.close();
	    } catch (IOException ignore) {}
        }

        /**
         * Overrides Thread.isInterrupted().
         */
        public boolean isInterrupted() {
            return interrupted;
        }
	
	public void run() {
	    Config conf = getConfig();
	    BasicAdmin ba = conf.getAdmin();
	    Socket tempSock;
	    while (!isInterrupted()) {
		try {
		    tempSock = serv.accept();
		    if (!tempSock.getInetAddress().equals(ba.getAddress())) {
			TestUtility.log(Config.ALL,"Test: ignoring socket "
			    + "connection from: " + tempSock.getInetAddress());
			tempSock.close();
		    } else {
			TestUtility.log(Config.ALL,"Test: "
			    + "got successful socket connection from: "
			    + tempSock.getInetAddress());
			setSocket(tempSock);
			break;
		    }
		} catch (Exception ignore) {
		    TestUtility.log(Config.ERROR,"Test: "
			+ "ignoring the following exception from "
			+ "either accept, setSoTimeOut or getAddress:",ignore);
		}
	    }   

	    try {
		serv.close();
	    } catch (IOException ignore) {}
	}
	
	private synchronized void setSocket(Socket s) {
	    sock = s;
	    notifyAll();
	}

	public int getServerSocketPort() {
	    return serv.getLocalPort();
	}
	
	public synchronized Socket getSocket() {
	    return sock;
	}
    }
	    
    public String[] getCategories() {
	return (new String[] { BasicServiceAdmin.CATEGORY });
    }

    public Class[] getRequiredAdmins() {
	return (new Class[] { BasicAdmin.class });
    }
			  
    public String getDescription() {
	return "AnnouncementResponseTest";
    }

}

