<commit_before>/*****************************************************************
JADE - Java Agent DEvelopment Framework is a framework to develop 
multi-agent systems in compliance with the FIPA specifications.
Copyright (C) 2000 CSELT S.p.A. 

GNU Lesser General Public License

This library is free software; you can redistribute it and/or
modify it under the terms of the GNU Lesser General Public
License as published by the Free Software Foundation, 
version 2.1 of the License. 

This library is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
Lesser General Public License for more details.

You should have received a copy of the GNU Lesser General Public
License along with this library; if not, write to the
Free Software Foundation, Inc., 59 Temple Place - Suite 330,
Boston, MA  02111-1307, USA.
*****************************************************************/

package jade.imtp.leap.http;

//#MIDP_EXCLUDE_FILE

import jade.core.BackEndContainer;
import jade.core.BEConnectionManager;
import jade.core.BackEnd;
import jade.core.FrontEnd;
import jade.core.IMTPException;
import jade.core.Profile;
import jade.core.ProfileImpl;
import jade.core.ProfileException;
import jade.core.ContainerID;
import jade.imtp.leap.FrontEndStub;
import jade.imtp.leap.MicroSkeleton;
import jade.imtp.leap.BackEndSkel;
import jade.imtp.leap.Dispatcher;
import jade.imtp.leap.ICP;
import jade.imtp.leap.ICPException;
import jade.util.leap.Properties;
import jade.imtp.leap.JICP.*;
import jade.core.TimerDispatcher;
import jade.core.Timer;
import jade.core.TimerListener;
import jade.core.Runtime;

import java.io.*;
import java.net.*;
import java.util.*;

/**
 * Class declaration
 * @author <NAME> - TILAB
 */
public class HTTPBEDispatcher implements BEConnectionManager, Dispatcher, JICPMediator {
	
	private int verbosity = 1;

  private JICPServer myJICPServer;
  private String myID;

  private MicroSkeleton mySkel = null;
  private FrontEndStub myStub = null;
  private BackEndContainer myContainer = null;

	private OutgoingsHandler myOutgoingsHandler;
	private InetAddress lastRspAddr;
	private int lastRspPort;
  
  /////////////////////////////////////
  // JICPMediator interface implementation
  /////////////////////////////////////
  /**
     Initialize parameters and activate the BackEndContainer
   */
  public void init(JICPServer srv, String id, Properties props) throws ICPException {
    myJICPServer = srv;
    myID = id;
    
		// Verbosity
  	try {
  		verbosity = Integer.parseInt(props.getProperty("verbosity"));
  	}
  	catch (NumberFormatException nfe) {
      // Use default (1)
  	}
  	verbosity = 3;
  	
  	// Max disconnection time
    long maxDisconnectionTime = JICPProtocol.DEFAULT_MAX_DISCONNECTION_TIME;
    try {
    	maxDisconnectionTime = Long.parseLong(props.getProperty(JICPProtocol.MAX_DISCONNECTION_TIME_KEY));
    }
    catch (Exception e) {
    	// Keep default
    }
    
    myOutgoingsHandler = new OutgoingsHandler(maxDisconnectionTime);
  	
    log("Created HTTPBEDispatcher V2.0 ID = "+myID+" MaxDisconnectionTime = "+maxDisconnectionTime, 1);
  	
    jade.util.Logger.println("Start-backend-"+System.currentTimeMillis());
    startBackEndContainer(props);
    jade.util.Logger.println("Backend-started-"+System.currentTimeMillis());    
  }
  
  protected final void startBackEndContainer(Properties props) throws ICPException {
    try {
    	myStub = new FrontEndStub(this);
    	props.setProperty(Profile.MAIN, "false");
    	props.setProperty("mobility", "jade.core.DummyMobilityManager");
    	myContainer = new BackEndContainer(new ProfileImpl(props), this);
			// Check that the BackEndContainer has successfully joined the platform
			ContainerID cid = (ContainerID) myContainer.here();
			if (cid == null || cid.getName().equals("No-Name")) {
				throw new ICPException("BackEnd container failed to join the platform");
			}
    	mySkel = new BackEndSkel(myContainer);
    	log("BackEndContainer successfully joined the platform: name is "+cid.getName(), 2);
    }
    catch (ProfileException pe) {
    	// should never happen
    	pe.printStackTrace();
			throw new ICPException("Error creating profile");
    }
  }
  
