/*
 * 
 * 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.io.IOException;
import java.io.ByteArrayInputStream;
import java.io.DataInputStream;
import java.io.EOFException;

import java.net.DatagramPacket;

import java.rmi.RemoteException;

import java.util.List;

import com.sun.jini.compat.harness.TestUtility;
import com.sun.jini.compat.harness.Status;
import com.sun.jini.compat.harness.DefaultTest;
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 net.jini.core.lookup.ServiceID;

/**
 * Tests whether the multicast request packets sent by the client or 
 * service are properly formatted.
 */
public class RequestPacketTest extends DefaultTest {

    BasicAdmin admin;

    /**
     * Listens for a multicast request packet from the appropriate 
     * multicast group. If it gets a packet from the provided address 
     * (from the Admin) it tries to decode the packet.
     * <ul>
     *   <li>It makes sure that the packet is not over 512 bytes and 
     *   that the protocol number is correct.
     *   <li>It then decodes the port and the group count. It makes 
     *   sure the group count is correct and decodes the group names.
     *   <li>Finally it decodes the lookup service count and makes 
     *   sure the count is correct by attempting to decode that many 
     *   lookup service ServiceID objects.
     * </ul>
     * If any of these steps cannot be performed (because of 
     * improper encoding) or returns the incorrect result (because of 
     * improper content), the service or client 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;
	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");
        }

	TestUtility.log(Config.ALL,"Test: checking multicast request "
            + "packet");
	DatagramPacket pkt = (DatagramPacket) results.get(0);

	if (pkt.getLength() > 512) {
	    return Status.failed(Status.TEST, "Packet over 512 bytes");
	}

	try {
	    /*
             * getData() returns a buffer whose length is longer than
             * getLength(). We shorten the buffer length so the 
             * EOFException detection mechanism (used below) will work.
             */
            byte[] buf = new byte[pkt.getLength()];
	    System.arraycopy(pkt.getData(), 0, buf, 0, buf.length);

	    ByteArrayInputStream bais = new ByteArrayInputStream(buf);
	    DataInputStream dis = new DataInputStream(bais);
	    
	    int protoVersion = dis.readInt();
	    TestUtility.log(Config.ALL,"Test: multicast request contains "
		+ "protocol version " + protoVersion);
	    if (protoVersion != 1) {
		return Status.failed(Status.TEST, "Multicast request should "
		    + "have protocol version 1");
	    }

	    int port = dis.readInt();
	    TestUtility.log(Config.ALL,"Test: multicast request contains "
		+ "port " + port);

	    int lookupCount = dis.readInt();
	    TestUtility.log(Config.ALL,"Test: multicast request contains "
		+ "a lookup count of " + lookupCount);

	    int count;
	    for (count = 0; count < lookupCount; count++) {
	        ServiceID tmpID = new ServiceID(dis);
	    }
	    TestUtility.log(Config.ALL,"Test: multicast request contains "
		+ "a list of " + count + " lookups");

	    // this simply makes sure that the group count is accurate
	    int groupCount = dis.readInt();
	    TestUtility.log(Config.ALL,"Test: multicast request contains "
		+ "a group count of " + groupCount);

	    StringBuffer groups = new StringBuffer("");
	    for (count = 0; count < groupCount; count++) {
		groups.append(dis.readUTF());
	    }
	    TestUtility.log(Config.ALL,"Test: multicast request contains "
		+ "the groups: " + groups);
	    
	} catch (EOFException eofe) {
	    TestUtility.log(Config.ERROR,"Test: caught exception",eofe);
	    return Status.failed(Status.TEST, "Multicast request packet "
		+ "ended unexpectedly");
	} catch (IOException ioe) {
	    TestUtility.log(Config.ERROR,"Test: caught exception",ioe);
	    return Status.failed(Status.TEST, "Multicast request packet "
		+ "improperly formatted");
	}    

	return Status.passed("OK");
    }

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

        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 "RequestPacketTest";
    }

}

