/*
 * 
 * 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.DatagramPacket;
import java.net.Socket;
import java.net.ConnectException;

import java.io.ByteArrayInputStream;
import java.io.DataInputStream;
import java.io.StringWriter;
import java.io.PrintWriter;
import java.io.EOFException;
import java.io.IOException;

import java.util.List;

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

/**
 * Tests whether a service or a client, having sent a multicast request 
 * packet and obtained a return socket connection, replies with a 
 * properly formatted unicast request packet on that socket.
 */
public class UnicastRequestTest extends DefaultTest {

    BasicAdmin admin;
    Socket sock;

    /**
     * Listens to the appropriate multicast group for a multicast 
     * request. When it receives the packet it, decodes the port 
     * information and gets the address the packet came
     * from and makes a socket connection to that port and address. 
     * It then proceeds to listen for a unicast request packet on 
     * that socket. If it receives the packet, it decodes its protocol 
     * version and checks that to make sure it is correct. If any of
     * these steps fail, such as a packet is not received in time or 
     * either of the packets improperly formatted, 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();

	List results = null;
	int timeout = conf.getFailureTime();
	try {	    
	    TestUtility.log(Config.ALL,"Test: starting program and "
		+ "waiting up to " + timeout
		+ " milliseconds for its first multicast request");
	    results = TestUtility.startProductAndGetMulticastRequests(
		timeout, 1, admin);
	} catch (IOException ioe) {
	    return Status.failed(Status.INDEF, "Failed to receive a "
                + "multicast request packet within " + timeout 
                + " milliseconds");
	} catch (Exception e) {
            TestUtility.log(Config.ERROR,"Test: caught exception",e);
            return Status.failed(Status.ENV,"Problem starting program or "
                + "waiting for multicast request");
        }
	    
	try {
	    TestUtility.log(Config.ALL,"Test: parsing multicast request "
		+ "packet");
	    DatagramPacket pkt = (DatagramPacket) results.get(0);
	    ByteArrayInputStream bais = new ByteArrayInputStream(pkt.getData());
	    DataInputStream dis = new DataInputStream(bais);
	    dis.readInt(); // protocol version
	    int port = dis.readInt();
	    InetAddress listenAddress = pkt.getAddress();
	    try { 
	        TestUtility.log(Config.ALL,"Test: opening socket to program " 
		    + "at: " + listenAddress + ":" + port);
	        sock = new Socket(listenAddress, port); 
	        sock.setSoTimeout(timeout);
	    } catch (Exception e) { 
                TestUtility.log(Config.ERROR,"Test: caught exception",e);
	        return Status.failed(Status.TEST, "Could not connect to "
		    + "program response address: " 
		    + listenAddress + ":" + port); 
	    } 
	} catch (IOException ioe) {
            TestUtility.log(Config.ERROR,"Test: caught exception",ioe);
            return Status.failed(Status.ENV,"Could not decode "
                + "incoming multicast request");
        }


	try {
	    TestUtility.log(Config.ALL,"Test: checking unicast request packet");
	    DataInputStream disUni = new DataInputStream(sock.getInputStream());
	    int protoVersion = disUni.readInt();
	    TestUtility.log(Config.ALL,"Test: unicast request contains "
		+ "protocol version: " + protoVersion);
	    if (protoVersion != 1) {
		return Status.failed(Status.TEST, "Unicast request "
		     + "should have protocol version 1");
	    }
	} 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();

	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) {}
    }

    public String[] getCategories() {
	return (new String[] { BasicClientAdmin.CATEGORY,
			       BasicServiceAdmin.CATEGORY });
    }

    public Class[] getRequiredAdmins() {
	return (new Class[] { BasicAdmin.class });
    }

    public String getDescription() {
	return "UnicastRequestTest";
    }

}