  /**
     Shutdown forced by the JICPServer this BackEndContainer is attached 
     to. This method is also called when the FrontEnd spontaneously exits
     and when the the communication with the FrontEnd cannot be 
     re-established.
   */
  public void kill() {
  	// Force the BackEndContainer to terminate. This will also
  	// cause this HTTPBEDispatcher to terminate 
  	try {
  		myContainer.exit();
  	}
  	catch (IMTPException imtpe) {
  		// Should never happen as this is a local call
  		imtpe.printStackTrace();
  	}
  }
  
  /**
     Handle an incoming JICP packet received by the JICPServer.
   */
  public JICPPacket handleJICPPacket(JICPPacket pkt, InetAddress addr, int port) throws ICPException {
  	if (pkt.getType() == JICPProtocol.COMMAND_TYPE) {
  		// COMMAND
    	if ((pkt.getInfo() & JICPProtocol.TERMINATED_INFO) != 0) {
    		// PEER TERMINATION NOTIFICATION
    		// The remote FrontEnd has terminated spontaneously -->
    		// Terminate and notify up.
    		log("Peer termination notification received", 2);
    		handlePeerExited();
    		return null;
    	}
    	else {
    		// NORMAL COMMAND
    		// Serve the incoming command and send back the response
    		byte sid = pkt.getSessionID();
      	log("Incoming command received "+sid, 3);
		  	byte[] rspData = mySkel.handleCommand(pkt.getData());
      	log("Incoming command served "+sid, 3);
		    pkt = new JICPPacket(JICPProtocol.RESPONSE_TYPE, JICPProtocol.DEFAULT_INFO, rspData);
		    pkt.setSessionID(sid);
		    return pkt;
    	}
  	}
  	else {
  		// RESPONSE<commit_msg>Fixed the shutdown method, and implemented the new activateReplica() method to throw a RuntimeException.<commit_after>/*****************************************************************
JADE - Java Agent DEvelopment Framework is a framework to develop 
multi-agent systems in compliance with the FIPA specifications.
Copyright (C) 2000 CSELT S.p.A. 

GNU Lesser General Public License

This library is free software; you can redistribute it and/or
modify it under the terms of the GNU Lesser General Public
License as published by the Free Software Foundation, 
version 2.1 of the License. 

This library is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
Lesser General Public License for more details.

You should have received a copy of the GNU Lesser General Public
License along with this library; if not, write to the
Free Software Foundation, Inc., 59 Temple Place - Suite 330,
Boston, MA  02111-1307, USA.
*****************************************************************/

package jade.imtp.leap.http;

//#MIDP_EXCLUDE_FILE

import jade.core.BackEndContainer;
import jade.core.BEConnectionManager;
import jade.core.BackEnd;
import jade.core.FrontEnd;
import jade.core.IMTPException;
import jade.core.Profile;
import jade.core.ProfileImpl;
import jade.core.ProfileException;
import jade.core.ContainerID;
import jade.imtp.leap.FrontEndStub;
import jade.imtp.leap.MicroSkeleton;
import jade.imtp.leap.BackEndSkel;
import jade.imtp.leap.Dispatcher;
import jade.imtp.leap.ICP;
import jade.imtp.leap.ICPException;
import jade.util.leap.Properties;
import jade.imtp.leap.JICP.*;
import jade.core.TimerDispatcher;
import jade.core.Timer;
import jade.core.TimerListener;
import jade.core.Runtime;

import java.io.*;
import java.net.*;
import java.util.*;

/**
 * Class declaration
 * @author <NAME> - TILAB
 */
public class HTTPBEDispatcher implements BEConnectionManager, Dispatcher, JICPMediator {
	
	private int verbosity = 1;

  private JICPServer myJICPServer;
  private String myID;

  private MicroSkeleton mySkel = null;
  private FrontEndStub myStub = null;
  private BackEndContainer myContainer = null;

	private OutgoingsHandler myOutgoingsHandler;
	private InetAddress lastRspAddr;
	private int lastRspPort;
  
  /////////////////////////////////////
  // JICPMediator interface implementation
  /////////////////////////////////////
  /**
     Initialize parameters and activate the BackEndContainer
   */
  public void init(JICPServer srv, String id, Properties props) throws ICPException {
    myJICPServer = srv;
    myID = id;
    
		// Verbosity
  	try {
  		verbosity = Integer.parseInt(props.getProperty("verbosity"));
  	}
  	catch (NumberFormatException nfe) {
      // Use default (1)
  	}
  	verbosity = 3;
  	
  	// Max disconnection time
    long maxDisconnectionTime = JICPProtocol.DEFAULT_MAX_DISCONNECTION_TIME;
    try {
    	maxDisconnectionTime = Long.parseLong(props.getProperty(JICPProtocol.MAX_DISCONNECTION_TIME_KEY));
    }
    catch (Exception e) {
    	// Keep default
    }
    
    myOutgoingsHandler = new OutgoingsHandler(maxDisconnectionTime);
  	
    log("Created HTTPBEDispatcher V2.0 ID = "+myID+" MaxDisconnectionTime = "+maxDisconnectionTime, 1);
  	
    jade.util.Logger.println("Start-backend-"+System.currentTimeMillis());
    startBackEndContainer(props);
    jade.util.Logger.println("Backend-started-"+System.currentTimeMillis());    
  }
  
  protected final void startBackEndContainer(Properties props) throws ICPException {
    try {
    	myStub = new FrontEndStub(this);
    	props.setProperty(Profile.MAIN, "false");
    	props.setProperty("mobility", "jade.core.DummyMobilityManager");
    	myContainer = new BackEndContainer(new ProfileImpl(props), this);
			// Check that the BackEndContainer has successfully joined the platform
			ContainerID cid = (ContainerID) myContainer.here();
			if (cid == null || cid.getName().equals("No-Name")) {
				throw new ICPException("BackEnd container failed to join the platform");
			}
    	mySkel = new BackEndSkel(myContainer);
    	log("BackEndContainer successfully joined the platform: name is "+cid.getName(), 2);
    }
    catch (ProfileException pe) {
    	// should never happen
    	pe.printStackTrace();
			throw new ICPException("Error creating profile");
    }
  }

  public void activateReplica(String addr, Properties props) {
      throw new RuntimeException("FIXME: Not Implemented");
  }
  
  /**
     Shutdown forced by the JICPServer this BackEndContainer is attached 
     to. This method is also called when the FrontEnd spontaneously exits
     and when the the communication with the FrontEnd cannot be 
     re-established.
   */
  public void kill() {
      // Force the BackEndContainer to terminate. This will also
      // cause this HTTPBEDispatcher to terminate 
      myContainer.exit();
  }
  
  /**
     Handle an incoming JICP packet received by the JICPServer.
   */
  public JICPPacket handleJICPPacket(JICPPacket pkt, InetAddress addr, int port) throws ICPException {
  	if (pkt.getType() == JICPProtocol.COMMAND_TYPE) {
  		// COMMAND
    	if ((pkt.getInfo() & JICPProtocol.TERMINATED_INFO) != 0) {
    		// PEER TERMINATION NOTIFICATION
    		// The remote FrontEnd has terminated spontaneously -->
    		// Terminate and notify up.
    		log("Peer termination notification received", 2);
    		handlePeerExited();
    		return null;
    	}
    	else {
    		// NORMAL COMMAND
    		// Serve the incoming command and send back the response
    		byte sid = pkt.getSessionID();
      	log("Incoming command received "+sid, 3);
		  	byte[] rspData = mySkel.handleCommand(pkt.getData());
      	log("Incoming command served "+sid, 3);
		    pkt = new JICPPacket(JICPProtocol.RESPONSE_TYPE, JICPProtocol.DEFAULT_INFO, rspData);
		    pkt.setSessionID(sid);
		    return pkt;
    	}
  	}
  	else {
  		// RESPONSE
{'fraction_non_alphanumeric': 0.11910983730928096, 'fraction_numerical': 0.005226333979600439, 'mean_word_length': 3.509312048650703, 'pattern_counts': {'":': 0, '<': 5, '<?xml version=': 0, '>': 7, 'https://': 0, 'lorem ipsum': 0, 'www.': 0, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 0, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'dir': 'git-commits-cleaned', 'id': '1455077', 'n_tokens_mistral': 3665, 'n_tokens_neox': 3516, 'n_words': 1035}