Skip to content
Snippets Groups Projects
Commit 8e931404 authored by Brutzman, Don's avatar Brutzman, Don
Browse files

making a program simpler and clearer... by getting rid of unnecessary noise

parent 0198122b
No related branches found
No related tags found
No related merge requests found
/** /**
* Copyright (c) 2008-2021, MOVES Institute, Naval Postgraduate School (NPS). All rights reserved. * Copyright (c) 2008-2021, MOVES Institute, Naval Postgraduate School (NPS). All rights reserved.
* This work is provided under a BSD open-source license, see project license.html and license.txt * This work is provided under a BSD open-source license, see project license.html and license.txt
* *
* This Program is a modified version of ExampleSimulationProgram in order to see the * This Program is a modified version of ExampleSimulationProgram in order to see the
* verbose plain text pdu log. This simulates a firewall identifying a malicious packet * verbose plain text pdu log. This simulates a firewall identifying a malicious packet
* and tracing its source before destroying it - updated September 12, 2021 to ensure * and tracing its source before destroying it - updated September 12, 2021 to ensure
* correct file pushed to Gitlab. * correct file pushed to Gitlab.
* *
* @author William Oblak (Changes made from copy given in class) * @author William Oblak (Changes made from copy given in class)
*/ */
package MV3500Cohort2023MarchJune.homework3.Oblak; package MV3500Cohort2023MarchJune.homework3.Oblak;
import edu.nps.moves.dis7.enumerations.*; // match any import edu.nps.moves.dis7.enumerations.*; // match any
import edu.nps.moves.dis7.pdus.*; // match any of the PDU classes, easier than listing individually import edu.nps.moves.dis7.pdus.*; // match any of the PDU classes, easier than listing individually
import edu.nps.moves.dis7.utilities.DisThreadedNetworkInterface; import edu.nps.moves.dis7.utilities.DisThreadedNetworkInterface;
import edu.nps.moves.dis7.utilities.PduFactory; import edu.nps.moves.dis7.utilities.PduFactory;
import edu.nps.moves.dis7.utilities.stream.PduRecorder; import edu.nps.moves.dis7.utilities.stream.PduRecorder;
import java.util.ArrayList; import java.util.ArrayList;
import java.util.logging.Level; import java.util.logging.Level;
import java.util.logging.Logger; import java.util.logging.Logger;
/** The purpose of this program is to provide an easily modifiable example simulation program /** The purpose of this program is to provide an easily modifiable example simulation program
* that includes DIS-capable entities doing tasks and reporting them to the network. * that includes DIS-capable entities doing tasks and reporting them to the network.
* Default settings include PDU recording turned on by default. * Default settings include PDU recording turned on by default.
*/ */
public class ExampleSimulationProgram public class ExampleSimulationProgram
{ {
private boolean verboseComments = true; private boolean verboseComments = true;
static final String NETWORK_ADDRESS_DEFAULT = "239.1.2.3"; private boolean verboseDisInterface = false;
static final int NETWORK_PORT_DEFAULT = 3000; static final String NETWORK_ADDRESS_DEFAULT = "239.1.2.3";
static String networkAddress = NETWORK_ADDRESS_DEFAULT; static final int NETWORK_PORT_DEFAULT = 3000;
static int networkPort = NETWORK_PORT_DEFAULT; static String networkAddress = NETWORK_ADDRESS_DEFAULT;
String DEFAULT_OUTPUT_DIRECTORY = "./pduLog"; static int networkPort = NETWORK_PORT_DEFAULT;
String DEFAULT_OUTPUT_DIRECTORY = "./pduLog";
private EntityID createFriendFireWall() {
EntityID FNFireWallID = new EntityID(); // 1.1.225.1.1.1 Platform,Cyber,USA,FireWall private EntityID createFriendFireWall() {
FNFireWallID.setSiteID(13); EntityID FNFireWallID = new EntityID(); // 1.1.225.1.1.1 Platform,Cyber,USA,FireWall
FNFireWallID.setApplicationID(43); FNFireWallID.setSiteID(13);
FNFireWallID.setEntityID(103); FNFireWallID.setApplicationID(43);
return FNFireWallID; FNFireWallID.setEntityID(103);
} return FNFireWallID;
}
private EntityType createFriendFireWallType() {
EntityType FNFireWallType = new EntityType(); private EntityType createFriendFireWallType() {
FNFireWallType.setEntityKind(EntityKind.PLATFORM); EntityType FNFireWallType = new EntityType();
FNFireWallType.setDomain(Domain.inst(PlatformDomain.OTHER)); FNFireWallType.setEntityKind(EntityKind.PLATFORM);
FNFireWallType.setCountry(Country.AUSTRALIA_AUS); FNFireWallType.setDomain(Domain.inst(PlatformDomain.OTHER));
FNFireWallType.setCategory(3); FNFireWallType.setCountry(Country.AUSTRALIA_AUS);
FNFireWallType.setSubCategory(1); FNFireWallType.setCategory(3);
FNFireWallType.setSpecific(1); FNFireWallType.setSubCategory(1);
return FNFireWallType; FNFireWallType.setSpecific(1);
} return FNFireWallType;
}
private EntityID createMalPacket() {
EntityID MalPacketID = new EntityID(); // 1.1.45.1.7.1 Platform,Cyber,China,MaliciousPacket private EntityID createMalPacket() {
MalPacketID.setSiteID(66); EntityID MalPacketID = new EntityID(); // 1.1.45.1.7.1 Platform,Cyber,China,MaliciousPacket
MalPacketID.setApplicationID(666); MalPacketID.setSiteID(66);
MalPacketID.setEntityID(6666); MalPacketID.setApplicationID(666);
return MalPacketID; MalPacketID.setEntityID(6666);
} return MalPacketID;
}
private EntityType createMalPacketType() {
EntityType MalPacketType = new EntityType(); private EntityType createMalPacketType() {
MalPacketType.setEntityKind(EntityKind.PLATFORM); EntityType MalPacketType = new EntityType();
MalPacketType.setDomain(Domain.inst(PlatformDomain.OTHER)); MalPacketType.setEntityKind(EntityKind.PLATFORM);
MalPacketType.setCountry(Country.CHINA_PEOPLES_REPUBLIC_OF_CHN); MalPacketType.setDomain(Domain.inst(PlatformDomain.OTHER));
MalPacketType.setCategory(3); MalPacketType.setCountry(Country.CHINA_PEOPLES_REPUBLIC_OF_CHN);
MalPacketType.setSubCategory(1); MalPacketType.setCategory(3);
MalPacketType.setSpecific(1); MalPacketType.setSubCategory(1);
return MalPacketType; MalPacketType.setSpecific(1);
} return MalPacketType;
}
private MunitionDescriptor createTraceroute() {
private MunitionDescriptor createTraceroute() {
EntityType TracerouteType = new EntityType(); //2.2.225.2.13.1
TracerouteType.setEntityKind(EntityKind.MUNITION); EntityType TracerouteType = new EntityType(); //2.2.225.2.13.1
TracerouteType.setDomain(Domain.inst(PlatformDomain.OTHER)); TracerouteType.setEntityKind(EntityKind.MUNITION);
TracerouteType.setCountry(Country.AUSTRALIA_AUS); TracerouteType.setDomain(Domain.inst(PlatformDomain.OTHER));
TracerouteType.setCategory(2); TracerouteType.setCountry(Country.AUSTRALIA_AUS);
TracerouteType.setSubCategory(8); TracerouteType.setCategory(2);
TracerouteType.setSpecific(1); TracerouteType.setSubCategory(8);
MunitionDescriptor Traceroute = new MunitionDescriptor(); TracerouteType.setSpecific(1);
Traceroute.setMunitionType(TracerouteType); MunitionDescriptor Traceroute = new MunitionDescriptor();
Traceroute.setQuantity(1000); Traceroute.setMunitionType(TracerouteType);
Traceroute.setFuse(MunitionDescriptorFuse.CONTACT); Traceroute.setQuantity(1000);
Traceroute.setRate(200); Traceroute.setFuse(MunitionDescriptorFuse.CONTACT);
return Traceroute; Traceroute.setRate(200);
} return Traceroute;
}
/**
* This runSimulationLoops() method is for you, a /**
* programmer-modifiable method for defining and running a new simulation of interest. * This runSimulationLoops() method is for you, a
* Welcome! Other parts of this program handle bookkeeping and plumbing tasks so that * programmer-modifiable method for defining and running a new simulation of interest.
* you can focus on your model entities and activities. * Welcome! Other parts of this program handle bookkeeping and plumbing tasks so that
* Expandable support includes DIS EntityStatePdu, FirePdu and CommentPdu all available for * you can focus on your model entities and activities.
* modification and sending in a simulation loop. * Expandable support includes DIS EntityStatePdu, FirePdu and CommentPdu all available for
* Continuous improvement efforts seek to make this program as easy and straightforward * modification and sending in a simulation loop.
* as possible for DIS simulationists to use and adapt. * Continuous improvement efforts seek to make this program as easy and straightforward
* All of the other methods are setup, teardown and configuration that you may find * as possible for DIS simulationists to use and adapt.
* interesting, even helpful, but don't really have to worry about. * All of the other methods are setup, teardown and configuration that you may find
*/ * interesting, even helpful, but don't really have to worry about.
@SuppressWarnings("SleepWhileInLoop") // yes we do that */
public void runSimulationLoops () @SuppressWarnings("SleepWhileInLoop") // yes we do that
{ public void runSimulationLoops ()
try {
{ try
/** seconds for real-time execution (not simulation time, which may or may not be the same) */ {
final double SIMULATION_LOOP_DURATION_SECONDS = 1.0; /** seconds for real-time execution (not simulation time, which may or may not be the same) */
final int SIMULATION_MAX_LOOP_COUNT = 10; // be deliberate out out there! also avoid infinite loops. final double SIMULATION_LOOP_DURATION_SECONDS = 1.0;
int simulationLoopCount = 0; // variable, initialized at 0 final int SIMULATION_MAX_LOOP_COUNT = 10; // be deliberate out out there! also avoid infinite loops.
boolean simulationComplete = false; // sentinel variable as termination condition,, are we done yet? int simulationLoopCount = 0; // variable, initialized at 0
boolean fireBool = false; boolean simulationComplete = false; // sentinel variable as termination condition,, are we done yet?
boolean destBool = false; boolean fireBool = false;
boolean destBool = false;
// TODO reset clock to zero each time for consistent outputs
// TODO reset clock to zero each time for consistent outputs
// Your model setup: define participants. who's who in this zoo?
// Assuming you keep track of entity objects... here is some support for for Entity 1. // Your model setup: define participants. who's who in this zoo?
// Assuming you keep track of entity objects... here is some support for for Entity 1.
// create PDU object for US Firewall and set its values.
//EntityID entityID_1 = new EntityID(); // create PDU object for US Firewall and set its values.
//entityID_1.setSiteID(1).setApplicationID(2).setEntityID(3); // made-up example ID; //EntityID entityID_1 = new EntityID();
//entityID_1.setSiteID(1).setApplicationID(2).setEntityID(3); // made-up example ID;
EntityStatePdu entityStatePdu_1 = pduFactory.makeEntityStatePdu();
entityStatePdu_1.setEntityID(createFriendFireWall()); EntityStatePdu entityStatePdu_1 = pduFactory.makeEntityStatePdu();
entityStatePdu_1.setEntityType(createFriendFireWallType()); entityStatePdu_1.setEntityID(createFriendFireWall());
entityStatePdu_1.getEntityLocation().setX(0); entityStatePdu_1.setEntityType(createFriendFireWallType());
entityStatePdu_1.setForceId(ForceID.FRIENDLY); entityStatePdu_1.getEntityLocation().setX(0);
entityStatePdu_1.setForceId(ForceID.FRIENDLY);
// TODO someday, use enumerations; is there a unique site triplet for MOVES Institute?
// create PDU object for Malware Packet and set its values. // TODO someday, use enumerations; is there a unique site triplet for MOVES Institute?
//EntityID entityID_2 = new EntityID(); // create PDU object for Malware Packet and set its values.
//entityID_2.setSiteID(4).setApplicationID(5).setEntityID(6); //EntityID entityID_2 = new EntityID();
//entityID_2.setSiteID(4).setApplicationID(5).setEntityID(6);
EntityStatePdu entityStatePdu_2 = pduFactory.makeEntityStatePdu();
entityStatePdu_2.setEntityID(createMalPacket()); EntityStatePdu entityStatePdu_2 = pduFactory.makeEntityStatePdu();
entityStatePdu_2.setEntityType(createMalPacketType()); entityStatePdu_2.setEntityID(createMalPacket());
entityStatePdu_2.getEntityLocation().setX(7); entityStatePdu_2.setEntityType(createMalPacketType());
entityStatePdu_2.setForceId(ForceID.OPPOSING); entityStatePdu_2.getEntityLocation().setX(7);
entityStatePdu_2.setForceId(ForceID.OPPOSING);
int MalPacketPingsReceived = 0;
int MalPacketPingsReceived = 0;
FirePdu firePdu = pduFactory.makeFirePdu(); // for entity 1 first weapon (possible traceroute)
// should we customize this munition? what is it for your simulation? FirePdu firePdu = pduFactory.makeFirePdu(); // for entity 1 first weapon (possible traceroute)
EntityID fireID = new EntityID(); // should we customize this munition? what is it for your simulation?
fireID.setSiteID(13); EntityID fireID = new EntityID();
fireID.setApplicationID(43); fireID.setSiteID(13);
fireID.setEntityID(103); fireID.setApplicationID(43);
EntityID targetID = new EntityID(); fireID.setEntityID(103);
targetID.setSiteID(66); EntityID targetID = new EntityID();
targetID.setApplicationID(666); targetID.setSiteID(66);
targetID.setEntityID(6666); targetID.setApplicationID(666);
targetID.setEntityID(6666);
firePdu.setFiringEntityID(fireID);
firePdu.setTargetEntityID(targetID); firePdu.setFiringEntityID(fireID);
firePdu.setTargetEntityID(targetID);
firePdu.setDescriptor(createTraceroute()); // calling create Traceroute Method
firePdu.setDescriptor(createTraceroute()); // calling create Traceroute Method
EntityID TracerouteID = new EntityID();
TracerouteID.setEntityID(1); EntityID TracerouteID = new EntityID();
firePdu.setMunitionExpendibleID(TracerouteID); TracerouteID.setEntityID(1);
firePdu.setMunitionExpendibleID(TracerouteID);
CommentReliablePdu MalPacketDestroyedComment = pduFactory.makeCommentReliablePdu("Malware Packet DESTROYED BY Firewall");
CommentReliablePdu MalPacketDetectedComment = pduFactory.makeCommentReliablePdu("Firewall Detects Malware engage Traceroute"); CommentReliablePdu MalPacketDestroyedComment = pduFactory.makeCommentReliablePdu("Malware Packet DESTROYED BY Firewall");
CommentReliablePdu MalPacketDetectedComment = pduFactory.makeCommentReliablePdu("Firewall Detects Malware engage Traceroute");
// TODO simulation management PDUs for startup, planning to design special class support
// TODO simulation management PDUs for startup, planning to design special class support
//DetonationPdu detonationPdu = pduFactory.makeDetonationPdu();
//detonationPdu.setDescriptor(pDescriptor); //DetonationPdu detonationPdu = pduFactory.makeDetonationPdu();
//detonationPdu.setDescriptor(pDescriptor);
// loop the simulation while allowed, programmer can set additional conditions to break out and finish
while (simulationLoopCount < SIMULATION_MAX_LOOP_COUNT) // are we done yet? // loop the simulation while allowed, programmer can set additional conditions to break out and finish
{ while (simulationLoopCount < SIMULATION_MAX_LOOP_COUNT) // are we done yet?
simulationLoopCount++; // good practice: increment loop counter as first action in that loop {
simulationLoopCount++; // good practice: increment loop counter as first action in that loop
// =============================================================================================
// * your own simulation code starts here! * // =============================================================================================
// ============================================================================================= // * your own simulation code starts here! *
// =============================================================================================
// are there any other variables to modify at the beginning of your loop?
// are there any other variables to modify at the beginning of your loop?
// compute a track, update an ESPDU, whatever it is that your model is doing...
// compute a track, update an ESPDU, whatever it is that your model is doing...
// Where is my entity? Insert changes in position; this sample only changes X position.
entityStatePdu_1.getEntityLocation().setX(entityStatePdu_1.getEntityLocation().getX()); // stationary defensive posture // Where is my entity? Insert changes in position; this sample only changes X position.
entityStatePdu_2.getEntityLocation().setX(entityStatePdu_2.getEntityLocation().getX() - 1.0); // 1m per timestep entityStatePdu_1.getEntityLocation().setX(entityStatePdu_1.getEntityLocation().getX()); // stationary defensive posture
entityStatePdu_2.getEntityLocation().setX(entityStatePdu_2.getEntityLocation().getX() - 1.0); // 1m per timestep
// decide whether to fire, and then update the firePdu. Hmmm, you might want a target to shoot at!
Double range = entityStatePdu_2.getEntityLocation().getX(); // decide whether to fire, and then update the firePdu. Hmmm, you might want a target to shoot at!
System.out.println("range: " + range + " hops from our Network DMZ!"); Double range = entityStatePdu_2.getEntityLocation().getX();
System.out.println("range: " + range + " hops from our Network DMZ!");
if (range < 5) { // Range 5
if (!fireBool) { if (range < 5) { // Range 5
sendSinglePdu(MalPacketDetectedComment); if (!fireBool) {
} sendSinglePdu(MalPacketDetectedComment);
fireBool = true; }
System.out.println("Entity#" + firePdu.getFiringEntityID().getEntityID() + " is firing " + firePdu.getDescriptor().getMunitionType().getDomain() + "." + firePdu.getDescriptor().getMunitionType().getCountry() + "." + firePdu.getDescriptor().getMunitionType().getCategory() + "." + firePdu.getDescriptor().getMunitionType().getSubCategory() + "." + firePdu.getDescriptor().getMunitionType().getSpecific() + "." + " at Entity#" + firePdu.getTargetEntityID().getEntityID()); fireBool = true;
System.out.println("Entity#" + firePdu.getFiringEntityID().getEntityID() + " is firing " + firePdu.getDescriptor().getMunitionType().getDomain() + "." + firePdu.getDescriptor().getMunitionType().getCountry() + "." + firePdu.getDescriptor().getMunitionType().getCategory() + "." + firePdu.getDescriptor().getMunitionType().getSubCategory() + "." + firePdu.getDescriptor().getMunitionType().getSpecific() + "." + " at Entity#" + firePdu.getTargetEntityID().getEntityID());
if (firePdu.getTargetEntityID().getEntityID() == 6666) {
MalPacketPingsReceived += 1; if (firePdu.getTargetEntityID().getEntityID() == 6666) {
if (MalPacketPingsReceived > 1) { MalPacketPingsReceived += 1;
// The Firewall destroys the MalPacket if (MalPacketPingsReceived > 1) {
// The Firewall destroys the MalPacket
System.out.println("Malware Packet DESTROYED BY Firewall after " + MalPacketPingsReceived + "pings from the traceroute.");
narrativeMessage4 = "Destroyed MalPacket"; System.out.println("Malware Packet DESTROYED BY Firewall after " + MalPacketPingsReceived + " pings from the traceroute.");
destBool = true; narrativeMessage4 = "Destroyed MalPacket";
simulationComplete = true; destBool = true;
simulationComplete = true;
}
} }
} }
// etc. etc. your code goes here for your simulation of interest }
// etc. etc. your code goes here for your simulation of interest
// something happens between my simulation entities, la de da de da...
System.out.println ("... My simulation just did something, no really..."); // something happens between my simulation entities, la de da de da...
// System.out.println ("... My simulation just did something, no really...");
// make your reports: narrative code for CommentPdu here (set all to empty strings to avoid sending)
narrativeMessage1 = "MV3500 ExampleSimulationProgramAllen_3"; // make your reports: narrative code for CommentPdu here (set all to empty strings to avoid sending)
narrativeMessage2 = "runSimulation() loop " + simulationLoopCount; narrativeMessage1 = "MV3500 ExampleSimulationProgram Oblak";
narrativeMessage3 = "this is working!"; // intentionally blank for testing narrativeMessage2 = "runSimulation() loop " + simulationLoopCount;
narrativeMessage3 = "this is working!"; // intentionally blank for testing
// your loop termination condition goes here
if (simulationLoopCount > 4) // for example // your loop termination condition goes here
{ if (simulationLoopCount > 4) // for example
simulationComplete = true; {
} simulationComplete = true;
// ============================================================================================= }
// * your own simulation code is finished here! * // =============================================================================================
// ============================================================================================= // * your own simulation code is finished here! *
// =============================================================================================
// staying synchronized with timestep: wait duration for elapsed time in this loop
// Thread.sleep needs a (long) parameter for milliseconds, which are clumsy to use sometimes // staying synchronized with timestep: wait duration for elapsed time in this loop
Thread.sleep((long)(SIMULATION_LOOP_DURATION_SECONDS * 1000)); // seconds * (1000 msec/sec) = milliseconds // Thread.sleep needs a (long) parameter for milliseconds, which are clumsy to use sometimes
System.out.println ("... [Pausing for " + SIMULATION_LOOP_DURATION_SECONDS + " seconds]"); Thread.sleep((long)(SIMULATION_LOOP_DURATION_SECONDS * 1000)); // seconds * (1000 msec/sec) = milliseconds
// System.out.println ("... [Pausing for " + SIMULATION_LOOP_DURATION_SECONDS + " seconds]");
// OK now send the status PDUs for this loop, and then continue
System.out.println ("sending PDUs for simulation step " + simulationLoopCount + ", monitor loopback to confirm sent"); // OK now send the status PDUs for this loop, and then continue
sendAllPdusForLoopTimestep(entityStatePdu_1, firePdu, timeStepComment, narrativeMessage1, narrativeMessage2, narrativeMessage3); // System.out.println ("sending PDUs for simulation step " + simulationLoopCount + ", monitor loopback to confirm sent");
sendSinglePdu(entityStatePdu_2); // me too i.e. 2! sendAllPdusForLoopTimestep(entityStatePdu_1, firePdu, timeStepComment, narrativeMessage1, narrativeMessage2, narrativeMessage3);
System.out.println ("... [PDUs successfully sent for this loop]"); sendSinglePdu(entityStatePdu_2); // me too i.e. 2!
// System.out.println ("... [PDUs successfully sent for this loop]");
// ===============================
// loop now finished, check whether to terminate if simulation complete, otherwise continue // ===============================
if (simulationComplete || (simulationLoopCount > 10000)) // for example; including fail-safe condition is good // loop now finished, check whether to terminate if simulation complete, otherwise continue
{ if (simulationComplete || (simulationLoopCount > 10000)) // for example; including fail-safe condition is good
//sendSinglePdu(detonationPdu); {
System.out.println ("... [Termination condition met, simulationComplete=" + simulationComplete + "]"); // ", final loopCount=" + loopCount + //sendSinglePdu(detonationPdu);
break; System.out.println ("... [Termination condition met, simulationComplete=" + simulationComplete + "]"); // ", final loopCount=" + loopCount +
} break;
} // end of simulation loop }
} // end of simulation loop
narrativeMessage2 = "runSimulation() completed successfully"; // all done
sendCommentPdu(narrativeComment, narrativeMessage1, narrativeMessage2, narrativeMessage3); narrativeMessage2 = "runSimulation() completed successfully"; // all done
System.out.println ("... [final CommentPdu successfully sent for simulation]"); sendCommentPdu(narrativeComment, narrativeMessage1, narrativeMessage2, narrativeMessage3);
// TODO simulation management PDUs System.out.println ("... [final CommentPdu successfully sent for simulation]");
} // TODO simulation management PDUs
catch (InterruptedException iex) // handle any exception that your code might choose to provoke! }
{ catch (InterruptedException iex) // handle any exception that your code might choose to provoke!
Logger.getLogger(ExampleSimulationProgram.class.getName()).log(Level.SEVERE, null, iex); {
} Logger.getLogger(ExampleSimulationProgram.class.getName()).log(Level.SEVERE, null, iex);
} }
/* **************************** infrastructure code, modification is seldom needed ************************* */ }
/* **************************** infrastructure code, modification is seldom needed ************************* */
String narrativeMessage1 = new String();
String narrativeMessage2 = new String(); String narrativeMessage1 = new String();
String narrativeMessage3 = new String(); String narrativeMessage2 = new String();
String narrativeMessage4 = new String(); String narrativeMessage3 = new String();
String narrativeMessage4 = new String();
/* VariableRecordType enumerations have potential use with CommentPdu logs */
/* TODO contrast to EntityType */ /* VariableRecordType enumerations have potential use with CommentPdu logs */
VariableRecordType descriptionComment = VariableRecordType.DESCRIPTION; /* TODO contrast to EntityType */
VariableRecordType narrativeComment = VariableRecordType.COMPLETE_EVENT_REPORT; VariableRecordType descriptionComment = VariableRecordType.DESCRIPTION;
VariableRecordType statusComment = VariableRecordType.APPLICATION_STATUS; VariableRecordType narrativeComment = VariableRecordType.COMPLETE_EVENT_REPORT;
VariableRecordType timeStepComment = VariableRecordType.APPLICATION_TIMESTEP; VariableRecordType statusComment = VariableRecordType.APPLICATION_STATUS;
VariableRecordType otherComment = VariableRecordType.OTHER; VariableRecordType timeStepComment = VariableRecordType.APPLICATION_TIMESTEP;
VariableRecordType otherComment = VariableRecordType.OTHER;
/**
* Output prefix to identify this class, helps with logging /**
*/ * Output prefix to identify this class, helps with logging
private final static String TRACE_PREFIX = "[" + ExampleSimulationProgram.class.getName() + "] "; */
private final static String TRACE_PREFIX = "[" + ExampleSimulationProgram.class.getName() + "] ";
// class variables
PduFactory pduFactory = new PduFactory(); // class variables
DisThreadedNetworkInterface disNetworkInterface; PduFactory pduFactory = new PduFactory();
DisThreadedNetworkInterface.PduListener pduListener; DisThreadedNetworkInterface disNetworkInterface;
Pdu receivedPdu; DisThreadedNetworkInterface.PduListener pduListener;
PduRecorder pduRecorder; Pdu receivedPdu;
PduRecorder pduRecorder;
/**
* Constructor design goal: additional built-in initialization conveniences can go here /**
* to keep student efforts focused on the runSimulation() method. * Constructor design goal: additional built-in initialization conveniences can go here
*/ * to keep student efforts focused on the runSimulation() method.
public ExampleSimulationProgram() */
{ public ExampleSimulationProgram()
// Constructor is under consideration. Constructor is not currently needed. {
} // Constructor is under consideration. Constructor is not currently needed.
}
/**
* Utility Constructor that allows your example simulation program to override default network address and port /**
* @param address network address to use * Utility Constructor that allows your example simulation program to override default network address and port
* @param port corresponding network port to use * @param address network address to use
*/ * @param port corresponding network port to use
public ExampleSimulationProgram(String address, int port) */
{ public ExampleSimulationProgram(String address, int port)
setNetworkAddress(address); {
setNetworkAddress(address);
setNetworkPort(port);
} setNetworkPort(port);
}
/**
* get networkAddress /**
* @return the networkAddress * get networkAddress
*/ * @return the networkAddress
public String getNetworkAddress() */
{ public String getNetworkAddress()
return networkAddress; {
} return networkAddress;
}
/**
* set networkAddress /**
* @param newNetworkAddress the networkAddress to set * set networkAddress
*/ * @param newNetworkAddress the networkAddress to set
public final void setNetworkAddress(String newNetworkAddress) */
{ public final void setNetworkAddress(String newNetworkAddress)
ExampleSimulationProgram.networkAddress = newNetworkAddress; {
} ExampleSimulationProgram.networkAddress = newNetworkAddress;
}
/**
* get networkPort /**
* @return the networkPort * get networkPort
*/ * @return the networkPort
public int getNetworkPort() */
{ public int getNetworkPort()
return networkPort; {
} return networkPort;
}
/**
* set networkPort /**
* @param newNetworkPort the networkPort to set * set networkPort
*/ * @param newNetworkPort the networkPort to set
public final void setNetworkPort(int newNetworkPort) */
{ public final void setNetworkPort(int newNetworkPort)
ExampleSimulationProgram.networkPort = newNetworkPort; {
} ExampleSimulationProgram.networkPort = newNetworkPort;
}
/**
* Initialize network interface, choosing best available network interface /**
*/ * Initialize network interface, choosing best available network interface
public void setUpNetworkInterface() */
{ public void setUpNetworkInterface()
disNetworkInterface = new DisThreadedNetworkInterface(getNetworkAddress(), getNetworkPort()); {
disNetworkInterface.setDescriptor ("ExampleSimulationProgramAllen_3 pdu looping"); disNetworkInterface = new DisThreadedNetworkInterface(getNetworkAddress(), getNetworkPort());
disNetworkInterface.setDescriptor ("ExampleSimulationProgram Oblak pdu looping");
System.out.println("Network confirmation:" + // trying to slience DIS logging so that the simulation progress is easier to follow
" address=" + disNetworkInterface.getAddress()+ // disNetworkInterface.getMulticastGroup() + disNetworkInterface.setVerbose(verboseDisInterface);
" port=" + disNetworkInterface.getPort()); // + disNetworkInterface.getDisPort()); disNetworkInterface.setVerboseIncludesTimestamp(verboseDisInterface);
pduListener = new DisThreadedNetworkInterface.PduListener() disNetworkInterface.setVerboseReceipt(verboseDisInterface);
{ disNetworkInterface.setVerboseSending(verboseDisInterface);
/** Callback handler for listener */
@Override System.out.println("Network confirmation:" +
public void incomingPdu(Pdu newPdu) " address=" + disNetworkInterface.getAddress()+ // disNetworkInterface.getMulticastGroup() +
{ " port=" + disNetworkInterface.getPort()); // + disNetworkInterface.getDisPort());
receivedPdu = newPdu; pduListener = new DisThreadedNetworkInterface.PduListener()
} {
}; /** Callback handler for listener */
disNetworkInterface.addListener(pduListener); @Override
public void incomingPdu(Pdu newPdu)
String outputDirectory = DEFAULT_OUTPUT_DIRECTORY; {
System.out.println("Beginning pdu save to directory " + outputDirectory); receivedPdu = newPdu;
pduRecorder = new PduRecorder(outputDirectory, getNetworkAddress(), getNetworkPort()); // assumes save }
pduRecorder.setDescriptor ("ExampleSimulationProgramAllen_3 pduRecorder"); };
pduRecorder.start(); // begin running disNetworkInterface.addListener(pduListener);
}
String outputDirectory = DEFAULT_OUTPUT_DIRECTORY;
/** All done, release network resources */ System.out.println("Beginning pdu save to directory " + outputDirectory);
public void tearDownNetworkInterface() pduRecorder = new PduRecorder(outputDirectory, getNetworkAddress(), getNetworkPort()); // assumes save
{ pduRecorder.setDescriptor ("ExampleSimulationProgram Oblak pduRecorder");
pduRecorder.stop(); // trying to slience DIS logging so that the simulation progress is easier to follow
pduRecorder.setVerbose(verboseDisInterface);
disNetworkInterface.removeListener(pduListener); pduRecorder.setVerboseIncludesTimestamp(verboseDisInterface);
pduRecorder.setVerboseReceipt(verboseDisInterface);
disNetworkInterface.close(); pduRecorder.setVerboseSending(verboseDisInterface);
// disNetworkInterface.kill(); // renamed as close(), deprecated
// disNetworkInterface = null; // making sure no possibility of zombie process remaining... pduRecorder.start(); // begin running
} }
/** /** All done, release network resources */
* Send a single Protocol Data Unit (PDU) of any type public void tearDownNetworkInterface()
* @param pdu the pdu to send {
*/ pduRecorder.stop();
private void sendSinglePdu(Pdu pdu)
{ disNetworkInterface.removeListener(pduListener);
try
{ disNetworkInterface.close();
disNetworkInterface.send(pdu); // disNetworkInterface.kill(); // renamed as close(), deprecated
Thread.sleep(100); // TODO consider refactoring the wait logic and moving externally // disNetworkInterface = null; // making sure no possibility of zombie process remaining...
} }
catch (InterruptedException ex)
{ /**
System.err.println(this.getClass().getName() + " Error sending PDU: " + ex.getLocalizedMessage()); * Send a single Protocol Data Unit (PDU) of any type
System.exit(1); * @param pdu the pdu to send
} */
} private void sendSinglePdu(Pdu pdu)
{
/** try
* Send Comment PDU {
* @see <a href="https://docs.oracle.com/javase/tutorial/java/javaOO/arguments.html">Passing Information to a Method or a Constructor</a> Arbitrary Number of Arguments disNetworkInterface.send(pdu);
* @param commentType enumeration value describing purpose of the narrative comment Thread.sleep(100); // TODO consider refactoring the wait logic and moving externally
* @param comments String array of narrative comments }
*/ catch (InterruptedException ex)
public void sendCommentPdu(VariableRecordType commentType, {
// vararg... variable-length set of String comments can optionally follow System.err.println(this.getClass().getName() + " Error sending PDU: " + ex.getLocalizedMessage());
String... comments) System.exit(1);
{ }
sendAllPdusForLoopTimestep (null, null, commentType, comments); }
}
/**
/** * Send Comment PDU
* Send EntityState, Fire, Comment PDUs that got updated for this loop, reflecting state of current simulation timestep. * @see <a href="https://docs.oracle.com/javase/tutorial/java/javaOO/arguments.html">Passing Information to a Method or a Constructor</a> Arbitrary Number of Arguments
* @see <a href="https://docs.oracle.com/javase/tutorial/java/javaOO/arguments.html">Passing Information to a Method or a Constructor</a> Arbitrary Number of Arguments * @param commentType enumeration value describing purpose of the narrative comment
* @param entityStatePdu the ESPDU to send, if any * @param comments String array of narrative comments
* @param firePdu the FirePDU to send, if any */
* @param commentType enumeration value describing purpose of the narrative comment public void sendCommentPdu(VariableRecordType commentType,
* @param comments String array of narrative comments // vararg... variable-length set of String comments can optionally follow
*/ String... comments)
public void sendAllPdusForLoopTimestep(EntityStatePdu entityStatePdu, {
FirePdu firePdu, sendAllPdusForLoopTimestep (null, null, commentType, comments);
VariableRecordType commentType, }
// vararg... variable-length set of String comments can optionally follow
String... comments) /**
{ * Send EntityState, Fire, Comment PDUs that got updated for this loop, reflecting state of current simulation timestep.
if (entityStatePdu != null) * @see <a href="https://docs.oracle.com/javase/tutorial/java/javaOO/arguments.html">Passing Information to a Method or a Constructor</a> Arbitrary Number of Arguments
sendSinglePdu(entityStatePdu); * @param entityStatePdu the ESPDU to send, if any
* @param firePdu the FirePDU to send, if any
if (firePdu != null) * @param commentType enumeration value describing purpose of the narrative comment
sendSinglePdu(firePdu); // bang * @param comments String array of narrative comments
*/
if ((comments != null) && (comments.length > 0)) public void sendAllPdusForLoopTimestep(EntityStatePdu entityStatePdu,
{ FirePdu firePdu,
ArrayList<String> newCommentsList = new ArrayList<>(); VariableRecordType commentType,
for (String comment : comments) // vararg... variable-length set of String comments can optionally follow
{ String... comments)
if (!comment.isEmpty()) {
{ if (entityStatePdu != null)
newCommentsList.add(comment); // OK found something to send sendSinglePdu(entityStatePdu);
}
} if (firePdu != null)
if (!newCommentsList.isEmpty()) sendSinglePdu(firePdu); // bang
{
if (commentType == null) if ((comments != null) && (comments.length > 0))
commentType = otherComment; // fallback value otherComment {
// now build the commentPdu from these string inputs, thus constructing a narrative entry ArrayList<String> newCommentsList = new ArrayList<>();
CommentPdu commentPdu = pduFactory.makeCommentPdu(commentType, newCommentsList.toArray(new String[0])); // comments); for (String comment : comments)
sendSinglePdu(commentPdu); {
if (isVerboseComments()) if (!comment.isEmpty())
System.out.println("*** [Narrative comment sent: " + commentType.name() + "] " + newCommentsList.toString()); {
} newCommentsList.add(comment); // OK found something to send
} }
} }
if (!newCommentsList.isEmpty())
/** {
* Main method is first executed when a program instance is loaded. if (commentType == null)
* @see <a href="https://docs.oracle.com/javase/tutorial/getStarted/application/index.html">Java Tutorials: A Closer Look at the "Hello World!" Application</a> commentType = otherComment; // fallback value otherComment
* @param args command-line arguments are an array of optional String parameters that are passed from execution environment during invocation // now build the commentPdu from these string inputs, thus constructing a narrative entry
*/ CommentPdu commentPdu = pduFactory.makeCommentPdu(commentType, newCommentsList.toArray(new String[0])); // comments);
public static void main(String[] args) sendSinglePdu(commentPdu);
{ if (isVerboseComments())
System.out.println(TRACE_PREFIX + "started..."); System.out.println("*** [Narrative comment sent: " + commentType.name() + "] " + newCommentsList.toString());
}
ExampleSimulationProgram thisProgram = new ExampleSimulationProgram(); // creates instance }
}
// initial execution: can handle args array of initialization arguments here
if (args.length == 2) /**
{ * Main method is first executed when a program instance is loaded.
if ((args[0] != null) && !args[0].isEmpty()) * @see <a href="https://docs.oracle.com/javase/tutorial/getStarted/application/index.html">Java Tutorials: A Closer Look at the "Hello World!" Application</a>
thisProgram.setNetworkAddress(args[0]); * @param args command-line arguments are an array of optional String parameters that are passed from execution environment during invocation
*/
if ((args[1] != null) && !args[1].isEmpty()) public static void main(String[] args)
thisProgram.setNetworkPort(Integer.parseInt(args[1])); {
} System.out.println(TRACE_PREFIX + "started...");
else if (args.length != 0)
{ ExampleSimulationProgram thisProgram = new ExampleSimulationProgram(); // creates instance
System.err.println("Usage: " + thisProgram.getClass().getName() + " [address port]");
System.exit(-1); // initial execution: can handle args array of initialization arguments here
} if (args.length == 2)
// OK here we go... {
if ((args[0] != null) && !args[0].isEmpty())
thisProgram.setUpNetworkInterface(); thisProgram.setNetworkAddress(args[0]);
thisProgram.runSimulationLoops (); // ... your simulation execution code goes in there ... if ((args[1] != null) && !args[1].isEmpty())
thisProgram.setNetworkPort(Integer.parseInt(args[1]));
thisProgram.tearDownNetworkInterface(); // make sure no processes are left lingering }
else if (args.length != 0)
System.out.println(TRACE_PREFIX + "complete."); // report successful completion {
} System.err.println("Usage: " + thisProgram.getClass().getName() + " [address port]");
System.exit(-1);
/** }
* get whether verbose comments are enabled // OK here we go...
* @return whether verboseComments mode is enabled
*/ thisProgram.setUpNetworkInterface();
public boolean isVerboseComments() {
return verboseComments; thisProgram.runSimulationLoops (); // ... your simulation execution code goes in there ...
}
thisProgram.tearDownNetworkInterface(); // make sure no processes are left lingering
/**
* set whether verbose comments are enabled System.out.println(TRACE_PREFIX + "complete."); // report successful completion
* @param newVerboseComments whether verboseComments mode is enabled }
*/
public void setVerboseComments(boolean newVerboseComments) { /**
this.verboseComments = newVerboseComments; * get whether verbose comments are enabled
} * @return whether verboseComments mode is enabled
} */
public boolean isVerboseComments() {
return verboseComments;
}
/**
* set whether verbose comments are enabled
* @param newVerboseComments whether verboseComments mode is enabled
*/
public void setVerboseComments(boolean newVerboseComments) {
this.verboseComments = newVerboseComments;
}
}
0% Loading or .
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment