From 05c72e6f6d5ad1f0e8c4d26bd622c63c504be4c0 Mon Sep 17 00:00:00 2001 From: Leif Gruenwoldt Date: Sun, 14 Jan 2024 13:56:53 -0500 Subject: [PATCH] Remove deprecated classes These were marked Deprecated in November 2022, well over a year ago now. It's time these be removed to clean up the code base. --- .../moves/deadreckoning/DIS_DR_FPB_06.java | 50 - .../moves/deadreckoning/DIS_DR_FPW_02.java | 42 - .../moves/deadreckoning/DIS_DR_FVB_09.java | 58 - .../moves/deadreckoning/DIS_DR_FVW_05.java | 39 - .../moves/deadreckoning/DIS_DR_RPB_07.java | 146 -- .../moves/deadreckoning/DIS_DR_RPW_03.java | 93 - .../moves/deadreckoning/DIS_DR_RPW_03b.java | 50 - .../moves/deadreckoning/DIS_DR_RVB_08.java | 204 -- .../moves/deadreckoning/DIS_DR_RVW_04.java | 96 - .../moves/deadreckoning/DIS_DR_RVW_04b.java | 46 - .../moves/deadreckoning/DIS_DR_Static_01.java | 21 - .../deadreckoning/DIS_DeadReckoning.java | 515 ------ .../nps/moves/deadreckoning/DeadReckoner.java | 5 - .../edu/nps/moves/dis/FastEntityStatePdu.java | 1123 ----------- .../nps/moves/dis7/FastEntityStatePdu.java | 1009 ---------- .../java/edu/nps/moves/dis7/PduFactory.java | 22 +- .../edu/nps/moves/disutil/ByteBufferPool.java | 69 - .../moves/disutil/CoordinateTransformer.java | 38 - .../edu/nps/moves/disutil/DisMarshaller.java | 86 - .../java/edu/nps/moves/disutil/NioServer.java | 1634 ----------------- .../edu/nps/moves/disutil/PduFactory.java | 36 +- .../moves/disutil/PduMulticastReceiver.java | 234 --- .../disutil/PduNioMulticastReceiver.java | 221 --- .../java/edu/nps/moves/disutil/UdpServer.java | 850 --------- .../nps/moves/disutil/VariableLengthData.java | 282 --- .../edu/nps/moves/net/BehaviorConsumerIF.java | 56 - .../moves/net/BehaviorConsumerThreaded.java | 64 - .../edu/nps/moves/net/BehaviorProducerIF.java | 67 - .../nps/moves/net/BehaviorProducerUDP.java | 160 -- .../edu/nps/moves/net/BehaviorWriterIF.java | 72 - .../moves/deadreckoning/DeadReckonerTest.java | 292 --- .../edu/nps/moves/disutil/PduFactoryTest.java | 14 - 32 files changed, 3 insertions(+), 7691 deletions(-) delete mode 100755 src/main/java/edu/nps/moves/deadreckoning/DIS_DR_FPB_06.java delete mode 100755 src/main/java/edu/nps/moves/deadreckoning/DIS_DR_FPW_02.java delete mode 100755 src/main/java/edu/nps/moves/deadreckoning/DIS_DR_FVB_09.java delete mode 100755 src/main/java/edu/nps/moves/deadreckoning/DIS_DR_FVW_05.java delete mode 100755 src/main/java/edu/nps/moves/deadreckoning/DIS_DR_RPB_07.java delete mode 100755 src/main/java/edu/nps/moves/deadreckoning/DIS_DR_RPW_03.java delete mode 100755 src/main/java/edu/nps/moves/deadreckoning/DIS_DR_RPW_03b.java delete mode 100755 src/main/java/edu/nps/moves/deadreckoning/DIS_DR_RVB_08.java delete mode 100755 src/main/java/edu/nps/moves/deadreckoning/DIS_DR_RVW_04.java delete mode 100755 src/main/java/edu/nps/moves/deadreckoning/DIS_DR_RVW_04b.java delete mode 100755 src/main/java/edu/nps/moves/deadreckoning/DIS_DR_Static_01.java delete mode 100755 src/main/java/edu/nps/moves/deadreckoning/DIS_DeadReckoning.java delete mode 100644 src/main/java/edu/nps/moves/dis/FastEntityStatePdu.java delete mode 100644 src/main/java/edu/nps/moves/dis7/FastEntityStatePdu.java delete mode 100644 src/main/java/edu/nps/moves/disutil/ByteBufferPool.java delete mode 100644 src/main/java/edu/nps/moves/disutil/CoordinateTransformer.java delete mode 100644 src/main/java/edu/nps/moves/disutil/DisMarshaller.java delete mode 100644 src/main/java/edu/nps/moves/disutil/NioServer.java delete mode 100644 src/main/java/edu/nps/moves/disutil/PduMulticastReceiver.java delete mode 100644 src/main/java/edu/nps/moves/disutil/PduNioMulticastReceiver.java delete mode 100644 src/main/java/edu/nps/moves/disutil/UdpServer.java delete mode 100644 src/main/java/edu/nps/moves/disutil/VariableLengthData.java delete mode 100644 src/main/java/edu/nps/moves/net/BehaviorConsumerIF.java delete mode 100644 src/main/java/edu/nps/moves/net/BehaviorConsumerThreaded.java delete mode 100644 src/main/java/edu/nps/moves/net/BehaviorProducerIF.java delete mode 100644 src/main/java/edu/nps/moves/net/BehaviorProducerUDP.java delete mode 100644 src/main/java/edu/nps/moves/net/BehaviorWriterIF.java diff --git a/src/main/java/edu/nps/moves/deadreckoning/DIS_DR_FPB_06.java b/src/main/java/edu/nps/moves/deadreckoning/DIS_DR_FPB_06.java deleted file mode 100755 index 6e6270f9..00000000 --- a/src/main/java/edu/nps/moves/deadreckoning/DIS_DR_FPB_06.java +++ /dev/null @@ -1,50 +0,0 @@ -package edu.nps.moves.deadreckoning; - -import org.apache.commons.math3.geometry.euclidean.threed.Vector3D; - -/** - * - * (SECONDARY Methods Group) Fixed, rate of position, body coordinates || - * Linear motion without rotation - * - * @author Sheldon L. Snyder - * @deprecated Use {@link DeadReckoner} instead. - */ -@Deprecated -public class DIS_DR_FPB_06 extends DIS_DeadReckoning -{ - /** - * The driver for a DIS_DR_FPB_06 DR algorithm from the Runnable interface - *

