diff --git a/README.md b/README.md index 661ece163c97eadcf7dd4eca2a5ccc105ab7931a..628875fec4f8fb4b60bcd164e584a38474c16764 100644 --- a/README.md +++ b/README.md @@ -7,6 +7,7 @@ Key course sites: * [NPS CLE Sakai site](https://cle.nps.edu/portal/site/6e9fe3d2-37ad-4dd1-83a3-39e8d3089435) for MV3500 course * [NPS GitLab site: NetworkedGraphicsMV3500](https://gitlab.nps.edu/Savage/NetworkedGraphicsMV3500) <!-- * [Wikipedia book: Networked_Modeling_and_Simulation](https://en.wikipedia.org/wiki/Book:Networked_Modeling_and_Simulation) --> +* [opendis7-java Distribution Products](https://savage.nps.edu/opendis7-java) * [Savage Developers Guide: telnet Network Protocol](https://savage.nps.edu/Savage/developers.html#telnet) References and resources: diff --git a/assignments/src/MV3500Cohort2023MarchJune/homework2/Oblak/UnicastUdpSender.java b/assignments/src/MV3500Cohort2023MarchJune/homework2/Oblak/UnicastUdpSender.java index 6c82fd9f6fcecf18e1ddb5fc7fd8a1888c2d33e3..c9df2c8982abc2486432d6b64c09945bfa68c0d0 100644 --- a/assignments/src/MV3500Cohort2023MarchJune/homework2/Oblak/UnicastUdpSender.java +++ b/assignments/src/MV3500Cohort2023MarchJune/homework2/Oblak/UnicastUdpSender.java @@ -28,7 +28,7 @@ public class UnicastUdpSender // public static final int SENDING_PORT = 1414; // not needed, can let system choose an open local port /** socket value of shared interest */ public static final int UDP_PORT = UnicastUdpReceiver.UDP_PORT; // 1415; ensure consistent - private static final int TOTAL_PACKETS_TO_SEND = 100; + private static final int TOTAL_PACKETS_TO_SEND = 50; /** socket value of shared interest */ public static final String DESTINATION_HOST = "localhost"; @@ -46,7 +46,7 @@ public class UnicastUdpSender DataOutputStream dos = null; int packetID = 0; // counter variable to send in packet float value = -1.0f; // unreachable value is good sentinel to ensure expected changes occur - String message = MY_NAME + " says Hello MV3500"; // no really + String message = MY_NAME + " says Hello to assingment 2 "; // no really String padding = new String(); try diff --git a/assignments/src/MV3500Cohort2023MarchJune/homework3/Chojnacki/ExampleSimulationProgram.java b/assignments/src/MV3500Cohort2023MarchJune/homework3/Chojnacki/ExampleSimulationProgram.java new file mode 100644 index 0000000000000000000000000000000000000000..7ad05cf86242849e80091ed1657dfffec1a7acf6 --- /dev/null +++ b/assignments/src/MV3500Cohort2023MarchJune/homework3/Chojnacki/ExampleSimulationProgram.java @@ -0,0 +1,515 @@ +/** + * 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 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 + * and tracing its source before destroying it - updated September 12, 2021 to ensure + * correct file pushed to Gitlab. + * + * @author Bruce Chojnacki + */ +package MV3500Cohort2023MarchJune.homework3.Chojnacki; + +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.utilities.DisThreadedNetworkInterface; +import edu.nps.moves.dis7.utilities.PduFactory; +import edu.nps.moves.dis7.utilities.stream.PduRecorder; +import java.util.ArrayList; +import java.util.logging.Level; +import java.util.logging.Logger; + +/** 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. + * Default settings include PDU recording turned on by default. + */ +public class ExampleSimulationProgram +{ + private boolean verboseComments = true; + static final String NETWORK_ADDRESS_DEFAULT = "239.1.2.3"; + static final int NETWORK_PORT_DEFAULT = 3000; + static String networkAddress = NETWORK_ADDRESS_DEFAULT; + 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 + FNFireWallID.setSiteID(13); + FNFireWallID.setApplicationID(43); + FNFireWallID.setEntityID(103); + return FNFireWallID; + } + + private EntityType createFriendFireWallType() { + EntityType FNFireWallType = new EntityType(); + FNFireWallType.setEntityKind(EntityKind.PLATFORM); + FNFireWallType.setDomain(Domain.inst(PlatformDomain.OTHER)); + FNFireWallType.setCountry(Country.UNITED_STATES_OF_AMERICA_USA); + FNFireWallType.setCategory(3); + FNFireWallType.setSubCategory(1); + FNFireWallType.setSpecific(1); + return FNFireWallType; + } + + private EntityID createMalPacket() { + EntityID MalPacketID = new EntityID(); // 1.1.45.1.7.1 Platform,Cyber,China,MaliciousPacket + MalPacketID.setSiteID(66); + MalPacketID.setApplicationID(666); + MalPacketID.setEntityID(6666); + return MalPacketID; + } + + private EntityType createMalPacketType() { + EntityType MalPacketType = new EntityType(); + MalPacketType.setEntityKind(EntityKind.PLATFORM); + MalPacketType.setDomain(Domain.inst(PlatformDomain.OTHER)); + MalPacketType.setCountry(Country.CHINA_PEOPLES_REPUBLIC_OF_CHN); + MalPacketType.setCategory(3); + MalPacketType.setSubCategory(1); + MalPacketType.setSpecific(1); + return MalPacketType; + } + + private MunitionDescriptor createTraceroute() { + + EntityType TracerouteType = new EntityType(); //2.2.225.2.13.1 + TracerouteType.setEntityKind(EntityKind.MUNITION); + TracerouteType.setDomain(Domain.inst(PlatformDomain.OTHER)); + TracerouteType.setCountry(Country.UNITED_STATES_OF_AMERICA_USA); + TracerouteType.setCategory(2); + TracerouteType.setSubCategory(8); + TracerouteType.setSpecific(1); + MunitionDescriptor Traceroute = new MunitionDescriptor(); + Traceroute.setMunitionType(TracerouteType); + Traceroute.setQuantity(1000); + Traceroute.setFuse(MunitionDescriptorFuse.CONTACT); + Traceroute.setRate(200); + return Traceroute; + } + + /** + * This runSimulationLoops() method is for you, a + * programmer-modifiable method for defining and running a new simulation of interest. + * Welcome! Other parts of this program handle bookkeeping and plumbing tasks so that + * you can focus on your model entities and activities. + * Expandable support includes DIS EntityStatePdu, FirePdu and CommentPdu all available for + * modification and sending in a simulation loop. + * Continuous improvement efforts seek to make this program as easy and straightforward + * as possible for DIS simulationists to use and adapt. + * 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 () + { + 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; + final int SIMULATION_MAX_LOOP_COUNT = 10; // be deliberate out out there! also avoid infinite loops. + int simulationLoopCount = 0; // variable, initialized at 0 + boolean simulationComplete = false; // sentinel variable as termination condition,, are we done yet? + boolean fireBool = false; + boolean destBool = false; + + // 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. + + // create PDU object for US Firewall and set its values. + //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_1.setEntityType(createFriendFireWallType()); + 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. + //EntityID entityID_2 = new EntityID(); + //entityID_2.setSiteID(4).setApplicationID(5).setEntityID(6); + + EntityStatePdu entityStatePdu_2 = pduFactory.makeEntityStatePdu(); + entityStatePdu_2.setEntityID(createMalPacket()); + entityStatePdu_2.setEntityType(createMalPacketType()); + entityStatePdu_2.getEntityLocation().setX(7); + entityStatePdu_2.setForceId(ForceID.OPPOSING); + + 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? + EntityID fireID = new EntityID(); + fireID.setSiteID(13); + fireID.setApplicationID(43); + fireID.setEntityID(103); + EntityID targetID = new EntityID(); + targetID.setSiteID(66); + targetID.setApplicationID(666); + targetID.setEntityID(6666); + + firePdu.setFiringEntityID(fireID); + firePdu.setTargetEntityID(targetID); + + firePdu.setDescriptor(createTraceroute()); // calling create Traceroute Method + + EntityID TracerouteID = new EntityID(); + TracerouteID.setEntityID(1); + firePdu.setMunitionExpendibleID(TracerouteID); + + 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 + + //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? + { + simulationLoopCount++; // good practice: increment loop counter as first action in that loop + + // ============================================================================================= + // * your own simulation code starts here! * + // ============================================================================================= + + // 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... + + // 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 + 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(); + System.out.println("range: " + range + " hops from our Network DMZ!"); + + if (range < 5) { // Range 5 + 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()); + + if (firePdu.getTargetEntityID().getEntityID() == 6666) { + MalPacketPingsReceived += 1; + 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"; + destBool = true; + simulationComplete = true; + + } + } + } + // 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..."); + + + // make your reports: narrative code for CommentPdu here (set all to empty strings to avoid sending) + narrativeMessage1 = "MV3500 ExampleSimulationProgramAllen_3"; + narrativeMessage2 = "runSimulation() loop " + simulationLoopCount; + narrativeMessage3 = "this is working!"; // intentionally blank for testing + + // your loop termination condition goes here + if (simulationLoopCount > 4) // for example + { + simulationComplete = true; + } + // ============================================================================================= + // * 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 + 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"); + sendAllPdusForLoopTimestep(entityStatePdu_1, firePdu, timeStepComment, narrativeMessage1, narrativeMessage2, narrativeMessage3); + 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 + { + //sendSinglePdu(detonationPdu); + System.out.println ("... [Termination condition met, simulationComplete=" + simulationComplete + "]"); // ", final loopCount=" + loopCount + + break; + } + } // end of simulation loop + + narrativeMessage2 = "runSimulation() completed successfully"; // all done + sendCommentPdu(narrativeComment, narrativeMessage1, narrativeMessage2, narrativeMessage3); + 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! + { + Logger.getLogger(ExampleSimulationProgram.class.getName()).log(Level.SEVERE, null, iex); + } + } + /* **************************** infrastructure code, modification is seldom needed ************************* */ + + String narrativeMessage1 = new String(); + String narrativeMessage2 = new String(); + String narrativeMessage3 = new String(); + String narrativeMessage4 = new String(); + + /* VariableRecordType enumerations have potential use with CommentPdu logs */ + /* TODO contrast to EntityType */ + VariableRecordType descriptionComment = VariableRecordType.DESCRIPTION; + VariableRecordType narrativeComment = VariableRecordType.COMPLETE_EVENT_REPORT; + VariableRecordType statusComment = VariableRecordType.APPLICATION_STATUS; + VariableRecordType timeStepComment = VariableRecordType.APPLICATION_TIMESTEP; + VariableRecordType otherComment = VariableRecordType.OTHER; + + /** + * Output prefix to identify this class, helps with logging + */ + private final static String TRACE_PREFIX = "[" + ExampleSimulationProgram.class.getName() + "] "; + + // class variables + PduFactory pduFactory = new PduFactory(); + DisThreadedNetworkInterface disNetworkInterface; + DisThreadedNetworkInterface.PduListener pduListener; + Pdu receivedPdu; + PduRecorder pduRecorder; + + /** + * Constructor design goal: additional built-in initialization conveniences can go here + * to keep student efforts focused on the runSimulation() method. + */ + public ExampleSimulationProgram() + { + // 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 + * @param port corresponding network port to use + */ + public ExampleSimulationProgram(String address, int port) + { + setNetworkAddress(address); + + setNetworkPort(port); + } + + /** + * get networkAddress + * @return the networkAddress + */ + public String getNetworkAddress() + { + return networkAddress; + } + + /** + * set networkAddress + * @param newNetworkAddress the networkAddress to set + */ + public final void setNetworkAddress(String newNetworkAddress) + { + ExampleSimulationProgram.networkAddress = newNetworkAddress; + } + + /** + * get networkPort + * @return the networkPort + */ + public int getNetworkPort() + { + return networkPort; + } + + /** + * set networkPort + * @param newNetworkPort the networkPort to set + */ + public final void setNetworkPort(int newNetworkPort) + { + ExampleSimulationProgram.networkPort = newNetworkPort; + } + + /** + * Initialize network interface, choosing best available network interface + */ + public void setUpNetworkInterface() + { + disNetworkInterface = new DisThreadedNetworkInterface(getNetworkAddress(), getNetworkPort()); + disNetworkInterface.setDescriptor ("ExampleSimulationProgramAllen_3 pdu looping"); + + System.out.println("Network confirmation:" + + " address=" + disNetworkInterface.getAddress()+ // disNetworkInterface.getMulticastGroup() + + " port=" + disNetworkInterface.getPort()); // + disNetworkInterface.getDisPort()); + pduListener = new DisThreadedNetworkInterface.PduListener() + { + /** Callback handler for listener */ + @Override + public void incomingPdu(Pdu newPdu) + { + receivedPdu = newPdu; + } + }; + disNetworkInterface.addListener(pduListener); + + String outputDirectory = DEFAULT_OUTPUT_DIRECTORY; + System.out.println("Beginning pdu save to directory " + outputDirectory); + pduRecorder = new PduRecorder(outputDirectory, getNetworkAddress(), getNetworkPort()); // assumes save + pduRecorder.setDescriptor ("ExampleSimulationProgramAllen_3 pduRecorder"); + pduRecorder.start(); // begin running + } + + /** All done, release network resources */ + public void tearDownNetworkInterface() + { + pduRecorder.stop(); + + disNetworkInterface.removeListener(pduListener); + + disNetworkInterface.close(); +// disNetworkInterface.kill(); // renamed as close(), deprecated +// disNetworkInterface = null; // making sure no possibility of zombie process remaining... + } + + /** + * Send a single Protocol Data Unit (PDU) of any type + * @param pdu the pdu to send + */ + private void sendSinglePdu(Pdu pdu) + { + try + { + disNetworkInterface.send(pdu); + Thread.sleep(100); // TODO consider refactoring the wait logic and moving externally + } + catch (InterruptedException ex) + { + System.err.println(this.getClass().getName() + " Error sending PDU: " + ex.getLocalizedMessage()); + System.exit(1); + } + } + + /** + * 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 + * @param commentType enumeration value describing purpose of the narrative comment + * @param comments String array of narrative comments + */ + public void sendCommentPdu(VariableRecordType commentType, + // vararg... variable-length set of String comments can optionally follow + String... comments) + { + sendAllPdusForLoopTimestep (null, null, commentType, comments); + } + + /** + * 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 + * @param entityStatePdu the ESPDU to send, if any + * @param firePdu the FirePDU to send, if any + * @param commentType enumeration value describing purpose of the narrative comment + * @param comments String array of narrative comments + */ + public void sendAllPdusForLoopTimestep(EntityStatePdu entityStatePdu, + FirePdu firePdu, + VariableRecordType commentType, + // vararg... variable-length set of String comments can optionally follow + String... comments) + { + if (entityStatePdu != null) + sendSinglePdu(entityStatePdu); + + if (firePdu != null) + sendSinglePdu(firePdu); // bang + + if ((comments != null) && (comments.length > 0)) + { + ArrayList<String> newCommentsList = new ArrayList<>(); + for (String comment : comments) + { + if (!comment.isEmpty()) + { + newCommentsList.add(comment); // OK found something to send + } + } + if (!newCommentsList.isEmpty()) + { + if (commentType == null) + commentType = otherComment; // fallback value otherComment + // now build the commentPdu from these string inputs, thus constructing a narrative entry + CommentPdu commentPdu = pduFactory.makeCommentPdu(commentType, newCommentsList.toArray(new String[0])); // comments); + sendSinglePdu(commentPdu); + if (isVerboseComments()) + System.out.println("*** [Narrative comment sent: " + commentType.name() + "] " + newCommentsList.toString()); + } + } + } + + /** + * Main method is first executed when a program instance is loaded. + * @see <a href="https://docs.oracle.com/javase/tutorial/getStarted/application/index.html">Java Tutorials: A Closer Look at the "Hello World!" Application</a> + * @param args command-line arguments are an array of optional String parameters that are passed from execution environment during invocation + */ + public static void main(String[] args) + { + System.out.println(TRACE_PREFIX + "started..."); + + ExampleSimulationProgram thisProgram = new ExampleSimulationProgram(); // creates instance + + // initial execution: can handle args array of initialization arguments here + if (args.length == 2) + { + if ((args[0] != null) && !args[0].isEmpty()) + thisProgram.setNetworkAddress(args[0]); + + if ((args[1] != null) && !args[1].isEmpty()) + thisProgram.setNetworkPort(Integer.parseInt(args[1])); + } + else if (args.length != 0) + { + System.err.println("Usage: " + thisProgram.getClass().getName() + " [address port]"); + System.exit(-1); + } + // OK here we go... + + thisProgram.setUpNetworkInterface(); + + thisProgram.runSimulationLoops (); // ... your simulation execution code goes in there ... + + thisProgram.tearDownNetworkInterface(); // make sure no processes are left lingering + + System.out.println(TRACE_PREFIX + "complete."); // report successful completion + } + + /** + * 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; + } +} diff --git a/assignments/src/MV3500Cohort2023MarchJune/homework3/Hedgcorth/ExampleSimulationProgram.java b/assignments/src/MV3500Cohort2023MarchJune/homework3/Hedgcorth/ExampleSimulationProgram.java new file mode 100644 index 0000000000000000000000000000000000000000..0fb320fec4ab75f4b0864ff06a6c30a7e5d52d47 --- /dev/null +++ b/assignments/src/MV3500Cohort2023MarchJune/homework3/Hedgcorth/ExampleSimulationProgram.java @@ -0,0 +1,435 @@ +package MV3500Cohort2023MarchJune.homework3.Hedgcorth; + +import edu.nps.moves.dis7.entities.swe.platform.surface._002Triton; +import edu.nps.moves.dis7.entities.usa.platform.air.CH53ESuperStallion; +import edu.nps.moves.dis7.enumerations.ForceID; +import edu.nps.moves.dis7.enumerations.VariableRecordType; +import edu.nps.moves.dis7.pdus.EntityID; +import edu.nps.moves.dis7.pdus.EntityStatePdu; +import edu.nps.moves.dis7.pdus.FirePdu; +import edu.nps.moves.dis7.pdus.MunitionDescriptor; +import edu.nps.moves.dis7.utilities.DisChannel; +import edu.nps.moves.dis7.utilities.PduFactory; +import java.time.LocalDateTime; +import java.util.logging.Level; +import java.util.logging.Logger; + +/** + * + * @author leahhedgcorth + */ +public class ExampleSimulationProgram { + + /* **************************** infrastructure code, modification is seldom needed ************************* */ + + private String descriptor = this.getClass().getSimpleName(); + /** + * DIS channel defined by network address/port combination includes multiple + * utility capabilities + */ + protected DisChannel disChannel; + /** + * Factory object used to create new PDU instances + */ + protected PduFactory pduFactory; + + /** + * seconds per loop for real-time or simulation execution + */ + private double simulationTimeStepDuration = 1.0; // seconds TODO encapsulate + /** + * initial simulation time in seconds + */ + double simulationTimeInitial = 0.0; + /** + * current simulation time in seconds + */ + double simulationTimeSeconds = simulationTimeInitial; + /** + * Maximum number of simulation loops + */ + int MAX_LOOP_COUNT = 4; + + String narrativeMessage1 = new String(); + String narrativeMessage2 = new String(); + String narrativeMessage3 = new String(); + + /** + * EntityID settings for entity 1 + */ + protected EntityID entityID_1 = new EntityID(); + /** + * EntityID settings for entity 2 + */ + protected EntityID entityID_2 = new EntityID(); + /** + * ESPDU for entity 1 + */ + protected EntityStatePdu entityStatePdu_1; + /** + * ESPDU for entity 2 + */ + protected EntityStatePdu entityStatePdu_2; + /** + * FirePdu for entity 1 first weapon (if any) + */ + protected FirePdu firePdu_1a; + /** + * FirePdu for entity 1 second weapon (if any) + */ + protected FirePdu firePdu_1b; + /** + * MunitionDescriptor for these weapons + */ + protected MunitionDescriptor munitionDescriptor1; + + /** + * Constructor to create an instance of this class. Design goal: additional + * built-in initialization conveniences can go here to keep your efforts + * focused on the runSimulation() method. + */ + // base constructor is not invoked automatically by other constructors + // https://stackoverflow.com/questions/581873/best-way-to-handle-multiple-constructors-in-java + public ExampleSimulationProgram() { + initialize(); + } + + /** + * Constructor to create an instance of this class. + * + * @param newDescriptor describes this program, useful for logging and + * debugging + */ + public ExampleSimulationProgram(String newDescriptor) { + descriptor = newDescriptor; + initialize(); + } + + /** + * Utility Constructor that allows your example simulation program to + * override default network address and port + * + * @param address network address to use + * @param port corresponding network port to use + */ + public ExampleSimulationProgram(String address, int port) { + disChannel.setNetworkAddress(address); + disChannel.setNetworkPort(port); + initialize(); + } + + /** + * Initialize channel setup for OpenDis7 and report a test PDU + * + * @see initializeDisChannel + * @see initializeSimulationEntities + */ + private void initialize() { + initializeDisChannel(); // must come first, uses PduFactory + + initializeSimulationEntities(); // set unchanging parameters + + disChannel.join(); // TODO further functionality expected + + String timeStepMessage = "Simulation timestep duration " + getSimulationTimeStepDuration() + " seconds"; + disChannel.sendCommentPdu(simulationTimeSeconds, DisChannel.COMMENTPDU_SIMULATION_TIMESTEP, timeStepMessage); + // additional constructor initialization can go here + } + + /** + * Initialize channel setup for OpenDis7 and report a test PDU + */ + private void initializeDisChannel() { + if (disChannel == null) { + disChannel = new DisChannel(); + } else { + disChannel.printlnTRACE("*** warning, duplicate invocation of initializeDisChannel() ignored"); + return; + } + pduFactory = disChannel.getPduFactory(); + disChannel.setDescriptor(this.getClass().getSimpleName()); // ExampleSimulationProgram might be a superclass + disChannel.setUpNetworkInterface(); + disChannel.printlnTRACE("just checking: disChannel.getNetworkAddress()=" + disChannel.getNetworkAddress() + + ", getNetworkPort()=" + disChannel.getNetworkPort()); + + disChannel.getPduRecorder().setVerbose(true); + +// disChannel.sendCommentPdu(VariableRecordType.OTHER, "ArrivalProcessOpenDis7 initialized"); // hello channel, debug + } + + /** + * Get ready, get set... initialize simulation entities + */ + public void initializeSimulationEntities() { + if (pduFactory == null) { + pduFactory = disChannel.getPduFactory(); + } + entityStatePdu_1 = pduFactory.makeEntityStatePdu(); + entityStatePdu_2 = pduFactory.makeEntityStatePdu(); + firePdu_1a = pduFactory.makeFirePdu(); + firePdu_1b = pduFactory.makeFirePdu(); + munitionDescriptor1 = new MunitionDescriptor(); + + // 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. + // PDU objects are already declared and instances created, so now set their values. + entityID_1.setSiteID(1).setApplicationID(2).setEntityID(3); // made-up example ID; + disChannel.addEntity(entityID_1); + + entityID_2.setSiteID(1).setApplicationID(2).setEntityID(4); // made-up example ID; + disChannel.addEntity(entityID_2); + // TODO someday, use enumerations for sites as part of a SimulationManager object; e.g. is there a unique site triplet for MOVES Institute? + + entityStatePdu_1.setEntityID(entityID_1); + entityStatePdu_1.setForceId(ForceID.FRIENDLY); +// entityStatePdu_1.setEntityType(new _001Poseidon()); // note import statement above +// entityStatePdu_1.setMarking("Entity #1"); + entityStatePdu_1.setEntityType(new CH53ESuperStallion()); // note import statement at top + entityStatePdu_1.setMarking("Entity #53"); + entityStatePdu_1.getMarkingString(); // use Netbeans Debug breakpoint here to check left justified... + + entityStatePdu_2.setEntityID(entityID_2); + entityStatePdu_2.setForceId(ForceID.OPPOSING); + entityStatePdu_2.setEntityType(new _002Triton()); // note import statement above + entityStatePdu_2.setMarking("Entity #2"); + + // TODO how should we customize this munition? what are key parameters for your simulation? + // more is needed here by scenario authors... + munitionDescriptor1.setQuantity(1); + firePdu_1a.setDescriptor(munitionDescriptor1).setRange(1000.0f); + } + + /** + * This runSimulationLoops() method is for you, a customizable + * programmer-modifiable code block for defining and running a new + * simulation of interest. + * + * Welcome! Other parts of this program handle bookkeeping and plumbing + * tasks so that you can focus on your model entities and activities. + * Expandable support includes DIS EntityStatePdu, FirePdu and CommentPdu + * all available for modification and sending in a simulation loop. + * Continuous improvement efforts seek to make this program as easy and + * straightforward as possible for DIS simulationists to use and adapt. 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 might do that + public void runSimulationLoops() { + try { + final int SIMULATION_MAX_LOOP_COUNT = 10; // be deliberate out there! also avoid infinite loops. + int simulationLoopCount = 0; // variable, initialized at 0 + boolean simulationComplete = false; // sentinel variable as termination condition, are we done yet? + + // TODO reset Clock Time for today's date and timestamp to zero, providing consistent outputs for each simulation run + String timeMessage = "Simulation time " + simulationTimeSeconds + " at LocalDateTime " + LocalDateTime.now(); + disChannel.sendCommentPdu(simulationTimeSeconds, DisChannel.COMMENTPDU_TIME, timeMessage); + // TODO replace enumeration with disChannel.COMMENTPDU_TIME + // TODO fix VariableRecordType.TIME_AMP_DATE_VALID + + // =================================================================================================== + // 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 + + // ============================================================================================= + // * your own simulation code starts here! ***************************************************** + // ============================================================================================= + // are there any other variables to modify at the beginning of your loop? + // are your reading any DIS PDUs from the network? check for them here + // 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() + 1.0); // 1m per timestep + + // decide whether to fire, and then update the firePdu. Hmmm, you might want a target to shoot at! + // 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..."); + System.out.flush(); // make sure this arrives to user even if other threads somehow become deadlocked + + // make your reports: narrative code for CommentPdu here (set all to empty strings to avoid sending) + narrativeMessage1 = "MV3500 ExampleSimulationProgram"; + narrativeMessage2 = "runSimulation() loop " + simulationLoopCount; + narrativeMessage3 = ""; // intentionally blank for testing + + // your loop termination condition goes here + if (simulationLoopCount > MAX_LOOP_COUNT) // for example + { + simulationComplete = true; + } + // ============================================================================================= + // * 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 + Thread.sleep((long) (getSimulationTimeStepDuration() * 1000)); // units of seconds * (1000 msec/sec) = milliseconds + System.out.println("... [Pausing for " + getSimulationTimeStepDuration() + " seconds]"); + + // OK now send the status PDUs for this loop, and then continue + System.out.println("... sending PDUs of interest for simulation step " + simulationLoopCount + ", monitor loopback to confirm sent"); + System.out.flush(); + + // TODO set timesteps in PDUs + sendAllPdusForLoopTimestep(simulationTimeSeconds, + entityStatePdu_1, + firePdu_1a, + DisChannel.COMMENTPDU_APPLICATION_STATUS, + narrativeMessage1, narrativeMessage2, narrativeMessage3); + disChannel.sendSinglePdu(simulationTimeSeconds, entityStatePdu_2); // me too i.e. 2! + + System.out.println("... [PDUs of interest successfully sent for this loop]"); + System.out.flush(); + + // =============================== + // current loop now finished, check whether to terminate if simulation complete, otherwise continue + if (simulationComplete || (simulationLoopCount > 10000)) // for example; including fail-safe condition is good + { + System.out.println("... [loop termination condition met, simulationComplete=" + simulationComplete + "]"); // ", final loopCount=" + loopCount + + System.out.flush(); + break; + } + simulationTimeSeconds += getSimulationTimeStepDuration(); // good practice: increment simulationTime as lastst action in that loop + + } // end of simulation loop, continue until done + // ===================================================================================================// ===================================================================================================// ===================================================================================================// =================================================================================================== + + narrativeMessage2 = "runSimulation() completed successfully"; // all done, so tell everyone else on the channel + // TODO better javadoc needs to be autogenerated for VariableRecordType enumerations + disChannel.sendCommentPdu(DisChannel.COMMENTPDU_NARRATIVE, narrativeMessage1, narrativeMessage2, narrativeMessage3); + System.out.println("... [final=completion CommentPdu successfully sent for simulation]"); + + disChannel.leave(); // embedded SimulationManager is expected to send appropriate PDUs for entity, application shutdown + } catch (InterruptedException iex) // handle any exception that your code might choose to provoke! + { + Logger.getLogger(ExampleSimulationProgram.class.getSimpleName()).log(Level.SEVERE, null, iex); + } + } + + /** + * Send EntityState, Fire, Comment PDUs that got updated for this loop, + * reflecting state of current simulation timestep. + * + * @param simTimeSeconds simulation time in second, applied to PDU as + * timestamp + * @param entityStatePdu the ESPDU to send, if any + * @param firePdu the FirePDU to send, if any + * @param commentType enumeration value describing purpose of the narrative + * comment PDU + * @param comments String array of narrative comments + * @see DisChannel // * @see DisTime // TODO find renamed version + * @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 + */ + public void sendAllPdusForLoopTimestep(double simTimeSeconds, + EntityStatePdu entityStatePdu, + FirePdu firePdu, + VariableRecordType commentType, + // vararg... variable-length set of String comments can optionally follow + String... comments) { + if (entityStatePdu != null) { + disChannel.sendSinglePdu(simTimeSeconds, entityStatePdu); + } + + if (firePdu != null) { + disChannel.sendSinglePdu(simTimeSeconds, firePdu); // bang + } + disChannel.sendCommentPdu(simTimeSeconds, commentType, comments); // empty comments are filtered + } + + /** + * Initial execution via main() method: handle args array of command-line + * initialization (CLI) arguments here + * + * @param args command-line parameters: network address and port + */ + protected void handleArguments(String[] args) { + // initial execution: handle args array of initialization arguments here + if (args.length == 2) { + if ((args[0] != null) && !args[0].isEmpty()) { + thisProgram.disChannel.setNetworkAddress(args[0]); + } + if ((args[1] != null) && !args[1].isEmpty()) { + thisProgram.disChannel.setNetworkPort(Integer.parseInt(args[1])); + } + } else if (args.length != 0) { + System.err.println("Usage: " + thisProgram.getClass().getSimpleName() + " [address port]"); + System.exit(-1); + } + } + + /** + * Get simple descriptor (such as parent class name) for this network + * interface, used in trace statements + * + * @return simple descriptor name + */ + public String getDescriptor() { + return descriptor; + } + + /** + * Set new simple descriptor (such as parent class name) for this network + * interface, used in trace statements + * + * @param newDescriptor simple descriptor name for this interface + */ + public void setDescriptor(String newDescriptor) { + if (newDescriptor == null) { + newDescriptor = ""; + } + this.descriptor = newDescriptor; + } + + /** + * parameter accessor method + * + * @return the simulationTimeStepDuration in seconds + */ + public double getSimulationTimeStepDuration() { + return simulationTimeStepDuration; + } + + /** + * parameter accessor method + * + * @param timeStepDurationSeconds the simulationTimeStepDuration in seconds + * to set + */ + public void setSimulationTimeStepDuration(double timeStepDurationSeconds) { + this.simulationTimeStepDuration = timeStepDurationSeconds; + } + + /** + * Locally instantiable copy of program, can be subclassed. + */ + protected static ExampleSimulationProgram thisProgram; + + /** + * Main method is first executed when a program instance is loaded. + * + * @see + * <a href="https://docs.oracle.com/javase/tutorial/getStarted/application/index.html">Java + * Tutorials: A Closer Look at the "Hello World!" Application</a> + * @param args command-line parameters: network address and port. + * Command-line arguments are an array of optional String parameters that + * are passed from execution environment during invocation + */ + public static void main(String[] args) { + thisProgram = new ExampleSimulationProgram("test constructor"); // create instance of self within static main() method + + thisProgram.disChannel.printlnTRACE("main() started..."); + + thisProgram.handleArguments(args); // process any command-line invocation arguments + + thisProgram.runSimulationLoops(); // ... your simulation execution code goes in there ... + + thisProgram.disChannel.tearDownNetworkInterface(); // make sure no processes are left lingering + + thisProgram.disChannel.printlnTRACE("complete."); // report successful completion + + System.exit(0); // ensure all threads and sockets released + } +} diff --git a/assignments/src/MV3500Cohort2023MarchJune/homework3/Oblak/ExampleSimulationProgram.java b/assignments/src/MV3500Cohort2023MarchJune/homework3/Oblak/ExampleSimulationProgram.java new file mode 100644 index 0000000000000000000000000000000000000000..48ede73ae0f26cc9c27500a6d3e0e5f6ffa5dce1 --- /dev/null +++ b/assignments/src/MV3500Cohort2023MarchJune/homework3/Oblak/ExampleSimulationProgram.java @@ -0,0 +1,515 @@ +/** + * 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 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 + * and tracing its source before destroying it - updated September 12, 2021 to ensure + * correct file pushed to Gitlab. + * + * @author William Oblak (Changes made from copy given in class) + */ +package MV3500Cohort2023MarchJune.homework3.Oblak; + +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.utilities.DisThreadedNetworkInterface; +import edu.nps.moves.dis7.utilities.PduFactory; +import edu.nps.moves.dis7.utilities.stream.PduRecorder; +import java.util.ArrayList; +import java.util.logging.Level; +import java.util.logging.Logger; + +/** 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. + * Default settings include PDU recording turned on by default. + */ +public class ExampleSimulationProgram +{ + private boolean verboseComments = true; + static final String NETWORK_ADDRESS_DEFAULT = "239.1.2.3"; + static final int NETWORK_PORT_DEFAULT = 3000; + static String networkAddress = NETWORK_ADDRESS_DEFAULT; + 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 + FNFireWallID.setSiteID(13); + FNFireWallID.setApplicationID(43); + FNFireWallID.setEntityID(103); + return FNFireWallID; + } + + private EntityType createFriendFireWallType() { + EntityType FNFireWallType = new EntityType(); + FNFireWallType.setEntityKind(EntityKind.PLATFORM); + FNFireWallType.setDomain(Domain.inst(PlatformDomain.OTHER)); + FNFireWallType.setCountry(Country.AUSTRALIA_AUS); + FNFireWallType.setCategory(3); + FNFireWallType.setSubCategory(1); + FNFireWallType.setSpecific(1); + return FNFireWallType; + } + + private EntityID createMalPacket() { + EntityID MalPacketID = new EntityID(); // 1.1.45.1.7.1 Platform,Cyber,China,MaliciousPacket + MalPacketID.setSiteID(66); + MalPacketID.setApplicationID(666); + MalPacketID.setEntityID(6666); + return MalPacketID; + } + + private EntityType createMalPacketType() { + EntityType MalPacketType = new EntityType(); + MalPacketType.setEntityKind(EntityKind.PLATFORM); + MalPacketType.setDomain(Domain.inst(PlatformDomain.OTHER)); + MalPacketType.setCountry(Country.CHINA_PEOPLES_REPUBLIC_OF_CHN); + MalPacketType.setCategory(3); + MalPacketType.setSubCategory(1); + MalPacketType.setSpecific(1); + return MalPacketType; + } + + private MunitionDescriptor createTraceroute() { + + EntityType TracerouteType = new EntityType(); //2.2.225.2.13.1 + TracerouteType.setEntityKind(EntityKind.MUNITION); + TracerouteType.setDomain(Domain.inst(PlatformDomain.OTHER)); + TracerouteType.setCountry(Country.AUSTRALIA_AUS); + TracerouteType.setCategory(2); + TracerouteType.setSubCategory(8); + TracerouteType.setSpecific(1); + MunitionDescriptor Traceroute = new MunitionDescriptor(); + Traceroute.setMunitionType(TracerouteType); + Traceroute.setQuantity(1000); + Traceroute.setFuse(MunitionDescriptorFuse.CONTACT); + Traceroute.setRate(200); + return Traceroute; + } + + /** + * This runSimulationLoops() method is for you, a + * programmer-modifiable method for defining and running a new simulation of interest. + * Welcome! Other parts of this program handle bookkeeping and plumbing tasks so that + * you can focus on your model entities and activities. + * Expandable support includes DIS EntityStatePdu, FirePdu and CommentPdu all available for + * modification and sending in a simulation loop. + * Continuous improvement efforts seek to make this program as easy and straightforward + * as possible for DIS simulationists to use and adapt. + * 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 () + { + 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; + final int SIMULATION_MAX_LOOP_COUNT = 10; // be deliberate out out there! also avoid infinite loops. + int simulationLoopCount = 0; // variable, initialized at 0 + boolean simulationComplete = false; // sentinel variable as termination condition,, are we done yet? + boolean fireBool = false; + boolean destBool = false; + + // 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. + + // create PDU object for US Firewall and set its values. + //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_1.setEntityType(createFriendFireWallType()); + 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. + //EntityID entityID_2 = new EntityID(); + //entityID_2.setSiteID(4).setApplicationID(5).setEntityID(6); + + EntityStatePdu entityStatePdu_2 = pduFactory.makeEntityStatePdu(); + entityStatePdu_2.setEntityID(createMalPacket()); + entityStatePdu_2.setEntityType(createMalPacketType()); + entityStatePdu_2.getEntityLocation().setX(7); + entityStatePdu_2.setForceId(ForceID.OPPOSING); + + 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? + EntityID fireID = new EntityID(); + fireID.setSiteID(13); + fireID.setApplicationID(43); + fireID.setEntityID(103); + EntityID targetID = new EntityID(); + targetID.setSiteID(66); + targetID.setApplicationID(666); + targetID.setEntityID(6666); + + firePdu.setFiringEntityID(fireID); + firePdu.setTargetEntityID(targetID); + + firePdu.setDescriptor(createTraceroute()); // calling create Traceroute Method + + EntityID TracerouteID = new EntityID(); + TracerouteID.setEntityID(1); + firePdu.setMunitionExpendibleID(TracerouteID); + + 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 + + //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? + { + simulationLoopCount++; // good practice: increment loop counter as first action in that loop + + // ============================================================================================= + // * your own simulation code starts here! * + // ============================================================================================= + + // 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... + + // 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 + 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(); + System.out.println("range: " + range + " hops from our Network DMZ!"); + + if (range < 5) { // Range 5 + 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()); + + if (firePdu.getTargetEntityID().getEntityID() == 6666) { + MalPacketPingsReceived += 1; + 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"; + destBool = true; + simulationComplete = true; + + } + } + } + // 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..."); + + + // make your reports: narrative code for CommentPdu here (set all to empty strings to avoid sending) + narrativeMessage1 = "MV3500 ExampleSimulationProgramAllen_3"; + narrativeMessage2 = "runSimulation() loop " + simulationLoopCount; + narrativeMessage3 = "this is working!"; // intentionally blank for testing + + // your loop termination condition goes here + if (simulationLoopCount > 4) // for example + { + simulationComplete = true; + } + // ============================================================================================= + // * 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 + 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"); + sendAllPdusForLoopTimestep(entityStatePdu_1, firePdu, timeStepComment, narrativeMessage1, narrativeMessage2, narrativeMessage3); + 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 + { + //sendSinglePdu(detonationPdu); + System.out.println ("... [Termination condition met, simulationComplete=" + simulationComplete + "]"); // ", final loopCount=" + loopCount + + break; + } + } // end of simulation loop + + narrativeMessage2 = "runSimulation() completed successfully"; // all done + sendCommentPdu(narrativeComment, narrativeMessage1, narrativeMessage2, narrativeMessage3); + 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! + { + Logger.getLogger(ExampleSimulationProgram.class.getName()).log(Level.SEVERE, null, iex); + } + } + /* **************************** infrastructure code, modification is seldom needed ************************* */ + + String narrativeMessage1 = new String(); + String narrativeMessage2 = new String(); + String narrativeMessage3 = new String(); + String narrativeMessage4 = new String(); + + /* VariableRecordType enumerations have potential use with CommentPdu logs */ + /* TODO contrast to EntityType */ + VariableRecordType descriptionComment = VariableRecordType.DESCRIPTION; + VariableRecordType narrativeComment = VariableRecordType.COMPLETE_EVENT_REPORT; + VariableRecordType statusComment = VariableRecordType.APPLICATION_STATUS; + VariableRecordType timeStepComment = VariableRecordType.APPLICATION_TIMESTEP; + VariableRecordType otherComment = VariableRecordType.OTHER; + + /** + * Output prefix to identify this class, helps with logging + */ + private final static String TRACE_PREFIX = "[" + ExampleSimulationProgram.class.getName() + "] "; + + // class variables + PduFactory pduFactory = new PduFactory(); + DisThreadedNetworkInterface disNetworkInterface; + DisThreadedNetworkInterface.PduListener pduListener; + Pdu receivedPdu; + PduRecorder pduRecorder; + + /** + * Constructor design goal: additional built-in initialization conveniences can go here + * to keep student efforts focused on the runSimulation() method. + */ + public ExampleSimulationProgram() + { + // 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 + * @param port corresponding network port to use + */ + public ExampleSimulationProgram(String address, int port) + { + setNetworkAddress(address); + + setNetworkPort(port); + } + + /** + * get networkAddress + * @return the networkAddress + */ + public String getNetworkAddress() + { + return networkAddress; + } + + /** + * set networkAddress + * @param newNetworkAddress the networkAddress to set + */ + public final void setNetworkAddress(String newNetworkAddress) + { + ExampleSimulationProgram.networkAddress = newNetworkAddress; + } + + /** + * get networkPort + * @return the networkPort + */ + public int getNetworkPort() + { + return networkPort; + } + + /** + * set networkPort + * @param newNetworkPort the networkPort to set + */ + public final void setNetworkPort(int newNetworkPort) + { + ExampleSimulationProgram.networkPort = newNetworkPort; + } + + /** + * Initialize network interface, choosing best available network interface + */ + public void setUpNetworkInterface() + { + disNetworkInterface = new DisThreadedNetworkInterface(getNetworkAddress(), getNetworkPort()); + disNetworkInterface.setDescriptor ("ExampleSimulationProgramAllen_3 pdu looping"); + + System.out.println("Network confirmation:" + + " address=" + disNetworkInterface.getAddress()+ // disNetworkInterface.getMulticastGroup() + + " port=" + disNetworkInterface.getPort()); // + disNetworkInterface.getDisPort()); + pduListener = new DisThreadedNetworkInterface.PduListener() + { + /** Callback handler for listener */ + @Override + public void incomingPdu(Pdu newPdu) + { + receivedPdu = newPdu; + } + }; + disNetworkInterface.addListener(pduListener); + + String outputDirectory = DEFAULT_OUTPUT_DIRECTORY; + System.out.println("Beginning pdu save to directory " + outputDirectory); + pduRecorder = new PduRecorder(outputDirectory, getNetworkAddress(), getNetworkPort()); // assumes save + pduRecorder.setDescriptor ("ExampleSimulationProgramAllen_3 pduRecorder"); + pduRecorder.start(); // begin running + } + + /** All done, release network resources */ + public void tearDownNetworkInterface() + { + pduRecorder.stop(); + + disNetworkInterface.removeListener(pduListener); + + disNetworkInterface.close(); +// disNetworkInterface.kill(); // renamed as close(), deprecated +// disNetworkInterface = null; // making sure no possibility of zombie process remaining... + } + + /** + * Send a single Protocol Data Unit (PDU) of any type + * @param pdu the pdu to send + */ + private void sendSinglePdu(Pdu pdu) + { + try + { + disNetworkInterface.send(pdu); + Thread.sleep(100); // TODO consider refactoring the wait logic and moving externally + } + catch (InterruptedException ex) + { + System.err.println(this.getClass().getName() + " Error sending PDU: " + ex.getLocalizedMessage()); + System.exit(1); + } + } + + /** + * 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 + * @param commentType enumeration value describing purpose of the narrative comment + * @param comments String array of narrative comments + */ + public void sendCommentPdu(VariableRecordType commentType, + // vararg... variable-length set of String comments can optionally follow + String... comments) + { + sendAllPdusForLoopTimestep (null, null, commentType, comments); + } + + /** + * 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 + * @param entityStatePdu the ESPDU to send, if any + * @param firePdu the FirePDU to send, if any + * @param commentType enumeration value describing purpose of the narrative comment + * @param comments String array of narrative comments + */ + public void sendAllPdusForLoopTimestep(EntityStatePdu entityStatePdu, + FirePdu firePdu, + VariableRecordType commentType, + // vararg... variable-length set of String comments can optionally follow + String... comments) + { + if (entityStatePdu != null) + sendSinglePdu(entityStatePdu); + + if (firePdu != null) + sendSinglePdu(firePdu); // bang + + if ((comments != null) && (comments.length > 0)) + { + ArrayList<String> newCommentsList = new ArrayList<>(); + for (String comment : comments) + { + if (!comment.isEmpty()) + { + newCommentsList.add(comment); // OK found something to send + } + } + if (!newCommentsList.isEmpty()) + { + if (commentType == null) + commentType = otherComment; // fallback value otherComment + // now build the commentPdu from these string inputs, thus constructing a narrative entry + CommentPdu commentPdu = pduFactory.makeCommentPdu(commentType, newCommentsList.toArray(new String[0])); // comments); + sendSinglePdu(commentPdu); + if (isVerboseComments()) + System.out.println("*** [Narrative comment sent: " + commentType.name() + "] " + newCommentsList.toString()); + } + } + } + + /** + * Main method is first executed when a program instance is loaded. + * @see <a href="https://docs.oracle.com/javase/tutorial/getStarted/application/index.html">Java Tutorials: A Closer Look at the "Hello World!" Application</a> + * @param args command-line arguments are an array of optional String parameters that are passed from execution environment during invocation + */ + public static void main(String[] args) + { + System.out.println(TRACE_PREFIX + "started..."); + + ExampleSimulationProgram thisProgram = new ExampleSimulationProgram(); // creates instance + + // initial execution: can handle args array of initialization arguments here + if (args.length == 2) + { + if ((args[0] != null) && !args[0].isEmpty()) + thisProgram.setNetworkAddress(args[0]); + + if ((args[1] != null) && !args[1].isEmpty()) + thisProgram.setNetworkPort(Integer.parseInt(args[1])); + } + else if (args.length != 0) + { + System.err.println("Usage: " + thisProgram.getClass().getName() + " [address port]"); + System.exit(-1); + } + // OK here we go... + + thisProgram.setUpNetworkInterface(); + + thisProgram.runSimulationLoops (); // ... your simulation execution code goes in there ... + + thisProgram.tearDownNetworkInterface(); // make sure no processes are left lingering + + System.out.println(TRACE_PREFIX + "complete."); // report successful completion + } + + /** + * 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; + } +} diff --git a/assignments/src/MV3500Cohort2023MarchJune/homework3/Oblak/package-info.java b/assignments/src/MV3500Cohort2023MarchJune/homework3/Oblak/package-info.java new file mode 100644 index 0000000000000000000000000000000000000000..827fb8cecab04050a26c05a1e42de08dddf697ac --- /dev/null +++ b/assignments/src/MV3500Cohort2023MarchJune/homework3/Oblak/package-info.java @@ -0,0 +1,10 @@ +/** + * Final project assignments supporting the NPS MOVES MV3500 Networked Graphics course. + * + * @see <a href="https://gitlab.nps.edu/Savage/NetworkedGraphicsMV3500/-/tree/master/assignments">networkedGraphicsMV3500 assignments</a> + * @see java.lang.Package + * @see <a href="https://stackoverflow.com/questions/22095487/why-is-package-info-java-useful">StackOverflow: why-is-package-info-java-useful</a> + * @see <a href="https://stackoverflow.com/questions/624422/how-do-i-document-packages-in-java">StackOverflow: how-do-i-document-packages-in-java</a> + */ + +package MV3500Cohort2023MarchJune.homework3.Oblak;