/*
 * ByteLoader.java
 *
 * Created on April 7, 2005, 5:25 PM
 */

package DDMT.Agents;

import jade.core.Agent;
import java.util.Vector;
import jade.lang.acl.ACLMessage;
import jade.core.AID;
import jade.core.behaviours.*;
import jade.lang.acl.MessageTemplate;
import java.lang.String;
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
import jade.domain.FIPAAgentManagement.*;
import jade.domain.*;
import java.lang.Integer;
import java.sql.*;
import java.util.Random;
import java.util.regex.Pattern;
import java.util.regex.Matcher;
import java.lang.ClassLoader;
import DDMT.core.nodeFileLoader;
import DDMT.Nodes.NodeCode;
import DDMT.Nodes.Neighbor;
import DDMT.Nodes.Node;
import java.io.*;

/**
 *This is the classloader used by the agents
 */
public class ByteLoader extends java.lang.ClassLoader
{
    //array of classes already defined
    Vector instances;

    public ByteLoader()
    {
        instances = new Vector();
    }

    public NodeCode defineClass(String name, byte[] def)
    {
        Class temp = null;

        //If this class has already been defined, then just load it
        for(int i = 0; i< instances.size(); i++)
        {
            if( ((String)instances.elementAt(i)).equals(name) )
            {
                try{
                    temp = super.loadClass(name);
                    super.resolveClass(temp);
                    NodeCode code = (NodeCode)temp.newInstance();
                    return code;
                }catch(Exception ex)
                {
                    System.out.println("Previously loaded class error!");
                    return new NodeCode();
                }
            }
        }

        //Otherwise, define it
        try
        {
            instances.addElement(new String(name));
            temp = super.defineClass(name, def, 0, def.length);
            super.resolveClass(temp);
            NodeCode code = (NodeCode)temp.newInstance();
            return code;
        }
        catch(Exception ex)
        {
            System.out.println("Error creating class!");
            ex.printStackTrace();
            return new NodeCode();
        }
    }
}