- * linear motion only without rotation - */ - public void run() - { - try - { - while(true) - { - Thread.sleep(stall); - update(); - }//while(true) - }// try - catch(Exception e) - { - System.out.println(e); - } - }//run()-------------------------------------------------------------------- - - void update() { - deltaCt++; - // solve for the new position - Vector3D velVec = new Vector3D(entityLinearVelocity_X, entityLinearVelocity_Y, entityLinearVelocity_Z); - // For fixed (non-rotating), R1 = changeDelta * Identity - Vector3D updated = initOrien.applyInverseTo(velVec.scalarMultiply(changeDelta)); - - // set the new position... - entityLocation_X += updated.getX(); - entityLocation_Y += updated.getY(); - entityLocation_Z += updated.getZ(); - } - -} diff --git a/src/main/java/edu/nps/moves/deadreckoning/DIS_DR_FPW_02.java b/src/main/java/edu/nps/moves/deadreckoning/DIS_DR_FPW_02.java deleted file mode 100755 index deb5fa01..00000000 --- a/src/main/java/edu/nps/moves/deadreckoning/DIS_DR_FPW_02.java +++ /dev/null @@ -1,42 +0,0 @@ -package edu.nps.moves.deadreckoning; - -/** - * - * (PRIMARY Methods group) Fixed, Rate of Position, World || Constant Linear motion - * - * @author Sheldon L. Snyder - * @deprecated Use {@link DeadReckoner} instead. - */ -@Deprecated -public class DIS_DR_FPW_02 extends DIS_DeadReckoning -{ - - /*************************************************************************** - * The driver for a DIS_DR_FPW_02 DR algorithm from the Runnable interface - *

- * Updates the position of this entity - *

- * P_new = P_original + LinVel * delta * t - *

- * called by thread.start() in the super class - *

- * Velocity is the speed that a entity is moving...linear constant speed - */ - public void run() - { - while(true) - { - try - { Thread.sleep(stall); }catch (Exception e){} - update(); - } - }//run()-------------------------------------------------------------------- - - void update() { - deltaCt++; - entityLocation_X += entityLinearVelocity_X * changeDelta; - entityLocation_Y += entityLinearVelocity_Y * changeDelta; - entityLocation_Z += entityLinearVelocity_Z * changeDelta; - - } -} diff --git a/src/main/java/edu/nps/moves/deadreckoning/DIS_DR_FVB_09.java b/src/main/java/edu/nps/moves/deadreckoning/DIS_DR_FVB_09.java deleted file mode 100755 index 96824965..00000000 --- a/src/main/java/edu/nps/moves/deadreckoning/DIS_DR_FVB_09.java +++ /dev/null @@ -1,58 +0,0 @@ -package edu.nps.moves.deadreckoning; - -import org.apache.commons.math3.geometry.euclidean.threed.Vector3D; - -/** - * (SECONDARY Methods Group) Fixed, rate of velocity, body coordinates || - * Linear Motion without Rotation - * - * @author Sheldon L. Snyder - * @deprecated Use {@link DeadReckoner} instead. - */ -@Deprecated -public class DIS_DR_FVB_09 extends DIS_DeadReckoning -{ - - /** - * The driver for a DIS_DR_FVB_09 DR algorithm from the Runnable interface - *

- * linear motion only without rotation - */ - public void run() - { - try - { - while(true) - { - Thread.sleep(stall); - update(); - }//while(true) - }// try - catch(Exception e) - { - System.out.println(e); - } - }//run()-------------------------------------------------------------------- - - void update() { - deltaCt++; - - Vector3D velVec = new Vector3D(entityLinearVelocity_X, entityLinearVelocity_Y, entityLinearVelocity_Z); - Vector3D accVec = new Vector3D(entityLinearAcceleration_X, entityLinearAcceleration_Y, entityLinearAcceleration_Z); - - // add the R1 and R2 - // Solve for new position - // For fixed (non-rotating), R1 = changeDelta * Identity and R2 = 0.5 * changeDelta^2 * Identity - Vector3D updated = initOrien.applyInverseTo(velVec.add(0.5 * changeDelta, accVec).scalarMultiply(changeDelta)); - - // Set the new position - entityLocation_X += updated.getX(); - entityLocation_Y += updated.getY(); - entityLocation_Z += updated.getZ(); - - entityLinearVelocity_X += entityLinearAcceleration_X * changeDelta; - entityLinearVelocity_Y += entityLinearAcceleration_Y * changeDelta; - entityLinearVelocity_Z += entityLinearAcceleration_Z * changeDelta; - } - -} diff --git a/src/main/java/edu/nps/moves/deadreckoning/DIS_DR_FVW_05.java b/src/main/java/edu/nps/moves/deadreckoning/DIS_DR_FVW_05.java deleted file mode 100755 index 3edc9689..00000000 --- a/src/main/java/edu/nps/moves/deadreckoning/DIS_DR_FVW_05.java +++ /dev/null @@ -1,39 +0,0 @@ -package edu.nps.moves.deadreckoning; - -/** - * (PRIMARY Methods group) Fixed, rate of velocity, world coordinates || Linear Motion with - * Acceleration but no rotation - * - * @author Sheldon L. Snyder - * @deprecated Use {@link DeadReckoner} instead. - */ -@Deprecated -public class DIS_DR_FVW_05 extends DIS_DeadReckoning -{ - /** - * The driver for a DIS_DR_FVW_05 DR algorithm from the Runnable interface - *

- * Linear motion with acceleration without rotation - */ - public void run() - { - while(true) - { - try - { Thread.sleep(stall); }catch (Exception e){} - update(); - } - }//run()-------------------------------------------------------------------- - - void update() { - deltaCt++; - - entityLocation_X += (entityLinearVelocity_X * changeDelta) + (.5 * entityLinearAcceleration_X * changeDelta * changeDelta); - entityLocation_Y += (entityLinearVelocity_Y * changeDelta) + (.5 * entityLinearAcceleration_Y * changeDelta * changeDelta); - entityLocation_Z += (entityLinearVelocity_Z * changeDelta) + (.5 * entityLinearAcceleration_Z * changeDelta * changeDelta); - - entityLinearVelocity_X += entityLinearAcceleration_X * changeDelta; - entityLinearVelocity_Y += entityLinearAcceleration_Y * changeDelta; - entityLinearVelocity_Z += entityLinearAcceleration_Z * changeDelta; - } -} diff --git a/src/main/java/edu/nps/moves/deadreckoning/DIS_DR_RPB_07.java b/src/main/java/edu/nps/moves/deadreckoning/DIS_DR_RPB_07.java deleted file mode 100755 index 19be4990..00000000 --- a/src/main/java/edu/nps/moves/deadreckoning/DIS_DR_RPB_07.java +++ /dev/null @@ -1,146 +0,0 @@ -package edu.nps.moves.deadreckoning; - -import org.apache.commons.math3.geometry.euclidean.threed.Rotation; -import org.apache.commons.math3.geometry.euclidean.threed.RotationConvention; -import org.apache.commons.math3.geometry.euclidean.threed.RotationOrder; -import org.apache.commons.math3.geometry.euclidean.threed.Vector3D; -import org.apache.commons.math3.linear.MatrixUtils; -import org.apache.commons.math3.linear.RealMatrix; -import org.apache.commons.math3.linear.RealVector; - -/** - * - * (SECONDARY Methods Group) Rotating, rate of position, body coordinates || - * Linear motion with Rotation - * - * @author Sheldon L. Snyder - * @deprecated Use {@link DeadReckoner} instead. - */ -@Deprecated -public class DIS_DR_RPB_07 extends DIS_DeadReckoning -{ - RealMatrix DR; - RealMatrix R1; - - /** - * The driver for a DIS_DR_RPB_07 DR algorithm from the Runnable interface - *

- * linear motion and rotation - */ - public void run() - { - try - { - while(true) - { - Thread.sleep(stall); - update(); - }//while(true) - }// try - catch(Exception e) - { - System.out.println(e); - } - }//run()-------------------------------------------------------------------- - - void update() { - deltaCt++; - - // solve for the new position - makeR1(); - - RealVector velVec = MatrixUtils.createRealVector(new double[] - {entityLinearVelocity_X, entityLinearVelocity_Y, entityLinearVelocity_Z}); - Rotation currOrien = new Rotation( - RotationOrder.ZYX, - RotationConvention.FRAME_TRANSFORM, - entityOrientation_psi, - entityOrientation_theta, - entityOrientation_phi); - Vector3D updated = currOrien.applyInverseTo(new Vector3D(R1.operate(velVec).toArray())); - - // set new positons - entityLocation_X += updated.getX(); - entityLocation_Y += updated.getY(); - entityLocation_Z += updated.getZ(); - - // make the rotation same as 1-4 rotations - makeThisDR(); - Rotation DRR = new Rotation(DR.getData(), 1e-15).applyTo(initOrien); - - double[] eulerAngles = DRR.getAngles(RotationOrder.ZYX, RotationConvention.FRAME_TRANSFORM); - // Update ESPDU Euler angle values - - entityOrientation_theta = (float) eulerAngles[1]; - //System.out.println(entityOrientation_theta); - entityOrientation_psi = (float) eulerAngles[0]; - entityOrientation_phi = (float) eulerAngles[2]; - - if(Double.isNaN(entityOrientation_psi)) - entityOrientation_psi = 0; - if(Double.isNaN(entityOrientation_theta)) - entityOrientation_theta = 0; - if(Double.isNaN(entityOrientation_phi)) - entityOrientation_phi = 0; - } - - - /*************************************************************************** - * Makes this iterations DR matrix - */ - private void makeThisDR() - { - if (wMag < MIN_ROTATION_RATE) { - DR = MatrixUtils.createRealIdentityMatrix(3); - return; - } - - double wDelta = wMag * changeDelta * deltaCt; - double cosWdelta = Math.cos(wDelta); - - double wwScale = (1 - cosWdelta) / wSq; - double identScalar = cosWdelta; - double skewScale = Math.sin(wDelta) / wMag; - - RealMatrix wwTmp = ww.scalarMultiply(wwScale); - RealMatrix identTmp = MatrixUtils.createRealIdentityMatrix(3).scalarMultiply(identScalar); - RealMatrix skwTmp = skewOmega.scalarMultiply(skewScale); - - DR = wwTmp.add(identTmp); - DR = DR.subtract(skwTmp); - } - - - /*************************************************************************** - * Makes the R1 matrix - * @return - the vector R1 - */ - private void makeR1() - { - if (wMag < MIN_ROTATION_RATE) { - R1 = MatrixUtils.createRealIdentityMatrix(3).scalarMultiply(changeDelta * deltaCt); - return; - } - - RealMatrix ident = MatrixUtils.createRealIdentityMatrix(3); - - // common factors - // double wDelta = wMag * changeDelta * deltaCt; - double wDelta = wMag * changeDelta; - - // matrix scalars - double wwScale = (wDelta-Math.sin(wDelta)) / (wSq * wMag); - double identScalar = Math.sin(wDelta) / wMag; - double skewScale = (1.0 - Math.cos(wDelta)) / wSq; - - // scaled matrixes - RealMatrix wwTmp = ww.scalarMultiply(wwScale); - RealMatrix identTmp = ident.scalarMultiply(identScalar); - RealMatrix skwTmp = skewOmega.scalarMultiply(skewScale); - - R1 = wwTmp.add(identTmp); - R1 = R1.add(skwTmp); - } - - -} diff --git a/src/main/java/edu/nps/moves/deadreckoning/DIS_DR_RPW_03.java b/src/main/java/edu/nps/moves/deadreckoning/DIS_DR_RPW_03.java deleted file mode 100755 index 6c678a42..00000000 --- a/src/main/java/edu/nps/moves/deadreckoning/DIS_DR_RPW_03.java +++ /dev/null @@ -1,93 +0,0 @@ -package edu.nps.moves.deadreckoning; - -import org.apache.commons.math3.geometry.euclidean.threed.Rotation; -import org.apache.commons.math3.geometry.euclidean.threed.RotationConvention; -import org.apache.commons.math3.geometry.euclidean.threed.RotationOrder; -import org.apache.commons.math3.linear.MatrixUtils; -import org.apache.commons.math3.linear.RealMatrix; -/** - * (PRIMARY Methods group) Rotating, rate of position, world coordinates || Constant Linear motion with - * Rotation - * - * @author Sheldon L. Snyder - * @deprecated Use {@link DeadReckoner} instead. - */ -@Deprecated -public class DIS_DR_RPW_03 extends DIS_DeadReckoning -{ - // put these in main abstract class...? - RealMatrix DR; - - /** - * The driver for a DIS_DR_RPW_03 DR algorithm from the Runnable interface - *

- * Rotation and linear motion - */ - public void run() - { - try - { - while(true) - { - Thread.sleep(stall); - update(); - }//while(true) - }// try - catch(Exception e) - { - System.out.println(e); - } - }//run()-------------------------------------------------------------------- - - void update() { - deltaCt++; - entityLocation_X += entityLinearVelocity_X * changeDelta; - entityLocation_Y += entityLinearVelocity_Y * changeDelta; - entityLocation_Z += entityLinearVelocity_Z * changeDelta; - - makeThisDR(); - - Rotation DRR = new Rotation(DR.getData(), 1e-15).applyTo(initOrien); - - double[] eulerAngles = DRR.getAngles(RotationOrder.ZYX, RotationConvention.FRAME_TRANSFORM); - // Update ESPDU Euler angle values - - entityOrientation_theta = (float) eulerAngles[1]; - //System.out.println(entityOrientation_theta); - entityOrientation_psi = (float) eulerAngles[0]; - entityOrientation_phi = (float) eulerAngles[2]; - - if(Double.isNaN(entityOrientation_psi)) - entityOrientation_psi = 0; - if(Double.isNaN(entityOrientation_theta)) - entityOrientation_theta = 0; - if(Double.isNaN(entityOrientation_phi)) - entityOrientation_phi = 0; - } - - /*************************************************************************** - * Makes this iterations DR matrix - */ - private void makeThisDR() - { - if (wMag < MIN_ROTATION_RATE) { - DR = MatrixUtils.createRealIdentityMatrix(3); - return; - } - - double wDelta = wMag * changeDelta * deltaCt; - double cosWdelta = Math.cos(wDelta); - - double wwScale = (1 - cosWdelta) / wSq; - double identScalar = cosWdelta; - double skewScale = Math.sin(wDelta) / wMag; - - RealMatrix wwTmp = ww.scalarMultiply(wwScale); - RealMatrix identTmp = MatrixUtils.createRealIdentityMatrix(3).scalarMultiply(identScalar); - RealMatrix skwTmp = skewOmega.scalarMultiply(skewScale); - - DR = wwTmp.add(identTmp); - DR = DR.subtract(skwTmp); - } - -} diff --git a/src/main/java/edu/nps/moves/deadreckoning/DIS_DR_RPW_03b.java b/src/main/java/edu/nps/moves/deadreckoning/DIS_DR_RPW_03b.java deleted file mode 100755 index f88674ca..00000000 --- a/src/main/java/edu/nps/moves/deadreckoning/DIS_DR_RPW_03b.java +++ /dev/null @@ -1,50 +0,0 @@ -package edu.nps.moves.deadreckoning; - -/** - * (PRIMARY Methods group) Rotating, rate of position, world coordinates || Constant Linear motion with - * Rotation (Alternative non-IEEE) - *

- * Doesn't follow the IEEE standard algorithms - *

- * Takes a more straightforward approach to rotation - * - * @author Sheldon L. Snyder - * - * @deprecated use {@link DIS_DR_RPW_03} instead - */ -@Deprecated -public class DIS_DR_RPW_03b extends DIS_DeadReckoning -{ - - /** - * The driver for a DIS_DR_RPW_03b DR algorithm from the Runnable interface - *

- * Rotation and linear motion - */ - public void run() - { - try - { - while(true) - { - deltaCt++; - Thread.sleep(stall); - update(); - }//while(true) - }// try - catch(Exception e) - { - System.out.println(e); - } - }//run()-------------------------------------------------------------------- - - void update() { - entityLocation_X += entityLinearVelocity_X * changeDelta; - entityLocation_Y += entityLinearVelocity_Y * changeDelta; - entityLocation_Z += entityLinearVelocity_Z * changeDelta; - - entityOrientation_psi = (entityOrientation_psi + entityAngularVelocity_X * changeDelta) % (2.0f * (float) Math.PI); - entityOrientation_theta = (entityOrientation_theta + entityAngularVelocity_Y * changeDelta) % (2.0f * (float) Math.PI); - entityOrientation_phi = (entityOrientation_phi + entityAngularVelocity_Z * changeDelta) % (2.0f * (float) Math.PI); - } -} diff --git a/src/main/java/edu/nps/moves/deadreckoning/DIS_DR_RVB_08.java b/src/main/java/edu/nps/moves/deadreckoning/DIS_DR_RVB_08.java deleted file mode 100755 index 172d3052..00000000 --- a/src/main/java/edu/nps/moves/deadreckoning/DIS_DR_RVB_08.java +++ /dev/null @@ -1,204 +0,0 @@ -package edu.nps.moves.deadreckoning; - -import org.apache.commons.math3.geometry.euclidean.threed.Rotation; -import org.apache.commons.math3.geometry.euclidean.threed.RotationConvention; -import org.apache.commons.math3.geometry.euclidean.threed.RotationOrder; -import org.apache.commons.math3.geometry.euclidean.threed.Vector3D; -import org.apache.commons.math3.linear.MatrixUtils; -import org.apache.commons.math3.linear.RealMatrix; -import org.apache.commons.math3.linear.RealVector; - -/** - * - * (SECONDARY Methods Group) Rotating, rate of velocity, body coordinates || - * Linear motion with Rotation - * - * @author Sheldon L. Snyder - * @deprecated Use {@link DeadReckoner} instead. - */ -@Deprecated -public class DIS_DR_RVB_08 extends DIS_DeadReckoning -{ - // put these in main abstract class...? - RealMatrix DR; - RealMatrix R1; - RealMatrix R2; - - /** - * The driver for a DIS_DR_RVB_08 DR algorithm from the Runnable interface - *

- * linear motion and rotation - */ - public void run() - { - try - { - while(true) - { - Thread.sleep(stall); - update(); - }//while(true) - }// try - catch(Exception e) - { - System.out.println(e); - } - }//run()-------------------------------------------------------------------- - - void update() { - deltaCt++; - - RealVector velVec = MatrixUtils.createRealVector(new double[] - {entityLinearVelocity_X, entityLinearVelocity_Y, entityLinearVelocity_Z}); - RealVector accVec = MatrixUtils.createRealVector(new double[] - {entityLinearAcceleration_X, entityLinearAcceleration_Y, entityLinearAcceleration_Z}); - - Rotation currOrien = new Rotation( - RotationOrder.ZYX, - RotationConvention.FRAME_TRANSFORM, - entityOrientation_psi, - entityOrientation_theta, - entityOrientation_phi); - - // make the R1 and R2 matrices - makeR1(); - makeR2(); - - RealVector updated1 = R1.operate(velVec); - RealVector updated2 = R2.operate(accVec); - - // add the R1 and R2 - // Solve for new position - Vector3D updated = currOrien.applyInverseTo(new Vector3D(updated1.add(updated2).toArray())); - - // Set the new position - entityLocation_X += updated.getX(); - entityLocation_Y += updated.getY(); - entityLocation_Z += updated.getZ(); - - entityLinearVelocity_X += entityLinearAcceleration_X * changeDelta; - entityLinearVelocity_Y += entityLinearAcceleration_Y * changeDelta; - entityLinearVelocity_Z += entityLinearAcceleration_Z * changeDelta; - - // make the rotation information updates...same as 1-4 - makeThisDR(); - Rotation DRR = new Rotation(DR.getData(), 1e-15).applyTo(initOrien); - double[] eulerAngles = DRR.getAngles(RotationOrder.ZYX, RotationConvention.FRAME_TRANSFORM); - - entityOrientation_theta = (float) eulerAngles[1]; - //System.out.println(entityOrientation_theta); - entityOrientation_psi = (float) eulerAngles[0]; - entityOrientation_phi = (float) eulerAngles[2]; - - if(Double.isNaN(entityOrientation_psi)) - entityOrientation_psi = 0; - if(Double.isNaN(entityOrientation_theta)) - entityOrientation_theta = 0; - if(Double.isNaN(entityOrientation_phi)) - entityOrientation_phi = 0; - } - - /*************************************************************************** - * Makes this iterations DR matrix - */ - private void makeThisDR() - { - if (wMag < MIN_ROTATION_RATE) { - DR = MatrixUtils.createRealIdentityMatrix(3); - return; - } - - RealMatrix ident = MatrixUtils.createRealIdentityMatrix(3); - double wDelta = wMag * changeDelta * deltaCt; - double cosWdelta = Math.cos(wDelta); - - double wwScale = (1 - cosWdelta) / wSq; - double identScalar = cosWdelta; - double skewScale = Math.sin(wDelta) / wMag; - - RealMatrix wwTmp = ww.scalarMultiply(wwScale); - RealMatrix identTmp = ident.scalarMultiply(identScalar); - RealMatrix skwTmp = skewOmega.scalarMultiply(skewScale); - - DR = wwTmp.add(identTmp); - DR = DR.subtract(skwTmp); - } - - - /*************************************************************************** - * Makes the R2 vector - * @return - the r2 vector - */ - private void makeR2() - { - if (wMag < MIN_ROTATION_RATE) { - R2 = MatrixUtils.createRealIdentityMatrix(3).scalarMultiply(changeDelta * deltaCt * changeDelta * deltaCt / 2.0); - return; - } - - RealMatrix ident = MatrixUtils.createRealIdentityMatrix(3); - - // common factors - // double wDelta = wMag * changeDelta * deltaCt; - double wDelta = wMag * changeDelta; - - // matrix scalars - // double wwScale = .5*wSq*changeDelta * deltaCt*changeDelta * deltaCt; - double wwScale = .5 * wSq * changeDelta * changeDelta; - wwScale -= Math.cos(wDelta); - wwScale -= wDelta*Math.sin(wDelta); - wwScale++; - wwScale /= wSq * wSq; - - double identScalar = Math.cos(wDelta) + wDelta*Math.sin(wDelta) - 1; - identScalar /= wSq; - - double skewScale = Math.sin(wDelta) - wDelta*Math.cos(wDelta); - skewScale /= wSq * wMag; - - // scaled matrixes - RealMatrix wwTmp = ww.scalarMultiply(wwScale); - RealMatrix identTmp = ident.scalarMultiply(identScalar); - RealMatrix skwTmp = skewOmega.scalarMultiply(skewScale); - - R2 = wwTmp.add(identTmp); - R2 = R2.add(skwTmp); - } - - - - /*************************************************************************** - * Makes the R1 matrix - * @return - the vector R1 - */ - private void makeR1() - { - if (wMag < MIN_ROTATION_RATE) { - R1 = MatrixUtils.createRealIdentityMatrix(3).scalarMultiply(changeDelta * deltaCt); - return; - } - - RealMatrix ident = MatrixUtils.createRealIdentityMatrix(3); - - // common factors - // double wDelta = wMag * changeDelta * deltaCt; - double wDelta = wMag * changeDelta; - - // matrix scalars - double wwScale = (wDelta-Math.sin(wDelta)) / (wSq * wMag); - double identScalar = Math.sin(wDelta) / wMag; - // NOTE: corrected from the SISO std, which contained an error. See - // http://discussions.sisostds.org/default.asp?action=9&read=44981&fid=32 - // Thanks to Ian Gilles for the correction. - double skewScale = (1 - Math.cos(wDelta)) / wSq; - - // scaled matrixes - RealMatrix wwTmp = ww.scalarMultiply(wwScale); - RealMatrix identTmp = ident.scalarMultiply(identScalar); - RealMatrix skwTmp = skewOmega.scalarMultiply(skewScale); - - R1 = wwTmp.add(identTmp); - R1 = R1.add(skwTmp); - } - -} diff --git a/src/main/java/edu/nps/moves/deadreckoning/DIS_DR_RVW_04.java b/src/main/java/edu/nps/moves/deadreckoning/DIS_DR_RVW_04.java deleted file mode 100755 index be6357fd..00000000 --- a/src/main/java/edu/nps/moves/deadreckoning/DIS_DR_RVW_04.java +++ /dev/null @@ -1,96 +0,0 @@ -package edu.nps.moves.deadreckoning; - -import org.apache.commons.math3.geometry.euclidean.threed.Rotation; -import org.apache.commons.math3.geometry.euclidean.threed.RotationConvention; -import org.apache.commons.math3.geometry.euclidean.threed.RotationOrder; -import org.apache.commons.math3.linear.MatrixUtils; -import org.apache.commons.math3.linear.RealMatrix; -/** - * (PRIMARY Methods group) Rotating, rate of velocity, world coordinates || Linear Motion with - * Acceleration and rotation - * - * @author Sheldon L. Snyder - * @deprecated Use {@link DeadReckoner} instead. - */ -@Deprecated -public class DIS_DR_RVW_04 extends DIS_DeadReckoning -{ - // put these in main abstract class...? - RealMatrix DR; - - /** - * The driver for a DIS_DR_RVW_04 DR algorithm from the Runnable interface - *

- * Rotation and linear motion with acceleration - */ - public void run() - { - try - { - while(true) - { - Thread.sleep(stall); - update(); - }//while(true) - }// try - catch(Exception e) - { - System.out.println(e); - } - }//run()-------------------------------------------------------------------- - - void update() { - deltaCt++; - entityLocation_X += (entityLinearVelocity_X * changeDelta) + (.5 * entityLinearAcceleration_X * changeDelta * changeDelta); - entityLocation_Y += (entityLinearVelocity_Y * changeDelta) + (.5 * entityLinearAcceleration_Y * changeDelta * changeDelta); - entityLocation_Z += (entityLinearVelocity_Z * changeDelta) + (.5 * entityLinearAcceleration_Z * changeDelta * changeDelta); - - entityLinearVelocity_X += entityLinearAcceleration_X * changeDelta; - entityLinearVelocity_Y += entityLinearAcceleration_Y * changeDelta; - entityLinearVelocity_Z += entityLinearAcceleration_Z * changeDelta; - - makeThisDR(); - - Rotation DRR = new Rotation(DR.getData(), 1e-15).applyTo(initOrien); - - double[] eulerAngles = DRR.getAngles(RotationOrder.ZYX, RotationConvention.FRAME_TRANSFORM); - - entityOrientation_theta = (float) eulerAngles[1]; - //System.out.println(entityOrientation_theta); - entityOrientation_psi = (float) eulerAngles[0]; - entityOrientation_phi = (float) eulerAngles[2]; - - if(Double.isNaN(entityOrientation_psi)) - entityOrientation_psi = 0; - if(Double.isNaN(entityOrientation_theta)) - entityOrientation_theta = 0; - if(Double.isNaN(entityOrientation_phi)) - entityOrientation_phi = 0; - } - - /*************************************************************************** - * Makes this iterations DR matrix - */ - private void makeThisDR() - { - if (wMag < MIN_ROTATION_RATE) { - DR = MatrixUtils.createRealIdentityMatrix(3); - return; - } - - double wDelta = wMag * changeDelta * deltaCt; - double cosWdelta = Math.cos(wDelta); - - double wwScale = (1 - cosWdelta) / wSq; - double identScalar = cosWdelta; - double skewScale = Math.sin(wDelta) / wMag; - - RealMatrix wwTmp = ww.scalarMultiply(wwScale); - RealMatrix identTmp = MatrixUtils.createRealIdentityMatrix(3).scalarMultiply(identScalar); - RealMatrix skwTmp = skewOmega.scalarMultiply(skewScale); - - DR = wwTmp.add(identTmp); - DR = DR.subtract(skwTmp); - } - -} diff --git a/src/main/java/edu/nps/moves/deadreckoning/DIS_DR_RVW_04b.java b/src/main/java/edu/nps/moves/deadreckoning/DIS_DR_RVW_04b.java deleted file mode 100755 index bcc5b845..00000000 --- a/src/main/java/edu/nps/moves/deadreckoning/DIS_DR_RVW_04b.java +++ /dev/null @@ -1,46 +0,0 @@ -package edu.nps.moves.deadreckoning; - -/** - * (PRIMARY Methods group) Rotating, rate of velocity, world coordinates || Linear Motion with - * Acceleration and rotation (Alterntive non-IEEE) - * - * @author Sheldon L. Snyder - * - * @deprecated use {@link DIS_DR_RVW_04} instead - */ -@Deprecated -public class DIS_DR_RVW_04b extends DIS_DeadReckoning -{ - - /** - * The driver for a DIS_DR_RVW_04 DR algorithm from the Runnable interface - *

- * Rotation and linear motion with acceleration - */ - public void run() - { - try - { - while(true) - { - deltaCt++; - Thread.sleep(stall); - update(); - }//while(true) - }// try - catch(Exception e) - { - System.out.println(e); - } - }//run()-------------------------------------------------------------------- - - void update() { - entityLocation_X += (entityLinearVelocity_X * changeDelta) + (.5 * entityLinearAcceleration_X * changeDelta * changeDelta); - entityLocation_Y += (entityLinearVelocity_Y * changeDelta) + (.5 * entityLinearAcceleration_Y * changeDelta * changeDelta); - entityLocation_Z += (entityLinearVelocity_Z * changeDelta) + (.5 * entityLinearAcceleration_Z * changeDelta * changeDelta); - - entityOrientation_psi = (entityOrientation_psi + entityAngularVelocity_X * changeDelta) % (2.0f * (float) Math.PI); - entityOrientation_theta = (entityOrientation_theta + entityAngularVelocity_Y * changeDelta) % (2.0f * (float) Math.PI); - entityOrientation_phi = (entityOrientation_phi + entityAngularVelocity_Z * changeDelta) % (2.0f * (float) Math.PI); - } -} diff --git a/src/main/java/edu/nps/moves/deadreckoning/DIS_DR_Static_01.java b/src/main/java/edu/nps/moves/deadreckoning/DIS_DR_Static_01.java deleted file mode 100755 index 6e88e2ff..00000000 --- a/src/main/java/edu/nps/moves/deadreckoning/DIS_DR_Static_01.java +++ /dev/null @@ -1,21 +0,0 @@ -package edu.nps.moves.deadreckoning; - -/** - * (PRIMARY Methods group) Static DR, no movement || No motion - * @author Sheldon L. Snyder - * @deprecated Use {@link DeadReckoner} instead. - */ -@Deprecated -public class DIS_DR_Static_01 extends DIS_DeadReckoning -{ - /** - * The driver for a DIS_DR_Static_01 DR algorithm from the Runnable interface - *

- * No motion or rotation - */ - public void run() { } - - void update() { - deltaCt++; - } -} diff --git a/src/main/java/edu/nps/moves/deadreckoning/DIS_DeadReckoning.java b/src/main/java/edu/nps/moves/deadreckoning/DIS_DeadReckoning.java deleted file mode 100755 index a0953a16..00000000 --- a/src/main/java/edu/nps/moves/deadreckoning/DIS_DeadReckoning.java +++ /dev/null @@ -1,515 +0,0 @@ -package edu.nps.moves.deadreckoning; - -import org.apache.commons.math3.geometry.euclidean.threed.Rotation; -import org.apache.commons.math3.geometry.euclidean.threed.RotationConvention; -import org.apache.commons.math3.geometry.euclidean.threed.RotationOrder; -import org.apache.commons.math3.linear.MatrixUtils; -import org.apache.commons.math3.linear.RealMatrix; - -/** - * The root super class for all DIS Dead-Reckoning algorithms. - * Based on the algorithms from the - * IEEE 1278_1-1995_DIS standards found in Annex B. - *

- * Creates an abstract instance of a Dead Reckoning (DR) algorithm, defined - * by the concrete Dead Reckoning algorithm on the right hand side. - *

- * At each PDU update received, call the set function to update the DR - * algorithm with the most accurate and updated information. Expected to receive - * a new update approximately every 5 seconds or so. Each PDU is essentially a - * restart or reset of the DR state. - *

- * The DR works off the last good state (origin) and extrapolates out from that - * point based on the velocity and acceleration parameters from the set - * function. - *

- * The DR algorithm updates 30 times a second. The instantiating entity - * can get updated DR states at its leisure up to 30 times a second by calling - * the get function, which returns an array of 6 doubles 3 x location and - * 3 x orientation. With these 6 parameters the entity can redraw itself in an - * updated location and orientation based on its projected path. - - * An Example:
- *

-import DIS.DeadReckoning.*;
-
-public class runTest 
-{
-    public static void main(String s[])
-    {
-        // create a DeadReconing Entity
-        DIS_DeadReckoning dr = new DIS_DR_FPW_02();
-
-        // make the arrays of location and other parameters
-        //                loc      orien    lin V    Accel    Ang V
-        double[] locOr = {2,3,4,   5,6,1,   1,2,1,   0,0,0,   0,0,0};
-
-        // set the parameters
-        dr.setNewAll(locOr);
-
-        // Print out the current state
-        System.out.println(dr.toString());
-        System.out.println();
-
-        try
-        {
-            // wait 1 second
-            Thread.sleep(1000);
-
-            // request an update from the DR algorithm
-            // should be original + 1 full value of other parameters
-            // new position should be (3, 5, 5)
-            double[] update = dr.getUpdatedPositionOrientation();
-
-            // print the update to the screen
-            System.out.println(dr.toString());        
-        }
-        catch(Exception e)
-        {
-            System.out.println("Unknow Error...?\n    " + e);
-        }
-
-        // terminate with exit to get out of the inf while loop
-        System.exit(0);
-    }
-}
-
-Resulting Output:
-Current State of this Entity:
-    Entity Location = (2.0, 3.0, 4.0)
-    Entity Orientation = (5.0, 6.0, 1.0)
-    Entity Linear Velocity = (1.0, 2.0, 1.0)
-    Entity Linear Acceleration = (0.0, 0.0, 0.0)
-    Entity Angular Velocity = (0.0, 0.0, 0.0)
-    Delta between updates = 0.033333335
-
-Current State of this Entity:
-    Entity Location = (3.000000052154064, 5.000000104308128, 5.000000052154064)
-    Entity Orientation = (5.0, 6.0, 1.0)
-    Entity Linear Velocity = (1.0, 2.0, 1.0)
-    Entity Linear Acceleration = (0.0, 0.0, 0.0)
-    Entity Angular Velocity = (0.0, 0.0, 0.0)
-    Delta between updates = 0.033333335
-
-
-
- * - * @author Sheldon L. Snyder - * @deprecated Use {@link DeadReckoner} instead. - */ -@Deprecated -public abstract class DIS_DeadReckoning implements Runnable -{ - /** - * The entity's X coordinate location with double precision 64bit - */ - protected double entityLocation_X; - /** - * The entity's Y coordinate location with double precision 64bit - */ - protected double entityLocation_Y; - /** - * The entity's Z coordinate location with double precision 64bit - */ - protected double entityLocation_Z; - - /** - * The X orientation of the entity with 32bit float - */ - protected float entityOrientation_psi; - /** - * The Y orientation of the entity with 32bit float - */ - protected float entityOrientation_theta; - /** - * The Z orientation of the entity with 32bit float - */ - protected float entityOrientation_phi; - - /** - * The X linear velocity 32bit float - */ - protected float entityLinearVelocity_X = 0; - /** - * The Y linear velocity 32bit float - */ - protected float entityLinearVelocity_Y = 0; - /** - * The Z linear velocity 32bit float - */ - protected float entityLinearVelocity_Z = 0; - - /** - * The linear X acceleration 32bit float - */ - protected float entityLinearAcceleration_X = 0; - /** - * The linear Y acceleration 32bit float - */ - protected float entityLinearAcceleration_Y = 0; - /** - * The linear Z acceleration 32bit float - */ - protected float entityLinearAcceleration_Z = 0; - - /** - * The X angular velocity 32bit float - */ - protected float entityAngularVelocity_X = 0; - /** - * The Y angular velocity 32bit float - */ - protected float entityAngularVelocity_Y = 0; - /** - * The Z angular velocity 32bit float - */ - protected float entityAngularVelocity_Z = 0; - - /** - * how may times per second to update this entity's position - */ - protected float fps = 30; - - /** - * How far to change the location/orientation per update - */ - protected float changeDelta = 1f/fps; - /** - * How many updates have occured ... only used for testing - *

- * Reset to 0 with each call to setAll() - */ - protected int deltaCt = 0;// how many updates have been called - /** - * How long to wait between updates - *

- * the delta between calls...how fast an entity will be updated - * - * - Assumed a desired rate of 30 fps - * - Given from the standard that all parameters are in meters/s - * - To move 1 meter/second with 30 increments = 1/30 Delta between updates - * - delay in milliseconds is 1/30 * 1000 || 1000 / 30 - *

- * Note from Java Doc for JDK:
- * Causes the currently executing thread to sleep (temporarily cease - * execution) for the specified number of milliseconds, subject to the - * precision and accuracy of system timers and schedulers. The thread does - * not lose ownership of any monitors. - */ - protected long stall = (long)(1000/fps); - - /** - * Thread for the DR algorithm update timing (1/30 second) - */ - protected Thread aThread; - - /** - * the initial orientation, constant between delta T - * Only changes when a setNewAll is called - */ - Rotation initOrien; - - /** - * SKEW matrix, constant between delta T - * Only changes when a setNewAll is called - */ - RealMatrix skewOmega; - - /** - * Angular velocity matrix, constant between delta T - * Only changes when a setNewAll is called - */ - RealMatrix ww; - - /** - * Angular velocity magnitude, constant between delta T - * Only changes when a setNewAll is called - */ - double wMag; - /** - * Magnitude of angular velocity squared - */ - double wSq; - - /** - * DIS timestamp - */ - private long initTimestamp; - - static double MIN_ROTATION_RATE = 0.2 * Math.PI / 180; // minimum significant rate = 1deg/5sec - - /*************************************************************************** - * Constructor for all DR algorithms... - *

- * Each subclass DR algorithm has a no arguments constructor, but all it - * does is call the super, i.e. this constructor, which establishes the - * Thread - */ - public DIS_DeadReckoning() - { - aThread = new Thread(this); - aThread.start(); - }//DIS_DeadReckoning()------------------------------------------------------ - - /*************************************************************************** - * Gets the revised position and orientation of this entity - *

- * Applies the required DR formula to the initial position and orientation - * of this entity and returns the updated location and position. - *

- * This function does not actually perform the computations, it only returns - * the current state of the entity. The entity state is updated by the - * specified DR algorithm within the DR class behind the scenes. Updates are - * created every 1/30 seconds. - * - * NOTE: The concrete classes implementing the various DR algorithms are not - * (currently) thread safe. As a result, the getter functions may return a - * result while the behind the scenes update is still in progress, - * i.e. this getter functions may sample an inconsistent state in which - * some fields have been updated to the current time sample while other - * fields still pertain to the previous time sample. - * - * Assume a desired rate of 30 fps - * All parameters are in meters/s - * to move 1 meter/second with 30 increments = 1/30 Delta between updates - * - * Only returns an array of location and orientation because that - * is all that is needed to update the location of the entity. All other - * DR inputs are parameters for solving the location and orientation and so - * are not returned, only set. - * - * Order of the returned array elements - * - * - entityLocation_X - * - entityLocation_Y - * - entityLocation_Z - * - entityOrientation_psi - * - entityOrientation_theta - * - entityOrientation_phi - * - * @return - 6 doubles of location and orientation - */ - public double[] getUpdatedPositionOrientation() - { - double[] newLoc = {entityLocation_X, entityLocation_Y, entityLocation_Z, - entityOrientation_psi, entityOrientation_theta, entityOrientation_phi}; - return newLoc; - }//getUpdatedPositionOrientation()------------------------------------------ - - /** - * @return e doubles of velocity - */ - public double[] getUpdatedVelocity() - { - return new double[] { entityLinearVelocity_X, entityLinearVelocity_Y, entityLinearVelocity_Z }; - }//getUpdatedVelocity()------------------------------------------ - - public long getUpdatedTimestamp() { - long dtimeStamp = 2 * (long) (deltaCt * changeDelta * 2147483648. / 3600.); - return initTimestamp + dtimeStamp; - } - - /*************************************************************************** - * Sets the refresh rate for the scene. - *

- * Default is 30 but can be changed through this function call - * - * @param frames - the number of updates per second to make - */ - public void setFPS(int frames) - { - fps = frames; - changeDelta = 1/fps; - }//setFPS(int frames)------------------------------------------------------- - - - - /*************************************************************************** - * Set the parameters for this entity's DR function based on the most - * recent PDU. - *

- * This is called by the entity any time the entity receives an updated - * ESPDU for this entity. - *

- * This can be the first and initialization call or update. - *

- * The following (triples) are set with each call: - * - * - Entity Location 64bit - * - Entity Orientation 32bit - * - Entity Linear Velocity 32bit - * - Entity Linear Acceleration 32bit - * - Entity Angular Velocity 32bit - - *

- * entityLocation_X = allDis[0];
- * entityLocation_Y = allDis[1];
- * entityLocation_Z = allDis[2];
- *

- * entityOrientation_psi = (float)allDis[3];
- * entityOrientation_theta = (float)allDis[4];
- * entityOrientation_phi = (float)allDis[5];
- *

- * entityLinearVelocity_X = (float)allDis[6];
- * entityLinearVelocity_Y = (float)allDis[7];
- * entityLinearVelocity_Z = (float)allDis[8];
- *

- * entityLinearAcceleration_X = (float)allDis[9];
- * entityLinearAcceleration_Y = (float)allDis[10];
- * entityLinearAcceleration_Z = (float)allDis[11];
- *

- * entityAngularVelocity_X = (float)allDis[12];
- * entityAngularVelocity_Y = (float)allDis[13];
- * entityAngularVelocity_Z = (float)allDis[14];
- *

- * DR fields from a PDU update or initial - * - * @param allDis - 15 double precisions representing the above in order of the above - */ - public void setNewAll(double[] allDis) - { - entityLocation_X = allDis[0]; - entityLocation_Y = allDis[1]; - entityLocation_Z = allDis[2]; - - entityOrientation_psi = (float)allDis[3]; - entityOrientation_theta = (float)allDis[4]; - entityOrientation_phi = (float)allDis[5]; - - entityLinearVelocity_X = (float)allDis[6]; - entityLinearVelocity_Y = (float)allDis[7]; - entityLinearVelocity_Z = (float)allDis[8]; - - entityLinearAcceleration_X = (float)allDis[9]; - entityLinearAcceleration_Y = (float)allDis[10]; - entityLinearAcceleration_Z = (float)allDis[11]; - - entityAngularVelocity_X = (float)allDis[12]; - entityAngularVelocity_Y = (float)allDis[13]; - entityAngularVelocity_Z = (float)allDis[14]; - - // solve for magnitude - wSq = entityAngularVelocity_X * entityAngularVelocity_X + - entityAngularVelocity_Y * entityAngularVelocity_Y + - entityAngularVelocity_Z * entityAngularVelocity_Z; - wMag = Math.sqrt(wSq); - - //System.out.println("wMag print"); - //System.out.println(wMag); - //System.out.println(); - - // build the skew matrix - setOmega(); - //System.out.println("skewOmega print"); - //skewOmega.print(); - //System.out.println(); - - // build the angular velocity matrix - setWW(); - //System.out.println("ww print"); - //ww.print(); - //System.out.println(); - - // reset delta count given this new update - setInitOrient(); - //System.out.println("init Orient print"); - //initOrien.print(); - //System.out.println(); - - deltaCt = 0; - }//setNewAll(double[] allDis)----------------------------------------------- - - /** - * Set the timestamp - * @param initTimestamp - */ - public void setInitTimestamp(long initTimestamp) { - this.initTimestamp = initTimestamp; - } - - /*************************************************************************** - * With each setNewAll() makes the new initial orientation matrix given the - * new parameters - */ - private void setInitOrient() - { - initOrien = new Rotation( - RotationOrder.ZYX, - RotationConvention.FRAME_TRANSFORM, - entityOrientation_psi, - entityOrientation_theta, - entityOrientation_phi); - } - - - - /*************************************************************************** - * With each setNewAll() makes the new angular velocity matrix given the - * new parameters - */ - private void setWW() - { - ww = MatrixUtils.createRealMatrix(3, 3); - ww.setEntry(0, 0, entityAngularVelocity_X * entityAngularVelocity_X); - ww.setEntry(0, 1, entityAngularVelocity_X * entityAngularVelocity_Y); - ww.setEntry(0, 2, entityAngularVelocity_X * entityAngularVelocity_Z); - ww.setEntry(1, 0, entityAngularVelocity_Y * entityAngularVelocity_X); - ww.setEntry(1, 1, entityAngularVelocity_Y * entityAngularVelocity_Y); - ww.setEntry(1, 2, entityAngularVelocity_Y * entityAngularVelocity_Z); - ww.setEntry(2, 0, entityAngularVelocity_Z * entityAngularVelocity_X); - ww.setEntry(2, 1, entityAngularVelocity_Z * entityAngularVelocity_Y); - ww.setEntry(2, 2, entityAngularVelocity_Z * entityAngularVelocity_Z); - } - - - - /*************************************************************************** - * With each setNewAll() makes the new skew matrix given the - * new parameters - */ - private void setOmega() - { - skewOmega = MatrixUtils.createRealMatrix(3, 3); - skewOmega.setEntry(0, 0, 0); - skewOmega.setEntry(1, 1, 0); - skewOmega.setEntry(2, 2, 0); - skewOmega.setEntry(1, 0, entityAngularVelocity_Z); - skewOmega.setEntry(2, 0, -entityAngularVelocity_Y); - skewOmega.setEntry(2, 1, entityAngularVelocity_X); - skewOmega.setEntry(0, 1, -entityAngularVelocity_Z); - skewOmega.setEntry(0, 2, entityAngularVelocity_Y); - skewOmega.setEntry(1, 2, -entityAngularVelocity_X); - } - - - - /*************************************************************************** - * Pretty print the current state of this Dead Reckoning object - *

- * Updates are not included in this call, this is only the state. - * - * @return - String of pretty print of this DR entity - */ - public String toString() - { - String buff = "Current State of this Entity:\n" + - " Entity Location = (" + entityLocation_X + ", " + - entityLocation_Y + ", " + entityLocation_Z + ")\n" + - - " Entity Orientation = (" + entityOrientation_psi + ", " + - entityOrientation_theta + ", " + entityOrientation_phi + ")\n" + - - " Entity Linear Velocity = (" + entityLinearVelocity_X + ", " + - entityLinearVelocity_Y + ", " + entityLinearVelocity_Z + ")\n" + - - " Entity Linear Acceleration = (" + entityLinearAcceleration_X + ", " + - entityLinearAcceleration_Y + ", " + entityLinearAcceleration_Z + ")\n" + - - " Entity Angular Velocity = (" + entityAngularVelocity_X + ", " + - entityAngularVelocity_Y + ", " + entityAngularVelocity_Z + ")\n" + - - " Delta between updates = " + changeDelta; - - return buff; - }// toString()-------------------------------------------------------------- -}// DIS_DeadReckoning----------------------------------------------------------- diff --git a/src/main/java/edu/nps/moves/deadreckoning/DeadReckoner.java b/src/main/java/edu/nps/moves/deadreckoning/DeadReckoner.java index c75d90ee..0460b302 100644 --- a/src/main/java/edu/nps/moves/deadreckoning/DeadReckoner.java +++ b/src/main/java/edu/nps/moves/deadreckoning/DeadReckoner.java @@ -18,12 +18,7 @@ * Tenth Workshop on Standards for the Interoperability of Defense Simulations, Orlando, FL, pp. 431-462, Mar. 1994. * Available at http://www.sisostds.org/DigitalLibrary.aspx?EntryId=31599 * - * This provides an alternate to the existing classes - * (DIS_DeadReckoning, DIS_DR_Static_01, DIS_DR_FPW_02, etc.) - * in the Java Open-DIS library. - * * @author camejia - * */ public class DeadReckoner { diff --git a/src/main/java/edu/nps/moves/dis/FastEntityStatePdu.java b/src/main/java/edu/nps/moves/dis/FastEntityStatePdu.java deleted file mode 100644 index 116bd99d..00000000 --- a/src/main/java/edu/nps/moves/dis/FastEntityStatePdu.java +++ /dev/null @@ -1,1123 +0,0 @@ -package edu.nps.moves.dis; - -import java.util.*; -import java.io.*; - -/** - * Section 5.3.3.1. Represents the postion and state of one entity in the world. - * This is identical in function to entity state pdu, but generates less garbage - * to collect in the Java world. COMPLETE - * - * Copyright (c) 2008-2016, MOVES Institute, Naval Postgraduate School. All - * rights reserved. This work is licensed under the BSD open source license, - * available at https://www.movesinstitute.org/licenses/bsd.html - * - * @author DMcG - */ -@Deprecated -public class FastEntityStatePdu extends EntityInformationFamilyPdu implements Serializable { - - /** - * The site ID - */ - protected int site; - - /** - * The application ID - */ - protected int application; - - /** - * the entity ID - */ - protected int entity; - - /** - * what force this entity is affiliated with, eg red, blue, neutral, etc - */ - protected short forceId; - - /** - * How many articulation parameters are in the variable length list - */ - protected byte numberOfArticulationParameters; - - /** - * Kind of entity - */ - protected short entityKind; - - /** - * Domain of entity (air, surface, subsurface, space, etc) - */ - protected short domain; - - /** - * country to which the design of the entity is attributed - */ - protected int country; - - /** - * category of entity - */ - protected short category; - - /** - * subcategory of entity - */ - protected short subcategory; - - /** - * specific info based on subcategory field. Name changed from specific - * because that is a reserved word in SQL. - */ - protected short specif; - - protected short extra; - - /** - * Kind of entity - */ - protected short altEntityKind; - - /** - * Domain of entity (air, surface, subsurface, space, etc) - */ - protected short altDomain; - - /** - * country to which the design of the entity is attributed - */ - protected int altCountry; - - /** - * category of entity - */ - protected short altCategory; - - /** - * subcategory of entity - */ - protected short altSubcategory; - - /** - * specific info based on subcategory field - */ - protected short altSpecific; - - protected short altExtra; - - /** - * X velo - */ - protected float xVelocity; - - /** - * y Value - */ - protected float yVelocity; - - /** - * Z value - */ - protected float zVelocity; - - /** - * X value - */ - protected double xLocation; - - /** - * y Value - */ - protected double yLocation; - - /** - * Z value - */ - protected double zLocation; - - protected float psi; - - protected float theta; - - protected float phi; - - /** - * a series of bit flags that are used to help draw the entity, such as - * smoking, on fire, etc. - */ - protected int entityAppearance; - - /** - * enumeration of what dead reckoning algorighm to use - */ - protected short deadReckoningAlgorithm; - - /** - * other parameters to use in the dead reckoning algorithm - */ - protected byte[] otherParameters = new byte[15]; - - /** - * X value - */ - protected float xAcceleration; - - /** - * y Value - */ - protected float yAcceleration; - - /** - * Z value - */ - protected float zAcceleration; - - /** - * X value - */ - protected float xAngularVelocity; - - /** - * y Value - */ - protected float yAngularVelocity; - - /** - * Z value - */ - protected float zAngularVelocity; - - /** - * characters that can be used for debugging, or to draw unique strings on - * the side of entities in the world - */ - protected byte[] marking = new byte[12]; - - /** - * a series of bit flags - */ - protected int capabilities; - - /** - * variable length list of articulation parameters - */ - protected List< ArticulationParameter> articulationParameters = new ArrayList< ArticulationParameter>(); - - /** - * Constructor - */ - public FastEntityStatePdu() { - setPduType((short) 1); - } - - public int getMarshalledSize() { - int marshalSize = 0; - - marshalSize = super.getMarshalledSize(); - marshalSize = marshalSize + 2; // site - marshalSize = marshalSize + 2; // application - marshalSize = marshalSize + 2; // entity - marshalSize = marshalSize + 1; // forceId - marshalSize = marshalSize + 1; // numberOfArticulationParameters - marshalSize = marshalSize + 1; // entityKind - marshalSize = marshalSize + 1; // domain - marshalSize = marshalSize + 2; // country - marshalSize = marshalSize + 1; // category - marshalSize = marshalSize + 1; // subcategory - marshalSize = marshalSize + 1; // specif - marshalSize = marshalSize + 1; // extra - marshalSize = marshalSize + 1; // altEntityKind - marshalSize = marshalSize + 1; // altDomain - marshalSize = marshalSize + 2; // altCountry - marshalSize = marshalSize + 1; // altCategory - marshalSize = marshalSize + 1; // altSubcategory - marshalSize = marshalSize + 1; // altSpecific - marshalSize = marshalSize + 1; // altExtra - marshalSize = marshalSize + 4; // xVelocity - marshalSize = marshalSize + 4; // yVelocity - marshalSize = marshalSize + 4; // zVelocity - marshalSize = marshalSize + 8; // xLocation - marshalSize = marshalSize + 8; // yLocation - marshalSize = marshalSize + 8; // zLocation - marshalSize = marshalSize + 4; // psi - marshalSize = marshalSize + 4; // theta - marshalSize = marshalSize + 4; // phi - marshalSize = marshalSize + 4; // entityAppearance - marshalSize = marshalSize + 1; // deadReckoningAlgorithm - marshalSize = marshalSize + 15 * 1; // otherParameters - marshalSize = marshalSize + 4; // xAcceleration - marshalSize = marshalSize + 4; // yAcceleration - marshalSize = marshalSize + 4; // zAcceleration - marshalSize = marshalSize + 4; // xAngularVelocity - marshalSize = marshalSize + 4; // yAngularVelocity - marshalSize = marshalSize + 4; // zAngularVelocity - marshalSize = marshalSize + 12 * 1; // marking - marshalSize = marshalSize + 4; // capabilities - for (int idx = 0; idx < articulationParameters.size(); idx++) { - ArticulationParameter listElement = articulationParameters.get(idx); - marshalSize = marshalSize + listElement.getMarshalledSize(); - } - - return marshalSize; - } - - public void setSite(int pSite) { - site = pSite; - } - - public int getSite() { - return site; - } - - public void setApplication(int pApplication) { - application = pApplication; - } - - public int getApplication() { - return application; - } - - public void setEntity(int pEntity) { - entity = pEntity; - } - - public int getEntity() { - return entity; - } - - public void setForceId(short pForceId) { - forceId = pForceId; - } - - public short getForceId() { - return forceId; - } - - public byte getNumberOfArticulationParameters() { - return (byte) articulationParameters.size(); - } - - /** - * Note that setting this value will not change the marshalled value. The - * list whose length this describes is used for that purpose. The - * getnumberOfArticulationParameters method will also be based on the actual - * list length rather than this value. The method is simply here for java - * bean completeness. - */ - public void setNumberOfArticulationParameters(byte pNumberOfArticulationParameters) { - numberOfArticulationParameters = pNumberOfArticulationParameters; - } - - public void setEntityKind(short pEntityKind) { - entityKind = pEntityKind; - } - - public short getEntityKind() { - return entityKind; - } - - public void setDomain(short pDomain) { - domain = pDomain; - } - - public short getDomain() { - return domain; - } - - public void setCountry(int pCountry) { - country = pCountry; - } - - public int getCountry() { - return country; - } - - public void setCategory(short pCategory) { - category = pCategory; - } - - public short getCategory() { - return category; - } - - public void setSubcategory(short pSubcategory) { - subcategory = pSubcategory; - } - - public short getSubcategory() { - return subcategory; - } - - public void setSpecif(short pSpecif) { - specif = pSpecif; - } - - public short getSpecif() { - return specif; - } - - public void setExtra(short pExtra) { - extra = pExtra; - } - - public short getExtra() { - return extra; - } - - public void setAltEntityKind(short pAltEntityKind) { - altEntityKind = pAltEntityKind; - } - - public short getAltEntityKind() { - return altEntityKind; - } - - public void setAltDomain(short pAltDomain) { - altDomain = pAltDomain; - } - - public short getAltDomain() { - return altDomain; - } - - public void setAltCountry(int pAltCountry) { - altCountry = pAltCountry; - } - - public int getAltCountry() { - return altCountry; - } - - public void setAltCategory(short pAltCategory) { - altCategory = pAltCategory; - } - - public short getAltCategory() { - return altCategory; - } - - public void setAltSubcategory(short pAltSubcategory) { - altSubcategory = pAltSubcategory; - } - - public short getAltSubcategory() { - return altSubcategory; - } - - public void setAltSpecific(short pAltSpecific) { - altSpecific = pAltSpecific; - } - - public short getAltSpecific() { - return altSpecific; - } - - public void setAltExtra(short pAltExtra) { - altExtra = pAltExtra; - } - - public short getAltExtra() { - return altExtra; - } - - public void setXVelocity(float pXVelocity) { - xVelocity = pXVelocity; - } - - public float getXVelocity() { - return xVelocity; - } - - public void setYVelocity(float pYVelocity) { - yVelocity = pYVelocity; - } - - public float getYVelocity() { - return yVelocity; - } - - public void setZVelocity(float pZVelocity) { - zVelocity = pZVelocity; - } - - public float getZVelocity() { - return zVelocity; - } - - public void setXLocation(double pXLocation) { - xLocation = pXLocation; - } - - public double getXLocation() { - return xLocation; - } - - public void setYLocation(double pYLocation) { - yLocation = pYLocation; - } - - public double getYLocation() { - return yLocation; - } - - public void setZLocation(double pZLocation) { - zLocation = pZLocation; - } - - public double getZLocation() { - return zLocation; - } - - public void setPsi(float pPsi) { - psi = pPsi; - } - - public float getPsi() { - return psi; - } - - public void setTheta(float pTheta) { - theta = pTheta; - } - - public float getTheta() { - return theta; - } - - public void setPhi(float pPhi) { - phi = pPhi; - } - - public float getPhi() { - return phi; - } - - public void setEntityAppearance(int pEntityAppearance) { - entityAppearance = pEntityAppearance; - } - - public int getEntityAppearance() { - return entityAppearance; - } - - public void setDeadReckoningAlgorithm(short pDeadReckoningAlgorithm) { - deadReckoningAlgorithm = pDeadReckoningAlgorithm; - } - - public short getDeadReckoningAlgorithm() { - return deadReckoningAlgorithm; - } - - public void setOtherParameters(byte[] pOtherParameters) { - otherParameters = pOtherParameters; - } - - public byte[] getOtherParameters() { - return otherParameters; - } - - public void setXAcceleration(float pXAcceleration) { - xAcceleration = pXAcceleration; - } - - public float getXAcceleration() { - return xAcceleration; - } - - public void setYAcceleration(float pYAcceleration) { - yAcceleration = pYAcceleration; - } - - public float getYAcceleration() { - return yAcceleration; - } - - public void setZAcceleration(float pZAcceleration) { - zAcceleration = pZAcceleration; - } - - public float getZAcceleration() { - return zAcceleration; - } - - public void setXAngularVelocity(float pXAngularVelocity) { - xAngularVelocity = pXAngularVelocity; - } - - public float getXAngularVelocity() { - return xAngularVelocity; - } - - public void setYAngularVelocity(float pYAngularVelocity) { - yAngularVelocity = pYAngularVelocity; - } - - public float getYAngularVelocity() { - return yAngularVelocity; - } - - public void setZAngularVelocity(float pZAngularVelocity) { - zAngularVelocity = pZAngularVelocity; - } - - public float getZAngularVelocity() { - return zAngularVelocity; - } - - public void setMarking(byte[] pMarking) { - marking = pMarking; - } - - public byte[] getMarking() { - return marking; - } - - public void setCapabilities(int pCapabilities) { - capabilities = pCapabilities; - } - - public int getCapabilities() { - return capabilities; - } - - public void setArticulationParameters(List pArticulationParameters) { - articulationParameters = pArticulationParameters; - } - - public List getArticulationParameters() { - return articulationParameters; - } - - /** - * 0 uniform color, 1 camouflage - */ - public int getEntityAppearance_paintScheme() { - int val = (int) (this.entityAppearance & (int) 0x1); - return (int) (val >> 0); - } - - /** - * 0 uniform color, 1 camouflage - */ - public void setEntityAppearance_paintScheme(int val) { - int aVal = 0; - this.entityAppearance &= (int) (~0x1); // clear bits - aVal = (int) (val << 0); - this.entityAppearance = (int) (this.entityAppearance | aVal); - } - - /** - * 0 no mobility kill, 1 mobility kill - */ - public int getEntityAppearance_mobility() { - int val = (int) (this.entityAppearance & (int) 0x2); - return (int) (val >> 1); - } - - /** - * 0 no mobility kill, 1 mobility kill - */ - public void setEntityAppearance_mobility(int val) { - int aVal = 0; - this.entityAppearance &= (int) (~0x2); // clear bits - aVal = (int) (val << 1); - this.entityAppearance = (int) (this.entityAppearance | aVal); - } - - /** - * 0 no firepower iill, 1 firepower kill - */ - public int getEntityAppearance_firepower() { - int val = (int) (this.entityAppearance & (int) 0x4); - return (int) (val >> 2); - } - - /** - * 0 no firepower iill, 1 firepower kill - */ - public void setEntityAppearance_firepower(int val) { - int aVal = 0; - this.entityAppearance &= (int) (~0x4); // clear bits - aVal = (int) (val << 2); - this.entityAppearance = (int) (this.entityAppearance | aVal); - } - - /** - * 0 no damage, 1 slight damage, 2 moderate, 3 destroyed - */ - public int getEntityAppearance_damage() { - int val = (int) (this.entityAppearance & (int) 0x18); - return (int) (val >> 3); - } - - /** - * 0 no damage, 1 slight damage, 2 moderate, 3 destroyed - */ - public void setEntityAppearance_damage(int val) { - int aVal = 0; - this.entityAppearance &= (int) (~0x18); // clear bits - aVal = (int) (val << 3); - this.entityAppearance = (int) (this.entityAppearance | aVal); - } - - /** - * 0 no smoke, 1 smoke plume, 2 engine smoke, 3 engine smoke and plume - */ - public int getEntityAppearance_smoke() { - int val = (int) (this.entityAppearance & (int) 0x60); - return (int) (val >> 5); - } - - /** - * 0 no smoke, 1 smoke plume, 2 engine smoke, 3 engine smoke and plume - */ - public void setEntityAppearance_smoke(int val) { - int aVal = 0; - this.entityAppearance &= (int) (~0x60); // clear bits - aVal = (int) (val << 5); - this.entityAppearance = (int) (this.entityAppearance | aVal); - } - - /** - * dust cloud, 0 none 1 small 2 medium 3 large - */ - public int getEntityAppearance_trailingEffects() { - int val = (int) (this.entityAppearance & (int) 0x180); - return (int) (val >> 7); - } - - /** - * dust cloud, 0 none 1 small 2 medium 3 large - */ - public void setEntityAppearance_trailingEffects(int val) { - int aVal = 0; - this.entityAppearance &= (int) (~0x180); // clear bits - aVal = (int) (val << 7); - this.entityAppearance = (int) (this.entityAppearance | aVal); - } - - /** - * 0 NA 1 closed popped 3 popped and person visible 4 open 5 open and person - * visible - */ - public int getEntityAppearance_hatch() { - int val = (int) (this.entityAppearance & (int) 0xe00); - return (int) (val >> 9); - } - - /** - * 0 NA 1 closed popped 3 popped and person visible 4 open 5 open and person - * visible - */ - public void setEntityAppearance_hatch(int val) { - int aVal = 0; - this.entityAppearance &= (int) (~0xe00); // clear bits - aVal = (int) (val << 9); - this.entityAppearance = (int) (this.entityAppearance | aVal); - } - - /** - * 0 off 1 on - */ - public int getEntityAppearance_headlights() { - int val = (int) (this.entityAppearance & (int) 0x1000); - return (int) (val >> 12); - } - - /** - * 0 off 1 on - */ - public void setEntityAppearance_headlights(int val) { - int aVal = 0; - this.entityAppearance &= (int) (~0x1000); // clear bits - aVal = (int) (val << 12); - this.entityAppearance = (int) (this.entityAppearance | aVal); - } - - /** - * 0 off 1 on - */ - public int getEntityAppearance_tailLights() { - int val = (int) (this.entityAppearance & (int) 0x2000); - return (int) (val >> 13); - } - - /** - * 0 off 1 on - */ - public void setEntityAppearance_tailLights(int val) { - int aVal = 0; - this.entityAppearance &= (int) (~0x2000); // clear bits - aVal = (int) (val << 13); - this.entityAppearance = (int) (this.entityAppearance | aVal); - } - - /** - * 0 off 1 on - */ - public int getEntityAppearance_brakeLights() { - int val = (int) (this.entityAppearance & (int) 0x4000); - return (int) (val >> 14); - } - - /** - * 0 off 1 on - */ - public void setEntityAppearance_brakeLights(int val) { - int aVal = 0; - this.entityAppearance &= (int) (~0x4000); // clear bits - aVal = (int) (val << 14); - this.entityAppearance = (int) (this.entityAppearance | aVal); - } - - /** - * 0 off 1 on - */ - public int getEntityAppearance_flaming() { - int val = (int) (this.entityAppearance & (int) 0x8000); - return (int) (val >> 15); - } - - /** - * 0 off 1 on - */ - public void setEntityAppearance_flaming(int val) { - int aVal = 0; - this.entityAppearance &= (int) (~0x8000); // clear bits - aVal = (int) (val << 15); - this.entityAppearance = (int) (this.entityAppearance | aVal); - } - - /** - * 0 not raised 1 raised - */ - public int getEntityAppearance_launcher() { - int val = (int) (this.entityAppearance & (int) 0x10000); - return (int) (val >> 16); - } - - /** - * 0 not raised 1 raised - */ - public void setEntityAppearance_launcher(int val) { - int aVal = 0; - this.entityAppearance &= (int) (~0x10000); // clear bits - aVal = (int) (val << 16); - this.entityAppearance = (int) (this.entityAppearance | aVal); - } - - /** - * 0 desert 1 winter 2 forest 3 unused - */ - public int getEntityAppearance_camouflageType() { - int val = (int) (this.entityAppearance & (int) 0x60000); - return (int) (val >> 17); - } - - /** - * 0 desert 1 winter 2 forest 3 unused - */ - public void setEntityAppearance_camouflageType(int val) { - int aVal = 0; - this.entityAppearance &= (int) (~0x60000); // clear bits - aVal = (int) (val << 17); - this.entityAppearance = (int) (this.entityAppearance | aVal); - } - - /** - * Packs a Pdu into the ByteBuffer. - * - * @throws java.nio.BufferOverflowException if buff is too small - * @throws java.nio.ReadOnlyBufferException if buff is read only - * @see java.nio.ByteBuffer - * @param buff The ByteBuffer at the position to begin writing - * @since ?? - */ - public void marshal(java.nio.ByteBuffer buff) { - super.marshal(buff); - buff.putShort((short) site); - buff.putShort((short) application); - buff.putShort((short) entity); - buff.put((byte) forceId); - buff.put((byte) articulationParameters.size()); - buff.put((byte) entityKind); - buff.put((byte) domain); - buff.putShort((short) country); - buff.put((byte) category); - buff.put((byte) subcategory); - buff.put((byte) specif); - buff.put((byte) extra); - buff.put((byte) altEntityKind); - buff.put((byte) altDomain); - buff.putShort((short) altCountry); - buff.put((byte) altCategory); - buff.put((byte) altSubcategory); - buff.put((byte) altSpecific); - buff.put((byte) altExtra); - buff.putFloat((float) xVelocity); - buff.putFloat((float) yVelocity); - buff.putFloat((float) zVelocity); - buff.putDouble((double) xLocation); - buff.putDouble((double) yLocation); - buff.putDouble((double) zLocation); - buff.putFloat((float) psi); - buff.putFloat((float) theta); - buff.putFloat((float) phi); - buff.putInt((int) entityAppearance); - buff.put((byte) deadReckoningAlgorithm); - - for (int idx = 0; idx < otherParameters.length; idx++) { - buff.put((byte) otherParameters[idx]); - } // end of array marshaling - - buff.putFloat((float) xAcceleration); - buff.putFloat((float) yAcceleration); - buff.putFloat((float) zAcceleration); - buff.putFloat((float) xAngularVelocity); - buff.putFloat((float) yAngularVelocity); - buff.putFloat((float) zAngularVelocity); - - for (int idx = 0; idx < marking.length; idx++) { - buff.put((byte) marking[idx]); - } // end of array marshaling - - buff.putInt((int) capabilities); - - for (int idx = 0; idx < articulationParameters.size(); idx++) { - ArticulationParameter aArticulationParameter = (ArticulationParameter) articulationParameters.get(idx); - aArticulationParameter.marshal(buff); - } // end of list marshalling - - } // end of marshal method - - /** - * Unpacks a Pdu from the underlying data. - * - * @throws java.nio.BufferUnderflowException if buff is too small - * @see java.nio.ByteBuffer - * @param buff The ByteBuffer at the position to begin reading - * @since ?? - */ - public void unmarshal(java.nio.ByteBuffer buff) { - super.unmarshal(buff); - - site = (int) (buff.getShort() & 0xFFFF); - application = (int) (buff.getShort() & 0xFFFF); - entity = (int) (buff.getShort() & 0xFFFF); - forceId = (short) (buff.get() & 0xFF); - numberOfArticulationParameters = buff.get(); - entityKind = (short) (buff.get() & 0xFF); - domain = (short) (buff.get() & 0xFF); - country = (int) (buff.getShort() & 0xFFFF); - category = (short) (buff.get() & 0xFF); - subcategory = (short) (buff.get() & 0xFF); - specif = (short) (buff.get() & 0xFF); - extra = (short) (buff.get() & 0xFF); - altEntityKind = (short) (buff.get() & 0xFF); - altDomain = (short) (buff.get() & 0xFF); - altCountry = (int) (buff.getShort() & 0xFFFF); - altCategory = (short) (buff.get() & 0xFF); - altSubcategory = (short) (buff.get() & 0xFF); - altSpecific = (short) (buff.get() & 0xFF); - altExtra = (short) (buff.get() & 0xFF); - xVelocity = buff.getFloat(); - yVelocity = buff.getFloat(); - zVelocity = buff.getFloat(); - xLocation = buff.getDouble(); - yLocation = buff.getDouble(); - zLocation = buff.getDouble(); - psi = buff.getFloat(); - theta = buff.getFloat(); - phi = buff.getFloat(); - entityAppearance = buff.getInt(); - deadReckoningAlgorithm = (short) (buff.get() & 0xFF); - for (int idx = 0; idx < otherParameters.length; idx++) { - otherParameters[idx] = buff.get(); - } // end of array unmarshaling - xAcceleration = buff.getFloat(); - yAcceleration = buff.getFloat(); - zAcceleration = buff.getFloat(); - xAngularVelocity = buff.getFloat(); - yAngularVelocity = buff.getFloat(); - zAngularVelocity = buff.getFloat(); - for (int idx = 0; idx < marking.length; idx++) { - marking[idx] = buff.get(); - } // end of array unmarshaling - capabilities = buff.getInt(); - for (int idx = 0; idx < numberOfArticulationParameters; idx++) { - ArticulationParameter anX = new ArticulationParameter(); - anX.unmarshal(buff); - articulationParameters.add(anX); - } - - } // end of unmarshal method - - - /* - * The equals method doesn't always work--mostly it works only on classes that consist only of primitives. Be careful. - */ - @Override - public boolean equals(Object obj) { - - if (this == obj) { - return true; - } - - if (obj == null) { - return false; - } - - if (getClass() != obj.getClass()) { - return false; - } - - return equalsImpl(obj); - } - - @Override - public boolean equalsImpl(Object obj) { - boolean ivarsEqual = true; - - if (!(obj instanceof FastEntityStatePdu)) { - return false; - } - - final FastEntityStatePdu rhs = (FastEntityStatePdu) obj; - - if (!(site == rhs.site)) { - ivarsEqual = false; - } - if (!(application == rhs.application)) { - ivarsEqual = false; - } - if (!(entity == rhs.entity)) { - ivarsEqual = false; - } - if (!(forceId == rhs.forceId)) { - ivarsEqual = false; - } - if (!(numberOfArticulationParameters == rhs.numberOfArticulationParameters)) { - ivarsEqual = false; - } - if (!(entityKind == rhs.entityKind)) { - ivarsEqual = false; - } - if (!(domain == rhs.domain)) { - ivarsEqual = false; - } - if (!(country == rhs.country)) { - ivarsEqual = false; - } - if (!(category == rhs.category)) { - ivarsEqual = false; - } - if (!(subcategory == rhs.subcategory)) { - ivarsEqual = false; - } - if (!(specif == rhs.specif)) { - ivarsEqual = false; - } - if (!(extra == rhs.extra)) { - ivarsEqual = false; - } - if (!(altEntityKind == rhs.altEntityKind)) { - ivarsEqual = false; - } - if (!(altDomain == rhs.altDomain)) { - ivarsEqual = false; - } - if (!(altCountry == rhs.altCountry)) { - ivarsEqual = false; - } - if (!(altCategory == rhs.altCategory)) { - ivarsEqual = false; - } - if (!(altSubcategory == rhs.altSubcategory)) { - ivarsEqual = false; - } - if (!(altSpecific == rhs.altSpecific)) { - ivarsEqual = false; - } - if (!(altExtra == rhs.altExtra)) { - ivarsEqual = false; - } - if (!(xVelocity == rhs.xVelocity)) { - ivarsEqual = false; - } - if (!(yVelocity == rhs.yVelocity)) { - ivarsEqual = false; - } - if (!(zVelocity == rhs.zVelocity)) { - ivarsEqual = false; - } - if (!(xLocation == rhs.xLocation)) { - ivarsEqual = false; - } - if (!(yLocation == rhs.yLocation)) { - ivarsEqual = false; - } - if (!(zLocation == rhs.zLocation)) { - ivarsEqual = false; - } - if (!(psi == rhs.psi)) { - ivarsEqual = false; - } - if (!(theta == rhs.theta)) { - ivarsEqual = false; - } - if (!(phi == rhs.phi)) { - ivarsEqual = false; - } - if (!(entityAppearance == rhs.entityAppearance)) { - ivarsEqual = false; - } - if (!(deadReckoningAlgorithm == rhs.deadReckoningAlgorithm)) { - ivarsEqual = false; - } - - for (int idx = 0; idx < 15; idx++) { - if (!(otherParameters[idx] == rhs.otherParameters[idx])) { - ivarsEqual = false; - } - } - - if (!(xAcceleration == rhs.xAcceleration)) { - ivarsEqual = false; - } - if (!(yAcceleration == rhs.yAcceleration)) { - ivarsEqual = false; - } - if (!(zAcceleration == rhs.zAcceleration)) { - ivarsEqual = false; - } - if (!(xAngularVelocity == rhs.xAngularVelocity)) { - ivarsEqual = false; - } - if (!(yAngularVelocity == rhs.yAngularVelocity)) { - ivarsEqual = false; - } - if (!(zAngularVelocity == rhs.zAngularVelocity)) { - ivarsEqual = false; - } - - for (int idx = 0; idx < 12; idx++) { - if (!(marking[idx] == rhs.marking[idx])) { - ivarsEqual = false; - } - } - - if (!(capabilities == rhs.capabilities)) { - ivarsEqual = false; - } - - for (int idx = 0; idx < articulationParameters.size(); idx++) { - if (!(articulationParameters.get(idx).equals(rhs.articulationParameters.get(idx)))) { - ivarsEqual = false; - } - } - - return ivarsEqual && super.equalsImpl(rhs); - } -} // end of class diff --git a/src/main/java/edu/nps/moves/dis7/FastEntityStatePdu.java b/src/main/java/edu/nps/moves/dis7/FastEntityStatePdu.java deleted file mode 100644 index 5348afb7..00000000 --- a/src/main/java/edu/nps/moves/dis7/FastEntityStatePdu.java +++ /dev/null @@ -1,1009 +0,0 @@ -package edu.nps.moves.dis7; - -import java.util.*; -import java.io.*; - -/** - * Represents the postion and state of one entity in the world. This is - * identical in function to entity state pdu, but generates less garbage to - * collect in the Java world. Section 7.2.2. COMPLETE - * - * Copyright (c) 2008-2016, MOVES Institute, Naval Postgraduate School. All - * rights reserved. This work is licensed under the BSD open source license, - * available at https://www.movesinstitute.org/licenses/bsd.html - * - * @author DMcG - */ -@Deprecated -public class FastEntityStatePdu extends EntityInformationFamilyPdu implements Serializable { - - /** - * The site ID - */ - protected int site; - - /** - * The application ID - */ - protected int application; - - /** - * the entity ID - */ - protected int entity; - - /** - * what force this entity is affiliated with, eg red, blue, neutral, etc - */ - protected short forceId; - - /** - * How many variable (nee articulation) parameters are in the variable - * length list - */ - protected byte numberOfVariableParameters; - - /** - * Kind of entity - */ - protected short entityKind; - - /** - * Domain of entity (air, surface, subsurface, space, etc) - */ - protected short domain; - - /** - * country to which the design of the entity is attributed - */ - protected int country; - - /** - * category of entity - */ - protected short category; - - /** - * subcategory of entity - */ - protected short subcategory; - - /** - * specific info based on subcategory field - */ - protected short specific; - - protected short extra; - - /** - * Kind of entity - */ - protected short altEntityKind; - - /** - * Domain of entity (air, surface, subsurface, space, etc) - */ - protected short altDomain; - - /** - * country to which the design of the entity is attributed - */ - protected int altCountry; - - /** - * category of entity - */ - protected short altCategory; - - /** - * subcategory of entity - */ - protected short altSubcategory; - - /** - * specific info based on subcategory field - */ - protected short altSpecific; - - protected short altExtra; - - /** - * X velo - */ - protected float xVelocity; - - /** - * y Value - */ - protected float yVelocity; - - /** - * Z value - */ - protected float zVelocity; - - /** - * X value - */ - protected double xLocation; - - /** - * y Value - */ - protected double yLocation; - - /** - * Z value - */ - protected double zLocation; - - protected float psi; - - protected float theta; - - protected float phi; - - /** - * a series of bit flags that are used to help draw the entity, such as - * smoking, on fire, etc. - */ - protected int entityAppearance; - - /** - * enumeration of what dead reckoning algorighm to use - */ - protected short deadReckoningAlgorithm; - - /** - * other parameters to use in the dead reckoning algorithm - */ - protected byte[] otherParameters = new byte[15]; - - /** - * X value - */ - protected float xAcceleration; - - /** - * y Value - */ - protected float yAcceleration; - - /** - * Z value - */ - protected float zAcceleration; - - /** - * X value - */ - protected float xAngularVelocity; - - /** - * y Value - */ - protected float yAngularVelocity; - - /** - * Z value - */ - protected float zAngularVelocity; - - /** - * characters that can be used for debugging, or to draw unique strings on - * the side of entities in the world - */ - protected byte[] marking = new byte[12]; - - /** - * a series of bit flags - */ - protected int capabilities; - - /** - * variable length list of variable parameters. In earlier versions of DIS - * these were known as articulation parameters - */ - protected List< VariableParameter> variableParameters = new ArrayList< VariableParameter>(); - - /** - * Constructor - */ - public FastEntityStatePdu() { - setPduType((short) 1); - } - - public int getMarshalledSize() { - int marshalSize = 0; - - marshalSize = super.getMarshalledSize(); - marshalSize = marshalSize + 2; // site - marshalSize = marshalSize + 2; // application - marshalSize = marshalSize + 2; // entity - marshalSize = marshalSize + 1; // forceId - marshalSize = marshalSize + 1; // numberOfVariableParameters - marshalSize = marshalSize + 1; // entityKind - marshalSize = marshalSize + 1; // domain - marshalSize = marshalSize + 2; // country - marshalSize = marshalSize + 1; // category - marshalSize = marshalSize + 1; // subcategory - marshalSize = marshalSize + 1; // specific - marshalSize = marshalSize + 1; // extra - marshalSize = marshalSize + 1; // altEntityKind - marshalSize = marshalSize + 1; // altDomain - marshalSize = marshalSize + 2; // altCountry - marshalSize = marshalSize + 1; // altCategory - marshalSize = marshalSize + 1; // altSubcategory - marshalSize = marshalSize + 1; // altSpecific - marshalSize = marshalSize + 1; // altExtra - marshalSize = marshalSize + 4; // xVelocity - marshalSize = marshalSize + 4; // yVelocity - marshalSize = marshalSize + 4; // zVelocity - marshalSize = marshalSize + 8; // xLocation - marshalSize = marshalSize + 8; // yLocation - marshalSize = marshalSize + 8; // zLocation - marshalSize = marshalSize + 4; // psi - marshalSize = marshalSize + 4; // theta - marshalSize = marshalSize + 4; // phi - marshalSize = marshalSize + 4; // entityAppearance - marshalSize = marshalSize + 1; // deadReckoningAlgorithm - marshalSize = marshalSize + 15 * 1; // otherParameters - marshalSize = marshalSize + 4; // xAcceleration - marshalSize = marshalSize + 4; // yAcceleration - marshalSize = marshalSize + 4; // zAcceleration - marshalSize = marshalSize + 4; // xAngularVelocity - marshalSize = marshalSize + 4; // yAngularVelocity - marshalSize = marshalSize + 4; // zAngularVelocity - marshalSize = marshalSize + 12 * 1; // marking - marshalSize = marshalSize + 4; // capabilities - for (int idx = 0; idx < variableParameters.size(); idx++) { - VariableParameter listElement = variableParameters.get(idx); - marshalSize = marshalSize + listElement.getMarshalledSize(); - } - - return marshalSize; - } - - public void setSite(int pSite) { - site = pSite; - } - - public int getSite() { - return site; - } - - public void setApplication(int pApplication) { - application = pApplication; - } - - public int getApplication() { - return application; - } - - public void setEntity(int pEntity) { - entity = pEntity; - } - - public int getEntity() { - return entity; - } - - public void setForceId(short pForceId) { - forceId = pForceId; - } - - public short getForceId() { - return forceId; - } - - public byte getNumberOfVariableParameters() { - return (byte) variableParameters.size(); - } - - /** - * Note that setting this value will not change the marshalled value. The - * list whose length this describes is used for that purpose. The - * getnumberOfVariableParameters method will also be based on the actual - * list length rather than this value. The method is simply here for java - * bean completeness. - */ - public void setNumberOfVariableParameters(byte pNumberOfVariableParameters) { - numberOfVariableParameters = pNumberOfVariableParameters; - } - - public void setEntityKind(short pEntityKind) { - entityKind = pEntityKind; - } - - public short getEntityKind() { - return entityKind; - } - - public void setDomain(short pDomain) { - domain = pDomain; - } - - public short getDomain() { - return domain; - } - - public void setCountry(int pCountry) { - country = pCountry; - } - - public int getCountry() { - return country; - } - - public void setCategory(short pCategory) { - category = pCategory; - } - - public short getCategory() { - return category; - } - - public void setSubcategory(short pSubcategory) { - subcategory = pSubcategory; - } - - public short getSubcategory() { - return subcategory; - } - - public void setSpecific(short pSpecific) { - specific = pSpecific; - } - - public short getSpecific() { - return specific; - } - - public void setExtra(short pExtra) { - extra = pExtra; - } - - public short getExtra() { - return extra; - } - - public void setAltEntityKind(short pAltEntityKind) { - altEntityKind = pAltEntityKind; - } - - public short getAltEntityKind() { - return altEntityKind; - } - - public void setAltDomain(short pAltDomain) { - altDomain = pAltDomain; - } - - public short getAltDomain() { - return altDomain; - } - - public void setAltCountry(int pAltCountry) { - altCountry = pAltCountry; - } - - public int getAltCountry() { - return altCountry; - } - - public void setAltCategory(short pAltCategory) { - altCategory = pAltCategory; - } - - public short getAltCategory() { - return altCategory; - } - - public void setAltSubcategory(short pAltSubcategory) { - altSubcategory = pAltSubcategory; - } - - public short getAltSubcategory() { - return altSubcategory; - } - - public void setAltSpecific(short pAltSpecific) { - altSpecific = pAltSpecific; - } - - public short getAltSpecific() { - return altSpecific; - } - - public void setAltExtra(short pAltExtra) { - altExtra = pAltExtra; - } - - public short getAltExtra() { - return altExtra; - } - - public void setXVelocity(float pXVelocity) { - xVelocity = pXVelocity; - } - - public float getXVelocity() { - return xVelocity; - } - - public void setYVelocity(float pYVelocity) { - yVelocity = pYVelocity; - } - - public float getYVelocity() { - return yVelocity; - } - - public void setZVelocity(float pZVelocity) { - zVelocity = pZVelocity; - } - - public float getZVelocity() { - return zVelocity; - } - - public void setXLocation(double pXLocation) { - xLocation = pXLocation; - } - - public double getXLocation() { - return xLocation; - } - - public void setYLocation(double pYLocation) { - yLocation = pYLocation; - } - - public double getYLocation() { - return yLocation; - } - - public void setZLocation(double pZLocation) { - zLocation = pZLocation; - } - - public double getZLocation() { - return zLocation; - } - - public void setPsi(float pPsi) { - psi = pPsi; - } - - public float getPsi() { - return psi; - } - - public void setTheta(float pTheta) { - theta = pTheta; - } - - public float getTheta() { - return theta; - } - - public void setPhi(float pPhi) { - phi = pPhi; - } - - public float getPhi() { - return phi; - } - - public void setEntityAppearance(int pEntityAppearance) { - entityAppearance = pEntityAppearance; - } - - public int getEntityAppearance() { - return entityAppearance; - } - - public void setDeadReckoningAlgorithm(short pDeadReckoningAlgorithm) { - deadReckoningAlgorithm = pDeadReckoningAlgorithm; - } - - public short getDeadReckoningAlgorithm() { - return deadReckoningAlgorithm; - } - - public void setOtherParameters(byte[] pOtherParameters) { - otherParameters = pOtherParameters; - } - - public byte[] getOtherParameters() { - return otherParameters; - } - - public void setXAcceleration(float pXAcceleration) { - xAcceleration = pXAcceleration; - } - - public float getXAcceleration() { - return xAcceleration; - } - - public void setYAcceleration(float pYAcceleration) { - yAcceleration = pYAcceleration; - } - - public float getYAcceleration() { - return yAcceleration; - } - - public void setZAcceleration(float pZAcceleration) { - zAcceleration = pZAcceleration; - } - - public float getZAcceleration() { - return zAcceleration; - } - - public void setXAngularVelocity(float pXAngularVelocity) { - xAngularVelocity = pXAngularVelocity; - } - - public float getXAngularVelocity() { - return xAngularVelocity; - } - - public void setYAngularVelocity(float pYAngularVelocity) { - yAngularVelocity = pYAngularVelocity; - } - - public float getYAngularVelocity() { - return yAngularVelocity; - } - - public void setZAngularVelocity(float pZAngularVelocity) { - zAngularVelocity = pZAngularVelocity; - } - - public float getZAngularVelocity() { - return zAngularVelocity; - } - - public void setMarking(byte[] pMarking) { - marking = pMarking; - } - - public byte[] getMarking() { - return marking; - } - - public void setCapabilities(int pCapabilities) { - capabilities = pCapabilities; - } - - public int getCapabilities() { - return capabilities; - } - - public void setVariableParameters(List pVariableParameters) { - variableParameters = pVariableParameters; - } - - public List getVariableParameters() { - return variableParameters; - } - - public void marshal(DataOutputStream dos) { - super.marshal(dos); - try { - dos.writeShort((short) site); - dos.writeShort((short) application); - dos.writeShort((short) entity); - dos.writeByte((byte) forceId); - dos.writeByte((byte) variableParameters.size()); - dos.writeByte((byte) entityKind); - dos.writeByte((byte) domain); - dos.writeShort((short) country); - dos.writeByte((byte) category); - dos.writeByte((byte) subcategory); - dos.writeByte((byte) specific); - dos.writeByte((byte) extra); - dos.writeByte((byte) altEntityKind); - dos.writeByte((byte) altDomain); - dos.writeShort((short) altCountry); - dos.writeByte((byte) altCategory); - dos.writeByte((byte) altSubcategory); - dos.writeByte((byte) altSpecific); - dos.writeByte((byte) altExtra); - dos.writeFloat((float) xVelocity); - dos.writeFloat((float) yVelocity); - dos.writeFloat((float) zVelocity); - dos.writeDouble((double) xLocation); - dos.writeDouble((double) yLocation); - dos.writeDouble((double) zLocation); - dos.writeFloat((float) psi); - dos.writeFloat((float) theta); - dos.writeFloat((float) phi); - dos.writeInt((int) entityAppearance); - dos.writeByte((byte) deadReckoningAlgorithm); - - for (int idx = 0; idx < otherParameters.length; idx++) { - dos.writeByte(otherParameters[idx]); - } // end of array marshaling - - dos.writeFloat((float) xAcceleration); - dos.writeFloat((float) yAcceleration); - dos.writeFloat((float) zAcceleration); - dos.writeFloat((float) xAngularVelocity); - dos.writeFloat((float) yAngularVelocity); - dos.writeFloat((float) zAngularVelocity); - - for (int idx = 0; idx < marking.length; idx++) { - dos.writeByte(marking[idx]); - } // end of array marshaling - - dos.writeInt((int) capabilities); - - for (int idx = 0; idx < variableParameters.size(); idx++) { - VariableParameter aVariableParameter = variableParameters.get(idx); - aVariableParameter.marshal(dos); - } // end of list marshalling - - } // end try - catch (Exception e) { - System.out.println(e); - } - } // end of marshal method - - public void unmarshal(DataInputStream dis) { - super.unmarshal(dis); - - try { - site = (int) dis.readUnsignedShort(); - application = (int) dis.readUnsignedShort(); - entity = (int) dis.readUnsignedShort(); - forceId = (short) dis.readUnsignedByte(); - numberOfVariableParameters = dis.readByte(); - entityKind = (short) dis.readUnsignedByte(); - domain = (short) dis.readUnsignedByte(); - country = (int) dis.readUnsignedShort(); - category = (short) dis.readUnsignedByte(); - subcategory = (short) dis.readUnsignedByte(); - specific = (short) dis.readUnsignedByte(); - extra = (short) dis.readUnsignedByte(); - altEntityKind = (short) dis.readUnsignedByte(); - altDomain = (short) dis.readUnsignedByte(); - altCountry = (int) dis.readUnsignedShort(); - altCategory = (short) dis.readUnsignedByte(); - altSubcategory = (short) dis.readUnsignedByte(); - altSpecific = (short) dis.readUnsignedByte(); - altExtra = (short) dis.readUnsignedByte(); - xVelocity = dis.readFloat(); - yVelocity = dis.readFloat(); - zVelocity = dis.readFloat(); - xLocation = dis.readDouble(); - yLocation = dis.readDouble(); - zLocation = dis.readDouble(); - psi = dis.readFloat(); - theta = dis.readFloat(); - phi = dis.readFloat(); - entityAppearance = dis.readInt(); - deadReckoningAlgorithm = (short) dis.readUnsignedByte(); - for (int idx = 0; idx < otherParameters.length; idx++) { - otherParameters[idx] = dis.readByte(); - } // end of array unmarshaling - xAcceleration = dis.readFloat(); - yAcceleration = dis.readFloat(); - zAcceleration = dis.readFloat(); - xAngularVelocity = dis.readFloat(); - yAngularVelocity = dis.readFloat(); - zAngularVelocity = dis.readFloat(); - for (int idx = 0; idx < marking.length; idx++) { - marking[idx] = dis.readByte(); - } // end of array unmarshaling - capabilities = dis.readInt(); - for (int idx = 0; idx < numberOfVariableParameters; idx++) { - VariableParameter anX = new VariableParameter(); - anX.unmarshal(dis); - variableParameters.add(anX); - } - - } // end try - catch (Exception e) { - System.out.println(e); - } - } // end of unmarshal method - - /** - * Packs a Pdu into the ByteBuffer. - * - * @throws java.nio.BufferOverflowException if buff is too small - * @throws java.nio.ReadOnlyBufferException if buff is read only - * @see java.nio.ByteBuffer - * @param buff The ByteBuffer at the position to begin writing - * @since ?? - */ - public void marshal(java.nio.ByteBuffer buff) { - super.marshal(buff); - buff.putShort((short) site); - buff.putShort((short) application); - buff.putShort((short) entity); - buff.put((byte) forceId); - buff.put((byte) variableParameters.size()); - buff.put((byte) entityKind); - buff.put((byte) domain); - buff.putShort((short) country); - buff.put((byte) category); - buff.put((byte) subcategory); - buff.put((byte) specific); - buff.put((byte) extra); - buff.put((byte) altEntityKind); - buff.put((byte) altDomain); - buff.putShort((short) altCountry); - buff.put((byte) altCategory); - buff.put((byte) altSubcategory); - buff.put((byte) altSpecific); - buff.put((byte) altExtra); - buff.putFloat((float) xVelocity); - buff.putFloat((float) yVelocity); - buff.putFloat((float) zVelocity); - buff.putDouble((double) xLocation); - buff.putDouble((double) yLocation); - buff.putDouble((double) zLocation); - buff.putFloat((float) psi); - buff.putFloat((float) theta); - buff.putFloat((float) phi); - buff.putInt((int) entityAppearance); - buff.put((byte) deadReckoningAlgorithm); - - for (int idx = 0; idx < otherParameters.length; idx++) { - buff.put((byte) otherParameters[idx]); - } // end of array marshaling - - buff.putFloat((float) xAcceleration); - buff.putFloat((float) yAcceleration); - buff.putFloat((float) zAcceleration); - buff.putFloat((float) xAngularVelocity); - buff.putFloat((float) yAngularVelocity); - buff.putFloat((float) zAngularVelocity); - - for (int idx = 0; idx < marking.length; idx++) { - buff.put((byte) marking[idx]); - } // end of array marshaling - - buff.putInt((int) capabilities); - - for (int idx = 0; idx < variableParameters.size(); idx++) { - VariableParameter aVariableParameter = (VariableParameter) variableParameters.get(idx); - aVariableParameter.marshal(buff); - } // end of list marshalling - - } // end of marshal method - - /** - * Unpacks a Pdu from the underlying data. - * - * @throws java.nio.BufferUnderflowException if buff is too small - * @see java.nio.ByteBuffer - * @param buff The ByteBuffer at the position to begin reading - * @since ?? - */ - public void unmarshal(java.nio.ByteBuffer buff) { - super.unmarshal(buff); - - site = (int) (buff.getShort() & 0xFFFF); - application = (int) (buff.getShort() & 0xFFFF); - entity = (int) (buff.getShort() & 0xFFFF); - forceId = (short) (buff.get() & 0xFF); - numberOfVariableParameters = buff.get(); - entityKind = (short) (buff.get() & 0xFF); - domain = (short) (buff.get() & 0xFF); - country = (int) (buff.getShort() & 0xFFFF); - category = (short) (buff.get() & 0xFF); - subcategory = (short) (buff.get() & 0xFF); - specific = (short) (buff.get() & 0xFF); - extra = (short) (buff.get() & 0xFF); - altEntityKind = (short) (buff.get() & 0xFF); - altDomain = (short) (buff.get() & 0xFF); - altCountry = (int) (buff.getShort() & 0xFFFF); - altCategory = (short) (buff.get() & 0xFF); - altSubcategory = (short) (buff.get() & 0xFF); - altSpecific = (short) (buff.get() & 0xFF); - altExtra = (short) (buff.get() & 0xFF); - xVelocity = buff.getFloat(); - yVelocity = buff.getFloat(); - zVelocity = buff.getFloat(); - xLocation = buff.getDouble(); - yLocation = buff.getDouble(); - zLocation = buff.getDouble(); - psi = buff.getFloat(); - theta = buff.getFloat(); - phi = buff.getFloat(); - entityAppearance = buff.getInt(); - deadReckoningAlgorithm = (short) (buff.get() & 0xFF); - for (int idx = 0; idx < otherParameters.length; idx++) { - otherParameters[idx] = buff.get(); - } // end of array unmarshaling - xAcceleration = buff.getFloat(); - yAcceleration = buff.getFloat(); - zAcceleration = buff.getFloat(); - xAngularVelocity = buff.getFloat(); - yAngularVelocity = buff.getFloat(); - zAngularVelocity = buff.getFloat(); - for (int idx = 0; idx < marking.length; idx++) { - marking[idx] = buff.get(); - } // end of array unmarshaling - capabilities = buff.getInt(); - for (int idx = 0; idx < numberOfVariableParameters; idx++) { - VariableParameter anX = new VariableParameter(); - anX.unmarshal(buff); - variableParameters.add(anX); - } - - } // end of unmarshal method - - - /* - * The equals method doesn't always work--mostly it works only on classes that consist only of primitives. Be careful. - */ - @Override - public boolean equals(Object obj) { - - if (this == obj) { - return true; - } - - if (obj == null) { - return false; - } - - if (getClass() != obj.getClass()) { - return false; - } - - return equalsImpl(obj); - } - - @Override - public boolean equalsImpl(Object obj) { - boolean ivarsEqual = true; - - if (!(obj instanceof FastEntityStatePdu)) { - return false; - } - - final FastEntityStatePdu rhs = (FastEntityStatePdu) obj; - - if (!(site == rhs.site)) { - ivarsEqual = false; - } - if (!(application == rhs.application)) { - ivarsEqual = false; - } - if (!(entity == rhs.entity)) { - ivarsEqual = false; - } - if (!(forceId == rhs.forceId)) { - ivarsEqual = false; - } - if (!(numberOfVariableParameters == rhs.numberOfVariableParameters)) { - ivarsEqual = false; - } - if (!(entityKind == rhs.entityKind)) { - ivarsEqual = false; - } - if (!(domain == rhs.domain)) { - ivarsEqual = false; - } - if (!(country == rhs.country)) { - ivarsEqual = false; - } - if (!(category == rhs.category)) { - ivarsEqual = false; - } - if (!(subcategory == rhs.subcategory)) { - ivarsEqual = false; - } - if (!(specific == rhs.specific)) { - ivarsEqual = false; - } - if (!(extra == rhs.extra)) { - ivarsEqual = false; - } - if (!(altEntityKind == rhs.altEntityKind)) { - ivarsEqual = false; - } - if (!(altDomain == rhs.altDomain)) { - ivarsEqual = false; - } - if (!(altCountry == rhs.altCountry)) { - ivarsEqual = false; - } - if (!(altCategory == rhs.altCategory)) { - ivarsEqual = false; - } - if (!(altSubcategory == rhs.altSubcategory)) { - ivarsEqual = false; - } - if (!(altSpecific == rhs.altSpecific)) { - ivarsEqual = false; - } - if (!(altExtra == rhs.altExtra)) { - ivarsEqual = false; - } - if (!(xVelocity == rhs.xVelocity)) { - ivarsEqual = false; - } - if (!(yVelocity == rhs.yVelocity)) { - ivarsEqual = false; - } - if (!(zVelocity == rhs.zVelocity)) { - ivarsEqual = false; - } - if (!(xLocation == rhs.xLocation)) { - ivarsEqual = false; - } - if (!(yLocation == rhs.yLocation)) { - ivarsEqual = false; - } - if (!(zLocation == rhs.zLocation)) { - ivarsEqual = false; - } - if (!(psi == rhs.psi)) { - ivarsEqual = false; - } - if (!(theta == rhs.theta)) { - ivarsEqual = false; - } - if (!(phi == rhs.phi)) { - ivarsEqual = false; - } - if (!(entityAppearance == rhs.entityAppearance)) { - ivarsEqual = false; - } - if (!(deadReckoningAlgorithm == rhs.deadReckoningAlgorithm)) { - ivarsEqual = false; - } - - for (int idx = 0; idx < 15; idx++) { - if (!(otherParameters[idx] == rhs.otherParameters[idx])) { - ivarsEqual = false; - } - } - - if (!(xAcceleration == rhs.xAcceleration)) { - ivarsEqual = false; - } - if (!(yAcceleration == rhs.yAcceleration)) { - ivarsEqual = false; - } - if (!(zAcceleration == rhs.zAcceleration)) { - ivarsEqual = false; - } - if (!(xAngularVelocity == rhs.xAngularVelocity)) { - ivarsEqual = false; - } - if (!(yAngularVelocity == rhs.yAngularVelocity)) { - ivarsEqual = false; - } - if (!(zAngularVelocity == rhs.zAngularVelocity)) { - ivarsEqual = false; - } - - for (int idx = 0; idx < 12; idx++) { - if (!(marking[idx] == rhs.marking[idx])) { - ivarsEqual = false; - } - } - - if (!(capabilities == rhs.capabilities)) { - ivarsEqual = false; - } - - for (int idx = 0; idx < variableParameters.size(); idx++) { - if (!(variableParameters.get(idx).equals(rhs.variableParameters.get(idx)))) { - ivarsEqual = false; - } - } - - return ivarsEqual && super.equalsImpl(rhs); - } -} // end of class diff --git a/src/main/java/edu/nps/moves/dis7/PduFactory.java b/src/main/java/edu/nps/moves/dis7/PduFactory.java index a205a383..aea06874 100644 --- a/src/main/java/edu/nps/moves/dis7/PduFactory.java +++ b/src/main/java/edu/nps/moves/dis7/PduFactory.java @@ -24,7 +24,6 @@ import edu.nps.moves.dis7.EntityStateUpdatePdu; import edu.nps.moves.dis7.EventReportPdu; import edu.nps.moves.dis7.EventReportReliablePdu; -import edu.nps.moves.dis7.FastEntityStatePdu; import edu.nps.moves.dis7.FirePdu; import edu.nps.moves.dis7.IntercomControlPdu; import edu.nps.moves.dis7.IntercomSignalPdu; @@ -64,28 +63,13 @@ public class PduFactory { - private boolean useFastPdu; private Logger logger; public PduFactory() { - this(false); - } - - public PduFactory(boolean useFastPdu) { - this.useFastPdu = false; - this.useFastPdu = useFastPdu; this.logger = Logger.getLogger(edu.nps.moves.disutil.PduFactory.class.getName()); this.logger.setLevel(Level.OFF); } - public boolean getUseFastPdu() { - return this.useFastPdu; - } - - public void setUseFastPdu(boolean use) { - this.useFastPdu = use; - } - public void setLoggingLevel(Level loggingLevel) { this.logger.setLevel(loggingLevel); } @@ -106,11 +90,7 @@ public Pdu createPdu(ByteBuffer buff) { Pdu aPdu = null; switch (pduTypeEnum) { case ENTITY_STATE: - if (this.useFastPdu) { - aPdu = new FastEntityStatePdu(); - } else { - aPdu = new EntityStatePdu(); - } + aPdu = new EntityStatePdu(); break; case FIRE: aPdu = new FirePdu(); diff --git a/src/main/java/edu/nps/moves/disutil/ByteBufferPool.java b/src/main/java/edu/nps/moves/disutil/ByteBufferPool.java deleted file mode 100644 index dba9af48..00000000 --- a/src/main/java/edu/nps/moves/disutil/ByteBufferPool.java +++ /dev/null @@ -1,69 +0,0 @@ - -package edu.nps.moves.disutil; - -import java.nio.*; -import java.util.*; - -/** - * A pool that holds ByteBuffer objects.

- * - * We'd like to reuse buffers for sending, but this is tricky because the - * Java NIO byte buffers can't expand. So if we try to marshal a PDU that is - * 144 bytes long and one that is 800 bytes long, we'd always need a byte - * buffer that is 800 bytes long. - * - * This has some obvious problems if we generate 2000 byte buffer objects, which - * will have a big memory footprint that won't be GC'd. If this turns out to be - * a problem--I suspect not, right now--we can implement some sort of clear() - * operation to wipe out the pool once some criteria is met.

- * - * Instances of this class are defitnely not thread-safe. If you have two threads, - * you should have a ByteBufferPool for each thread to ensure that the same byte buffer - * from the pool isn't being used by two threads. - * - * @author DMcG - */ -@Deprecated -public class ByteBufferPool -{ - - private HashMap pool; - - - public ByteBufferPool() - { - pool = new HashMap(); - } - - /** - * Returns a byte buffer from the pool that has the given length. - * If there is not ByteBuffer with that length, it is created and - * added to the pool. - * - * @param length - * @return The byte buffer with the given length - */ - public ByteBuffer getByteBufferOfLength(int length) - { - ByteBuffer bbuf = pool.get(new Integer(length)); - - if(bbuf == null) - { - byte[] backingStore = new byte[length]; - bbuf = ByteBuffer.wrap(backingStore); - pool.put(new Integer(length), bbuf); - } - - return bbuf; - } - - /** - * Removes all the byte buffers from the pool, allowing them to - * be GC'd. - */ - public void clear() - { - pool.clear(); - } - -} diff --git a/src/main/java/edu/nps/moves/disutil/CoordinateTransformer.java b/src/main/java/edu/nps/moves/disutil/CoordinateTransformer.java deleted file mode 100644 index 06ee5fe1..00000000 --- a/src/main/java/edu/nps/moves/disutil/CoordinateTransformer.java +++ /dev/null @@ -1,38 +0,0 @@ - - -package edu.nps.moves.disutil; - -import edu.nps.moves.dis.Vector3Double; -import edu.nps.moves.dis.Vector3Float; - -/** - * Abstract superclass for doing global coordinate transforms. Given a Vector3Double - * that specifies the location of an entity in the world, transforms it from a given - * initial coordinate system (such as lat/lon/altitude, or x/y/altitude) to another - * coordinate system, such as DIS earth-centered. This transformation is carried out - * in the concrete subclass. - * - * Ideally you want to translate into DIS standard coordinates, but not everyone - * actually uses that, so I'm agnostic about whether you want to follow the - * standard. If you want to write a transform that puts lat/lon on the wire, that's - * up to you. - * - * @author DMcG - */ -@Deprecated -public abstract class CoordinateTransformer -{ - /** Changes the coordinate system of the input coordinates to the target. - * - * @param source - */ - public abstract void transformLocation(Vector3Double source); - - /** - * Transforms the euler angles from the source to the destination coordinate - * system. - * @param source - */ - public abstract void transformOrientation(Vector3Float source); - -} diff --git a/src/main/java/edu/nps/moves/disutil/DisMarshaller.java b/src/main/java/edu/nps/moves/disutil/DisMarshaller.java deleted file mode 100644 index 45a4c03c..00000000 --- a/src/main/java/edu/nps/moves/disutil/DisMarshaller.java +++ /dev/null @@ -1,86 +0,0 @@ - -package edu.nps.moves.disutil; - -import edu.nps.moves.dis.*; - -/** - * Marhsalls a Java object PDU to IEEE DIS, optionally changing coordinate systems - * of some PDUs to conform to the desired coordinate system. - * - * DIS has a standard coordiante system; its origin is a the center of the - * earth and it is cartesian. It's very difficult for casual programmers to work - * with, though. Often simulators want to specify object locations in (lat, lon, altitude) - * or (x,y) offset from some position on the surface of the earth. Also, the timestamp - * updates are not always easy to work with. In short, there are some fields in the - * PDUs whose values are not easily set, but that nonetheless need to be correctly - * specified. This class accoplishes that. - * - * The class can rewrite the coordinates used for position in PDUs to conform to - * the DIS standard, or someother agreed-upon standard. Fields such as the - * timestamp or exercise ID can also be set--in short, it can look over the - * shoulder of the programmer and set the fields correctly even if the programmer - * doesn't. As with any effort of this type, the line betwen being helpful and - * being annoying is a fine one. - * - * @author DMcG - */ -@Deprecated -public class DisMarshaller -{ - /** The various formats we can use for the timestamp format in the PDU header when marshalled */ - public enum TimestampStyle { IEEE_ABSOLUTE, IEEE_RELATIVE, NPS}; - - - /** Class that performs coordinate transformations */ - private CoordinateTransformer coordinateTransformer; - private boolean doCoordinateTransform = false; - - /** The exercise ID, which is in the header */ - private short exerciseId = 0; - private boolean doExerciseId = false; - - /** We can marshal the PDU with a timestamp set to any of several styles. Remember, you - * pretty much MUST set a timestamp; DIS will regard multiple packets sent with the - * same timestamp as duplicates and may discard them. - */ - private TimestampStyle timestampStyle; - private boolean doTimestamp = false; - - - public byte[] marshalPdu(Pdu aPdu) - { - // Should we rewrite the timestamp field? - if(doTimestamp) - { - this.rewriteTimestamp(aPdu); - } - - // Should we set the exercise ID when we send? - if(doExerciseId) - { - aPdu.setExerciseID(exerciseId); - } - - // - - return null; - } - - private void rewriteTimestamp(Pdu aPdu) - { - switch(timestampStyle) - { - case IEEE_ABSOLUTE: - break; - - case IEEE_RELATIVE: - break; - - case NPS: - break; - - default: - break; - } - } -} diff --git a/src/main/java/edu/nps/moves/disutil/NioServer.java b/src/main/java/edu/nps/moves/disutil/NioServer.java deleted file mode 100644 index e138ca1f..00000000 --- a/src/main/java/edu/nps/moves/disutil/NioServer.java +++ /dev/null @@ -1,1634 +0,0 @@ -package edu.nps.moves.disutil; - - -import java.util.concurrent.*; -import java.nio.channels.*; -import java.util.logging.*; -import java.beans.*; -import java.util.*; -import java.nio.*; -import java.net.*; -import java.io.*; -import java.lang.reflect.Constructor; -import java.lang.reflect.Field; -import java.lang.reflect.Method; - - - -/** - *

A robust class for establishing simultaneous TCP and UDP servers and manipulating - * their listening ports. - * The {@link Event}s and property change events make - * it an appropriate tool in a threaded, GUI application. - * It is almost identical in design to the UdpServer and TcpServer classes that - * should have accompanied this class when you downloaded it.

- * - *

To start a server, create a new NioServer and call start():

- * - *
 NioServer server = new NioServer();
- * server.start();
- * - *

You'll want to bind to a port or two:

- * - *
 server.addTcpBinding( new InetSocketAddress( 80 ) );
- * server.addUdpBinding( new InetSocketAddress( 80 ) );
- * - *

Of course it won't be much help unless you register as a listener - * so you'll know when data has come in:

- * - *
 server.addNioServerListener( new NioServer.Adapter(){
- *     public void nioServerTcpDataReceived( NioServer.Event evt ){
- *         ByteBuffer buff = evt.getBuffer();
- *         ...
- *     }   // end data received
- *
- *     public void nioServerUdpDataReceived( NioServer.Event evt ){
- *         ByteBuffer buff = evt.getBuffer();
- *         ...
- *     }   // end data received
- * });
- * - *

The server runs on one thread, and all events are fired on that thread. - * Consider offloading heavy processing to another thread. Be aware that - * you can register multiple listeners to respond to incoming data - * so be mindful of more than one listener being around to makes calls - * on the data.

- * - *

The public methods are all synchronized on this, and great - * care has been taken to avoid deadlocks and race conditions. That being said, - * there may still be bugs (please contact the author if you find any), and - * you certainly still have the power to introduce these problems yourself.

- * - *

It's often handy to have your own class extend this one rather than - * making an instance field to hold a NioServer where you'd have to - * pass along all the setPort(...) methods and so forth.

- * - *

The supporting {@link Event}, {@link Listener}, and {@link Adapter} - * classes are static inner classes in this file so that you have only one - * file to copy to your project. You're welcome.

- * - *

Since the TcpServer.java, UdpServer.java, and NioServer.java are - * so similar, and since lots of copying and pasting was going on among them, - * you may find some comments that refer to TCP instead of UDP or vice versa. - * Please feel free to let me know, so I can correct that.

- * - *

This code is released into the Public Domain. - * Since this is Public Domain, you don't need to worry about - * licensing, and you can simply copy this NioServer.java file - * to your own package and use it as you like. Enjoy. - * Please consider leaving the following statement here in this code:

- * - *

This NioServer class was copied to this project from its source as - * found at iHarder.net.

- * - * @author Robert Harder - * @author rharder@users.sourceforge.net - * @version 0.1 - * @see NioServer - * @see Adapter - * @see Event - * @see Listener - */ -@Deprecated -public class NioServer { - - /** Standard Java logger. */ - private final static Logger LOGGER = Logger.getLogger(NioServer.class.getName()); - - - /** The buffer size property. */ - public final static String BUFFER_SIZE_PROP = "bufferSize"; - private final static int BUFFER_SIZE_DEFAULT = 4096; - private int bufferSize = BUFFER_SIZE_DEFAULT; - - - /** - *

One of four possible states for the server to be in:

- * - * - */ - public static enum State { STARTING, STARTED, STOPPING, STOPPED }; - private State currentState = State.STOPPED; - public final static String STATE_PROP = "state"; - - - public final static String LAST_EXCEPTION_PROP = "lastException"; - private Throwable lastException; - - - private final Collection listeners = new LinkedList(); // Event listeners - private NioServer.Listener[] cachedListeners = null; - private final NioServer.Event event = new NioServer.Event(this); // Shared event - private final PropertyChangeSupport propSupport = new PropertyChangeSupport(this); // Properties - - private ThreadFactory threadFactory; // Optional thread factory - private Thread ioThread; // Performs IO - private Selector selector; // Brokers all the connections - - public final static String TCP_BINDINGS_PROP = "tcpBindings"; - public final static String UDP_BINDINGS_PROP = "udpBindings"; - public final static String SINGLE_TCP_PORT_PROP = "singleTcpPort"; - public final static String SINGLE_UDP_PORT_PROP = "singleUdpPort"; - - private final Map tcpBindings = new HashMap();// Requested TCP bindings, e.g., "listen on port 80" - private final Map udpBindings = new HashMap();// Requested UDP bindings - - private final Map multicastGroups = new HashMap(); - - private final Set pendingTcpAdds = new HashSet(); // TCP bindings to add to selector on next cycle - private final Set pendingUdpAdds = new HashSet(); // UDP bindings to add to selector on next cycle - - private final Map pendingTcpRemoves = new HashMap(); // TCP bindings to remove from selector on next cycle - private final Map pendingUdpRemoves = new HashMap(); // UDP bindings to remove from selector on next cycle - - private final Map leftoverData = new HashMap(); // Store leftovers here instead of key.attachment() - -/* ******** C O N S T R U C T O R S ******** */ - - - /** - * Constructs a new NioServer, listening to nothing, and not started. - */ - public NioServer(){ - } - - /** - * Constructs a new NioServer, listening to nothing, and not started. - * The provided - * ThreadFactory will be used when starting and running the server. - * @param factory the ThreadFactory to use when starting the server - */ - public NioServer( ThreadFactory factory ){ - this.threadFactory = factory; - } - - - - -/* ******** R U N N I N G ******** */ - - - /** - * Attempts to start the server listening and returns immediately. - * Listen for start events to know if the server was - * successfully started. - * - * @see Listener - */ - public synchronized void start(){ - if( this.currentState == State.STOPPED ){ // Only if we're stopped now - assert ioThread == null : ioThread; // Shouldn't have a thread - - Runnable run = new Runnable() { - public void run() { - runServer(); // This runs for a long time - ioThread = null; - setState( State.STOPPED ); // Clear thread - } // end run - }; // end runnable - - if( this.threadFactory != null ){ // User-specified threads - this.ioThread = this.threadFactory.newThread(run); - - } else { // Our own threads - this.ioThread = new Thread( run, this.getClass().getName() ); // Named - } - - setState( State.STARTING ); // Update state - this.ioThread.start(); // Start thread - } // end if: currently stopped - } // end start - - - /** - * Attempts to stop the server, if the server is in - * the STARTED state, and returns immediately. - * Be sure to listen for stop events to know if the server was - * successfully stopped. - * - * @see Listener - */ - public synchronized void stop(){ - if( this.currentState == State.STARTED || this.currentState == State.STARTING ){ // Only if already STARTED - setState( State.STOPPING ); // Mark as STOPPING - if( this.selector != null ){ - try{ - Set keys = this.selector.keys(); - for( SelectionKey key : this.selector.keys() ){ - key.channel().close(); - key.cancel(); - } - this.selector.close(); - } catch( IOException exc ){ - fireExceptionNotification(exc); - LOGGER.log( - Level.SEVERE, - "An error occurred while closing the server. " + - "This may have left the server in an undefined state.", - exc ); - } - } // end if: not null - } // end if: already STARTED - } // end stop - - - - - /** - * Returns the current state of the server, one of - * STOPPED, STARTING, or STARTED. - * @return state of the server - */ - public synchronized State getState(){ - return this.currentState; - } - - - /** - * Sets the state and fires an event. This method - * does not change what the server is doing, only - * what is reflected by the currentState variable. - * @param state the new state of the server - */ - protected synchronized void setState( State state ){ - State oldVal = this.currentState; - this.currentState = state; - firePropertyChange(STATE_PROP, oldVal, state); - } - - - /** - * Resets the server, if it is running, otherwise does nothing. - * This is accomplished by registering as a listener, stopping - * the server, detecting the stop, unregistering, and starting - * the server again. It's a useful design pattern, and you may - * want to look at the source code for this method to check it out. - */ - public synchronized void reset(){ - switch( this.currentState ){ - case STARTED: - this.addPropertyChangeListener(STATE_PROP, new PropertyChangeListener() { - public void propertyChange(PropertyChangeEvent evt) { - State newState = (State)evt.getNewValue(); - if( newState == State.STOPPED ){ - NioServer server = (NioServer)evt.getSource(); - server.removePropertyChangeListener(STATE_PROP,this); - server.start(); - } // end if: stopped - } // end prop change - }); - stop(); - break; - } // end switch - } - - - /** - * This method starts up and listens indefinitely - * for TCP packets. On entering this method, - * the state is assumed to be STARTING. Upon exiting - * this method, the state will be STOPPING. - */ - protected void runServer(){ - try{ - ByteBuffer buff = ByteBuffer.allocateDirect(this.bufferSize); - - // Add all the requested TCP and UDP bindings to the "pending" lists - synchronized( this ){ - this.selector = Selector.open(); - this.pendingTcpAdds.clear(); - this.pendingTcpAdds.addAll(this.tcpBindings.keySet()); - this.pendingUdpAdds.clear(); - this.pendingUdpAdds.addAll(this.udpBindings.keySet()); - this.pendingTcpRemoves.clear(); - this.pendingTcpRemoves.clear(); - } - - setState( State.STARTED ); // Mark as started - while( this.selector.isOpen() ){ - - // Check to see if the server is supposed to be stopping - synchronized( this ){ - if( this.currentState == State.STOPPING ){ - LOGGER.finer( "Stopping server by request." ); - this.selector.close(); - continue; - } // end if: stopping - } // end sync - - - // Add and remove pending bindings - synchronized( this ){ - - // Pending TCP Adds - for( SocketAddress addr : this.pendingTcpAdds ){ // For each add - LOGGER.fine("Binding TCP: " + addr ); - ServerSocketChannel sc = ServerSocketChannel.open(); // Open a channel - sc.socket().bind(addr); // Bind as requested - sc.configureBlocking(false); // Make non-blocking - SelectionKey acceptKey = sc.register( // Register with master Selector - this.selector, SelectionKey.OP_ACCEPT ); // We want to "accept" connections - this.tcpBindings.put(addr, acceptKey); // Save the key - } // end for: each address - this.pendingTcpAdds.clear(); // Remove list of pending adds - - // Pending UDP Adds - for( SocketAddress addr : this.pendingUdpAdds ){ // Same comments as for TCP - LOGGER.fine("Binding UDP: " + addr ); - DatagramChannel dc = DatagramChannel.open(); - dc.socket().bind(addr); - dc.configureBlocking(false); - SelectionKey acceptKey = dc.register( - this.selector, SelectionKey.OP_READ ); - this.udpBindings.put(addr, acceptKey); - - - // Found a weird hack to support multicast -- at least for now. - String group = this.multicastGroups.get(addr); - if( group != null && addr instanceof InetSocketAddress ){ - int port = ((InetSocketAddress)addr).getPort(); - InetSocketAddress groupAddr = new InetSocketAddress(group,port); - if( groupAddr.getAddress().isMulticastAddress() ){ - - // http://www.mernst.org/blog/archives/12-01-2006_12-31-2006.html - // UGLY UGLY HACK: multicast support for NIO - // create a temporary instanceof PlainDatagramSocket, set its fd and configure it - @SuppressWarnings("unchecked") - Constructor c = - (Constructor) - Class.forName("java.net.PlainDatagramSocketImpl").getDeclaredConstructor(); - c.setAccessible(true); - DatagramSocketImpl socketImpl = c.newInstance(); - - Field channelFd = Class.forName("sun.nio.ch.DatagramChannelImpl").getDeclaredField("fd"); - channelFd.setAccessible(true); - - Field socketFd = DatagramSocketImpl.class.getDeclaredField("fd"); - socketFd.setAccessible(true); - socketFd.set(socketImpl, channelFd.get(dc)); - - try { - Method m = DatagramSocketImpl.class.getDeclaredMethod("joinGroup", SocketAddress.class, NetworkInterface.class); - //Method m = DatagramSocketImpl.class.getDeclaredMethod("joinGroup", InetAddress.class ); - m.setAccessible(true); - m.invoke(socketImpl, groupAddr, null ); - }catch(Exception e){ - e.printStackTrace(); - } - finally { - // important, otherwise the fake socket's finalizer will nuke the fd - socketFd.set(socketImpl, null); - } - - } // end if: multicast - else{ - LOGGER.warning("Could not join non-multicast group: " + group); - } - } // end if: got group - - - - - } // end for: each address - this.pendingUdpAdds.clear(); - - // Pending TCP Removes - for( Map.Entry e : this.pendingTcpRemoves.entrySet() ){ - SelectionKey key = e.getValue(); // Get the registered key - if( key != null ){ // Might be null if someone gave us bogus address - key.channel().close(); // Close the channel - key.cancel(); // And cancel the key (redundant?) - } // end if: key != null - } // end for: each remove - this.pendingTcpRemoves.clear(); // Remove from list of pending removes - - - // Pending UDP Removes - for( Map.Entry e : this.pendingUdpRemoves.entrySet() ){ - SelectionKey key = e.getValue(); // Get the registered key - if( key != null ){ // Might be null if someone gave us bogus address - key.channel().close(); // Close the channel - key.cancel(); // And cancel the key (redundant?) - } // end if: key != null - } // end for: each remove - this.pendingUdpRemoves.clear(); // Remove from list of pending removes - - } // end sync: this - - // - // The meat of the matter begins now - // - - //////// B L O C K S H E R E - if( this.selector.select() <= 0 ){ // Block until notified - LOGGER.finer("selector.select() <= 0"); // Possible false start - Thread.sleep(100); // Let's not run away from ourselves - }/////// B L O C K S H E R E - - - // Possibly resize buffer if a change was requested since last cycle - if( this.bufferSize != buff.capacity() ){ // Mismatch size means someone asked for something new - assert this.bufferSize >= 0 : this.bufferSize; // We check for this in setBufferSize(..) - buff = ByteBuffer.allocateDirect(this.bufferSize); // Resize and use direct for OS efficiencies - } - - Set keys = this.selector.selectedKeys(); // These keys need attention - if( LOGGER.isLoggable(Level.FINEST ) ){ // Only report this at finest grained logging level - LOGGER.finest("Keys: " + keys ); // Which keys are being examined this round - } - - Iterator iter = keys.iterator(); // Iterate over keys -- cannot use "for" loop since we remove keys - while( iter.hasNext() ){ // Each key - SelectionKey key = iter.next(); // The key - iter.remove(); // Remove from list - - // Accept connections - // This should only be from the TCP bindings - if( key.isAcceptable() ){ // New, incoming connection? - handleAccept( key ); // Handle accepting connections - } - - // Data to read - // This could be an ongoing TCP connection - // or a new (is there any other kind) UDP datagram - else if( key.isReadable() ){ // Existing connection has data (or is closing) - handleRead( key, buff ); // Handle data - } // end if: readable - - } // end while: keys - - } // end while: selector is open - - } catch( Exception exc ){ - synchronized( this ){ - if( this.currentState == State.STOPPING ){ // User asked to stop - try{ - this.selector.close(); - LOGGER.info( "Server closed normally." ); - } catch( IOException exc2 ){ - this.lastException = exc2; - LOGGER.log( - Level.SEVERE, - "An error occurred while closing the server. " + - "This may have left the server in an undefined state.", - exc2 ); - fireExceptionNotification(exc2); - } // end catch IOException - } else { - LOGGER.log( Level.WARNING, "Server closed unexpectedly: " + exc.getMessage(), exc ); - } // end else - } // end sync - fireExceptionNotification(exc); - } finally { - setState( State.STOPPING ); - if( this.selector != null ){ - try{ - this.selector.close(); - LOGGER.info( "Server closed normally." ); - } catch( IOException exc2 ){ - LOGGER.log( - Level.SEVERE, - "An error occurred while closing the server. " + - "This may have left the server in an undefined state.", - exc2 ); - fireExceptionNotification(exc2); - } // end catch IOException - } // end if: not null - this.selector = null; - } // end finally - } - - - /** - * Handles accepting new connections. - * @param key The OP_ACCEPT key - * @throws IOException - */ - private void handleAccept( SelectionKey key ) throws IOException{ - assert key.isAcceptable() : key.readyOps(); // We know it should be acceptable - assert selector.isOpen(); // Not sure this matters. Meh. - - SelectableChannel sc = key.channel(); // Channel for th key - assert sc instanceof ServerSocketChannel : sc; // Only our TCP connections have OP_ACCEPT -// if( sc instanceof ServerSocketChannel ){ - - ServerSocketChannel ch = (ServerSocketChannel)key.channel(); // Server channel - SocketChannel incoming = null; // Reusable for all pending connections - while( (incoming = ch.accept()) != null ){ // Iterate over all pending connections - incoming.configureBlocking(false); // Non-blocking IO - SelectionKey incomingReadKey = incoming.register( // Register new connection - this.selector, // With the Selector - SelectionKey.OP_READ);//, // Want to READ data - //(ByteBuffer)ByteBuffer.allocateDirect(128).flip() ); // Will store leftover data between read ops - - fireNewConnection(incomingReadKey); - - if( LOGGER.isLoggable(Level.FINEST) ){ - LOGGER.finest(" " + incoming + ", key: " + incomingReadKey ); - } - } // end while: each incoming connection - - } - - /** - * Handles reading incoming data and then firing events. - * @param key The key associated with the reading - * @param buff the ByteBuffer to hold the data - * @throws IOException - */ - private void handleRead(SelectionKey key, ByteBuffer buff ) throws IOException { - - SelectableChannel sc = key.channel(); - buff.clear(); // Clear input buffer - - // TCP - if( sc instanceof SocketChannel ){ - - SocketChannel client = (SocketChannel) key.channel(); // Source socket - ByteBuffer leftover = this.leftoverData.get(key); // Leftover data from last read - - if( leftover != null && leftover.remaining() > 0 ){ // Have a leftover buffer - buff.put(leftover); // Preload leftovers - } // end if: have leftover buffer - - // Read into the buffer here - // If End of Stream - if( client.read(buff) == -1 ){ // End of stream? - key.cancel(); // Cancel the key - client.close(); // And cancel the client - fireConnectionClosed(key); // Fire event for connection closed - this.leftoverData.remove(key); // Remove any leftover data - if( LOGGER.isLoggable(Level.FINER) ){ - LOGGER.finer("Connection closed: " + key ); - } - - } else { - // Not End of Stream - buff.flip(); // Flip the buffer to prepare to read - fireTcpDataReceived(key,buff); // Fire event for new data - - if( buff.remaining() > 0 ){ // Did the user leave data for next time? - if( leftover == null || // Leftover buffer not yet created? - buff.remaining() > leftover.capacity() ){ // Or is too small? - leftover = ByteBuffer.allocateDirect(buff.remaining()); // Create/resize - } // end if: need to resize - leftover.clear(); // Clear old leftovers - leftover.put(buff).flip(); // Save new leftovers - } // end if: has remaining bytes - this.leftoverData.put(key,leftover); // Save leftovers for next time - } // end else: read - } // end if: SocketChannel - - // Datagram - else if( sc instanceof DatagramChannel ){ - DatagramChannel dc = (DatagramChannel)sc; // Cast to datagram channel - SocketAddress remote = null; - while( (remote = dc.receive(buff)) != null ){ // Loop over all pending datagrams - buff.flip(); // Flip after reading in - key.attach( buff ); // Attach buffer to key - fireUdpDataReceived(key,buff,remote); // Fire event - } // end while: each pending datagram - } // end else: UDP - - } // end handleRead - - - - - - - -/* ******** B U F F E R S I Z E ******** */ - - /** - * Returns the size of the ByteBuffer used to read - * from the connections. This refers to the buffer - * that will be passed along with {@link Event} - * objects as data is received and so forth. - * @return The size of the ByteBuffer - */ - public synchronized int getBufferSize(){ - return this.bufferSize; - } - - /** - * Sets the size of the ByteBuffer used to read - * from the connections. This refers to the buffer - * that will be passed along with {@link Event} - * objects as data is received and so forth. - * @param size The size of the ByteBuffer - */ - public synchronized void setBufferSize( int size ){ - if( size <= 0 ){ - throw new IllegalArgumentException( "New buffer size must be positive: " + size ); - } // end if: size outside range - - int oldVal = this.bufferSize; - this.bufferSize = size; - this.selector.wakeup(); - - firePropertyChange( BUFFER_SIZE_PROP, oldVal, size ); - } - -/* ******** T C P B I N D I N G S ******** */ - - - - /** - * Adds a TCP binding to the server. Effectively this is how you - * set which ports and on which interfaces you want the server - * to listen. In the simplest case, you might do the following - * to listen generically on port 80: - * addTcpBinding( new InetAddress(80) );. - * The server can listen on multiple ports at once. - * @param addr The address on which to listen - * @return "this" to aid in chaining commands - */ - public synchronized NioServer addTcpBinding( SocketAddress addr ){ - Set oldVal = this.getTcpBindings(); // Save old set for prop change event - this.tcpBindings.put(addr,null); // Add binding - Set newVal = this.getTcpBindings(); // Save new set for prop change event - this.pendingTcpAdds.add(addr); // Prepare pending add action - this.pendingTcpRemoves.remove(addr); // In case it's also pending a remove - - if( this.selector != null ){ // If there's a selector... - this.selector.wakeup(); // Wake it up to handle the add action - } - firePropertyChange(TCP_BINDINGS_PROP, oldVal, newVal); // Fire prop change - return this; - } - - - - /** - * Removes a TCP binding. Effectively stops the server from - * listening to this or that port. - * @param addr The address to stop listening to - * @return "this" to aid in chaining commands - */ - public synchronized NioServer removeTcpBinding( SocketAddress addr ){ - Set oldVal = this.getTcpBindings(); // Save old set for prop change event - this.pendingTcpRemoves.put( addr, this.tcpBindings.get(addr) ); // Prepare pending remove action - this.tcpBindings.remove(addr); // Remove binding - this.pendingTcpAdds.remove(addr); // In case it's also pending an add - Set newVal = this.getTcpBindings(); // Save new set for prop change event - - if( this.selector != null ){ // If there's a selector... - this.selector.wakeup(); // Wake it up to handle the remove action - } - firePropertyChange(TCP_BINDINGS_PROP, oldVal, newVal); // Fire prop change - return this; - } - - - - /** - * Returns a set of socket addresses that the server is (or will - * be when started) bound to/listening on. This set is not - * backed by the actual data structures. Changes to this returned - * set have no effect on the server. - * @return set of tcp listening points - */ - public synchronized Set getTcpBindings(){ - Set bindings = new HashSet(); - bindings.addAll( this.tcpBindings.keySet() ); - return bindings; - } - - - /** - *

Sets the TCP bindings that the server should use. - * The expression setTcpBindings( getTcpBindings() ) - * should result in no change to the server.

- * @param newSet - * @return "this" to aid in chaining commands - */ - public synchronized NioServer setTcpBindings( Set newSet ){ - Set toAdd = new HashSet(); - Set toRemove = new HashSet(); - - toRemove.addAll( getTcpBindings() ); - for( SocketAddress addr : newSet ){ - if( toRemove.contains(addr) ){ - toRemove.remove(addr); - } else { - toAdd.add(addr); - } - } // end for: each new addr - - - for( SocketAddress addr : toRemove ){ - removeTcpBinding(addr); - } // end for: each new addr - - for( SocketAddress addr : toAdd ){ - addTcpBinding(addr); - } // end for: each new addr - - return this; - } - - - - /** - * Clears all TCP bindings. - * @return "this" to aid in chaining commands - */ - public synchronized NioServer clearTcpBindings(){ - for( SocketAddress addr : getTcpBindings() ){ - removeTcpBinding(addr); - } - return this; - } - - -/* ******** U D P B I N D I N G S ******** */ - - - /** - * Adds a UDP binding to the server. Effectively this is how you - * set which ports and on which interfaces you want the server - * to listen. In the simplest case, you might do the following - * to listen generically on port 6997: - * addUdpBinding( new InetAddress(6997) );. - * The server can listen on multiple ports at once. - * @param addr The address on which to listen - * @return "this" to aid in chaining commands - */ - public synchronized NioServer addUdpBinding( SocketAddress addr ){ - return addUdpBinding(addr,null); - } - - - /** - *

Experimental Hack - Adds a UDP binding to the server - * and joins the given multicast group (if group - * is not null and is a valid multicast group). - * In the simplest case, you might do the following - * to listen on port 16000 and multicast group 239.0.0.1: - * addUdpBinding( new InetAddress(16000), "239.0.0.1" );. - * The server can listen on multiple ports at once.

- * - *

As of Java 6, the java.nio "New IO" packages - * don't support multicast groups ("annoyed grunt"), however I - * found a clever hack at this gentleman's website - * (http://www.mernst.org/blog/archives/12-01-2006_12-31-2006.html) - * that makes multicast work -- for now.

- * - * @param addr The address on which to listen - * @param group The multicast group to join - * @return "this" to aid in chaining commands - */ - public synchronized NioServer addUdpBinding( SocketAddress addr, String group ){ - Map oldVal = this.getUdpBindings(); - this.udpBindings.put(addr,null); - this.pendingUdpAdds.add(addr); - this.pendingUdpRemoves.remove(addr); - if( group != null ){ - this.multicastGroups.put(addr,group); - } // end if: multicast too - Map newVal = this.getUdpBindings(); - if( this.selector != null ){ - this.selector.wakeup(); - } - firePropertyChange(UDP_BINDINGS_PROP,oldVal,newVal); - return this; - } - - - - - /** - * Removes a UDP binding. Effectively stops the server from - * listening to this or that port. - * @param addr The address to stop listening to - * @return "this" to aid in chaining commands - */ - public synchronized NioServer removeUdpBinding( SocketAddress addr ){ - Map oldVal = this.getUdpBindings(); // Save old set for prop change event - this.pendingUdpRemoves.put( addr, this.udpBindings.get(addr) ); // Prepare pending remove action - this.udpBindings.remove(addr); // Remove binding - this.multicastGroups.remove(addr); // Remove multicast note - this.pendingUdpAdds.remove(addr); // In case it's also pending an add - Map newVal = this.getUdpBindings(); // Save new set for prop change event - - if( this.selector != null ){ // If there's a selector... - this.selector.wakeup(); // Wake it up to handle the remove action - } - firePropertyChange(UDP_BINDINGS_PROP, oldVal, newVal); // Fire prop change - return this; - } - - - - /** - * Returns a map of socket addresses and multicast groups - * that the server is (or will - * be when started) bound to/listening on. This set is not - * backed by the actual data structures. Changes to this returned - * set have no effect on the server. - * The map's value portion will be null if not multicast group - * is joined for that port or it may have a String which would - * be the requested multicast group. - * @return map of udp listening points - */ - public synchronized Map getUdpBindings(){ - Mapbindings = new HashMap(); - for( SocketAddress addr : this.udpBindings.keySet() ){ - bindings.put(addr, this.multicastGroups.get(addr) ); - } // end for: each address - return bindings; - } - - - - /** - *

Sets the UDP bindings that the server should use. - * The expression setTcpBindings( getTcpBindings() ) - * should result in no change to the server.

- * - *

The map consists of socket addresses (probably InetSocketAddress) - * and multicast addresses (the String value).

- * @param newMap - * @return "this" to aid in chaining commands - */ - public synchronized NioServer setUdpBindings( Map newMap ){ - Map toAdd = new HashMap(); - Map toRemove = new HashMap(); - - toRemove.putAll( getUdpBindings() ); - for( Map.Entry e : newMap.entrySet() ){ - SocketAddress addr = e.getKey(); - String group = e.getValue(); - if( toRemove.containsKey(addr) ){ - toRemove.remove(addr); - } else { - toAdd.put(addr,group); - } - } // end for: each new addr - - - for( Map.Entry e : toRemove.entrySet() ){ - removeUdpBinding(e.getKey()); - } // end for: each new addr - - for( Map.Entry e : toAdd.entrySet() ){ - addUdpBinding(e.getKey(),e.getValue()); - } // end for: each new addr - - return this; - } - - - /** - * Clears all UDP bindings. - * @return "this" to aid in chaining commands - */ - public synchronized NioServer clearUdpBindings(){ - for( SocketAddress addr : getUdpBindings().keySet() ){ - removeUdpBinding(addr); - } - return this; - } - - -/* ******** S I N G L E P O R T ******** */ - - - - /** - * Convenience method for clearing all bindings and - * setting up listening for TCP on the given port. - * @param port the port to listen to - * @return this to aid in chaining - */ - public synchronized NioServer setSingleTcpPort( int port ){ - int oldVal = getSingleTcpPort(); - if( oldVal == port ){ - return this; - } - clearTcpBindings(); - addTcpBinding( new InetSocketAddress(port) ); - int newVal = port; - firePropertyChange( SINGLE_TCP_PORT_PROP, oldVal, newVal ); - return this; - } - - - /** - * Convenience method for clearing all bindings and - * setting up listening for UDP on the given port. - * @param port the port to listen to - * @return this to aid in chaining - */ - public synchronized NioServer setSingleUdpPort( int port ){ - return setSingleUdpPort( port, null ); - } - - - - /** - * Convenience method for clearing all bindings and - * setting up listening for UDP on the given port - * and joining the provided multicast group. - * @param port the port to listen to - * @param group - * @return this to aid in chaining - */ - public synchronized NioServer setSingleUdpPort( int port, String group ){ - int oldVal = getSingleUdpPort(); - if( oldVal == port ){ - return this; - } - clearUdpBindings(); - addUdpBinding( new InetSocketAddress(port), group ); - int newVal = port; - firePropertyChange( SINGLE_UDP_PORT_PROP, oldVal, newVal ); - return this; - } - - - - /** - * Returns the port for the single TCP binding in effect, - * or -1 (minus one) if there are no or multiple TCP - * bindings or some other error. - * @return TCP listening port or -1 - */ - public synchronized int getSingleTcpPort(){ - int port = -1; - Set bindings = getTcpBindings(); - if( bindings.size() == 1 ){ - SocketAddress sa = bindings.iterator().next(); - if( sa instanceof InetSocketAddress ){ - port = ((InetSocketAddress)sa).getPort(); - } // end if: inet - } // end if: only one binding - return port; - } - - - - /** - * Returns the port for the single UDP binding in effect, - * or -1 (minus one) if there are no or multiple UDP - * bindings or some other error. - * @return UDP listening port or -1 - */ - public synchronized int getSingleUdpPort(){ - int port = -1; - Map bindings = getUdpBindings(); - if( bindings.size() == 1 ){ - SocketAddress sa = bindings.keySet().iterator().next(); - if( sa instanceof InetSocketAddress ){ - port = ((InetSocketAddress)sa).getPort(); - } // end if: inet - } // end if: only one binding - return port; - } - -/* ******** E V E N T S ******** */ - - - - /** Adds a {@link Listener}. - * @param l the listener - */ - public synchronized void addNioServerListener(NioServer.Listener l) { - listeners.add(l); - cachedListeners = null; - } - - - /** Removes a {@link Listener}. - * @param l the listener - */ - public synchronized void removeNioServerListener(NioServer.Listener l) { - listeners.remove(l); - cachedListeners = null; - } - - - /** - * Fire when data is received. - * @param key the SelectionKey associated with the data - * @param buffer the buffer containing the new (and possibly leftover) data - */ - protected synchronized void fireTcpDataReceived(SelectionKey key, ByteBuffer buffer) { - - if( cachedListeners == null ){ - cachedListeners = listeners.toArray(new NioServer.Listener[ listeners.size() ] ); - } - this.event.reset(key,buffer,null); - - // Make a Runnable object to execute the calls to listeners. - // In the event we don't have an Executor, this results in - // an unnecessary object instantiation, but it also makes - // the code more maintainable. - for( NioServer.Listener l : cachedListeners ){ - try{ - l.nioServerTcpDataReceived(event); - } catch( Exception exc ){ - LOGGER.warning("NioServer.Listener " + l + " threw an exception: " + exc.getMessage() ); - fireExceptionNotification(exc); - } // end catch - } // end for: each listener - } - - - /** - * Fire when data is received. - * @param key the SelectionKey associated with the data - * @param buffer the buffer containing the data - * @param remote the source address of the datagram or null if not available - */ - protected synchronized void fireUdpDataReceived(SelectionKey key, ByteBuffer buffer, SocketAddress remote) { - - if( cachedListeners == null ){ - cachedListeners = listeners.toArray(new NioServer.Listener[ listeners.size() ] ); - } - this.event.reset(key,buffer,remote); - - // Make a Runnable object to execute the calls to listeners. - // In the event we don't have an Executor, this results in - // an unnecessary object instantiation, but it also makes - // the code more maintainable. - for( NioServer.Listener l : cachedListeners ){ - try{ - l.nioServerUdpDataReceived(event); - } catch( Exception exc ){ - LOGGER.warning("NioServer.Listener " + l + " threw an exception: " + exc.getMessage() ); - fireExceptionNotification(exc); - } // end catch - } // end for: each listener - } // end fireNioServerPacketReceived - - - - /** - * Fire when a connection is closed remotely. - * @param key The key for the closed connection. - */ - protected synchronized void fireConnectionClosed(SelectionKey key) { - - if( cachedListeners == null ){ - cachedListeners = listeners.toArray(new NioServer.Listener[ listeners.size() ] ); - } - this.event.reset(key,null,null); - - // Make a Runnable object to execute the calls to listeners. - // In the event we don't have an Executor, this results in - // an unnecessary object instantiation, but it also makes - // the code more maintainable. - for( NioServer.Listener l : cachedListeners ){ - try{ - l.nioServerConnectionClosed(event); - } catch( Exception exc ){ - LOGGER.warning("NioServer.Listener " + l + " threw an exception: " + exc.getMessage() ); - fireExceptionNotification(exc); - } // end catch - } // end for: each listener - } // end fireNioServerPacketReceived - - - - - /** - * Fire when a new connection is established. - * @param key the SelectionKey associated with the connection - */ - protected synchronized void fireNewConnection(SelectionKey key) { - - if( cachedListeners == null ){ - cachedListeners = listeners.toArray(new NioServer.Listener[ listeners.size() ] ); - } - this.event.reset(key,null,null); - - // Make a Runnable object to execute the calls to listeners. - // In the event we don't have an Executor, this results in - // an unnecessary object instantiation, but it also makes - // the code more maintainable. - for( NioServer.Listener l : cachedListeners ){ - try{ - l.nioServerNewConnectionReceived(event); - } catch( Exception exc ){ - LOGGER.warning("NioServer.Listener " + l + " threw an exception: " + exc.getMessage() ); - fireExceptionNotification(exc); - } // end catch - } // end for: each listener - } // end fireNioServerPacketReceived - - - - - -/* ******** P R O P E R T Y C H A N G E ******** */ - - - /** - * Fires property chagne events for all current values - * setting the old value to null and new value to the current. - */ - public synchronized void fireProperties(){ - firePropertyChange( STATE_PROP, null, getState() ); - firePropertyChange( BUFFER_SIZE_PROP, null, getBufferSize() ); - } - - - /** - * Fire a property change event on the current thread. - * - * @param prop name of property - * @param oldVal old value - * @param newVal new value - */ - protected synchronized void firePropertyChange( final String prop, final Object oldVal, final Object newVal ){ - try{ - propSupport.firePropertyChange(prop,oldVal,newVal); - } catch( Exception exc ){ - LOGGER.log(Level.WARNING, - "A property change listener threw an exception: " + exc.getMessage() - ,exc); - fireExceptionNotification(exc); - } // end catch - } // end fire - - - - /** - * Add a property listener. - * @param listener the listener - */ - public synchronized void addPropertyChangeListener( PropertyChangeListener listener ){ - propSupport.addPropertyChangeListener(listener); - } - - - /** - * Add a property listener for the named property. - * @param property the property name - * @param listener the listener - */ - public synchronized void addPropertyChangeListener( String property, PropertyChangeListener listener ){ - propSupport.addPropertyChangeListener(property,listener); - } - - - /** - * Remove a property listener. - * @param listener the listener - */ - public synchronized void removePropertyChangeListener( PropertyChangeListener listener ){ - propSupport.removePropertyChangeListener(listener); - } - - - /** - * Remove a property listener for the named property. - * @param property the property name - * @param listener the listener - */ - public synchronized void removePropertyChangeListener( String property, PropertyChangeListener listener ){ - propSupport.removePropertyChangeListener(property,listener); - } - - - -/* ******** E X C E P T I O N S ******** */ - - - /** - * Returns the last exception (Throwable, actually) - * that the server encountered. - * @return last exception - */ - public synchronized Throwable getLastException(){ - return this.lastException; - } - - /** - * Fires a property change event with the new exception. - * @param t - */ - protected void fireExceptionNotification( Throwable t ){ - Throwable oldVal = this.lastException; - this.lastException = t; - firePropertyChange( LAST_EXCEPTION_PROP, oldVal, t ); - } - - - -/* ******** L O G G I N G ******** */ - - - - /** - * Static method to set the logging level using Java's - * java.util.logging package. Example: - * NioServer.setLoggingLevel(Level.OFF);. - * - * @param level the new logging level - */ - public static void setLoggingLevel( Level level ){ - LOGGER.setLevel(level); - } - - /** - * Static method returning the logging level using Java's - * java.util.logging package. - * @return the logging level - */ - public static Level getLoggingLevel(){ - return LOGGER.getLevel(); - } - - - - - -/* ******** ******** */ -/* ******** ******** */ -/* ******** S T A T I C I N N E R C L A S S L I S T E N E R ******** */ -/* ******** ******** */ -/* ******** ******** */ - - - - - - /** - * An interface for listening to events from a {@link NioServer}. - * A single {@link Event} is shared for all invocations - * of these methods. - * - *

This code is released into the Public Domain. - * Since this is Public Domain, you don't need to worry about - * licensing, and you can simply copy this NioServer.java file - * to your own package and use it as you like. Enjoy. - * Please consider leaving the following statement here in this code:

- * - *

This NioServer class was copied to this project from its source as - * found at iHarder.net.

- * - * @author Robert Harder - * @author rharder@users.sourceforge.net - * @version 0.1 - * @see NioServer - * @see Adapter - * @see Event - */ - public static interface Listener extends java.util.EventListener { - - /** - *

Called when a new connection is received. The SelectionKey associated - * with the event (an OP_READ key), is the key that will be - * used with the data received event. In this way, you can seed a - * Map or other data structure and associate this very - * key with the connection. You will only get new connection - * events for TCP connections (not UDP).

- * - *

The key's attachment mechanism is unused by NioServer and is - * available for you to store whatever you like.

- * - *

If your protocol requires the server to respond to a client - * upon connection, this sample code demonstrates such an arrangement:

- * - *
-         *   public void nioServerNewConnectionReceived(NioServer.Event evt) {
-         *       SocketChannel ch = (SocketChannel) evt.getKey().channel();
-         *       try {
-         *           ch.write(ByteBuffer.wrap("Greetings\r\n".getBytes()));
-         *       } catch (IOException ex) {
-         *           ex.printStackTrace(); // Please don't do printStackTrace in production code
-         *       }
-         *   }
-         * 
- * @param evt the shared event - */ - public abstract void nioServerNewConnectionReceived( NioServer.Event evt ); - - - /** - *

Called when TCP data is received. Retrieve the associated ByteBuffer - * with evt.getBuffer(). This is the source ByteBuffer - * used by the server directly to receive the data. It is a - * "direct" ByteBuffer (created with ByteBuffer.allocateDirect(..)). - * Read from it as much as - * you can. Any data that remains on or after the value - * of position() will be saved for the next - * time an event is fired. In this way, you can defer - * processing incomplete data until everything arrives. - * Be careful that you don't leave the buffer full - * or you won't be able to receive anything next time around - * (unless you call {@link #setBufferSize} to resize buffer).

- * - *

The key's attachment mechanism is unused by NioServer and is - * available for you to store whatever you like.

- * - *

Example: You are receiving lines of text. The ByteBuffer - * returned here contains one and a half lines of text. - * When you realize this, you process the first line as you - * like, but you leave this buffer's position at the beginning - * of the second line. In this way, The beginning of the second - * line will be the start of the buffer the next time around.

- * - * @param evt the shared event - */ - public abstract void nioServerTcpDataReceived( NioServer.Event evt ); - - - - /** - *

Called when UDP data is received. Retrieve the associated ByteBuffer - * with evt.getBuffer(). This is the source ByteBuffer - * used by the server directly to receive the data. It is a - * "direct" ByteBuffer (created with ByteBuffer.allocateDirect(..)). - * The contents of the ByteBuffer will be the entire contents - * received from the UDP datagram.

- * - * @param evt the shared event - */ - public abstract void nioServerUdpDataReceived( NioServer.Event evt ); - - /** - * Called when a connection is closed remotely. If you close the connection - * somewhere in your own code, this event probably won't be fired. - * @param evt the shared event - */ - public abstract void nioServerConnectionClosed( NioServer.Event evt ); - - - } // end inner static class Listener - - - - - - -/* ******** ******** */ -/* ******** ******** */ -/* ******** S T A T I C I N N E R C L A S S A D A P T E R ******** */ -/* ******** ******** */ -/* ******** ******** */ - - - - - /** - * A helper class that implements all methods of the - * {@link NioServer.Listener} interface with empty methods. - * - *

This code is released into the Public Domain. - * Since this is Public Domain, you don't need to worry about - * licensing, and you can simply copy this NioServer.java file - * to your own package and use it as you like. Enjoy. - * Please consider leaving the following statement here in this code:

- * - *

This NioServer class was copied to this project from its source as - * found at iHarder.net.

- * - * @author Robert Harder - * @author rharder@users.sourceforge.net - * @version 0.1 - * @see NioServer - * @see Listener - * @see Event - */ - public class Adapter implements Listener { - - /** - * Empty method. - * @see Listener - * @param evt the shared event - */ - public void nioServerTcpDataReceived(NioServer.Event evt) {} - - - /** - * Empty method. - * @see Listener - * @param evt the shared event - */ - public void nioServerUdpDataReceived(NioServer.Event evt) {} - - - /** - * Empty method. - * @see Listener - * @param evt the shared event - */ - public void nioServerNewConnectionReceived(NioServer.Event evt) {} - - /** - * Empty method. - * @see Listener - * @param evt the shared event - */ - public void nioServerConnectionClosed(NioServer.Event evt) {} - - } // end static inner class Adapter - - -/* ******** ******** */ -/* ******** ******** */ -/* ******** S T A T I C I N N E R C L A S S E V E N T ******** */ -/* ******** ******** */ -/* ******** ******** */ - - - - /** - * An event representing activity by a {@link NioServer}. - * - *

This code is released into the Public Domain. - * Since this is Public Domain, you don't need to worry about - * licensing, and you can simply copy this NioServer.java file - * to your own package and use it as you like. Enjoy. - * Please consider leaving the following statement here in this code:

- * - *

This NioServer class was copied to this project from its source as - * found at iHarder.net.

- * - * @author Robert Harder - * @author rharder@users.sourceforge.net - * @version 0.1 - * @see NioServer - * @see Adapter - * @see Listener - */ - public static class Event extends java.util.EventObject { - - private final static long serialVersionUID = 1; - - /** - * The key associated with this (reusable) event. - * Use setKey(..) to change the key between firings. - */ - private SelectionKey key; - - /** - * The buffer that holds the data, for some events. - */ - private ByteBuffer buffer; - - - /** - * The source address for incoming UDP datagrams. - * The {@link #getRemoteSocketAddress} method - * will return this value if data is from UDP. - */ - private SocketAddress remoteUdp; - - - /** - * Creates a Event based on the given {@link NioServer}. - * @param src the source of the event - */ - public Event( NioServer src ){ - super(src); - } - - /** - * Returns the source of the event, a {@link NioServer}. - * Shorthand for (NioServer)getSource(). - * @return the server - */ - public NioServer getNioServer(){ - return (NioServer)getSource(); - } - - /** - * Shorthand for getNioServer().getState(). - * @return the state of the server - * @see NioServer.State - */ - public NioServer.State getState(){ - return getNioServer().getState(); - } - - - /** - * Returns the SelectionKey associated with this event. - * - * @return the SelectionKey - */ - public SelectionKey getKey(){ - return this.key; - } - - - /** - * Resets an event between firings by updating the parameters - * that change. - * @param key The SelectionKey for the event - * @param buffer - * @param remoteUdp the remote UDP source or null for TCP - */ - protected void reset( SelectionKey key, ByteBuffer buffer, SocketAddress remoteUdp ){ - this.key = key; - this.buffer = buffer; - this.remoteUdp = remoteUdp; - } - - - /** - *

Returns the {@link java.nio.ByteBuffer} that contains - * the data for this connection. Read from it as much as - * you can. Any data that remains on or after the value - * of position() will be saved for the next - * time an event is fired. In this way, you can defer - * processing incomplete data until everything arrives.

- * - *

Example: You are receiving lines of text. The ByteBuffer - * returned here contains one and a half lines of text. - * When you realize this, you process the first line as you - * like, but you leave this buffer's position at the beginning - * of the second line. In this way, The beginning of the second - * line will be the start of the buffer the next time around.

- * @return buffer with the data - */ - public ByteBuffer getBuffer(){ - return this.buffer; - } - - - /** - *

Returns the local address/port to which this connection - * is bound. That is, if you are listening on port 80, then - * this might return something like an InetSocketAddress - * (probably) that indicated /127.0.0.1:80.

- *

This is - * essentially a convenience method for returning the same-name - * methods from the key's channel after checking the type - * of channel (SocketChannel or DatagramChannel).

- * - * @return local address that server is bound to for this connection - */ - public SocketAddress getLocalSocketAddress(){ - SocketAddress addr = null; - if( this.key != null ){ - SelectableChannel sc = this.key.channel(); - if( sc instanceof SocketChannel ){ - addr = ((SocketChannel)sc).socket().getLocalSocketAddress(); - } else if( sc instanceof DatagramChannel ){ - addr = ((DatagramChannel)sc).socket().getLocalSocketAddress(); - } - } - return addr; - } - - - /** - *

Returns the address of the endpoint this socket is - * connected to, or null if it is unconnected.

- *

This is - * essentially a convenience method for returning the same-name - * methods from the key's channel after checking the type - * of channel (SocketChannel or DatagramChannel).

- * - * @return remote address from which connection came - */ - public SocketAddress getRemoteSocketAddress(){ - SocketAddress addr = null; - if( this.key != null ){ - SelectableChannel sc = this.key.channel(); - if( sc instanceof SocketChannel ){ - addr = ((SocketChannel)sc).socket().getRemoteSocketAddress(); - } else if( sc instanceof DatagramChannel ){ - addr = this.remoteUdp; - } - } - return addr; - } - - - /** - * Convenience method for checking - * getKey().channel() instanceof SocketChannel. - * @return true if a TCP connection - */ - public boolean isTcp(){ - return this.key == null ? false : this.key.channel() instanceof SocketChannel; - } - - - /** - * Convenience method for checking - * getKey().channel() instanceof DatagramChannel. - * @return true if a UDP connection - */ - public boolean isUdp(){ - return this.key == null ? false : this.key.channel() instanceof DatagramChannel; - } - - - } // end static inner class Event - - - -} // end class NioServer diff --git a/src/main/java/edu/nps/moves/disutil/PduFactory.java b/src/main/java/edu/nps/moves/disutil/PduFactory.java index f7f7b595..f845d6fb 100644 --- a/src/main/java/edu/nps/moves/disutil/PduFactory.java +++ b/src/main/java/edu/nps/moves/disutil/PduFactory.java @@ -16,29 +16,10 @@ */ public class PduFactory { - /** - * whether we should use return flattened, "fast" espdus with fewer objects - */ - private boolean useFastPdu = false; - private Logger logger; - /** - * Creates a new instance of PduFactory - */ - public PduFactory() { - this(false); - } - /** - * Create a new PDU factory; if true is passed in, we use "fast PDUs", which - * minimize the memory garbage generated at the cost of being somewhat less - * pleasant to work with. - * - * @param useFastPdu - */ - public PduFactory(boolean useFastPdu) { - this.useFastPdu = useFastPdu; + public PduFactory() { // By default don't log anything logger = Logger.getLogger(PduFactory.class.getName()); @@ -46,14 +27,6 @@ public PduFactory(boolean useFastPdu) { } - public void setUseFastPdu(boolean use) { - this.useFastPdu = use; - } - - public boolean getUseFastPdu() { - return this.useFastPdu; - } - /** * Set the logging level that will be printed, typically to Level.INFO * @@ -98,12 +71,7 @@ public Pdu createPdu(java.nio.ByteBuffer buff) { // NOTE: OTHER is a valid pduTypeEnum, but has no corresponding object case ENTITY_STATE: - // if the user has created the factory requesting that he get fast espdus back, give him those. - if (useFastPdu) { - aPdu = new FastEntityStatePdu(); - } else { - aPdu = new EntityStatePdu(); - } + aPdu = new EntityStatePdu(); break; case FIRE: diff --git a/src/main/java/edu/nps/moves/disutil/PduMulticastReceiver.java b/src/main/java/edu/nps/moves/disutil/PduMulticastReceiver.java deleted file mode 100644 index 6effd12a..00000000 --- a/src/main/java/edu/nps/moves/disutil/PduMulticastReceiver.java +++ /dev/null @@ -1,234 +0,0 @@ - -package edu.nps.moves.disutil; - -import edu.nps.moves.dis.Pdu; -import java.net.DatagramPacket; -import java.nio.ByteBuffer; -import java.util.Collection; -import java.util.LinkedList; -import java.util.logging.Logger; - -/** - *

A UDP server that receives DIS PDU packets and fires off events - * to interested parties. The event firing is on the socket-processing - * thread, so be quick about handling the events.

- * - *

Using the new {@link java.nio.ByteBuffer}-based marshalling is - * more efficient than the old IO Streams technique, and it also supports - * receiving several DIS PDUs in a single UDP datagram. Each datagram - * is scraped sequentially so that if one PDU is placed after another, - * they will each be unmarshalled, and an event will be fired off for - * each one in turn.

- * - * @author Robert Harder - * @since ?? - */ -@Deprecated -public class PduMulticastReceiver extends UdpServer { - - private final static Logger LOGGER = Logger.getLogger(PduMulticastReceiver.class.getName()); - - private Collection listeners = new LinkedList(); // Event listeners - private PduMulticastReceiver.Event event = new PduMulticastReceiver.Event(this); - - private PduFactory pduFactory; - private Pdu pdu; // Last pdu received - private ByteBuffer buffer; - private ByteBuffer directBuffer; - private boolean unmarshalWithByteBuffer = true; // instead of data input stream - //private boolean lookForMultiplePdusPerPacket; - - - /** - * Creates a new instance of PduMulticastReceiver that is - * in the {@link UdpServer.State#STOPPED} state - */ - public PduMulticastReceiver(){ - super(); - initComponents(); - } - - private void initComponents(){ - final DatagramPacket packet = super.getPacket(); // Long-lived, shared packet - buffer = ByteBuffer.wrap( packet.getData() ); // Wrap the data portion - pduFactory = new PduFactory(); - - super.addUdpServerListener(new UdpServer.Adapter() { - Pdu lastPdu; - Pdu temp; - @Override - public void udpServerPacketReceived(UdpServer.Event evt) { - try{ - temp = null; - // Efficient and clean - if( unmarshalWithByteBuffer ){ - buffer.rewind(); - buffer.position( packet.getOffset() ); - buffer.limit(packet.getOffset() + packet.getLength() ); - while( (temp = pduFactory.createPdu(buffer)) != null ){ - lastPdu = temp; // This inner class - pdu = temp; // The server's reference - firePduReceived(); - } // end while: more pdus to check - } // end if: use byte buffer - - // Inefficient and dirty - else { - if( packet.getOffset() == 0 ){ - temp = pduFactory.createPdu( packet.getData() ); - } else { - byte[] data = new byte[ packet.getLength() ]; - System.arraycopy( packet.getData(), packet.getOffset(), data,0,data.length ); - temp = pduFactory.createPdu(data); - } // end else: need to clean up array - - lastPdu = temp; // This inner class - pdu = temp; // The server's reference - firePduReceived(); - } // end else: use old system - }catch(Exception e){ - System.err.println("Encountered an error. Please contact open-dis developers."); - e.printStackTrace(); - } - } // end packet received - }); // end listener - } - - - /** - * Returns the last parsed PDU. - * @return PDU object - */ - public Pdu getPdu(){ - return this.pdu; - } - - - - /** - * Returns whether or not the ByteBuffer marshalling - * technique is being used (default). - * @return is the byte buffer marshalling technique being used? - */ - public boolean getUseByteBuffer(){ - return this.unmarshalWithByteBuffer; - } - - /** - * Sets whether or not to use the more efficient - * ByteBuffer marshalling technique (default). - * @param use whether or not to use it - */ - public void setUseByteBuffer( boolean use ){ - this.unmarshalWithByteBuffer = use; - } - - /** - * Returns whether or not FastEspdu objects - * are created which use less memory since - * all their fields are flattened to primitives - * instead of several objects. - * @return using or not using fast pdu - */ - public boolean getUseFastPdu(){ - return this.pduFactory.getUseFastPdu(); - } - - - /** - * Sets whether or not to generate the - * Fast Espdu packets (all primitive fields). - * @param use - */ - public void setUseFastEspdu( boolean use ){ - this.pduFactory.setUseFastPdu(use); - } - - -/* ******** E V E N T S ******** */ - - - - /** Adds a {@link Listener}. - * @param l the UdpServer.Listener - */ - public synchronized void addPduMulticastReceiverListener(PduMulticastReceiver.Listener l) { - listeners.add(l); - } - - /** Removes a {@link Listener}. - * @param l the UdpServer.Listener - */ - public synchronized void removePduMulticastReceiverListener(PduMulticastReceiver.Listener l) { - listeners.remove(l); - } - - - /** - * Fires event on calling thread. - */ - protected synchronized void firePduReceived() { - - PduMulticastReceiver.Listener[] ll = listeners.toArray(new PduMulticastReceiver.Listener[ listeners.size() ] ); - for( PduMulticastReceiver.Listener l : ll ){ - try{ - l.pduReceived(event); - } catch( Exception exc ){ - LOGGER.warning("PduMulticastReceiver.Listener " + l + " threw an exception: " + exc.getMessage() ); - } // end catch - } // end for: each listener - } // end fireUdpServerPacketReceived - - - - - - -/* ******** L I S T E N E R ******** */ - - - public static interface Listener extends java.util.EventListener{ - - - /** - * Called when a packet is received. This is called on the IO thread, - * so don't take too long, and if you want to offload the processing - * to another thread, be sure to copy the data out of the datagram - * since it will be clobbered the next time around. - * - * @param evt the event - * @see Event#getPdu - */ - public abstract void pduReceived( PduMulticastReceiver.Event evt ); - - - } // end inner static class Listener - - - -/* ******** E V E N T ******** */ - - - public static class Event extends java.util.EventObject { - - - /** - * Creates a Event based on the given {@link PduMulticastReceiver}. - * @param src the source of the event - */ - public Event( PduMulticastReceiver src ){ - super(src); - } - - /** - * Returns the {@link Pdu} for this event. Since the server - * runs on a single thread, this method is a shorthand - * for ((PduMulticastReceiver)getSource()).getPdu(). - * @return the {@link Pdu} - */ - public Pdu getPdu(){ - return ((PduMulticastReceiver)getSource()).getPdu(); - } - } - -} diff --git a/src/main/java/edu/nps/moves/disutil/PduNioMulticastReceiver.java b/src/main/java/edu/nps/moves/disutil/PduNioMulticastReceiver.java deleted file mode 100644 index c813d6ed..00000000 --- a/src/main/java/edu/nps/moves/disutil/PduNioMulticastReceiver.java +++ /dev/null @@ -1,221 +0,0 @@ - -package edu.nps.moves.disutil; - -import edu.nps.moves.dis.Pdu; -import java.nio.ByteBuffer; -import java.util.Collection; -import java.util.LinkedList; -import java.util.logging.Logger; - -/** - *

A UDP server that receives DIS PDU packets and fires off events - * to interested parties. The event firing is on the socket-processing - * thread, so be quick about handling the events.

- * - *

Using the new {@link java.nio.ByteBuffer}-based marshalling is - * more efficient than the old IO Streams technique, and it also supports - * receiving several DIS PDUs in a single UDP datagram. Each datagram - * is scraped sequentially so that if one PDU is placed after another, - * they will each be unmarshalled, and an event will be fired off for - * each one in turn.

- * - * @author Robert Harder - * @since ?? - */ -@Deprecated -public class PduNioMulticastReceiver extends NioServer { - - private final static Logger LOGGER = Logger.getLogger(PduNioMulticastReceiver.class.getName()); - - private Collection listeners = new LinkedList(); // Event listeners - private PduNioMulticastReceiver.Event event = new PduNioMulticastReceiver.Event(this); - - private PduFactory pduFactory; - private Pdu pdu; // Last pdu received - //private ByteBuffer buffer; - private boolean unmarshalWithByteBuffer = true; // instead of data input stream - //private boolean lookForMultiplePdusPerPacket; - - - /** - * Creates a new instance of PduMulticastReceiver that is - * in the {@link UdpServer.State#STOPPED} state - */ - public PduNioMulticastReceiver(){ - super(); - initComponents(); - } - - private void initComponents(){ -// final DatagramPacket packet = super.getPacket(); // Long-lived, shared packet -// buffer = ByteBuffer.wrap( packet.getData() ); // Wrap the data portion - pduFactory = new PduFactory(); - - super.addNioServerListener(new NioServer.Adapter() { - Pdu temp; - @Override - public void nioServerUdpDataReceived(NioServer.Event evt) { - try{ - temp = null; - // Efficient and clean - if( unmarshalWithByteBuffer ){ - ByteBuffer buffer = evt.getBuffer(); - while( (temp = pduFactory.createPdu(buffer)) != null ){ - firePduReceived( temp ); - } // end while: more pdus to check - } // end if: use byte buffer - - // Inefficient and dirty - else { - ByteBuffer buffer = evt.getBuffer(); - byte[] data = new byte[ buffer.remaining() ]; - buffer.get(data); - temp = pduFactory.createPdu(data); - firePduReceived(temp); - } // end else: use old system - }catch(Exception e){ - System.err.println("Encountered an error. Please contact open-dis developers."); - e.printStackTrace(); - } - } // end packet received - - }); // end listener - } - - - /** - * Returns the last parsed PDU. - */ - public Pdu getPdu(){ - return this.pdu; - } - - - /** - * Returns whether or not the ByteBuffer marshalling - * technique is being used (default). - */ - public boolean getUseByteBuffer(){ - return this.unmarshalWithByteBuffer; - } - - /** - * Sets whether or not to use the more efficient - * ByteBuffer marshalling technique (default). - * @param use whether or not to use it - */ - public void setUseByteBuffer( boolean use ){ - this.unmarshalWithByteBuffer = use; - } - - - /** - * Returns whether or not FastEspdu objects - * are created which use less memory since - * all their fields are flattened to primitives - * instead of several objects. - * @return using or not using fast pdu - */ - public boolean getUseFastPdu(){ - return this.pduFactory.getUseFastPdu(); - } - - - /** - * Sets whether or not to generate the - * Fast Espdu packets (all primitive fields). - * @param use - */ - public void setUseFastEspdu( boolean use ){ - this.pduFactory.setUseFastPdu(use); - } - - -/* ******** E V E N T S ******** */ - - - - /** Adds a {@link Listener}. - * @param l the UdpServer.Listener - */ - public synchronized void addPduMulticastReceiverListener(PduNioMulticastReceiver.Listener l) { - listeners.add(l); - } - - /** Removes a {@link Listener}. - * @param l the UdpServer.Listener - */ - public synchronized void removePduMulticastReceiverListener(PduNioMulticastReceiver.Listener l) { - listeners.remove(l); - } - - - /** - * Fires event on calling thread. - * @param pdu - */ - protected synchronized void firePduReceived( Pdu pdu ) { - this.pdu = pdu; - PduNioMulticastReceiver.Listener[] ll = listeners.toArray(new PduNioMulticastReceiver.Listener[ listeners.size() ] ); - for( PduNioMulticastReceiver.Listener l : ll ){ - try{ - l.pduReceived(event); - } catch( Exception exc ){ - LOGGER.warning("PduMulticastReceiver.Listener " + l + " threw an exception: " + exc.getMessage() ); - } // end catch - } // end for: each listener - } // end fireUdpServerPacketReceived - - - - - - -/* ******** L I S T E N E R ******** */ - - - public static interface Listener extends java.util.EventListener{ - - - /** - * Called when a packet is received. This is called on the IO thread, - * so don't take too long, and if you want to offload the processing - * to another thread, be sure to copy the data out of the datagram - * since it will be clobbered the next time around. - * - * @param evt the event - * @see Event#getPdu - */ - public abstract void pduReceived( PduNioMulticastReceiver.Event evt ); - - - } // end inner static class Listener - - - -/* ******** E V E N T ******** */ - - - public static class Event extends java.util.EventObject { - - - /** - * Creates a Event based on the given {@link PduMulticastReceiver}. - * @param src the source of the event - */ - public Event( PduNioMulticastReceiver src ){ - super(src); - } - - /** - * Returns the {@link Pdu} for this event. Since the server - * runs on a single thread, this method is a shorthand - * for ((PduMulticastReceiver)getSource()).getPdu(). - * @return the {@link Pdu} - */ - public Pdu getPdu(){ - return ((PduNioMulticastReceiver)getSource()).getPdu(); - } - } - -} diff --git a/src/main/java/edu/nps/moves/disutil/UdpServer.java b/src/main/java/edu/nps/moves/disutil/UdpServer.java deleted file mode 100644 index 88592963..00000000 --- a/src/main/java/edu/nps/moves/disutil/UdpServer.java +++ /dev/null @@ -1,850 +0,0 @@ -package edu.nps.moves.disutil; - -import java.util.concurrent.ThreadFactory; -import java.beans.PropertyChangeListener; -import java.beans.PropertyChangeSupport; -import java.io.IOException; -import java.net.MulticastSocket; -import java.util.logging.Logger; -import java.util.logging.Level; -import java.net.DatagramPacket; -import java.net.InetAddress; -import java.net.SocketException; -import java.util.Collection; -import java.util.LinkedList; - - - -/** - *

Used in support of {@link PduMulticastReceiver}.

- * - *

A robust class for establishing a UDP server and manipulating - * its listening port and optionally a multicast groups to join. - * The {@link Event}s and property change events make - * it an appropriate tool in a threaded, GUI application. - * It is almost identical in design to the TcpServer class that - * should have accompanied this class when you downloaded it.

- * - *

To start a UDP server, create a new UdpServer and call start():

- * - *
 UdpServer server = new UdpServer();
- * server.start();
- * - *

Of course it won't be much help unless you know which port it's - * listening on and you register as a listener - * so you'll know when a java.net.DatagramPacket has come in:

- * - *
 server.setPort(1234);
- *  server.addUdpServerListener( new UdpServer.Adapter(){
- *     public void udpServerPacketReceived( UdpServer.Event evt ){
- *         DatagramPacket packet = evt.getPacket();
- *         ...
- *     }   // end packet received
- * });
- * - *

The server runs on one thread, and all events are fired on that thread. - * If you have to offload heavy processing to another thread, be sure to - * make a copy of the datagram data array since it will be reused the next - * time around. You may use the {@link Event#getPacketAsBytes} - * command as a convenient way to make a copy of the byte array.

- * - *

The full 64KB allowed by the UDP standard is set aside to receive - * the datagrams, but it's possible that your host platform may truncate that.

- * - *

The public methods are all synchronized on this, and great - * care has been taken to avoid deadlocks and race conditions. That being said, - * there may still be bugs (please contact the author if you find any), and - * you certainly still have the power to introduce these problems yourself.

- * - *

It's often handy to have your own class extend this one rather than - * making an instance field to hold a UdpServer where you'd have to - * pass along all the setPort(...) methods and so forth.

- * - *

The supporting {@link Event}, {@link Listener}, and {@link Adapter} - * classes are static inner classes in this file so that you have only one - * file to copy to your project. You're welcome.

- * - *

This code is released into the Public Domain. - * Since this is Public Domain, you don't need to worry about - * licensing, and you can simply copy this UdpServer.java file - * to your own package and use it as you like. Enjoy. - * Please consider leaving the following statement here in this code:

- * - *

This UdpServer class was copied to this project from its source as - * found at iHarder.net.

- * - * @author Robert Harder - * @author rharder@users.sourceforge.net - * @version 0.1 - * @see UdpServer - * @see Adapter - * @see Event - * @see Listener - */ -@Deprecated -public class UdpServer { - - private final static Logger LOGGER = Logger.getLogger(UdpServer.class.getName()); - - /** - * The port property port used with - * the property change listeners and the preferences, - * if a preferences object is given. - */ - public final static String PORT_PROP = "port"; - private final static int PORT_DEFAULT = 8000; - private int port = PORT_DEFAULT; - - - /** - * The multicast groups property groups used with - * the property change listeners and the preferences, - * if a preferences object is given. If the multicast - * groups is null, then no multicast groups will be joined. - */ - public final static String GROUPS_PROP = "groups"; - private final static String GROUPS_DEFAULT = null; - private String groups = GROUPS_DEFAULT; - - - - /** - *

One of four possible states for the server to be in:

- * - *
    - *
  • STARTING
  • - *
  • STARTED
  • - *
  • STOPPING
  • - *
  • STOPPED
  • - *
- */ - public static enum State { STARTING, STARTED, STOPPING, STOPPED }; - private State currentState = State.STOPPED; - - - private Collection listeners = new LinkedList(); // Event listeners - private UdpServer.Event event = new UdpServer.Event(this); // Shared event - private PropertyChangeSupport propSupport = new PropertyChangeSupport(this); // Properties - - private final UdpServer This = this; // To aid in synchronizing - private ThreadFactory threadFactory; // Optional thread factory - private Thread ioThread; // Performs IO - private MulticastSocket mSocket; // The server - private DatagramPacket packet = new DatagramPacket( new byte[64*1024], 64*1024 ); // Shared datagram - - -/* ******** C O N S T R U C T O R S ******** */ - - - /** - * Constructs a new UdpServer that will listen on the default port 8000 - * (but not until {@link #start} is called). - * The I/O thread will not be in daemon mode. - */ - public UdpServer(){ - } - - /** - * Constructs a new UdpServer that will listen on the given port - * (but not until {@link #start} is called). - * The I/O thread will not be in daemon mode. - * @param port The initial port on which to listen - */ - public UdpServer( int port ){ - this.port = port; - } - - /** - * Constructs a new UdpServer that will listen on the given port - * (but not until {@link #start} is called). The provided - * ThreadFactory will be used when starting and running the server. - * @param port The initial port on which to listen - * @param factory The thread factory used to generate a thread to run the server - */ - public UdpServer( int port, ThreadFactory factory ){ - this.port = port; - this.threadFactory = factory; - } - - - - -/* ******** R U N N I N G ******** */ - - - /** - * Attempts to start the server listening and returns immediately. - * Listen for start events to know if the server was - * successfully started. - * - * @see Listener - */ - public synchronized void start(){ - if( this.currentState == UdpServer.State.STOPPED ){ // Only if we're stopped now - assert ioThread == null : ioThread; // Shouldn't have a thread - - Runnable run = new Runnable() { - // @Override - public void run() { - runServer(); // This runs for a long time - ioThread = null; - recordState( UdpServer.State.STOPPED ); // Clear thread - } // end run - }; // end runnable - - if( this.threadFactory != null ){ // User-specified threads - this.ioThread = this.threadFactory.newThread(run); - - } else { // Our own threads - this.ioThread = new Thread( run, this.getClass().getName() ); // Named - } - - recordState( UdpServer.State.STARTING ); // Update state - this.ioThread.start(); // Start thread - } // end if: currently stopped - } // end start - - - /** - * Attempts to stop the server, if the server is in - * the STARTED state, and returns immediately. - * Be sure to listen for stop events to know if the server was - * successfully stopped. - * - * @see Listener - */ - public synchronized void stop(){ - if( this.currentState == UdpServer.State.STARTED ){ // Only if already STARTED - recordState( UdpServer.State.STOPPING ); // Mark as STOPPING - if( this.mSocket != null ){ - this.mSocket.close(); - } // end if: not null - } // end if: already STARTED - } // end stop - - - - - /** - * Returns the current state of the server, one of - * STOPPED, STARTING, or STARTED. - * @return state of the server - */ - public synchronized UdpServer.State getState(){ - return this.currentState; - } - - - /** - * Records (sets) the state and fires an event. This method - * does not change what the server is doing, only - * what is reflected by the currentState variable. - * @param state The new state of the server - */ - protected synchronized void recordState( UdpServer.State state ){ - this.currentState = state; - fireUdpServerStateChanged(); - } - - - /** - * Fires an event declaring the current state of the server. - * This may encourage lazy programming on your part, but it's - * handy to set yourself up as a listener and then fire an - * event in order to initialize this or that. - */ - public synchronized void fireState(){ - fireUdpServerStateChanged(); - } - - - /** - * Resets the server, if it is running, otherwise does nothing. - * This is accomplished by registering as a listener, stopping - * the server, detecting the stop, unregistering, and starting - * the server again. It's a useful design pattern, and you may - * want to look at the source code for this method to check it out. - */ - public synchronized void reset(){ - switch( this.currentState ){ - case STARTED: - this.addUdpServerListener( new Adapter(){ - @Override - public void udpServerStateChanged( UdpServer.Event evt ){ - if( evt.getState() == State.STOPPED ){ - UdpServer server = (UdpServer)evt.getSource(); - server.removeUdpServerListener(this); - server.start(); - } // end if: stopped - } // end state changed - }); // end adapter - stop(); - break; - } // end switch - } - - - /** - * This method starts up and listens indefinitely - * for UDP packets. On entering this method, - * the state is assumed to be STARTING. Upon exiting - * this method, the state will be STOPPING. - */ - protected void runServer(){ - try{ - this.mSocket = new MulticastSocket( getPort() ); // Create server - LOGGER.info("UDP Server established on port " + getPort() ); - - try{ - this.mSocket.setReceiveBufferSize( this.packet.getData().length ); - LOGGER.info("UDP Server receive buffer size (bytes): " + this.mSocket.getReceiveBufferSize() ); - } catch( IOException exc ){ - int pl = this.packet.getData().length; - int bl = this.mSocket.getReceiveBufferSize(); - LOGGER.warning(String.format( "Could not set receive buffer to %d. It is now at %d. Error: %s", - pl, bl, exc.getMessage() ) ); - } // end catch - - String gg = getGroups(); // Get multicast groups - String[] proposed = gg.split("[\\s,]+"); // Split along whitespace - for( String p : proposed ){ // See which ones are valid - try{ - this.mSocket.joinGroup( InetAddress.getByName(p) ); - LOGGER.info( "UDP Server joined multicast group " + p ); - } catch( IOException exc ){ - LOGGER.warning("Could not join " + p + " as a multicast group: " + exc.getMessage() ); - } // end catch - } // end for: each proposed - - - recordState( State.STARTED ); // Mark as started - LOGGER.info( "UDP Server listening..." ); - - while( !this.mSocket.isClosed() ){ - synchronized( This ){ - if( this.currentState == State.STOPPING ){ - LOGGER.info( "Stopping UDP Server by request." ); - this.mSocket.close(); - } // end if: stopping - } // end sync - - if( !this.mSocket.isClosed() ){ - - //////// B L O C K I N G - this.mSocket.receive(packet); - //////// B L O C K I N G - - if( LOGGER.isLoggable(Level.FINE) ){ - LOGGER.fine( "UDP Server received datagram: " + packet ); - } - fireUdpServerPacketReceived(); - - } //end if: not closed - } // end while: keepGoing - - } catch( Exception exc ){ - synchronized( This ){ - if( this.currentState == State.STOPPING ){ // User asked to stop - this.mSocket.close(); - LOGGER.info( "Udp Server closed normally." ); - } else { - LOGGER.log( Level.WARNING, "Server closed unexpectedly: " + exc.getMessage(), exc ); - } // end else - } // end sync - } finally { - recordState( State.STOPPING ); - if( this.mSocket != null ){ - this.mSocket.close(); - } // end if: not null - this.mSocket = null; - } - } - -/* ******** P A C K E T ******** */ - - /** - * Returns the last DatagramPacket received. - * @return the shared DatagramPacket - */ - public synchronized DatagramPacket getPacket(){ - return this.packet; - } - - -/* ******** R E C E I V E B U F F E R ******** */ - - - /** - * Returns the receive buffer for the underlying MulticastSocket - * if the server is currently running (otherwise there is no - * MulticastSocket to query). Please see the javadocs for - * java.net.MulticastSocket for more information. - * - * @return receive buffer size - * @throws java.net.SocketException - */ - public synchronized int getReceiveBufferSize() throws SocketException{ - if( this.mSocket == null ){ - throw new SocketException("getReceiveBufferSize() cannot be called when the server is not started."); - } else { - return this.mSocket.getReceiveBufferSize(); - } - } // end getReceiveBufferSize - - /** - * Recommends a receive buffer size for the underlying MulticastSocket. - * Please see the javadocs for - * java.net.MulticastSocket for more information. - * - * @param size - * @throws java.net.SocketException - */ - public synchronized void setReceiveBufferSize(int size) throws SocketException{ - if( this.mSocket == null ){ - throw new SocketException("setReceiveBufferSize(..) cannot be called when the server is not started."); - } else { - this.mSocket.setReceiveBufferSize(size); - } - } // end setReceiveBufferSize - - - - - - -/* ******** P O R T ******** */ - - /** - * Returns the port on which the server is or will be listening. - * @return The port for listening. - */ - public synchronized int getPort(){ - return this.port; - } - - /** - * Sets the new port on which the server will attempt to listen. - * If the server is already listening, then it will attempt to - * restart on the new port, generating start and stop events. - * @param port the new port for listening - * @throws IllegalArgumentException if port is outside 0..65535 - */ - public synchronized void setPort( int port ){ - if( port < 0 || port > 65535 ){ - throw new IllegalArgumentException( "Cannot set port outside range 0..65535: " + port ); - } // end if: port outside range - - - int oldVal = this.port; - this.port = port; - if( getState() == State.STARTED ){ - reset(); - } // end if: is running - - firePropertyChange( PORT_PROP, oldVal, port ); - } - - - -/* ******** M U L T I C A S T G R O U P ******** */ - - /** - * Returns the multicast groups to which the server has joined. - * May be null. - * @return The multicast groups - */ - public synchronized String getGroups(){ - return this.groups; - } - - /** - *

Sets the new multicast groups to which the server will join. - * If the server is already listening, then it will attempt to - * restart, generating start and stop events.

- * - *

The list of groups may be whitespace- and/or comma-separated. - * When the server starts up (or restarts), the list will be - * parsed, and only legitimate groups will actually be joined.

- * May be null. - * - * @param group the new groups to join - */ - public synchronized void setGroups( String group ){ - - String oldVal = this.groups; - this.groups = group; - if( getState() == State.STARTED ){ - reset(); - } // end if: is running - - firePropertyChange( GROUPS_PROP, oldVal, this.groups ); - } - - -/* ******** E V E N T S ******** */ - - - - /** Adds a {@link Listener}. - * @param l the UdpServer.Listener - */ - public synchronized void addUdpServerListener(UdpServer.Listener l) { - listeners.add(l); - } - - /** Removes a {@link Listener}. - * @param l the UdpServer.Listener - */ - public synchronized void removeUdpServerListener(UdpServer.Listener l) { - listeners.remove(l); - } - - - /** - * Fires event on calling thread. - */ - protected synchronized void fireUdpServerPacketReceived() { - - UdpServer.Listener[] ll = listeners.toArray(new UdpServer.Listener[ listeners.size() ] ); - for( UdpServer.Listener l : ll ){ - try{ - l.udpServerPacketReceived(event); - } catch( Exception exc ){ - LOGGER.warning("UdpServer.Listener " + l + " threw an exception: " + exc.getMessage() ); - } // end catch - } // end for: each listener - } // end fireUdpServerPacketReceived - - - - /** - * Fires event on calling thread. - */ - protected synchronized void fireUdpServerStateChanged() { - - final UdpServer.Listener[] ll = listeners.toArray(new UdpServer.Listener[ listeners.size() ] ); - for( UdpServer.Listener l : ll ){ - try{ - l.udpServerStateChanged(event); - } catch( Exception exc ){ - LOGGER.warning("UdpServer.Listener " + l + " threw an exception: " + exc.getMessage() ); - } // end catch - } // end for: each listener - } // end fireUdpServerStateChanged - - - - -/* ******** P R O P E R T Y C H A N G E ******** */ - - - /** - * Fires property chagne events for all current values - * setting the old value to null and new value to the current. - */ - public synchronized void fireProperties(){ - firePropertyChange( PORT_PROP, null, getPort() ); // Port - firePropertyChange( GROUPS_PROP, null, getGroups() ); // Multicast groups - } - - - /** - * Fire a property change event on the current thread. - * - * @param prop name of property - * @param oldVal old value - * @param newVal new value - */ - protected synchronized void firePropertyChange( final String prop, final Object oldVal, final Object newVal ){ - try{ - propSupport.firePropertyChange(prop,oldVal,newVal); - } catch( Exception exc ){ - LOGGER.log(Level.WARNING, - "A property change listener threw an exception: " + exc.getMessage() - ,exc); - } // end catch - } // end fire - - - - /** Add a property listener. - * @param listener the property change listener - */ - public synchronized void addPropertyChangeListener( PropertyChangeListener listener ){ - propSupport.addPropertyChangeListener(listener); - } - - - /** Add a property listener for the named property. - * @param property the sole property name for which to register - * @param listener the property change listener - */ - public synchronized void addPropertyChangeListener( String property, PropertyChangeListener listener ){ - propSupport.addPropertyChangeListener(property,listener); - } - - - /** Remove a property listener. - * @param listener the property change listener - */ - public synchronized void removePropertyChangeListener( PropertyChangeListener listener ){ - propSupport.removePropertyChangeListener(listener); - } - - - /** Remove a property listener for the named property. - * @param property the sole property name for which to stop receiving events - * @param listener the property change listener - */ - public synchronized void removePropertyChangeListener( String property, PropertyChangeListener listener ){ - propSupport.removePropertyChangeListener(property,listener); - } - - - - - -/* ******** L O G G I N G ******** */ - - /** - * Static method to set the logging level using Java's - * java.util.logging package. Example: - * UdpServer.setLoggingLevel(Level.OFF);. - * - * @param level the new logging level - */ - public static void setLoggingLevel( Level level ){ - LOGGER.setLevel(level); - } - - /** - * Static method returning the logging level using Java's - * java.util.logging package. - * @return the logging level - */ - public static Level getLoggingLevel(){ - return LOGGER.getLevel(); - } - - - - - - - - -/* ******** ******** */ -/* ******** ******** */ -/* ******** S T A T I C I N N E R C L A S S L I S T E N E R ******** */ -/* ******** ******** */ -/* ******** ******** */ - - - - - - /** - * An interface for listening to events from a {@link UdpServer}. - * A single {@link Event} is shared for all invocations - * of these methods. - * - *

This code is released into the Public Domain. - * Since this is Public Domain, you don't need to worry about - * licensing, and you can simply copy this UdpServer.java file - * to your own package and use it as you like. Enjoy. - * Please consider leaving the following statement here in this code:

- * - *

This UdpServer class was copied to this project from its source as - * found at iHarder.net.

- * - * @author Robert Harder - * @author rharder@users.sourceforge.net - * @version 0.1 - * @see UdpServer - * @see Adapter - * @see Event - */ - public static interface Listener extends java.util.EventListener { - - /** - * Called when the state of the server has changed, such as - * "starting" or "stopped." - * @param evt the event - * @see UdpServer.State - */ - public abstract void udpServerStateChanged( UdpServer.Event evt ); - - /** - * Called when a packet is received. This is called on the IO thread, - * so don't take too long, and if you want to offload the processing - * to another thread, be sure to copy the data out of the datagram - * since it will be clobbered the next time around. - * - * @param evt the event - * @see Event#getPacket - */ - public abstract void udpServerPacketReceived( UdpServer.Event evt ); - - - } // end inner static class Listener - - - - -/* ******** ******** */ -/* ******** ******** */ -/* ******** S T A T I C I N N E R C L A S S A D A P T E R ******** */ -/* ******** ******** */ -/* ******** ******** */ - - - - - /** - * A helper class that implements all methods of the - * {@link UdpServer.Listener} interface with empty methods. - * - *

This code is released into the Public Domain. - * Since this is Public Domain, you don't need to worry about - * licensing, and you can simply copy this UdpServer.java file - * to your own package and use it as you like. Enjoy. - * Please consider leaving the following statement here in this code:

- * - *

This UdpServer class was copied to this project from its source as - * found at iHarder.net.

- * - * @author Robert Harder - * @author rharder@users.sourceforge.net - * @version 0.1 - * @see UdpServer - * @see Listener - * @see Event - */ - public class Adapter implements UdpServer.Listener { - - /** - * Empty call for {@link UdpServer.Listener#udpServerStateChanged}. - * @param evt the event - */ - public void udpServerStateChanged( UdpServer.Event evt ) {} - - - /** - * Empty call for {@link UdpServer.Listener#udpServerPacketReceived}. - * @param evt the event - */ - public void udpServerPacketReceived( UdpServer.Event evt ) {} - - } // end static inner class Adapter - - -/* ******** ******** */ -/* ******** ******** */ -/* ******** S T A T I C I N N E R C L A S S E V E N T ******** */ -/* ******** ******** */ -/* ******** ******** */ - - - - /** - * An event representing activity by a {@link UdpServer}. - * - *

This code is released into the Public Domain. - * Since this is Public Domain, you don't need to worry about - * licensing, and you can simply copy this UdpServer.java file - * to your own package and use it as you like. Enjoy. - * Please consider leaving the following statement here in this code:

- * - *

This UdpServer class was copied to this project from its source as - * found at iHarder.net.

- * - * @author Robert Harder - * @author rharder@users.sourceforge.net - * @version 0.1 - * @see UdpServer - * @see Adapter - * @see Listener - */ - public static class Event extends java.util.EventObject { - - - /** - * Creates a Event based on the given {@link UdpServer}. - * @param src the source of the event - */ - public Event( UdpServer src ){ - super(src); - } - - /** - * Returns the source of the event, a {@link UdpServer}. - * Shorthand for (UdpServer)getSource(). - * @return the server - */ - public UdpServer getUdpServer(){ - return (UdpServer)getSource(); - } - - /** - * Shorthand for getUdpServer().getState(). - * @return the state of the server - * @see UdpServer.State - */ - public UdpServer.State getState(){ - return getUdpServer().getState(); - } - - - /** - * Returns the most recent datagram packet received - * by the {@link UdpServer}. Shorthand for - * getUdpServer().getPacket(). - * @return the most recent datagram - */ - public DatagramPacket getPacket(){ - return getUdpServer().getPacket(); - } - - /** - * Copies and returns the bytes in the most recently - * received packet, or null if not available. - * @return a copy of the datagram's byte array - */ - public byte[] getPacketAsBytes(){ - DatagramPacket packet = getPacket(); - if( packet == null ){ - return null; - } else { - byte[] data = new byte[ packet.getLength() ]; - System.arraycopy( - packet.getData(), packet.getOffset(), - data, 0, data.length ); - return data; - } // end else - } // end getPacketAsBytes - - - /** - * Returns the data in the most recently-received - * packet as if it were a String - * or null if not available. - * @return The datagram as a string - */ - public String getPacketAsString(){ - DatagramPacket packet = getPacket(); - if( packet == null ){ - return null; - } else { - String s = new String( - packet.getData(), - packet.getOffset(), - packet.getLength() ); - return s; - } // end else - } - - } // end static inner class Event - - - -} // end class UdpServer diff --git a/src/main/java/edu/nps/moves/disutil/VariableLengthData.java b/src/main/java/edu/nps/moves/disutil/VariableLengthData.java deleted file mode 100644 index ca5c58a2..00000000 --- a/src/main/java/edu/nps/moves/disutil/VariableLengthData.java +++ /dev/null @@ -1,282 +0,0 @@ - -package edu.nps.moves.disutil; - -import java.io.*; - -/** - * DIS has a frequent problem of shifting between units when describing - * the data length of some fields. This is an attempt to fix that once, - * in hand-written code, rather than generate source code to do it.

- * - * The field has a length, a units descriptor (bytes or bits) and a descriptor - * that tells us whether the record as a whole should end on a 8, 16, 32, or - * 64 bit word boundary, including the length field. - * - * @author DMcG - */ -@Deprecated -public class VariableLengthData -{ - - /** What units does the length field use? Typically bytes (octet) - * but also often bits. bits, bytes, 16 bit words, 32 bit words, - * 64 bit words. - */ - public enum DataLengthUnits { L_BIT, L_OCTET }; - - /** We want the record as a whole to end on a byte, 16 bit word, 32 bit - * word, or 64 bit word boundary, so we pad to reach that. - */ - public enum PadToBoundary { BOUNDARY_8, BOUNDARY_16, BOUNDARY_32, BOUNDARY_64}; - - public long dataLength = 0; - public VariableLengthData.PadToBoundary padToBoundary = PadToBoundary.BOUNDARY_64; - public VariableLengthData.DataLengthUnits dataLengthUnits = DataLengthUnits.L_BIT; - public byte[] data = null; - - - public VariableLengthData() - { - padToBoundary = VariableLengthData.PadToBoundary.BOUNDARY_64; - dataLengthUnits = VariableLengthData.DataLengthUnits.L_BIT; - } - - public int getMarshalledSize() - { - int marshalSize = 0; - marshalSize = marshalSize + 4; - if(data != null) - { - marshalSize = marshalSize + data.length; - } - - return marshalSize; - } - - - public void setDataLength(int dataLength) - { - this.dataLength = dataLength; - } - - public int getDataLength() - { - return (int)this.dataLength; - } - - /** - * Set the data to write. The assumption is that if your data is not - * written to a byte boundary (eg, 17 bits) you have padded the data - * array yourself to at least a byte boundary (eg, 24 bits or three - * bytes in the byte array). The code will handle padding the rest - * to a given byte, short, int, or 64 bit record boundary. - * @param data - */ - public void setData(byte[] data) - { - this.data = data; - } - - /** - * Retrieves data, padded to at least a byte boundary - * @return byte array - */ - public byte[] getData() - { - return this.data; - } - - public void marshal(DataOutputStream dos) - { - try - { - dos.writeInt((int)dataLength); - int dataBytes = 0; - int paddingBytes = 0; - - // This is how long the data field should be written, based - // on the reported field length - int writeLengthInBytes = 0; - if(this.dataLengthUnits == DataLengthUnits.L_BIT) - { - writeLengthInBytes = (int)(dataLength / 8); - int remainder = (int)(dataLength % 8); - if(remainder != 0) - { - writeLengthInBytes++; - } - } - else - { - writeLengthInBytes = (int)this.dataLength; - } - - paddingBytes = this.getPaddingBytes(writeLengthInBytes); - - if(data != null) - { - dos.write(data); - } - - for(int idx = 0; idx < paddingBytes; idx++) - { - dos.writeByte(0); - } - - } - catch(Exception e) - { - System.out.println(e); - } - } - - private int getPaddingBytes(int writeLengthInBytes) - { - int paddingBytes = 0; - - switch(padToBoundary) - { - case BOUNDARY_8: - break; - case BOUNDARY_16: - paddingBytes = writeLengthInBytes % 2; - break; - case BOUNDARY_32: - paddingBytes = writeLengthInBytes % 4; - break; - - case BOUNDARY_64: - paddingBytes = writeLengthInBytes % 8; - break; - - default: - break; - } - - return paddingBytes; - } - - public void unmarshal(DataInputStream dis) - { - try - { - int dataBytesToRead = 0; - dataLength = dis.readInt(); - if(dataLengthUnits == DataLengthUnits.L_BIT) - { - dataBytesToRead = (int)dataLength / 8; - - if(dataLength % 8 != 0) - { - dataBytesToRead++; - } - } - else - { - dataBytesToRead = (int)this.dataLength; - } - - data = new byte[dataBytesToRead]; - for(int idx = 0; idx < dataBytesToRead; idx++) - { - data[idx] = dis.readByte(); - } - - // read and throw away padding bytes - int paddingBytes = this.getPaddingBytes(data.length); - for(int idx = 0; idx < paddingBytes; idx++) - { - dis.readByte(); - } - - } - catch(Exception e) - { - System.out.println(e); - e.printStackTrace(); - } - } - -public void marshal(java.nio.ByteBuffer buff) -{ - try - { - int paddingBytes = 0; - - buff.putInt( (int)dataLength); - - for(int idx = 0; idx < data.length; idx++) - { - buff.put((byte)data[idx]); - } // end of array marshaling - - // This is how long the data field should be written, based - // on the reported field length - int writeLengthInBytes = 0; - if(this.dataLengthUnits == DataLengthUnits.L_BIT) - { - writeLengthInBytes = (int)(dataLength / 8); - int remainder = (int)(dataLength % 8); - if(remainder != 0) - { - writeLengthInBytes++; - } - } - else - { - writeLengthInBytes = (int)this.dataLength; - } - - // Write padding bytes to get us on a byte/word/int/64 bit boundary - paddingBytes = this.getPaddingBytes(writeLengthInBytes); - for(int idx = 0; idx < paddingBytes; idx++) - { - buff.put((byte)0); - } - - } - catch(Exception e) - { - System.out.println(e); - e.printStackTrace(); - } -} - - public void unmarshal(java.nio.ByteBuffer buff) - { - try - { - int dataBytesToRead = 0; - dataLength = buff.getInt(); - if(dataLengthUnits == DataLengthUnits.L_BIT) - { - dataBytesToRead = (int)dataLength / 8; - - if(dataLength % 8 != 0) - { - dataBytesToRead++; - } - } - - data = new byte[dataBytesToRead]; - for(int idx = 0; idx < dataBytesToRead; idx++) - { - data[idx] = buff.get(); - } - - // read and throw away padding bytes - int paddingBytes = this.getPaddingBytes(data.length); - for(int idx = 0; idx < paddingBytes; idx++) - { - buff.get(); - } - - } - catch(Exception e) - { - System.out.println(e); - e.printStackTrace(); - } - } - -} diff --git a/src/main/java/edu/nps/moves/net/BehaviorConsumerIF.java b/src/main/java/edu/nps/moves/net/BehaviorConsumerIF.java deleted file mode 100644 index 81eaa75b..00000000 --- a/src/main/java/edu/nps/moves/net/BehaviorConsumerIF.java +++ /dev/null @@ -1,56 +0,0 @@ -/* - Copyright (c) 1995-2009 held by the author(s). All rights reserved. - -Redistribution and use in source and binary forms, with or without -modification, are permitted provided that the following conditions -are met: - - * Redistributions of source code must retain the above copyright - notice, this list of conditions and the following disclaimer. - * Redistributions in binary form must reproduce the above copyright - notice, this list of conditions and the following disclaimer - in the documentation and/or other materials provided with the - distribution. - * Neither the names of the Naval Postgraduate School (NPS) - Modeling Virtual Environments and Simulation (MOVES) Institute - (http://www.nps.edu and http://www.movesinstitute.org) - nor the names of its contributors may be used to endorse or - promote products derived from this software without specific - prior written permission. - -THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS -"AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT -LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS -FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE -COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, -INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, -BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; -LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER -CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT -LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN -ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE -POSSIBILITY OF SUCH DAMAGE. -*/ -package edu.nps.moves.net; - -import edu.nps.moves.dis.Pdu; - -/** - * BehaviorConsumer is the listening part of the listener pattern. The - * other half of this is the BehaviorProducer interface. This - * receives data when the BehaviorProducer notifies us of an arriving - * PDU. - * - * @author DMcG - * @version $Id:$ - */ -@Deprecated -public interface BehaviorConsumerIF { - - /** - * Receives a PDU from the BehaviorProducer. - * - * @param pdu the Pdu received and generated by the BehaviorProducer - */ - void receivePdu(Pdu pdu); -} diff --git a/src/main/java/edu/nps/moves/net/BehaviorConsumerThreaded.java b/src/main/java/edu/nps/moves/net/BehaviorConsumerThreaded.java deleted file mode 100644 index f0d796c3..00000000 --- a/src/main/java/edu/nps/moves/net/BehaviorConsumerThreaded.java +++ /dev/null @@ -1,64 +0,0 @@ -package edu.nps.moves.net; - -import java.util.*; - -import edu.nps.moves.dis.*; - -/** - * Example threaded implementation of the BehaviorConsumerIF interface.

- * - * A threaded BehaviorConsumer should be used if it takes a long time to - * process each DIS packet, or if you want to process the packets in your - * own thread, rather than the thread used in the BehaviorProducer. - * - * @see BehaviorProducerIF - * @see BehaviorConsumerIF - * - * @author DMcG - */ -@Deprecated -public class BehaviorConsumerThreaded implements BehaviorConsumerIF, Runnable { - - private Vector receivedPdus; - - public BehaviorConsumerThreaded() { - receivedPdus = new Vector(); - } - - /** - * Receives a PDU from the BehaviorProducer. - * - * @param pdu the ProtocolDataUnit generated by the BehaviorProducer - */ - public void receivePdu(Pdu pdu) { - System.out.println("Got pdu from producer"); - synchronized (receivedPdus) { - receivedPdus.add(pdu); - } - } - - /** - * Implementation of the Runnable interface - */ - public void run() { - while (true) { - while (true) // Yield the thread until we receive data - { - synchronized (receivedPdus) { - if (receivedPdus.size() == 0) { - Thread.yield(); - } else { - break; - } - } - } - - // Print out how many we received, and create a new vector. - synchronized (receivedPdus) { - System.out.println("PDUs received: " + receivedPdus.size()); - receivedPdus = new Vector(); - } - - } // end of main wait loop - } -} \ No newline at end of file diff --git a/src/main/java/edu/nps/moves/net/BehaviorProducerIF.java b/src/main/java/edu/nps/moves/net/BehaviorProducerIF.java deleted file mode 100644 index ff378fab..00000000 --- a/src/main/java/edu/nps/moves/net/BehaviorProducerIF.java +++ /dev/null @@ -1,67 +0,0 @@ -/* - Copyright (c) 1995-2009 held by the author(s). All rights reserved. - -Redistribution and use in source and binary forms, with or without -modification, are permitted provided that the following conditions -are met: - - * Redistributions of source code must retain the above copyright - notice, this list of conditions and the following disclaimer. - * Redistributions in binary form must reproduce the above copyright - notice, this list of conditions and the following disclaimer - in the documentation and/or other materials provided with the - distribution. - * Neither the names of the Naval Postgraduate School (NPS) - Modeling Virtual Environments and Simulation (MOVES) Institute - (http://www.nps.edu and http://www.movesinstitute.org) - nor the names of its contributors may be used to endorse or - promote products derived from this software without specific - prior written permission. - -THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS -"AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT -LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS -FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE -COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, -INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, -BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; -LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER -CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT -LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN -ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE -POSSIBILITY OF SUCH DAMAGE. -*/ -package edu.nps.moves.net; - -/** - * The BehaviorProducer interface describes a class that listens - * in its own thread for PDUs, then notifies any listeners when - * they arrive. - * - * This implements a listener pattern. Those interested in hearing - * from the BehaviorProducerIF register with the object. When the BehaviorProducerIF - * gets (or produces) a PDU, it notifies all listeners. Note that there is - * no attempt to limit which listeners/consumers receive the PDU. - * - * @author DMcG - * @version $Id:$ - */ -@Deprecated - public interface BehaviorProducerIF { - - /** - * Add a listener that will be notified when a PDU is - * ready. - * - * @param consumer the object that will be notified of the PDU - */ - void addListener(BehaviorConsumerIF consumer); - - /** - * Remove a listener/consumer of PDUs from the notification list. - * - * @param consumer to be removed from the notification list - */ - void removeListener(BehaviorConsumerIF consumer); - - } diff --git a/src/main/java/edu/nps/moves/net/BehaviorProducerUDP.java b/src/main/java/edu/nps/moves/net/BehaviorProducerUDP.java deleted file mode 100644 index e3fbdd6a..00000000 --- a/src/main/java/edu/nps/moves/net/BehaviorProducerUDP.java +++ /dev/null @@ -1,160 +0,0 @@ -/* - Copyright (c) 1995-2009 held by the author(s). All rights reserved. - -Redistribution and use in source and binary forms, with or without -modification, are permitted provided that the following conditions -are met: - - * Redistributions of source code must retain the above copyright - notice, this list of conditions and the following disclaimer. - * Redistributions in binary form must reproduce the above copyright - notice, this list of conditions and the following disclaimer - in the documentation and/or other materials provided with the - distribution. - * Neither the names of the Naval Postgraduate School (NPS) - Modeling Virtual Environments and Simulation (MOVES) Institute - (http://www.nps.edu and http://www.movesinstitute.org) - nor the names of its contributors may be used to endorse or - promote products derived from this software without specific - prior written permission. - -THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS -"AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT -LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS -FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE -COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, -INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, -BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; -LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER -CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT -LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN -ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE -POSSIBILITY OF SUCH DAMAGE. -*/ -package edu.nps.moves.net; - -import java.io.IOException; -import java.net.DatagramPacket; -import java.net.DatagramSocket; -import java.net.InetAddress; -import java.nio.ByteBuffer; -import java.util.Vector; - -import edu.nps.moves.dis.Pdu; -import edu.nps.moves.disutil.PduFactory; -import java.nio.Buffer; - -/** - * This implements an object that can read and write DIS PDUs from a unicast - * or multicast UDP socket. It implements the BehaviorProducer interface, - * which allows objects to register as listeners for PDU arrival events, - * and the BehaviorWriter interface, which allows PDUs to be written. It's - * a bit complex internally, but not all that bad from an interface standpoint.

- * - * This runs in a thread of its own. The listeners for PDU events can either - * run in threads of their own, which is a bit complex, or simply process - * PDU objects as they come in, which is simple but may have performance - * problems if processing a PDU takes a long time.

- * - * @author DMcG - */ -@Deprecated -public class BehaviorProducerUDP implements BehaviorProducerIF, // Listener pattern for pdus - BehaviorWriterIF, // IF for writing DIS pdus - Runnable // Threaded object -{ - - /** People who listen to us for PDU events. This is a Vector rather than - * the preferred List to preserve compatability with older VRML browsers - * that don't have the newer List interface. - */ - private Vector behaviorConsumerListeners; - - /** - * Socket (multicast or unicast) that sends and receives data - */ - private final DatagramSocket socket; - private DatagramPacket packet; - private Pdu pdu; - private PduFactory pduf; - - /** An allocated receive only buffer */ - private ByteBuffer buffer; - - public BehaviorProducerUDP(DatagramSocket pSocket) { - behaviorConsumerListeners = new Vector(); - socket = pSocket; - buffer = ByteBuffer.allocate(MTU_SIZE); - packet = new DatagramPacket(buffer.array(), buffer.capacity()); - - // Doesn't use FastEntityStatePdu (by default) - pduf = new PduFactory(); - } - - public void addListener(BehaviorConsumerIF consumer) { - // Add it only if absent, so we don't get dupe copies. - if (!(behaviorConsumerListeners.contains(consumer))) { - behaviorConsumerListeners.add(consumer); - } - } - - public void removeListener(BehaviorConsumerIF consumer) { - behaviorConsumerListeners.remove(consumer); - } - - public void setDefaultDestination(InetAddress addr, int port) { - packet.setAddress(addr); - packet.setPort(port); - } - - public void write(ByteBuffer buffer) { - packet.setData(buffer.array()); - try { - socket.send(packet); - } catch (IOException ioe) { - System.out.println(ioe); - } - } - - /** - * If we have a byte buffer we are marshalling to, it may be bigger than the - * actuall size of the marshalled PDU. This writes only the first numberOfBytes - * bytes of the ByteBuffer to the network. - * - * @param buffer - * @param numberOfBytes - */ - public void write(ByteBuffer buffer, int numberOfBytes) { - byte[] normalBuffer = buffer.array(); - packet.setData(normalBuffer, 0, numberOfBytes); - try { - socket.send(packet); - } catch (IOException ioe) { - System.out.println(ioe); - } - } - - /** Entry point for thread */ - public void run() { - - while (true) { - try { - final Buffer buff = buffer.rewind(); - socket.receive(packet); - - // ByteBuffers are not thread safe - synchronized (buff) { - pdu = pduf.createPdu(buffer); - if (pdu != null) { - for (BehaviorConsumerIF consumer : behaviorConsumerListeners) { - consumer.receivePdu(pdu); - } - } - } - } catch (IOException ioe) { - System.out.println(ioe); - } - } - } - -} // end class file BehaviorProducerUDP.java \ No newline at end of file diff --git a/src/main/java/edu/nps/moves/net/BehaviorWriterIF.java b/src/main/java/edu/nps/moves/net/BehaviorWriterIF.java deleted file mode 100644 index 75339aa3..00000000 --- a/src/main/java/edu/nps/moves/net/BehaviorWriterIF.java +++ /dev/null @@ -1,72 +0,0 @@ -/* - Copyright (c) 1995-2009 held by the author(s). All rights reserved. - -Redistribution and use in source and binary forms, with or without -modification, are permitted provided that the following conditions -are met: - - * Redistributions of source code must retain the above copyright - notice, this list of conditions and the following disclaimer. - * Redistributions in binary form must reproduce the above copyright - notice, this list of conditions and the following disclaimer - in the documentation and/or other materials provided with the - distribution. - * Neither the names of the Naval Postgraduate School (NPS) - Modeling Virtual Environments and Simulation (MOVES) Institute - (http://www.nps.edu and http://www.movesinstitute.org) - nor the names of its contributors may be used to endorse or - promote products derived from this software without specific - prior written permission. - -THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS -"AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT -LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS -FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE -COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, -INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, -BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; -LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER -CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT -LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN -ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE -POSSIBILITY OF SUCH DAMAGE. -*/ -package edu.nps.moves.net; - -import java.net.InetAddress; -import java.nio.ByteBuffer; - -/** - * This interface lets you set up some very general defaults, which - * will be handled by the concrete implementations.

- * - * In general, you write to a destination. That destination is represented - * by an IP address and a port. You can also set a "default destination", where - * things will go unless you specify otherwise.

- * - * @author DMcG - * @version $Id:$ - */ -@Deprecated -public interface BehaviorWriterIF { - - /** The (rough) size of an ethernet frame */ - static final int MTU_SIZE = 1500; - - /** - * Set the default destination that the plain write(pdu) method - * will send data to. - * - * @param addr first object that describes destination (eg, IP) - * @param port second object that describes destination (eg, port number) - */ - void setDefaultDestination(InetAddress addr, int port); - - /** - * Write PDU information to the default destination. The user must clear - * the buffer if it is desired to be reused. - * - * @param buffer the DIS PDU infomation to be written - */ - void write(ByteBuffer buffer); -} diff --git a/src/test/java/edu/nps/moves/deadreckoning/DeadReckonerTest.java b/src/test/java/edu/nps/moves/deadreckoning/DeadReckonerTest.java index fce87857..25266f0f 100644 --- a/src/test/java/edu/nps/moves/deadreckoning/DeadReckonerTest.java +++ b/src/test/java/edu/nps/moves/deadreckoning/DeadReckonerTest.java @@ -369,226 +369,6 @@ public void testPerform_DR9halfStep() { answers9(espdu8); } - // DIS_DeadReckoning et al - - @Test - public void testStatic01B() throws Exception { - DIS_DR_Static_01 disDr = new DIS_DR_Static_01(); - disDr.setNewAll(toAllDis(espdu4)); - disDr.setInitTimestamp(espdu4.getTimestamp()); - disDr.setFPS(FRAMES_PER_SECOND); - disDr.update(); - double[] newLoc = disDr.getUpdatedPositionOrientation(); - double[] newVel = disDr.getUpdatedVelocity(); - long timestamp = disDr.getUpdatedTimestamp(); - fromNewLocVelTimestamp(newLoc, newVel, timestamp, espdu4); - answers1B(espdu4); - } - - @Test - public void testFpw02() throws Exception { - DIS_DR_FPW_02 disDr = new DIS_DR_FPW_02(); - disDr.setNewAll(toAllDis(espdu4)); - disDr.setInitTimestamp(espdu4.getTimestamp()); - disDr.setFPS(FRAMES_PER_SECOND); - disDr.update(); - double[] newLoc = disDr.getUpdatedPositionOrientation(); - double[] newVel = disDr.getUpdatedVelocity(); - long timestamp = disDr.getUpdatedTimestamp(); - fromNewLocVelTimestamp(newLoc, newVel, timestamp, espdu4); - answers2(espdu4); - } - - @Test - public void testRpw03() throws Exception { - DIS_DR_RPW_03 disDr = new DIS_DR_RPW_03(); - disDr.setNewAll(toAllDis(espdu4)); - disDr.setInitTimestamp(espdu4.getTimestamp()); - disDr.setFPS(FRAMES_PER_SECOND); - disDr.update(); - double[] newLoc = disDr.getUpdatedPositionOrientation(); - double[] newVel = disDr.getUpdatedVelocity(); - long timestamp = disDr.getUpdatedTimestamp(); - fromNewLocVelTimestamp(newLoc, newVel, timestamp, espdu4); - answers3(espdu4); - } - - @Test - public void testRvw04() throws Exception { - DIS_DR_RVW_04 disDr = new DIS_DR_RVW_04(); - disDr.setNewAll(toAllDis(espdu4)); - disDr.setInitTimestamp(espdu4.getTimestamp()); - disDr.setFPS(FRAMES_PER_SECOND); - disDr.update(); - double[] newLoc = disDr.getUpdatedPositionOrientation(); - double[] newVel = disDr.getUpdatedVelocity(); - long timestamp = disDr.getUpdatedTimestamp(); - fromNewLocVelTimestamp(newLoc, newVel, timestamp, espdu4); - answers4(espdu4); - } - - @Test - public void testRvw04halfStep() throws Exception { - DIS_DR_RVW_04 disDr = new DIS_DR_RVW_04(); - disDr.setNewAll(toAllDis(espdu4)); - disDr.setInitTimestamp(espdu4.getTimestamp()); - disDr.setFPS(2 * FRAMES_PER_SECOND); - disDr.update(); - disDr.update(); - double[] newLoc = disDr.getUpdatedPositionOrientation(); - double[] newVel = disDr.getUpdatedVelocity(); - long timestamp = disDr.getUpdatedTimestamp(); - fromNewLocVelTimestamp(newLoc, newVel, timestamp, espdu4); - answers4(espdu4); - } - - // DIS_DR_RPW_03b and DIS_DR_RVW_04b do not follow IEEE Std 1278.1 - // and should be deprecated immediately! - - @Test - public void testFvw05() throws Exception { - DIS_DR_FVW_05 disDr = new DIS_DR_FVW_05(); - disDr.setNewAll(toAllDis(espdu4)); - disDr.setInitTimestamp(espdu4.getTimestamp()); - disDr.setFPS(FRAMES_PER_SECOND); - disDr.update(); - double[] newLoc = disDr.getUpdatedPositionOrientation(); - double[] newVel = disDr.getUpdatedVelocity(); - long timestamp = disDr.getUpdatedTimestamp(); - fromNewLocVelTimestamp(newLoc, newVel, timestamp, espdu4); - answers5(espdu4); - } - - @Test - public void testFvw05halfStep() throws Exception { - DIS_DR_FVW_05 disDr = new DIS_DR_FVW_05(); - disDr.setNewAll(toAllDis(espdu4)); - disDr.setInitTimestamp(espdu4.getTimestamp()); - disDr.setFPS(2 * FRAMES_PER_SECOND); - disDr.update(); - disDr.update(); - double[] newLoc = disDr.getUpdatedPositionOrientation(); - double[] newVel = disDr.getUpdatedVelocity(); - long timestamp = disDr.getUpdatedTimestamp(); - fromNewLocVelTimestamp(newLoc, newVel, timestamp, espdu4); - answers5(espdu4); - } - - @Test - public void testStatic01W() throws Exception { - DIS_DR_Static_01 disDr = new DIS_DR_Static_01(); - disDr.setNewAll(toAllDis(espdu8)); - disDr.setInitTimestamp(espdu8.getTimestamp()); - disDr.setFPS(FRAMES_PER_SECOND); - disDr.update(); - double[] newLoc = disDr.getUpdatedPositionOrientation(); - double[] newVel = disDr.getUpdatedVelocity(); - long timestamp = disDr.getUpdatedTimestamp(); - fromNewLocVelTimestamp(newLoc, newVel, timestamp, espdu8); - answers1W(espdu8); - } - - @Test - public void testFpb06() throws Exception { - DIS_DR_FPB_06 disDr = new DIS_DR_FPB_06(); - disDr.setNewAll(toAllDis(espdu8)); - disDr.setInitTimestamp(espdu8.getTimestamp()); - disDr.setFPS(FRAMES_PER_SECOND); - disDr.update(); - double[] newLoc = disDr.getUpdatedPositionOrientation(); - double[] newVel = disDr.getUpdatedVelocity(); - long timestamp = disDr.getUpdatedTimestamp(); - fromNewLocVelTimestamp(newLoc, newVel, timestamp, espdu8); - answers6(espdu8); - } - - @Test - public void testRpb07() throws Exception { - DIS_DR_RPB_07 disDr = new DIS_DR_RPB_07(); - disDr.setNewAll(toAllDis(espdu8)); - disDr.setInitTimestamp(espdu8.getTimestamp()); - disDr.setFPS(FRAMES_PER_SECOND); - disDr.update(); - double[] newLoc = disDr.getUpdatedPositionOrientation(); - double[] newVel = disDr.getUpdatedVelocity(); - long timestamp = disDr.getUpdatedTimestamp(); - fromNewLocVelTimestamp(newLoc, newVel, timestamp, espdu8); - answers7(espdu8); - } - - @Test - public void testRpb07HalfStep() throws Exception { - DIS_DR_RPB_07 disDr = new DIS_DR_RPB_07(); - disDr.setNewAll(toAllDis(espdu8)); - disDr.setInitTimestamp(espdu8.getTimestamp()); - disDr.setFPS(2 * FRAMES_PER_SECOND); - disDr.update(); - disDr.update(); - double[] newLoc = disDr.getUpdatedPositionOrientation(); - double[] newVel = disDr.getUpdatedVelocity(); - long timestamp = disDr.getUpdatedTimestamp(); - fromNewLocVelTimestamp(newLoc, newVel, timestamp, espdu8); - answers7(espdu8); - } - - @Test - public void testRvb08() throws Exception { - DIS_DR_RVB_08 disDr = new DIS_DR_RVB_08(); - disDr.setNewAll(toAllDis(espdu8)); - disDr.setInitTimestamp(espdu8.getTimestamp()); - disDr.setFPS(FRAMES_PER_SECOND); - disDr.update(); - double[] newLoc = disDr.getUpdatedPositionOrientation(); - double[] newVel = disDr.getUpdatedVelocity(); - long timestamp = disDr.getUpdatedTimestamp(); - fromNewLocVelTimestamp(newLoc, newVel, timestamp, espdu8); - answers8(espdu8); - } - - @Test - public void testRvb08halfStep() throws Exception { - DIS_DR_RVB_08 disDr = new DIS_DR_RVB_08(); - disDr.setNewAll(toAllDis(espdu8)); - disDr.setInitTimestamp(espdu8.getTimestamp()); - disDr.setFPS(2 * FRAMES_PER_SECOND); - disDr.update(); - disDr.update(); - double[] newLoc = disDr.getUpdatedPositionOrientation(); - double[] newVel = disDr.getUpdatedVelocity(); - long timestamp = disDr.getUpdatedTimestamp(); - fromNewLocVelTimestamp(newLoc, newVel, timestamp, espdu8); - answers8(espdu8); - } - - @Test - public void testFvb09() throws Exception { - DIS_DR_FVB_09 disDr = new DIS_DR_FVB_09(); - disDr.setNewAll(toAllDis(espdu8)); - disDr.setInitTimestamp(espdu8.getTimestamp()); - disDr.setFPS(FRAMES_PER_SECOND); - disDr.update(); - double[] newLoc = disDr.getUpdatedPositionOrientation(); - double[] newVel = disDr.getUpdatedVelocity(); - long timestamp = disDr.getUpdatedTimestamp(); - fromNewLocVelTimestamp(newLoc, newVel, timestamp, espdu8); - answers9(espdu8); - } - - @Test - public void testFvb09halfStep() throws Exception { - DIS_DR_FVB_09 disDr = new DIS_DR_FVB_09(); - disDr.setNewAll(toAllDis(espdu8)); - disDr.setInitTimestamp(espdu8.getTimestamp()); - disDr.setFPS(2 * FRAMES_PER_SECOND); - disDr.update(); - disDr.update(); - double[] newLoc = disDr.getUpdatedPositionOrientation(); - double[] newVel = disDr.getUpdatedVelocity(); - long timestamp = disDr.getUpdatedTimestamp(); - fromNewLocVelTimestamp(newLoc, newVel, timestamp, espdu8); - answers9(espdu8); - } - @Test public void testCwCircle() { double gravity = 10.0; // Rounded from 9.8 m/s^2 @@ -880,78 +660,6 @@ public void testCcwCircle() { } // zero angular velocity tests - - @Test - public void testRpw03omega0() throws Exception { - espdu4.getDeadReckoningParameters().getEntityAngularVelocity().setX(0.0f); - espdu4.getDeadReckoningParameters().getEntityAngularVelocity().setY(0.0f); - espdu4.getDeadReckoningParameters().getEntityAngularVelocity().setZ(0.0f); - - DIS_DR_RPW_03 disDr = new DIS_DR_RPW_03(); - disDr.setNewAll(toAllDis(espdu4)); - disDr.setInitTimestamp(espdu4.getTimestamp()); - disDr.setFPS(FRAMES_PER_SECOND); - disDr.update(); - double[] newLoc = disDr.getUpdatedPositionOrientation(); - double[] newVel = disDr.getUpdatedVelocity(); - long timestamp = disDr.getUpdatedTimestamp(); - fromNewLocVelTimestamp(newLoc, newVel, timestamp, espdu4); - answers2(espdu4); // NOTE: With zero angular velocity, DR3 should get same results as DR2 - } - - @Test - public void testRvw04omega0() throws Exception { - espdu4.getDeadReckoningParameters().getEntityAngularVelocity().setX(0.0f); - espdu4.getDeadReckoningParameters().getEntityAngularVelocity().setY(0.0f); - espdu4.getDeadReckoningParameters().getEntityAngularVelocity().setZ(0.0f); - - DIS_DR_RVW_04 disDr = new DIS_DR_RVW_04(); - disDr.setNewAll(toAllDis(espdu4)); - disDr.setInitTimestamp(espdu4.getTimestamp()); - disDr.setFPS(FRAMES_PER_SECOND); - disDr.update(); - double[] newLoc = disDr.getUpdatedPositionOrientation(); - double[] newVel = disDr.getUpdatedVelocity(); - long timestamp = disDr.getUpdatedTimestamp(); - fromNewLocVelTimestamp(newLoc, newVel, timestamp, espdu4); - answers5(espdu4); // NOTE: With zero angular velocity, DR4 should get same results as DR5 - } - - @Test - public void testRpb07omega0() throws Exception { - espdu8.getDeadReckoningParameters().getEntityAngularVelocity().setX(0.0f); - espdu8.getDeadReckoningParameters().getEntityAngularVelocity().setY(0.0f); - espdu8.getDeadReckoningParameters().getEntityAngularVelocity().setZ(0.0f); - - DIS_DR_RPB_07 disDr = new DIS_DR_RPB_07(); - disDr.setNewAll(toAllDis(espdu8)); - disDr.setInitTimestamp(espdu8.getTimestamp()); - disDr.setFPS(FRAMES_PER_SECOND); - disDr.update(); - double[] newLoc = disDr.getUpdatedPositionOrientation(); - double[] newVel = disDr.getUpdatedVelocity(); - long timestamp = disDr.getUpdatedTimestamp(); - fromNewLocVelTimestamp(newLoc, newVel, timestamp, espdu8); - answers6(espdu8); // NOTE: With zero angular velocity, DR7 should get same results as DR6 - } - - @Test - public void testRvb08omega0() throws Exception { - espdu8.getDeadReckoningParameters().getEntityAngularVelocity().setX(0.0f); - espdu8.getDeadReckoningParameters().getEntityAngularVelocity().setY(0.0f); - espdu8.getDeadReckoningParameters().getEntityAngularVelocity().setZ(0.0f); - - DIS_DR_RVB_08 disDr = new DIS_DR_RVB_08(); - disDr.setNewAll(toAllDis(espdu8)); - disDr.setInitTimestamp(espdu8.getTimestamp()); - disDr.setFPS(FRAMES_PER_SECOND); - disDr.update(); - double[] newLoc = disDr.getUpdatedPositionOrientation(); - double[] newVel = disDr.getUpdatedVelocity(); - long timestamp = disDr.getUpdatedTimestamp(); - fromNewLocVelTimestamp(newLoc, newVel, timestamp, espdu8); - answers9(espdu8); // NOTE: With zero angular velocity, DR8 should get same results as DR9 - } @Test public void testPerform_DR3omega0() { diff --git a/src/test/java/edu/nps/moves/disutil/PduFactoryTest.java b/src/test/java/edu/nps/moves/disutil/PduFactoryTest.java index 8bf40607..52baaf85 100644 --- a/src/test/java/edu/nps/moves/disutil/PduFactoryTest.java +++ b/src/test/java/edu/nps/moves/disutil/PduFactoryTest.java @@ -32,7 +32,6 @@ import edu.nps.moves.dis.EnvironmentalProcessPdu; import edu.nps.moves.dis.EventReportPdu; import edu.nps.moves.dis.EventReportReliablePdu; -import edu.nps.moves.dis.FastEntityStatePdu; import edu.nps.moves.dis.FirePdu; import edu.nps.moves.dis.GriddedDataPdu; import edu.nps.moves.dis.IntercomControlPdu; @@ -157,19 +156,6 @@ public void testCreatePduByteBuffer() { assertTrue(pduFactory.createPdu(ByteBuffer.wrap(new EntityStatePdu().marshal())) instanceof EntityStatePdu); // etc. previous test gives coverage } - - @Test - public void testUseFastPdu() { - PduFactory pduFactory = new PduFactory(false); - // No matter which you start with, createPdu returns EntityStatePdu - assertTrue(pduFactory.createPdu(new EntityStatePdu().marshal()) instanceof EntityStatePdu); - assertTrue(pduFactory.createPdu(new FastEntityStatePdu().marshal()) instanceof EntityStatePdu); - - pduFactory = new PduFactory(true); - // No matter which you start with, createPdu returns FastEntityStatePdu - assertTrue(pduFactory.createPdu(new EntityStatePdu().marshal()) instanceof FastEntityStatePdu); - assertTrue(pduFactory.createPdu(new FastEntityStatePdu().marshal()) instanceof FastEntityStatePdu); - } @Test public void testUnsupportedPduType() throws IOException {