/*
 * 
 * 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.rmi.RemoteException;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.File;
import java.net.InetAddress;

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.BasicAdmin;
import com.sun.jini.compat.harness.BasicClientAdmin;
import com.sun.jini.compat.harness.BasicServiceAdmin;
import com.sun.jini.compat.harness.Config;
import com.sun.jini.compat.harness.DownloadEvent;
import com.sun.jini.compat.harness.InstrumentedClassServer;
import com.sun.jini.compat.harness.DownloadListener;

import net.jini.core.lookup.ServiceRegistrar;

/**
 * Tests whether a service or a client downloads code from the
 * java.rmi.server.codebase provided by the class server of the LDJ Kit.
 * The code-base URL must use the HTTP protocol.
 */
public class CodeDownloadTest extends DefaultTest {

    String randomName;
    String tempJarFileName;
    ServiceRegistrar lookup;
    BasicAdmin admin;
    InstrumentedClassServer ics;
    CDListener cdl;

    /**
     * Copies the JAR file that contains the lookup service's 
     * downloadable code to a random file name. This new file is 
     * created to prevent caching from causing false negative
     * results. The test then starts a lookup service with a 
     * codebase that points to the new file and registers a 
     * DownloadListener with the instrumented class server
     * provided with the LDJ Kit. CodeDownloadTest then starts the 
     * program and waits for five times the failureTime. After 
     * either the wait times out or the test is notified,
     * the test checks to see if the appropriate file (the 
     * randomly named file) was actually downloaded. The 
     * randomly named file is then deleted. If the randomly named file
     * wasn't downloaded, the client or service being tested 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();
	cdl = new CDListener();
	admin = conf.getAdmin();
	ics = conf.getClassServer();
	randomName = TestUtility.randomString(8) + ".jar";

	try {
	    createTempJar();
	} catch (IOException ioe) {
            TestUtility.log(Config.ERROR,"Test: caught exception",ioe);
            return Status.failed(Status.ENV,"Could not create a temporary "
                + "copy of compat-lus-dl.jar");
        }
	    
	try {
	    TestUtility.log(Config.ALL,"Test: starting lookup in public group");
	    lookup = TestUtility.startLookup(new String[] {""}, 
		conf.getQuietTime(), "CodeDownloadTest_RegistrarLog", 
		randomName, conf);
	} catch (Exception e) {
            TestUtility.log(Config.ERROR,"Test: caught exception",e);
            return Status.failed(Status.ENV,"Problem starting lookup service");
        }
	    
	try {
	    synchronized(cdl) {
		ics.addDownloadListener(cdl);
		TestUtility.log(Config.ALL,"Test: starting program");
		admin.start();
		long waitTime = 5 * conf.getFailureTime();
		TestUtility.log(Config.ALL,"Test: waiting up to " 
		    + waitTime + " milliseconds for code to be download");
		cdl.wait(waitTime);
	    }
	} catch (RemoteException re) {
	    TestUtility.log(Config.ERROR,"Test: caught exception",re);
            return Status.failed(Status.ENV,"Problem starting program");
	} catch (InterruptedException ie) {
            TestUtility.log(Config.ERROR,"Test: caught exception",ie);
            return Status.failed(Status.ENV,"Test interrupted");
        }

	if (cdl.getFileName() == null) {
	    return Status.failed(Status.TEST, "Product never downloaded "
		+ "the lookup jar");
	}

	return Status.passed("OK");
    }    

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

	deleteTempJar();
	ics.removeDownloadListener(cdl);
        try {
            if (lookup != null) {
		TestUtility.log(Config.ALL,"Test: stopping lookup");
                TestUtility.stopLookup(lookup, getConfig());
            }
        } catch (RemoteException ignore) {}
        try {
            if (admin != null) {
		TestUtility.log(Config.ALL,"Test: stopping program");
                admin.stop();
            }
        } catch (RemoteException ignore) {}
    }
    
    private class CDListener implements DownloadListener {

	private String fname = null;

	public synchronized String getFileName() {
	    return fname;
	}

	public synchronized void fileDownloaded(DownloadEvent de) {
	    String fileName = de.getName();
	    InetAddress address = de.getAddress();
	    Config conf = getConfig();
	    BasicAdmin ba = conf.getAdmin();
	    InetAddress ourAddr = null;

	    try {
		ourAddr = ba.getAddress();
	    } catch(RemoteException re) {
		TestUtility.log(Config.ERROR,"Test: <admin>.getAddress "
		    + "threw a RemoteException",re);
	    }
	    TestUtility.log(Config.ALL,"Test: " + address + " downloaded " 
		+ fileName);
	    if (fileName.equals(randomName) && address.equals(ourAddr)) {
		fname = fileName;
		notifyAll();
	    }
	}
    }
    
    private void createTempJar() throws IOException {
	String iDir = getConfig().getSysConfig().getStringConfigVal(
	    "com.sun.jini.compat.installDir", ".");

	String sep = File.separator;
	String path = iDir + sep + "lib" + sep + "dl" + sep; 
	String oldJarFileName = path + "compat-lus-dl.jar";
	tempJarFileName = path + randomName;

	FileInputStream fis = new FileInputStream(oldJarFileName);
	FileOutputStream fos = new FileOutputStream(tempJarFileName);
	
	TestUtility.log(Config.ALL,"Test: copying " + oldJarFileName);
	TestUtility.log(Config.ALL,"      to " + tempJarFileName);

	//must copy file from one location to the other
	byte inBytes[] = new byte[1000];
	int count;
	while ((count = fis.read(inBytes)) != -1) {
	    fos.write(inBytes, 0, count);
	}
	fos.close();
	fis.close();
    }

    private void deleteTempJar() {
	if (tempJarFileName != null) {
	    File f = new File(tempJarFileName);
	    f.delete();
	    TestUtility.log(Config.ALL,"Test: deleted file " + tempJarFileName);
	}
    }

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

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

}

