From ba4d552c018c63b3dd437e356df17ce0f8a595bb Mon Sep 17 00:00:00 2001 From: Paul Bender Date: Wed, 7 Mar 2018 14:57:28 -0500 Subject: [PATCH 01/58] iuse a more descriptive name for thread. --- java/src/jmri/jmrix/sprog/SprogTrafficController.java | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/java/src/jmri/jmrix/sprog/SprogTrafficController.java b/java/src/jmri/jmrix/sprog/SprogTrafficController.java index 50af5b5264c..ebd5c0b25f0 100644 --- a/java/src/jmri/jmrix/sprog/SprogTrafficController.java +++ b/java/src/jmri/jmrix/sprog/SprogTrafficController.java @@ -50,7 +50,7 @@ public class SprogTrafficController implements SprogInterface, SerialPortEventLi public SprogTrafficController(SprogSystemConnectionMemo adaptermemo) { memo = adaptermemo; tcThread = new Thread(this); - tcThread.setName("TC thread"); + tcThread.setName("SPROG TC thread"); tcThread.setPriority(Thread.MAX_PRIORITY-1); tcThread.start(); } From 3e3488bfeaa0a7a000089545b4c4d9a6d28cd30d Mon Sep 17 00:00:00 2001 From: Paul Bender Date: Thu, 8 Mar 2018 11:44:54 -0500 Subject: [PATCH 02/58] WIP reducing threads for openlcb tests. --- .../jmrix/openlcb/OlcbConfigurationManagerTest.java | 6 ++++-- .../jmri/jmrix/openlcb/OlcbSensorManagerTest.java | 5 ++++- java/test/jmri/jmrix/openlcb/OlcbSensorTest.java | 1 + .../jmrix/openlcb/OlcbSystemConnectionMemoTest.java | 1 + java/test/jmri/jmrix/openlcb/OlcbTestInterface.java | 7 +++++++ .../jmri/jmrix/openlcb/OlcbThrottleManagerTest.java | 4 +++- java/test/jmri/jmrix/openlcb/OlcbThrottleTest.java | 5 ++++- .../jmri/jmrix/openlcb/OlcbTurnoutInheritedTest.java | 12 +++++++++++- .../jmri/jmrix/openlcb/OlcbTurnoutManagerTest.java | 5 ++++- java/test/jmri/jmrix/openlcb/OlcbTurnoutTest.java | 1 + .../configurexml/OlcbSensorManagerXmlTest.java | 1 + .../openlcb/configurexml/OlcbSignalMastXmlTest.java | 5 ++++- .../jmri/jmrix/openlcb/swing/ClientActionsTest.java | 2 ++ .../jmri/jmrix/openlcb/swing/hub/HubActionTest.java | 1 + .../jmri/jmrix/openlcb/swing/hub/HubPaneTest.java | 1 + .../swing/networktree/NetworkTreeActionTest.java | 1 + .../swing/networktree/NetworkTreePaneTest.java | 1 + .../openlcb/swing/send/OpenLcbCanSendActionTest.java | 1 + 18 files changed, 52 insertions(+), 8 deletions(-) diff --git a/java/test/jmri/jmrix/openlcb/OlcbConfigurationManagerTest.java b/java/test/jmri/jmrix/openlcb/OlcbConfigurationManagerTest.java index fff12fd3e5d..c6c04b4c666 100644 --- a/java/test/jmri/jmrix/openlcb/OlcbConfigurationManagerTest.java +++ b/java/test/jmri/jmrix/openlcb/OlcbConfigurationManagerTest.java @@ -11,17 +11,17 @@ * @author Paul Bender Copyright (C) 2017 */ public class OlcbConfigurationManagerTest { + + private OlcbSystemConnectionMemo memo; @Test public void testCTor() { - OlcbSystemConnectionMemo memo = OlcbTestInterface.createForLegacyTests(); OlcbConfigurationManager t = new OlcbConfigurationManager(memo); Assert.assertNotNull("exists",t); } @Test public void testConfigureManagers() { - OlcbSystemConnectionMemo memo = OlcbTestInterface.createForLegacyTests(); OlcbConfigurationManager t = new OlcbConfigurationManager(memo); // this tet verifies this does not throw an exception t.configureManagers(); @@ -31,10 +31,12 @@ public void testConfigureManagers() { @Before public void setUp() { JUnitUtil.setUp(); + OlcbSystemConnectionMemo memo = OlcbTestInterface.createForLegacyTests(); } @After public void tearDown() { + memo.getInterface().dispose(); JUnitUtil.tearDown(); } diff --git a/java/test/jmri/jmrix/openlcb/OlcbSensorManagerTest.java b/java/test/jmri/jmrix/openlcb/OlcbSensorManagerTest.java index 363771ebdf4..a1cec8a21a6 100644 --- a/java/test/jmri/jmrix/openlcb/OlcbSensorManagerTest.java +++ b/java/test/jmri/jmrix/openlcb/OlcbSensorManagerTest.java @@ -14,6 +14,8 @@ */ public class OlcbSensorManagerTest extends jmri.managers.AbstractSensorMgrTestBase { + private OlcbSystemConnectionMemo m; + @Override public String getSystemName(int i) { return "MSX010203040506070" + i; @@ -72,7 +74,7 @@ public void testDotted() { public void setUp() { JUnitUtil.setUp(); - OlcbSystemConnectionMemo m = OlcbTestInterface.createForLegacyTests(); + m = OlcbTestInterface.createForLegacyTests(); l = new OlcbSensorManager(m); } @@ -80,6 +82,7 @@ public void setUp() { @After public void tearDown() { l.dispose(); + m.getInterface().dispose(); JUnitUtil.tearDown(); } diff --git a/java/test/jmri/jmrix/openlcb/OlcbSensorTest.java b/java/test/jmri/jmrix/openlcb/OlcbSensorTest.java index 8676c86a8b6..f4d76936d7d 100644 --- a/java/test/jmri/jmrix/openlcb/OlcbSensorTest.java +++ b/java/test/jmri/jmrix/openlcb/OlcbSensorTest.java @@ -320,6 +320,7 @@ protected void setUp() { @Override protected void tearDown() { + t.dispose(); JUnitUtil.tearDown(); } } diff --git a/java/test/jmri/jmrix/openlcb/OlcbSystemConnectionMemoTest.java b/java/test/jmri/jmrix/openlcb/OlcbSystemConnectionMemoTest.java index 78a6720bce8..aa0e7773799 100644 --- a/java/test/jmri/jmrix/openlcb/OlcbSystemConnectionMemoTest.java +++ b/java/test/jmri/jmrix/openlcb/OlcbSystemConnectionMemoTest.java @@ -34,6 +34,7 @@ public void setUp() { @Override @After public void tearDown() { + ((OlcbSystemConnectionMemo)scm).getInterface().dispose(); JUnitUtil.tearDown(); } } diff --git a/java/test/jmri/jmrix/openlcb/OlcbTestInterface.java b/java/test/jmri/jmrix/openlcb/OlcbTestInterface.java index dff02428b31..03dbb6e540f 100644 --- a/java/test/jmri/jmrix/openlcb/OlcbTestInterface.java +++ b/java/test/jmri/jmrix/openlcb/OlcbTestInterface.java @@ -149,4 +149,11 @@ public OlcbConfigurationManager createConfigurationManager() { public CanInterface canInterface; public OlcbInterface iface; public OlcbConfigurationManager configurationManager; + + public void dispose(){ + // terminate the OlcbInterface (and terminate thread) + iface.dispose(); + } + + } diff --git a/java/test/jmri/jmrix/openlcb/OlcbThrottleManagerTest.java b/java/test/jmri/jmrix/openlcb/OlcbThrottleManagerTest.java index 1d762d01757..d7896321d12 100644 --- a/java/test/jmri/jmrix/openlcb/OlcbThrottleManagerTest.java +++ b/java/test/jmri/jmrix/openlcb/OlcbThrottleManagerTest.java @@ -12,18 +12,20 @@ */ public class OlcbThrottleManagerTest extends jmri.managers.AbstractThrottleManagerTestBase { + private OlcbSystemConnectionMemo m; // The minimal setup for log4J @Override @Before public void setUp() { JUnitUtil.setUp(); - OlcbSystemConnectionMemo m = OlcbTestInterface.createForLegacyTests(); + m = OlcbTestInterface.createForLegacyTests(); tm = new OlcbThrottleManager(m,new OlcbConfigurationManagerScaffold(m)); } @After public void tearDown() { + m.getInterface().dispose(); JUnitUtil.tearDown(); } } diff --git a/java/test/jmri/jmrix/openlcb/OlcbThrottleTest.java b/java/test/jmri/jmrix/openlcb/OlcbThrottleTest.java index 5a5213ae571..5a8715d8047 100644 --- a/java/test/jmri/jmrix/openlcb/OlcbThrottleTest.java +++ b/java/test/jmri/jmrix/openlcb/OlcbThrottleTest.java @@ -13,6 +13,8 @@ * @author Bob Jacobsen Copyright 2008, 2010, 2011 */ public class OlcbThrottleTest extends jmri.jmrix.AbstractThrottleTest { + + private OlcbSystemConnectionMemo m; /** * Test of getIsForward method, of class AbstractThrottle. @@ -359,7 +361,7 @@ public void testSendFunctionGroup5() { @Before public void setUp() { JUnitUtil.setUp(); - OlcbSystemConnectionMemo m = OlcbTestInterface.createForLegacyTests(); + m = OlcbTestInterface.createForLegacyTests(); OlcbConfigurationManager ocm = new OlcbConfigurationManagerScaffold(m); m.configureManagers(); ocm.configureManagers(); @@ -369,6 +371,7 @@ public void setUp() { @Override @After public void tearDown() { + m.getInterface().dispose(); JUnitUtil.tearDown(); } } diff --git a/java/test/jmri/jmrix/openlcb/OlcbTurnoutInheritedTest.java b/java/test/jmri/jmrix/openlcb/OlcbTurnoutInheritedTest.java index 32fa44d00a1..785bc0cd3f2 100644 --- a/java/test/jmri/jmrix/openlcb/OlcbTurnoutInheritedTest.java +++ b/java/test/jmri/jmrix/openlcb/OlcbTurnoutInheritedTest.java @@ -1,6 +1,9 @@ package jmri.jmrix.openlcb; +import jmri.util.JUnitUtil; import jmri.implementation.AbstractTurnoutTestBase; +import org.junit.Before; +import org.junit.After; /** * Tests inherited from the abstract turnout test base, specialized for the OlcbTurnout. This is @@ -14,8 +17,9 @@ public class OlcbTurnoutInheritedTest extends AbstractTurnoutTestBase { int baselineListeners; @Override + @Before public void setUp() { - apps.tests.Log4JFixture.setUp(); + JUnitUtil.setUp(); tif = new OlcbTestInterface(); tif.waitForStartup(); baselineListeners = tif.iface.numMessageListeners(); @@ -24,6 +28,12 @@ public void setUp() { t = ot; } + @After + public void tearDown() { + tif.dispose(); + JUnitUtil.tearDown(); + } + @Override public int numListeners() { return tif.iface.numMessageListeners() - baselineListeners; diff --git a/java/test/jmri/jmrix/openlcb/OlcbTurnoutManagerTest.java b/java/test/jmri/jmrix/openlcb/OlcbTurnoutManagerTest.java index 57db0030aad..0319d3c2930 100644 --- a/java/test/jmri/jmrix/openlcb/OlcbTurnoutManagerTest.java +++ b/java/test/jmri/jmrix/openlcb/OlcbTurnoutManagerTest.java @@ -14,6 +14,8 @@ */ public class OlcbTurnoutManagerTest extends jmri.managers.AbstractTurnoutMgrTestBase { + private OlcbSystemConnectionMemo m; + @Override public String getSystemName(int i) { return "MTX010203040506070" + i + ";X010203040506070" + (i - 1); @@ -50,7 +52,7 @@ public void testDefaultSystemName() { public void setUp() { JUnitUtil.setUp(); - OlcbSystemConnectionMemo m = OlcbTestInterface.createForLegacyTests(); + m = OlcbTestInterface.createForLegacyTests(); l = new OlcbTurnoutManager(m); } @@ -58,6 +60,7 @@ public void setUp() { @After public void tearDown() { l.dispose(); + m.getInterface().dispose(); JUnitUtil.tearDown(); } diff --git a/java/test/jmri/jmrix/openlcb/OlcbTurnoutTest.java b/java/test/jmri/jmrix/openlcb/OlcbTurnoutTest.java index 0509dbcd305..9cf8b785c7e 100644 --- a/java/test/jmri/jmrix/openlcb/OlcbTurnoutTest.java +++ b/java/test/jmri/jmrix/openlcb/OlcbTurnoutTest.java @@ -408,6 +408,7 @@ protected void setUp() { @Override protected void tearDown() { + t.dispose(); JUnitUtil.tearDown(); } } diff --git a/java/test/jmri/jmrix/openlcb/configurexml/OlcbSensorManagerXmlTest.java b/java/test/jmri/jmrix/openlcb/configurexml/OlcbSensorManagerXmlTest.java index 388db1e5b08..902dd743ec8 100644 --- a/java/test/jmri/jmrix/openlcb/configurexml/OlcbSensorManagerXmlTest.java +++ b/java/test/jmri/jmrix/openlcb/configurexml/OlcbSensorManagerXmlTest.java @@ -102,6 +102,7 @@ public void testSaveAndRestoreWithProperties() throws Exception { expected = new CanMessage(new byte[]{1,2,3,4,5,6,7,8}, 0x194C7C4C); expected.setExtended(true); Assert.assertEquals(expected, t.tc.rcvMessage); + t.dispose(); } OlcbTestInterface t; diff --git a/java/test/jmri/jmrix/openlcb/configurexml/OlcbSignalMastXmlTest.java b/java/test/jmri/jmrix/openlcb/configurexml/OlcbSignalMastXmlTest.java index 2590a5308f5..00bb8620dae 100644 --- a/java/test/jmri/jmrix/openlcb/configurexml/OlcbSignalMastXmlTest.java +++ b/java/test/jmri/jmrix/openlcb/configurexml/OlcbSignalMastXmlTest.java @@ -36,6 +36,8 @@ */ public class OlcbSignalMastXmlTest { + private OlcbSystemConnectionMemo memo = null; + @Test public void testCtor(){ Assert.assertNotNull("OlcbSignalMastXml constructor",new OlcbSignalMastXml()); @@ -75,12 +77,13 @@ public void put(Message msg, Connection sender) { } }; - OlcbSystemConnectionMemo memo = OlcbTestInterface.createForLegacyTests(); + memo = OlcbTestInterface.createForLegacyTests(); memo.setInterface(new OlcbInterface(new NodeID(new byte[]{1, 0, 0, 0, 0, 0}), connection)); } @After public void tearDown() { + memo.getInterface().dispose(); JUnitUtil.tearDown(); } diff --git a/java/test/jmri/jmrix/openlcb/swing/ClientActionsTest.java b/java/test/jmri/jmrix/openlcb/swing/ClientActionsTest.java index 167b4b1541f..6a9d5a14036 100644 --- a/java/test/jmri/jmrix/openlcb/swing/ClientActionsTest.java +++ b/java/test/jmri/jmrix/openlcb/swing/ClientActionsTest.java @@ -25,6 +25,8 @@ public void testCTor() { OlcbInterface iface = canInterface.getInterface(); ClientActions t = new ClientActions(iface); Assert.assertNotNull("exists",t); + // terminate the OlcbInterface (and terminate thread) + iface.dispose(); } // The minimal setup for log4J diff --git a/java/test/jmri/jmrix/openlcb/swing/hub/HubActionTest.java b/java/test/jmri/jmrix/openlcb/swing/hub/HubActionTest.java index f950929bf83..09bdffbc742 100644 --- a/java/test/jmri/jmrix/openlcb/swing/hub/HubActionTest.java +++ b/java/test/jmri/jmrix/openlcb/swing/hub/HubActionTest.java @@ -33,6 +33,7 @@ public void setUp() { @After public void tearDown() { + ((jmri.jmrix.openlcb.OlcbSystemConnectionMemo)memo).getInterface().dispose(); JUnitUtil.tearDown(); } } diff --git a/java/test/jmri/jmrix/openlcb/swing/hub/HubPaneTest.java b/java/test/jmri/jmrix/openlcb/swing/hub/HubPaneTest.java index b385d47e217..8f3129b5b89 100644 --- a/java/test/jmri/jmrix/openlcb/swing/hub/HubPaneTest.java +++ b/java/test/jmri/jmrix/openlcb/swing/hub/HubPaneTest.java @@ -35,6 +35,7 @@ public void setUp() { @After public void tearDown() { hub.stopHubThread(); + ((jmri.jmrix.openlcb.OlcbSystemConnectionMemo)memo).getInterface().dispose(); JUnitUtil.tearDown(); } } diff --git a/java/test/jmri/jmrix/openlcb/swing/networktree/NetworkTreeActionTest.java b/java/test/jmri/jmrix/openlcb/swing/networktree/NetworkTreeActionTest.java index c381d9197e1..0f2efa99bd8 100644 --- a/java/test/jmri/jmrix/openlcb/swing/networktree/NetworkTreeActionTest.java +++ b/java/test/jmri/jmrix/openlcb/swing/networktree/NetworkTreeActionTest.java @@ -34,6 +34,7 @@ public void setUp() { @After public void tearDown() { + ((jmri.jmrix.openlcb.OlcbSystemConnectionMemo)memo).getInterface().dispose(); JUnitUtil.tearDown(); } } diff --git a/java/test/jmri/jmrix/openlcb/swing/networktree/NetworkTreePaneTest.java b/java/test/jmri/jmrix/openlcb/swing/networktree/NetworkTreePaneTest.java index 0485fe1bc98..75059a742fe 100644 --- a/java/test/jmri/jmrix/openlcb/swing/networktree/NetworkTreePaneTest.java +++ b/java/test/jmri/jmrix/openlcb/swing/networktree/NetworkTreePaneTest.java @@ -32,6 +32,7 @@ public void setUp() { @After public void tearDown() { jmri.util.JUnitUtil.resetWindows(false, false); + ((jmri.jmrix.openlcb.OlcbSystemConnectionMemo)memo).getInterface().dispose(); JUnitUtil.tearDown(); } } diff --git a/java/test/jmri/jmrix/openlcb/swing/send/OpenLcbCanSendActionTest.java b/java/test/jmri/jmrix/openlcb/swing/send/OpenLcbCanSendActionTest.java index d01978738ab..2fb0832f5f9 100644 --- a/java/test/jmri/jmrix/openlcb/swing/send/OpenLcbCanSendActionTest.java +++ b/java/test/jmri/jmrix/openlcb/swing/send/OpenLcbCanSendActionTest.java @@ -34,6 +34,7 @@ public void setUp() { @After public void tearDown() { + ((jmri.jmrix.openlcb.OlcbSystemConnectionMemo)memo).getInterface().dispose(); JUnitUtil.tearDown(); } } From ab2f07822b4569126cab63f385c7dd15953ae39d Mon Sep 17 00:00:00 2001 From: Paul Bender Date: Sat, 10 Mar 2018 19:09:20 -0500 Subject: [PATCH 03/58] work on openlcb thread cleanup --- .../openlcb/OlcbConfigurationManagerTest.java | 15 +++++++++++++-- .../jmri/jmrix/openlcb/OlcbTestInterface.java | 2 +- .../test/jmri/jmrix/openlcb/OlcbThrottleTest.java | 2 +- .../openlcb/swing/networktree/TreePaneDemo.java | 7 +++---- 4 files changed, 18 insertions(+), 8 deletions(-) diff --git a/java/test/jmri/jmrix/openlcb/OlcbConfigurationManagerTest.java b/java/test/jmri/jmrix/openlcb/OlcbConfigurationManagerTest.java index c6c04b4c666..cd63ff2da31 100644 --- a/java/test/jmri/jmrix/openlcb/OlcbConfigurationManagerTest.java +++ b/java/test/jmri/jmrix/openlcb/OlcbConfigurationManagerTest.java @@ -5,6 +5,11 @@ import org.junit.Assert; import org.junit.Before; import org.junit.Test; +import org.openlcb.NodeID; +import jmri.InstanceManager; +import jmri.jmrix.can.CanSystemConnectionMemo; +import jmri.jmrix.can.ConfigurationManager; +import jmri.jmrix.can.TestTrafficController; /** * @@ -13,11 +18,14 @@ public class OlcbConfigurationManagerTest { private OlcbSystemConnectionMemo memo; + public TestTrafficController tc; + public OlcbConfigurationManager configurationManager; @Test public void testCTor() { OlcbConfigurationManager t = new OlcbConfigurationManager(memo); Assert.assertNotNull("exists",t); + t.dispose(); } @Test @@ -25,18 +33,21 @@ public void testConfigureManagers() { OlcbConfigurationManager t = new OlcbConfigurationManager(memo); // this tet verifies this does not throw an exception t.configureManagers(); + t.dispose(); } // The minimal setup for log4J @Before public void setUp() { JUnitUtil.setUp(); - OlcbSystemConnectionMemo memo = OlcbTestInterface.createForLegacyTests(); + tc = new TestTrafficController(); + memo = new OlcbSystemConnectionMemo(); + memo.setTrafficController(tc); + memo.setProtocol(ConfigurationManager.OPENLCB); } @After public void tearDown() { - memo.getInterface().dispose(); JUnitUtil.tearDown(); } diff --git a/java/test/jmri/jmrix/openlcb/OlcbTestInterface.java b/java/test/jmri/jmrix/openlcb/OlcbTestInterface.java index 03dbb6e540f..248ee3aab1d 100644 --- a/java/test/jmri/jmrix/openlcb/OlcbTestInterface.java +++ b/java/test/jmri/jmrix/openlcb/OlcbTestInterface.java @@ -44,7 +44,7 @@ public OlcbTestInterface(CreateConfigurationManager hh) { CanSystemConnectionMemo memo = new CanSystemConnectionMemo(); memo.setTrafficController(tc); memo.setProtocol(ConfigurationManager.OPENLCB); - memo.configureManagers(); + //memo.configureManagers(); configurationManager = InstanceManager.getDefault(OlcbConfigurationManager.class); canInterface = configurationManager.olcbCanInterface; iface = canInterface.getInterface(); diff --git a/java/test/jmri/jmrix/openlcb/OlcbThrottleTest.java b/java/test/jmri/jmrix/openlcb/OlcbThrottleTest.java index 5a8715d8047..b20d5e6491e 100644 --- a/java/test/jmri/jmrix/openlcb/OlcbThrottleTest.java +++ b/java/test/jmri/jmrix/openlcb/OlcbThrottleTest.java @@ -363,7 +363,7 @@ public void setUp() { JUnitUtil.setUp(); m = OlcbTestInterface.createForLegacyTests(); OlcbConfigurationManager ocm = new OlcbConfigurationManagerScaffold(m); - m.configureManagers(); + //m.configureManagers(); ocm.configureManagers(); instance = new OlcbThrottle(new DccLocoAddress(100,true),m,ocm); } diff --git a/java/test/jmri/jmrix/openlcb/swing/networktree/TreePaneDemo.java b/java/test/jmri/jmrix/openlcb/swing/networktree/TreePaneDemo.java index c1bf040f89c..8433bef1534 100644 --- a/java/test/jmri/jmrix/openlcb/swing/networktree/TreePaneDemo.java +++ b/java/test/jmri/jmrix/openlcb/swing/networktree/TreePaneDemo.java @@ -103,11 +103,10 @@ public void select(DefaultMutableTreeNode rep) { @After public void tearDown() { store = null; - jmri.util.JUnitUtil.resetWindows(false, false); - if (GraphicsEnvironment.isHeadless()) { - return; // don't bother tearing down a frame in headless. + if (!GraphicsEnvironment.isHeadless()) { + frame.setVisible(false); } - frame.setVisible(false); + jmri.util.JUnitUtil.tearDown(); } @Test From 0272306f4482e40225c2bf7dbab79fa80b5bfc31 Mon Sep 17 00:00:00 2001 From: Paul Bender Date: Tue, 13 Mar 2018 00:20:55 -0400 Subject: [PATCH 04/58] more work on OpenLCB threads --- java/test/jmri/jmrix/openlcb/OlcbTestInterface.java | 2 +- .../jmri/jmrix/openlcb/configurexml/OlcbSignalMastXmlTest.java | 1 - java/test/jmri/jmrix/openlcb/swing/hub/HubActionTest.java | 1 - java/test/jmri/jmrix/openlcb/swing/hub/HubPaneTest.java | 1 - .../jmrix/openlcb/swing/networktree/NetworkTreeActionTest.java | 1 - .../jmrix/openlcb/swing/networktree/NetworkTreePaneTest.java | 1 - .../jmri/jmrix/openlcb/swing/send/OpenLcbCanSendActionTest.java | 1 - 7 files changed, 1 insertion(+), 7 deletions(-) diff --git a/java/test/jmri/jmrix/openlcb/OlcbTestInterface.java b/java/test/jmri/jmrix/openlcb/OlcbTestInterface.java index 248ee3aab1d..03dbb6e540f 100644 --- a/java/test/jmri/jmrix/openlcb/OlcbTestInterface.java +++ b/java/test/jmri/jmrix/openlcb/OlcbTestInterface.java @@ -44,7 +44,7 @@ public OlcbTestInterface(CreateConfigurationManager hh) { CanSystemConnectionMemo memo = new CanSystemConnectionMemo(); memo.setTrafficController(tc); memo.setProtocol(ConfigurationManager.OPENLCB); - //memo.configureManagers(); + memo.configureManagers(); configurationManager = InstanceManager.getDefault(OlcbConfigurationManager.class); canInterface = configurationManager.olcbCanInterface; iface = canInterface.getInterface(); diff --git a/java/test/jmri/jmrix/openlcb/configurexml/OlcbSignalMastXmlTest.java b/java/test/jmri/jmrix/openlcb/configurexml/OlcbSignalMastXmlTest.java index 4e8486f415a..31172ab5677 100644 --- a/java/test/jmri/jmrix/openlcb/configurexml/OlcbSignalMastXmlTest.java +++ b/java/test/jmri/jmrix/openlcb/configurexml/OlcbSignalMastXmlTest.java @@ -83,7 +83,6 @@ public void put(Message msg, Connection sender) { @After public void tearDown() { - memo.getInterface().dispose(); JUnitUtil.tearDown(); } diff --git a/java/test/jmri/jmrix/openlcb/swing/hub/HubActionTest.java b/java/test/jmri/jmrix/openlcb/swing/hub/HubActionTest.java index a804af6d9af..f4c69a611cf 100644 --- a/java/test/jmri/jmrix/openlcb/swing/hub/HubActionTest.java +++ b/java/test/jmri/jmrix/openlcb/swing/hub/HubActionTest.java @@ -36,7 +36,6 @@ public void setUp() { @After public void tearDown() { - ((jmri.jmrix.openlcb.OlcbSystemConnectionMemo)memo).getInterface().dispose(); JUnitUtil.tearDown(); } } diff --git a/java/test/jmri/jmrix/openlcb/swing/hub/HubPaneTest.java b/java/test/jmri/jmrix/openlcb/swing/hub/HubPaneTest.java index f3c7fb156d9..236866b1bf4 100644 --- a/java/test/jmri/jmrix/openlcb/swing/hub/HubPaneTest.java +++ b/java/test/jmri/jmrix/openlcb/swing/hub/HubPaneTest.java @@ -38,7 +38,6 @@ public void setUp() { @After public void tearDown() { hub.stopHubThread(); - ((jmri.jmrix.openlcb.OlcbSystemConnectionMemo)memo).getInterface().dispose(); JUnitUtil.tearDown(); } } diff --git a/java/test/jmri/jmrix/openlcb/swing/networktree/NetworkTreeActionTest.java b/java/test/jmri/jmrix/openlcb/swing/networktree/NetworkTreeActionTest.java index a581b6712ce..6a13eea275a 100644 --- a/java/test/jmri/jmrix/openlcb/swing/networktree/NetworkTreeActionTest.java +++ b/java/test/jmri/jmrix/openlcb/swing/networktree/NetworkTreeActionTest.java @@ -37,7 +37,6 @@ public void setUp() { @After public void tearDown() { - ((jmri.jmrix.openlcb.OlcbSystemConnectionMemo)memo).getInterface().dispose(); JUnitUtil.tearDown(); } } diff --git a/java/test/jmri/jmrix/openlcb/swing/networktree/NetworkTreePaneTest.java b/java/test/jmri/jmrix/openlcb/swing/networktree/NetworkTreePaneTest.java index 803c3a503d0..912f71dcb0f 100644 --- a/java/test/jmri/jmrix/openlcb/swing/networktree/NetworkTreePaneTest.java +++ b/java/test/jmri/jmrix/openlcb/swing/networktree/NetworkTreePaneTest.java @@ -35,7 +35,6 @@ public void setUp() { @After public void tearDown() { jmri.util.JUnitUtil.resetWindows(false, false); - ((jmri.jmrix.openlcb.OlcbSystemConnectionMemo)memo).getInterface().dispose(); JUnitUtil.tearDown(); } } diff --git a/java/test/jmri/jmrix/openlcb/swing/send/OpenLcbCanSendActionTest.java b/java/test/jmri/jmrix/openlcb/swing/send/OpenLcbCanSendActionTest.java index 9e36c41266c..d9329806353 100644 --- a/java/test/jmri/jmrix/openlcb/swing/send/OpenLcbCanSendActionTest.java +++ b/java/test/jmri/jmrix/openlcb/swing/send/OpenLcbCanSendActionTest.java @@ -37,7 +37,6 @@ public void setUp() { @After public void tearDown() { - ((jmri.jmrix.openlcb.OlcbSystemConnectionMemo)memo).getInterface().dispose(); JUnitUtil.tearDown(); } } From 31a246b773d7380d6fde8e0fa15c9e9879403845 Mon Sep 17 00:00:00 2001 From: Paul Bender Date: Fri, 16 Mar 2018 00:24:30 -0400 Subject: [PATCH 05/58] more threading work --- java/test/jmri/jmrix/openlcb/OlcbConfigurationManagerTest.java | 3 +++ 1 file changed, 3 insertions(+) diff --git a/java/test/jmri/jmrix/openlcb/OlcbConfigurationManagerTest.java b/java/test/jmri/jmrix/openlcb/OlcbConfigurationManagerTest.java index 02bb13b3b67..f4551238b78 100644 --- a/java/test/jmri/jmrix/openlcb/OlcbConfigurationManagerTest.java +++ b/java/test/jmri/jmrix/openlcb/OlcbConfigurationManagerTest.java @@ -1,5 +1,6 @@ package jmri.jmrix.openlcb; +import jmri.jmrix.can.TestTrafficController; import jmri.util.JUnitUtil; import org.junit.After; import org.junit.Assert; @@ -11,6 +12,8 @@ * @author Paul Bender Copyright (C) 2017 */ public class OlcbConfigurationManagerTest { + + private OlcbSystemConnectionMemo scm; @Test public void testCTor() { From bdbb15307b699a82a01576a1081f972bec697f5b Mon Sep 17 00:00:00 2001 From: Paul Bender Date: Sun, 25 Mar 2018 01:46:31 -0400 Subject: [PATCH 06/58] more OpenLCB thread management --- .../jmri/jmrix/openlcb/OlcbConfigurationManagerTest.java | 3 +++ java/test/jmri/jmrix/openlcb/OlcbSignalMastTest.java | 3 +++ java/test/jmri/jmrix/openlcb/OlcbThrottleManagerTest.java | 4 +++- java/test/jmri/jmrix/openlcb/OlcbThrottleTest.java | 5 ++++- .../jmrix/openlcb/configurexml/OlcbSignalMastXmlTest.java | 5 +++-- java/test/jmri/jmrix/openlcb/swing/ClientActionsTest.java | 2 ++ 6 files changed, 18 insertions(+), 4 deletions(-) diff --git a/java/test/jmri/jmrix/openlcb/OlcbConfigurationManagerTest.java b/java/test/jmri/jmrix/openlcb/OlcbConfigurationManagerTest.java index f4551238b78..94f54c855ff 100644 --- a/java/test/jmri/jmrix/openlcb/OlcbConfigurationManagerTest.java +++ b/java/test/jmri/jmrix/openlcb/OlcbConfigurationManagerTest.java @@ -42,6 +42,9 @@ public void setUp() { @After public void tearDown() { + if(scm.getInterface()!=null) { + scm.getInterface().dispose(); + } JUnitUtil.tearDown(); } diff --git a/java/test/jmri/jmrix/openlcb/OlcbSignalMastTest.java b/java/test/jmri/jmrix/openlcb/OlcbSignalMastTest.java index 20e9774a165..5a7227ceb49 100644 --- a/java/test/jmri/jmrix/openlcb/OlcbSignalMastTest.java +++ b/java/test/jmri/jmrix/openlcb/OlcbSignalMastTest.java @@ -30,6 +30,8 @@ * updated to JUnit4 2016 */ public class OlcbSignalMastTest { + + private OlcbSystemConnectionMemo memo; @Test public void testCtor1() { @@ -326,6 +328,7 @@ public Connection getOutputConnection() { @After public void tearDown() throws Exception { + memo.getInterface().dispose(); JUnitUtil.tearDown(); } } diff --git a/java/test/jmri/jmrix/openlcb/OlcbThrottleManagerTest.java b/java/test/jmri/jmrix/openlcb/OlcbThrottleManagerTest.java index a0f71006ed5..e47f06ba8c0 100644 --- a/java/test/jmri/jmrix/openlcb/OlcbThrottleManagerTest.java +++ b/java/test/jmri/jmrix/openlcb/OlcbThrottleManagerTest.java @@ -13,13 +13,14 @@ */ public class OlcbThrottleManagerTest extends jmri.managers.AbstractThrottleManagerTestBase { + private OlcbSystemConnectionMemo m; // The minimal setup for log4J @Override @Before public void setUp() { JUnitUtil.setUp(); - OlcbSystemConnectionMemo m = new jmri.jmrix.openlcb.OlcbSystemConnectionMemo(); + m = new jmri.jmrix.openlcb.OlcbSystemConnectionMemo(); TestTrafficController tc = new TestTrafficController(); m.setTrafficController(tc); tm = new OlcbThrottleManager(m,new OlcbConfigurationManagerScaffold(m)); @@ -27,6 +28,7 @@ public void setUp() { @After public void tearDown() { + m.getInterface().dispose(); JUnitUtil.tearDown(); } } diff --git a/java/test/jmri/jmrix/openlcb/OlcbThrottleTest.java b/java/test/jmri/jmrix/openlcb/OlcbThrottleTest.java index c0cc4a7f4fc..138a1824201 100644 --- a/java/test/jmri/jmrix/openlcb/OlcbThrottleTest.java +++ b/java/test/jmri/jmrix/openlcb/OlcbThrottleTest.java @@ -14,6 +14,8 @@ * @author Bob Jacobsen Copyright 2008, 2010, 2011 */ public class OlcbThrottleTest extends jmri.jmrix.AbstractThrottleTest { + + private OlcbSystemConnectionMemo m; /** * Test of getIsForward method, of class AbstractThrottle. @@ -360,7 +362,7 @@ public void testSendFunctionGroup5() { @Before public void setUp() { JUnitUtil.setUp(); - OlcbSystemConnectionMemo m = new OlcbSystemConnectionMemo(); + m = new OlcbSystemConnectionMemo(); TestTrafficController tc = new TestTrafficController(); m.setTrafficController(tc); OlcbConfigurationManager ocm = new OlcbConfigurationManagerScaffold(m); @@ -371,6 +373,7 @@ public void setUp() { @Override @After public void tearDown() { + m.getInterface().dispose(); JUnitUtil.tearDown(); } } diff --git a/java/test/jmri/jmrix/openlcb/configurexml/OlcbSignalMastXmlTest.java b/java/test/jmri/jmrix/openlcb/configurexml/OlcbSignalMastXmlTest.java index c979b887bb7..9d4816b8a5f 100644 --- a/java/test/jmri/jmrix/openlcb/configurexml/OlcbSignalMastXmlTest.java +++ b/java/test/jmri/jmrix/openlcb/configurexml/OlcbSignalMastXmlTest.java @@ -12,7 +12,6 @@ import org.openlcb.EventState; import org.openlcb.Message; import org.openlcb.NodeID; -import org.openlcb.OlcbInterface; import org.openlcb.ProducerConsumerEventReportMessage; import org.openlcb.IdentifyConsumersMessage; import org.openlcb.ConsumerIdentifiedMessage; @@ -35,6 +34,8 @@ * @author Bob Jacobsen Copyright (C) 2018 */ public class OlcbSignalMastXmlTest { + + private OlcbSystemConnectionMemo memo; @Test public void testCtor(){ @@ -76,11 +77,11 @@ public void put(Message msg, Connection sender) { }; OlcbSystemConnectionMemo memo = OlcbTestInterface.createForLegacyTests(); - //memo.setInterface(new OlcbInterface(new NodeID(new byte[]{1, 0, 0, 0, 0, 0}), connection)); } @After public void tearDown() { + memo.getInterface().dispose(); JUnitUtil.tearDown(); } diff --git a/java/test/jmri/jmrix/openlcb/swing/ClientActionsTest.java b/java/test/jmri/jmrix/openlcb/swing/ClientActionsTest.java index 6a9d5a14036..caf76860412 100644 --- a/java/test/jmri/jmrix/openlcb/swing/ClientActionsTest.java +++ b/java/test/jmri/jmrix/openlcb/swing/ClientActionsTest.java @@ -25,6 +25,8 @@ public void testCTor() { OlcbInterface iface = canInterface.getInterface(); ClientActions t = new ClientActions(iface); Assert.assertNotNull("exists",t); + // terminate the canInterface (and terminate thread) + canInterface.dispose(); // terminate the OlcbInterface (and terminate thread) iface.dispose(); } From a4b3a0f6d048d804ee7a1c85039a0df441d1f67f Mon Sep 17 00:00:00 2001 From: Egbert Broerse Date: Sat, 31 Mar 2018 23:31:03 +0200 Subject: [PATCH 07/58] add Simulator, Javadoc fixes --- .../serialdriver/SerialDriverAdapter.java | 2 +- .../jmri/jmrix/maple/MapleBundle.properties | 1 + java/src/jmri/jmrix/maple/MapleMenu.java | 4 +- .../jmri/jmrix/maple/SerialLightManager.java | 2 +- java/src/jmri/jmrix/maple/SerialNode.java | 10 +- .../jmri/jmrix/maple/SerialSensorManager.java | 2 +- .../jmrix/maple/SerialTurnoutManager.java | 6 +- .../maple/nodeconfig/NodeConfigFrame.java | 75 +-- .../packetgen/SerialPacketGenAction.java | 18 +- .../serialdriver/SerialDriverAdapter.java | 32 +- .../maple/serialmon/SerialMonAction.java | 14 +- .../jmrix/maple/serialmon/SerialMonFrame.java | 10 +- .../jmri/jmrix/maple/simulator/Bundle.java | 94 ++++ java/src/jmri/jmrix/maple/simulator/COPYING | 372 +++++++++++++ .../maple/simulator/ConnectionConfig.java | 78 +++ .../maple/simulator/SimulatorAdapter.java | 509 ++++++++++++++++++ .../maple/simulator/configurexml/COPYING | 372 +++++++++++++ .../configurexml/ConnectionConfigXml.java | 116 ++++ 18 files changed, 1638 insertions(+), 79 deletions(-) create mode 100644 java/src/jmri/jmrix/maple/simulator/Bundle.java create mode 100644 java/src/jmri/jmrix/maple/simulator/COPYING create mode 100644 java/src/jmri/jmrix/maple/simulator/ConnectionConfig.java create mode 100644 java/src/jmri/jmrix/maple/simulator/SimulatorAdapter.java create mode 100644 java/src/jmri/jmrix/maple/simulator/configurexml/COPYING create mode 100644 java/src/jmri/jmrix/maple/simulator/configurexml/ConnectionConfigXml.java diff --git a/java/src/jmri/jmrix/grapevine/serialdriver/SerialDriverAdapter.java b/java/src/jmri/jmrix/grapevine/serialdriver/SerialDriverAdapter.java index 09a0d61d9e4..1772dcee54f 100644 --- a/java/src/jmri/jmrix/grapevine/serialdriver/SerialDriverAdapter.java +++ b/java/src/jmri/jmrix/grapevine/serialdriver/SerialDriverAdapter.java @@ -211,7 +211,7 @@ public void configureBaudRate(String rate) { InputStream serialStream = null; /** - * @deprecated JMRI Since 4.12.3 instance() shouldn't be used, convert to JMRI multi-system support structure + * @deprecated JMRI Since 4.11.3 instance() shouldn't be used, convert to JMRI multi-system support structure */ static public SerialDriverAdapter instance() { return null; diff --git a/java/src/jmri/jmrix/maple/MapleBundle.properties b/java/src/jmri/jmrix/maple/MapleBundle.properties index 5eda80cc9cf..6b156239aae 100644 --- a/java/src/jmri/jmrix/maple/MapleBundle.properties +++ b/java/src/jmri/jmrix/maple/MapleBundle.properties @@ -3,6 +3,7 @@ # Default properties for the jmri.jmrix.maple menu MenuMaple = Maple +MapleSimulatorName = Maple Simulator MenuItemCommandMonitor = Line Monitor MenuItemSendCommand = Send Command diff --git a/java/src/jmri/jmrix/maple/MapleMenu.java b/java/src/jmri/jmrix/maple/MapleMenu.java index 76d422894dd..e472172ba88 100644 --- a/java/src/jmri/jmrix/maple/MapleMenu.java +++ b/java/src/jmri/jmrix/maple/MapleMenu.java @@ -23,8 +23,8 @@ public MapleMenu(MapleSystemConnectionMemo memo) { setText(Bundle.getMessage("MenuMaple")); } - add(new jmri.jmrix.maple.serialmon.SerialMonAction(Bundle.getMessage("MenuItemCommandMonitor"),memo)); - add(new jmri.jmrix.maple.packetgen.SerialPacketGenAction(Bundle.getMessage("MenuItemSendCommand"),memo)); + add(new jmri.jmrix.maple.serialmon.SerialMonAction(Bundle.getMessage("MenuItemCommandMonitor"), memo)); + add(new jmri.jmrix.maple.packetgen.SerialPacketGenAction(Bundle.getMessage("MenuItemSendCommand"), memo)); add(new javax.swing.JSeparator()); if (memo != null) { add(new jmri.jmrix.maple.nodeconfig.NodeConfigAction(memo)); diff --git a/java/src/jmri/jmrix/maple/SerialLightManager.java b/java/src/jmri/jmrix/maple/SerialLightManager.java index fae3e5f6870..aa5fe039237 100644 --- a/java/src/jmri/jmrix/maple/SerialLightManager.java +++ b/java/src/jmri/jmrix/maple/SerialLightManager.java @@ -8,7 +8,7 @@ /** * Implement light manager for Maple serial systems *

- * System names are "KLnnn", where nnn is the bit number without padding. + * System names are "MiLnnn", where nnn is the bit number without padding. *

* Based in part on SerialTurnoutManager.java * diff --git a/java/src/jmri/jmrix/maple/SerialNode.java b/java/src/jmri/jmrix/maple/SerialNode.java index 872ed92b885..1e03fb1e537 100644 --- a/java/src/jmri/jmrix/maple/SerialNode.java +++ b/java/src/jmri/jmrix/maple/SerialNode.java @@ -34,6 +34,7 @@ public class SerialNode extends AbstractNode { private int _address = 0; // operational instance variables (should not be preserved between runs) + /** * Assumes a node address of 1, and a node type of 0. If this constructor is * used, actual node address must be set using setNodeAddress. @@ -43,7 +44,8 @@ public SerialNode(SerialTrafficController tc) { } /** - * Creates a new SerialNode and initialize default instance variables + * Create a new SerialNode and initialize default instance variables. + * * @param address Address of node on serial bus (0-99) * @param type 0 (ignored) */ @@ -68,7 +70,7 @@ public boolean getSensorsActive() { /** * Check valid node address, must match value configured in the Maple HMI. * - * @param address allowed values are 1-99 + * @param address node ID, allowed values are 1-99 * @return true if in valid range */ @Override @@ -124,14 +126,14 @@ void warn(String s) { public boolean handleTimeout(AbstractMRMessage m, AbstractMRListener l) { // increment timeout count timeout++; - log.warn("Poll of node " + _address + " timed out. Timeout count = " + timeout); + log.warn("Poll of node {} timed out. Timeout count = {}", _address, timeout); return false; } @Override public void resetTimeout(AbstractMRMessage m) { if (timeout > 0) { - log.debug("Reset " + timeout + " timeout count"); + log.debug("Reset {} timeout count", timeout); } timeout = 0; } diff --git a/java/src/jmri/jmrix/maple/SerialSensorManager.java b/java/src/jmri/jmrix/maple/SerialSensorManager.java index 5a44768732a..f08e86526e0 100644 --- a/java/src/jmri/jmrix/maple/SerialSensorManager.java +++ b/java/src/jmri/jmrix/maple/SerialSensorManager.java @@ -8,7 +8,7 @@ /** * Manage the specific Sensor implementation. *

- * System names are "KSnnnn", where nnnn is the sensor number without padding. + * System names are "MiSnnnn", where nnnn is the sensor number without padding. *

* Sensors are numbered from 1. *

diff --git a/java/src/jmri/jmrix/maple/SerialTurnoutManager.java b/java/src/jmri/jmrix/maple/SerialTurnoutManager.java index fb0f846e6ef..3893e83606b 100644 --- a/java/src/jmri/jmrix/maple/SerialTurnoutManager.java +++ b/java/src/jmri/jmrix/maple/SerialTurnoutManager.java @@ -7,8 +7,8 @@ /** * Implement turnout manager for serial systems - *

- * System names are "KTnnn", where nnn is the turnout number without padding. + *

+ * System names are "MiTnnn", where nnn is the turnout number without padding. * * @author Bob Jacobsen Copyright (C) 2003, 2008 */ @@ -102,7 +102,7 @@ public NameValidity validSystemNameFormat(String systemName) { /** * Public method to normalize a system name. - *

+ *

* Returns a normalized system name if system name has a valid format, else * returns "". */ diff --git a/java/src/jmri/jmrix/maple/nodeconfig/NodeConfigFrame.java b/java/src/jmri/jmrix/maple/nodeconfig/NodeConfigFrame.java index 6512cbf939b..3dd2ca3b1c6 100644 --- a/java/src/jmri/jmrix/maple/nodeconfig/NodeConfigFrame.java +++ b/java/src/jmri/jmrix/maple/nodeconfig/NodeConfigFrame.java @@ -14,7 +14,7 @@ /** * Frame for user configuration of Maple panel nodes. - * + *

* Note: Currently anything to do with pulse width for pulsing a turnout is * commented out. This code from the C/MRI version was not deleted in case it is * needed in the future. @@ -53,7 +53,7 @@ public class NodeConfigFrame extends jmri.util.JmriJFrame { protected int nodeAddress = 0; // Node address protected int pollTimeoutTime = 2000; // reply timeout time protected int sendDelay = 200; // delay time after send commands -// protected int pulseWidth = 500; // pulse width for turnout control (milliseconds) + // protected int pulseWidth = 500; // pulse width for turnout control (milliseconds) protected int inputBits = 40; // maximum number of input bits - all nodes protected int outputBits = 40; // maximum number of output bits - all nodes @@ -248,7 +248,7 @@ public void actionPerformed(java.awt.event.ActionEvent e) { } /** - * Method to handle add button + * Handle Add button */ public void addButtonActionPerformed() { // Check that a node with this address does not exist @@ -295,7 +295,7 @@ public void addButtonActionPerformed() { } /** - * Method to handle edit button + * Handle Edit button */ public void editButtonActionPerformed() { // Find Serial Node address @@ -316,7 +316,7 @@ public void editButtonActionPerformed() { nodeAddrStatic.setText(Integer.toString(nodeAddress)); nodeAddrField.setVisible(false); nodeAddrStatic.setVisible(true); -// // set up pulse width + // set up pulse width // pulseWidth = curNode.getPulseWidth(); // pulseWidthField.setText(Integer.toString(pulseWidth)); // set up number of input and output bits @@ -344,7 +344,7 @@ public void editButtonActionPerformed() { } /** - * Method to handle delete button + * Handle Delete button */ public void deleteButtonActionPerformed() { // Find Serial Node address @@ -382,7 +382,7 @@ public void deleteButtonActionPerformed() { } /** - * Method to handle done button + * Handle Done button */ public void doneButtonActionPerformed() { if (editMode) { @@ -411,7 +411,7 @@ public void doneButtonActionPerformed() { } /** - * Method to handle update button + * Handle Update button */ public void updateButtonActionPerformed() { // get node information from window @@ -421,7 +421,7 @@ public void updateButtonActionPerformed() { if (!readSendDelay()) { return; } -// if ( !readPulseWidth() ) return; + // if ( !readPulseWidth() ) return; if (!readNumInputBits()) { return; } @@ -454,7 +454,7 @@ public void updateButtonActionPerformed() { } /** - * Method to handle cancel button + * Handle Cancel button */ public void cancelButtonActionPerformed() { // Reset @@ -477,7 +477,7 @@ public void cancelButtonActionPerformed() { } /** - * Method to close the window when the close box is clicked + * Close the window when the close box is clicked. */ @Override public void windowClosing(java.awt.event.WindowEvent e) { @@ -486,7 +486,7 @@ public void windowClosing(java.awt.event.WindowEvent e) { } /** - * Method to set node parameters The node must exist, and be in 'curNode' + * Set node parameters. The node must exist, and be in 'curNode' * Also, the node type must be set and in 'nodeType' */ void setNodeParameters() { @@ -499,7 +499,7 @@ void setNodeParameters() { } /** - * Method to reset the notes error after error display + * Reset the notes error text after error display. */ private void resetNotes() { if (errorInStatus1) { @@ -514,7 +514,7 @@ private void resetNotes() { } /** - * Reset the second line of Notes area + * Reset the second line of Notes area. */ private void resetNotes2() { if (errorInStatus2) { @@ -528,8 +528,9 @@ private void resetNotes2() { } /** - * Read node address and check for legal range If successful, a node address - * in the range 1-99 is returned. If not successful, -1 is returned and an + * Read node address and check for legal range. + * + * @return a node address in the range 1-99 if successful. If not, -1 is returned and an * appropriate error message is placed in statusText1. */ private int readNodeAddress() { @@ -554,9 +555,11 @@ private int readNodeAddress() { } /** - * Read receive poll reply timeout time from window Returns 'true' if - * successful, 'false' if an error was detected. If an error is detected, a - * suitable error message is placed in the Notes area + * Read receive poll reply timeout time from window. + * If an error is detected, a suitable error message is placed + * in the Notes area. + * + * @return 'true' if successful, 'false' if an error was detected. */ protected boolean readPollTimeout() { // get the timeout time @@ -591,9 +594,11 @@ protected boolean readPollTimeout() { } /** - * Read send delay time from window Returns 'true' if successful, 'false' if - * an error was detected. If an error is detected, a suitable error message - * is placed in the Notes area + * Read send delay time from window. + * If an error is detected, a suitable error message + * is placed in the Notes area. + * + * @return 'true' if successful, 'false' if an error was detected. */ protected boolean readSendDelay() { // get the timeout time @@ -628,9 +633,11 @@ protected boolean readSendDelay() { } /** - * Read number of input bits from window Returns 'true' if successful, - * 'false' if an error was detected. If an error is detected, a suitable - * error message is placed in the Notes area + * Read number of input bits from window. + * If an error is detected, a suitable error message is + * placed in the Notes area. + * + * @return 'true' if successful, 'false' if an error was detected. */ protected boolean readNumInputBits() { // get the input bits @@ -665,9 +672,11 @@ protected boolean readNumInputBits() { } /** - * Read number of output bits from window Returns 'true' if successful, - * 'false' if an error was detected. If an error is detected, a suitable - * error message is placed in the Notes area + * Read number of output bits from window. + * If an error is detected, a suitable error message is placed + * in the Notes area. + * + * @return 'true' if successful, 'false' if an error was detected. */ protected boolean readNumOutputBits() { // get the output bits @@ -702,10 +711,11 @@ protected boolean readNumOutputBits() { } // /** -// * Read pulse width from window -// * Returns 'true' if successful, 'false' if an error was detected. -// * If an error is detected, a suitable error message is placed in the -// * Notes area +// * Read pulse width from window. +// * If an error is detected, a suitable error message is placed in the +// * Notes area. +// * +// * @return 'true' if successful, 'false' if an error was detected. // */ // protected boolean readPulseWidth() { // // get the pulse width @@ -743,6 +753,7 @@ protected boolean readNumOutputBits() { // // successful // return true; // } + // private final static Logger log = LoggerFactory.getLogger(NodeConfigFrame.class); } diff --git a/java/src/jmri/jmrix/maple/packetgen/SerialPacketGenAction.java b/java/src/jmri/jmrix/maple/packetgen/SerialPacketGenAction.java index 3ce52689000..1d6ba336b4f 100644 --- a/java/src/jmri/jmrix/maple/packetgen/SerialPacketGenAction.java +++ b/java/src/jmri/jmrix/maple/packetgen/SerialPacketGenAction.java @@ -7,32 +7,34 @@ import jmri.jmrix.maple.MapleSystemConnectionMemo; /** - * Swing action to create and register a SerialPacketGenFrame object + * Swing action to create and register a SerialPacketGenFrame object. * * @author Bob Jacobsen Copyright (C) 2008 */ public class SerialPacketGenAction extends AbstractAction { - private MapleSystemConnectionMemo memo = null; + private MapleSystemConnectionMemo _memo = null; - public SerialPacketGenAction(String s,MapleSystemConnectionMemo _memo) { + public SerialPacketGenAction(String s, MapleSystemConnectionMemo memo) { super(s); - memo = _memo; + _memo = memo; } - public SerialPacketGenAction(MapleSystemConnectionMemo _memo) { - this("Send Maple message",_memo); + public SerialPacketGenAction(MapleSystemConnectionMemo memo) { + this(Bundle.getMessage("SendXCommandTitle", "Maple"), memo); } @Override public void actionPerformed(ActionEvent e) { - SerialPacketGenFrame f = new SerialPacketGenFrame(memo); + SerialPacketGenFrame f = new SerialPacketGenFrame(_memo); try { f.initComponents(); } catch (Exception ex) { - log.error("Exception: " + ex.toString()); + log.error("Exception: {}", ex.toString()); } f.setVisible(true); } + private final static Logger log = LoggerFactory.getLogger(SerialPacketGenAction.class); + } diff --git a/java/src/jmri/jmrix/maple/serialdriver/SerialDriverAdapter.java b/java/src/jmri/jmrix/maple/serialdriver/SerialDriverAdapter.java index d07d750889a..1bdd53e364c 100644 --- a/java/src/jmri/jmrix/maple/serialdriver/SerialDriverAdapter.java +++ b/java/src/jmri/jmrix/maple/serialdriver/SerialDriverAdapter.java @@ -44,26 +44,28 @@ public String openPort(String portName, String appName) { try { setSerialPort(); } catch (UnsupportedCommOperationException e) { - log.error("Cannot set serial parameters on port " + portName + ": " + e.getMessage()); + log.error("Cannot set serial parameters on port {}: {}", portName, e.getMessage()); return "Cannot set serial parameters on port " + portName + ": " + e.getMessage(); } // set framing (end) character try { activeSerialPort.enableReceiveFraming(0x03); - log.debug("Serial framing was observed as: " + activeSerialPort.isReceiveFramingEnabled() - + " " + activeSerialPort.getReceiveFramingByte()); + log.debug("Serial framing was observed as: {} {}", + activeSerialPort.isReceiveFramingEnabled(), + activeSerialPort.getReceiveFramingByte()); } catch (Exception ef) { - log.debug("failed to set serial framing: " + ef); + log.debug("failed to set serial framing: ", ef); } // set timeout; framing should work before this anyway try { activeSerialPort.enableReceiveTimeout(10); - log.debug("Serial timeout was observed as: " + activeSerialPort.getReceiveTimeout() - + " " + activeSerialPort.isReceiveTimeoutEnabled()); + log.debug("Serial timeout was observed as: {} {}", + activeSerialPort.getReceiveTimeout(), + activeSerialPort.isReceiveTimeoutEnabled()); } catch (Exception et) { - log.info("failed to set serial timeout: " + et); + log.info("failed to set serial timeout: ", et); } // get and save stream @@ -86,8 +88,8 @@ public String openPort(String portName, String appName) { } if (log.isDebugEnabled()) { // report additional status - log.debug(" port flow control shows " // NOI18N - + (activeSerialPort.getFlowControlMode() == SerialPort.FLOWCONTROL_RTSCTS_OUT ? "hardware flow control" : "no flow control")); // NOI18N + log.debug(" port flow control shows {}", // NOI18N + (activeSerialPort.getFlowControlMode() == SerialPort.FLOWCONTROL_RTSCTS_OUT ? "hardware flow control" : "no flow control")); // NOI18N // log events setPortEventLogging(activeSerialPort); @@ -147,7 +149,7 @@ public DataOutputStream getOutputStream() { try { return new DataOutputStream(activeSerialPort.getOutputStream()); } catch (java.io.IOException e) { - log.error("getOutputStream exception: " + e.getMessage()); + log.error("getOutputStream exception: {}", e.getMessage()); } return null; } @@ -189,7 +191,7 @@ public String[] validBaudRates() { */ @Override public void configureBaudRate(String rate) { - log.debug("configureBaudRate: " + rate); + log.debug("configureBaudRate: {}", rate); selectedSpeed = rate; super.configureBaudRate(rate); } @@ -203,11 +205,11 @@ public void configureBaudRate(String rate) { private boolean opened = false; InputStream serialStream = null; + /** + * @deprecated JMRI Since 4.11.5 instance() shouldn't be used, convert to JMRI multi-system support structure + */ static public SerialDriverAdapter instance() { - if (mInstance == null) { - mInstance = new SerialDriverAdapter(); - } - return mInstance; + return null; } static SerialDriverAdapter mInstance = null; diff --git a/java/src/jmri/jmrix/maple/serialmon/SerialMonAction.java b/java/src/jmri/jmrix/maple/serialmon/SerialMonAction.java index 7a5034ff1e2..7790b9e893c 100644 --- a/java/src/jmri/jmrix/maple/serialmon/SerialMonAction.java +++ b/java/src/jmri/jmrix/maple/serialmon/SerialMonAction.java @@ -13,25 +13,25 @@ */ public class SerialMonAction extends AbstractAction { - private MapleSystemConnectionMemo memo = null; + private MapleSystemConnectionMemo _memo = null; - public SerialMonAction(String s, MapleSystemConnectionMemo _memo) { + public SerialMonAction(String s, MapleSystemConnectionMemo memo) { super(s); - memo = _memo; + _memo = memo; } - public SerialMonAction(MapleSystemConnectionMemo _memo) { - this("Maple monitor", _memo); + public SerialMonAction(MapleSystemConnectionMemo memo) { + this("Maple monitor", memo); } @Override public void actionPerformed(ActionEvent e) { // create a SerialMonFrame - SerialMonFrame f = new SerialMonFrame(memo); + SerialMonFrame f = new SerialMonFrame(_memo); try { f.initComponents(); } catch (Exception ex) { - log.warn("SerialMonAction starting SerialMonFrame: Exception: " + ex.toString()); + log.warn("SerialMonAction starting SerialMonFrame: Exception: {}", ex.toString()); } f.setVisible(true); } diff --git a/java/src/jmri/jmrix/maple/serialmon/SerialMonFrame.java b/java/src/jmri/jmrix/maple/serialmon/SerialMonFrame.java index 05fe8024f31..8aa086e44b6 100644 --- a/java/src/jmri/jmrix/maple/serialmon/SerialMonFrame.java +++ b/java/src/jmri/jmrix/maple/serialmon/SerialMonFrame.java @@ -12,11 +12,11 @@ */ public class SerialMonFrame extends jmri.jmrix.AbstractMonFrame implements SerialListener { - private MapleSystemConnectionMemo memo = null; + private MapleSystemConnectionMemo _memo = null; - public SerialMonFrame(MapleSystemConnectionMemo _memo) { + public SerialMonFrame(MapleSystemConnectionMemo memo) { super(); - memo = _memo; + _memo = memo; } @Override @@ -27,12 +27,12 @@ protected String title() { @Override protected void init() { // connect to TrafficController - memo.getTrafficController().addSerialListener(this); + _memo.getTrafficController().addSerialListener(this); } @Override public void dispose() { - memo.getTrafficController().removeSerialListener(this); + _memo.getTrafficController().removeSerialListener(this); super.dispose(); } diff --git a/java/src/jmri/jmrix/maple/simulator/Bundle.java b/java/src/jmri/jmrix/maple/simulator/Bundle.java new file mode 100644 index 00000000000..30a20e97254 --- /dev/null +++ b/java/src/jmri/jmrix/maple/simulator/Bundle.java @@ -0,0 +1,94 @@ + +package jmri.jmrix.maple.simulator; + +import edu.umd.cs.findbugs.annotations.SuppressFBWarnings; +import java.util.Locale; +import javax.annotation.CheckReturnValue; +import javax.annotation.Nullable; +import javax.annotation.ParametersAreNonnullByDefault; + +@ParametersAreNonnullByDefault +@CheckReturnValue +@SuppressFBWarnings(value = "NM_SAME_SIMPLE_NAME_AS_SUPERCLASS",justification="Desired pattern is repeated class names with package-level access to members") + +@javax.annotation.concurrent.Immutable + +/** + * Provides standard access for resource bundles in a package. + * + * Convention is to provide a subclass of this name + * in each package, working off the local resource bundle name. + * + * @author Bob Jacobsen Copyright (C) 2012 + * @since 4.9.5 + */ +public class Bundle extends jmri.jmrix.maple.Bundle { + + @Nullable private static final String name = null; // No local resources + + // + // below here is boilerplate to be copied exactly + // + + /** + * Provides a translated string for a given + * key from the package resource bundle or + * parent. + *

+ * Note that this is intentionally package-local + * access. + * + * @param key Bundle key to be translated + * @return Internationalized text + */ + static String getMessage(String key) { + return getBundle().handleGetMessage(key); + } + /** + * Merges user data with a translated string for a given + * key from the package resource bundle or + * parent. + *

+ * Uses the transformation conventions of + * the Java MessageFormat utility. + *

+ * Note that this is intentionally package-local + * access. + * + * @see java.text.MessageFormat + * @param key Bundle key to be translated + * @param subs One or more objects to be inserted into the message + * @return Internationalized text + */ + static String getMessage(String key, Object ... subs) { + return getBundle().handleGetMessage(key, subs); + } + + /** + * Merges user data with a translated string for a given key in a given + * locale from the package resource bundle or parent. + *

+ * Uses the transformation conventions of the Java MessageFormat utility. + *

+ * Note that this is intentionally package-local access. + * + * @see java.text.MessageFormat + * @param locale The locale to be used + * @param key Bundle key to be translated + * @param subs One or more objects to be inserted into the message + * @return Internationalized text + */ + static String getMessage(Locale locale, String key, Object... subs) { + return getBundle().handleGetMessage(locale, key, subs); + } + + private final static Bundle b = new Bundle(); + @Override @Nullable protected String bundleName() {return name; } + protected static jmri.Bundle getBundle() { return b; } + + @Override + protected String retry(Locale locale,String key) { + return super.getBundle().handleGetMessage(locale,key); + } + +} diff --git a/java/src/jmri/jmrix/maple/simulator/COPYING b/java/src/jmri/jmrix/maple/simulator/COPYING new file mode 100644 index 00000000000..d93eaffc912 --- /dev/null +++ b/java/src/jmri/jmrix/maple/simulator/COPYING @@ -0,0 +1,372 @@ +JMRI is free software; you can redistribute it and/or modify it +under the terms of version 2 of the GNU General Public License as +published by the Free Software Foundation. + +JMRI is distributed in the hope that it will be useful, but +WITHOUT ANY WARRANTY; without even the implied warranty of +MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +GNU General Public License for more details. + +A copy of version 2 of the GNU General Public License is +appended below. For more information, see +. + +Linking JMRI or its parts statically or dynamically with other +modules is making a combined work based on this library. Thus, the +terms and conditions of the GNU General Public License 2.0 cover +the whole combination. + +As a special exception, the copyright holders of JMRI give you +permission to link JMRI with independent modules to produce an +executable, regardless of the license terms of these independent +modules, and to copy and distribute the resulting executable under +terms of your choice, provided that you also meet, for each linked +independent module, the terms and conditions of the license of that +module. An independent module is a module which is not derived from +or based on JMRI. If you modify JMRI, you may extend this exception +to your version of JMRI, but you are not obligated to do so. If you do +not wish to do so, delete this exception statement from your version. + + +------------------------------------------------------------------- + + GNU GENERAL PUBLIC LICENSE + Version 2, June 1991 + + Copyright (C) 1989, 1991 Free Software Foundation, Inc., + 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA + Everyone is permitted to copy and distribute verbatim copies + of this license document, but changing it is not allowed. + + Preamble + + The licenses for most software are designed to take away your +freedom to share and change it. By contrast, the GNU General Public +License is intended to guarantee your freedom to share and change free +software--to make sure the software is free for all its users. This +General Public License applies to most of the Free Software +Foundation's software and to any other program whose authors commit to +using it. (Some other Free Software Foundation software is covered by +the GNU Lesser General Public License instead.) You can apply it to +your programs, too. + + When we speak of free software, we are referring to freedom, not +price. Our General Public Licenses are designed to make sure that you +have the freedom to distribute copies of free software (and charge for +this service if you wish), that you receive source code or can get it +if you want it, that you can change the software or use pieces of it +in new free programs; and that you know you can do these things. + + To protect your rights, we need to make restrictions that forbid +anyone to deny you these rights or to ask you to surrender the rights. +These restrictions translate to certain responsibilities for you if you +distribute copies of the software, or if you modify it. + + For example, if you distribute copies of such a program, whether +gratis or for a fee, you must give the recipients all the rights that +you have. You must make sure that they, too, receive or can get the +source code. And you must show them these terms so they know their +rights. + + We protect your rights with two steps: (1) copyright the software, and +(2) offer you this license which gives you legal permission to copy, +distribute and/or modify the software. + + Also, for each author's protection and ours, we want to make certain +that everyone understands that there is no warranty for this free +software. If the software is modified by someone else and passed on, we +want its recipients to know that what they have is not the original, so +that any problems introduced by others will not reflect on the original +authors' reputations. + + Finally, any free program is threatened constantly by software +patents. We wish to avoid the danger that redistributors of a free +program will individually obtain patent licenses, in effect making the +program proprietary. To prevent this, we have made it clear that any +patent must be licensed for everyone's free use or not licensed at all. + + The precise terms and conditions for copying, distribution and +modification follow. + + GNU GENERAL PUBLIC LICENSE + TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION + + 0. This License applies to any program or other work which contains +a notice placed by the copyright holder saying it may be distributed +under the terms of this General Public License. The "Program", below, +refers to any such program or work, and a "work based on the Program" +means either the Program or any derivative work under copyright law: +that is to say, a work containing the Program or a portion of it, +either verbatim or with modifications and/or translated into another +language. (Hereinafter, translation is included without limitation in +the term "modification".) Each licensee is addressed as "you". + +Activities other than copying, distribution and modification are not +covered by this License; they are outside its scope. The act of +running the Program is not restricted, and the output from the Program +is covered only if its contents constitute a work based on the +Program (independent of having been made by running the Program). +Whether that is true depends on what the Program does. + + 1. You may copy and distribute verbatim copies of the Program's +source code as you receive it, in any medium, provided that you +conspicuously and appropriately publish on each copy an appropriate +copyright notice and disclaimer of warranty; keep intact all the +notices that refer to this License and to the absence of any warranty; +and give any other recipients of the Program a copy of this License +along with the Program. + +You may charge a fee for the physical act of transferring a copy, and +you may at your option offer warranty protection in exchange for a fee. + + 2. You may modify your copy or copies of the Program or any portion +of it, thus forming a work based on the Program, and copy and +distribute such modifications or work under the terms of Section 1 +above, provided that you also meet all of these conditions: + + a) You must cause the modified files to carry prominent notices + stating that you changed the files and the date of any change. + + b) You must cause any work that you distribute or publish, that in + whole or in part contains or is derived from the Program or any + part thereof, to be licensed as a whole at no charge to all third + parties under the terms of this License. + + c) If the modified program normally reads commands interactively + when run, you must cause it, when started running for such + interactive use in the most ordinary way, to print or display an + announcement including an appropriate copyright notice and a + notice that there is no warranty (or else, saying that you provide + a warranty) and that users may redistribute the program under + these conditions, and telling the user how to view a copy of this + License. (Exception: if the Program itself is interactive but + does not normally print such an announcement, your work based on + the Program is not required to print an announcement.) + +These requirements apply to the modified work as a whole. If +identifiable sections of that work are not derived from the Program, +and can be reasonably considered independent and separate works in +themselves, then this License, and its terms, do not apply to those +sections when you distribute them as separate works. But when you +distribute the same sections as part of a whole which is a work based +on the Program, the distribution of the whole must be on the terms of +this License, whose permissions for other licensees extend to the +entire whole, and thus to each and every part regardless of who wrote it. + +Thus, it is not the intent of this section to claim rights or contest +your rights to work written entirely by you; rather, the intent is to +exercise the right to control the distribution of derivative or +collective works based on the Program. + +In addition, mere aggregation of another work not based on the Program +with the Program (or with a work based on the Program) on a volume of +a storage or distribution medium does not bring the other work under +the scope of this License. + + 3. You may copy and distribute the Program (or a work based on it, +under Section 2) in object code or executable form under the terms of +Sections 1 and 2 above provided that you also do one of the following: + + a) Accompany it with the complete corresponding machine-readable + source code, which must be distributed under the terms of Sections + 1 and 2 above on a medium customarily used for software interchange; or, + + b) Accompany it with a written offer, valid for at least three + years, to give any third party, for a charge no more than your + cost of physically performing source distribution, a complete + machine-readable copy of the corresponding source code, to be + distributed under the terms of Sections 1 and 2 above on a medium + customarily used for software interchange; or, + + c) Accompany it with the information you received as to the offer + to distribute corresponding source code. (This alternative is + allowed only for noncommercial distribution and only if you + received the program in object code or executable form with such + an offer, in accord with Subsection b above.) + +The source code for a work means the preferred form of the work for +making modifications to it. For an executable work, complete source +code means all the source code for all modules it contains, plus any +associated interface definition files, plus the scripts used to +control compilation and installation of the executable. However, as a +special exception, the source code distributed need not include +anything that is normally distributed (in either source or binary +form) with the major components (compiler, kernel, and so on) of the +operating system on which the executable runs, unless that component +itself accompanies the executable. + +If distribution of executable or object code is made by offering +access to copy from a designated place, then offering equivalent +access to copy the source code from the same place counts as +distribution of the source code, even though third parties are not +compelled to copy the source along with the object code. + + 4. You may not copy, modify, sublicense, or distribute the Program +except as expressly provided under this License. Any attempt +otherwise to copy, modify, sublicense or distribute the Program is +void, and will automatically terminate your rights under this License. +However, parties who have received copies, or rights, from you under +this License will not have their licenses terminated so long as such +parties remain in full compliance. + + 5. You are not required to accept this License, since you have not +signed it. However, nothing else grants you permission to modify or +distribute the Program or its derivative works. These actions are +prohibited by law if you do not accept this License. Therefore, by +modifying or distributing the Program (or any work based on the +Program), you indicate your acceptance of this License to do so, and +all its terms and conditions for copying, distributing or modifying +the Program or works based on it. + + 6. Each time you redistribute the Program (or any work based on the +Program), the recipient automatically receives a license from the +original licensor to copy, distribute or modify the Program subject to +these terms and conditions. You may not impose any further +restrictions on the recipients' exercise of the rights granted herein. +You are not responsible for enforcing compliance by third parties to +this License. + + 7. If, as a consequence of a court judgment or allegation of patent +infringement or for any other reason (not limited to patent issues), +conditions are imposed on you (whether by court order, agreement or +otherwise) that contradict the conditions of this License, they do not +excuse you from the conditions of this License. If you cannot +distribute so as to satisfy simultaneously your obligations under this +License and any other pertinent obligations, then as a consequence you +may not distribute the Program at all. For example, if a patent +license would not permit royalty-free redistribution of the Program by +all those who receive copies directly or indirectly through you, then +the only way you could satisfy both it and this License would be to +refrain entirely from distribution of the Program. + +If any portion of this section is held invalid or unenforceable under +any particular circumstance, the balance of the section is intended to +apply and the section as a whole is intended to apply in other +circumstances. + +It is not the purpose of this section to induce you to infringe any +patents or other property right claims or to contest validity of any +such claims; this section has the sole purpose of protecting the +integrity of the free software distribution system, which is +implemented by public license practices. Many people have made +generous contributions to the wide range of software distributed +through that system in reliance on consistent application of that +system; it is up to the author/donor to decide if he or she is willing +to distribute software through any other system and a licensee cannot +impose that choice. + +This section is intended to make thoroughly clear what is believed to +be a consequence of the rest of this License. + + 8. If the distribution and/or use of the Program is restricted in +certain countries either by patents or by copyrighted interfaces, the +original copyright holder who places the Program under this License +may add an explicit geographical distribution limitation excluding +those countries, so that distribution is permitted only in or among +countries not thus excluded. In such case, this License incorporates +the limitation as if written in the body of this License. + + 9. The Free Software Foundation may publish revised and/or new versions +of the General Public License from time to time. Such new versions will +be similar in spirit to the present version, but may differ in detail to +address new problems or concerns. + +Each version is given a distinguishing version number. If the Program +specifies a version number of this License which applies to it and "any +later version", you have the option of following the terms and conditions +either of that version or of any later version published by the Free +Software Foundation. If the Program does not specify a version number of +this License, you may choose any version ever published by the Free Software +Foundation. + + 10. If you wish to incorporate parts of the Program into other free +programs whose distribution conditions are different, write to the author +to ask for permission. For software which is copyrighted by the Free +Software Foundation, write to the Free Software Foundation; we sometimes +make exceptions for this. Our decision will be guided by the two goals +of preserving the free status of all derivatives of our free software and +of promoting the sharing and reuse of software generally. + + NO WARRANTY + + 11. BECAUSE THE PROGRAM IS LICENSED FREE OF CHARGE, THERE IS NO WARRANTY +FOR THE PROGRAM, TO THE EXTENT PERMITTED BY APPLICABLE LAW. EXCEPT WHEN +OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR OTHER PARTIES +PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED +OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF +MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE ENTIRE RISK AS +TO THE QUALITY AND PERFORMANCE OF THE PROGRAM IS WITH YOU. SHOULD THE +PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF ALL NECESSARY SERVICING, +REPAIR OR CORRECTION. + + 12. IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING +WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MAY MODIFY AND/OR +REDISTRIBUTE THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, +INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING +OUT OF THE USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED +TO LOSS OF DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY +YOU OR THIRD PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER +PROGRAMS), EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE +POSSIBILITY OF SUCH DAMAGES. + + END OF TERMS AND CONDITIONS + + How to Apply These Terms to Your New Programs + + If you develop a new program, and you want it to be of the greatest +possible use to the public, the best way to achieve this is to make it +free software which everyone can redistribute and change under these terms. + + To do so, attach the following notices to the program. It is safest +to attach them to the start of each source file to most effectively +convey the exclusion of warranty; and each file should have at least +the "copyright" line and a pointer to where the full notice is found. + + + Copyright (C) + + This program is free software; you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation; either version 2 of the License, or + (at your option) any later version. + + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. + + You should have received a copy of the GNU General Public License along + with this program; if not, write to the Free Software Foundation, Inc., + 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. + +Also add information on how to contact you by electronic and paper mail. + +If the program is interactive, make it output a short notice like this +when it starts in an interactive mode: + + Gnomovision version 69, Copyright (C) year name of author + Gnomovision comes with ABSOLUTELY NO WARRANTY; for details type `show w'. + This is free software, and you are welcome to redistribute it + under certain conditions; type `show c' for details. + +The hypothetical commands `show w' and `show c' should show the appropriate +parts of the General Public License. Of course, the commands you use may +be called something other than `show w' and `show c'; they could even be +mouse-clicks or menu items--whatever suits your program. + +You should also get your employer (if you work as a programmer) or your +school, if any, to sign a "copyright disclaimer" for the program, if +necessary. Here is a sample; alter the names: + + Yoyodyne, Inc., hereby disclaims all copyright interest in the program + `Gnomovision' (which makes passes at compilers) written by James Hacker. + + , 1 April 1989 + Ty Coon, President of Vice + +This General Public License does not permit incorporating your program into +proprietary programs. If your program is a subroutine library, you may +consider it more useful to permit linking proprietary applications with the +library. If this is what you want to do, use the GNU Lesser General +Public License instead of this License. + diff --git a/java/src/jmri/jmrix/maple/simulator/ConnectionConfig.java b/java/src/jmri/jmrix/maple/simulator/ConnectionConfig.java new file mode 100644 index 00000000000..6e29e4db091 --- /dev/null +++ b/java/src/jmri/jmrix/maple/simulator/ConnectionConfig.java @@ -0,0 +1,78 @@ +package jmri.jmrix.maple.simulator; + +import java.util.ResourceBundle; +import javax.swing.JButton; +import javax.swing.JPanel; +import jmri.jmrix.maple.MapleSystemConnectionMemo; +import jmri.jmrix.maple.nodeconfig.NodeConfigAction; + +/** + * Handle configuring an Maple layout connection via a MapleSimulator + * adapter. + *

+ * This uses the {@link SimulatorAdapter} class to do the actual connection. + * + * @author Bob Jacobsen Copyright (C) 2001, 2003 + * @author Paul Bender Copyright (C) 2009 + * @author Mark Underwood Copyright (C) 2015 + * + * @see SimulatorAdapter + * + * Based on jmri.jmrix.lenz.xnetsimulator.ConnectionConfig, copied from EasyDCC + */ +public class ConnectionConfig extends jmri.jmrix.AbstractSimulatorConnectionConfig { + + /** + * Ctor for an object being created during load process; Swing init is + * deferred. + */ + public ConnectionConfig(jmri.jmrix.SerialPortAdapter p) { + super(p); + } + + /** + * Ctor for a functional Swing object with no prexisting adapter + */ + public ConnectionConfig() { + super(); + } + + JButton b = new JButton(Bundle.getMessage("ConfigNodesTitle")); + + @Override + public void loadDetails(JPanel details) { + setInstance(); + + // have to embed the usual one in a new JPanel + b.addActionListener(new NodeConfigAction((MapleSystemConnectionMemo)adapter.getSystemConnectionMemo())); + if (!additionalItems.contains(b)) { + additionalItems.add(b); + } + super.loadDetails(details); + } + + @Override + public String name() { + return "Maple Simulator"; + } + + String manufacturerName = jmri.jmrix.maple.SerialConnectionTypeList.MAPLE; + + @Override + public String getManufacturer() { + return manufacturerName; + } + + @Override + public void setManufacturer(String manu) { + manufacturerName = manu; + } + + @Override + protected void setInstance() { + if (adapter == null) { + adapter = new SimulatorAdapter(); + } + } + +} diff --git a/java/src/jmri/jmrix/maple/simulator/SimulatorAdapter.java b/java/src/jmri/jmrix/maple/simulator/SimulatorAdapter.java new file mode 100644 index 00000000000..a7abee4a528 --- /dev/null +++ b/java/src/jmri/jmrix/maple/simulator/SimulatorAdapter.java @@ -0,0 +1,509 @@ +package jmri.jmrix.maple.simulator; + +import java.io.DataInputStream; +import java.io.DataOutputStream; +import java.io.IOException; +import java.io.PipedInputStream; +import java.io.PipedOutputStream; +import javax.swing.JOptionPane; +import jmri.jmrix.maple.SerialMessage; +import jmri.jmrix.maple.SerialPortController; // no special xSimulatorController +import jmri.jmrix.maple.SerialReply; +import jmri.jmrix.maple.MapleSystemConnectionMemo; +import jmri.jmrix.maple.SerialTrafficController; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +/** + * Provide access to a simulated Maple system. + *

+ * Currently, the Maple SimulatorAdapter reacts to the following commands sent from the user + * interface with an appropriate reply {@link #generateReply(SerialMessage)}: + *

    + *
  • Software version (poll) + *
  • Renumber (displays dialog: not supported) + *
  • Node Init (2 replies + user configurable node-bank-bit status) + *
  • Set signal/sensor/turnout (echoes message) + *
+ * + * Based on jmri.jmrix.lenz.xnetsimulator.XNetSimulatorAdapter / GrapevineSimulatorAdapter 2017 + *

+ * NOTE: Some material in this file was modified from other portions of the + * support infrastructure. + * + * @author Paul Bender, Copyright (C) 2009-2010 + * @author Mark Underwood, Copyright (C) 2015 + * @author Egbert Broerse, Copyright (C) 2018 + */ +public class SimulatorAdapter extends SerialPortController implements jmri.jmrix.SerialPortAdapter, Runnable { + + // private control members + private boolean opened = false; + private Thread sourceThread; + + private boolean outputBufferEmpty = true; + private boolean checkBuffer = true; + /** + * Simulator auto-init setting for number of banks to auto-reply on poll + */ + private int autoInit = 0; + + /** + * Create a new SimulatorAdapter. + */ + public SimulatorAdapter() { + super(new MapleSystemConnectionMemo("M", Bundle.getMessage("MapleSimulatorName"))); // pass customized user name + option1Name = "InitPreference"; // NOI18N + // init pref setting, the default is No init + options.put(option1Name, new Option(Bundle.getMessage("AutoInitLabel"), + new String[]{Bundle.getMessage("ButtonNoInit"), + Bundle.getMessage("ButtonAll"), Bundle.getMessage("Button4Each")})); + setManufacturer(jmri.jmrix.maple.SerialConnectionTypeList.MAPLE); + } + + /** + * {@inheritDoc} + * Simulated input/output pipes. + */ + @Override + public String openPort(String portName, String appName) { + try { + PipedOutputStream tempPipeI = new PipedOutputStream(); + log.debug("tempPipeI created"); + pout = new DataOutputStream(tempPipeI); + inpipe = new DataInputStream(new PipedInputStream(tempPipeI)); + log.debug("inpipe created {}", inpipe != null); + PipedOutputStream tempPipeO = new PipedOutputStream(); + outpipe = new DataOutputStream(tempPipeO); + pin = new DataInputStream(new PipedInputStream(tempPipeO)); + } catch (java.io.IOException e) { + log.error("init (pipe): Exception: " + e.toString()); + } + opened = true; + return null; // indicates OK return + } + + /** + * Set if the output buffer is empty or full. This should only be set to + * false by external processes. + * + * @param s true if output buffer is empty; false otherwise + */ + synchronized public void setOutputBufferEmpty(boolean s) { + outputBufferEmpty = s; + } + + /** + * Can the port accept additional characters? The state of CTS determines + * this, as there seems to be no way to check the number of queued bytes and + * buffer length. This might go false for short intervals, but it might also + * stick off if something goes wrong. + * + * @return true if port can accept additional characters; false otherwise + */ + public boolean okToSend() { + if (checkBuffer) { + log.debug("Buffer Empty: {}", outputBufferEmpty); + return (outputBufferEmpty); + } else { + log.debug("No Flow Control or Buffer Check"); + return (true); + } + } + + /** + * Set up all of the other objects to operate with a MapleSimulator + * connected to this port. + */ + @Override + public void configure() { + // connect to the traffic controller + log.debug("set tc for memo {}", getSystemConnectionMemo().getUserName()); + SerialTrafficController control = new SerialTrafficController(getSystemConnectionMemo()); + //compare with: XNetTrafficController packets = new XNetPacketizer(new LenzCommandStation()); + control.connectPort(this); + getSystemConnectionMemo().setTrafficController(control); + // do the common manager config + getSystemConnectionMemo().configureManagers(); + + if (getOptionState(option1Name).equals(getOptionChoices(option1Name)[1])) { + autoInit = 1; // auto-init all bits + } else if (getOptionState(option1Name).equals(getOptionChoices(option1Name)[2])) { + autoInit = 2; // first 4 items + } // default = none, also after locale change just to be safe + + // start the simulator + sourceThread = new Thread(this); + sourceThread.setName("Maple Simulator"); + sourceThread.setPriority(Thread.MIN_PRIORITY); + sourceThread.start(); + } + + /** + * {@inheritDoc} + */ + @Override + public void connect() throws java.io.IOException { + log.debug("connect called"); + super.connect(); + } + + // Base class methods for the Maple SerialPortController simulated interface + + /** + * {@inheritDoc} + */ + @Override + public DataInputStream getInputStream() { + if (!opened || pin == null) { + log.error("getInputStream called before load(), stream not available"); + } + log.debug("DataInputStream pin returned"); + return pin; + } + + /** + * {@inheritDoc} + */ + @Override + public DataOutputStream getOutputStream() { + if (!opened || pout == null) { + log.error("getOutputStream called before load(), stream not available"); + } + log.debug("DataOutputStream pout returned"); + return pout; + } + + /** + * {@inheritDoc} + * @return always true, given this SimulatorAdapter is running + */ + @Override + public boolean status() { + return opened; + } + + /** + * Get an array of valid baud rates. + * + * @return null + */ + @Override + public String[] validBaudRates() { + log.debug("validBaudRates should not have been invoked"); + return null; + } + + @Override + public String getCurrentBaudRate() { + return ""; + } + + @Override + public void run() { // start a new thread + // This thread has one task. It repeatedly reads from the input pipe + // and writes an appropriate response to the output pipe. This is the heart + // of the Maple command station simulation. + log.info("Maple Simulator Started"); + while (true) { + try { + synchronized (this) { + wait(50); + } + } catch (InterruptedException e) { + log.debug("interrupted, ending"); + return; + } + SerialMessage m = readMessage(); + SerialReply r; + if (log.isDebugEnabled()) { + StringBuffer buf = new StringBuffer(); + buf.append("Maple Simulator Thread received message: "); + if (m != null) { + for (int i = 0; i < m.getNumDataElements(); i++) { + buf.append(Integer.toHexString(0xFF & m.getElement(i)) + " "); + } + } else { + buf.append("null message buffer"); + } + log.trace(buf.toString()); // generates a lot of traffic + } + if (m != null) { + r = generateReply(m); + if (r != null) { // ignore errors + writeReply(r); + if (log.isDebugEnabled()) { + StringBuffer buf = new StringBuffer(); + buf.append("Maple Simulator Thread sent reply: "); + for (int i = 0; i < r.getNumDataElements(); i++) { + buf.append(Integer.toHexString(0xFF & r.getElement(i)) + " "); + } + log.debug(buf.toString()); + } + } + } + } + } + + /** + * Read one incoming message from the buffer + * and set outputBufferEmpty to true. + */ + private SerialMessage readMessage() { + SerialMessage msg = null; + // log.debug("Simulator reading message"); + try { + if (inpipe != null && inpipe.available() > 0) { + msg = loadChars(); + } + } catch (java.io.IOException e) { + // should do something meaningful here. + } + setOutputBufferEmpty(true); + return (msg); + } + + /** + * This is the heart of the simulation. It translates an + * incoming SerialMessage into an outgoing SerialReply. + * See {@link jmri.jmrix.maple.SerialMessage#generateReply(SerialMessage)}. + * + * @param msg the message received in the simulated node + * @return a single Maple message to confirm the requested operation, or a series + * of messages for each (fictitious) node/pin/state. To ignore certain commands, return null. + */ + @SuppressWarnings("fallthrough") + private SerialReply generateReply(SerialMessage msg) { + log.debug("Generate Reply to message from node {} (string = {})", msg.getAddr(), msg.toString()); + + SerialReply reply = new SerialReply(); // reply length is determined by highest byte added + int nodeaddr = msg.getAddr(); // node addres from element(0) + int b1 = msg.getElement(0); // raw hex value from element(0) + int b2 = msg.getElement(1); // bit + state + int b3 = msg.getElement(2); // element(2), must repeat node address + int b4 = msg.getElement(3); // bank + parity + int bank = (b4 & 0xF0) >> 4; // bank # on node, 0 on node initialization + log.debug("Message nodeaddress={} b1={} b2={} b3={} b4={}", nodeaddr, b1, b2, b3, b4); + + if (nodeaddr == 0) { // error + log.debug("general error: coded as: {}", (((b4 & 0x70) << 4) - 1)); + return null; + } + + switch (b2) { + + case 119: + log.debug("get software version (poll) message detected"); + // 2 byte software version number reply + reply.setElement(0, nodeaddr | 0x80); + reply.setElement(1, 9); // pretend version "9" + // no parity + break; + + case 0x71 : + log.debug("init node message 1 detected - ASD sensors"); + // init reply as set in prefs autoInit + if (autoInit > 0) { // not disabled + log.debug("start init 1 of node {}", nodeaddr); + NodeResponse(nodeaddr, 1, 1, autoInit); // banks 1-4 + } + // all replies are generated and sent by NodeResponse() + reply = null; + break; + + case 0x73: //(b2 == 0x70) && ((b4 & 0xF0) == 0x10) + log.debug("init node message 2 detected - parallel sensors"); + // init reply as set in prefs autoInit + if (autoInit > 0) { // not disabled + log.debug("start init 2 of node {}", nodeaddr); + NodeResponse(nodeaddr, 5, 5, autoInit); // bank 5 = parallel + } + // all replies are generated and sent by NodeResponse() + reply = null; + break; + + default: + if (bank == 0x6) { // this is the rename command, with element 2 = new node number + JOptionPane.showMessageDialog(null, + Bundle.getMessage("RenumberSupport"), + Bundle.getMessage("MessageTitle"), + JOptionPane.ERROR_MESSAGE); + log.debug("rename command not supported, old address: {}, new address: {}, bank: {}", + nodeaddr, b2, bank); + } else { + log.debug("echo normal command, node {} bank {} ignored", nodeaddr, bank); + reply = null; // ignore all other messages + // alternatavely, send a 4 byte general reply: + // reply.setElement(0, (nodeaddr | 0x80)); + // reply.setElement(1, (b2 & 0xFF)); // normally: bit + state + // reply.setElement(2, (nodeaddr | 0x80)); + // reply.setElement(3, (bank << 4)); // 0 = error, bank 1..3 for signals, 4..5 sensors (and parity) + // reply = setParity(reply, 0); + } + } + log.debug(reply == null ? "Message ignored" : "Reply generated " + reply.toString()); + return (reply); + } + + /** + * Write reply to output. + *

+ * Adapted from jmri.jmrix.nce.simulator.SimulatorAdapter. + * + * @param r reply on message + */ + private void writeReply(SerialReply r) { + if (r == null) { + return; // there is no reply to be sent + } + for (int i = 0; i < r.getNumDataElements(); i++) { + try { + outpipe.writeByte((byte) r.getElement(i)); + } catch (java.io.IOException ex) { + } + } + try { + outpipe.flush(); + } catch (java.io.IOException ex) { + } + } + + /** + * Get characters from the input source. + *

+ * Only used in the Receive thread. + * + * @return filled message, only when the message is complete. + * @throws IOException when presented by the input source. + */ + private SerialMessage loadChars() throws java.io.IOException { + int nchars; + byte[] rcvBuffer = new byte[32]; + + nchars = inpipe.read(rcvBuffer, 0, 32); + //log.debug("new message received"); + SerialMessage msg = new SerialMessage(nchars); + + for (int i = 0; i < nchars; i++) { + msg.setElement(i, rcvBuffer[i] & 0xFF); + } + return msg; + } + + /** + * Set parity on simulated Maple Node reply. + * Code copied from {@link SerialMessage#setParity(int)} + * + * @param r the SerialReply to complete + * @param start bit index to start + * @return SerialReply with parity set + */ + public SerialReply setParity(SerialReply r, int start) { + // nibble sum method + int sum = r.getElement(0 + start) & 0x0F; + sum += (r.getElement(0 + start) & 0x70) >> 4; + sum += (r.getElement(1 + start) * 2) & 0x0F; + sum += ((r.getElement(1 + start) * 2) & 0xF0) >> 4; + sum += (r.getElement(3 + start) & 0x70) >> 4; + //log.debug("PPPParity element read: {}", + // Integer.toHexString(r.getElement(3 + start) & 0x70)); + int parity = 16 - (sum & 0xF); + + r.setElement(3 + start, (r.getElement(3 + start) & 0xF0) | (parity & 0xF)); + return r; + } + + int SignalBankSize = 16; // theoretically: 16 + int SensorBankSize = 64; // theoretically: 0x3F + javax.swing.Timer timer; + + /** + * Pretend a node init reply for a range of banks and bits. Is this a proper simulation of hardware? + *

+ * Based on information in {@link jmri.jmrix.maple.SerialMessage#staticFormat(int, int, int, int)}. + * + * @param node the node address + * @param startBank first bank id to report + * @param endBank last bank id to report + * @param initBits number of inputs/output bits to report + */ + private void NodeResponse(int node, int startBank, int endBank, int initBits) { + if (node < 1 || node > 127) { // node address invalid + log.warn("Invalid Node Address; no response generated"); + return; + } + if (initBits > 1) { // leave at max when 1 + SignalBankSize = 4; // only first 4 signal bits reporting + SensorBankSize = 4; // only first 4 sensor bits reporting + } + int b1 = -1; + int b2 = -1; + int b3 = -1; + int b4 = -1; + + SerialReply nReply = new SerialReply(); // reply length is determined by highest byte added + nReply.setElement(0, node | 0x80); + nReply.setElement(2, node | 0x80); + + for (int k = startBank; k <= endBank; k++) { // bank + if (k <= 3) { // bank 1 to 3, signals + nReply.setElement(3, (k << 4)); // bank (bit 1234): 1-3 = signals + log.debug("element 3 set to 0x{} - {}", (k << 4) & 0x70, Integer.toBinaryString((k << 4) & 0x70)); + + for (int j = 1; j < SignalBankSize; j++) { // bits, send state of each signal bit (banks 1, 2, 3) + log.debug("Sending signal state of node {}, bank {}, bit {}", node, k, j); + nReply.setElement(1, ((j << 3) | 0x6) & 0x7F); // bit id (bits 2345) + state (bits 678): set to Red + + nReply = setParity(nReply, 0); + writeReply(nReply); + // check + b1 = nReply.getElement(0) & 0x7F; // raw hex value from element(0) + b2 = nReply.getElement(1) & 0x7F; // bit + state + b3 = nReply.getElement(2) & 0x7F; // element(2), repeat node address + b4 = nReply.getElement(3) & 0xFF; // bank + parity + if (b1 != b3) { + log.error("Address mismatch on node {} bank {} bit {}", node, k, j); + } + log.debug("Reply written for node {} bank {} bit {}: b1= {} b2={} b3={} b4={}", node, k, j, b1, b2, b3, b4); + log.debug("Reply as hex: {} {} {} {}", Integer.toHexString(b1), + Integer.toHexString(b2), Integer.toHexString(b3), Integer.toHexString(b4)); + log.debug("Reply as bin: {} - {} - {} - {}", Integer.toBinaryString(b1), + Integer.toBinaryString(b2), Integer.toBinaryString(b3), Integer.toBinaryString(b4)); + } + } else { // bank 4 and 5, sensors + nReply.setElement(3, (k << 4)); // bank (bit 1234): 4-5 = sensors + log.debug("element 3 set to 0x{} - {}", (k << 4) & 0x70, Integer.toBinaryString((k << 4) & 0x70)); + + for (int j = 1; j < SensorBankSize; j++) { // bits, send state of each sensor bit (banks 4, 5) + log.debug("Sending sensor state of node {}, bank {}, bit {}", node, k, j); + nReply.setElement(1, ((j << 1) | 0x1) & 0x7F); // bit id (bits 234567) + state (bit 8): inactive + + nReply = setParity(nReply,0); + writeReply(nReply); + // check + b1 = nReply.getElement(0) & 0x7F; // raw hex value from element(0) + b2 = nReply.getElement(1) & 0x7F; // bit + state + b3 = nReply.getElement(2) & 0x7F; // element(2), repeat node address + b4 = nReply.getElement(3) & 0xFF; // bank + parity + if (b1 != b3) { + log.error("Address mismatch on node {} bank {} bit {}", node, k, j); + } + log.debug("Reply written for node {} bank {} bit {}: b1= {} b2={} b3={} b4={}", node, k, j, b1, b2, b3, b4); + log.debug("Reply as hex: {} {} {} {}", Integer.toHexString(b1), + Integer.toHexString(b2), Integer.toHexString(b3), Integer.toHexString(b4)); + log.debug("Reply as bin: {} - {} - {} - {}", Integer.toBinaryString(b1), + Integer.toBinaryString(b2), Integer.toBinaryString(b3), Integer.toBinaryString(b4)); } + } + } + } + + // streams to share with user class + private DataOutputStream pout = null; // this is provided to classes who want to write to us + private DataInputStream pin = null; // this is provided to classes who want data from us + // internal ends of the pipes + private DataOutputStream outpipe = null; // feed pin + private DataInputStream inpipe = null; // feed pout + + private final static Logger log = LoggerFactory.getLogger(SimulatorAdapter.class); + +} diff --git a/java/src/jmri/jmrix/maple/simulator/configurexml/COPYING b/java/src/jmri/jmrix/maple/simulator/configurexml/COPYING new file mode 100644 index 00000000000..d93eaffc912 --- /dev/null +++ b/java/src/jmri/jmrix/maple/simulator/configurexml/COPYING @@ -0,0 +1,372 @@ +JMRI is free software; you can redistribute it and/or modify it +under the terms of version 2 of the GNU General Public License as +published by the Free Software Foundation. + +JMRI is distributed in the hope that it will be useful, but +WITHOUT ANY WARRANTY; without even the implied warranty of +MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +GNU General Public License for more details. + +A copy of version 2 of the GNU General Public License is +appended below. For more information, see +. + +Linking JMRI or its parts statically or dynamically with other +modules is making a combined work based on this library. Thus, the +terms and conditions of the GNU General Public License 2.0 cover +the whole combination. + +As a special exception, the copyright holders of JMRI give you +permission to link JMRI with independent modules to produce an +executable, regardless of the license terms of these independent +modules, and to copy and distribute the resulting executable under +terms of your choice, provided that you also meet, for each linked +independent module, the terms and conditions of the license of that +module. An independent module is a module which is not derived from +or based on JMRI. If you modify JMRI, you may extend this exception +to your version of JMRI, but you are not obligated to do so. If you do +not wish to do so, delete this exception statement from your version. + + +------------------------------------------------------------------- + + GNU GENERAL PUBLIC LICENSE + Version 2, June 1991 + + Copyright (C) 1989, 1991 Free Software Foundation, Inc., + 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA + Everyone is permitted to copy and distribute verbatim copies + of this license document, but changing it is not allowed. + + Preamble + + The licenses for most software are designed to take away your +freedom to share and change it. By contrast, the GNU General Public +License is intended to guarantee your freedom to share and change free +software--to make sure the software is free for all its users. This +General Public License applies to most of the Free Software +Foundation's software and to any other program whose authors commit to +using it. (Some other Free Software Foundation software is covered by +the GNU Lesser General Public License instead.) You can apply it to +your programs, too. + + When we speak of free software, we are referring to freedom, not +price. Our General Public Licenses are designed to make sure that you +have the freedom to distribute copies of free software (and charge for +this service if you wish), that you receive source code or can get it +if you want it, that you can change the software or use pieces of it +in new free programs; and that you know you can do these things. + + To protect your rights, we need to make restrictions that forbid +anyone to deny you these rights or to ask you to surrender the rights. +These restrictions translate to certain responsibilities for you if you +distribute copies of the software, or if you modify it. + + For example, if you distribute copies of such a program, whether +gratis or for a fee, you must give the recipients all the rights that +you have. You must make sure that they, too, receive or can get the +source code. And you must show them these terms so they know their +rights. + + We protect your rights with two steps: (1) copyright the software, and +(2) offer you this license which gives you legal permission to copy, +distribute and/or modify the software. + + Also, for each author's protection and ours, we want to make certain +that everyone understands that there is no warranty for this free +software. If the software is modified by someone else and passed on, we +want its recipients to know that what they have is not the original, so +that any problems introduced by others will not reflect on the original +authors' reputations. + + Finally, any free program is threatened constantly by software +patents. We wish to avoid the danger that redistributors of a free +program will individually obtain patent licenses, in effect making the +program proprietary. To prevent this, we have made it clear that any +patent must be licensed for everyone's free use or not licensed at all. + + The precise terms and conditions for copying, distribution and +modification follow. + + GNU GENERAL PUBLIC LICENSE + TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION + + 0. This License applies to any program or other work which contains +a notice placed by the copyright holder saying it may be distributed +under the terms of this General Public License. The "Program", below, +refers to any such program or work, and a "work based on the Program" +means either the Program or any derivative work under copyright law: +that is to say, a work containing the Program or a portion of it, +either verbatim or with modifications and/or translated into another +language. (Hereinafter, translation is included without limitation in +the term "modification".) Each licensee is addressed as "you". + +Activities other than copying, distribution and modification are not +covered by this License; they are outside its scope. The act of +running the Program is not restricted, and the output from the Program +is covered only if its contents constitute a work based on the +Program (independent of having been made by running the Program). +Whether that is true depends on what the Program does. + + 1. You may copy and distribute verbatim copies of the Program's +source code as you receive it, in any medium, provided that you +conspicuously and appropriately publish on each copy an appropriate +copyright notice and disclaimer of warranty; keep intact all the +notices that refer to this License and to the absence of any warranty; +and give any other recipients of the Program a copy of this License +along with the Program. + +You may charge a fee for the physical act of transferring a copy, and +you may at your option offer warranty protection in exchange for a fee. + + 2. You may modify your copy or copies of the Program or any portion +of it, thus forming a work based on the Program, and copy and +distribute such modifications or work under the terms of Section 1 +above, provided that you also meet all of these conditions: + + a) You must cause the modified files to carry prominent notices + stating that you changed the files and the date of any change. + + b) You must cause any work that you distribute or publish, that in + whole or in part contains or is derived from the Program or any + part thereof, to be licensed as a whole at no charge to all third + parties under the terms of this License. + + c) If the modified program normally reads commands interactively + when run, you must cause it, when started running for such + interactive use in the most ordinary way, to print or display an + announcement including an appropriate copyright notice and a + notice that there is no warranty (or else, saying that you provide + a warranty) and that users may redistribute the program under + these conditions, and telling the user how to view a copy of this + License. (Exception: if the Program itself is interactive but + does not normally print such an announcement, your work based on + the Program is not required to print an announcement.) + +These requirements apply to the modified work as a whole. If +identifiable sections of that work are not derived from the Program, +and can be reasonably considered independent and separate works in +themselves, then this License, and its terms, do not apply to those +sections when you distribute them as separate works. But when you +distribute the same sections as part of a whole which is a work based +on the Program, the distribution of the whole must be on the terms of +this License, whose permissions for other licensees extend to the +entire whole, and thus to each and every part regardless of who wrote it. + +Thus, it is not the intent of this section to claim rights or contest +your rights to work written entirely by you; rather, the intent is to +exercise the right to control the distribution of derivative or +collective works based on the Program. + +In addition, mere aggregation of another work not based on the Program +with the Program (or with a work based on the Program) on a volume of +a storage or distribution medium does not bring the other work under +the scope of this License. + + 3. You may copy and distribute the Program (or a work based on it, +under Section 2) in object code or executable form under the terms of +Sections 1 and 2 above provided that you also do one of the following: + + a) Accompany it with the complete corresponding machine-readable + source code, which must be distributed under the terms of Sections + 1 and 2 above on a medium customarily used for software interchange; or, + + b) Accompany it with a written offer, valid for at least three + years, to give any third party, for a charge no more than your + cost of physically performing source distribution, a complete + machine-readable copy of the corresponding source code, to be + distributed under the terms of Sections 1 and 2 above on a medium + customarily used for software interchange; or, + + c) Accompany it with the information you received as to the offer + to distribute corresponding source code. (This alternative is + allowed only for noncommercial distribution and only if you + received the program in object code or executable form with such + an offer, in accord with Subsection b above.) + +The source code for a work means the preferred form of the work for +making modifications to it. For an executable work, complete source +code means all the source code for all modules it contains, plus any +associated interface definition files, plus the scripts used to +control compilation and installation of the executable. However, as a +special exception, the source code distributed need not include +anything that is normally distributed (in either source or binary +form) with the major components (compiler, kernel, and so on) of the +operating system on which the executable runs, unless that component +itself accompanies the executable. + +If distribution of executable or object code is made by offering +access to copy from a designated place, then offering equivalent +access to copy the source code from the same place counts as +distribution of the source code, even though third parties are not +compelled to copy the source along with the object code. + + 4. You may not copy, modify, sublicense, or distribute the Program +except as expressly provided under this License. Any attempt +otherwise to copy, modify, sublicense or distribute the Program is +void, and will automatically terminate your rights under this License. +However, parties who have received copies, or rights, from you under +this License will not have their licenses terminated so long as such +parties remain in full compliance. + + 5. You are not required to accept this License, since you have not +signed it. However, nothing else grants you permission to modify or +distribute the Program or its derivative works. These actions are +prohibited by law if you do not accept this License. Therefore, by +modifying or distributing the Program (or any work based on the +Program), you indicate your acceptance of this License to do so, and +all its terms and conditions for copying, distributing or modifying +the Program or works based on it. + + 6. Each time you redistribute the Program (or any work based on the +Program), the recipient automatically receives a license from the +original licensor to copy, distribute or modify the Program subject to +these terms and conditions. You may not impose any further +restrictions on the recipients' exercise of the rights granted herein. +You are not responsible for enforcing compliance by third parties to +this License. + + 7. If, as a consequence of a court judgment or allegation of patent +infringement or for any other reason (not limited to patent issues), +conditions are imposed on you (whether by court order, agreement or +otherwise) that contradict the conditions of this License, they do not +excuse you from the conditions of this License. If you cannot +distribute so as to satisfy simultaneously your obligations under this +License and any other pertinent obligations, then as a consequence you +may not distribute the Program at all. For example, if a patent +license would not permit royalty-free redistribution of the Program by +all those who receive copies directly or indirectly through you, then +the only way you could satisfy both it and this License would be to +refrain entirely from distribution of the Program. + +If any portion of this section is held invalid or unenforceable under +any particular circumstance, the balance of the section is intended to +apply and the section as a whole is intended to apply in other +circumstances. + +It is not the purpose of this section to induce you to infringe any +patents or other property right claims or to contest validity of any +such claims; this section has the sole purpose of protecting the +integrity of the free software distribution system, which is +implemented by public license practices. Many people have made +generous contributions to the wide range of software distributed +through that system in reliance on consistent application of that +system; it is up to the author/donor to decide if he or she is willing +to distribute software through any other system and a licensee cannot +impose that choice. + +This section is intended to make thoroughly clear what is believed to +be a consequence of the rest of this License. + + 8. If the distribution and/or use of the Program is restricted in +certain countries either by patents or by copyrighted interfaces, the +original copyright holder who places the Program under this License +may add an explicit geographical distribution limitation excluding +those countries, so that distribution is permitted only in or among +countries not thus excluded. In such case, this License incorporates +the limitation as if written in the body of this License. + + 9. The Free Software Foundation may publish revised and/or new versions +of the General Public License from time to time. Such new versions will +be similar in spirit to the present version, but may differ in detail to +address new problems or concerns. + +Each version is given a distinguishing version number. If the Program +specifies a version number of this License which applies to it and "any +later version", you have the option of following the terms and conditions +either of that version or of any later version published by the Free +Software Foundation. If the Program does not specify a version number of +this License, you may choose any version ever published by the Free Software +Foundation. + + 10. If you wish to incorporate parts of the Program into other free +programs whose distribution conditions are different, write to the author +to ask for permission. For software which is copyrighted by the Free +Software Foundation, write to the Free Software Foundation; we sometimes +make exceptions for this. Our decision will be guided by the two goals +of preserving the free status of all derivatives of our free software and +of promoting the sharing and reuse of software generally. + + NO WARRANTY + + 11. BECAUSE THE PROGRAM IS LICENSED FREE OF CHARGE, THERE IS NO WARRANTY +FOR THE PROGRAM, TO THE EXTENT PERMITTED BY APPLICABLE LAW. EXCEPT WHEN +OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR OTHER PARTIES +PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED +OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF +MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE ENTIRE RISK AS +TO THE QUALITY AND PERFORMANCE OF THE PROGRAM IS WITH YOU. SHOULD THE +PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF ALL NECESSARY SERVICING, +REPAIR OR CORRECTION. + + 12. IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING +WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MAY MODIFY AND/OR +REDISTRIBUTE THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, +INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING +OUT OF THE USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED +TO LOSS OF DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY +YOU OR THIRD PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER +PROGRAMS), EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE +POSSIBILITY OF SUCH DAMAGES. + + END OF TERMS AND CONDITIONS + + How to Apply These Terms to Your New Programs + + If you develop a new program, and you want it to be of the greatest +possible use to the public, the best way to achieve this is to make it +free software which everyone can redistribute and change under these terms. + + To do so, attach the following notices to the program. It is safest +to attach them to the start of each source file to most effectively +convey the exclusion of warranty; and each file should have at least +the "copyright" line and a pointer to where the full notice is found. + + + Copyright (C) + + This program is free software; you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation; either version 2 of the License, or + (at your option) any later version. + + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. + + You should have received a copy of the GNU General Public License along + with this program; if not, write to the Free Software Foundation, Inc., + 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. + +Also add information on how to contact you by electronic and paper mail. + +If the program is interactive, make it output a short notice like this +when it starts in an interactive mode: + + Gnomovision version 69, Copyright (C) year name of author + Gnomovision comes with ABSOLUTELY NO WARRANTY; for details type `show w'. + This is free software, and you are welcome to redistribute it + under certain conditions; type `show c' for details. + +The hypothetical commands `show w' and `show c' should show the appropriate +parts of the General Public License. Of course, the commands you use may +be called something other than `show w' and `show c'; they could even be +mouse-clicks or menu items--whatever suits your program. + +You should also get your employer (if you work as a programmer) or your +school, if any, to sign a "copyright disclaimer" for the program, if +necessary. Here is a sample; alter the names: + + Yoyodyne, Inc., hereby disclaims all copyright interest in the program + `Gnomovision' (which makes passes at compilers) written by James Hacker. + + , 1 April 1989 + Ty Coon, President of Vice + +This General Public License does not permit incorporating your program into +proprietary programs. If your program is a subroutine library, you may +consider it more useful to permit linking proprietary applications with the +library. If this is what you want to do, use the GNU Lesser General +Public License instead of this License. + diff --git a/java/src/jmri/jmrix/maple/simulator/configurexml/ConnectionConfigXml.java b/java/src/jmri/jmrix/maple/simulator/configurexml/ConnectionConfigXml.java new file mode 100644 index 00000000000..9b5bfe8b046 --- /dev/null +++ b/java/src/jmri/jmrix/maple/simulator/configurexml/ConnectionConfigXml.java @@ -0,0 +1,116 @@ +package jmri.jmrix.maple.simulator.configurexml; + +import java.util.List; +import jmri.jmrix.configurexml.AbstractSerialConnectionConfigXml; +import jmri.jmrix.maple.SerialNode; +import jmri.jmrix.maple.SerialTrafficController; +import jmri.jmrix.maple.simulator.ConnectionConfig; +import jmri.jmrix.maple.simulator.SimulatorAdapter; +import jmri.jmrix.maple.MapleSystemConnectionMemo; +import org.jdom2.Element; + +/** + * Handle XML persistence of layout connections by persisting the + * SerialDriverAdapter (and connections). + *

+ * Note this is named as the XML version of a ConnectionConfig object, + * but it's actually persisting the SerialDriverAdapter. + *

+ * This class is invoked from jmrix.JmrixConfigPaneXml on write, as that class + * is the one actually registered. Reads are brought here directly via the class + * attribute in the XML. + * + * @author Bob Jacobsen Copyright (c) 2003 copied from NCE/Tams code + * @author kcameron Copyright (c) 2014 + */ +public class ConnectionConfigXml extends AbstractSerialConnectionConfigXml { + + public ConnectionConfigXml() { + super(); + } + + /** + * Write out the SerialNode objects too. + * + * @param e Element being extended + */ + @Override + protected void extendElement(Element e) { + SerialNode node = (SerialNode) ((MapleSystemConnectionMemo)adapter.getSystemConnectionMemo()).getTrafficController().getNode(0); + int index = 1; + while (node != null) { + // add node as an element + Element n = new Element("node"); + n.setAttribute("name", "" + node.getNodeAddress()); + e.addContent(n); + // add parameters to the node as needed + n.addContent(makeParameter("nodetype", "" + node.getNodeType())); + + // look for the next node + node = (SerialNode) ((MapleSystemConnectionMemo)adapter.getSystemConnectionMemo()).getTrafficController().getNode(index); + index++; + } + } + + protected Element makeParameter(String name, String value) { + Element p = new Element("parameter"); + p.setAttribute("name", name); + p.addContent(value); + return p; + } + + @Override + protected void getInstance(Object object) { + adapter = ((ConnectionConfig) object).getAdapter(); + } + + @Override + protected void getInstance() { + if (adapter == null) { + adapter = new SimulatorAdapter(); + } + } + + @Override + protected void unpackElement(Element shared, Element perNode) { + List l = shared.getChildren("node"); + for (int i = 0; i < l.size(); i++) { + Element n = l.get(i); + int addr = Integer.parseInt(n.getAttributeValue("name")); + int type = Integer.parseInt(findParmValue(n, "nodetype")); + + SerialTrafficController tc = ((MapleSystemConnectionMemo) adapter.getSystemConnectionMemo()).getTrafficController(); + + // create node (they register themselves) + SerialNode node = new SerialNode(addr, type, tc); + + // Trigger initialization of this Node to reflect these parameters + tc.initializeSerialNode(node); + } + } + + /** + * Service routine to look through "parameter" child elements to find a + * particular parameter value + * + * @param e Element containing parameters + * @param name name of desired parameter + * @return String value + */ + String findParmValue(Element e, String name) { + List l = e.getChildren("parameter"); + for (int i = 0; i < l.size(); i++) { + Element n = l.get(i); + if (n.getAttributeValue("name").equals(name)) { + return n.getTextTrim(); + } + } + return null; + } + + @Override + protected void register() { + this.register(new ConnectionConfig(adapter)); + } + +} From dd32c40f064968dfdc0c36370f249206fadb5391 Mon Sep 17 00:00:00 2001 From: Egbert Broerse Date: Sat, 31 Mar 2018 23:54:25 +0200 Subject: [PATCH 08/58] basically operational --- .../maple/MapleSystemConnectionMemo.java | 3 +++ .../jmrix/maple/SerialConnectionTypeList.java | 6 ++--- .../jmrix/maple/SerialTrafficController.java | 22 ++++++----------- .../maple/simulator/SimulatorAdapter.java | 24 ++++--------------- .../configurexml/ConnectionConfigXml.java | 2 -- 5 files changed, 18 insertions(+), 39 deletions(-) diff --git a/java/src/jmri/jmrix/maple/MapleSystemConnectionMemo.java b/java/src/jmri/jmrix/maple/MapleSystemConnectionMemo.java index fa23caffe14..d7bcaebd127 100644 --- a/java/src/jmri/jmrix/maple/MapleSystemConnectionMemo.java +++ b/java/src/jmri/jmrix/maple/MapleSystemConnectionMemo.java @@ -69,8 +69,11 @@ protected ResourceBundle getActionModelResourceBundle() { public void configureManagers(){ setTurnoutManager(new SerialTurnoutManager(this)); + InstanceManager.setTurnoutManager(getTurnoutManager()); setLightManager(new SerialLightManager(this)); + InstanceManager.setLightManager(getLightManager()); setSensorManager(new SerialSensorManager(this)); + InstanceManager.setSensorManager(getSensorManager()); } /** diff --git a/java/src/jmri/jmrix/maple/SerialConnectionTypeList.java b/java/src/jmri/jmrix/maple/SerialConnectionTypeList.java index dfa0c9658f9..5d9de103a4b 100644 --- a/java/src/jmri/jmrix/maple/SerialConnectionTypeList.java +++ b/java/src/jmri/jmrix/maple/SerialConnectionTypeList.java @@ -5,10 +5,9 @@ /** * Returns a list of valid Maple Connection Types - *

+ * * @author Bob Jacobsen Copyright (C) 2010 * @author Kevin Dickerson Copyright (C) 2010 - * */ @ServiceProvider(service = ConnectionTypeList.class) public class SerialConnectionTypeList implements jmri.jmrix.ConnectionTypeList { @@ -18,7 +17,8 @@ public class SerialConnectionTypeList implements jmri.jmrix.ConnectionTypeList { @Override public String[] getAvailableProtocolClasses() { return new String[]{ - "jmri.jmrix.maple.serialdriver.ConnectionConfig" + "jmri.jmrix.maple.serialdriver.ConnectionConfig", + "jmri.jmrix.maple.simulator.ConnectionConfig" }; } diff --git a/java/src/jmri/jmrix/maple/SerialTrafficController.java b/java/src/jmri/jmrix/maple/SerialTrafficController.java index 683a9398c37..b45e2900d09 100644 --- a/java/src/jmri/jmrix/maple/SerialTrafficController.java +++ b/java/src/jmri/jmrix/maple/SerialTrafficController.java @@ -211,14 +211,14 @@ protected void handleTimeout(AbstractMRMessage m, AbstractMRListener l) { wrTimeoutCount++; // should not happen } else if (m.getElement(3) == 'R' && m.getElement(4) == 'C') { if (mNeedAdditionalPollPacket) { -// log.warn("Timeout of poll message, node = "+curSerialNodeIndex+" beg addr = "+mSavedPollAddress); + // log.warn("Timeout of poll message, node = {} beg addr = {}", curSerialNodeIndex, mSavedPollAddress); getNode(curSerialNodeIndex).handleTimeout(m, l); } else { -// log.warn("Timeout of poll message, node = "+(curSerialNodeIndex-1)+" beg addr = "+mSavedPollAddress); + // log.warn("Timeout of poll message, node = {} beg addr = {}", (curSerialNodeIndex-1), mSavedPollAddress); getNode(curSerialNodeIndex - 1).handleTimeout(m, l); } } else { - log.error("Timeout of unknown message - " + m.toString()); + log.error("Timeout of unknown message - {}", m.toString()); } } @@ -285,15 +285,11 @@ protected void loadChars(AbstractMRReply msg, DataInputStream istream) throws ja msg.setElement(i, char1 & 0xFF); if (first) { first = false; - if (log.isDebugEnabled()) { - log.debug("start message with " + char1); - } + log.debug("start message with {}", char1); } if (char1 == 0x03) { // normal message // get checksum bytes and end - if (log.isDebugEnabled()) { - log.debug("ETX ends message"); - } + log.debug("ETX ends message"); char1 = readByteProtected(istream); msg.setElement(i + 1, char1 & 0xFF); char1 = readByteProtected(istream); @@ -302,9 +298,7 @@ protected void loadChars(AbstractMRReply msg, DataInputStream istream) throws ja } if (char1 == 0x06) { // ACK OK // get station, command and end - if (log.isDebugEnabled()) { - log.debug("ACK ends message"); - } + log.debug("ACK ends message"); char1 = readByteProtected(istream); // byte 2 msg.setElement(++i, char1 & 0xFF); char1 = readByteProtected(istream); // byte 3 @@ -317,9 +311,7 @@ protected void loadChars(AbstractMRReply msg, DataInputStream istream) throws ja } if (char1 == 0x15) { // NAK error // get station, command, error bytes and end - if (log.isDebugEnabled()) { - log.debug("NAK ends message"); - } + log.debug("NAK ends message"); char1 = readByteProtected(istream); // byte 2 msg.setElement(++i, char1 & 0xFF); char1 = readByteProtected(istream); // byte 3 diff --git a/java/src/jmri/jmrix/maple/simulator/SimulatorAdapter.java b/java/src/jmri/jmrix/maple/simulator/SimulatorAdapter.java index a7abee4a528..952ddc77f2d 100644 --- a/java/src/jmri/jmrix/maple/simulator/SimulatorAdapter.java +++ b/java/src/jmri/jmrix/maple/simulator/SimulatorAdapter.java @@ -53,11 +53,6 @@ public class SimulatorAdapter extends SerialPortController implements jmri.jmrix */ public SimulatorAdapter() { super(new MapleSystemConnectionMemo("M", Bundle.getMessage("MapleSimulatorName"))); // pass customized user name - option1Name = "InitPreference"; // NOI18N - // init pref setting, the default is No init - options.put(option1Name, new Option(Bundle.getMessage("AutoInitLabel"), - new String[]{Bundle.getMessage("ButtonNoInit"), - Bundle.getMessage("ButtonAll"), Bundle.getMessage("Button4Each")})); setManufacturer(jmri.jmrix.maple.SerialConnectionTypeList.MAPLE); } @@ -117,20 +112,11 @@ public boolean okToSend() { */ @Override public void configure() { - // connect to the traffic controller log.debug("set tc for memo {}", getSystemConnectionMemo().getUserName()); - SerialTrafficController control = new SerialTrafficController(getSystemConnectionMemo()); - //compare with: XNetTrafficController packets = new XNetPacketizer(new LenzCommandStation()); - control.connectPort(this); - getSystemConnectionMemo().setTrafficController(control); + // connect to the traffic controller + ((MapleSystemConnectionMemo) getSystemConnectionMemo()).getTrafficController().connectPort(this); // do the common manager config - getSystemConnectionMemo().configureManagers(); - - if (getOptionState(option1Name).equals(getOptionChoices(option1Name)[1])) { - autoInit = 1; // auto-init all bits - } else if (getOptionState(option1Name).equals(getOptionChoices(option1Name)[2])) { - autoInit = 2; // first 4 items - } // default = none, also after locale change just to be safe + ((MapleSystemConnectionMemo) getSystemConnectionMemo()).configureManagers(); // start the simulator sourceThread = new Thread(this); @@ -274,10 +260,10 @@ private SerialMessage readMessage() { */ @SuppressWarnings("fallthrough") private SerialReply generateReply(SerialMessage msg) { - log.debug("Generate Reply to message from node {} (string = {})", msg.getAddr(), msg.toString()); + log.debug("Generate Reply to message from node {} (string = {})", msg.getAddress(), msg.toString()); SerialReply reply = new SerialReply(); // reply length is determined by highest byte added - int nodeaddr = msg.getAddr(); // node addres from element(0) + int nodeaddr = msg.getAddress(); // node addres from element(0) int b1 = msg.getElement(0); // raw hex value from element(0) int b2 = msg.getElement(1); // bit + state int b3 = msg.getElement(2); // element(2), must repeat node address diff --git a/java/src/jmri/jmrix/maple/simulator/configurexml/ConnectionConfigXml.java b/java/src/jmri/jmrix/maple/simulator/configurexml/ConnectionConfigXml.java index 9b5bfe8b046..f727988ecd7 100644 --- a/java/src/jmri/jmrix/maple/simulator/configurexml/ConnectionConfigXml.java +++ b/java/src/jmri/jmrix/maple/simulator/configurexml/ConnectionConfigXml.java @@ -43,8 +43,6 @@ protected void extendElement(Element e) { Element n = new Element("node"); n.setAttribute("name", "" + node.getNodeAddress()); e.addContent(n); - // add parameters to the node as needed - n.addContent(makeParameter("nodetype", "" + node.getNodeType())); // look for the next node node = (SerialNode) ((MapleSystemConnectionMemo)adapter.getSystemConnectionMemo()).getTrafficController().getNode(index); From 681b65c6abf2ba7b2f16b704d5730954b744168f Mon Sep 17 00:00:00 2001 From: Egbert Broerse Date: Wed, 4 Apr 2018 00:22:19 +0200 Subject: [PATCH 09/58] add maple poll reply, using public tc method i18n --- java/src/jmri/jmrix/JmrixBundle.properties | 1 + java/src/jmri/jmrix/maple/OutputBits.java | 22 +- java/src/jmri/jmrix/maple/SerialMessage.java | 6 + .../jmrix/maple/SerialTrafficController.java | 4 +- .../maple/assignment/ListBundle.properties | 5 +- .../maple/assignment/ListBundle_da.properties | 5 +- .../maple/assignment/ListBundle_de.properties | 5 +- .../maple/assignment/ListBundle_es.properties | 14 +- .../maple/assignment/ListBundle_fr.properties | 5 +- .../maple/assignment/ListBundle_it.properties | 15 +- .../assignment/ListBundle_ja_JP.properties | 41 +-- .../jmrix/maple/assignment/ListFrame.java | 7 +- .../maple/nodeconfig/NodeConfigFrame.java | 12 +- .../maple/packetgen/SerialPacketGenFrame.java | 21 +- .../configurexml/ConnectionConfigXml.java | 2 +- .../maple/simulator/SimulatorAdapter.java | 239 +++++------------- .../configurexml/ConnectionConfigXml.java | 21 +- 17 files changed, 174 insertions(+), 251 deletions(-) diff --git a/java/src/jmri/jmrix/JmrixBundle.properties b/java/src/jmri/jmrix/JmrixBundle.properties index f5ac5b1c160..3040b79e287 100644 --- a/java/src/jmri/jmrix/JmrixBundle.properties +++ b/java/src/jmri/jmrix/JmrixBundle.properties @@ -234,6 +234,7 @@ ConfigNodesTitle = Configure Nodes LabelPoll = Poll ButtonQueryNode = Query Node PollToolTip = Send poll request +PollToolTipMulti = Send poll request (first command only, if multiple commands) NodePanelName = Node NodeBoxLabel = Node: NodeBoxTip = Select a configured node diff --git a/java/src/jmri/jmrix/maple/OutputBits.java b/java/src/jmri/jmrix/maple/OutputBits.java index 45dda94b730..c79b6b6ce31 100644 --- a/java/src/jmri/jmrix/maple/OutputBits.java +++ b/java/src/jmri/jmrix/maple/OutputBits.java @@ -5,7 +5,7 @@ /** * Utility Class supporting output to Maple HMI's - *

+ *

* All of the Maple HMI panels receive the same output bits. This keeps them * synchronized. Output is sent in "broadcast" mode to Station Address 0. All * HMI's receive the output. Output is sent at the end of each polling cycle, @@ -16,7 +16,7 @@ * the same output bits. Coil bits within Maple Systems HMI's are divided into * input (1-1000) and output (1001-9000), so input bits are read starting from * HMI address 1, and output bits are written starting at HMI address 1001. - *

+ * * @author Dave Duchamp, Copyright (C) 2009 */ public class OutputBits { @@ -54,8 +54,10 @@ public static int getSendDelay() { } /** - * Public method setting an output bit. Note: state = 'true' for 0, 'false' - * for 1 bits are numbered from 1 (not 0) + * Set an output bit. + *

+ * Note: state = 'true' for 0, 'false' for 1. + * Bits are numbered from 1 (not 0) */ public void setOutputBit(int bitNumber, boolean state) { // validate that this bitNumber is defined @@ -75,8 +77,11 @@ public void setOutputBit(int bitNumber, boolean state) { } /** - * Public method get the current state of an output bit. Note: returns - * 'true' for 0, 'false' for 1 bits are numbered from 1 (not 0) + * Get the current state of an output bit. + *

+ * Bits are numbered from 1 (not 0). + * + * @return 'true' for 0, 'false' for 1 */ public boolean getOutputBit(int bitNumber) { // locate in the outputArray @@ -97,7 +102,7 @@ public boolean getOutputBit(int bitNumber) { } /** - * Public Method to create an Transmit packet (SerialMessage) + * Create a Transmit packet (SerialMessage). */ public SerialMessage createOutPacket(int startBitNum, int endBitNum) { int nBits = endBitNum - startBitNum + 1; @@ -153,6 +158,5 @@ public static OutputBits instance() { } private final static Logger log = LoggerFactory.getLogger(OutputBits.class); -} - +} diff --git a/java/src/jmri/jmrix/maple/SerialMessage.java b/java/src/jmri/jmrix/maple/SerialMessage.java index 77611cf34ac..40eec228811 100644 --- a/java/src/jmri/jmrix/maple/SerialMessage.java +++ b/java/src/jmri/jmrix/maple/SerialMessage.java @@ -96,6 +96,7 @@ public int getNumItems() { } // static methods to return a formatted message + static public SerialMessage getPoll(int UA, int startAdd, int count) { if ((count <= 0) || (count > 99)) { log.error("Illegal count in Maple poll message - {}", count); @@ -147,6 +148,11 @@ void setChecksum(int index) { setElement(index + 1, secondChar); } +// public int maxSize() { +// return DEFAULTMAXSIZE; +// } +// static public final int DEFAULTMAXSIZE = 404; // Maple RR Request Docs page 9 + private final static Logger log = LoggerFactory.getLogger(SerialMessage.class); } diff --git a/java/src/jmri/jmrix/maple/SerialTrafficController.java b/java/src/jmri/jmrix/maple/SerialTrafficController.java index b45e2900d09..8ee3a935cf2 100644 --- a/java/src/jmri/jmrix/maple/SerialTrafficController.java +++ b/java/src/jmri/jmrix/maple/SerialTrafficController.java @@ -277,7 +277,7 @@ protected boolean endOfMessage(AbstractMRReply msg) { } @Override - protected void loadChars(AbstractMRReply msg, DataInputStream istream) throws java.io.IOException { + public void loadChars(AbstractMRReply msg, DataInputStream istream) throws java.io.IOException { int i; boolean first = true; for (i = 0; i < msg.maxSize() - 1; i++) { @@ -287,7 +287,7 @@ protected void loadChars(AbstractMRReply msg, DataInputStream istream) throws ja first = false; log.debug("start message with {}", char1); } - if (char1 == 0x03) { // normal message + if (char1 == 0x03) { // normal message // get checksum bytes and end log.debug("ETX ends message"); char1 = readByteProtected(istream); diff --git a/java/src/jmri/jmrix/maple/assignment/ListBundle.properties b/java/src/jmri/jmrix/maple/assignment/ListBundle.properties index 02c933b7017..a3cfbaa6bb4 100644 --- a/java/src/jmri/jmrix/maple/assignment/ListBundle.properties +++ b/java/src/jmri/jmrix/maple/assignment/ListBundle.properties @@ -10,8 +10,9 @@ ShowInputButton = Show Input Bits ShowInputTip = Select this button to show input bit assignments ShowOutputButton = Show Output Bits ShowOutputTip = Select this button to show output bit assignments -InputBitsAnd = input bits and -OutputBits = output bits + +NodeInfoText = Node Information +BitsInfoText = {0} input bits and {1} output bits # BitsPerCard = bits per card NoNodesError = ERROR - no Maple nodes were found. diff --git a/java/src/jmri/jmrix/maple/assignment/ListBundle_da.properties b/java/src/jmri/jmrix/maple/assignment/ListBundle_da.properties index 285d4f6f52e..3192ab931df 100644 --- a/java/src/jmri/jmrix/maple/assignment/ListBundle_da.properties +++ b/java/src/jmri/jmrix/maple/assignment/ListBundle_da.properties @@ -13,8 +13,9 @@ ShowInputButton = Show Input Bits ShowInputTip = Select this button to show input bit assignments ShowOutputButton = Show Output Bits ShowOutputTip = Select this button to show output bit assignments -InputBitsAnd = input bits and -OutputBits = output bits + +NodeInfoText = Node Information +BitsInfoText = {0} input bits and {1} output bits # BitsPerCard = bits per card NoNodesError = ERROR - no Maple nodes were found. diff --git a/java/src/jmri/jmrix/maple/assignment/ListBundle_de.properties b/java/src/jmri/jmrix/maple/assignment/ListBundle_de.properties index 4a50f698d43..b198c50d00f 100644 --- a/java/src/jmri/jmrix/maple/assignment/ListBundle_de.properties +++ b/java/src/jmri/jmrix/maple/assignment/ListBundle_de.properties @@ -13,8 +13,9 @@ ShowInputButton = Zeige Eingangsbits ShowInputTip = W\u00e4hle diese Option zur Anzeige der Eingangsbits ShowOutputButton = Zeige Ausgangsbits ShowOutputTip = W\u00e4hle diese Option zur Anzeige der Ausgangsbits -InputBitsAnd = Eingangsbits und -OutputBits = Ausgangsbits + +NodeInfoText = Node-Information +BitsInfoText = {0} Eingangsbits und {1} Ausgangsbits # BitsPerCard = Bits pro Karte NoNodesError = Fehler - Kein Maple konnte gefunden werden. diff --git a/java/src/jmri/jmrix/maple/assignment/ListBundle_es.properties b/java/src/jmri/jmrix/maple/assignment/ListBundle_es.properties index aded37411ce..822511ba762 100644 --- a/java/src/jmri/jmrix/maple/assignment/ListBundle_es.properties +++ b/java/src/jmri/jmrix/maple/assignment/ListBundle_es.properties @@ -1,12 +1,10 @@ -# ListBundle.properties +# ListBundle_es.properties # -# -# -# Default properties for the jmri.jmrix.maple.assignment window +# Spanish properties for the jmri.jmrix.maple.assignment window WindowTitle = Lista de asignaciones Maple -NodePanelName = Nodo C/MRI +NodePanelName = Nodo Maple NodeBoxLabel = Nodo: NodeBoxTip = Elija un nodo configurado ShowInputButton = Ver bits de entrada @@ -16,10 +14,10 @@ ShowOutputTip = Pulse para ver las asignaciones de los bits de salida InputBitsAnd = bits de entrada y OutputBits = bits de salida BitsPerCard = bits por tarjeta -NoNodesError = ERROR - no se encuentran nodos C/MRI. +NoNodesError = ERROR - no se encuentran nodos Maple. -AssignmentPanelInputName = Asignaciones de entrada -AssignmentPanelOutputName = Asignaciones de salida +NodeInfoText = Informacion de Nodos +BitsInfoText = {0} Asignaciones de entrada e {1} Asignaciones de salida HeadingBit = Bit HeadingAddress = Direccion HeadingSystemName = Nombre de sistema diff --git a/java/src/jmri/jmrix/maple/assignment/ListBundle_fr.properties b/java/src/jmri/jmrix/maple/assignment/ListBundle_fr.properties index c40826aa6cb..c2dac1b3c3a 100644 --- a/java/src/jmri/jmrix/maple/assignment/ListBundle_fr.properties +++ b/java/src/jmri/jmrix/maple/assignment/ListBundle_fr.properties @@ -11,8 +11,9 @@ ShowInputButton = Montrer Bits d'Entrée ShowInputTip = Sélectionnez ce bouton pour montrer les affectations des bits d'entrée ShowOutputButton = Montrer Bits de Sortie ShowOutputTip = SSélectionnez ce bouton pour montrer les affectations des bits de sortie -InputBitsAnd = bits d'entrée et -OutputBits = bits de sortie + +NodeInfoText = Information du Nœud +BitsInfoText = {0} bits d'entrée et {1} bits de sortie # BitsPerCard = bits par cartes NoNodesError = ERREUR - Pas de Nœud Maple trouvés. diff --git a/java/src/jmri/jmrix/maple/assignment/ListBundle_it.properties b/java/src/jmri/jmrix/maple/assignment/ListBundle_it.properties index 17e7bef03da..9e8cbf817c6 100644 --- a/java/src/jmri/jmrix/maple/assignment/ListBundle_it.properties +++ b/java/src/jmri/jmrix/maple/assignment/ListBundle_it.properties @@ -1,11 +1,8 @@ -# ListBundle.properties -# -# -# -# Default properties for the jmri.jmrix.maple.assignment window -# -# Italian translation: Enzo Fortuna (babbo_enzo@yahoo.com ) +# ListBundle_it.properties # +# Italian properties for the jmri.jmrix.maple.assignment window +# Translation: Enzo Fortuna (babbo_enzo@yahoo.com ) + WindowTitle = Lista Assegnazioni Maple NodePanelName = Nodo Maple @@ -15,8 +12,8 @@ ShowInputButton = Visualizza Bits in Ingresso ShowInputTip = Seleziona questo pulsante per vedere le assegnazioni Bits in Ingresso ShowOutputButton = Visualizza Bits in Uscita ShowOutputTip = Seleziona questo pulsante per vedere le assegnazioni Bits di Uscita -InputBitsAnd = Bit Ingresso e -OutputBits = Bit Uscita +NodeInfoText = Informazione di Nodo +BitsInfoText = {0} Bit Ingresso e {1} Bit Uscita # BitsPerCard = bits per scheda NoNodesError = ERRORE - Nessun Nordo Maple trovato. diff --git a/java/src/jmri/jmrix/maple/assignment/ListBundle_ja_JP.properties b/java/src/jmri/jmrix/maple/assignment/ListBundle_ja_JP.properties index 10c5e298164..a18b1a43061 100644 --- a/java/src/jmri/jmrix/maple/assignment/ListBundle_ja_JP.properties +++ b/java/src/jmri/jmrix/maple/assignment/ListBundle_ja_JP.properties @@ -4,27 +4,28 @@ # # Japanese properties for the jmri.jmrix.maple.assignment window # Translated by Sakae Akanum -WindowTitle = Maple\u5272\u308A\u5F53\u3066\u30EA\u30B9\u30C8 +WindowTitle = Maple\u5272\u308a\u5f53\u3066\u30ea\u30b9\u30c8 -NodePanelName = Maple\u30CE\u30FC\u30C9 -NodeBoxLabel = \u30CE\u30FC\u30C9: -NodeBoxTip = \u8A2D\u5B9A\u3055\u308C\u305F\u30CE\u30FC\u30C9\u3092\u9078\u629E\u3057\u3066\u4E0B\u3055\u3044\u3002 -ShowInputButton = \u5165\u529B\u30D3\u30C3\u30C8\u3092\u8868\u793A -ShowInputTip = \u3053\u306E\u30DC\u30BF\u30F3\u3067\u5165\u529B\u30D3\u30C3\u30C8\u306E\u5272\u308A\u5F53\u3066\u3092\u8868\u793A\u3057\u307E\u3059\u3002 -ShowOutputButton = \u51FA\u529B\u30D3\u30C3\u30C8\u8868\u793A -ShowOutputTip = \u3053\u306E\u30DC\u30BF\u30F3\u3067\u51FA\u529B\u30D3\u30C3\u30C8\u306E\u5272\u308A\u5F53\u3066\u3092\u8868\u793A\u3057\u307E\u3059\u3002 -InputBitsAnd = \u5165\u529B\u30D3\u30C3\u30C8\u3068 -OutputBits = \u51FA\u529B\u30D3\u30C3\u30C8 -BitsPerCard = \u30AB\u30FC\u30C9\u6BCE\u306E\u30D3\u30C3\u30C8\u6570 -NoNodesError = \u30A8\u30E9\u30FC - Maple\u30CE\u30FC\u30C9\u304C\u898B\u3064\u304B\u308A\u307E\u305B\u3093\u3067\u3057\u305F\u3002 +NodePanelName = Maple\u30ce\u30fc\u30c9 +NodeBoxLabel = \u30ce\u30fc\u30c9: +NodeBoxTip = \u8a2d\u5b9a\u3055\u308c\u305f\u30ce\u30fc\u30c9\u3092\u9078\u629e\u3057\u3066\u4e0b\u3055\u3044\u3002 +ShowInputButton = \u5165\u529b\u30d3\u30c3\u30c8\u3092\u8868\u793a +ShowInputTip = \u3053\u306e\u30dc\u30bf\u30f3\u3067\u5165\u529b\u30d3\u30c3\u30c8\u306e\u5272\u308a\u5f53\u3066\u3092\u8868\u793a\u3057\u307e\u3059\u3002 +ShowOutputButton = \u51fa\u529b\u30d3\u30c3\u30c8\u8868\u793a +ShowOutputTip = \u3053\u306e\u30dc\u30bf\u30f3\u3067\u51fa\u529b\u30d3\u30c3\u30c8\u306e\u5272\u308a\u5f53\u3066\u3092\u8868\u793a\u3057\u307e\u3059\u3002 -AssignmentPanelInputName = \u5165\u529B\u5272\u308A\u5F53\u3066 -AssignmentPanelOutputName = \u51FA\u529B\u5272\u308A\u5F53\u3066 -HeadingBit = \u30D3\u30C3\u30C8 -HeadingAddress = \u30A2\u30C9\u30EC\u30B9 -HeadingSystemName = \u30B7\u30B9\u30C6\u30E0\u540D -HeadingUserName = \u30E6\u30FC\u30B6\u30FC\u540D -AssignmentFree = - \u30D5\u30EA\u30FC - +NodeInfoText = Node Information +BitsInfoText = {0} \u5165\u529b\u30d3\u30c3\u30c8\u3068 {1} \u51fa\u529b\u30d3\u30c3\u30c8 +#BitsPerCard = \u30ab\u30fc\u30c9\u6bce\u306e\u30d3\u30c3\u30c8\u6570 +NoNodesError = \u30a8\u30e9\u30fc - Maple\u30ce\u30fc\u30c9\u304c\u898b\u3064\u304b\u308a\u307e\u305b\u3093\u3067\u3057\u305f\u3002 + +AssignmentPanelInputName = \u5165\u529b\u5272\u308a\u5f53\u3066 +AssignmentPanelOutputName = \u51fa\u529b\u5272\u308a\u5f53\u3066 +HeadingBit = \u30d3\u30c3\u30c8 +HeadingAddress = \u30a2\u30c9\u30ec\u30b9 +HeadingSystemName = \u30b7\u30b9\u30c6\u30e0\u540d +HeadingUserName = \u30e6\u30fc\u30b6\u30fc\u540d +AssignmentFree = - \u30d5\u30ea\u30fc - PrintButtonText = \u5370\u5237 -PrintButtonTip = \u3053\u3053\u3092\u30AF\u30EA\u30C3\u30AF\u3059\u308B\u3068\u4E0A\u8A18\u306E\u5272\u308A\u5F53\u3066\u304C\u5370\u5237\u3055\u308C\u307E\u3059\u3002 +PrintButtonTip = \u3053\u3053\u3092\u30af\u30ea\u30c3\u30af\u3059\u308b\u3068\u4e0a\u8a18\u306e\u5272\u308a\u5f53\u3066\u304c\u5370\u5237\u3055\u308c\u307e\u3059\u3002 diff --git a/java/src/jmri/jmrix/maple/assignment/ListFrame.java b/java/src/jmri/jmrix/maple/assignment/ListFrame.java index 19ed5a23a11..4e8f7f47abd 100644 --- a/java/src/jmri/jmrix/maple/assignment/ListFrame.java +++ b/java/src/jmri/jmrix/maple/assignment/ListFrame.java @@ -57,7 +57,7 @@ public class ListFrame extends jmri.util.JmriJFrame { ButtonGroup bitTypeGroup = new ButtonGroup(); JRadioButton inputBits = new JRadioButton(Bundle.getMessage("ShowInputButton") + " ", false); JRadioButton outputBits = new JRadioButton(Bundle.getMessage("ShowOutputButton"), true); - JLabel nodeInfoText = new JLabel("Node Information Text"); + JLabel nodeInfoText = new JLabel(Bundle.getMessage("NodeInfoText")); // assignment pane items protected JPanel assignmentPanel = null; @@ -257,7 +257,7 @@ public void displayNodeInfo(String nodeID) { } if (s == null) { // serious trouble, log error and ignore - log.error("Cannot find Node " + nodeID + " in list of configured Nodes."); + log.error("Cannot find Node {} in list of configured Nodes.", nodeID); return; } // have node, initialize for new node @@ -267,8 +267,7 @@ public void displayNodeInfo(String nodeID) { // prepare the information line numInputBits = InputBits.getNumInputBits(); numOutputBits = OutputBits.getNumOutputBits(); - nodeInfoText.setText(" - " + numInputBits + " " + Bundle.getMessage("InputBitsAnd") + " " - + numOutputBits + " " + Bundle.getMessage("OutputBits")); + nodeInfoText.setText(" - " + Bundle.getMessage("BitsInfoText", numInputBits, numOutputBits)); } // initialize for input or output assignments if (inputSelected) { diff --git a/java/src/jmri/jmrix/maple/nodeconfig/NodeConfigFrame.java b/java/src/jmri/jmrix/maple/nodeconfig/NodeConfigFrame.java index 3dd2ca3b1c6..3b5a1e4480c 100644 --- a/java/src/jmri/jmrix/maple/nodeconfig/NodeConfigFrame.java +++ b/java/src/jmri/jmrix/maple/nodeconfig/NodeConfigFrame.java @@ -531,7 +531,7 @@ private void resetNotes2() { * Read node address and check for legal range. * * @return a node address in the range 1-99 if successful. If not, -1 is returned and an - * appropriate error message is placed in statusText1. + * appropriate error message is placed in statusText1 */ private int readNodeAddress() { int addr = -1; @@ -559,7 +559,7 @@ private int readNodeAddress() { * If an error is detected, a suitable error message is placed * in the Notes area. * - * @return 'true' if successful, 'false' if an error was detected. + * @return 'true' if successful, 'false' if an error was detected */ protected boolean readPollTimeout() { // get the timeout time @@ -598,7 +598,7 @@ protected boolean readPollTimeout() { * If an error is detected, a suitable error message * is placed in the Notes area. * - * @return 'true' if successful, 'false' if an error was detected. + * @return 'true' if successful, 'false' if an error was detected */ protected boolean readSendDelay() { // get the timeout time @@ -637,7 +637,7 @@ protected boolean readSendDelay() { * If an error is detected, a suitable error message is * placed in the Notes area. * - * @return 'true' if successful, 'false' if an error was detected. + * @return 'true' if successful, 'false' if an error was detected */ protected boolean readNumInputBits() { // get the input bits @@ -676,7 +676,7 @@ protected boolean readNumInputBits() { * If an error is detected, a suitable error message is placed * in the Notes area. * - * @return 'true' if successful, 'false' if an error was detected. + * @return 'true' if successful, 'false' if an error was detected */ protected boolean readNumOutputBits() { // get the output bits @@ -715,7 +715,7 @@ protected boolean readNumOutputBits() { // * If an error is detected, a suitable error message is placed in the // * Notes area. // * -// * @return 'true' if successful, 'false' if an error was detected. +// * @return 'true' if successful, 'false' if an error was detected // */ // protected boolean readPulseWidth() { // // get the pulse width diff --git a/java/src/jmri/jmrix/maple/packetgen/SerialPacketGenFrame.java b/java/src/jmri/jmrix/maple/packetgen/SerialPacketGenFrame.java index 04b3009d9bc..9b6fc15fc42 100644 --- a/java/src/jmri/jmrix/maple/packetgen/SerialPacketGenFrame.java +++ b/java/src/jmri/jmrix/maple/packetgen/SerialPacketGenFrame.java @@ -13,7 +13,7 @@ import jmri.util.StringUtil; /** - * Frame for user input of serial messages + * Frame for user input of serial messages. * * @author Bob Jacobsen Copyright (C) 2002, 2003 */ @@ -26,7 +26,7 @@ public class SerialPacketGenFrame extends jmri.util.JmriJFrame implements jmri.j javax.swing.JButton sendButton = new javax.swing.JButton(); javax.swing.JTextField packetTextField = new javax.swing.JTextField(12); - javax.swing.JButton pollButton = new javax.swing.JButton("Send poll"); // TODO I18N using jmrix.Bundle, cf secsi + javax.swing.JButton pollButton = new javax.swing.JButton("Send poll"); // I18N using jmrix.Bundle javax.swing.JTextField uaAddrField = new javax.swing.JTextField(5); public SerialPacketGenFrame(MapleSystemConnectionMemo _memo) { @@ -41,22 +41,22 @@ public SerialPacketGenFrame(MapleSystemConnectionMemo _memo) { public void initComponents() { // the following code sets the frame's initial state - jLabel1.setText("Command:"); + jLabel1.setText(Bundle.getMessage("CommandLabel")); jLabel1.setVisible(true); - sendButton.setText("Send"); + sendButton.setText(Bundle.getMessage("ButtonSend")); sendButton.setVisible(true); - sendButton.setToolTipText("Send packet"); + sendButton.setToolTipText(Bundle.getMessage("TooltipSendPacket")); packetTextField.setText(""); - packetTextField.setToolTipText("Enter command as hexadecimal bytes separated by a space"); + packetTextField.setToolTipText(Bundle.getMessage("EnterHexToolTip")); packetTextField.setMaximumSize( new Dimension(packetTextField.getMaximumSize().width, packetTextField.getPreferredSize().height ) ); - setTitle("Send Maple serial command"); + setTitle(Bundle.getMessage("SendXCommandTitle", "Maple")); getContentPane().setLayout(new BoxLayout(getContentPane(), BoxLayout.Y_AXIS)); getContentPane().add(jLabel1); @@ -75,11 +75,11 @@ public void actionPerformed(java.awt.event.ActionEvent e) { // add poll message buttons JPanel pane3 = new JPanel(); pane3.setLayout(new FlowLayout()); - pane3.add(new JLabel("UA:")); + pane3.add(new JLabel(Bundle.getMessage("LabelNodeAddress"))); pane3.add(uaAddrField); pane3.add(pollButton); uaAddrField.setText("0"); - uaAddrField.setToolTipText("Enter node address (decimal integer)"); + uaAddrField.setToolTipText(Bundle.getMessage("TooltipNodeAddress")); getContentPane().add(pane3); pollButton.addActionListener(new java.awt.event.ActionListener() { @@ -88,7 +88,7 @@ public void actionPerformed(java.awt.event.ActionEvent e) { pollButtonActionPerformed(e); } }); - pollButton.setToolTipText("Send poll request (first command only, if multiple commands)"); + pollButton.setToolTipText(Bundle.getMessage("PollToolTipMulti")); // pack for display pack(); @@ -135,4 +135,5 @@ public void message(SerialMessage m) { @Override public void reply(SerialReply r) { } + } diff --git a/java/src/jmri/jmrix/maple/serialdriver/configurexml/ConnectionConfigXml.java b/java/src/jmri/jmrix/maple/serialdriver/configurexml/ConnectionConfigXml.java index 95aec5dee23..998d96ba828 100644 --- a/java/src/jmri/jmrix/maple/serialdriver/configurexml/ConnectionConfigXml.java +++ b/java/src/jmri/jmrix/maple/serialdriver/configurexml/ConnectionConfigXml.java @@ -32,7 +32,7 @@ public ConnectionConfigXml() { } /** - * Write out the SerialNode objects too + * Write out the SerialNode objects too. * * @param e Element being extended */ diff --git a/java/src/jmri/jmrix/maple/simulator/SimulatorAdapter.java b/java/src/jmri/jmrix/maple/simulator/SimulatorAdapter.java index 952ddc77f2d..a6e54b58ee3 100644 --- a/java/src/jmri/jmrix/maple/simulator/SimulatorAdapter.java +++ b/java/src/jmri/jmrix/maple/simulator/SimulatorAdapter.java @@ -52,7 +52,7 @@ public class SimulatorAdapter extends SerialPortController implements jmri.jmrix * Create a new SimulatorAdapter. */ public SimulatorAdapter() { - super(new MapleSystemConnectionMemo("M", Bundle.getMessage("MapleSimulatorName"))); // pass customized user name + super(new MapleSystemConnectionMemo("K", Bundle.getMessage("MapleSimulatorName"))); // pass customized user name setManufacturer(jmri.jmrix.maple.SerialConnectionTypeList.MAPLE); } @@ -252,7 +252,7 @@ private SerialMessage readMessage() { /** * This is the heart of the simulation. It translates an * incoming SerialMessage into an outgoing SerialReply. - * See {@link jmri.jmrix.maple.SerialMessage#generateReply(SerialMessage)}. + * See {@link jmri.jmrix.maple.SerialMessage}. * * @param msg the message received in the simulated node * @return a single Maple message to confirm the requested operation, or a series @@ -263,69 +263,36 @@ private SerialReply generateReply(SerialMessage msg) { log.debug("Generate Reply to message from node {} (string = {})", msg.getAddress(), msg.toString()); SerialReply reply = new SerialReply(); // reply length is determined by highest byte added - int nodeaddr = msg.getAddress(); // node addres from element(0) - int b1 = msg.getElement(0); // raw hex value from element(0) - int b2 = msg.getElement(1); // bit + state - int b3 = msg.getElement(2); // element(2), must repeat node address - int b4 = msg.getElement(3); // bank + parity - int bank = (b4 & 0xF0) >> 4; // bank # on node, 0 on node initialization - log.debug("Message nodeaddress={} b1={} b2={} b3={} b4={}", nodeaddr, b1, b2, b3, b4); - - if (nodeaddr == 0) { // error - log.debug("general error: coded as: {}", (((b4 & 0x70) << 4) - 1)); - return null; - } + int nodeaddr = msg.getUA(); // node addres from element 1 + 2 + int cmd1 = msg.getElement(3); // command char 1 + int cmd2 = msg.getElement(4); // command char 2 + int n1 = msg.getElement(9) - '0'; // N char 1 + int n2 = msg.getElement(10) - '0'; // N char 2 + log.debug("Message nodeaddress={} cmd1={} cmd2={} n1={} n2={} isPoll {}", nodeaddr, cmd1, cmd2, n1, n2, msg.isPoll()); + + if (msg.isPoll()) { + int i = 1; + log.debug("general poll message detected"); + // init reply + log.debug("start init of node {}", nodeaddr); + reply.setElement(0, 0x02); + reply.setElement(1, msg.getElement(1)); + reply.setElement(2, msg.getElement(2)); + reply.setElement(3, 'R'); + reply.setElement(4, 'C'); + //for (i = 1; i < (10 * n1 + n2); i++) { // combine n1, n2 + reply.setElement(i + 4, 0x00); // report state of each requested coil + //} + reply.setElement(i + 5, 0x03); + reply = setChecksum(reply, i + 6); + } else { + // TODO more message replies - switch (b2) { - - case 119: - log.debug("get software version (poll) message detected"); - // 2 byte software version number reply - reply.setElement(0, nodeaddr | 0x80); - reply.setElement(1, 9); // pretend version "9" - // no parity - break; - - case 0x71 : - log.debug("init node message 1 detected - ASD sensors"); - // init reply as set in prefs autoInit - if (autoInit > 0) { // not disabled - log.debug("start init 1 of node {}", nodeaddr); - NodeResponse(nodeaddr, 1, 1, autoInit); // banks 1-4 - } - // all replies are generated and sent by NodeResponse() - reply = null; - break; - - case 0x73: //(b2 == 0x70) && ((b4 & 0xF0) == 0x10) - log.debug("init node message 2 detected - parallel sensors"); - // init reply as set in prefs autoInit - if (autoInit > 0) { // not disabled - log.debug("start init 2 of node {}", nodeaddr); - NodeResponse(nodeaddr, 5, 5, autoInit); // bank 5 = parallel - } - // all replies are generated and sent by NodeResponse() - reply = null; - break; - - default: - if (bank == 0x6) { // this is the rename command, with element 2 = new node number - JOptionPane.showMessageDialog(null, - Bundle.getMessage("RenumberSupport"), - Bundle.getMessage("MessageTitle"), - JOptionPane.ERROR_MESSAGE); - log.debug("rename command not supported, old address: {}, new address: {}, bank: {}", - nodeaddr, b2, bank); - } else { - log.debug("echo normal command, node {} bank {} ignored", nodeaddr, bank); - reply = null; // ignore all other messages - // alternatavely, send a 4 byte general reply: - // reply.setElement(0, (nodeaddr | 0x80)); - // reply.setElement(1, (b2 & 0xFF)); // normally: bit + state - // reply.setElement(2, (nodeaddr | 0x80)); - // reply.setElement(3, (bank << 4)); // 0 = error, bank 1..3 for signals, 4..5 sensors (and parity) - // reply = setParity(reply, 0); - } + log.debug("command ignored"); + reply = null; // ignore all other messages + // alternatively, send a 12 byte general reply: + // reply.setElement(0, (nodeaddr)); + // reply = setChecksum(reply, 12); } log.debug(reply == null ? "Message ignored" : "Reply generated " + reply.toString()); return (reply); @@ -359,43 +326,55 @@ private void writeReply(SerialReply r) { *

* Only used in the Receive thread. * - * @return filled message, only when the message is complete. - * @throws IOException when presented by the input source. + * @return filled message, only when the message is complete + * @throws IOException when presented by the input source */ private SerialMessage loadChars() throws java.io.IOException { - int nchars; - byte[] rcvBuffer = new byte[32]; - - nchars = inpipe.read(rcvBuffer, 0, 32); - //log.debug("new message received"); - SerialMessage msg = new SerialMessage(nchars); - - for (int i = 0; i < nchars; i++) { - msg.setElement(i, rcvBuffer[i] & 0xFF); - } + SerialReply reply = new SerialReply(); + ((MapleSystemConnectionMemo) getSystemConnectionMemo()).getTrafficController().loadChars(reply, inpipe); + + // copy received "reply" to a Maple message of known length + SerialMessage msg = new SerialMessage(reply.getNumDataElements()); + for (int i = 0; i < msg.getNumDataElements(); i++) { + //log.debug("" + reply.getElement(i)); + msg.setElement(i, reply.getElement(i)); + } + log.debug("new message received"); return msg; } /** - * Set parity on simulated Maple Node reply. - * Code copied from {@link SerialMessage#setParity(int)} + * Set checksum on simulated Maple Node reply. + * Code copied from {@link SerialMessage#setChecksum(int)} * * @param r the SerialReply to complete * @param start bit index to start * @return SerialReply with parity set */ - public SerialReply setParity(SerialReply r, int start) { - // nibble sum method - int sum = r.getElement(0 + start) & 0x0F; - sum += (r.getElement(0 + start) & 0x70) >> 4; - sum += (r.getElement(1 + start) * 2) & 0x0F; - sum += ((r.getElement(1 + start) * 2) & 0xF0) >> 4; - sum += (r.getElement(3 + start) & 0x70) >> 4; - //log.debug("PPPParity element read: {}", - // Integer.toHexString(r.getElement(3 + start) & 0x70)); - int parity = 16 - (sum & 0xF); - - r.setElement(3 + start, (r.getElement(3 + start) & 0xF0) | (parity & 0xF)); + public SerialReply setChecksum(SerialReply r, int index) { + int sum = 0; + for (int i = 1; i < index; i++) { + sum += r.getElement(i); + } + sum = sum & 0xFF; + + char firstChar; + int firstVal = (sum / 16) & 0xF; + if (firstVal > 9) { + firstChar = (char) ('A' - 10 + firstVal); + } else { + firstChar = (char) ('0' + firstVal); + } + r.setElement(index, firstChar); + + char secondChar; + int secondVal = sum & 0xf; + if (secondVal > 9) { + secondChar = (char) ('A' - 10 + secondVal); + } else { + secondChar = (char) ('0' + secondVal); + } + r.setElement(index + 1, secondChar); return r; } @@ -403,86 +382,6 @@ public SerialReply setParity(SerialReply r, int start) { int SensorBankSize = 64; // theoretically: 0x3F javax.swing.Timer timer; - /** - * Pretend a node init reply for a range of banks and bits. Is this a proper simulation of hardware? - *

- * Based on information in {@link jmri.jmrix.maple.SerialMessage#staticFormat(int, int, int, int)}. - * - * @param node the node address - * @param startBank first bank id to report - * @param endBank last bank id to report - * @param initBits number of inputs/output bits to report - */ - private void NodeResponse(int node, int startBank, int endBank, int initBits) { - if (node < 1 || node > 127) { // node address invalid - log.warn("Invalid Node Address; no response generated"); - return; - } - if (initBits > 1) { // leave at max when 1 - SignalBankSize = 4; // only first 4 signal bits reporting - SensorBankSize = 4; // only first 4 sensor bits reporting - } - int b1 = -1; - int b2 = -1; - int b3 = -1; - int b4 = -1; - - SerialReply nReply = new SerialReply(); // reply length is determined by highest byte added - nReply.setElement(0, node | 0x80); - nReply.setElement(2, node | 0x80); - - for (int k = startBank; k <= endBank; k++) { // bank - if (k <= 3) { // bank 1 to 3, signals - nReply.setElement(3, (k << 4)); // bank (bit 1234): 1-3 = signals - log.debug("element 3 set to 0x{} - {}", (k << 4) & 0x70, Integer.toBinaryString((k << 4) & 0x70)); - - for (int j = 1; j < SignalBankSize; j++) { // bits, send state of each signal bit (banks 1, 2, 3) - log.debug("Sending signal state of node {}, bank {}, bit {}", node, k, j); - nReply.setElement(1, ((j << 3) | 0x6) & 0x7F); // bit id (bits 2345) + state (bits 678): set to Red - - nReply = setParity(nReply, 0); - writeReply(nReply); - // check - b1 = nReply.getElement(0) & 0x7F; // raw hex value from element(0) - b2 = nReply.getElement(1) & 0x7F; // bit + state - b3 = nReply.getElement(2) & 0x7F; // element(2), repeat node address - b4 = nReply.getElement(3) & 0xFF; // bank + parity - if (b1 != b3) { - log.error("Address mismatch on node {} bank {} bit {}", node, k, j); - } - log.debug("Reply written for node {} bank {} bit {}: b1= {} b2={} b3={} b4={}", node, k, j, b1, b2, b3, b4); - log.debug("Reply as hex: {} {} {} {}", Integer.toHexString(b1), - Integer.toHexString(b2), Integer.toHexString(b3), Integer.toHexString(b4)); - log.debug("Reply as bin: {} - {} - {} - {}", Integer.toBinaryString(b1), - Integer.toBinaryString(b2), Integer.toBinaryString(b3), Integer.toBinaryString(b4)); - } - } else { // bank 4 and 5, sensors - nReply.setElement(3, (k << 4)); // bank (bit 1234): 4-5 = sensors - log.debug("element 3 set to 0x{} - {}", (k << 4) & 0x70, Integer.toBinaryString((k << 4) & 0x70)); - - for (int j = 1; j < SensorBankSize; j++) { // bits, send state of each sensor bit (banks 4, 5) - log.debug("Sending sensor state of node {}, bank {}, bit {}", node, k, j); - nReply.setElement(1, ((j << 1) | 0x1) & 0x7F); // bit id (bits 234567) + state (bit 8): inactive - - nReply = setParity(nReply,0); - writeReply(nReply); - // check - b1 = nReply.getElement(0) & 0x7F; // raw hex value from element(0) - b2 = nReply.getElement(1) & 0x7F; // bit + state - b3 = nReply.getElement(2) & 0x7F; // element(2), repeat node address - b4 = nReply.getElement(3) & 0xFF; // bank + parity - if (b1 != b3) { - log.error("Address mismatch on node {} bank {} bit {}", node, k, j); - } - log.debug("Reply written for node {} bank {} bit {}: b1= {} b2={} b3={} b4={}", node, k, j, b1, b2, b3, b4); - log.debug("Reply as hex: {} {} {} {}", Integer.toHexString(b1), - Integer.toHexString(b2), Integer.toHexString(b3), Integer.toHexString(b4)); - log.debug("Reply as bin: {} - {} - {} - {}", Integer.toBinaryString(b1), - Integer.toBinaryString(b2), Integer.toBinaryString(b3), Integer.toBinaryString(b4)); } - } - } - } - // streams to share with user class private DataOutputStream pout = null; // this is provided to classes who want to write to us private DataInputStream pin = null; // this is provided to classes who want data from us diff --git a/java/src/jmri/jmrix/maple/simulator/configurexml/ConnectionConfigXml.java b/java/src/jmri/jmrix/maple/simulator/configurexml/ConnectionConfigXml.java index f727988ecd7..82b8d2dca57 100644 --- a/java/src/jmri/jmrix/maple/simulator/configurexml/ConnectionConfigXml.java +++ b/java/src/jmri/jmrix/maple/simulator/configurexml/ConnectionConfigXml.java @@ -2,11 +2,13 @@ import java.util.List; import jmri.jmrix.configurexml.AbstractSerialConnectionConfigXml; +import jmri.jmrix.maple.InputBits; +import jmri.jmrix.maple.MapleSystemConnectionMemo; +import jmri.jmrix.maple.OutputBits; import jmri.jmrix.maple.SerialNode; import jmri.jmrix.maple.SerialTrafficController; import jmri.jmrix.maple.simulator.ConnectionConfig; import jmri.jmrix.maple.simulator.SimulatorAdapter; -import jmri.jmrix.maple.MapleSystemConnectionMemo; import org.jdom2.Element; /** @@ -43,6 +45,11 @@ protected void extendElement(Element e) { Element n = new Element("node"); n.setAttribute("name", "" + node.getNodeAddress()); e.addContent(n); + // add parameters to the node as needed + n.addContent(makeParameter("transmissiondelay", "" + InputBits.getTimeoutTime())); + n.addContent(makeParameter("inputbits", "" + InputBits.getNumInputBits())); + n.addContent(makeParameter("senddelay", "" + OutputBits.getSendDelay())); + n.addContent(makeParameter("outputbits", "" + OutputBits.getNumOutputBits())); // look for the next node node = (SerialNode) ((MapleSystemConnectionMemo)adapter.getSystemConnectionMemo()).getTrafficController().getNode(index); @@ -75,12 +82,18 @@ protected void unpackElement(Element shared, Element perNode) { for (int i = 0; i < l.size(); i++) { Element n = l.get(i); int addr = Integer.parseInt(n.getAttributeValue("name")); - int type = Integer.parseInt(findParmValue(n, "nodetype")); + int delay = Integer.parseInt(findParmValue(n, "transmissiondelay")); + int senddelay = Integer.parseInt(findParmValue(n, "senddelay")); + int numinput = Integer.parseInt(findParmValue(n, "inputbits")); + int numoutput = Integer.parseInt(findParmValue(n, "outputbits")); SerialTrafficController tc = ((MapleSystemConnectionMemo) adapter.getSystemConnectionMemo()).getTrafficController(); - // create node (they register themselves) - SerialNode node = new SerialNode(addr, type, tc); + SerialNode node = new SerialNode(addr, 0, tc); + InputBits.setTimeoutTime(delay); + InputBits.setNumInputBits(numinput); + OutputBits.setSendDelay(senddelay); + OutputBits.setNumOutputBits(numoutput); // Trigger initialization of this Node to reflect these parameters tc.initializeSerialNode(node); From 8b6927e1314e0df02b4e76d654086e0bf01b8fa6 Mon Sep 17 00:00:00 2001 From: Bob Jacobsen Date: Wed, 4 Apr 2018 08:30:02 -0700 Subject: [PATCH 10/58] fix leak of Graphics objects --- java/src/jmri/util/swing/ButtonSwatchColorChooserPanel.java | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/java/src/jmri/util/swing/ButtonSwatchColorChooserPanel.java b/java/src/jmri/util/swing/ButtonSwatchColorChooserPanel.java index 5474b27717e..a30d6f4ec87 100644 --- a/java/src/jmri/util/swing/ButtonSwatchColorChooserPanel.java +++ b/java/src/jmri/util/swing/ButtonSwatchColorChooserPanel.java @@ -41,6 +41,7 @@ public void updateChooser(){ g.drawRect(0, 0, ICON_DIMENSION - 1, ICON_DIMENSION - 1); ImageIcon icon = new ImageIcon(image); + g.dispose(); swatch.setIcon(icon); } @@ -56,8 +57,11 @@ protected void buildChooser(){ g.fillRect(0, 0, ICON_DIMENSION, ICON_DIMENSION); ImageIcon icon = new ImageIcon(image); + g.dispose(); + swatch = new JLabel(icon); add(swatch); + setButton = new JButton(Bundle.getMessage("SetColor")); setButton.addActionListener((ActionEvent e) -> { Color desiredColor = JColorChooser.showDialog(this, From d3484b91891160ec2dc6840355bfbace8fb03c48 Mon Sep 17 00:00:00 2001 From: Egbert Broerse Date: Wed, 4 Apr 2018 22:16:33 +0200 Subject: [PATCH 11/58] complete poll reply, i18n, JSpinner for node selection --- .../maple/nodeconfig/NodeConfigFrame.java | 100 ++++++++---------- .../maple/packetgen/SerialPacketGenFrame.java | 32 +++--- .../maple/simulator/SimulatorAdapter.java | 79 ++++++++------ 3 files changed, 111 insertions(+), 100 deletions(-) diff --git a/java/src/jmri/jmrix/maple/nodeconfig/NodeConfigFrame.java b/java/src/jmri/jmrix/maple/nodeconfig/NodeConfigFrame.java index 3b5a1e4480c..afab7181292 100644 --- a/java/src/jmri/jmrix/maple/nodeconfig/NodeConfigFrame.java +++ b/java/src/jmri/jmrix/maple/nodeconfig/NodeConfigFrame.java @@ -4,8 +4,13 @@ import java.awt.FlowLayout; import javax.swing.BorderFactory; import javax.swing.BoxLayout; +import javax.swing.JButton; import javax.swing.JLabel; +import javax.swing.JOptionPane; import javax.swing.JPanel; +import javax.swing.JSpinner; +import javax.swing.JTextField; +import javax.swing.SpinnerNumberModel; import javax.swing.border.Border; import jmri.jmrix.maple.InputBits; import jmri.jmrix.maple.MapleSystemConnectionMemo; @@ -24,27 +29,27 @@ */ public class NodeConfigFrame extends jmri.util.JmriJFrame { - protected javax.swing.JTextField nodeAddrField = new javax.swing.JTextField(3); - protected javax.swing.JLabel nodeAddrStatic = new javax.swing.JLabel("000"); - protected javax.swing.JTextField pollTimeoutField = new javax.swing.JTextField(3); - protected javax.swing.JTextField sendDelayField = new javax.swing.JTextField(3); -// protected javax.swing.JTextField pulseWidthField = new javax.swing.JTextField(4); - protected javax.swing.JTextField numInputField = new javax.swing.JTextField(4); - protected javax.swing.JTextField numOutputField = new javax.swing.JTextField(4); + protected JSpinner nodeAddrSpinner; + protected JLabel nodeAddrStatic = new JLabel("000"); + protected JTextField pollTimeoutField = new JTextField(3); + protected JTextField sendDelayField = new JTextField(3); +// protected JTextField pulseWidthField = new JTextField(4); + protected JTextField numInputField = new JTextField(4); + protected JTextField numOutputField = new JTextField(4); - protected javax.swing.JButton addButton = new javax.swing.JButton(Bundle.getMessage("ButtonAdd")); - protected javax.swing.JButton editButton = new javax.swing.JButton(Bundle.getMessage("ButtonEdit")); - protected javax.swing.JButton deleteButton = new javax.swing.JButton(Bundle.getMessage("ButtonDelete")); - protected javax.swing.JButton doneButton = new javax.swing.JButton(Bundle.getMessage("ButtonDone")); - protected javax.swing.JButton updateButton = new javax.swing.JButton(Bundle.getMessage("ButtonUpdate")); - protected javax.swing.JButton cancelButton = new javax.swing.JButton(Bundle.getMessage("ButtonCancel")); + protected JButton addButton = new JButton(Bundle.getMessage("ButtonAdd")); + protected JButton editButton = new JButton(Bundle.getMessage("ButtonEdit")); + protected JButton deleteButton = new JButton(Bundle.getMessage("ButtonDelete")); + protected JButton doneButton = new JButton(Bundle.getMessage("ButtonDone")); + protected JButton updateButton = new JButton(Bundle.getMessage("ButtonUpdate")); + protected JButton cancelButton = new JButton(Bundle.getMessage("ButtonCancel")); - protected javax.swing.JLabel statusText1 = new javax.swing.JLabel(); - protected javax.swing.JLabel statusText2 = new javax.swing.JLabel(); - protected javax.swing.JLabel statusText3 = new javax.swing.JLabel(); + protected JLabel statusText1 = new JLabel(); + protected JLabel statusText2 = new JLabel(); + protected JLabel statusText3 = new JLabel(); - protected javax.swing.JPanel panel2 = new JPanel(); - protected javax.swing.JPanel panel2a = new JPanel(); + protected JPanel panel2 = new JPanel(); + protected JPanel panel2a = new JPanel(); protected boolean changedNode = false; // true if a node was changed, deleted, or added protected boolean editMode = false; // true if in edit mode @@ -98,9 +103,9 @@ public void initComponents() { JPanel panel11 = new JPanel(); panel11.setLayout(new FlowLayout()); panel11.add(new JLabel(Bundle.getMessage("LabelNodeAddress") + " ")); - panel11.add(nodeAddrField); - nodeAddrField.setToolTipText(Bundle.getMessage("TipNodeAddress")); - nodeAddrField.setText("1"); + nodeAddrSpinner = new JSpinner(new SpinnerNumberModel(1, 1, 99, 1)); + panel11.add(nodeAddrSpinner); + nodeAddrSpinner.setToolTipText(Bundle.getMessage("TipNodeAddress")); panel11.add(nodeAddrStatic); nodeAddrStatic.setVisible(false); JPanel panel12 = new JPanel(); @@ -248,7 +253,7 @@ public void actionPerformed(java.awt.event.ActionEvent e) { } /** - * Handle Add button + * Handle Add button. */ public void addButtonActionPerformed() { // Check that a node with this address does not exist @@ -295,7 +300,7 @@ public void addButtonActionPerformed() { } /** - * Handle Edit button + * Handle Edit button. */ public void editButtonActionPerformed() { // Find Serial Node address @@ -314,7 +319,7 @@ public void editButtonActionPerformed() { } // Set up static node address nodeAddrStatic.setText(Integer.toString(nodeAddress)); - nodeAddrField.setVisible(false); + nodeAddrSpinner.setVisible(false); nodeAddrStatic.setVisible(true); // set up pulse width // pulseWidth = curNode.getPulseWidth(); @@ -344,7 +349,7 @@ public void editButtonActionPerformed() { } /** - * Handle Delete button + * Handle Delete button. */ public void deleteButtonActionPerformed() { // Find Serial Node address @@ -362,11 +367,11 @@ public void deleteButtonActionPerformed() { return; } // confirm deletion with the user - if (javax.swing.JOptionPane.OK_OPTION == javax.swing.JOptionPane.showConfirmDialog( + if (JOptionPane.OK_OPTION == JOptionPane.showConfirmDialog( this, Bundle.getMessage("ConfirmDelete1") + " " + nodeAddress + "?", Bundle.getMessage("ConfirmDeleteTitle"), - javax.swing.JOptionPane.OK_CANCEL_OPTION, - javax.swing.JOptionPane.WARNING_MESSAGE)) { + JOptionPane.OK_CANCEL_OPTION, + JOptionPane.WARNING_MESSAGE)) { // delete this node _memo.getTrafficController().deleteNode(nodeAddress); // provide user feedback @@ -382,7 +387,7 @@ public void deleteButtonActionPerformed() { } /** - * Handle Done button + * Handle Done button. */ public void doneButtonActionPerformed() { if (editMode) { @@ -396,22 +401,22 @@ public void doneButtonActionPerformed() { doneButton.setVisible(true); updateButton.setVisible(false); cancelButton.setVisible(false); - nodeAddrField.setVisible(true); + nodeAddrSpinner.setVisible(true); nodeAddrStatic.setVisible(false); } if (changedNode) { // Remind user to Save new configuration - javax.swing.JOptionPane.showMessageDialog(this, + JOptionPane.showMessageDialog(this, Bundle.getMessage("ReminderNode1") + "\n" + Bundle.getMessage("Reminder2"), Bundle.getMessage("ReminderTitle"), - javax.swing.JOptionPane.INFORMATION_MESSAGE); + JOptionPane.INFORMATION_MESSAGE); } setVisible(false); dispose(); } /** - * Handle Update button + * Handle Update button. */ public void updateButtonActionPerformed() { // get node information from window @@ -442,7 +447,7 @@ public void updateButtonActionPerformed() { updateButton.setVisible(false); cancelButton.setVisible(false); // make node address editable again - nodeAddrField.setVisible(true); + nodeAddrSpinner.setVisible(true); nodeAddrStatic.setVisible(false); // refresh notes panel statusText2.setText(stdStatus2); @@ -454,7 +459,7 @@ public void updateButtonActionPerformed() { } /** - * Handle Cancel button + * Handle Cancel button. */ public void cancelButtonActionPerformed() { // Reset @@ -468,7 +473,7 @@ public void cancelButtonActionPerformed() { updateButton.setVisible(false); cancelButton.setVisible(false); // make node address editable again - nodeAddrField.setVisible(true); + nodeAddrSpinner.setVisible(true); nodeAddrStatic.setVisible(false); // refresh notes panel statusText1.setText(stdStatus1); @@ -529,29 +534,12 @@ private void resetNotes2() { /** * Read node address and check for legal range. + * Range is protected by JSpinner, error dialogs removed. * - * @return a node address in the range 1-99 if successful. If not, -1 is returned and an - * appropriate error message is placed in statusText1 + * @return a node address in the range 1-99. */ private int readNodeAddress() { - int addr = -1; - try { - addr = Integer.parseInt(nodeAddrField.getText()); - } catch (Exception e) { - statusText1.setText(Bundle.getMessage("Error5")); - statusText1.setVisible(true); - errorInStatus1 = true; - resetNotes2(); - return -1; - } - if ((addr < 1) || (addr > 99)) { - statusText1.setText(Bundle.getMessage("Error6")); - statusText1.setVisible(true); - errorInStatus1 = true; - resetNotes2(); - return -1; - } - return (addr); + return (Integer) nodeAddrSpinner.getValue(); } /** diff --git a/java/src/jmri/jmrix/maple/packetgen/SerialPacketGenFrame.java b/java/src/jmri/jmrix/maple/packetgen/SerialPacketGenFrame.java index 9b6fc15fc42..25854ce6f64 100644 --- a/java/src/jmri/jmrix/maple/packetgen/SerialPacketGenFrame.java +++ b/java/src/jmri/jmrix/maple/packetgen/SerialPacketGenFrame.java @@ -3,9 +3,13 @@ import java.awt.Dimension; import java.awt.FlowLayout; import javax.swing.BoxLayout; +import javax.swing.JButton; import javax.swing.JLabel; import javax.swing.JPanel; import javax.swing.JSeparator; +import javax.swing.JSpinner; +import javax.swing.JTextField; +import javax.swing.SpinnerNumberModel; import jmri.jmrix.maple.InputBits; import jmri.jmrix.maple.SerialMessage; import jmri.jmrix.maple.SerialReply; @@ -19,19 +23,19 @@ */ public class SerialPacketGenFrame extends jmri.util.JmriJFrame implements jmri.jmrix.maple.SerialListener { - private MapleSystemConnectionMemo memo = null; + private MapleSystemConnectionMemo _memo = null; // member declarations - javax.swing.JLabel jLabel1 = new javax.swing.JLabel(); - javax.swing.JButton sendButton = new javax.swing.JButton(); - javax.swing.JTextField packetTextField = new javax.swing.JTextField(12); + JLabel jLabel1 = new JLabel(); + JButton sendButton = new JButton(); + JTextField packetTextField = new JTextField(12); - javax.swing.JButton pollButton = new javax.swing.JButton("Send poll"); // I18N using jmrix.Bundle - javax.swing.JTextField uaAddrField = new javax.swing.JTextField(5); + JButton pollButton = new JButton(Bundle.getMessage("LabelPoll")); // I18N using jmrix.Bundle + protected JSpinner nodeAddrSpinner; - public SerialPacketGenFrame(MapleSystemConnectionMemo _memo) { + public SerialPacketGenFrame(MapleSystemConnectionMemo memo) { super(); - memo = _memo; + _memo = memo; } /** @@ -76,10 +80,10 @@ public void actionPerformed(java.awt.event.ActionEvent e) { JPanel pane3 = new JPanel(); pane3.setLayout(new FlowLayout()); pane3.add(new JLabel(Bundle.getMessage("LabelNodeAddress"))); - pane3.add(uaAddrField); + nodeAddrSpinner = new JSpinner(new SpinnerNumberModel(1, 1, 99, 1)); + nodeAddrSpinner.setToolTipText(Bundle.getMessage("TooltipNodeAddress")); + pane3.add(nodeAddrSpinner); pane3.add(pollButton); - uaAddrField.setText("0"); - uaAddrField.setToolTipText(Bundle.getMessage("TooltipNodeAddress")); getContentPane().add(pane3); pollButton.addActionListener(new java.awt.event.ActionListener() { @@ -99,12 +103,12 @@ public void pollButtonActionPerformed(java.awt.event.ActionEvent e) { if (endAddr > 99) { endAddr = 99; } - SerialMessage msg = SerialMessage.getPoll(Integer.valueOf(uaAddrField.getText()).intValue(), 1, endAddr); - memo.getTrafficController().sendSerialMessage(msg, this); + SerialMessage msg = SerialMessage.getPoll((Integer) nodeAddrSpinner.getValue(), 1, endAddr); + _memo.getTrafficController().sendSerialMessage(msg, this); } public void sendButtonActionPerformed(java.awt.event.ActionEvent e) { - memo.getTrafficController().sendSerialMessage(createPacket(packetTextField.getText()), this); + _memo.getTrafficController().sendSerialMessage(createPacket(packetTextField.getText()), this); } SerialMessage createPacket(String s) { diff --git a/java/src/jmri/jmrix/maple/simulator/SimulatorAdapter.java b/java/src/jmri/jmrix/maple/simulator/SimulatorAdapter.java index a6e54b58ee3..52fd2038a0c 100644 --- a/java/src/jmri/jmrix/maple/simulator/SimulatorAdapter.java +++ b/java/src/jmri/jmrix/maple/simulator/SimulatorAdapter.java @@ -263,41 +263,60 @@ private SerialReply generateReply(SerialMessage msg) { log.debug("Generate Reply to message from node {} (string = {})", msg.getAddress(), msg.toString()); SerialReply reply = new SerialReply(); // reply length is determined by highest byte added - int nodeaddr = msg.getUA(); // node addres from element 1 + 2 - int cmd1 = msg.getElement(3); // command char 1 - int cmd2 = msg.getElement(4); // command char 2 - int n1 = msg.getElement(9) - '0'; // N char 1 - int n2 = msg.getElement(10) - '0'; // N char 2 - log.debug("Message nodeaddress={} cmd1={} cmd2={} n1={} n2={} isPoll {}", nodeaddr, cmd1, cmd2, n1, n2, msg.isPoll()); - - if (msg.isPoll()) { - int i = 1; - log.debug("general poll message detected"); - // init reply - log.debug("start init of node {}", nodeaddr); - reply.setElement(0, 0x02); - reply.setElement(1, msg.getElement(1)); - reply.setElement(2, msg.getElement(2)); - reply.setElement(3, 'R'); - reply.setElement(4, 'C'); - //for (i = 1; i < (10 * n1 + n2); i++) { // combine n1, n2 - reply.setElement(i + 4, 0x00); // report state of each requested coil - //} - reply.setElement(i + 5, 0x03); - reply = setChecksum(reply, i + 6); - } else { - // TODO more message replies - - log.debug("command ignored"); - reply = null; // ignore all other messages - // alternatively, send a 12 byte general reply: - // reply.setElement(0, (nodeaddr)); - // reply = setChecksum(reply, 12); + int nodeAddress = msg.getUA(); // node addres from element 1 + 2 + //convert hex to character + char cmd1 = (char) msg.getElement(3); // command char 1 + char cmd2 = (char) msg.getElement(4); // command char 2 + + log.debug("Message nodeaddress={} cmd={}{}, Start={}, Num={}", + nodeAddress, cmd1, cmd2, + getStartAddress(msg), getNumberOfCoils(msg)); + + switch ("" + cmd1 + cmd2) { + case "RC": // broadcast Read Coils (poll) message received + log.debug("poll message detected"); + int i = 1; + int lastNode = 1; + if (nodeAddress == 0) { // broadcast poll, reply from all existing nodes + lastNode = 99; + } + // init reply + log.debug("start init of node {}", nodeAddress); + reply.setElement(0, 0x02); + reply.setElement(1, msg.getElement(1)); + reply.setElement(2, msg.getElement(2)); + reply.setElement(3, 'R'); + reply.setElement(4, 'C'); + for (i = 1; i < getNumberOfCoils(msg); i++) { + reply.setElement(i + 4, 0x01); // report state of each requested coil as INactive = 0 + // TODO: echo commanded state from JMRI node-bit using: getCommandedState(nodeAddress * 1000 + getStartAddress(msg) + 1) + } + reply.setElement(i + 5, 0x03); + reply = setChecksum(reply, i + 6); + break; + default: + // TODO other message replies + log.debug("command ignored"); + reply = null; // ignore all other messages } log.debug(reply == null ? "Message ignored" : "Reply generated " + reply.toString()); return (reply); } + private int getStartAddress(SerialMessage msg) { + int a1 = msg.getElement(5) - '0'; // StartAt char 1 + int a2 = msg.getElement(6) - '0'; // StartAt char 2 + int a3 = msg.getElement(7) - '0'; // StartAt char 3 + int a4 = msg.getElement(8) - '0'; // StartAt char 4 + return 1000 * a1 + 100 * a2 + 10 * a3 + a4; // combine a1..a4 + } + + private int getNumberOfCoils(SerialMessage msg) { + int n1 = msg.getElement(9) - '0'; // N char 1 + int n2 = msg.getElement(10) - '0'; // N char 2 + return 10 * n1 + n2; // combine n1, n2 + } + /** * Write reply to output. *

From db6e23bd6453c22de74c17a23eed65c093bb6837 Mon Sep 17 00:00:00 2001 From: Egbert Broerse Date: Wed, 4 Apr 2018 22:31:28 +0200 Subject: [PATCH 12/58] add WC reply, javaDoc --- .../maple/simulator/SimulatorAdapter.java | 28 ++++++++++++------- 1 file changed, 18 insertions(+), 10 deletions(-) diff --git a/java/src/jmri/jmrix/maple/simulator/SimulatorAdapter.java b/java/src/jmri/jmrix/maple/simulator/SimulatorAdapter.java index 52fd2038a0c..b49c94b2a7a 100644 --- a/java/src/jmri/jmrix/maple/simulator/SimulatorAdapter.java +++ b/java/src/jmri/jmrix/maple/simulator/SimulatorAdapter.java @@ -20,10 +20,8 @@ * Currently, the Maple SimulatorAdapter reacts to the following commands sent from the user * interface with an appropriate reply {@link #generateReply(SerialMessage)}: *

    - *
  • Software version (poll) - *
  • Renumber (displays dialog: not supported) - *
  • Node Init (2 replies + user configurable node-bank-bit status) - *
  • Set signal/sensor/turnout (echoes message) + *
  • RC Read Coils (poll), all coil bits 0 + *
  • WC Write Coils (ACK) *
* * Based on jmri.jmrix.lenz.xnetsimulator.XNetSimulatorAdapter / GrapevineSimulatorAdapter 2017 @@ -273,29 +271,39 @@ private SerialReply generateReply(SerialMessage msg) { getStartAddress(msg), getNumberOfCoils(msg)); switch ("" + cmd1 + cmd2) { - case "RC": // broadcast Read Coils (poll) message received - log.debug("poll message detected"); + case "RC": // Read Coils message + log.debug("Read Coils (poll) message detected"); int i = 1; int lastNode = 1; if (nodeAddress == 0) { // broadcast poll, reply from all existing nodes lastNode = 99; } // init reply - log.debug("start init of node {}", nodeAddress); - reply.setElement(0, 0x02); + log.debug("RC Reply from node {}", nodeAddress); + reply.setElement(0, 0x02); // reply.setElement(1, msg.getElement(1)); reply.setElement(2, msg.getElement(2)); reply.setElement(3, 'R'); reply.setElement(4, 'C'); for (i = 1; i < getNumberOfCoils(msg); i++) { - reply.setElement(i + 4, 0x01); // report state of each requested coil as INactive = 0 + reply.setElement(i + 4, 0x00); // report state of each requested coil as Inactive = 0 // TODO: echo commanded state from JMRI node-bit using: getCommandedState(nodeAddress * 1000 + getStartAddress(msg) + 1) } reply.setElement(i + 5, 0x03); reply = setChecksum(reply, i + 6); break; + case "WC": // Write Coils message + log.debug("Write Coils message detected"); + // init reply + log.debug("WC Reply from node {}", nodeAddress); + reply.setElement(0, 0x06); // + reply.setElement(1, msg.getElement(1)); + reply.setElement(2, msg.getElement(2)); + reply.setElement(3, 'W'); + reply.setElement(4, 'C'); + break; default: - // TODO other message replies + // TODO "WC" message replies log.debug("command ignored"); reply = null; // ignore all other messages } From 6f100b682aa26f2a2bcbf0170479325977d9bfe9 Mon Sep 17 00:00:00 2001 From: Egbert Broerse Date: Wed, 4 Apr 2018 22:43:16 +0200 Subject: [PATCH 13/58] Javadoc --- .../jmrix/maple/simulator/SimulatorAdapter.java | 13 +++++++++++++ 1 file changed, 13 insertions(+) diff --git a/java/src/jmri/jmrix/maple/simulator/SimulatorAdapter.java b/java/src/jmri/jmrix/maple/simulator/SimulatorAdapter.java index b49c94b2a7a..67bcdd60fc5 100644 --- a/java/src/jmri/jmrix/maple/simulator/SimulatorAdapter.java +++ b/java/src/jmri/jmrix/maple/simulator/SimulatorAdapter.java @@ -311,6 +311,12 @@ private SerialReply generateReply(SerialMessage msg) { return (reply); } + /** + * Extract start coils from RC/WC message. + * + * @param msg te SerialMessage received from Simulator inpipe + * @return decimal coil ID + */ private int getStartAddress(SerialMessage msg) { int a1 = msg.getElement(5) - '0'; // StartAt char 1 int a2 = msg.getElement(6) - '0'; // StartAt char 2 @@ -319,6 +325,13 @@ private int getStartAddress(SerialMessage msg) { return 1000 * a1 + 100 * a2 + 10 * a3 + a4; // combine a1..a4 } + /** + * Extract the number of coils to precess from RC/WC message. + * + * @param msg te SerialMessage received from Simulator inpipe + * @return the number of consecutive coils to read/write (decimal) + * after starting Coil + */ private int getNumberOfCoils(SerialMessage msg) { int n1 = msg.getElement(9) - '0'; // N char 1 int n2 = msg.getElement(10) - '0'; // N char 2 From 722fd9227162849d7a977aa62b4f6edbe91e174e Mon Sep 17 00:00:00 2001 From: Egbert Broerse Date: Wed, 4 Apr 2018 22:53:01 +0200 Subject: [PATCH 14/58] add tests for sim --- java/test/jmri/jmrix/maple/PackageTest.java | 1 + .../jmrix/maple/simulator/BundleTest.java | 29 ++++++++++++++ .../maple/simulator/ConnectionConfigTest.java | 34 +++++++++++++++++ .../jmrix/maple/simulator/PackageTest.java | 38 +++++++++++++++++++ .../maple/simulator/SimulatorAdapterTest.java | 34 +++++++++++++++++ .../configurexml/ConnectionConfigXmlTest.java | 32 ++++++++++++++++ .../simulator/configurexml/PackageTest.java | 35 +++++++++++++++++ 7 files changed, 203 insertions(+) create mode 100644 java/test/jmri/jmrix/maple/simulator/BundleTest.java create mode 100644 java/test/jmri/jmrix/maple/simulator/ConnectionConfigTest.java create mode 100644 java/test/jmri/jmrix/maple/simulator/PackageTest.java create mode 100644 java/test/jmri/jmrix/maple/simulator/SimulatorAdapterTest.java create mode 100644 java/test/jmri/jmrix/maple/simulator/configurexml/ConnectionConfigXmlTest.java create mode 100644 java/test/jmri/jmrix/maple/simulator/configurexml/PackageTest.java diff --git a/java/test/jmri/jmrix/maple/PackageTest.java b/java/test/jmri/jmrix/maple/PackageTest.java index 91b9e0da36a..c4a3cf996f3 100644 --- a/java/test/jmri/jmrix/maple/PackageTest.java +++ b/java/test/jmri/jmrix/maple/PackageTest.java @@ -30,6 +30,7 @@ SerialSensorTest.class, BundleTest.class, jmri.jmrix.maple.swing.PackageTest.class, + jmri.jmrix.maple.simulator.PackageTest.class }) /** diff --git a/java/test/jmri/jmrix/maple/simulator/BundleTest.java b/java/test/jmri/jmrix/maple/simulator/BundleTest.java new file mode 100644 index 00000000000..eeef2bd751a --- /dev/null +++ b/java/test/jmri/jmrix/maple/simulator/BundleTest.java @@ -0,0 +1,29 @@ +package jmri.jmrix.maple.simulator; + + +import org.junit.Assert; +import org.junit.Test; + +/** + * Tests for the Bundle class + * + * @author Bob Jacobsen Copyright (C) 2012 + */ +public class BundleTest { + + @Test public void testGoodKeys() { + Assert.assertEquals("(none)", Bundle.getMessage("none")); + Assert.assertEquals("No locomotive detected (301);", Bundle.getMessage("NoLocoDetected")); + Assert.assertEquals("Turnout", Bundle.getMessage("BeanNameTurnout")); + } + + @Test public void testBadKey() { + try { + Bundle.getMessage("FFFFFTTTTTTT"); + } catch (java.util.MissingResourceException e) { + return; + } // OK + Assert.fail("No exception thrown"); + } + +} diff --git a/java/test/jmri/jmrix/maple/simulator/ConnectionConfigTest.java b/java/test/jmri/jmrix/maple/simulator/ConnectionConfigTest.java new file mode 100644 index 00000000000..c299aeefed3 --- /dev/null +++ b/java/test/jmri/jmrix/maple/simulator/ConnectionConfigTest.java @@ -0,0 +1,34 @@ +package jmri.jmrix.maple.simulator; + +import jmri.util.JUnitUtil; +import org.junit.After; +import org.junit.Assert; +import org.junit.Before; +import org.junit.Test; + +/** + * Tests for ConnectionConfig class. + * + * @author Paul Bender Copyright (C) 2016 + **/ + +public class ConnectionConfigTest { + + @Test + public void ConstructorTest(){ + Assert.assertNotNull("ConnectionConfig constructor", new ConnectionConfig()); + } + + @Before + public void setUp() { + JUnitUtil.setUp(); + + jmri.util.JUnitUtil.initDefaultUserMessagePreferences(); + } + + @After + public void tearDown(){ + JUnitUtil.tearDown(); + } + +} diff --git a/java/test/jmri/jmrix/maple/simulator/PackageTest.java b/java/test/jmri/jmrix/maple/simulator/PackageTest.java new file mode 100644 index 00000000000..03e930c6d7c --- /dev/null +++ b/java/test/jmri/jmrix/maple/simulator/PackageTest.java @@ -0,0 +1,38 @@ +package jmri.jmrix.maple.simulator; + +import org.junit.runner.RunWith; +import org.junit.runners.Suite; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + + +@RunWith(Suite.class) +@Suite.SuiteClasses({ + ConnectionConfigTest.class, + SimulatorAdapterTest.class, + jmri.jmrix.maple.simulator.configurexml.PackageTest.class, + BundleTest.class, +}) +/** + * Tests for the jmri.jmrix.maple.simulator package. + * + * @author Paul Bender Copyright (C) 2016 + */ +public class PackageTest { + + // Main entry point + static public void main(String[] args) { + org.junit.runner.Result result = org.junit.runner.JUnitCore + .runClasses(PackageTest.class); + for(org.junit.runner.notification.Failure fail: result.getFailures()) { + log.error(fail.toString()); + } + //junit.textui.TestRunner.main(testCaseName); + if (result.wasSuccessful()) { + log.info("Success"); + } + } + + private final static Logger log = LoggerFactory.getLogger(PackageTest.class); + +} diff --git a/java/test/jmri/jmrix/maple/simulator/SimulatorAdapterTest.java b/java/test/jmri/jmrix/maple/simulator/SimulatorAdapterTest.java new file mode 100644 index 00000000000..032402f78e4 --- /dev/null +++ b/java/test/jmri/jmrix/maple/simulator/SimulatorAdapterTest.java @@ -0,0 +1,34 @@ +package jmri.jmrix.maple.simulator; + +import jmri.util.JUnitUtil; +import org.junit.After; +import org.junit.Assert; +import org.junit.Before; +import org.junit.Test; + +/** + * Tests for simulator SimulatorAdapter class. + * + * @author Paul Bender Copyright (C) 2016 + **/ + +public class SimulatorAdapterTest { + + @Test + public void ConstructorTest(){ + Assert.assertNotNull("SimulatorAdapter constructor", new SimulatorAdapter()); + } + + @Before + public void setUp() { + JUnitUtil.setUp(); + + jmri.util.JUnitUtil.initDefaultUserMessagePreferences(); + } + + @After + public void tearDown(){ + JUnitUtil.tearDown(); + } + +} diff --git a/java/test/jmri/jmrix/maple/simulator/configurexml/ConnectionConfigXmlTest.java b/java/test/jmri/jmrix/maple/simulator/configurexml/ConnectionConfigXmlTest.java new file mode 100644 index 00000000000..12dae67736d --- /dev/null +++ b/java/test/jmri/jmrix/maple/simulator/configurexml/ConnectionConfigXmlTest.java @@ -0,0 +1,32 @@ +package jmri.jmrix.maple.simulator.configurexml; + +import jmri.util.JUnitUtil; +import org.junit.After; +import org.junit.Assert; +import org.junit.Before; +import org.junit.Test; + +/** + * Tests for the ConnectionConfigXml class + * + * @author Paul Bender Copyright (C) 2016 + */ +public class ConnectionConfigXmlTest { + + @Test + public void testCtor(){ + Assert.assertNotNull("ConnectionConfigXml constructor", new ConnectionConfigXml()); + } + + // The minimal setup for log4J + @Before + public void setUp() { + JUnitUtil.setUp(); + } + + @After + public void tearDown() { + JUnitUtil.tearDown(); + } + +} diff --git a/java/test/jmri/jmrix/maple/simulator/configurexml/PackageTest.java b/java/test/jmri/jmrix/maple/simulator/configurexml/PackageTest.java new file mode 100644 index 00000000000..ad9c6047d1a --- /dev/null +++ b/java/test/jmri/jmrix/maple/simulator/configurexml/PackageTest.java @@ -0,0 +1,35 @@ +package jmri.jmrix.maple.simulator.configurexml; + +import org.junit.runner.RunWith; +import org.junit.runners.Suite; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + + +@RunWith(Suite.class) +@Suite.SuiteClasses({ + ConnectionConfigXmlTest.class +}) +/** + * Tests for the jmri.jmrix.maple.simulator.configurexml package. + * + * @author Paul Bender Copyright (C) 2016 + */ +public class PackageTest { + + // Main entry point + static public void main(String[] args) { + org.junit.runner.Result result = org.junit.runner.JUnitCore + .runClasses(PackageTest.class); + for(org.junit.runner.notification.Failure fail: result.getFailures()) { + log.error(fail.toString()); + } + //junit.textui.TestRunner.main(testCaseName); + if (result.wasSuccessful()) { + log.info("Success"); + } + } + + private final static Logger log = LoggerFactory.getLogger(PackageTest.class); + +} From c2cea93326bffad07fbcc7e9c28d48cca30c0fcf Mon Sep 17 00:00:00 2001 From: Paul Bender Date: Wed, 4 Apr 2018 17:27:52 -0400 Subject: [PATCH 15/58] missed adding After import --- .../jmri/jmrit/display/controlPanelEditor/PortalIconTest.java | 1 + 1 file changed, 1 insertion(+) diff --git a/java/test/jmri/jmrit/display/controlPanelEditor/PortalIconTest.java b/java/test/jmri/jmrit/display/controlPanelEditor/PortalIconTest.java index c5d76a573ad..6d0380f136a 100644 --- a/java/test/jmri/jmrit/display/controlPanelEditor/PortalIconTest.java +++ b/java/test/jmri/jmrit/display/controlPanelEditor/PortalIconTest.java @@ -3,6 +3,7 @@ import java.awt.GraphicsEnvironment; import jmri.util.JUnitUtil; import jmri.jmrit.display.PositionableIconTest; +import org.junit.After; import org.junit.Assert; import org.junit.Assume; import org.junit.Before; From 203daae9543e752fdf372b576de2b7aecc28fe3a Mon Sep 17 00:00:00 2001 From: Egbert Broerse Date: Thu, 5 Apr 2018 09:16:45 +0200 Subject: [PATCH 16/58] fix Javadoc param --- java/src/jmri/jmrix/maple/simulator/SimulatorAdapter.java | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/java/src/jmri/jmrix/maple/simulator/SimulatorAdapter.java b/java/src/jmri/jmrix/maple/simulator/SimulatorAdapter.java index 67bcdd60fc5..ede99e85066 100644 --- a/java/src/jmri/jmrix/maple/simulator/SimulatorAdapter.java +++ b/java/src/jmri/jmrix/maple/simulator/SimulatorAdapter.java @@ -388,7 +388,7 @@ private SerialMessage loadChars() throws java.io.IOException { * Code copied from {@link SerialMessage#setChecksum(int)} * * @param r the SerialReply to complete - * @param start bit index to start + * @param index element index to place 2 checksum bytes * @return SerialReply with parity set */ public SerialReply setChecksum(SerialReply r, int index) { From d883e2147fa7a5d74a62d083c88d3f493daecaba Mon Sep 17 00:00:00 2001 From: Paul Bender Date: Thu, 5 Apr 2018 08:32:50 -0400 Subject: [PATCH 17/58] set proper memo --- java/test/jmri/jmrix/openlcb/OlcbSignalMastTest.java | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/java/test/jmri/jmrix/openlcb/OlcbSignalMastTest.java b/java/test/jmri/jmrix/openlcb/OlcbSignalMastTest.java index 5a7227ceb49..5661ed8b3b3 100644 --- a/java/test/jmri/jmrix/openlcb/OlcbSignalMastTest.java +++ b/java/test/jmri/jmrix/openlcb/OlcbSignalMastTest.java @@ -19,8 +19,10 @@ import org.openlcb.IdentifyEventsMessage; import org.junit.After; +import org.junit.AfterClass; import org.junit.Assert; import org.junit.Before; +import org.junit.BeforeClass; import org.junit.Test; /** @@ -314,7 +316,7 @@ public void put(Message msg, Connection sender) { } }; - OlcbSystemConnectionMemo memo = new OlcbSystemConnectionMemo(); // this self-registers as 'M' + memo = new OlcbSystemConnectionMemo(); // this self-registers as 'M' memo.setProtocol(jmri.jmrix.can.ConfigurationManager.OPENLCB); memo.setInterface(new OlcbInterface(nodeID, connection) { public Connection getOutputConnection() { From 132c9957841d3356d7d12a250b8bd82ee92b93b2 Mon Sep 17 00:00:00 2001 From: Egbert Broerse Date: Fri, 6 Apr 2018 00:37:49 +0200 Subject: [PATCH 18/58] migrate Direct connection, use address in ThrottleManager, i18n, menu disabled --- java/src/jmri/jmrix/AbstractThrottle.java | 2 +- .../jmri/jmrix/AbstractThrottleManager.java | 4 +- java/src/jmri/jmrix/JmrixBundle.properties | 2 + java/src/jmri/jmrix/JmrixBundle_nl.properties | 1 + .../dccpp/DCCppSystemConnectionMemo.java | 1 - java/src/jmri/jmrix/direct/Bundle.java | 111 ++++++++++++++++++ .../jmri/jmrix/direct/DirectBundle.properties | 9 ++ .../jmrix/direct/DirectBundle_nl.properties | 9 ++ .../direct/DirectConnectionTypeList.java | 29 +++++ java/src/jmri/jmrix/direct/DirectMenu.java | 22 ++-- .../direct/DirectSystemConnectionMemo.java | 9 +- java/src/jmri/jmrix/direct/MakePacket.java | 40 +++---- java/src/jmri/jmrix/direct/Message.java | 3 +- .../src/jmri/jmrix/direct/PortController.java | 14 ++- java/src/jmri/jmrix/direct/Throttle.java | 41 +++---- .../jmri/jmrix/direct/ThrottleManager.java | 25 ++-- .../jmri/jmrix/direct/TrafficController.java | 10 +- java/src/jmri/jmrix/direct/serial/Bundle.java | 98 ++++++++++++++++ .../jmrix/direct/serial/ConnectionConfig.java | 7 +- .../direct/serial/SerialDriverAdapter.java | 20 ++-- .../configurexml/ConnectionConfigXml.java | 6 +- .../direct/swing/DirectComponentFactory.java | 2 +- .../sprog/simulator/SimulatorAdapter.java | 2 +- 23 files changed, 366 insertions(+), 101 deletions(-) create mode 100644 java/src/jmri/jmrix/direct/Bundle.java create mode 100644 java/src/jmri/jmrix/direct/DirectBundle.properties create mode 100644 java/src/jmri/jmrix/direct/DirectBundle_nl.properties create mode 100644 java/src/jmri/jmrix/direct/DirectConnectionTypeList.java create mode 100644 java/src/jmri/jmrix/direct/serial/Bundle.java diff --git a/java/src/jmri/jmrix/AbstractThrottle.java b/java/src/jmri/jmrix/AbstractThrottle.java index 2fe4a517300..611742f335d 100644 --- a/java/src/jmri/jmrix/AbstractThrottle.java +++ b/java/src/jmri/jmrix/AbstractThrottle.java @@ -19,7 +19,7 @@ /** * An abstract implementation of DccThrottle. Based on Glen Oberhauser's * original LnThrottleManager implementation. - *

+ *

* Note that this implements DccThrottle, not Throttle directly, so it has some * DCC-specific content. * diff --git a/java/src/jmri/jmrix/AbstractThrottleManager.java b/java/src/jmri/jmrix/AbstractThrottleManager.java index 3f497fc54c5..96808c75e9c 100644 --- a/java/src/jmri/jmrix/AbstractThrottleManager.java +++ b/java/src/jmri/jmrix/AbstractThrottleManager.java @@ -18,11 +18,11 @@ /** * Abstract implementation of a ThrottleManager. - *

+ *

* Based on Glen Oberhauser's original LnThrottleManager implementation. * * @author Bob Jacobsen Copyright (C) 2001 - * @author Steve Rawlinson Copyright (C) 2016 + * @author Steve Rawlinson Copyright (C) 2016 */ abstract public class AbstractThrottleManager implements ThrottleManager { diff --git a/java/src/jmri/jmrix/JmrixBundle.properties b/java/src/jmri/jmrix/JmrixBundle.properties index f5ac5b1c160..d7d465a95c4 100644 --- a/java/src/jmri/jmrix/JmrixBundle.properties +++ b/java/src/jmri/jmrix/JmrixBundle.properties @@ -178,6 +178,7 @@ SerialPortNotFound = Serial port {0} not found. SerialPortInUse = Serial port {0} is in use. #Wrap an exception's description in html and indent ErrorSubException =     {0} +ErrorConnectionTitle = Connection failed # Manager error items, some in NamedBeanBundle #ErrorConvertAddressX = Unable to convert {0} Hardware Address to a number @@ -305,6 +306,7 @@ ProtocolVersionLabel = Protocol Version: UseDefaultValue = Use default setting ButtonResetDefaults = Defaults MenuItemConsole = Console +MenuNoOptions = No Options #Error message displayed on start if internal connection has all defaults. ManagerDefaultSelector.AllInternal = All defaults are assigned to an internal connection. diff --git a/java/src/jmri/jmrix/JmrixBundle_nl.properties b/java/src/jmri/jmrix/JmrixBundle_nl.properties index d2a2c690e4c..2c32321a864 100644 --- a/java/src/jmri/jmrix/JmrixBundle_nl.properties +++ b/java/src/jmri/jmrix/JmrixBundle_nl.properties @@ -292,6 +292,7 @@ ProtocolVersionLabel = Protocol-versie: UseDefaultValue = Gebruik standaardwaarde ButtonResetDefaults = Standaardwaardes MenuItemConsole = Systeemconsole +MenuNoOptions = Geen Opties #Error message displayed on start if internal connection has all defaults. ManagerDefaultSelector.AllInternal = Alle Standaard-opties zijn toegewezen aan de Interne connectie. diff --git a/java/src/jmri/jmrix/dccpp/DCCppSystemConnectionMemo.java b/java/src/jmri/jmrix/dccpp/DCCppSystemConnectionMemo.java index 6ae1a92aa89..bb65f119a6f 100644 --- a/java/src/jmri/jmrix/dccpp/DCCppSystemConnectionMemo.java +++ b/java/src/jmri/jmrix/dccpp/DCCppSystemConnectionMemo.java @@ -91,7 +91,6 @@ public ThrottleManager getThrottleManager() { throttleManager = new DCCppThrottleManager(this); // TODO: Create this throttle manager } return throttleManager; - } public void setThrottleManager(ThrottleManager t) { diff --git a/java/src/jmri/jmrix/direct/Bundle.java b/java/src/jmri/jmrix/direct/Bundle.java new file mode 100644 index 00000000000..c6d6c843b00 --- /dev/null +++ b/java/src/jmri/jmrix/direct/Bundle.java @@ -0,0 +1,111 @@ +package jmri.jmrix.direct; + +import edu.umd.cs.findbugs.annotations.SuppressFBWarnings; +import java.util.Locale; +import javax.annotation.CheckReturnValue; +import javax.annotation.Nullable; +import javax.annotation.ParametersAreNonnullByDefault; + +@ParametersAreNonnullByDefault +@CheckReturnValue +@SuppressFBWarnings(value = "NM_SAME_SIMPLE_NAME_AS_SUPERCLASS", justification = "Desired pattern is repeated class names with package-level access to members") + +@javax.annotation.concurrent.Immutable + +/** + * Provides standard access for resource bundles in a package. + * + * Convention is to provide a subclass of this name in each package, working off + * the local resource bundle name. + * + * @author Bob Jacobsen Copyright (C) 2012 + * @since 3.3.1 + */ +public class Bundle extends jmri.jmrix.Bundle { + + @Nullable + private static final String name = "jmri.jmrix.direct.DirectBundle"; // NOI18N + + // + // below here is boilerplate to be copied exactly + // + /** + * Provides a translated string for a given key from the package resource + * bundle or parent. + *

+ * Note that this is intentionally package-local access. + * + * @param key Bundle key to be translated + * @return Internationalized text + */ + static String getMessage(String key) { + return getBundle().handleGetMessage(key); + } + + /** + * Provides a translated string for a given key in a given locale from the + * package resource bundle or parent. + *

+ * Note that this is intentionally package-local access. + * + * @param locale The locale to be used + * @param key Bundle key to be translated + * @return Internationalized text + */ + static String getMessage(Locale locale, String key) { + return getBundle().handleGetMessage(locale, key); + } + + /** + * Merges user data with a translated string for a given key from the + * package resource bundle or parent. + *

+ * Uses the transformation conventions of the Java MessageFormat utility. + *

+ * Note that this is intentionally package-local access. + * + * @see java.text.MessageFormat + * @param key Bundle key to be translated + * @param subs One or more objects to be inserted into the message + * @return Internationalized text + */ + static String getMessage(String key, Object... subs) { + return getBundle().handleGetMessage(key, subs); + } + + /** + * Merges user data with a translated string for a given key in a given + * locale from the package resource bundle or parent. + *

+ * Uses the transformation conventions of the Java MessageFormat utility. + *

+ * Note that this is intentionally package-local access. + * + * @see java.text.MessageFormat + * @param locale The locale to be used + * @param key Bundle key to be translated + * @param subs One or more objects to be inserted into the message + * @return Internationalized text + */ + static String getMessage(Locale locale, String key, Object... subs) { + return getBundle().handleGetMessage(locale, key, subs); + } + + private final static Bundle b = new Bundle(); + + @Override + @Nullable + protected String bundleName() { + return name; + } + + protected static jmri.Bundle getBundle() { + return b; + } + + @Override + protected String retry(Locale locale, String key) { + return super.getBundle().handleGetMessage(locale,key); + } + +} diff --git a/java/src/jmri/jmrix/direct/DirectBundle.properties b/java/src/jmri/jmrix/direct/DirectBundle.properties new file mode 100644 index 00000000000..0fffe5f83a1 --- /dev/null +++ b/java/src/jmri/jmrix/direct/DirectBundle.properties @@ -0,0 +1,9 @@ +# DirectBundle.properties +# +# Properties for Direct i18n items + +MenuTitle = Direct +MenuItemDirect = DirectDrive + +DirectBaudError = Failed to set the correct baud rate. Port is set to {0} baud.\n\ + See the README file for more info. diff --git a/java/src/jmri/jmrix/direct/DirectBundle_nl.properties b/java/src/jmri/jmrix/direct/DirectBundle_nl.properties new file mode 100644 index 00000000000..79df5a26c3f --- /dev/null +++ b/java/src/jmri/jmrix/direct/DirectBundle_nl.properties @@ -0,0 +1,9 @@ +# DirectBundle_nl.properties +# +# Dutch properties for Direct i18n items + +MenuTitle = Direct +MenuItemDirect = DirectDrive + +DirectBaudError = Instellen van juiste baud snelheid mislukt. Poort ingesteld op {0} baud.\n\ + Bekijk het README bestand voor meer info info. diff --git a/java/src/jmri/jmrix/direct/DirectConnectionTypeList.java b/java/src/jmri/jmrix/direct/DirectConnectionTypeList.java new file mode 100644 index 00000000000..4607b63a74a --- /dev/null +++ b/java/src/jmri/jmrix/direct/DirectConnectionTypeList.java @@ -0,0 +1,29 @@ +package jmri.jmrix.direct; + +import jmri.jmrix.ConnectionTypeList; +import org.openide.util.lookup.ServiceProvider; + +/** + * Return a list of valid Direct Connection Types. + * + * @author Bob Jacobsen Copyright (C) 2010 + * @author Kevin Dickerson Copyright (C) 2010 + */ +@ServiceProvider(service = ConnectionTypeList.class) +public class DirectConnectionTypeList implements jmri.jmrix.ConnectionTypeList { + + public static final String DIRECT = "Others"; + + @Override + public String[] getAvailableProtocolClasses() { + return new String[]{ + "jmri.jmrix.direct.serial.ConnectionConfig" + }; + } + + @Override + public String[] getManufacturers() { + return new String[]{DIRECT}; + } + +} diff --git a/java/src/jmri/jmrix/direct/DirectMenu.java b/java/src/jmri/jmrix/direct/DirectMenu.java index c01377ac831..f4461c45a35 100644 --- a/java/src/jmri/jmrix/direct/DirectMenu.java +++ b/java/src/jmri/jmrix/direct/DirectMenu.java @@ -2,27 +2,35 @@ import java.util.ResourceBundle; import javax.swing.JMenu; +import javax.swing.JMenuItem; /** - * Create a "Systems" menu containing the Jmri direct-drive-specific tools. + * Create a "Systems" menu containing the Jmri direct-drive-specific tools (none at present). * * @author Bob Jacobsen Copyright 2003 */ public class DirectMenu extends JMenu { - public DirectMenu(String name,DirectSystemConnectionMemo memo) { + public DirectMenu(String name, DirectSystemConnectionMemo memo) { this(memo); setText(name); } public DirectMenu(DirectSystemConnectionMemo memo) { - super(); - ResourceBundle rb = ResourceBundle.getBundle("jmri.jmrix.JmrixSystemsBundle"); - - setText(rb.getString("MenuItemDirect")); - + if (memo != null) { + setText(memo.getUserName()); + } else { + setText(Bundle.getMessage("MenuItemDirect")); + } + + // no items + if (memo != null) { + // do we have a TrafficController? + setEnabled(false); // memo.getTrafficController() != null); // disable menu, no connection, no tools! + add(new JMenuItem(Bundle.getMessage("MenuNoOptions"))); + } } } diff --git a/java/src/jmri/jmrix/direct/DirectSystemConnectionMemo.java b/java/src/jmri/jmrix/direct/DirectSystemConnectionMemo.java index 6372c9e79fb..ff085ee4058 100644 --- a/java/src/jmri/jmrix/direct/DirectSystemConnectionMemo.java +++ b/java/src/jmri/jmrix/direct/DirectSystemConnectionMemo.java @@ -50,7 +50,7 @@ public void setTrafficController(TrafficController s){ */ public TrafficController getTrafficController(){ if (tc == null) { - setTrafficController(new TrafficController()); + setTrafficController(new TrafficController(this)); log.debug("Auto create of TrafficController for initial configuration"); } return tc; @@ -69,23 +69,24 @@ public void setThrottleManager(ThrottleManager s){ } /** - * Get the throttle manager instance associated with this connection memo. + * Get the ThrottleManager instance associated with this connection memo. */ public ThrottleManager getThrottleManager(){ if (tm == null) { - setThrottleManager(new ThrottleManager(getTrafficController())); + setThrottleManager(new ThrottleManager(this)); log.debug("Auto create of ThrottleManager for initial configuration"); } return tm; } - @Override protected ResourceBundle getActionModelResourceBundle() { return null; } public void configureManagers(){ + tm = new jmri.jmrix.direct.ThrottleManager(this); + jmri.InstanceManager.setThrottleManager(tm); } @Override diff --git a/java/src/jmri/jmrix/direct/MakePacket.java b/java/src/jmri/jmrix/direct/MakePacket.java index 804e159d7fe..1ceda7c1327 100644 --- a/java/src/jmri/jmrix/direct/MakePacket.java +++ b/java/src/jmri/jmrix/direct/MakePacket.java @@ -1,10 +1,9 @@ package jmri.jmrix.direct; - /** * Provide utilities for coding/decoding NMRA {@literal S&RP} DCC packets into * sequences to send through a standard serial port. - *

+ *

* This is strongly based on the makepckt.c file from the PacketScript 1.1. * package of Kenneth Rice. The original header comment from that file follows * here. @@ -77,7 +76,7 @@ * 73577,1653 (compuserve) * * Created 02/08/93 - * 03/05/93 Works for all 3 byte packets. Still errors for 4 byte. + * 03/05/93 Works for all 3 byte packets. Still errors for 4 byte. * 07/01/93 Renamed to makepckt.c to be nice to dos users. * 10/23/93 Added backtracking and max length. * @@ -131,14 +130,14 @@ private static class Node { /* Node definition for first depth, prune largest tree. */ /** - * Function to set the Preamble Length - Default is 15 NRMA '1's Every NMRA + * Set the Preamble Length - Default is 15 NRMA '1's Every NMRA * packet decoded starts with a preamble Service mode requires longer * preambles Thus this public function allowing user to define the lenght of * desired preamble * * @param preambleLen int - * @return boolean - true if preamble is a multiple of 5 otherwise fails and - * returns alse + * @return boolean true if preamble is a multiple of 5, otherwise fails and + * returns false */ public static boolean setPreambleLength(int preambleLen) { //Just make sure that no negatives values are passed. @@ -154,12 +153,12 @@ public static boolean setPreambleLength(int preambleLen) { } /** - * Function that takes in the packet as a array of Bytes and converts an + * Take in the packet as an array of Bytes and convert * them into NMRA'1','0' representation, in preparation to be sent over a * serial link. * - * @param packet byte[] - NRMA packet in a array of bytes - * @return int[] - first byte is length - 0 length indicates failed to do + * @param packet byte[] NRMA packet in a array of bytes + * @return int[] first byte is length - 0 length indicates failed to do */ public static int[] createStream(byte[] packet) { int i = 0; @@ -200,13 +199,13 @@ public static int[] createStream(byte[] packet) { /** * Generate the serial bytes from the bit stream. - *

+ *

* Basically this is a depth first, prune largest tree search, always going down the subtree * that uses the most bits for the next byte. If we get an error, backtrack up * the tree until we reach a Node that we have not completely traversed all the * subtrees for and try going down the subtree that uses the second most bits. * Keep going until we finish converting the packet or run out of things to try. - *

+ *

* This is not guaranteed to find the shortest serial stream for a given * packet, but it is guaranteed to find a stream if one exists. Also, it * usually does come up with the shortest packet. @@ -265,10 +264,9 @@ static int[] bitStreamToSerialBytes(int[] inputBitStream) { } /** - * Routine to find the next largest (ie longest lenght) child - * at this Node. + * Find the next largest (ie longest lenght) child at this Node. * - * @param thisNode - (INPUT/OUTPUT) determine if there is another child + * @param thisNode (INPUT/OUTPUT) determine if there is another child * if so update Node with ie the Bit * pattern and its associated lenght * @@ -328,16 +326,16 @@ static boolean readNextChild(Node thisNode) { } /** - * Routine to find the first largest (ie longest length) child + * Find the first largest (ie longest length) child * at this Node. * - * @param bs - (INPUT) Bit stream array - * @param offset - Offset in to buffer - * @param validBits - (INPUT) number of valid bits in the bit stream. - * @param thisNode - (OUTPUT) where to put largest child found ie the Bit - * pattern and its associated lenght. + * @param bs (INPUT) Bit stream array + * @param offset Offset in to buffer + * @param validBits (INPUT) number of valid bits in the bit stream + * @param thisNode (OUTPUT) where to put largest child found ie the Bit + * pattern and its associated lenght * - * @return false if one doesn't exist otherwise returns true. + * @return false if one doesn't exist otherwise returns true */ @SuppressWarnings("fallthrough") static boolean readFirstChild(int bs[], int offset, int validBits, diff --git a/java/src/jmri/jmrix/direct/Message.java b/java/src/jmri/jmrix/direct/Message.java index 85677d552ff..c168b9e0ad1 100644 --- a/java/src/jmri/jmrix/direct/Message.java +++ b/java/src/jmri/jmrix/direct/Message.java @@ -6,8 +6,7 @@ import org.slf4j.LoggerFactory; /** - * Encodes a message for direct DCC - *

+ * Encodes a message for Direct DCC. * * @author Bob Jacobsen Copyright (C) 2004 */ diff --git a/java/src/jmri/jmrix/direct/PortController.java b/java/src/jmri/jmrix/direct/PortController.java index dfb8745ce52..65428ff716a 100644 --- a/java/src/jmri/jmrix/direct/PortController.java +++ b/java/src/jmri/jmrix/direct/PortController.java @@ -1,17 +1,21 @@ package jmri.jmrix.direct; /* - * Identifying class representing a direct-drive communications port - * @author Bob Jacobsen Copyright (C) 2001, 2004 + * Identifying class representing a direct-drive communications port. + * + * @author Bob Jacobsen Copyright (C) 2001, 2004 */ public abstract class PortController extends jmri.jmrix.AbstractSerialPortController { // base class. Implementations will provide InputStream and OutputStream // objects to TrafficController classes, who in turn will deal in messages. - protected PortController() { - super(new DirectSystemConnectionMemo()); + protected PortController(DirectSystemConnectionMemo memo) { + super(memo); this.manufacturerName = jmri.jmrix.OtherConnectionTypeList.OTHER; } -} + protected PortController() { + this(new DirectSystemConnectionMemo()); + } +} diff --git a/java/src/jmri/jmrix/direct/Throttle.java b/java/src/jmri/jmrix/direct/Throttle.java index 62ce3e6fa39..341269d0028 100644 --- a/java/src/jmri/jmrix/direct/Throttle.java +++ b/java/src/jmri/jmrix/direct/Throttle.java @@ -1,28 +1,25 @@ package jmri.jmrix.direct; import edu.umd.cs.findbugs.annotations.SuppressFBWarnings; +import jmri.CommandStation; import jmri.DccLocoAddress; import jmri.LocoAddress; import jmri.jmrix.AbstractThrottle; /** - * An implementation of DccThrottle with code specific to a direct serial + * An implementation of DccThrottle with code specific to a Direct serial * connection. - *

- * Addresses of 99 and below are considered short addresses, and over 100 are - * considered long addresses. - *

* * @author Bob Jacobsen Copyright (C) 2004 */ public class Throttle extends AbstractThrottle { - private jmri.CommandStation tcl = null; + private CommandStation tcl = null; /** * Constructor. */ - public Throttle(int address,jmri.CommandStation tc) { + public Throttle(DccLocoAddress address, CommandStation tc) { super(null); tcl = tc; @@ -43,17 +40,21 @@ public Throttle(int address,jmri.CommandStation tc) { this.f12 = false; this.address = address; this.isForward = true; - } - int address; // store integer value for now, ignoring long/short + DccLocoAddress address; + + @Override + public LocoAddress getLocoAddress() { + return address; + } /** * Send the message to set the state of functions F0, F1, F2, F3, F4. */ @Override protected void sendFunctionGroup1() { - byte[] result = jmri.NmraPacket.function0Through4Packet(address, (address >= 100), + byte[] result = jmri.NmraPacket.function0Through4Packet(address.getNumber(), address.isLongAddress(), getF0(), getF1(), getF2(), getF3(), getF4()); tcl.sendPacket(result, 1); @@ -65,7 +66,7 @@ protected void sendFunctionGroup1() { @Override protected void sendFunctionGroup2() { - byte[] result = jmri.NmraPacket.function5Through8Packet(address, (address >= 100), + byte[] result = jmri.NmraPacket.function5Through8Packet(address.getNumber(), address.isLongAddress(), getF5(), getF6(), getF7(), getF8()); tcl.sendPacket(result, 1); @@ -77,7 +78,7 @@ protected void sendFunctionGroup2() { @Override protected void sendFunctionGroup3() { - byte[] result = jmri.NmraPacket.function9Through12Packet(address, (address >= 100), + byte[] result = jmri.NmraPacket.function9Through12Packet(address.getNumber(), address.isLongAddress(), getF9(), getF10(), getF11(), getF12()); tcl.sendPacket(result, 1); @@ -85,7 +86,7 @@ protected void sendFunctionGroup3() { /** * Set the speed {@literal &} direction. - *

+ *

* This intentionally skips the emergency stop value of 1. * * @param speed Number from 0 to 1; less than zero is emergency stop @@ -95,15 +96,15 @@ protected void sendFunctionGroup3() { public void setSpeedSetting(float speed) { float oldSpeed = this.speedSetting; this.speedSetting = speed; - int value = (int) ((127 - 1) * speed); // -1 for rescale to avoid estop + int value = (int) ((127 - 1) * speed); // -1 for rescale to avoid estop if (value > 0) { - value = value + 1; // skip estop + value = value + 1; // skip estop } if (value > 127) { - value = 127; // max possible speed + value = 127; // max possible speed } if (value < 0) { - value = 1; // emergency stop + value = 1; // emergency stop } String step = "" + value; @@ -135,12 +136,6 @@ public void setIsForward(boolean forward) { } } - @Override - public LocoAddress getLocoAddress() { - //log.error("getLocoAddress not fully implemented yet"); - return new DccLocoAddress(address, address > 100); // always short address if <100 - } - @Override protected void throttleDispose() { finishRecord(); diff --git a/java/src/jmri/jmrix/direct/ThrottleManager.java b/java/src/jmri/jmrix/direct/ThrottleManager.java index 668418103c1..50c7d8adf9e 100644 --- a/java/src/jmri/jmrix/direct/ThrottleManager.java +++ b/java/src/jmri/jmrix/direct/ThrottleManager.java @@ -1,17 +1,19 @@ package jmri.jmrix.direct; +import jmri.CommandStation; import jmri.DccLocoAddress; import jmri.LocoAddress; import jmri.jmrix.AbstractThrottleManager; +import jmri.jmrix.direct.DirectSystemConnectionMemo; import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** * Direct DCC implementation of a ThrottleManager. - *

+ *

* When the traffic manager doesn't have anything else to do, it comes here to * get a command to send. - *

+ *

* This is a partial implementation, which can only handle one Throttle at a * time. It also is missing logic to alternate sending speed and function * commands; right now it only sends the first group of function packets. @@ -20,14 +22,14 @@ */ public class ThrottleManager extends AbstractThrottleManager { - private jmri.CommandStation tc = null; + private CommandStation tc = null; /** - * Constructor. + * Constructor for a ThrottleManager. */ - public ThrottleManager(jmri.CommandStation tcl) { - super(); - tc = tcl; - jmri.InstanceManager.setDefault(jmri.jmrix.direct.ThrottleManager.class,this); + public ThrottleManager(DirectSystemConnectionMemo memo) { + super(memo); + tc = memo.getTrafficController(); + jmri.InstanceManager.setDefault(jmri.jmrix.direct.ThrottleManager.class, this); } /** @@ -46,12 +48,11 @@ static public ThrottleManager instance() { @Override public void requestThrottleSetup(LocoAddress address, boolean control) { if (currentThrottle != null) { - log.error("DCC direct cannot handle more than one throttle now"); + log.error("DCC Direct cannot handle more than one throttle"); failedThrottleRequest((DccLocoAddress) address, "DCC direct cannot handle more than one throttle " + address); return; } - log.warn("requestThrottleSetup should preserve actual address object, not use ints"); - currentThrottle = new Throttle(((DccLocoAddress) address).getNumber(),tc); + currentThrottle = new Throttle(((DccLocoAddress) address), tc); // uses address object notifyThrottleKnown(currentThrottle, currentThrottle.getLocoAddress()); } @@ -72,7 +73,7 @@ public boolean canBeLongAddress(int a) { /** * Invoked when a throttle is released, this updates the local data - * structures + * structures. */ @Override public boolean disposeThrottle(jmri.DccThrottle t, jmri.ThrottleListener l) { diff --git a/java/src/jmri/jmrix/direct/TrafficController.java b/java/src/jmri/jmrix/direct/TrafficController.java index 483449a78ff..fae60727e79 100644 --- a/java/src/jmri/jmrix/direct/TrafficController.java +++ b/java/src/jmri/jmrix/direct/TrafficController.java @@ -28,8 +28,9 @@ public class TrafficController implements jmri.CommandStation { /** * Create a new Direct TrafficController instance. */ - public TrafficController() { + public TrafficController(DirectSystemConnectionMemo memo) { super(); + _memo = memo; } /** @@ -93,11 +94,10 @@ public void sendPacket(byte[] packet, int repeats) { } catch (IOException e) { log.warn("sendMessage: Exception: {}", e.getMessage()); } - } // methods to connect/disconnect to a source of data in an AbstractSerialPortController - + private DirectSystemConnectionMemo _memo = null; private AbstractSerialPortController controller = null; public boolean status() { @@ -141,12 +141,12 @@ public void disconnectPort(AbstractSerialPortController p) { @Override public String getUserName() { - return "Others"; + return _memo.getUserName(); } @Override public String getSystemPrefix() { - return "N"; + return _memo.getSystemPrefix(); } private final static Logger log = LoggerFactory.getLogger(TrafficController.class); diff --git a/java/src/jmri/jmrix/direct/serial/Bundle.java b/java/src/jmri/jmrix/direct/serial/Bundle.java new file mode 100644 index 00000000000..0591113d03a --- /dev/null +++ b/java/src/jmri/jmrix/direct/serial/Bundle.java @@ -0,0 +1,98 @@ +package jmri.jmrix.direct.serial; + +import edu.umd.cs.findbugs.annotations.SuppressFBWarnings; +import java.util.Locale; +import javax.annotation.CheckReturnValue; +import javax.annotation.Nullable; +import javax.annotation.ParametersAreNonnullByDefault; + +@ParametersAreNonnullByDefault +@CheckReturnValue +@SuppressFBWarnings(value = "NM_SAME_SIMPLE_NAME_AS_SUPERCLASS", justification = "Desired pattern is repeated class names with package-level access to members") + +@javax.annotation.concurrent.Immutable + +/** + * Provides standard access for resource bundles in a package. + * + * Convention is to provide a subclass of this name in each package, working off + * the local resource bundle name. + * + * @author Bob Jacobsen Copyright (C) 2012 + * @since 3.3.1 + */ +public class Bundle extends jmri.jmrix.direct.Bundle { + + @Nullable + private static final String name = null; // No local resources + + // + // below here is boilerplate to be copied exactly + // + /** + * Provides a translated string for a given key from the package resource + * bundle or parent. + *

+ * Note that this is intentionally package-local access. + * + * @param key Bundle key to be translated + * @return Internationalized text + */ + static String getMessage(String key) { + return getBundle().handleGetMessage(key); + } + + /** + * Merges user data with a translated string for a given key from the + * package resource bundle or parent. + *

+ * Uses the transformation conventions of the Java MessageFormat utility. + *

+ * Note that this is intentionally package-local access. + * + * @see java.text.MessageFormat + * @param key Bundle key to be translated + * @param subs One or more objects to be inserted into the message + * @return Internationalized text + */ + static String getMessage(String key, Object... subs) { + return getBundle().handleGetMessage(key, subs); + } + + /** + * Merges user data with a translated string for a given key in a given + * locale from the package resource bundle or parent. + *

+ * Uses the transformation conventions of the Java MessageFormat utility. + *

+ * Note that this is intentionally package-local access. + * + * @see java.text.MessageFormat + * @param locale The locale to be used + * @param key Bundle key to be translated + * @param subs One or more objects to be inserted into the message + * @return Internationalized text + */ + static String getMessage(Locale locale, String key, Object... subs) { + return getBundle().handleGetMessage(locale, key, subs); + } + + + private final static Bundle b = new Bundle(); + + @Override + @Nullable + protected String bundleName() { + return name; + } + + protected static jmri.Bundle getBundle() { + return b; + } + + @Override + protected String retry(Locale locale, String key) { + return super.getBundle().handleGetMessage(locale,key); + } + +} diff --git a/java/src/jmri/jmrix/direct/serial/ConnectionConfig.java b/java/src/jmri/jmrix/direct/serial/ConnectionConfig.java index d6c9f0a3541..2c5a9095841 100644 --- a/java/src/jmri/jmrix/direct/serial/ConnectionConfig.java +++ b/java/src/jmri/jmrix/direct/serial/ConnectionConfig.java @@ -19,7 +19,7 @@ public ConnectionConfig(jmri.jmrix.SerialPortAdapter p) { } /** - * Ctor for a functional Swing object with no prexisting adapter + * Ctor for a functional Swing object with no prexisting adapter. */ public ConnectionConfig() { super(); @@ -37,8 +37,9 @@ public String name() { @Override protected void setInstance() { - if(adapter == null ){ - adapter = SerialDriverAdapter.instance(); + if (adapter == null) { + adapter = new SerialDriverAdapter(); } } + } diff --git a/java/src/jmri/jmrix/direct/serial/SerialDriverAdapter.java b/java/src/jmri/jmrix/direct/serial/SerialDriverAdapter.java index 5a4d5c2f361..5f83a211bb5 100644 --- a/java/src/jmri/jmrix/direct/serial/SerialDriverAdapter.java +++ b/java/src/jmri/jmrix/direct/serial/SerialDriverAdapter.java @@ -50,7 +50,7 @@ public Vector getPortNames() { } @edu.umd.cs.findbugs.annotations.SuppressFBWarnings(value="SR_NOT_CHECKED", - justification="this is for skip-chars while loop: no matter how many, we're skipping") + justification="this is for skip-chars while loop: no matter how many, we're skipping") @Override public String openPort(String portName, String appName) { try { @@ -74,10 +74,8 @@ public String openPort(String portName, String appName) { log.warn("trouble setting 16457 baud"); activeSerialPort.setSerialPortParams(19200, SerialPort.DATABITS_8, SerialPort.STOPBITS_1, SerialPort.PARITY_NONE); javax.swing.JOptionPane.showMessageDialog(null, - "Failed to set the correct baud rate. Port is set to " - + activeSerialPort.getBaudRate() - + " baud. See the README file for more info.", - "Connection failed", javax.swing.JOptionPane.ERROR_MESSAGE); + Bundle.getMessage("DirectBaudError", activeSerialPort.getBaudRate()), + Bundle.getMessage("ErrorConnectionTitle"), javax.swing.JOptionPane.ERROR_MESSAGE); } } @@ -85,8 +83,8 @@ public String openPort(String portName, String appName) { configureLeadsAndFlowControl(activeSerialPort, 0); // activeSerialPort.enableReceiveTimeout(1000); - log.debug("Serial timeout was observed as: " + activeSerialPort.getReceiveTimeout() - + " " + activeSerialPort.isReceiveTimeoutEnabled()); + log.debug("Serial timeout was observed as: {} {}", activeSerialPort.getReceiveTimeout(), + activeSerialPort.isReceiveTimeoutEnabled()); // get and save stream serialInStream = activeSerialPort.getInputStream(); @@ -95,7 +93,7 @@ public String openPort(String portName, String appName) { // port is open, start work on the stream // purge contents, if any int count = serialInStream.available(); - log.debug("input stream shows " + count + " bytes available"); + log.debug("input stream shows {} bytes available", count); while (count > 0) { serialInStream.skip(count); count = serialInStream.available(); @@ -128,10 +126,12 @@ public String openPort(String portName, String appName) { */ @Override public void configure() { - TrafficController tc = new TrafficController(); + TrafficController tc = new TrafficController((jmri.jmrix.direct.DirectSystemConnectionMemo)getSystemConnectionMemo()); ((jmri.jmrix.direct.DirectSystemConnectionMemo)getSystemConnectionMemo()).setTrafficController(tc); // connect to the traffic controller tc.connectPort(this); + + ((jmri.jmrix.direct.DirectSystemConnectionMemo)getSystemConnectionMemo()).configureManagers(); } // base class methods for the PortController interface @@ -172,7 +172,7 @@ public boolean status() { */ @Override public String[] validBaudRates() { - return new String[]{"19,200 bps"}; + return new String[]{Bundle.getMessage("Baud19200")}; } // private control members diff --git a/java/src/jmri/jmrix/direct/serial/configurexml/ConnectionConfigXml.java b/java/src/jmri/jmrix/direct/serial/configurexml/ConnectionConfigXml.java index 0b53be8c649..dceeaf74d15 100644 --- a/java/src/jmri/jmrix/direct/serial/configurexml/ConnectionConfigXml.java +++ b/java/src/jmri/jmrix/direct/serial/configurexml/ConnectionConfigXml.java @@ -9,7 +9,7 @@ * SerialDriverAdapter (and connections). Note this is named as the XML version * of a ConnectionConfig object, but it's actually persisting the * SerialDriverAdapter. - *

+ *

* This class is invoked from jmrix.JmrixConfigPaneXml on write, as that class * is the one actually registered. Reads are brought here directly via the class * attribute in the XML. @@ -24,8 +24,8 @@ public ConnectionConfigXml() { @Override protected void getInstance() { - if(adapter == null ) { - adapter = SerialDriverAdapter.instance(); + if (adapter == null ) { + adapter = new SerialDriverAdapter(); } } diff --git a/java/src/jmri/jmrix/direct/swing/DirectComponentFactory.java b/java/src/jmri/jmrix/direct/swing/DirectComponentFactory.java index 1f6725e3cc0..d62913b0ae7 100644 --- a/java/src/jmri/jmrix/direct/swing/DirectComponentFactory.java +++ b/java/src/jmri/jmrix/direct/swing/DirectComponentFactory.java @@ -28,5 +28,5 @@ public javax.swing.JMenu getMenu() { } return new DirectMenu(memo); } -} +} diff --git a/java/src/jmri/jmrix/sprog/simulator/SimulatorAdapter.java b/java/src/jmri/jmrix/sprog/simulator/SimulatorAdapter.java index 1ff95f94fef..ff169debe8c 100644 --- a/java/src/jmri/jmrix/sprog/simulator/SimulatorAdapter.java +++ b/java/src/jmri/jmrix/sprog/simulator/SimulatorAdapter.java @@ -325,7 +325,7 @@ private SprogReply generateReply(SprogMessage msg) { case 'S': log.debug("getStatus detected"); - reply = new SprogReply("S\n"); + reply = new SprogReply("OK\n"); break; default: From edfc0ad04702cbcaa1bf2790aaaf2c54efbececa Mon Sep 17 00:00:00 2001 From: Paul Bender Date: Fri, 6 Apr 2018 00:16:54 -0400 Subject: [PATCH 19/58] updated tests --- .../openlcb/OlcbConfigurationManagerTest.java | 23 +++++++------- .../jmrix/openlcb/OlcbSensorManagerTest.java | 4 ++- .../jmrix/openlcb/OlcbSignalMastTest.java | 7 +++-- .../openlcb/OlcbThrottleManagerTest.java | 27 +++++++++++++---- .../jmri/jmrix/openlcb/OlcbThrottleTest.java | 30 ++++++++++++++----- .../jmrix/openlcb/OlcbTurnoutManagerTest.java | 4 ++- .../configurexml/OlcbSignalMastXmlTest.java | 28 ++++++++++------- .../openlcb/configurexml/PackageTest.java | 19 ------------ 8 files changed, 82 insertions(+), 60 deletions(-) diff --git a/java/test/jmri/jmrix/openlcb/OlcbConfigurationManagerTest.java b/java/test/jmri/jmrix/openlcb/OlcbConfigurationManagerTest.java index 94f54c855ff..0ee7be397d8 100644 --- a/java/test/jmri/jmrix/openlcb/OlcbConfigurationManagerTest.java +++ b/java/test/jmri/jmrix/openlcb/OlcbConfigurationManagerTest.java @@ -2,9 +2,9 @@ import jmri.jmrix.can.TestTrafficController; import jmri.util.JUnitUtil; -import org.junit.After; +import org.junit.AfterClass; import org.junit.Assert; -import org.junit.Before; +import org.junit.BeforeClass; import org.junit.Test; /** @@ -13,7 +13,7 @@ */ public class OlcbConfigurationManagerTest { - private OlcbSystemConnectionMemo scm; + private static OlcbSystemConnectionMemo scm; @Test public void testCTor() { @@ -28,23 +28,20 @@ public void testConfigureManagers() { t.configureManagers(); } - // The minimal setup for log4J - @Before - public void setUp() { + @BeforeClass + public static void preClassInit() { JUnitUtil.setUp(); - //OlcbTestInterface testIf = new OlcbTestInterface(); - scm = new OlcbSystemConnectionMemo(); - //scm.setTrafficController(testIf.tc); - //scm.setInterface(testIf.iface); + scm = new OlcbSystemConnectionMemo(); TestTrafficController tc = new TestTrafficController(); scm.setTrafficController(tc); } - @After - public void tearDown() { - if(scm.getInterface()!=null) { + @AfterClass + public static void postClassTearDown() { + if(scm != null && scm.getInterface() !=null ) { scm.getInterface().dispose(); } + scm = null; JUnitUtil.tearDown(); } diff --git a/java/test/jmri/jmrix/openlcb/OlcbSensorManagerTest.java b/java/test/jmri/jmrix/openlcb/OlcbSensorManagerTest.java index a1cec8a21a6..83ecb7ecff3 100644 --- a/java/test/jmri/jmrix/openlcb/OlcbSensorManagerTest.java +++ b/java/test/jmri/jmrix/openlcb/OlcbSensorManagerTest.java @@ -82,7 +82,9 @@ public void setUp() { @After public void tearDown() { l.dispose(); - m.getInterface().dispose(); + if(m != null && m.getInterface() !=null ) { + m.getInterface().dispose(); + } JUnitUtil.tearDown(); } diff --git a/java/test/jmri/jmrix/openlcb/OlcbSignalMastTest.java b/java/test/jmri/jmrix/openlcb/OlcbSignalMastTest.java index d18246958b2..957226445d4 100644 --- a/java/test/jmri/jmrix/openlcb/OlcbSignalMastTest.java +++ b/java/test/jmri/jmrix/openlcb/OlcbSignalMastTest.java @@ -19,10 +19,8 @@ import org.openlcb.IdentifyEventsMessage; import org.junit.After; -import org.junit.AfterClass; import org.junit.Assert; import org.junit.Before; -import org.junit.BeforeClass; import org.junit.Test; /** @@ -330,7 +328,10 @@ public Connection getOutputConnection() { @After public void tearDown() throws Exception { - memo.getInterface().dispose(); + if(memo != null && memo.getInterface() !=null ) { + memo.getInterface().dispose(); + } + memo = null; JUnitUtil.tearDown(); } } diff --git a/java/test/jmri/jmrix/openlcb/OlcbThrottleManagerTest.java b/java/test/jmri/jmrix/openlcb/OlcbThrottleManagerTest.java index e47f06ba8c0..69661c1017e 100644 --- a/java/test/jmri/jmrix/openlcb/OlcbThrottleManagerTest.java +++ b/java/test/jmri/jmrix/openlcb/OlcbThrottleManagerTest.java @@ -2,7 +2,9 @@ import jmri.util.JUnitUtil; import org.junit.After; +import org.junit.AfterClass; import org.junit.Before; +import org.junit.BeforeClass; import jmri.jmrix.can.TestTrafficController; /** @@ -13,22 +15,37 @@ */ public class OlcbThrottleManagerTest extends jmri.managers.AbstractThrottleManagerTestBase { - private OlcbSystemConnectionMemo m; + private static OlcbSystemConnectionMemo m; + private static OlcbConfigurationManagerScaffold ocm; // The minimal setup for log4J @Override @Before public void setUp() { + tm = new OlcbThrottleManager(m,ocm); + } + + @After + public void tearDown() { + tm = null; + } + + @BeforeClass + public static void preClassInit() { JUnitUtil.setUp(); m = new jmri.jmrix.openlcb.OlcbSystemConnectionMemo(); TestTrafficController tc = new TestTrafficController(); m.setTrafficController(tc); - tm = new OlcbThrottleManager(m,new OlcbConfigurationManagerScaffold(m)); + ocm = new OlcbConfigurationManagerScaffold(m); } - @After - public void tearDown() { - m.getInterface().dispose(); + @AfterClass + public static void postClassTearDown() { + if(m != null && m.getInterface() !=null ) { + m.getInterface().dispose(); + } + m = null; + ocm = null; JUnitUtil.tearDown(); } } diff --git a/java/test/jmri/jmrix/openlcb/OlcbThrottleTest.java b/java/test/jmri/jmrix/openlcb/OlcbThrottleTest.java index 138a1824201..7897def8d37 100644 --- a/java/test/jmri/jmrix/openlcb/OlcbThrottleTest.java +++ b/java/test/jmri/jmrix/openlcb/OlcbThrottleTest.java @@ -3,8 +3,10 @@ import jmri.DccLocoAddress; import jmri.util.JUnitUtil; import org.junit.After; +import org.junit.AfterClass; import org.junit.Assert; import org.junit.Before; +import org.junit.BeforeClass; import org.junit.Test; import jmri.jmrix.can.TestTrafficController; @@ -15,7 +17,8 @@ */ public class OlcbThrottleTest extends jmri.jmrix.AbstractThrottleTest { - private OlcbSystemConnectionMemo m; + private static OlcbSystemConnectionMemo m; + private static OlcbConfigurationManager ocm; /** * Test of getIsForward method, of class AbstractThrottle. @@ -361,19 +364,32 @@ public void testSendFunctionGroup5() { @Override @Before public void setUp() { + instance = new OlcbThrottle(new DccLocoAddress(100,true),m,ocm); + } + + @Override + @After + public void tearDown() { + instance = null; + } + + @BeforeClass + public static void preClassInit() { JUnitUtil.setUp(); m = new OlcbSystemConnectionMemo(); TestTrafficController tc = new TestTrafficController(); m.setTrafficController(tc); - OlcbConfigurationManager ocm = new OlcbConfigurationManagerScaffold(m); + ocm = new OlcbConfigurationManagerScaffold(m); ocm.configureManagers(); - instance = new OlcbThrottle(new DccLocoAddress(100,true),m,ocm); } - @Override - @After - public void tearDown() { - m.getInterface().dispose(); + @AfterClass + public static void postClassTearDown() { + if(m != null && m.getInterface() !=null ) { + m.getInterface().dispose(); + } + m = null; + ocm = null; JUnitUtil.tearDown(); } } diff --git a/java/test/jmri/jmrix/openlcb/OlcbTurnoutManagerTest.java b/java/test/jmri/jmrix/openlcb/OlcbTurnoutManagerTest.java index 0319d3c2930..e538dd8edc8 100644 --- a/java/test/jmri/jmrix/openlcb/OlcbTurnoutManagerTest.java +++ b/java/test/jmri/jmrix/openlcb/OlcbTurnoutManagerTest.java @@ -60,7 +60,9 @@ public void setUp() { @After public void tearDown() { l.dispose(); - m.getInterface().dispose(); + if(m != null && m.getInterface() !=null ) { + m.getInterface().dispose(); + } JUnitUtil.tearDown(); } diff --git a/java/test/jmri/jmrix/openlcb/configurexml/OlcbSignalMastXmlTest.java b/java/test/jmri/jmrix/openlcb/configurexml/OlcbSignalMastXmlTest.java index 9d4816b8a5f..50ba512e5d1 100644 --- a/java/test/jmri/jmrix/openlcb/configurexml/OlcbSignalMastXmlTest.java +++ b/java/test/jmri/jmrix/openlcb/configurexml/OlcbSignalMastXmlTest.java @@ -22,8 +22,10 @@ import org.jdom2.Element; import org.junit.After; +import org.junit.AfterClass; import org.junit.Assert; import org.junit.Before; +import org.junit.BeforeClass; import org.junit.Test; /** @@ -35,7 +37,7 @@ */ public class OlcbSignalMastXmlTest { - private OlcbSystemConnectionMemo memo; + static OlcbSystemConnectionMemo memo; @Test public void testCtor(){ @@ -68,20 +70,24 @@ public void testStore(){ // The minimal setup for log4J @Before public void setUp() { - JUnitUtil.setUp(); - - Connection connection = new AbstractConnection() { - @Override - public void put(Message msg, Connection sender) { - } - }; - - OlcbSystemConnectionMemo memo = OlcbTestInterface.createForLegacyTests(); } @After public void tearDown() { - memo.getInterface().dispose(); + } + + @BeforeClass + public static void preClassInit() { + JUnitUtil.setUp(); + memo = OlcbTestInterface.createForLegacyTests(); + } + + @AfterClass + public static void postClassTearDown() { + if(memo != null && memo.getInterface() !=null ) { + memo.getInterface().dispose(); + } + memo = null; JUnitUtil.tearDown(); } diff --git a/java/test/jmri/jmrix/openlcb/configurexml/PackageTest.java b/java/test/jmri/jmrix/openlcb/configurexml/PackageTest.java index 419e98d6d24..abc7cdde64d 100644 --- a/java/test/jmri/jmrix/openlcb/configurexml/PackageTest.java +++ b/java/test/jmri/jmrix/openlcb/configurexml/PackageTest.java @@ -2,9 +2,6 @@ import org.junit.runner.RunWith; import org.junit.runners.Suite; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - @RunWith(Suite.class) @Suite.SuiteClasses({ @@ -18,20 +15,4 @@ * @author Paul Bender Copyright (C) 2016 */ public class PackageTest { - - // Main entry point - static public void main(String[] args) { - org.junit.runner.Result result = org.junit.runner.JUnitCore - .runClasses(PackageTest.class); - for(org.junit.runner.notification.Failure fail: result.getFailures()) { - log.error(fail.toString()); - } - //junit.textui.TestRunner.main(testCaseName); - if (result.wasSuccessful()) { - log.info("Success"); - } - } - - private final static Logger log = LoggerFactory.getLogger(PackageTest.class); - } From c0e3c88df7591599c41ccffae4117c37e6e6327d Mon Sep 17 00:00:00 2001 From: Paul Bender Date: Fri, 6 Apr 2018 01:28:36 -0400 Subject: [PATCH 20/58] convert to JUnit4 --- .../jmri/jmrix/openlcb/OlcbTurnoutTest.java | 56 +++++++++---------- 1 file changed, 26 insertions(+), 30 deletions(-) diff --git a/java/test/jmri/jmrix/openlcb/OlcbTurnoutTest.java b/java/test/jmri/jmrix/openlcb/OlcbTurnoutTest.java index 9cf8b785c7e..346191994f7 100644 --- a/java/test/jmri/jmrix/openlcb/OlcbTurnoutTest.java +++ b/java/test/jmri/jmrix/openlcb/OlcbTurnoutTest.java @@ -6,11 +6,11 @@ import jmri.jmrix.can.CanMessage; import jmri.util.PropertyChangeListenerScaffold; -import junit.framework.Test; -import junit.framework.TestCase; -import junit.framework.TestSuite; - +import org.junit.After; import org.junit.Assert; +import org.junit.Before; +import org.junit.Test; + import org.openlcb.EventID; import org.openlcb.implementations.EventTable; import org.slf4j.Logger; @@ -20,11 +20,12 @@ * * @author Bob Jacobsen Copyright 2008, 2010, 2011 */ -public class OlcbTurnoutTest extends TestCase { +public class OlcbTurnoutTest { private final static Logger log = LoggerFactory.getLogger(OlcbTurnoutTest.class); protected PropertyChangeListenerScaffold l; + @Test public void testIncomingChange() { Assert.assertNotNull("exists", t); OlcbTurnout s = new OlcbTurnout("M", "1.2.3.4.5.6.7.8;1.2.3.4.5.6.7.9", t.iface); @@ -61,6 +62,7 @@ public void testIncomingChange() { Assert.assertTrue(s.getCommandedState() == Turnout.CLOSED); } + @Test public void testLocalChange() throws jmri.JmriException { // load dummy TrafficController OlcbTurnout s = new OlcbTurnout("M", "1.2.3.4.5.6.7.8;1.2.3.4.5.6.7.9", t.iface); @@ -97,6 +99,7 @@ public void testLocalChange() throws jmri.JmriException { Assert.assertTrue(new OlcbAddress("1.2.3.4.5.6.7.9").match(t.tc.rcvMessage)); } + @Test public void testDirectFeedback() throws jmri.JmriException { OlcbTurnout s = new OlcbTurnout("M", "1.2.3.4.5.6.7.8;1.2.3.4.5.6.7.9", t.iface); s.setFeedbackMode(Turnout.DIRECT); @@ -145,6 +148,7 @@ public void testDirectFeedback() throws jmri.JmriException { Assert.assertEquals("not called",0,l.getCallCount()); } + @Test public void testAuthoritative() throws jmri.JmriException { OlcbTurnout s = new OlcbTurnout("M", "1.2.3.4.5.6.7.8;1.2.3.4.5.6.7.9", t.iface); s.setFeedbackMode(Turnout.MONITORING); @@ -179,6 +183,7 @@ public void testAuthoritative() throws jmri.JmriException { Assert.assertEquals(expected, t.tc.rcvMessage); } + @Test public void testLoopback() throws jmri.JmriException { // Two turnouts behaving in opposite ways. One will be used to generate an event and the // other will be observed to make sure it catches it. @@ -203,6 +208,7 @@ public void testLoopback() throws jmri.JmriException { Assert.assertTrue(s.getCommandedState() == Turnout.CLOSED); } + @Test public void testForgetState() { OlcbTurnout s = new OlcbTurnout("M", "1.2.3.4.5.6.7.8;1.2.3.4.5.6.7.9", t.iface); s.setProperty(OlcbUtils.PROPERTY_LISTEN, Boolean.FALSE.toString()); @@ -226,7 +232,7 @@ public void testForgetState() { t.sendMessage(":X19544123N0102030405060709;"); Assert.assertEquals("not called",0,l.getCallCount()); l.resetPropertyChanged(); - assertEquals(Turnout.THROWN, s.getKnownState()); + Assert.assertEquals(Turnout.THROWN, s.getKnownState()); // Resets the turnout to unknown state s.setState(Turnout.UNKNOWN); @@ -243,7 +249,7 @@ public void testForgetState() { JUnitUtil.waitFor( () -> { return l.getPropertyChanged(); }); Assert.assertEquals("called twice",2,l.getCallCount()); l.resetPropertyChanged(); - assertEquals(Turnout.CLOSED, s.getKnownState()); + Assert.assertEquals(Turnout.CLOSED, s.getKnownState()); // state is reported as known (thrown==invalid) t.sendMessageAndExpectResponse(":X19914123N0102030405060708;", @@ -253,9 +259,10 @@ public void testForgetState() { t.sendMessage(":X19544123N0102030405060708;"); Assert.assertEquals("not called",0,l.getCallCount()); l.resetPropertyChanged(); - assertEquals(Turnout.CLOSED, s.getKnownState()); + Assert.assertEquals(Turnout.CLOSED, s.getKnownState()); } + @Test public void testQueryState() { OlcbTurnout s = new OlcbTurnout("M", "1.2.3.4.5.6.7.8;1.2.3.4.5.6.7.9", t.iface); s.finishLoad(); @@ -273,6 +280,7 @@ public void testQueryState() { t.assertNoSentMessages(); } + @Test public void testEventTable() { OlcbTurnout s = new OlcbTurnout("M", "1.2.3.4.5.6.7.8;1.2.3.4.5.6.7.9", t.iface); s.finishLoad(); @@ -298,6 +306,7 @@ public void testEventTable() { Assert.assertEquals("Turnout MySwitch Closed", elist[0].getDescription()); } + @Test public void testNameFormatXlower() { // load dummy TrafficController OlcbTurnout s = new OlcbTurnout("M", "x0501010114FF2000;x0501010114FF2001", t.iface); @@ -328,6 +337,7 @@ public void testNameFormatXlower() { } + @Test public void testNameFormatXupper() { // load dummy TrafficController OlcbTurnout s = new OlcbTurnout("M", "X0501010114FF2000;X0501010114FF2001", t.iface); @@ -358,6 +368,7 @@ public void testNameFormatXupper() { } + @Test public void testSystemSpecificComparisonOfSpecificFormats() { // test by putting into a tree set, then extracting and checking order @@ -376,28 +387,11 @@ public void testSystemSpecificComparisonOfSpecificFormats() { Assert.assertEquals("MTX0501010114FF2000;X0501010114FF2011", it.next().getSystemName()); } - // from here down is testing infrastructure - public OlcbTurnoutTest(String s) { - super(s); - } - - // Main entry point - static public void main(String[] args) { - String[] testCaseName = {OlcbTurnoutTest.class.getName()}; - junit.textui.TestRunner.main(testCaseName); - } - - // test suite from all defined tests - public static Test suite() { - TestSuite suite = new TestSuite(OlcbTurnoutTest.class); - return suite; - } - - OlcbTestInterface t; + private OlcbTestInterface t; // The minimal setup for log4J - @Override - protected void setUp() { + @Before + public void setUp() { JUnitUtil.setUp(); l = new PropertyChangeListenerScaffold(); @@ -406,9 +400,11 @@ protected void setUp() { t.waitForStartup(); } - @Override - protected void tearDown() { + @After + public void tearDown() { + l = null; t.dispose(); + t = null; JUnitUtil.tearDown(); } } From e502377f220e0aa34dc6797efa7f82ca5153504f Mon Sep 17 00:00:00 2001 From: Paul Bender Date: Fri, 6 Apr 2018 01:28:57 -0400 Subject: [PATCH 21/58] add thread to handle the dispose operation for the test interface, allowing other tests to proceed with new interfaces. --- java/test/jmri/jmrix/openlcb/OlcbTestInterface.java | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/java/test/jmri/jmrix/openlcb/OlcbTestInterface.java b/java/test/jmri/jmrix/openlcb/OlcbTestInterface.java index 03dbb6e540f..fef04da0835 100644 --- a/java/test/jmri/jmrix/openlcb/OlcbTestInterface.java +++ b/java/test/jmri/jmrix/openlcb/OlcbTestInterface.java @@ -152,7 +152,7 @@ public OlcbConfigurationManager createConfigurationManager() { public void dispose(){ // terminate the OlcbInterface (and terminate thread) - iface.dispose(); + new Thread(() -> { iface.dispose();},"OLCB Interface dispose thread").start(); } From b8cd5422048879ec029876ee98f1e5fa1299bcd4 Mon Sep 17 00:00:00 2001 From: Alain LM Date: Fri, 6 Apr 2018 07:38:03 +0200 Subject: [PATCH 22/58] Digitrax Economy Series 6: add BEMF --- xml/decoders/Digitrax_Economy_Series6.xml | 9 ++++++--- 1 file changed, 6 insertions(+), 3 deletions(-) diff --git a/xml/decoders/Digitrax_Economy_Series6.xml b/xml/decoders/Digitrax_Economy_Series6.xml index 60a7a293580..064188e9a5f 100644 --- a/xml/decoders/Digitrax_Economy_Series6.xml +++ b/xml/decoders/Digitrax_Economy_Series6.xml @@ -15,14 +15,17 @@ + - - + + + @@ -63,7 +66,7 @@ - + From 12c22675b54032899cec9eaa017aa389aab388e7 Mon Sep 17 00:00:00 2001 From: Egbert Broerse Date: Fri, 6 Apr 2018 09:12:30 +0200 Subject: [PATCH 23/58] add Direct simulator --- .../jmri/jmrix/direct/DirectBundle.properties | 1 + .../direct/DirectConnectionTypeList.java | 3 +- java/src/jmri/jmrix/direct/Message.java | 7 + java/src/jmri/jmrix/direct/Reply.java | 51 +++ .../jmri/jmrix/direct/ThrottleManager.java | 2 +- .../jmri/jmrix/direct/simulator/Bundle.java | 94 +++++ java/src/jmri/jmrix/direct/simulator/COPYING | 372 ++++++++++++++++++ .../direct/simulator/ConnectionConfig.java | 63 +++ .../direct/simulator/SimulatorAdapter.java | 335 ++++++++++++++++ .../direct/simulator/configurexml/COPYING | 372 ++++++++++++++++++ .../configurexml/ConnectionConfigXml.java | 44 +++ 11 files changed, 1342 insertions(+), 2 deletions(-) create mode 100644 java/src/jmri/jmrix/direct/Reply.java create mode 100644 java/src/jmri/jmrix/direct/simulator/Bundle.java create mode 100644 java/src/jmri/jmrix/direct/simulator/COPYING create mode 100644 java/src/jmri/jmrix/direct/simulator/ConnectionConfig.java create mode 100644 java/src/jmri/jmrix/direct/simulator/SimulatorAdapter.java create mode 100644 java/src/jmri/jmrix/direct/simulator/configurexml/COPYING create mode 100644 java/src/jmri/jmrix/direct/simulator/configurexml/ConnectionConfigXml.java diff --git a/java/src/jmri/jmrix/direct/DirectBundle.properties b/java/src/jmri/jmrix/direct/DirectBundle.properties index 0fffe5f83a1..27224d54205 100644 --- a/java/src/jmri/jmrix/direct/DirectBundle.properties +++ b/java/src/jmri/jmrix/direct/DirectBundle.properties @@ -4,6 +4,7 @@ MenuTitle = Direct MenuItemDirect = DirectDrive +DirectSimulatorName = DirectSim DirectBaudError = Failed to set the correct baud rate. Port is set to {0} baud.\n\ See the README file for more info. diff --git a/java/src/jmri/jmrix/direct/DirectConnectionTypeList.java b/java/src/jmri/jmrix/direct/DirectConnectionTypeList.java index 4607b63a74a..3582b1e47c5 100644 --- a/java/src/jmri/jmrix/direct/DirectConnectionTypeList.java +++ b/java/src/jmri/jmrix/direct/DirectConnectionTypeList.java @@ -17,7 +17,8 @@ public class DirectConnectionTypeList implements jmri.jmrix.ConnectionTypeList { @Override public String[] getAvailableProtocolClasses() { return new String[]{ - "jmri.jmrix.direct.serial.ConnectionConfig" + "jmri.jmrix.direct.serial.ConnectionConfig", + "jmri.jmrix.direct.simulator.ConnectionConfig" }; } diff --git a/java/src/jmri/jmrix/direct/Message.java b/java/src/jmri/jmrix/direct/Message.java index c168b9e0ad1..8b141139617 100644 --- a/java/src/jmri/jmrix/direct/Message.java +++ b/java/src/jmri/jmrix/direct/Message.java @@ -78,6 +78,7 @@ public boolean isEnableMain() { } // static methods to return a formatted message + static public Message getEnableMain() { log.error("getEnableMain doesn't have a reasonable implementation yet"); return null; @@ -163,6 +164,12 @@ private static String addIntAsThree(int val, Message m, int offset) { return s; } + // static methods to recognize a message + + public int getAddr() { + return getElement(0) & 0x7F; + } + private final static Logger log = LoggerFactory.getLogger(Message.class); } diff --git a/java/src/jmri/jmrix/direct/Reply.java b/java/src/jmri/jmrix/direct/Reply.java new file mode 100644 index 00000000000..9ff62cd9c2a --- /dev/null +++ b/java/src/jmri/jmrix/direct/Reply.java @@ -0,0 +1,51 @@ +package jmri.jmrix.direct; + +/** + * Contains the data payload of a serial reply packet. Note that _only_ the + * payload, not the header or trailer, nor the padding DLE characters are + * included. But it does include addressing characters, etc. + * + * @author Bob Jacobsen Copyright (C) 2002, 2008 + */ +public class Reply extends jmri.jmrix.AbstractMRReply { + + // create a new one + public Reply() { + super(); + } + + public Reply(String s) { + super(s); + } + + public Reply(Reply l) { + super(l); + } + + @Override + public String toString() { + StringBuilder s = new StringBuilder(""); + for (int i = 0; i < getNumDataElements(); i++) { + if (i != 0) { + s.append(" "); + } + if (getElement(i) < 16) { + s.append("0"); + } + s.append(Integer.toHexString(getElement(i) & 0xFF)); + } + return s.toString(); + } + + // recognize format + public boolean isRcv() { + return getElement(0) == 0x02; + } + + @Override + protected int skipPrefix(int index) { + // doesn't have to do anything + return index; + } + +} diff --git a/java/src/jmri/jmrix/direct/ThrottleManager.java b/java/src/jmri/jmrix/direct/ThrottleManager.java index 50c7d8adf9e..63ff680d6f4 100644 --- a/java/src/jmri/jmrix/direct/ThrottleManager.java +++ b/java/src/jmri/jmrix/direct/ThrottleManager.java @@ -24,7 +24,7 @@ public class ThrottleManager extends AbstractThrottleManager { private CommandStation tc = null; /** - * Constructor for a ThrottleManager. + * Constructor for a Direct ThrottleManager. */ public ThrottleManager(DirectSystemConnectionMemo memo) { super(memo); diff --git a/java/src/jmri/jmrix/direct/simulator/Bundle.java b/java/src/jmri/jmrix/direct/simulator/Bundle.java new file mode 100644 index 00000000000..22df6ed58d4 --- /dev/null +++ b/java/src/jmri/jmrix/direct/simulator/Bundle.java @@ -0,0 +1,94 @@ + +package jmri.jmrix.direct.simulator; + +import edu.umd.cs.findbugs.annotations.SuppressFBWarnings; +import java.util.Locale; +import javax.annotation.CheckReturnValue; +import javax.annotation.Nullable; +import javax.annotation.ParametersAreNonnullByDefault; + +@ParametersAreNonnullByDefault +@CheckReturnValue +@SuppressFBWarnings(value = "NM_SAME_SIMPLE_NAME_AS_SUPERCLASS",justification="Desired pattern is repeated class names with package-level access to members") + +@javax.annotation.concurrent.Immutable + +/** + * Provides standard access for resource bundles in a package. + * + * Convention is to provide a subclass of this name + * in each package, working off the local resource bundle name. + * + * @author Bob Jacobsen Copyright (C) 2012 + * @since 4.9.5 + */ +public class Bundle extends jmri.jmrix.direct.Bundle { + + @Nullable private static final String name = null; // No local resources + + // + // below here is boilerplate to be copied exactly + // + + /** + * Provides a translated string for a given + * key from the package resource bundle or + * parent. + *

+ * Note that this is intentionally package-local + * access. + * + * @param key Bundle key to be translated + * @return Internationalized text + */ + static String getMessage(String key) { + return getBundle().handleGetMessage(key); + } + /** + * Merges user data with a translated string for a given + * key from the package resource bundle or + * parent. + *

+ * Uses the transformation conventions of + * the Java MessageFormat utility. + *

+ * Note that this is intentionally package-local + * access. + * + * @see java.text.MessageFormat + * @param key Bundle key to be translated + * @param subs One or more objects to be inserted into the message + * @return Internationalized text + */ + static String getMessage(String key, Object ... subs) { + return getBundle().handleGetMessage(key, subs); + } + + /** + * Merges user data with a translated string for a given key in a given + * locale from the package resource bundle or parent. + *

+ * Uses the transformation conventions of the Java MessageFormat utility. + *

+ * Note that this is intentionally package-local access. + * + * @see java.text.MessageFormat + * @param locale The locale to be used + * @param key Bundle key to be translated + * @param subs One or more objects to be inserted into the message + * @return Internationalized text + */ + static String getMessage(Locale locale, String key, Object... subs) { + return getBundle().handleGetMessage(locale, key, subs); + } + + private final static Bundle b = new Bundle(); + @Override @Nullable protected String bundleName() {return name; } + protected static jmri.Bundle getBundle() { return b; } + + @Override + protected String retry(Locale locale,String key) { + return super.getBundle().handleGetMessage(locale,key); + } + +} diff --git a/java/src/jmri/jmrix/direct/simulator/COPYING b/java/src/jmri/jmrix/direct/simulator/COPYING new file mode 100644 index 00000000000..d93eaffc912 --- /dev/null +++ b/java/src/jmri/jmrix/direct/simulator/COPYING @@ -0,0 +1,372 @@ +JMRI is free software; you can redistribute it and/or modify it +under the terms of version 2 of the GNU General Public License as +published by the Free Software Foundation. + +JMRI is distributed in the hope that it will be useful, but +WITHOUT ANY WARRANTY; without even the implied warranty of +MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +GNU General Public License for more details. + +A copy of version 2 of the GNU General Public License is +appended below. For more information, see +. + +Linking JMRI or its parts statically or dynamically with other +modules is making a combined work based on this library. Thus, the +terms and conditions of the GNU General Public License 2.0 cover +the whole combination. + +As a special exception, the copyright holders of JMRI give you +permission to link JMRI with independent modules to produce an +executable, regardless of the license terms of these independent +modules, and to copy and distribute the resulting executable under +terms of your choice, provided that you also meet, for each linked +independent module, the terms and conditions of the license of that +module. An independent module is a module which is not derived from +or based on JMRI. If you modify JMRI, you may extend this exception +to your version of JMRI, but you are not obligated to do so. If you do +not wish to do so, delete this exception statement from your version. + + +------------------------------------------------------------------- + + GNU GENERAL PUBLIC LICENSE + Version 2, June 1991 + + Copyright (C) 1989, 1991 Free Software Foundation, Inc., + 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA + Everyone is permitted to copy and distribute verbatim copies + of this license document, but changing it is not allowed. + + Preamble + + The licenses for most software are designed to take away your +freedom to share and change it. By contrast, the GNU General Public +License is intended to guarantee your freedom to share and change free +software--to make sure the software is free for all its users. This +General Public License applies to most of the Free Software +Foundation's software and to any other program whose authors commit to +using it. (Some other Free Software Foundation software is covered by +the GNU Lesser General Public License instead.) You can apply it to +your programs, too. + + When we speak of free software, we are referring to freedom, not +price. Our General Public Licenses are designed to make sure that you +have the freedom to distribute copies of free software (and charge for +this service if you wish), that you receive source code or can get it +if you want it, that you can change the software or use pieces of it +in new free programs; and that you know you can do these things. + + To protect your rights, we need to make restrictions that forbid +anyone to deny you these rights or to ask you to surrender the rights. +These restrictions translate to certain responsibilities for you if you +distribute copies of the software, or if you modify it. + + For example, if you distribute copies of such a program, whether +gratis or for a fee, you must give the recipients all the rights that +you have. You must make sure that they, too, receive or can get the +source code. And you must show them these terms so they know their +rights. + + We protect your rights with two steps: (1) copyright the software, and +(2) offer you this license which gives you legal permission to copy, +distribute and/or modify the software. + + Also, for each author's protection and ours, we want to make certain +that everyone understands that there is no warranty for this free +software. If the software is modified by someone else and passed on, we +want its recipients to know that what they have is not the original, so +that any problems introduced by others will not reflect on the original +authors' reputations. + + Finally, any free program is threatened constantly by software +patents. We wish to avoid the danger that redistributors of a free +program will individually obtain patent licenses, in effect making the +program proprietary. To prevent this, we have made it clear that any +patent must be licensed for everyone's free use or not licensed at all. + + The precise terms and conditions for copying, distribution and +modification follow. + + GNU GENERAL PUBLIC LICENSE + TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION + + 0. This License applies to any program or other work which contains +a notice placed by the copyright holder saying it may be distributed +under the terms of this General Public License. The "Program", below, +refers to any such program or work, and a "work based on the Program" +means either the Program or any derivative work under copyright law: +that is to say, a work containing the Program or a portion of it, +either verbatim or with modifications and/or translated into another +language. (Hereinafter, translation is included without limitation in +the term "modification".) Each licensee is addressed as "you". + +Activities other than copying, distribution and modification are not +covered by this License; they are outside its scope. The act of +running the Program is not restricted, and the output from the Program +is covered only if its contents constitute a work based on the +Program (independent of having been made by running the Program). +Whether that is true depends on what the Program does. + + 1. You may copy and distribute verbatim copies of the Program's +source code as you receive it, in any medium, provided that you +conspicuously and appropriately publish on each copy an appropriate +copyright notice and disclaimer of warranty; keep intact all the +notices that refer to this License and to the absence of any warranty; +and give any other recipients of the Program a copy of this License +along with the Program. + +You may charge a fee for the physical act of transferring a copy, and +you may at your option offer warranty protection in exchange for a fee. + + 2. You may modify your copy or copies of the Program or any portion +of it, thus forming a work based on the Program, and copy and +distribute such modifications or work under the terms of Section 1 +above, provided that you also meet all of these conditions: + + a) You must cause the modified files to carry prominent notices + stating that you changed the files and the date of any change. + + b) You must cause any work that you distribute or publish, that in + whole or in part contains or is derived from the Program or any + part thereof, to be licensed as a whole at no charge to all third + parties under the terms of this License. + + c) If the modified program normally reads commands interactively + when run, you must cause it, when started running for such + interactive use in the most ordinary way, to print or display an + announcement including an appropriate copyright notice and a + notice that there is no warranty (or else, saying that you provide + a warranty) and that users may redistribute the program under + these conditions, and telling the user how to view a copy of this + License. (Exception: if the Program itself is interactive but + does not normally print such an announcement, your work based on + the Program is not required to print an announcement.) + +These requirements apply to the modified work as a whole. If +identifiable sections of that work are not derived from the Program, +and can be reasonably considered independent and separate works in +themselves, then this License, and its terms, do not apply to those +sections when you distribute them as separate works. But when you +distribute the same sections as part of a whole which is a work based +on the Program, the distribution of the whole must be on the terms of +this License, whose permissions for other licensees extend to the +entire whole, and thus to each and every part regardless of who wrote it. + +Thus, it is not the intent of this section to claim rights or contest +your rights to work written entirely by you; rather, the intent is to +exercise the right to control the distribution of derivative or +collective works based on the Program. + +In addition, mere aggregation of another work not based on the Program +with the Program (or with a work based on the Program) on a volume of +a storage or distribution medium does not bring the other work under +the scope of this License. + + 3. You may copy and distribute the Program (or a work based on it, +under Section 2) in object code or executable form under the terms of +Sections 1 and 2 above provided that you also do one of the following: + + a) Accompany it with the complete corresponding machine-readable + source code, which must be distributed under the terms of Sections + 1 and 2 above on a medium customarily used for software interchange; or, + + b) Accompany it with a written offer, valid for at least three + years, to give any third party, for a charge no more than your + cost of physically performing source distribution, a complete + machine-readable copy of the corresponding source code, to be + distributed under the terms of Sections 1 and 2 above on a medium + customarily used for software interchange; or, + + c) Accompany it with the information you received as to the offer + to distribute corresponding source code. (This alternative is + allowed only for noncommercial distribution and only if you + received the program in object code or executable form with such + an offer, in accord with Subsection b above.) + +The source code for a work means the preferred form of the work for +making modifications to it. For an executable work, complete source +code means all the source code for all modules it contains, plus any +associated interface definition files, plus the scripts used to +control compilation and installation of the executable. However, as a +special exception, the source code distributed need not include +anything that is normally distributed (in either source or binary +form) with the major components (compiler, kernel, and so on) of the +operating system on which the executable runs, unless that component +itself accompanies the executable. + +If distribution of executable or object code is made by offering +access to copy from a designated place, then offering equivalent +access to copy the source code from the same place counts as +distribution of the source code, even though third parties are not +compelled to copy the source along with the object code. + + 4. You may not copy, modify, sublicense, or distribute the Program +except as expressly provided under this License. Any attempt +otherwise to copy, modify, sublicense or distribute the Program is +void, and will automatically terminate your rights under this License. +However, parties who have received copies, or rights, from you under +this License will not have their licenses terminated so long as such +parties remain in full compliance. + + 5. You are not required to accept this License, since you have not +signed it. However, nothing else grants you permission to modify or +distribute the Program or its derivative works. These actions are +prohibited by law if you do not accept this License. Therefore, by +modifying or distributing the Program (or any work based on the +Program), you indicate your acceptance of this License to do so, and +all its terms and conditions for copying, distributing or modifying +the Program or works based on it. + + 6. Each time you redistribute the Program (or any work based on the +Program), the recipient automatically receives a license from the +original licensor to copy, distribute or modify the Program subject to +these terms and conditions. You may not impose any further +restrictions on the recipients' exercise of the rights granted herein. +You are not responsible for enforcing compliance by third parties to +this License. + + 7. If, as a consequence of a court judgment or allegation of patent +infringement or for any other reason (not limited to patent issues), +conditions are imposed on you (whether by court order, agreement or +otherwise) that contradict the conditions of this License, they do not +excuse you from the conditions of this License. If you cannot +distribute so as to satisfy simultaneously your obligations under this +License and any other pertinent obligations, then as a consequence you +may not distribute the Program at all. For example, if a patent +license would not permit royalty-free redistribution of the Program by +all those who receive copies directly or indirectly through you, then +the only way you could satisfy both it and this License would be to +refrain entirely from distribution of the Program. + +If any portion of this section is held invalid or unenforceable under +any particular circumstance, the balance of the section is intended to +apply and the section as a whole is intended to apply in other +circumstances. + +It is not the purpose of this section to induce you to infringe any +patents or other property right claims or to contest validity of any +such claims; this section has the sole purpose of protecting the +integrity of the free software distribution system, which is +implemented by public license practices. Many people have made +generous contributions to the wide range of software distributed +through that system in reliance on consistent application of that +system; it is up to the author/donor to decide if he or she is willing +to distribute software through any other system and a licensee cannot +impose that choice. + +This section is intended to make thoroughly clear what is believed to +be a consequence of the rest of this License. + + 8. If the distribution and/or use of the Program is restricted in +certain countries either by patents or by copyrighted interfaces, the +original copyright holder who places the Program under this License +may add an explicit geographical distribution limitation excluding +those countries, so that distribution is permitted only in or among +countries not thus excluded. In such case, this License incorporates +the limitation as if written in the body of this License. + + 9. The Free Software Foundation may publish revised and/or new versions +of the General Public License from time to time. Such new versions will +be similar in spirit to the present version, but may differ in detail to +address new problems or concerns. + +Each version is given a distinguishing version number. If the Program +specifies a version number of this License which applies to it and "any +later version", you have the option of following the terms and conditions +either of that version or of any later version published by the Free +Software Foundation. If the Program does not specify a version number of +this License, you may choose any version ever published by the Free Software +Foundation. + + 10. If you wish to incorporate parts of the Program into other free +programs whose distribution conditions are different, write to the author +to ask for permission. For software which is copyrighted by the Free +Software Foundation, write to the Free Software Foundation; we sometimes +make exceptions for this. Our decision will be guided by the two goals +of preserving the free status of all derivatives of our free software and +of promoting the sharing and reuse of software generally. + + NO WARRANTY + + 11. BECAUSE THE PROGRAM IS LICENSED FREE OF CHARGE, THERE IS NO WARRANTY +FOR THE PROGRAM, TO THE EXTENT PERMITTED BY APPLICABLE LAW. EXCEPT WHEN +OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR OTHER PARTIES +PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED +OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF +MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE ENTIRE RISK AS +TO THE QUALITY AND PERFORMANCE OF THE PROGRAM IS WITH YOU. SHOULD THE +PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF ALL NECESSARY SERVICING, +REPAIR OR CORRECTION. + + 12. IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING +WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MAY MODIFY AND/OR +REDISTRIBUTE THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, +INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING +OUT OF THE USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED +TO LOSS OF DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY +YOU OR THIRD PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER +PROGRAMS), EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE +POSSIBILITY OF SUCH DAMAGES. + + END OF TERMS AND CONDITIONS + + How to Apply These Terms to Your New Programs + + If you develop a new program, and you want it to be of the greatest +possible use to the public, the best way to achieve this is to make it +free software which everyone can redistribute and change under these terms. + + To do so, attach the following notices to the program. It is safest +to attach them to the start of each source file to most effectively +convey the exclusion of warranty; and each file should have at least +the "copyright" line and a pointer to where the full notice is found. + + + Copyright (C) + + This program is free software; you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation; either version 2 of the License, or + (at your option) any later version. + + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. + + You should have received a copy of the GNU General Public License along + with this program; if not, write to the Free Software Foundation, Inc., + 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. + +Also add information on how to contact you by electronic and paper mail. + +If the program is interactive, make it output a short notice like this +when it starts in an interactive mode: + + Gnomovision version 69, Copyright (C) year name of author + Gnomovision comes with ABSOLUTELY NO WARRANTY; for details type `show w'. + This is free software, and you are welcome to redistribute it + under certain conditions; type `show c' for details. + +The hypothetical commands `show w' and `show c' should show the appropriate +parts of the General Public License. Of course, the commands you use may +be called something other than `show w' and `show c'; they could even be +mouse-clicks or menu items--whatever suits your program. + +You should also get your employer (if you work as a programmer) or your +school, if any, to sign a "copyright disclaimer" for the program, if +necessary. Here is a sample; alter the names: + + Yoyodyne, Inc., hereby disclaims all copyright interest in the program + `Gnomovision' (which makes passes at compilers) written by James Hacker. + + , 1 April 1989 + Ty Coon, President of Vice + +This General Public License does not permit incorporating your program into +proprietary programs. If your program is a subroutine library, you may +consider it more useful to permit linking proprietary applications with the +library. If this is what you want to do, use the GNU Lesser General +Public License instead of this License. + diff --git a/java/src/jmri/jmrix/direct/simulator/ConnectionConfig.java b/java/src/jmri/jmrix/direct/simulator/ConnectionConfig.java new file mode 100644 index 00000000000..d7c2af02cdd --- /dev/null +++ b/java/src/jmri/jmrix/direct/simulator/ConnectionConfig.java @@ -0,0 +1,63 @@ +package jmri.jmrix.direct.simulator; + +import java.util.ResourceBundle; +import javax.swing.JButton; +import javax.swing.JPanel; +import jmri.jmrix.direct.DirectSystemConnectionMemo; + +/** + * Handle configuring an Direct layout connection via a Simulator + * adapter. + *

+ * This uses the {@link SimulatorAdapter} class to do the actual connection. + * + * @author Bob Jacobsen Copyright (C) 2001, 2003 + * @author Paul Bender Copyright (C) 2009 + * @author Mark Underwood Copyright (C) 2015 + * + * @see SimulatorAdapter + * + * Based on jmri.jmrix.lenz.xnetsimulator.ConnectionConfig, copied from EasyDCC + */ +public class ConnectionConfig extends jmri.jmrix.AbstractSimulatorConnectionConfig { + + /** + * Ctor for an object being created during load process; Swing init is + * deferred. + */ + public ConnectionConfig(jmri.jmrix.SerialPortAdapter p) { + super(p); + } + + /** + * Ctor for a functional Swing object with no prexisting adapter + */ + public ConnectionConfig() { + super(); + } + + @Override + public String name() { + return "Direct Simulator"; + } + + String manufacturerName = jmri.jmrix.direct.DirectConnectionTypeList.DIRECT; + + @Override + public String getManufacturer() { + return manufacturerName; + } + + @Override + public void setManufacturer(String manu) { + manufacturerName = manu; + } + + @Override + protected void setInstance() { + if (adapter == null) { + adapter = new SimulatorAdapter(); + } + } + +} diff --git a/java/src/jmri/jmrix/direct/simulator/SimulatorAdapter.java b/java/src/jmri/jmrix/direct/simulator/SimulatorAdapter.java new file mode 100644 index 00000000000..79b0807b537 --- /dev/null +++ b/java/src/jmri/jmrix/direct/simulator/SimulatorAdapter.java @@ -0,0 +1,335 @@ +package jmri.jmrix.direct.simulator; + +import java.io.DataInputStream; +import java.io.DataOutputStream; +import java.io.IOException; +import java.io.PipedInputStream; +import java.io.PipedOutputStream; +import javax.swing.JOptionPane; +import jmri.jmrix.direct.DirectSystemConnectionMemo; +import jmri.jmrix.direct.Message; +import jmri.jmrix.direct.PortController; // no special xSimulatorController +import jmri.jmrix.direct.Reply; +import jmri.jmrix.direct.TrafficController; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +/** + * Provide access to a simulated DirectDrive system. + *

+ * Currently, the Direct SimulatorAdapter reacts to the following commands sent from the user + * interface with an appropriate reply {@link #generateReply(Message)}: + *

    + *
  • N/A + *
+ * + * Based on jmri.jmrix.lenz.xnetsimulator.XNetSimulatorAdapter / EasyDCCSimulatorAdapter 2017 + *

+ * NOTE: Some material in this file was modified from other portions of the + * support infrastructure. + * + * @author Paul Bender, Copyright (C) 2009-2010 + * @author Mark Underwood, Copyright (C) 2015 + * @author Egbert Broerse, Copyright (C) 2018 + */ +public class SimulatorAdapter extends PortController implements jmri.jmrix.SerialPortAdapter, Runnable { + + // private control members + private boolean opened = false; + private Thread sourceThread; + + private boolean outputBufferEmpty = true; + private boolean checkBuffer = true; + + /** + * Create a new SimulatorAdapter. + */ + public SimulatorAdapter() { + super(new DirectSystemConnectionMemo("N", Bundle.getMessage("DirectSimulatorName"))); // pass customized user name + + setManufacturer(jmri.jmrix.direct.DirectConnectionTypeList.DIRECT); + } + + /** + * {@inheritDoc} + * Simulated input/output pipes. + */ + @Override + public String openPort(String portName, String appName) { + try { + PipedOutputStream tempPipeI = new PipedOutputStream(); + log.debug("tempPipeI created"); + pout = new DataOutputStream(tempPipeI); + inpipe = new DataInputStream(new PipedInputStream(tempPipeI)); + log.debug("inpipe created {}", inpipe != null); + PipedOutputStream tempPipeO = new PipedOutputStream(); + outpipe = new DataOutputStream(tempPipeO); + pin = new DataInputStream(new PipedInputStream(tempPipeO)); + } catch (java.io.IOException e) { + log.error("init (pipe): Exception: " + e.toString()); + } + opened = true; + return null; // indicates OK return + } + + /** + * Set if the output buffer is empty or full. This should only be set to + * false by external processes. + * + * @param s true if output buffer is empty; false otherwise + */ + synchronized public void setOutputBufferEmpty(boolean s) { + outputBufferEmpty = s; + } + + /** + * Can the port accept additional characters? The state of CTS determines + * this, as there seems to be no way to check the number of queued bytes and + * buffer length. This might go false for short intervals, but it might also + * stick off if something goes wrong. + * + * @return true if port can accept additional characters; false otherwise + */ + public boolean okToSend() { + if (checkBuffer) { + log.debug("Buffer Empty: " + outputBufferEmpty); + return (outputBufferEmpty); + } else { + log.debug("No Flow Control or Buffer Check"); + return (true); + } + } + + /** + * Set up all of the other objects to operate with a DirectSimulator + * connected to this port. + */ + @Override + public void configure() { + // connect to the traffic controller + TrafficController tc = new TrafficController((jmri.jmrix.direct.DirectSystemConnectionMemo)getSystemConnectionMemo()); + ((jmri.jmrix.direct.DirectSystemConnectionMemo)getSystemConnectionMemo()).setTrafficController(tc); + // connect to the traffic controller + tc.connectPort(this); + log.debug("set tc for memo {}", getSystemConnectionMemo().getUserName()); + + // do the common manager config + ((jmri.jmrix.direct.DirectSystemConnectionMemo)getSystemConnectionMemo()).configureManagers(); + + // start the simulator + sourceThread = new Thread(this); + sourceThread.setName("Direct Simulator"); + sourceThread.setPriority(Thread.MIN_PRIORITY); + sourceThread.start(); + } + + /** + * {@inheritDoc} + */ + @Override + public void connect() throws java.io.IOException { + log.debug("connect called"); + super.connect(); + } + + // Base class methods for the Direct SerialPortController simulated interface + + /** + * {@inheritDoc} + */ + @Override + public DataInputStream getInputStream() { + if (!opened || pin == null) { + log.error("getInputStream called before load(), stream not available"); + } + log.debug("DataInputStream pin returned"); + return pin; + } + + /** + * {@inheritDoc} + */ + @Override + public DataOutputStream getOutputStream() { + if (!opened || pout == null) { + log.error("getOutputStream called before load(), stream not available"); + } + log.debug("DataOutputStream pout returned"); + return pout; + } + + /** + * {@inheritDoc} + * @return always true, given this SimulatorAdapter is running + */ + @Override + public boolean status() { + return opened; + } + + /** + * Get an array of valid baud rates. + * + * @return null + */ + @Override + public String[] validBaudRates() { + log.debug("validBaudRates should not have been invoked"); + return null; + } + + @Override + public String getCurrentBaudRate() { + return ""; + } + + @Override + public void run() { // start a new thread + // This thread has one task. It repeatedly reads from the input pipe + // and writes an appropriate response to the output pipe. This is the heart + // of the Direct command station simulation. + log.info("Direct Simulator Started"); + while (true) { + try { + synchronized (this) { + wait(50); + } + } catch (InterruptedException e) { + log.debug("interrupted, ending"); + return; + } + Message m = readMessage(); + Reply r; + if (log.isDebugEnabled()) { + StringBuffer buf = new StringBuffer(); + buf.append("Direct Simulator Thread received message: "); + if (m != null) { + for (int i = 0; i < m.getNumDataElements(); i++) { + buf.append(Integer.toHexString(0xFF & m.getElement(i)) + " "); + } + } else { + buf.append("null message buffer"); + } + log.trace(buf.toString()); // generates a lot of traffic + } + if (m != null) { + r = generateReply(m); + if (r != null) { // ignore errors + writeReply(r); + if (log.isDebugEnabled()) { + StringBuffer buf = new StringBuffer(); + buf.append("Direct Simulator Thread sent reply: "); + for (int i = 0; i < r.getNumDataElements(); i++) { + buf.append(Integer.toHexString(0xFF & r.getElement(i)) + " "); + } + log.debug(buf.toString()); + } + } + } + } + } + + /** + * Read one incoming message from the buffer and set + * outputBufferEmpty to true. + */ + private Message readMessage() { + Message msg = null; + // log.debug("Simulator reading message"); + try { + if (inpipe != null && inpipe.available() > 0) { + msg = loadChars(); + } + } catch (java.io.IOException e) { + // should do something meaningful here. + } + setOutputBufferEmpty(true); + return (msg); + } + + /** + * This is the heart of the simulation. It translates an + * incoming Message into an outgoing Reply. + * + * @param msg the message received + * @return a single Direct message to confirm the requested operation. + * To ignore certain commands, return null. + */ + @SuppressWarnings("fallthrough") + private Reply generateReply(Message msg) { + log.debug("Generate Reply to message (string = {})", msg.toString()); + + Reply reply = new Reply(); // reply length is determined by highest byte added + int addr = msg.getAddr(); // address from element(0) + log.debug("Message address={}", addr); + + switch (addr) { // use a more meaningful key + + case 3: + reply.setElement(0, addr | 0x80); + reply.setElement(1, 0); // pretend speed 0 + // no parity + break; + + default: + reply = null; + } + log.debug(reply == null ? "Message ignored" : "Reply generated " + reply.toString()); + return (reply); + } + + /** + * Write reply to output. + *

+ * Adapted from jmri.jmrix.nce.simulator.SimulatorAdapter. + * + * @param r reply on message + */ + private void writeReply(Reply r) { + if (r == null) { + return; // there is no reply to be sent + } + for (int i = 0; i < r.getNumDataElements(); i++) { + try { + outpipe.writeByte((byte) r.getElement(i)); + } catch (java.io.IOException ex) { + } + } + try { + outpipe.flush(); + } catch (java.io.IOException ex) { + } + } + + /** + * Get characters from the input source. + *

+ * Only used in the Receive thread. + * + * @return filled message, only when the message is complete. + * @throws IOException when presented by the input source. + */ + private Message loadChars() throws java.io.IOException { + int nchars; + byte[] rcvBuffer = new byte[32]; + + nchars = inpipe.read(rcvBuffer, 0, 32); + //log.debug("new message received"); + Message msg = new Message(nchars); + + for (int i = 0; i < nchars; i++) { + msg.setElement(i, rcvBuffer[i] & 0xFF); + } + return msg; + } + + // streams to share with user class + private DataOutputStream pout = null; // this is provided to classes who want to write to us + private DataInputStream pin = null; // this is provided to classes who want data from us + // internal ends of the pipes + private DataOutputStream outpipe = null; // feed pin + private DataInputStream inpipe = null; // feed pout + + private final static Logger log = LoggerFactory.getLogger(SimulatorAdapter.class); + +} diff --git a/java/src/jmri/jmrix/direct/simulator/configurexml/COPYING b/java/src/jmri/jmrix/direct/simulator/configurexml/COPYING new file mode 100644 index 00000000000..d93eaffc912 --- /dev/null +++ b/java/src/jmri/jmrix/direct/simulator/configurexml/COPYING @@ -0,0 +1,372 @@ +JMRI is free software; you can redistribute it and/or modify it +under the terms of version 2 of the GNU General Public License as +published by the Free Software Foundation. + +JMRI is distributed in the hope that it will be useful, but +WITHOUT ANY WARRANTY; without even the implied warranty of +MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +GNU General Public License for more details. + +A copy of version 2 of the GNU General Public License is +appended below. For more information, see +. + +Linking JMRI or its parts statically or dynamically with other +modules is making a combined work based on this library. Thus, the +terms and conditions of the GNU General Public License 2.0 cover +the whole combination. + +As a special exception, the copyright holders of JMRI give you +permission to link JMRI with independent modules to produce an +executable, regardless of the license terms of these independent +modules, and to copy and distribute the resulting executable under +terms of your choice, provided that you also meet, for each linked +independent module, the terms and conditions of the license of that +module. An independent module is a module which is not derived from +or based on JMRI. If you modify JMRI, you may extend this exception +to your version of JMRI, but you are not obligated to do so. If you do +not wish to do so, delete this exception statement from your version. + + +------------------------------------------------------------------- + + GNU GENERAL PUBLIC LICENSE + Version 2, June 1991 + + Copyright (C) 1989, 1991 Free Software Foundation, Inc., + 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA + Everyone is permitted to copy and distribute verbatim copies + of this license document, but changing it is not allowed. + + Preamble + + The licenses for most software are designed to take away your +freedom to share and change it. By contrast, the GNU General Public +License is intended to guarantee your freedom to share and change free +software--to make sure the software is free for all its users. This +General Public License applies to most of the Free Software +Foundation's software and to any other program whose authors commit to +using it. (Some other Free Software Foundation software is covered by +the GNU Lesser General Public License instead.) You can apply it to +your programs, too. + + When we speak of free software, we are referring to freedom, not +price. Our General Public Licenses are designed to make sure that you +have the freedom to distribute copies of free software (and charge for +this service if you wish), that you receive source code or can get it +if you want it, that you can change the software or use pieces of it +in new free programs; and that you know you can do these things. + + To protect your rights, we need to make restrictions that forbid +anyone to deny you these rights or to ask you to surrender the rights. +These restrictions translate to certain responsibilities for you if you +distribute copies of the software, or if you modify it. + + For example, if you distribute copies of such a program, whether +gratis or for a fee, you must give the recipients all the rights that +you have. You must make sure that they, too, receive or can get the +source code. And you must show them these terms so they know their +rights. + + We protect your rights with two steps: (1) copyright the software, and +(2) offer you this license which gives you legal permission to copy, +distribute and/or modify the software. + + Also, for each author's protection and ours, we want to make certain +that everyone understands that there is no warranty for this free +software. If the software is modified by someone else and passed on, we +want its recipients to know that what they have is not the original, so +that any problems introduced by others will not reflect on the original +authors' reputations. + + Finally, any free program is threatened constantly by software +patents. We wish to avoid the danger that redistributors of a free +program will individually obtain patent licenses, in effect making the +program proprietary. To prevent this, we have made it clear that any +patent must be licensed for everyone's free use or not licensed at all. + + The precise terms and conditions for copying, distribution and +modification follow. + + GNU GENERAL PUBLIC LICENSE + TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION + + 0. This License applies to any program or other work which contains +a notice placed by the copyright holder saying it may be distributed +under the terms of this General Public License. The "Program", below, +refers to any such program or work, and a "work based on the Program" +means either the Program or any derivative work under copyright law: +that is to say, a work containing the Program or a portion of it, +either verbatim or with modifications and/or translated into another +language. (Hereinafter, translation is included without limitation in +the term "modification".) Each licensee is addressed as "you". + +Activities other than copying, distribution and modification are not +covered by this License; they are outside its scope. The act of +running the Program is not restricted, and the output from the Program +is covered only if its contents constitute a work based on the +Program (independent of having been made by running the Program). +Whether that is true depends on what the Program does. + + 1. You may copy and distribute verbatim copies of the Program's +source code as you receive it, in any medium, provided that you +conspicuously and appropriately publish on each copy an appropriate +copyright notice and disclaimer of warranty; keep intact all the +notices that refer to this License and to the absence of any warranty; +and give any other recipients of the Program a copy of this License +along with the Program. + +You may charge a fee for the physical act of transferring a copy, and +you may at your option offer warranty protection in exchange for a fee. + + 2. You may modify your copy or copies of the Program or any portion +of it, thus forming a work based on the Program, and copy and +distribute such modifications or work under the terms of Section 1 +above, provided that you also meet all of these conditions: + + a) You must cause the modified files to carry prominent notices + stating that you changed the files and the date of any change. + + b) You must cause any work that you distribute or publish, that in + whole or in part contains or is derived from the Program or any + part thereof, to be licensed as a whole at no charge to all third + parties under the terms of this License. + + c) If the modified program normally reads commands interactively + when run, you must cause it, when started running for such + interactive use in the most ordinary way, to print or display an + announcement including an appropriate copyright notice and a + notice that there is no warranty (or else, saying that you provide + a warranty) and that users may redistribute the program under + these conditions, and telling the user how to view a copy of this + License. (Exception: if the Program itself is interactive but + does not normally print such an announcement, your work based on + the Program is not required to print an announcement.) + +These requirements apply to the modified work as a whole. If +identifiable sections of that work are not derived from the Program, +and can be reasonably considered independent and separate works in +themselves, then this License, and its terms, do not apply to those +sections when you distribute them as separate works. But when you +distribute the same sections as part of a whole which is a work based +on the Program, the distribution of the whole must be on the terms of +this License, whose permissions for other licensees extend to the +entire whole, and thus to each and every part regardless of who wrote it. + +Thus, it is not the intent of this section to claim rights or contest +your rights to work written entirely by you; rather, the intent is to +exercise the right to control the distribution of derivative or +collective works based on the Program. + +In addition, mere aggregation of another work not based on the Program +with the Program (or with a work based on the Program) on a volume of +a storage or distribution medium does not bring the other work under +the scope of this License. + + 3. You may copy and distribute the Program (or a work based on it, +under Section 2) in object code or executable form under the terms of +Sections 1 and 2 above provided that you also do one of the following: + + a) Accompany it with the complete corresponding machine-readable + source code, which must be distributed under the terms of Sections + 1 and 2 above on a medium customarily used for software interchange; or, + + b) Accompany it with a written offer, valid for at least three + years, to give any third party, for a charge no more than your + cost of physically performing source distribution, a complete + machine-readable copy of the corresponding source code, to be + distributed under the terms of Sections 1 and 2 above on a medium + customarily used for software interchange; or, + + c) Accompany it with the information you received as to the offer + to distribute corresponding source code. (This alternative is + allowed only for noncommercial distribution and only if you + received the program in object code or executable form with such + an offer, in accord with Subsection b above.) + +The source code for a work means the preferred form of the work for +making modifications to it. For an executable work, complete source +code means all the source code for all modules it contains, plus any +associated interface definition files, plus the scripts used to +control compilation and installation of the executable. However, as a +special exception, the source code distributed need not include +anything that is normally distributed (in either source or binary +form) with the major components (compiler, kernel, and so on) of the +operating system on which the executable runs, unless that component +itself accompanies the executable. + +If distribution of executable or object code is made by offering +access to copy from a designated place, then offering equivalent +access to copy the source code from the same place counts as +distribution of the source code, even though third parties are not +compelled to copy the source along with the object code. + + 4. You may not copy, modify, sublicense, or distribute the Program +except as expressly provided under this License. Any attempt +otherwise to copy, modify, sublicense or distribute the Program is +void, and will automatically terminate your rights under this License. +However, parties who have received copies, or rights, from you under +this License will not have their licenses terminated so long as such +parties remain in full compliance. + + 5. You are not required to accept this License, since you have not +signed it. However, nothing else grants you permission to modify or +distribute the Program or its derivative works. These actions are +prohibited by law if you do not accept this License. Therefore, by +modifying or distributing the Program (or any work based on the +Program), you indicate your acceptance of this License to do so, and +all its terms and conditions for copying, distributing or modifying +the Program or works based on it. + + 6. Each time you redistribute the Program (or any work based on the +Program), the recipient automatically receives a license from the +original licensor to copy, distribute or modify the Program subject to +these terms and conditions. You may not impose any further +restrictions on the recipients' exercise of the rights granted herein. +You are not responsible for enforcing compliance by third parties to +this License. + + 7. If, as a consequence of a court judgment or allegation of patent +infringement or for any other reason (not limited to patent issues), +conditions are imposed on you (whether by court order, agreement or +otherwise) that contradict the conditions of this License, they do not +excuse you from the conditions of this License. If you cannot +distribute so as to satisfy simultaneously your obligations under this +License and any other pertinent obligations, then as a consequence you +may not distribute the Program at all. For example, if a patent +license would not permit royalty-free redistribution of the Program by +all those who receive copies directly or indirectly through you, then +the only way you could satisfy both it and this License would be to +refrain entirely from distribution of the Program. + +If any portion of this section is held invalid or unenforceable under +any particular circumstance, the balance of the section is intended to +apply and the section as a whole is intended to apply in other +circumstances. + +It is not the purpose of this section to induce you to infringe any +patents or other property right claims or to contest validity of any +such claims; this section has the sole purpose of protecting the +integrity of the free software distribution system, which is +implemented by public license practices. Many people have made +generous contributions to the wide range of software distributed +through that system in reliance on consistent application of that +system; it is up to the author/donor to decide if he or she is willing +to distribute software through any other system and a licensee cannot +impose that choice. + +This section is intended to make thoroughly clear what is believed to +be a consequence of the rest of this License. + + 8. If the distribution and/or use of the Program is restricted in +certain countries either by patents or by copyrighted interfaces, the +original copyright holder who places the Program under this License +may add an explicit geographical distribution limitation excluding +those countries, so that distribution is permitted only in or among +countries not thus excluded. In such case, this License incorporates +the limitation as if written in the body of this License. + + 9. The Free Software Foundation may publish revised and/or new versions +of the General Public License from time to time. Such new versions will +be similar in spirit to the present version, but may differ in detail to +address new problems or concerns. + +Each version is given a distinguishing version number. If the Program +specifies a version number of this License which applies to it and "any +later version", you have the option of following the terms and conditions +either of that version or of any later version published by the Free +Software Foundation. If the Program does not specify a version number of +this License, you may choose any version ever published by the Free Software +Foundation. + + 10. If you wish to incorporate parts of the Program into other free +programs whose distribution conditions are different, write to the author +to ask for permission. For software which is copyrighted by the Free +Software Foundation, write to the Free Software Foundation; we sometimes +make exceptions for this. Our decision will be guided by the two goals +of preserving the free status of all derivatives of our free software and +of promoting the sharing and reuse of software generally. + + NO WARRANTY + + 11. BECAUSE THE PROGRAM IS LICENSED FREE OF CHARGE, THERE IS NO WARRANTY +FOR THE PROGRAM, TO THE EXTENT PERMITTED BY APPLICABLE LAW. EXCEPT WHEN +OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR OTHER PARTIES +PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED +OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF +MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE ENTIRE RISK AS +TO THE QUALITY AND PERFORMANCE OF THE PROGRAM IS WITH YOU. SHOULD THE +PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF ALL NECESSARY SERVICING, +REPAIR OR CORRECTION. + + 12. IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING +WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MAY MODIFY AND/OR +REDISTRIBUTE THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, +INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING +OUT OF THE USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED +TO LOSS OF DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY +YOU OR THIRD PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER +PROGRAMS), EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE +POSSIBILITY OF SUCH DAMAGES. + + END OF TERMS AND CONDITIONS + + How to Apply These Terms to Your New Programs + + If you develop a new program, and you want it to be of the greatest +possible use to the public, the best way to achieve this is to make it +free software which everyone can redistribute and change under these terms. + + To do so, attach the following notices to the program. It is safest +to attach them to the start of each source file to most effectively +convey the exclusion of warranty; and each file should have at least +the "copyright" line and a pointer to where the full notice is found. + + + Copyright (C) + + This program is free software; you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation; either version 2 of the License, or + (at your option) any later version. + + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. + + You should have received a copy of the GNU General Public License along + with this program; if not, write to the Free Software Foundation, Inc., + 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. + +Also add information on how to contact you by electronic and paper mail. + +If the program is interactive, make it output a short notice like this +when it starts in an interactive mode: + + Gnomovision version 69, Copyright (C) year name of author + Gnomovision comes with ABSOLUTELY NO WARRANTY; for details type `show w'. + This is free software, and you are welcome to redistribute it + under certain conditions; type `show c' for details. + +The hypothetical commands `show w' and `show c' should show the appropriate +parts of the General Public License. Of course, the commands you use may +be called something other than `show w' and `show c'; they could even be +mouse-clicks or menu items--whatever suits your program. + +You should also get your employer (if you work as a programmer) or your +school, if any, to sign a "copyright disclaimer" for the program, if +necessary. Here is a sample; alter the names: + + Yoyodyne, Inc., hereby disclaims all copyright interest in the program + `Gnomovision' (which makes passes at compilers) written by James Hacker. + + , 1 April 1989 + Ty Coon, President of Vice + +This General Public License does not permit incorporating your program into +proprietary programs. If your program is a subroutine library, you may +consider it more useful to permit linking proprietary applications with the +library. If this is what you want to do, use the GNU Lesser General +Public License instead of this License. + diff --git a/java/src/jmri/jmrix/direct/simulator/configurexml/ConnectionConfigXml.java b/java/src/jmri/jmrix/direct/simulator/configurexml/ConnectionConfigXml.java new file mode 100644 index 00000000000..f3d2b66ccfe --- /dev/null +++ b/java/src/jmri/jmrix/direct/simulator/configurexml/ConnectionConfigXml.java @@ -0,0 +1,44 @@ +package jmri.jmrix.direct.simulator.configurexml; + +import jmri.jmrix.configurexml.AbstractSerialConnectionConfigXml; +import jmri.jmrix.direct.simulator.ConnectionConfig; +import jmri.jmrix.direct.simulator.SimulatorAdapter; + +/** + * Handle XML persistence of layout connections by persisting the + * SerialDriverAdapter (and connections). + *

+ * Note this is named as the XML version of a ConnectionConfig object, + * but it's actually persisting the SerialDriverAdapter. + *

+ * This class is invoked from jmrix.JmrixConfigPaneXml on write, as that class + * is the one actually registered. Reads are brought here directly via the class + * attribute in the XML. + * + * @author Bob Jacobsen Copyright (c) 2003 copied from NCE/Tams code + * @author kcameron Copyright (c) 2014 + */ +public class ConnectionConfigXml extends AbstractSerialConnectionConfigXml { + + public ConnectionConfigXml() { + super(); + } + + @Override + protected void getInstance(Object object) { + adapter = ((ConnectionConfig) object).getAdapter(); + } + + @Override + protected void getInstance() { + if (adapter == null) { + adapter = new SimulatorAdapter(); + } + } + + @Override + protected void register() { + this.register(new ConnectionConfig(adapter)); + } + +} From 2aea1b9589fd8897ba12a51118f532b4a03369d9 Mon Sep 17 00:00:00 2001 From: Egbert Broerse Date: Fri, 6 Apr 2018 11:14:31 +0200 Subject: [PATCH 24/58] add Direct tests --- .../jmri/jmrix/AbstractConnectionConfig.java | 1 + .../AbstractNetworkConnectionConfig.java | 33 ++++++------ .../AbstractSimulatorConnectionConfig.java | 12 ++--- .../jmrix/AbstractUsbConnectionConfig.java | 20 ++++---- java/src/jmri/jmrix/JmrixBundle.properties | 3 +- java/src/jmri/jmrix/JmrixBundle_nl.properties | 3 ++ java/src/jmri/jmrix/JmrixConfigPane.java | 11 ++-- .../jmri/jmrix/OtherConnectionTypeList.java | 11 ++-- .../jmri/jmrix/direct/DirectBundle.properties | 2 + .../jmrix/direct/DirectBundle_nl.properties | 3 ++ .../direct/DirectConnectionTypeList.java | 2 +- .../jmrix/direct/serial/ConnectionConfig.java | 4 +- .../direct/simulator/ConnectionConfig.java | 3 +- .../direct/simulator/SimulatorAdapter.java | 9 ++-- .../direct/swing/DirectComponentFactory.java | 2 +- .../jmrix/pi/RaspberryPiConnectionConfig.java | 4 +- .../jmrix/SystemConnectionMemoTestBase.java | 4 +- .../DirectSystemConnectionMemoTest.java | 7 +-- java/test/jmri/jmrix/direct/MessageTest.java | 2 +- java/test/jmri/jmrix/direct/PackageTest.java | 2 + java/test/jmri/jmrix/direct/ReplyTest.java | 34 +++++++++++++ .../jmrix/direct/ThrottleManagerTest.java | 8 +-- java/test/jmri/jmrix/direct/ThrottleTest.java | 11 ++-- .../jmrix/direct/TrafficControllerTest.java | 9 ++-- .../jmrix/direct/simulator/BundleTest.java | 50 +++++++++++++++++++ .../simulator/ConnectionConfigTest.java | 34 +++++++++++++ .../jmrix/direct/simulator/PackageTest.java | 23 +++++++++ .../simulator/SimulatorAdapterTest.java | 33 ++++++++++++ .../configurexml/ConnectionConfigXmlTest.java | 32 ++++++++++++ .../simulator/configurexml/PackageTest.java | 35 +++++++++++++ .../jmri/jmrix/sprog/SprogThrottleTest.java | 2 +- 31 files changed, 329 insertions(+), 80 deletions(-) create mode 100644 java/test/jmri/jmrix/direct/ReplyTest.java create mode 100644 java/test/jmri/jmrix/direct/simulator/BundleTest.java create mode 100644 java/test/jmri/jmrix/direct/simulator/ConnectionConfigTest.java create mode 100644 java/test/jmri/jmrix/direct/simulator/PackageTest.java create mode 100644 java/test/jmri/jmrix/direct/simulator/SimulatorAdapterTest.java create mode 100644 java/test/jmri/jmrix/direct/simulator/configurexml/ConnectionConfigXmlTest.java create mode 100644 java/test/jmri/jmrix/direct/simulator/configurexml/PackageTest.java diff --git a/java/src/jmri/jmrix/AbstractConnectionConfig.java b/java/src/jmri/jmrix/AbstractConnectionConfig.java index e03800495c1..f431b3b9568 100644 --- a/java/src/jmri/jmrix/AbstractConnectionConfig.java +++ b/java/src/jmri/jmrix/AbstractConnectionConfig.java @@ -248,4 +248,5 @@ public void dispose() { } private final static org.slf4j.Logger log = org.slf4j.LoggerFactory.getLogger(AbstractThrottle.class); + } diff --git a/java/src/jmri/jmrix/AbstractNetworkConnectionConfig.java b/java/src/jmri/jmrix/AbstractNetworkConnectionConfig.java index b1684517216..05227bb6e4c 100644 --- a/java/src/jmri/jmrix/AbstractNetworkConnectionConfig.java +++ b/java/src/jmri/jmrix/AbstractNetworkConnectionConfig.java @@ -11,7 +11,6 @@ import java.awt.event.ItemListener; import java.awt.event.KeyEvent; import java.awt.event.KeyListener; -import java.util.ResourceBundle; import javax.swing.JCheckBox; import javax.swing.JComboBox; import javax.swing.JComponent; @@ -31,8 +30,6 @@ */ abstract public class AbstractNetworkConnectionConfig extends AbstractConnectionConfig { - private final static ResourceBundle rb = ResourceBundle.getBundle("jmri.jmrix.JmrixBundle"); - /** * Create a connection configuration with a preexisting adapter. This is * used principally when loading a configuration that defines this @@ -56,9 +53,7 @@ public AbstractNetworkConnectionConfig() { @SuppressWarnings("unchecked") @Override protected void checkInitDone() { - if (log.isDebugEnabled()) { - log.debug("init called for " + name()); - } + log.debug("init called for {}", name()); if (init) { return; } @@ -175,7 +170,7 @@ public void actionPerformed(ActionEvent e) { @Override public void actionPerformed(ActionEvent e) { if (!adapter.getSystemConnectionMemo().setSystemPrefix(systemPrefixField.getText())) { - JOptionPane.showMessageDialog(null, "System Prefix " + systemPrefixField.getText() + " is already assigned"); + JOptionPane.showMessageDialog(null, Bundle.getMessage("ConnectionPrefixDialog", systemPrefixField.getText())); systemPrefixField.setValue(adapter.getSystemConnectionMemo().getSystemPrefix()); } } @@ -184,7 +179,7 @@ public void actionPerformed(ActionEvent e) { @Override public void focusLost(FocusEvent e) { if (!adapter.getSystemConnectionMemo().setSystemPrefix(systemPrefixField.getText())) { - JOptionPane.showMessageDialog(null, "System Prefix " + systemPrefixField.getText() + " is already assigned"); + JOptionPane.showMessageDialog(null, Bundle.getMessage("ConnectionPrefixDialog", systemPrefixField.getText())); systemPrefixField.setValue(adapter.getSystemConnectionMemo().getSystemPrefix()); } } @@ -197,7 +192,7 @@ public void focusGained(FocusEvent e) { @Override public void actionPerformed(ActionEvent e) { if (!adapter.getSystemConnectionMemo().setUserName(connectionNameField.getText())) { - JOptionPane.showMessageDialog(null, "Connection Name " + connectionNameField.getText() + " is already assigned"); + JOptionPane.showMessageDialog(null, Bundle.getMessage("ConnectionNameDialog", connectionNameField.getText())); connectionNameField.setText(adapter.getSystemConnectionMemo().getUserName()); } } @@ -206,7 +201,7 @@ public void actionPerformed(ActionEvent e) { @Override public void focusLost(FocusEvent e) { if (!adapter.getSystemConnectionMemo().setUserName(connectionNameField.getText())) { - JOptionPane.showMessageDialog(null, "Connection Name " + connectionNameField.getText() + " is already assigned"); + JOptionPane.showMessageDialog(null, Bundle.getMessage("ConnectionNameDialog", connectionNameField.getText())); connectionNameField.setText(adapter.getSystemConnectionMemo().getUserName()); } } @@ -256,7 +251,7 @@ public void updateAdapter() { protected JTextField portField = new JTextField(10); protected JLabel portFieldLabel; - protected JCheckBox showAutoConfig = new JCheckBox(rb.getString("AutoConfigLabel")); + protected JCheckBox showAutoConfig = new JCheckBox(Bundle.getMessage("AutoConfigLabel")); protected JTextField adNameField = new JTextField(15); protected JLabel adNameFieldLabel; protected JTextField serviceTypeField = new JTextField(15); @@ -317,28 +312,28 @@ public void loadDetails(final JPanel details) { NUMOPTIONS = NUMOPTIONS + options.size(); hostNameField.setText(adapter.getHostName()); - hostNameFieldLabel = new JLabel(rb.getString("HostFieldLabel")); - hostNameField.setToolTipText(rb.getString("HostFieldToolTip")); + hostNameFieldLabel = new JLabel(Bundle.getMessage("HostFieldLabel")); + hostNameField.setToolTipText(Bundle.getMessage("HostFieldToolTip")); if (adapter.getHostName() == null || adapter.getHostName().equals("")) { hostNameField.setText(p.getComboBoxLastSelection(adapter.getClass().getName() + ".hostname")); adapter.setHostName(hostNameField.getText()); } - portField.setToolTipText(rb.getString("PortFieldToolTip")); + portField.setToolTipText(Bundle.getMessage("PortFieldToolTip")); portField.setEnabled(true); portField.setText("" + adapter.getPort()); - portFieldLabel = new JLabel(rb.getString("PortFieldLabel")); + portFieldLabel = new JLabel(Bundle.getMessage("PortFieldLabel")); - adNameField.setToolTipText(rb.getString("AdNameFieldToolTip")); + adNameField.setToolTipText(Bundle.getMessage("AdNameFieldToolTip")); adNameField.setEnabled(false); adNameField.setText("" + adapter.getAdvertisementName()); - adNameFieldLabel = new JLabel(rb.getString("AdNameFieldLabel")); + adNameFieldLabel = new JLabel(Bundle.getMessage("AdNameFieldLabel")); adNameFieldLabel.setEnabled(false); - serviceTypeField.setToolTipText(rb.getString("ServiceTypeFieldToolTip")); + serviceTypeField.setToolTipText(Bundle.getMessage("ServiceTypeFieldToolTip")); serviceTypeField.setEnabled(false); serviceTypeField.setText("" + adapter.getServiceType()); - serviceTypeFieldLabel = new JLabel(rb.getString("ServiceTypeFieldLabel")); + serviceTypeFieldLabel = new JLabel(Bundle.getMessage("ServiceTypeFieldLabel")); serviceTypeFieldLabel.setEnabled(false); showAutoConfig.setFont(showAutoConfig.getFont().deriveFont(9f)); diff --git a/java/src/jmri/jmrix/AbstractSimulatorConnectionConfig.java b/java/src/jmri/jmrix/AbstractSimulatorConnectionConfig.java index 885c10fabe6..5cbe795ed06 100644 --- a/java/src/jmri/jmrix/AbstractSimulatorConnectionConfig.java +++ b/java/src/jmri/jmrix/AbstractSimulatorConnectionConfig.java @@ -57,9 +57,7 @@ public AbstractSimulatorConnectionConfig() { @SuppressWarnings("unchecked") @Override protected void checkInitDone() { - if (log.isDebugEnabled()) { - log.debug("init called for " + name()); - } + log.debug("init called for ()", name()); if (init) { return; } @@ -69,7 +67,7 @@ protected void checkInitDone() { @Override public void actionPerformed(ActionEvent e) { if (!adapter.getSystemConnectionMemo().setSystemPrefix(systemPrefixField.getText())) { - JOptionPane.showMessageDialog(null, "System Prefix " + systemPrefixField.getText() + " is already assigned"); + JOptionPane.showMessageDialog(null, Bundle.getMessage("ConnectionPrefixDialog", systemPrefixField.getText())); systemPrefixField.setValue(adapter.getSystemConnectionMemo().getSystemPrefix()); } } @@ -78,7 +76,7 @@ public void actionPerformed(ActionEvent e) { @Override public void focusLost(FocusEvent e) { if (!adapter.getSystemConnectionMemo().setSystemPrefix(systemPrefixField.getText())) { - JOptionPane.showMessageDialog(null, "System Prefix " + systemPrefixField.getText() + " is already assigned"); + JOptionPane.showMessageDialog(null, Bundle.getMessage("ConnectionPrefixDialog", systemPrefixField.getText())); systemPrefixField.setValue(adapter.getSystemConnectionMemo().getSystemPrefix()); } } @@ -91,7 +89,7 @@ public void focusGained(FocusEvent e) { @Override public void actionPerformed(ActionEvent e) { if (!adapter.getSystemConnectionMemo().setUserName(connectionNameField.getText())) { - JOptionPane.showMessageDialog(null, "Connection Name " + connectionNameField.getText() + " is already assigned"); + JOptionPane.showMessageDialog(null, Bundle.getMessage("ConnectionNameDialog", connectionNameField.getText())); connectionNameField.setText(adapter.getSystemConnectionMemo().getUserName()); } } @@ -100,7 +98,7 @@ public void actionPerformed(ActionEvent e) { @Override public void focusLost(FocusEvent e) { if (!adapter.getSystemConnectionMemo().setUserName(connectionNameField.getText())) { - JOptionPane.showMessageDialog(null, "Connection Name " + connectionNameField.getText() + " is already assigned"); + JOptionPane.showMessageDialog(null, Bundle.getMessage("ConnectionNameDialog", connectionNameField.getText())); connectionNameField.setText(adapter.getSystemConnectionMemo().getUserName()); } } diff --git a/java/src/jmri/jmrix/AbstractUsbConnectionConfig.java b/java/src/jmri/jmrix/AbstractUsbConnectionConfig.java index 9d7338bb9c6..72938d7c55b 100644 --- a/java/src/jmri/jmrix/AbstractUsbConnectionConfig.java +++ b/java/src/jmri/jmrix/AbstractUsbConnectionConfig.java @@ -131,8 +131,8 @@ public void focusLost(FocusEvent e) { } } init = true; - } // if (!init) - } // checkInitDone() + } + } @Override public void updateAdapter() { @@ -184,8 +184,8 @@ public void refreshPortBox() { return; } - /* as we make amendments to the list of port in newList, we keep a copy of it before - modification, this copy is then used to validate against any changes in the port lists. + /* As we make amendments to the list of ports in newList, we keep a copy of it before + modification. This copy is then used to validate against any changes in the port lists. */ originalList = new ArrayList<>(newList); if (portBox.getActionListeners().length > 0) { @@ -216,7 +216,7 @@ public void refreshPortBox() { updateUsbPortNames(portName, portBox, newList); - // If there's no name selected, select one that seems most likely + // If no name is selected, select one that seems most likely boolean didSetName = false; if ((portName == null) || portName.equals(Bundle.getMessage("noneSelected")) @@ -279,11 +279,11 @@ public void loadDetails(final JPanel details) { try { newList = getPortNames(); if (log.isDebugEnabled()) { - log.debug("loadDetails called in class " + this.getClass().getName()); - log.debug("adapter class: " + adapter.getClass().getName()); - log.debug("loadDetails called for " + name()); + log.debug("loadDetails called in class {}", this.getClass().getName()); + log.debug("adapter class: {}", adapter.getClass().getName()); + log.debug("loadDetails called for {}", name()); if (newList != null) { - log.debug("Found " + newList.size() + " ports"); + log.debug("Found {} ports", newList.size()); } else { log.debug("Zero-length port List"); } @@ -291,7 +291,7 @@ public void loadDetails(final JPanel details) { } catch (UnsatisfiedLinkError e1) { log.error("UnsatisfiedLinkError - the serial library has not been installed properly"); log.error("java.library.path=" + System.getProperty("java.library.path", "")); - JOptionPane.showMessageDialog(null, "Failed to load comm library.\nYou have to fix that before setting preferences."); + JOptionPane.showMessageDialog(null, Bundle.getMessage("ErrorComLibLoad")); return; } diff --git a/java/src/jmri/jmrix/JmrixBundle.properties b/java/src/jmri/jmrix/JmrixBundle.properties index d7d465a95c4..5e12ed7d152 100644 --- a/java/src/jmri/jmrix/JmrixBundle.properties +++ b/java/src/jmri/jmrix/JmrixBundle.properties @@ -57,7 +57,7 @@ Settings = Settings TypeSerial = Serial TypeUSB = USB SerialPortLabel = Serial port: -UsbPortLocationLabel = Usb Port Location: +UsbPortLocationLabel = USB Port Location: BaudRateLabel = Baud rate: CommunicationPortLabel = Communication Port: #FlowControlTitle = Flow Control @@ -179,6 +179,7 @@ SerialPortInUse = Serial port {0} is in use. #Wrap an exception's description in html and indent ErrorSubException =     {0} ErrorConnectionTitle = Connection failed +ErrorComLibLoad = Failed to load comm library.\nYou have to fix that before setting preferences. # Manager error items, some in NamedBeanBundle #ErrorConvertAddressX = Unable to convert {0} Hardware Address to a number diff --git a/java/src/jmri/jmrix/JmrixBundle_nl.properties b/java/src/jmri/jmrix/JmrixBundle_nl.properties index 2c32321a864..ca49e473e38 100644 --- a/java/src/jmri/jmrix/JmrixBundle_nl.properties +++ b/java/src/jmri/jmrix/JmrixBundle_nl.properties @@ -65,6 +65,7 @@ BaudRateLabel = Baud rate (snelheid): # generic connection type description TypeSerial = Seri\u00eble SerialPortLabel = Seri\u00eble poort: +UsbPortLocationLabel = USB-poort: #FlowControl items FlowOptionNo = geen flow control FlowOptionHw = hardware flow control @@ -170,6 +171,8 @@ SerialPortNotFound = Seri\u00eble poort {0} niet gevonden. SerialPortInUse = Seri\u00eble poort {0} is bezet. #Wrap an expection's description in html and indent ErrorSubException =     {0} +ErrorConnectionTitle = Verbinding mislukt +ErrorComLibLoad = Laden van comm library mislukt.\nLos dit probleem op voordat u Voorkeuren instelt. # Manager error items, some in NamedBeanBundle #ErrorConvertAddressX = Unable to convert {0} Hardware Address to a number diff --git a/java/src/jmri/jmrix/JmrixConfigPane.java b/java/src/jmri/jmrix/JmrixConfigPane.java index 69ebf95dcbf..96d5b25f629 100644 --- a/java/src/jmri/jmrix/JmrixConfigPane.java +++ b/java/src/jmri/jmrix/JmrixConfigPane.java @@ -19,19 +19,18 @@ /** * Provide GUI to configure communications links. - *

+ *

* This is really just a catalog of connections to classes within the systems. * Reflection is used to reduce coupling at load time. - *

+ *

* Objects of this class are based on an underlying ConnectionConfig * implementation, which in turn is obtained from the InstanceManager. Those * must be created at load time by the ConfigXml process, or in some Application * class. - *

+ *

* The classes referenced are the specific subclasses of * {@link jmri.jmrix.ConnectionConfig} which provides the methods providing data * to the configuration GUI, and responding to its changes. - *

* * @author Bob Jacobsen Copyright (C) 2001, 2003, 2004, 2010 */ @@ -47,7 +46,7 @@ public class JmrixConfigPane extends JPanel implements PreferencesPanel { /** * Get access to a pane describing existing configuration information, or * create one if needed. - *

+ *

* The index argument is used to connect the new pane to the right * communications info. A value of "1" means the first (primary) port, 2 is * the second, etc. @@ -161,7 +160,7 @@ public static void dispose(JmrixConfigPane confPane) { try { confPane.ccCurrent.dispose(); } catch (RuntimeException ex) { - log.error("Error Occured while disposing connection {}", ex.toString()); + log.error("Error Occurred while disposing connection {}", ex.toString()); } } ConfigureManager cmOD = InstanceManager.getNullableDefault(jmri.ConfigureManager.class); diff --git a/java/src/jmri/jmrix/OtherConnectionTypeList.java b/java/src/jmri/jmrix/OtherConnectionTypeList.java index 9d9595b16d8..cb92de8c402 100644 --- a/java/src/jmri/jmrix/OtherConnectionTypeList.java +++ b/java/src/jmri/jmrix/OtherConnectionTypeList.java @@ -3,21 +3,22 @@ import org.openide.util.lookup.ServiceProvider; /** - * Returns a list of valid Connection Types - *

+ * Return a list of valid Connection Types. + * @see jmri.jmrix.direct.DirectConnectionTypeList + * * @author Bob Jacobsen Copyright (C) 2010 * @author Kevin Dickerson Copyright (C) 2010 - * */ @ServiceProvider(service = ConnectionTypeList.class) public class OtherConnectionTypeList implements jmri.jmrix.ConnectionTypeList { - public static final String OTHER = "Others"; + public static final String OTHER = "Others"; // NOI18N @Override public String[] getAvailableProtocolClasses() { return new String[]{ - "jmri.jmrix.direct.serial.ConnectionConfig" + "jmri.jmrix.direct.serial.ConnectionConfig", + "jmri.jmrix.direct.simulator.ConnectionConfig" }; } diff --git a/java/src/jmri/jmrix/direct/DirectBundle.properties b/java/src/jmri/jmrix/direct/DirectBundle.properties index 27224d54205..db4df173282 100644 --- a/java/src/jmri/jmrix/direct/DirectBundle.properties +++ b/java/src/jmri/jmrix/direct/DirectBundle.properties @@ -5,6 +5,8 @@ MenuTitle = Direct MenuItemDirect = DirectDrive DirectSimulatorName = DirectSim +DirectSerialName = Direct Drive (Serial) +DirectSerialNameNot = (Direct Drive (Serial) not available) DirectBaudError = Failed to set the correct baud rate. Port is set to {0} baud.\n\ See the README file for more info. diff --git a/java/src/jmri/jmrix/direct/DirectBundle_nl.properties b/java/src/jmri/jmrix/direct/DirectBundle_nl.properties index 79df5a26c3f..f72ec85ce6b 100644 --- a/java/src/jmri/jmrix/direct/DirectBundle_nl.properties +++ b/java/src/jmri/jmrix/direct/DirectBundle_nl.properties @@ -4,6 +4,9 @@ MenuTitle = Direct MenuItemDirect = DirectDrive +DirectSimulatorName = DirectSim +DirectSerialName = Direct Drive (Serieel) +DirectSerialNameNot = (Direct Drive (Serieel) niet beschikbaar) DirectBaudError = Instellen van juiste baud snelheid mislukt. Poort ingesteld op {0} baud.\n\ Bekijk het README bestand voor meer info info. diff --git a/java/src/jmri/jmrix/direct/DirectConnectionTypeList.java b/java/src/jmri/jmrix/direct/DirectConnectionTypeList.java index 3582b1e47c5..d1dba73dd6d 100644 --- a/java/src/jmri/jmrix/direct/DirectConnectionTypeList.java +++ b/java/src/jmri/jmrix/direct/DirectConnectionTypeList.java @@ -12,7 +12,7 @@ @ServiceProvider(service = ConnectionTypeList.class) public class DirectConnectionTypeList implements jmri.jmrix.ConnectionTypeList { - public static final String DIRECT = "Others"; + public static final String DIRECT = "Others"; // NOI18N @Override public String[] getAvailableProtocolClasses() { diff --git a/java/src/jmri/jmrix/direct/serial/ConnectionConfig.java b/java/src/jmri/jmrix/direct/serial/ConnectionConfig.java index 2c5a9095841..feedbc52b53 100644 --- a/java/src/jmri/jmrix/direct/serial/ConnectionConfig.java +++ b/java/src/jmri/jmrix/direct/serial/ConnectionConfig.java @@ -29,10 +29,10 @@ public ConnectionConfig() { public String name() { if (SystemType.isMacOSX() || (SystemType.isWindows() && Double.valueOf(System.getProperty("os.version")) >= 6)) { - return "(Direct Drive (Serial) not available)"; + return Bundle.getMessage("DirectSerialNameNot"); } - return "Direct Drive (Serial)"; + return Bundle.getMessage("DirectSerialName"); } @Override diff --git a/java/src/jmri/jmrix/direct/simulator/ConnectionConfig.java b/java/src/jmri/jmrix/direct/simulator/ConnectionConfig.java index d7c2af02cdd..ff2cf0e18d8 100644 --- a/java/src/jmri/jmrix/direct/simulator/ConnectionConfig.java +++ b/java/src/jmri/jmrix/direct/simulator/ConnectionConfig.java @@ -1,6 +1,5 @@ package jmri.jmrix.direct.simulator; -import java.util.ResourceBundle; import javax.swing.JButton; import javax.swing.JPanel; import jmri.jmrix.direct.DirectSystemConnectionMemo; @@ -38,7 +37,7 @@ public ConnectionConfig() { @Override public String name() { - return "Direct Simulator"; + return Bundle.getMessage("DirectSimulatorName"); } String manufacturerName = jmri.jmrix.direct.DirectConnectionTypeList.DIRECT; diff --git a/java/src/jmri/jmrix/direct/simulator/SimulatorAdapter.java b/java/src/jmri/jmrix/direct/simulator/SimulatorAdapter.java index 79b0807b537..a555d653aad 100644 --- a/java/src/jmri/jmrix/direct/simulator/SimulatorAdapter.java +++ b/java/src/jmri/jmrix/direct/simulator/SimulatorAdapter.java @@ -5,7 +5,6 @@ import java.io.IOException; import java.io.PipedInputStream; import java.io.PipedOutputStream; -import javax.swing.JOptionPane; import jmri.jmrix.direct.DirectSystemConnectionMemo; import jmri.jmrix.direct.Message; import jmri.jmrix.direct.PortController; // no special xSimulatorController @@ -66,7 +65,7 @@ public String openPort(String portName, String appName) { outpipe = new DataOutputStream(tempPipeO); pin = new DataInputStream(new PipedInputStream(tempPipeO)); } catch (java.io.IOException e) { - log.error("init (pipe): Exception: " + e.toString()); + log.error("init (pipe): Exception: {}", e.toString()); } opened = true; return null; // indicates OK return @@ -92,7 +91,7 @@ synchronized public void setOutputBufferEmpty(boolean s) { */ public boolean okToSend() { if (checkBuffer) { - log.debug("Buffer Empty: " + outputBufferEmpty); + log.debug("Buffer Empty: {}", outputBufferEmpty); return (outputBufferEmpty); } else { log.debug("No Flow Control or Buffer Check"); @@ -118,7 +117,7 @@ public void configure() { // start the simulator sourceThread = new Thread(this); - sourceThread.setName("Direct Simulator"); + sourceThread.setName("Direct Simulator"); // NOI18N sourceThread.setPriority(Thread.MIN_PRIORITY); sourceThread.start(); } @@ -314,7 +313,7 @@ private Message loadChars() throws java.io.IOException { byte[] rcvBuffer = new byte[32]; nchars = inpipe.read(rcvBuffer, 0, 32); - //log.debug("new message received"); + log.debug("new message received"); Message msg = new Message(nchars); for (int i = 0; i < nchars; i++) { diff --git a/java/src/jmri/jmrix/direct/swing/DirectComponentFactory.java b/java/src/jmri/jmrix/direct/swing/DirectComponentFactory.java index d62913b0ae7..285b242f8bb 100644 --- a/java/src/jmri/jmrix/direct/swing/DirectComponentFactory.java +++ b/java/src/jmri/jmrix/direct/swing/DirectComponentFactory.java @@ -19,7 +19,7 @@ public DirectComponentFactory(DirectSystemConnectionMemo memo) { DirectSystemConnectionMemo memo; /** - * Provide a menu with all items attached to this system connection. + * Provide a menu with all (in this case: no) items attached to this system connection. */ @Override public javax.swing.JMenu getMenu() { diff --git a/java/src/jmri/jmrix/pi/RaspberryPiConnectionConfig.java b/java/src/jmri/jmrix/pi/RaspberryPiConnectionConfig.java index c8e79fc88b2..9b4750bb036 100644 --- a/java/src/jmri/jmrix/pi/RaspberryPiConnectionConfig.java +++ b/java/src/jmri/jmrix/pi/RaspberryPiConnectionConfig.java @@ -75,7 +75,7 @@ public void focusGained(FocusEvent e) { }); connectionNameField.addActionListener((ActionEvent e) -> { if (!adapter.getSystemConnectionMemo().setUserName(connectionNameField.getText())) { - JOptionPane.showMessageDialog(null, "Connection Name " + connectionNameField.getText() + " is already assigned"); + JOptionPane.showMessageDialog(null, Bundle.getMessage("ConnectionNameDialog", connectionNameField.getText())); connectionNameField.setText(adapter.getSystemConnectionMemo().getUserName()); } }); @@ -83,7 +83,7 @@ public void focusGained(FocusEvent e) { @Override public void focusLost(FocusEvent e) { if (!adapter.getSystemConnectionMemo().setUserName(connectionNameField.getText())) { - JOptionPane.showMessageDialog(null, "Connection Name " + connectionNameField.getText() + " is already assigned"); + JOptionPane.showMessageDialog(null, Bundle.getMessage("ConnectionNameDialog", connectionNameField.getText())); connectionNameField.setText(adapter.getSystemConnectionMemo().getUserName()); } } diff --git a/java/test/jmri/jmrix/SystemConnectionMemoTestBase.java b/java/test/jmri/jmrix/SystemConnectionMemoTestBase.java index 70986db48b2..eca016abde2 100644 --- a/java/test/jmri/jmrix/SystemConnectionMemoTestBase.java +++ b/java/test/jmri/jmrix/SystemConnectionMemoTestBase.java @@ -18,9 +18,9 @@ abstract public class SystemConnectionMemoTestBase { public void getTest(Class t){ if(scm.provides(t)){ // if the manager reports providing the class, make sure it exists. - Assert.assertNotNull("Provides Class " + t.getName() ,scm.get(t)); + Assert.assertNotNull("Provides Class " + t.getName(), scm.get(t)); } else { - Assert.assertNull("Provides Class " + t.getName() ,scm.get(t)); + Assert.assertNull("Provides Class " + t.getName(), scm.get(t)); } } diff --git a/java/test/jmri/jmrix/direct/DirectSystemConnectionMemoTest.java b/java/test/jmri/jmrix/direct/DirectSystemConnectionMemoTest.java index 995076705c8..6ed5357aefa 100644 --- a/java/test/jmri/jmrix/direct/DirectSystemConnectionMemoTest.java +++ b/java/test/jmri/jmrix/direct/DirectSystemConnectionMemoTest.java @@ -6,12 +6,13 @@ /** * JUnit tests for the DirectSystemConnectionMemo class - *

* - * @author Paul Bender Copyright (C) 2016 + * @author Paul Bender Copyright (C) 2016 */ public class DirectSystemConnectionMemoTest extends jmri.jmrix.SystemConnectionMemoTestBase { - + + // Ctor etc are tested in MemoTestBase + @Override @Before public void setUp(){ diff --git a/java/test/jmri/jmrix/direct/MessageTest.java b/java/test/jmri/jmrix/direct/MessageTest.java index e24c22ea80b..c87920d2a5e 100644 --- a/java/test/jmri/jmrix/direct/MessageTest.java +++ b/java/test/jmri/jmrix/direct/MessageTest.java @@ -15,7 +15,7 @@ public class MessageTest { @Test public void testCTor() { Message t = new Message(5); - Assert.assertNotNull("exists",t); + Assert.assertNotNull("exists", t); } // The minimal setup for log4J diff --git a/java/test/jmri/jmrix/direct/PackageTest.java b/java/test/jmri/jmrix/direct/PackageTest.java index f1ff059a0b7..36249da3ffb 100644 --- a/java/test/jmri/jmrix/direct/PackageTest.java +++ b/java/test/jmri/jmrix/direct/PackageTest.java @@ -14,8 +14,10 @@ ThrottleManagerTest.class, ThrottleTest.class, MessageTest.class, + ReplyTest.class, jmri.jmrix.direct.swing.PackageTest.class, DirectSystemConnectionMemoTest.class, + jmri.jmrix.direct.simulator.PackageTest.class, }) /** diff --git a/java/test/jmri/jmrix/direct/ReplyTest.java b/java/test/jmri/jmrix/direct/ReplyTest.java new file mode 100644 index 00000000000..8fbdc92bb45 --- /dev/null +++ b/java/test/jmri/jmrix/direct/ReplyTest.java @@ -0,0 +1,34 @@ +package jmri.jmrix.direct; + +import jmri.util.JUnitUtil; +import org.junit.After; +import org.junit.Assert; +import org.junit.Before; +import org.junit.Test; + +/** + * + * @author Paul Bender Copyright (C) 2017 + */ +public class ReplyTest { + + @Test + public void testCTor() { + Reply t = new Reply(); + Assert.assertNotNull("exists", t); + } + + // The minimal setup for log4J + @Before + public void setUp() { + JUnitUtil.setUp(); + } + + @After + public void tearDown() { + JUnitUtil.tearDown(); + } + + // private final static Logger log = LoggerFactory.getLogger(ReplyTest.class); + +} diff --git a/java/test/jmri/jmrix/direct/ThrottleManagerTest.java b/java/test/jmri/jmrix/direct/ThrottleManagerTest.java index 8245af95c13..9c021ac68e7 100644 --- a/java/test/jmri/jmrix/direct/ThrottleManagerTest.java +++ b/java/test/jmri/jmrix/direct/ThrottleManagerTest.java @@ -14,16 +14,16 @@ public class ThrottleManagerTest extends jmri.managers.AbstractThrottleManagerTe @Test public void testCTor() { - Assert.assertNotNull("exists",tm); + Assert.assertNotNull("exists", tm); } // The minimal setup for log4J @Before public void setUp() { JUnitUtil.setUp(); - JUnitUtil.initDebugCommandStation(); - jmri.CommandStation cs = jmri.InstanceManager.getDefault(jmri.CommandStation.class); - tm = new ThrottleManager(cs); + + DirectSystemConnectionMemo m = new DirectSystemConnectionMemo(); + tm = new ThrottleManager(m); } @After diff --git a/java/test/jmri/jmrix/direct/ThrottleTest.java b/java/test/jmri/jmrix/direct/ThrottleTest.java index f881614330f..b8671243a4f 100644 --- a/java/test/jmri/jmrix/direct/ThrottleTest.java +++ b/java/test/jmri/jmrix/direct/ThrottleTest.java @@ -14,7 +14,7 @@ public class ThrottleTest extends jmri.jmrix.AbstractThrottleTest { @Test public void testCTor() { - Assert.assertNotNull("exists",instance); + Assert.assertNotNull("exists", instance); } /** @@ -356,15 +356,18 @@ public void testSendFunctionGroup4() { public void testSendFunctionGroup5() { } - // The minimal setup for log4J @Before public void setUp() { JUnitUtil.setUp(); JUnitUtil.initDebugCommandStation(); + + // prepare an interface + DirectSystemConnectionMemo m = new DirectSystemConnectionMemo(); + jmri.CommandStation cs = jmri.InstanceManager.getDefault(jmri.CommandStation.class); - jmri.InstanceManager.setDefault(jmri.ThrottleManager.class,new ThrottleManager(cs)); - instance = new Throttle(5,cs); + jmri.InstanceManager.setDefault(jmri.ThrottleManager.class, new ThrottleManager(m)); + instance = new Throttle(new jmri.DccLocoAddress(5, false), cs); } @After diff --git a/java/test/jmri/jmrix/direct/TrafficControllerTest.java b/java/test/jmri/jmrix/direct/TrafficControllerTest.java index c126591272d..d8089f45fb4 100644 --- a/java/test/jmri/jmrix/direct/TrafficControllerTest.java +++ b/java/test/jmri/jmrix/direct/TrafficControllerTest.java @@ -8,9 +8,8 @@ /** * JUnit tests for the TrafficController class - *

* - * @author Paul Bender Copyright (C) 2016 + * @author Paul Bender Copyright (C) 2016 */ public class TrafficControllerTest { @@ -18,13 +17,15 @@ public class TrafficControllerTest { @Test public void testCtor(){ - Assert.assertNotNull("exists",tc); + Assert.assertNotNull("exists", tc); } @Before public void setUp(){ JUnitUtil.setUp(); - tc = new TrafficController(); + + DirectSystemConnectionMemo m = new DirectSystemConnectionMemo(); + tc = new TrafficController(m); } @After diff --git a/java/test/jmri/jmrix/direct/simulator/BundleTest.java b/java/test/jmri/jmrix/direct/simulator/BundleTest.java new file mode 100644 index 00000000000..ce35be98677 --- /dev/null +++ b/java/test/jmri/jmrix/direct/simulator/BundleTest.java @@ -0,0 +1,50 @@ +package jmri.jmrix.direct.simulator; + +import java.util.Locale; +import org.junit.Assert; +import org.junit.Test; + +/** + * Tests for the Bundle class. + * + * @author Bob Jacobsen Copyright (C) 2012 + */ +public class BundleTest { + + @Test public void testGoodKeyMessage() { + Assert.assertEquals("Turnout", Bundle.getMessage("BeanNameTurnout")); + } + + @Test public void testBadKeyMessage() { + try { + Bundle.getMessage("FFFFFTTTTTTT"); + } catch (java.util.MissingResourceException e) { + return; + } // OK + Assert.fail("No exception thrown"); + } + + @Test public void testGoodKeyMessageArg() { + Assert.assertEquals("Turnout", Bundle.getMessage("BeanNameTurnout", new Object[]{})); + Assert.assertEquals("About Test", Bundle.getMessage("TitleAbout", "Test")); + } + + @Test public void testBadKeyMessageArg() { + try { + Bundle.getMessage("FFFFFTTTTTTT", new Object[]{}); + } catch (java.util.MissingResourceException e) { + return; + } // OK + Assert.fail("No exception thrown"); + } + + @Test public void testLocaleMessage() { + Assert.assertEquals("Scambio", Bundle.getMessage(Locale.ITALY, "BeanNameTurnout")); + } + + @Test public void testLocaleMessageArg() { + Assert.assertEquals("Scambio", Bundle.getMessage(Locale.ITALY, "BeanNameTurnout", new Object[]{})); + Assert.assertEquals("Informazioni su Test", Bundle.getMessage(Locale.ITALY, "TitleAbout", "Test")); + } + +} diff --git a/java/test/jmri/jmrix/direct/simulator/ConnectionConfigTest.java b/java/test/jmri/jmrix/direct/simulator/ConnectionConfigTest.java new file mode 100644 index 00000000000..683e388422b --- /dev/null +++ b/java/test/jmri/jmrix/direct/simulator/ConnectionConfigTest.java @@ -0,0 +1,34 @@ +package jmri.jmrix.direct.simulator; + +import jmri.util.JUnitUtil; +import org.junit.After; +import org.junit.Assert; +import org.junit.Before; +import org.junit.Test; + +/** + * Tests for ConnectionConfig class. + * + * @author Paul Bender Copyright (C) 2016 + **/ + +public class ConnectionConfigTest { + + @Test + public void ConstructorTest(){ + Assert.assertNotNull("ConnectionConfig constructor", new ConnectionConfig()); + } + + @Before + public void setUp() { + JUnitUtil.setUp(); + + jmri.util.JUnitUtil.initDefaultUserMessagePreferences(); + } + + @After + public void tearDown(){ + JUnitUtil.tearDown(); + } + +} diff --git a/java/test/jmri/jmrix/direct/simulator/PackageTest.java b/java/test/jmri/jmrix/direct/simulator/PackageTest.java new file mode 100644 index 00000000000..1fd705df020 --- /dev/null +++ b/java/test/jmri/jmrix/direct/simulator/PackageTest.java @@ -0,0 +1,23 @@ +package jmri.jmrix.direct.simulator; + +import org.junit.runner.RunWith; +import org.junit.runners.Suite; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + + +@RunWith(Suite.class) +@Suite.SuiteClasses({ + ConnectionConfigTest.class, + SimulatorAdapterTest.class, + jmri.jmrix.direct.simulator.configurexml.PackageTest.class, + BundleTest.class, +}) +/** + * Tests for the jmri.jmrix.grapevine.simulator package. + * + * @author Paul Bender Copyright (C) 2016 + */ +public class PackageTest { + +} diff --git a/java/test/jmri/jmrix/direct/simulator/SimulatorAdapterTest.java b/java/test/jmri/jmrix/direct/simulator/SimulatorAdapterTest.java new file mode 100644 index 00000000000..2c25999f2d0 --- /dev/null +++ b/java/test/jmri/jmrix/direct/simulator/SimulatorAdapterTest.java @@ -0,0 +1,33 @@ +package jmri.jmrix.direct.simulator; + +import jmri.util.JUnitUtil; +import org.junit.After; +import org.junit.Assert; +import org.junit.Before; +import org.junit.Test; + +/** + * Tests for SimulatorAdapter class. + * + * @author Paul Bender Copyright (C) 2016 + */ +public class SimulatorAdapterTest { + + @Test + public void ConstructorTest(){ + Assert.assertNotNull("SimulatorAdapter constructor", new SimulatorAdapter()); + } + + @Before + public void setUp() { + JUnitUtil.setUp(); + + jmri.util.JUnitUtil.initDefaultUserMessagePreferences(); + } + + @After + public void tearDown(){ + JUnitUtil.tearDown(); + } + +} diff --git a/java/test/jmri/jmrix/direct/simulator/configurexml/ConnectionConfigXmlTest.java b/java/test/jmri/jmrix/direct/simulator/configurexml/ConnectionConfigXmlTest.java new file mode 100644 index 00000000000..c8b9a50b883 --- /dev/null +++ b/java/test/jmri/jmrix/direct/simulator/configurexml/ConnectionConfigXmlTest.java @@ -0,0 +1,32 @@ +package jmri.jmrix.direct.simulator.configurexml; + +import jmri.util.JUnitUtil; +import org.junit.After; +import org.junit.Assert; +import org.junit.Before; +import org.junit.Test; + +/** + * Tests for the ConnectionConfigXml class + * + * @author Paul Bender Copyright (C) 2016 + */ +public class ConnectionConfigXmlTest { + + @Test + public void testCtor(){ + Assert.assertNotNull("ConnectionConfigXml constructor", new ConnectionConfigXml()); + } + + // The minimal setup for log4J + @Before + public void setUp() { + JUnitUtil.setUp(); + } + + @After + public void tearDown() { + JUnitUtil.tearDown(); + } + +} diff --git a/java/test/jmri/jmrix/direct/simulator/configurexml/PackageTest.java b/java/test/jmri/jmrix/direct/simulator/configurexml/PackageTest.java new file mode 100644 index 00000000000..e1eb6ad5aa9 --- /dev/null +++ b/java/test/jmri/jmrix/direct/simulator/configurexml/PackageTest.java @@ -0,0 +1,35 @@ +package jmri.jmrix.direct.simulator.configurexml; + +import org.junit.runner.RunWith; +import org.junit.runners.Suite; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + + +@RunWith(Suite.class) +@Suite.SuiteClasses({ + ConnectionConfigXmlTest.class +}) +/** + * Tests for the jmri.jmrix.direct.simulator.configurexml package. + * + * @author Paul Bender Copyright (C) 2016 + */ +public class PackageTest { + + // Main entry point + static public void main(String[] args) { + org.junit.runner.Result result = org.junit.runner.JUnitCore + .runClasses(PackageTest.class); + for(org.junit.runner.notification.Failure fail: result.getFailures()) { + log.error(fail.toString()); + } + //junit.textui.TestRunner.main(testCaseName); + if (result.wasSuccessful()) { + log.info("Success"); + } + } + + private final static Logger log = LoggerFactory.getLogger(PackageTest.class); + +} diff --git a/java/test/jmri/jmrix/sprog/SprogThrottleTest.java b/java/test/jmri/jmrix/sprog/SprogThrottleTest.java index 2d41d520e3a..f9710caaeca 100644 --- a/java/test/jmri/jmrix/sprog/SprogThrottleTest.java +++ b/java/test/jmri/jmrix/sprog/SprogThrottleTest.java @@ -373,7 +373,7 @@ public void setUp() { m.setSprogTrafficController(stcs); m.configureCommandStation(); jmri.InstanceManager.setDefault(jmri.ThrottleManager.class,new SprogThrottleManager(m)); - instance = new SprogThrottle(m,new jmri.DccLocoAddress(2,false)); + instance = new SprogThrottle(m, new jmri.DccLocoAddress(2,false)); } @After From eb28be043b584bda517857d5a9ba656d238cbd1e Mon Sep 17 00:00:00 2001 From: Bob Jacobsen Date: Fri, 6 Apr 2018 06:55:43 -0700 Subject: [PATCH 25/58] unused var warning --- java/test/jmri/ManagerTest.java | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/java/test/jmri/ManagerTest.java b/java/test/jmri/ManagerTest.java index 81ca350ea66..6a53a0b9b7a 100644 --- a/java/test/jmri/ManagerTest.java +++ b/java/test/jmri/ManagerTest.java @@ -130,7 +130,7 @@ public void checkTreeMap() { NamedBean n3 = new BogusBean("BB3"); NamedBean n4 = new BogusBean("BB4"); NamedBean n5 = new BogusBean("BB5"); - NamedBean n6 = new BogusBean("BB5"); + new BogusBean("BB5"); // created, but not used directly TreeSet set1 = new TreeSet<>(); From fae741da24267ec615cb6ae0777d0be92363b5e1 Mon Sep 17 00:00:00 2001 From: Bob Jacobsen Date: Fri, 6 Apr 2018 06:55:54 -0700 Subject: [PATCH 26/58] type-safety --- java/src/jmri/managers/AbstractManager.java | 6 +++--- java/src/jmri/managers/AbstractProxyManager.java | 6 +++--- 2 files changed, 6 insertions(+), 6 deletions(-) diff --git a/java/src/jmri/managers/AbstractManager.java b/java/src/jmri/managers/AbstractManager.java index eca2b6d5d28..33249e2ed03 100644 --- a/java/src/jmri/managers/AbstractManager.java +++ b/java/src/jmri/managers/AbstractManager.java @@ -526,7 +526,7 @@ public void setDataListenerMute(boolean m) { if (muted && !m) { // send a total update, as we haven't kept track of specifics ManagerDataEvent e = new ManagerDataEvent(this, ManagerDataEvent.CONTENTS_CHANGED, 0, getObjectCount()-1, null); - for (ManagerDataListener listener : listeners) { + for (ManagerDataListener listener : listeners) { listener.contentsChanged(e); } } @@ -536,14 +536,14 @@ public void setDataListenerMute(boolean m) { protected void fireDataListenersAdded(int start, int end, E changedBean) { if (muted) return; ManagerDataEvent e = new ManagerDataEvent(this, ManagerDataEvent.INTERVAL_ADDED, start, end, changedBean); - for (ManagerDataListener m : listeners) { + for (ManagerDataListener m : listeners) { m.intervalAdded(e); } } protected void fireDataListenersRemoved(int start, int end, E changedBean) { if (muted) return; ManagerDataEvent e = new ManagerDataEvent(this, ManagerDataEvent.INTERVAL_REMOVED, start, end, changedBean); - for (ManagerDataListener m : listeners) { + for (ManagerDataListener m : listeners) { m.intervalRemoved(e); } } diff --git a/java/src/jmri/managers/AbstractProxyManager.java b/java/src/jmri/managers/AbstractProxyManager.java index c5ff4572f28..482627a10fb 100644 --- a/java/src/jmri/managers/AbstractProxyManager.java +++ b/java/src/jmri/managers/AbstractProxyManager.java @@ -560,7 +560,7 @@ public void intervalAdded(AbstractProxyManager.ManagerDataEvent e) { ManagerDataEvent eOut = new ManagerDataEvent(this, Manager.ManagerDataEvent.INTERVAL_ADDED, e.getIndex0()+offset, e.getIndex1()+offset, e.getChangedBean()); - for (ManagerDataListener m : listeners) { + for (ManagerDataListener m : listeners) { m.intervalAdded(eOut); } } @@ -585,7 +585,7 @@ public void intervalRemoved(AbstractProxyManager.ManagerDataEvent e) { ManagerDataEvent eOut = new ManagerDataEvent(this, Manager.ManagerDataEvent.INTERVAL_REMOVED, e.getIndex0()+offset, e.getIndex1()+offset, e.getChangedBean()); - for (ManagerDataListener m : listeners) { + for (ManagerDataListener m : listeners) { m.intervalRemoved(eOut); } } @@ -596,7 +596,7 @@ public void setDataListenerMute(boolean m) { if (muted && !m) { // send a total update, as we haven't kept track of specifics ManagerDataEvent e = new ManagerDataEvent(this, ManagerDataEvent.CONTENTS_CHANGED, 0, getObjectCount()-1, null); - for (ManagerDataListener listener : listeners) { + for (ManagerDataListener listener : listeners) { listener.contentsChanged(e); } } From 1a680875f27d5545fdc982de14d558a91563b6c9 Mon Sep 17 00:00:00 2001 From: Bob Jacobsen Date: Fri, 6 Apr 2018 07:01:04 -0700 Subject: [PATCH 27/58] remove improper equals operator --- java/src/jmri/managers/AbstractProxyManager.java | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/java/src/jmri/managers/AbstractProxyManager.java b/java/src/jmri/managers/AbstractProxyManager.java index 482627a10fb..8c427c76f7a 100644 --- a/java/src/jmri/managers/AbstractProxyManager.java +++ b/java/src/jmri/managers/AbstractProxyManager.java @@ -134,8 +134,8 @@ private Manager initInternal() { } private final IndexedTreeSet> mgrs = new IndexedTreeSet<>(new java.util.Comparator>(){ + @Override public int compare(Manager e1, Manager e2) { return e1.getSystemPrefix().compareTo(e2.getSystemPrefix()); } - public boolean equals(Manager e1, Manager e2) { return e1.getSystemPrefix().equals(e2.getSystemPrefix()); } }); private Manager internalManager = null; private Manager defaultManager = null; From 8ae4c65b26088c7a6aed40857cfd1bc0d26d8629 Mon Sep 17 00:00:00 2001 From: Egbert Broerse Date: Fri, 6 Apr 2018 21:29:46 +0200 Subject: [PATCH 28/58] Fix Jenkins errors, remove unused vars --- java/src/jmri/jmrix/grapevine/SerialTrafficController.java | 1 - java/src/jmri/jmrix/oaktree/SerialTrafficController.java | 3 --- java/src/jmri/jmrix/oaktree/simulator/SimulatorAdapter.java | 4 ---- java/src/jmri/jmrix/secsi/SerialAddress.java | 6 +++--- java/src/jmri/jmrix/secsi/SerialReply.java | 4 +--- java/src/jmri/jmrix/secsi/SerialTrafficController.java | 4 +--- java/src/jmri/jmrix/secsi/simulator/SimulatorAdapter.java | 4 ---- java/src/jmri/jmrix/sprog/simulator/SimulatorAdapter.java | 3 --- .../jmri/jmrix/grapevine/SerialTrafficControlScaffold.java | 4 ---- java/test/jmri/jmrix/oaktree/OakTreeMenuTest.java | 2 +- java/test/jmri/jmrix/oaktree/SerialAddressTest.java | 2 +- .../jmri/jmrix/oaktree/SerialTrafficControlScaffold.java | 4 ---- java/test/jmri/jmrix/oaktree/SerialTurnoutManagerTest.java | 2 +- .../jmrix/oaktree/packetgen/SerialPacketGenActionTest.java | 2 +- .../jmrix/oaktree/swing/OakTreeComponentFactoryTest.java | 2 +- java/test/jmri/jmrix/secsi/SerialLightTest.java | 2 +- java/test/jmri/jmrix/secsi/SerialSensorTest.java | 4 ++-- .../test/jmri/jmrix/secsi/SerialTrafficControlScaffold.java | 6 +++--- java/test/jmri/jmrix/secsi/SerialTurnoutTest.java | 2 +- 19 files changed, 17 insertions(+), 44 deletions(-) diff --git a/java/src/jmri/jmrix/grapevine/SerialTrafficController.java b/java/src/jmri/jmrix/grapevine/SerialTrafficController.java index aff5221dd96..8d44ea33965 100644 --- a/java/src/jmri/jmrix/grapevine/SerialTrafficController.java +++ b/java/src/jmri/jmrix/grapevine/SerialTrafficController.java @@ -247,7 +247,6 @@ static public SerialTrafficController instance() { @Override @Deprecated protected void setInstance() { - self = this; } /** diff --git a/java/src/jmri/jmrix/oaktree/SerialTrafficController.java b/java/src/jmri/jmrix/oaktree/SerialTrafficController.java index 3b0d69914f0..b9a1939e03d 100644 --- a/java/src/jmri/jmrix/oaktree/SerialTrafficController.java +++ b/java/src/jmri/jmrix/oaktree/SerialTrafficController.java @@ -200,14 +200,11 @@ static public SerialTrafficController instance() { return null; } - static volatile protected SerialTrafficController self = null; - @SuppressFBWarnings(value = "ST_WRITE_TO_STATIC_FROM_INSTANCE_METHOD", justification = "temporary until multi-system; only set at startup") @Override @Deprecated protected void setInstance() { - self = this; } /** diff --git a/java/src/jmri/jmrix/oaktree/simulator/SimulatorAdapter.java b/java/src/jmri/jmrix/oaktree/simulator/SimulatorAdapter.java index c32e62463a6..d5ee9b8f89c 100644 --- a/java/src/jmri/jmrix/oaktree/simulator/SimulatorAdapter.java +++ b/java/src/jmri/jmrix/oaktree/simulator/SimulatorAdapter.java @@ -40,10 +40,6 @@ public class SimulatorAdapter extends SerialPortController implements jmri.jmrix private boolean outputBufferEmpty = true; private boolean checkBuffer = true; - /** - * Simulator auto-init setting for number of banks to auto-reply on poll - */ - private int autoInit = 0; /** * Create a new SimulatorAdapter. diff --git a/java/src/jmri/jmrix/secsi/SerialAddress.java b/java/src/jmri/jmrix/secsi/SerialAddress.java index b4b174a6e6c..ea589046d0a 100644 --- a/java/src/jmri/jmrix/secsi/SerialAddress.java +++ b/java/src/jmri/jmrix/secsi/SerialAddress.java @@ -160,7 +160,7 @@ public static NameValidity validSystemNameFormat(String systemName, char type, S String s = ""; int k = 0; boolean noB = true; - for (int i = i = prefix.length() + 1; (i < systemName.length()) && noB; i++) { + for (int i = prefix.length() + 1; (i < systemName.length()) && noB; i++) { if (systemName.charAt(i) == 'B') { s = systemName.substring(prefix.length() + 1, i); k = i + 1; @@ -177,7 +177,7 @@ public static NameValidity validSystemNameFormat(String systemName, char type, S return NameValidity.INVALID; } if ((num < 1) || (num >= 128000)) { - log.warn("number field out of range in system name: {}", systemName); + log.debug("number field out of range in system name: {}", systemName); return NameValidity.INVALID; } if ((num - ((num / 1000) * 1000)) == 0) { @@ -277,7 +277,7 @@ public static String convertSystemNameToAlternate(String systemName, String pref String s = ""; int k = 0; boolean noB = true; - for (int i = i = prefix.length() + 1; (i < systemName.length()) && noB; i++) { + for (int i = prefix.length() + 1; (i < systemName.length()) && noB; i++) { if (systemName.charAt(i) == 'B') { s = systemName.substring(prefix.length() + 1, i); k = i + 1; diff --git a/java/src/jmri/jmrix/secsi/SerialReply.java b/java/src/jmri/jmrix/secsi/SerialReply.java index afa377bef48..b9c0d559286 100644 --- a/java/src/jmri/jmrix/secsi/SerialReply.java +++ b/java/src/jmri/jmrix/secsi/SerialReply.java @@ -42,8 +42,6 @@ protected int skipPrefix(int index) { return index; } - private final static Logger log = LoggerFactory.getLogger(SerialReply.class); + //private final static Logger log = LoggerFactory.getLogger(SerialReply.class); } - - diff --git a/java/src/jmri/jmrix/secsi/SerialTrafficController.java b/java/src/jmri/jmrix/secsi/SerialTrafficController.java index f1ee6d1ac56..392242c9489 100644 --- a/java/src/jmri/jmrix/secsi/SerialTrafficController.java +++ b/java/src/jmri/jmrix/secsi/SerialTrafficController.java @@ -199,13 +199,11 @@ static public SerialTrafficController instance() { return null; } - static volatile protected SerialTrafficController self = null; - @SuppressFBWarnings(value = "ST_WRITE_TO_STATIC_FROM_INSTANCE_METHOD", justification = "temporary until multi-system; only set at startup") + @Deprecated @Override protected void setInstance() { - self = this; } /** diff --git a/java/src/jmri/jmrix/secsi/simulator/SimulatorAdapter.java b/java/src/jmri/jmrix/secsi/simulator/SimulatorAdapter.java index a73d330a001..aff88be9065 100644 --- a/java/src/jmri/jmrix/secsi/simulator/SimulatorAdapter.java +++ b/java/src/jmri/jmrix/secsi/simulator/SimulatorAdapter.java @@ -40,10 +40,6 @@ public class SimulatorAdapter extends SerialPortController implements jmri.jmrix private boolean outputBufferEmpty = true; private boolean checkBuffer = true; - /** - * Simulator auto-init setting for number of banks to auto-reply on poll - */ - private int autoInit = 0; /** * Create a new SimulatorAdapter. diff --git a/java/src/jmri/jmrix/sprog/simulator/SimulatorAdapter.java b/java/src/jmri/jmrix/sprog/simulator/SimulatorAdapter.java index 1ff95f94fef..5d0a78d9016 100644 --- a/java/src/jmri/jmrix/sprog/simulator/SimulatorAdapter.java +++ b/java/src/jmri/jmrix/sprog/simulator/SimulatorAdapter.java @@ -37,7 +37,6 @@ public class SimulatorAdapter extends SprogPortController implements Runnable { private boolean outputBufferEmpty = true; private boolean checkBuffer = true; - private boolean trackPowerState = false; private SprogMode operatingMode = SprogMode.SERVICE; // Simulator responses @@ -302,13 +301,11 @@ private SprogReply generateReply(SprogMessage msg) { case '+': log.debug("TRACK_POWER_ON detected"); - trackPowerState = true; //reply = new SprogReply(SPR_PR); break; case '-': log.debug("TRACK_POWER_OFF detected"); - trackPowerState = false; //reply = new SprogReply(SPR_PR); break; diff --git a/java/test/jmri/jmrix/grapevine/SerialTrafficControlScaffold.java b/java/test/jmri/jmrix/grapevine/SerialTrafficControlScaffold.java index 6844f0a7d08..cfb43c85a88 100644 --- a/java/test/jmri/jmrix/grapevine/SerialTrafficControlScaffold.java +++ b/java/test/jmri/jmrix/grapevine/SerialTrafficControlScaffold.java @@ -13,10 +13,6 @@ public class SerialTrafficControlScaffold extends SerialTrafficController { public SerialTrafficControlScaffold(GrapevineSystemConnectionMemo memo) { super(memo); - if (log.isDebugEnabled()) { - log.debug("setting instance: " + this); - } - self = this; } // override some SerialTrafficController methods for test purposes diff --git a/java/test/jmri/jmrix/oaktree/OakTreeMenuTest.java b/java/test/jmri/jmrix/oaktree/OakTreeMenuTest.java index 8f246f3edc7..53744671781 100644 --- a/java/test/jmri/jmrix/oaktree/OakTreeMenuTest.java +++ b/java/test/jmri/jmrix/oaktree/OakTreeMenuTest.java @@ -34,7 +34,7 @@ public void setUp() { m = new OakTreeSystemConnectionMemo(); tc = new SerialTrafficControlScaffold(m); m.setSystemPrefix("ABC"); - m.setTrafficController(tc); + m.setTrafficController(tc); // important for successful getTrafficController() } @After diff --git a/java/test/jmri/jmrix/oaktree/SerialAddressTest.java b/java/test/jmri/jmrix/oaktree/SerialAddressTest.java index d2e68d49839..5b90de9cb1e 100644 --- a/java/test/jmri/jmrix/oaktree/SerialAddressTest.java +++ b/java/test/jmri/jmrix/oaktree/SerialAddressTest.java @@ -208,7 +208,7 @@ public static Test suite() { @Override protected void setUp() { memo = new OakTreeSystemConnectionMemo(); - memo.setTrafficController(new SerialTrafficControlScaffold(memo)); + memo.setTrafficController(new SerialTrafficControlScaffold(memo)); // important for successful getTrafficController() JUnitUtil.setUp(); } diff --git a/java/test/jmri/jmrix/oaktree/SerialTrafficControlScaffold.java b/java/test/jmri/jmrix/oaktree/SerialTrafficControlScaffold.java index b6934ec7bed..d2aaefc7521 100644 --- a/java/test/jmri/jmrix/oaktree/SerialTrafficControlScaffold.java +++ b/java/test/jmri/jmrix/oaktree/SerialTrafficControlScaffold.java @@ -13,10 +13,6 @@ public class SerialTrafficControlScaffold extends SerialTrafficController { public SerialTrafficControlScaffold(OakTreeSystemConnectionMemo memo) { super(memo); - if (log.isDebugEnabled()) { - log.debug("setting instance: " + this); - } -// self = this; } // override some SerialTrafficController methods for test purposes diff --git a/java/test/jmri/jmrix/oaktree/SerialTurnoutManagerTest.java b/java/test/jmri/jmrix/oaktree/SerialTurnoutManagerTest.java index 6825323b435..8c5dfba3b50 100644 --- a/java/test/jmri/jmrix/oaktree/SerialTurnoutManagerTest.java +++ b/java/test/jmri/jmrix/oaktree/SerialTurnoutManagerTest.java @@ -63,7 +63,7 @@ public void setUp() { apps.tests.Log4JFixture.setUp(); memo = new OakTreeSystemConnectionMemo("O", "Oak Tree"); SerialTrafficController t = new SerialTrafficControlScaffold(memo); - memo.setTrafficController(t); + memo.setTrafficController(t); // important for successful getTrafficController() t.registerNode(new SerialNode(0, SerialNode.IO48, memo)); // create and register the manager object l = new SerialTurnoutManager(memo); diff --git a/java/test/jmri/jmrix/oaktree/packetgen/SerialPacketGenActionTest.java b/java/test/jmri/jmrix/oaktree/packetgen/SerialPacketGenActionTest.java index f6167b192ed..249a9d7cdbc 100644 --- a/java/test/jmri/jmrix/oaktree/packetgen/SerialPacketGenActionTest.java +++ b/java/test/jmri/jmrix/oaktree/packetgen/SerialPacketGenActionTest.java @@ -41,7 +41,7 @@ public void setUp() { m = new OakTreeSystemConnectionMemo(); tc = new SerialTrafficControlScaffold(m); m.setSystemPrefix("ABC"); - m.setTrafficController(tc); + m.setTrafficController(tc); // important for successful getTrafficController() } @After diff --git a/java/test/jmri/jmrix/oaktree/swing/OakTreeComponentFactoryTest.java b/java/test/jmri/jmrix/oaktree/swing/OakTreeComponentFactoryTest.java index efc3a514edc..d93555f90e7 100644 --- a/java/test/jmri/jmrix/oaktree/swing/OakTreeComponentFactoryTest.java +++ b/java/test/jmri/jmrix/oaktree/swing/OakTreeComponentFactoryTest.java @@ -34,7 +34,7 @@ public void setUp() { m = new OakTreeSystemConnectionMemo(); tc = new SerialTrafficControlScaffold(m); m.setSystemPrefix("ABC"); - m.setTrafficController(tc); + m.setTrafficController(tc); // important for successful getTrafficController() } @After diff --git a/java/test/jmri/jmrix/secsi/SerialLightTest.java b/java/test/jmri/jmrix/secsi/SerialLightTest.java index d77a3a947de..e0583609212 100644 --- a/java/test/jmri/jmrix/secsi/SerialLightTest.java +++ b/java/test/jmri/jmrix/secsi/SerialLightTest.java @@ -18,7 +18,7 @@ public class SerialLightTest { @Test public void testCTor() { SerialLight t = new SerialLight("VL1", memo); - Assert.assertNotNull("exists",t); + Assert.assertNotNull("exists", t); } // The minimal setup for log4J diff --git a/java/test/jmri/jmrix/secsi/SerialSensorTest.java b/java/test/jmri/jmrix/secsi/SerialSensorTest.java index 5ad1aa79679..9348d21bda7 100644 --- a/java/test/jmri/jmrix/secsi/SerialSensorTest.java +++ b/java/test/jmri/jmrix/secsi/SerialSensorTest.java @@ -17,8 +17,8 @@ public class SerialSensorTest { @Test public void testCTor() { - SerialSensor t = new SerialSensor("VS1",memo); - Assert.assertNotNull("exists",t); + SerialSensor t = new SerialSensor("VS1", memo); + Assert.assertNotNull("exists", t); } // The minimal setup for log4J diff --git a/java/test/jmri/jmrix/secsi/SerialTrafficControlScaffold.java b/java/test/jmri/jmrix/secsi/SerialTrafficControlScaffold.java index bc25b37516e..d23284749e1 100644 --- a/java/test/jmri/jmrix/secsi/SerialTrafficControlScaffold.java +++ b/java/test/jmri/jmrix/secsi/SerialTrafficControlScaffold.java @@ -16,7 +16,6 @@ public SerialTrafficControlScaffold(SecsiSystemConnectionMemo adaptermemo) { if (log.isDebugEnabled()) { log.debug("setting instance: " + this); } - self = this; memo = adaptermemo; } @@ -43,11 +42,12 @@ public void sendSerialMessage(SerialMessage m, SerialListener reply) { } // test control member functions + /** - * forward a message to the listeners, e.g. test receipt + * Forward a message to the listeners, e.g. test receipt. */ protected void sendTestMessage(SerialMessage m, SerialListener l) { - // forward a test message to NceListeners + // forward a test message to SecsiListeners if (log.isDebugEnabled()) { log.debug("sendTestMessage [" + m + "]"); } diff --git a/java/test/jmri/jmrix/secsi/SerialTurnoutTest.java b/java/test/jmri/jmrix/secsi/SerialTurnoutTest.java index 2c6eff4a56b..3175b9403b0 100644 --- a/java/test/jmri/jmrix/secsi/SerialTurnoutTest.java +++ b/java/test/jmri/jmrix/secsi/SerialTurnoutTest.java @@ -7,7 +7,7 @@ * Tests for the jmri.jmrix.secsi.SerialTurnout class * * @author Bob Jacobsen - */ + */ public class SerialTurnoutTest extends AbstractTurnoutTestBase { private SerialTrafficControlScaffold tcis = null; From 5dd5ffc44a20f9cc7d2db6168a122d07cf70bfab Mon Sep 17 00:00:00 2001 From: Egbert Broerse Date: Fri, 6 Apr 2018 22:57:47 +0200 Subject: [PATCH 29/58] 'receive' spelling fix --- .idea/ant.xml | 3 +++ default.lcf | 1 + .../manual/DecoderPro3/Main_Monitor_Window.shtml | 2 +- java/src/jmri/implementation/DccConsist.java | 2 +- .../jmrit/display/layoutEditor/LayoutBlock.java | 14 +++++++------- .../jmrit/withrottle/AbstractController.java | 2 +- .../jmri/jmrix/dcc4pc/Dcc4PcBoardManager.java | 4 ++-- .../jmri/jmrix/dcc4pc/Dcc4PcSensorManager.java | 2 +- .../dcc4pc/swing/monitor/Dcc4PcMonPane.java | 2 +- .../jmri/jmrix/dccpp/DCCppOpsModeProgrammer.java | 2 +- java/src/jmri/jmrix/dccpp/DCCppPowerManager.java | 2 +- java/src/jmri/jmrix/dccpp/DCCppSensor.java | 2 +- .../src/jmri/jmrix/dccpp/DCCppSensorManager.java | 2 +- java/src/jmri/jmrix/dccpp/DCCppThrottle.java | 2 +- java/src/jmri/jmrix/dccpp/DCCppTurnout.java | 8 ++++---- .../jmri/jmrix/dccpp/DCCppTurnoutManager.java | 2 +- .../jmri/jmrix/dccpp/DCCppTurnoutReplyCache.java | 2 +- .../jmrix/direct/serial/SerialDriverAdapter.java | 2 ++ .../jmrix/direct/simulator/SimulatorAdapter.java | 2 +- .../jmri/jmrix/ieee802154/xbee/XBeeSensor.java | 2 +- .../locormi/LnMessageClientPollThread.java | 4 ++-- java/src/jmri/jmrix/mrc/MrcPacketizer.java | 4 ++-- java/src/jmri/jmrix/mrc/MrcPackets.java | 12 ++++++------ .../jmrix/mrc/simulator/SimulatorAdapter.java | 16 ++++++++-------- java/src/jmri/jmrix/nce/NceTurnoutMonitor.java | 2 +- java/src/jmri/jmrix/roco/z21/Z21XNetTurnout.java | 2 +- .../z21/swing/configtool/Z21ConfigFrame.java | 2 +- java/src/jmri/jmrix/rps/Engine.java | 4 ++-- .../jmrix/rps/aligntable/AlignTablePane.java | 2 +- java/src/jmri/util/com/rbnb/UDPInputStream.java | 2 +- .../jmri/jmrix/direct/PortControllerTest.java | 9 ++++----- .../jmriclient/JMRIClientPowerManagerTest.java | 2 +- .../test/jmri/jmrix/lenz/XNetPacketizerTest.java | 2 +- .../jmri/jmrix/lenz/XNetPowerManagerTest.java | 2 +- .../lenz/xntcp/XnTcpXNetPacketizerTest.java | 2 +- .../jmri/jmrix/sprog/SprogPowerManagerTest.java | 2 +- .../jmri/jmrix/srcp/SRCPPowerManagerTest.java | 2 +- .../test/jmri/jmrix/xpa/XpaPowerManagerTest.java | 2 +- xml/decoders/Lenz_Plus_2010.xml | 2 +- 39 files changed, 70 insertions(+), 65 deletions(-) diff --git a/.idea/ant.xml b/.idea/ant.xml index 6a04963d051..96be31e8895 100644 --- a/.idea/ant.xml +++ b/.idea/ant.xml @@ -9,6 +9,9 @@ + + + \ No newline at end of file diff --git a/default.lcf b/default.lcf index 5d524832daf..31caf575b99 100644 --- a/default.lcf +++ b/default.lcf @@ -112,3 +112,4 @@ log4j.category.javax.jmdns=OFF #log4j.category.jmri.jmrit.display.layoutEditor=DEBUG #log4j.category.jmri.jmrit.display.layoutEditor.LayoutBlock=DEBUG +log4j.category.jmri.jmrix.direct=DEBUG diff --git a/help/en/manual/DecoderPro3/Main_Monitor_Window.shtml b/help/en/manual/DecoderPro3/Main_Monitor_Window.shtml index 94d87b110d6..49f8e54fea8 100644 --- a/help/en/manual/DecoderPro3/Main_Monitor_Window.shtml +++ b/help/en/manual/DecoderPro3/Main_Monitor_Window.shtml @@ -73,7 +73,7 @@ "checkbox"> Show timestamps-Normally, the program just displays the data from the communication link.. If you would like each message to be preceded by the time it - was sent or recieved, check this box.

+ was sent or received, check this box.

Window always on Top -- Always diff --git a/java/src/jmri/implementation/DccConsist.java b/java/src/jmri/implementation/DccConsist.java index 1f3117295d2..cf648472c09 100644 --- a/java/src/jmri/implementation/DccConsist.java +++ b/java/src/jmri/implementation/DccConsist.java @@ -492,7 +492,7 @@ protected void notifyConsistListeners(DccLocoAddress LocoAddress, int ErrorCode) // include the programmingOpReply() function @Override public void programmingOpReply(int value, int status) { - log.debug("Programming Operation reply recieved, value is {}, status is {}", value, status); + log.debug("Programming Operation reply received, value is {}, status is {}", value, status); notifyConsistListeners(new DccLocoAddress(0, false), ConsistListener.OPERATION_SUCCESS); } diff --git a/java/src/jmri/jmrit/display/layoutEditor/LayoutBlock.java b/java/src/jmri/jmrit/display/layoutEditor/LayoutBlock.java index d226ba57787..ce7878d5d54 100644 --- a/java/src/jmri/jmrit/display/layoutEditor/LayoutBlock.java +++ b/java/src/jmri/jmrit/display/layoutEditor/LayoutBlock.java @@ -1902,7 +1902,7 @@ private void removeAdjacency(LayoutBlock layoutBlock) { //Work our way backward through the list of neighbours //We need to work out which routes to remove first. //here we simply remove the routes which are advertised from the removed neighbour - List tmpBlock = removeRouteRecievedFromNeighbour(removedBlock); + List tmpBlock = removeRouteReceivedFromNeighbour(removedBlock); for (int i = neighbours.size() - 1; i > -1; i--) { //Use to check against direction but don't now. @@ -1992,7 +1992,7 @@ private void removeRouteFromNeighbour(LayoutBlock src, RoutingPacket update) { notifyNeighboursOfRemoval(routesToRemove, srcblk); } - private List removeRouteRecievedFromNeighbour(Block removedBlock) { + private List removeRouteReceivedFromNeighbour(Block removedBlock) { List tmpBlock = new ArrayList<>(); //here we simply remove the routes which are advertised from the removed neighbour @@ -2073,7 +2073,7 @@ protected void updateNeighbourPacketFlow(Adjacencies neighbour, final int flow) neighLBlock.removePropertyChangeListener(this); //This should remove routes learned from our neighbour - List tmpBlock = removeRouteRecievedFromNeighbour(neighBlock); + List tmpBlock = removeRouteReceivedFromNeighbour(neighBlock); notifyNeighboursOfRemoval(tmpBlock, neighBlock); @@ -3395,7 +3395,7 @@ void updateRoutingInfo(LayoutBlock src, RoutingPacket update) { which would end up be rejected*/ actedUponUpdates.add(update.getPacketId()); - adj.addPacketRecievedFromNeighbour(update.getPacketId()); + adj.addPacketReceivedFromNeighbour(update.getPacketId()); int hopCount = update.getHopCount(); int packetmetric = update.getMetric(); @@ -3919,8 +3919,8 @@ public int getNeighbourMetric(int i) { /** * Get the flow of traffic to and from neighbouring block at index i RXTX - * Means Traffic can flow both ways between the blocks RXONLY - Means we can - * only recieve traffic from our neighbour, we can not send traffic to it - * TXONLY - Means we do not recieve traffic from our neighbour, but can send + * only receive traffic from our neighbour, we can not send traffic to it + * TXONLY - Means we do not receive traffic from our neighbour, but can send * traffic to it. * * @param i index in neighbors @@ -4109,7 +4109,7 @@ boolean updatePacketActedUpon(Integer packetID) { return actedUponUpdates.contains(packetID); } - void addPacketRecievedFromNeighbour(Integer packetID) { + void addPacketReceivedFromNeighbour(Integer packetID) { actedUponUpdates.add(packetID); if (actedUponUpdates.size() > 500) { actedUponUpdates.subList(0, 250).clear(); diff --git a/java/src/jmri/jmrit/withrottle/AbstractController.java b/java/src/jmri/jmrit/withrottle/AbstractController.java index a50695e08ce..a8e55a2d9f0 100644 --- a/java/src/jmri/jmrit/withrottle/AbstractController.java +++ b/java/src/jmri/jmrit/withrottle/AbstractController.java @@ -4,7 +4,7 @@ import java.util.List; /** - * Abstract for controllers that want to recieve or send communications to a + * Abstract for controllers that want to receive or send communications to a * connected wi-fi device. * * diff --git a/java/src/jmri/jmrix/dcc4pc/Dcc4PcBoardManager.java b/java/src/jmri/jmrix/dcc4pc/Dcc4PcBoardManager.java index 108dd227be7..769158337d9 100644 --- a/java/src/jmri/jmrix/dcc4pc/Dcc4PcBoardManager.java +++ b/java/src/jmri/jmrix/dcc4pc/Dcc4PcBoardManager.java @@ -124,9 +124,9 @@ public void reply(Dcc4PcReply r) { @Override public void handleTimeout(Dcc4PcMessage m) { if (log.isDebugEnabled()) { - log.debug("timeout recieved to our last message " + m.toString()); + log.debug("timeout received to our last message " + m.toString()); } - log.debug("Timeout to message " + m.toString() + " for board " + m.getBoard()); + log.debug("Timeout to message {} for board {}", m.toString(), m.getBoard()); } @Override diff --git a/java/src/jmri/jmrix/dcc4pc/Dcc4PcSensorManager.java b/java/src/jmri/jmrix/dcc4pc/Dcc4PcSensorManager.java index 86ded797dd0..66d5845dc9a 100644 --- a/java/src/jmri/jmrix/dcc4pc/Dcc4PcSensorManager.java +++ b/java/src/jmri/jmrix/dcc4pc/Dcc4PcSensorManager.java @@ -539,7 +539,7 @@ protected void createSensorsFromReply(Dcc4PcReply r) { @Override public void handleTimeout(Dcc4PcMessage m) { if (log.isDebugEnabled()) { - log.debug("timeout recieved to our last message " + m.toString()); + log.debug("timeout received to our last message " + m.toString()); } if (!stopPolling) { synchronized (this) { diff --git a/java/src/jmri/jmrix/dcc4pc/swing/monitor/Dcc4PcMonPane.java b/java/src/jmri/jmrix/dcc4pc/swing/monitor/Dcc4PcMonPane.java index b90f8603b88..10da8e6f8c0 100644 --- a/java/src/jmri/jmrix/dcc4pc/swing/monitor/Dcc4PcMonPane.java +++ b/java/src/jmri/jmrix/dcc4pc/swing/monitor/Dcc4PcMonPane.java @@ -128,7 +128,7 @@ public Default() { @Override public void handleTimeout(Dcc4PcMessage m) { - log.info("timeout recieved to our last message " + m.toString()); + log.info("timeout received to our last message {}", m.toString()); } private final static Logger log = LoggerFactory.getLogger(Dcc4PcMonPane.class); diff --git a/java/src/jmri/jmrix/dccpp/DCCppOpsModeProgrammer.java b/java/src/jmri/jmrix/dccpp/DCCppOpsModeProgrammer.java index cfac3d27962..83358e10dcf 100644 --- a/java/src/jmri/jmrix/dccpp/DCCppOpsModeProgrammer.java +++ b/java/src/jmri/jmrix/dccpp/DCCppOpsModeProgrammer.java @@ -54,7 +54,7 @@ synchronized public void writeCV(int CV, int val, ProgListener p) throws Program DCCppMessage msg = DCCppMessage.makeWriteOpsModeCVMsg(mAddress, CV, val); tc.sendDCCppMessage(msg, this); /* we need to save the programer and value so we can send messages - back to the screen when the programming screen when we recieve + back to the screen when the programming screen when we receive something from the command station */ progListener = p; value = val; diff --git a/java/src/jmri/jmrix/dccpp/DCCppPowerManager.java b/java/src/jmri/jmrix/dccpp/DCCppPowerManager.java index 5c93b984c29..dbc955da737 100644 --- a/java/src/jmri/jmrix/dccpp/DCCppPowerManager.java +++ b/java/src/jmri/jmrix/dccpp/DCCppPowerManager.java @@ -92,7 +92,7 @@ public synchronized void removePropertyChangeListener(java.beans.PropertyChangeL @Override public void message(DCCppReply m) { if (log.isDebugEnabled()) { - log.debug("Message recieved: " + m.toString()); + log.debug("Message received: " + m.toString()); } if (m.isPowerReply()) { if (m.getPowerBool()) { diff --git a/java/src/jmri/jmrix/dccpp/DCCppSensor.java b/java/src/jmri/jmrix/dccpp/DCCppSensor.java index f79b91f0612..067d2a124f3 100644 --- a/java/src/jmri/jmrix/dccpp/DCCppSensor.java +++ b/java/src/jmri/jmrix/dccpp/DCCppSensor.java @@ -114,7 +114,7 @@ synchronized void initmessage(DCCppReply l) { @Override public synchronized void message(DCCppReply l) { if (log.isDebugEnabled()) { - log.debug("recieved message: " + l); + log.debug("received message: " + l); } if (l.isSensorDefReply()) { diff --git a/java/src/jmri/jmrix/dccpp/DCCppSensorManager.java b/java/src/jmri/jmrix/dccpp/DCCppSensorManager.java index af8876c2939..2fa8a76704b 100644 --- a/java/src/jmri/jmrix/dccpp/DCCppSensorManager.java +++ b/java/src/jmri/jmrix/dccpp/DCCppSensorManager.java @@ -76,7 +76,7 @@ public Sensor createNewSensor(String systemName, String userName) throws Illegal public void message(DCCppReply l) { int addr = -1; // -1 flags that no sensor address was found in reply if (log.isDebugEnabled()) { - log.debug("recieved message: " + l); + log.debug("received message: " + l); } if (l.isSensorDefReply()) { addr = l.getSensorDefNumInt(); diff --git a/java/src/jmri/jmrix/dccpp/DCCppThrottle.java b/java/src/jmri/jmrix/dccpp/DCCppThrottle.java index 474f13432e6..a146e217fcd 100644 --- a/java/src/jmri/jmrix/dccpp/DCCppThrottle.java +++ b/java/src/jmri/jmrix/dccpp/DCCppThrottle.java @@ -324,7 +324,7 @@ public void message(DCCppReply l) { // First, we want to see if this throttle is waiting for a message //or not. if (log.isDebugEnabled()) { - log.debug("Throttle " + getDccAddress() + " - recieved message " + l.toString()); + log.debug("Throttle {} - received message \"{}\"", getDccAddress(), l.toString()); } if (requestState == THROTTLEIDLE) { if (log.isDebugEnabled()) { diff --git a/java/src/jmri/jmrix/dccpp/DCCppTurnout.java b/java/src/jmri/jmrix/dccpp/DCCppTurnout.java index 91621bb21e6..feb537c419e 100644 --- a/java/src/jmri/jmrix/dccpp/DCCppTurnout.java +++ b/java/src/jmri/jmrix/dccpp/DCCppTurnout.java @@ -256,7 +256,7 @@ synchronized void initmessage(DCCppReply l) { @Override synchronized public void message(DCCppReply l) { if (log.isDebugEnabled()) { - log.debug("recieved message: " + l); + log.debug("received message: " + l); } switch (getFeedbackMode()) { @@ -295,10 +295,10 @@ synchronized private void handleDirectModeFeedback(DCCppReply l) { /* If commanded state does not equal known state, we are going to check to see if one of the following conditions applies: - 1) The recieved message is a feedback message for a turnout + 1) The received message is a feedback message for a turnout and one of the two addresses to which it applies is our address - 2) We recieve an "OK" message, indicating the command was + 2) We receive an "OK" message, indicating the command was successfully sent If either of these two cases occur, we trigger an off message @@ -325,7 +325,7 @@ synchronized private void handleDirectModeFeedback(DCCppReply l) { *

* After we send a request to operate a turnout, We ask the command * station to stop sending information to the stationary decoder - * when the either a feedback message or an "OK" message is recieved. + * when the either a feedback message or an "OK" message is received. * * @param l an {@link DCCppReply} message * diff --git a/java/src/jmri/jmrix/dccpp/DCCppTurnoutManager.java b/java/src/jmri/jmrix/dccpp/DCCppTurnoutManager.java index 41af56ffdb7..04d1a8cd421 100644 --- a/java/src/jmri/jmrix/dccpp/DCCppTurnoutManager.java +++ b/java/src/jmri/jmrix/dccpp/DCCppTurnoutManager.java @@ -57,7 +57,7 @@ public Turnout createNewTurnout(String systemName, String userName) { @Override public void message(DCCppReply l) { if (log.isDebugEnabled()) { - log.debug("recieved message: {}", l.toString()); + log.debug("received message: {}", l.toString()); } if (l.isTurnoutReply()) { // parse message type diff --git a/java/src/jmri/jmrix/dccpp/DCCppTurnoutReplyCache.java b/java/src/jmri/jmrix/dccpp/DCCppTurnoutReplyCache.java index 0f13ed80906..73485a75644 100644 --- a/java/src/jmri/jmrix/dccpp/DCCppTurnoutReplyCache.java +++ b/java/src/jmri/jmrix/dccpp/DCCppTurnoutReplyCache.java @@ -98,7 +98,7 @@ synchronized public void requestCachedStateFromLayout(DCCppSensor sensor) { @Override synchronized public void message(DCCppReply l) { if (log.isDebugEnabled()) { - log.debug("recieved message: " + l); + log.debug("received message: " + l); } if (l.isTurnoutReply()) { // cache the message for later requests diff --git a/java/src/jmri/jmrix/direct/serial/SerialDriverAdapter.java b/java/src/jmri/jmrix/direct/serial/SerialDriverAdapter.java index 5f83a211bb5..d71c93afe3e 100644 --- a/java/src/jmri/jmrix/direct/serial/SerialDriverAdapter.java +++ b/java/src/jmri/jmrix/direct/serial/SerialDriverAdapter.java @@ -126,11 +126,13 @@ public String openPort(String portName, String appName) { */ @Override public void configure() { + // connect to the traffic controller TrafficController tc = new TrafficController((jmri.jmrix.direct.DirectSystemConnectionMemo)getSystemConnectionMemo()); ((jmri.jmrix.direct.DirectSystemConnectionMemo)getSystemConnectionMemo()).setTrafficController(tc); // connect to the traffic controller tc.connectPort(this); + // do the common manager config ((jmri.jmrix.direct.DirectSystemConnectionMemo)getSystemConnectionMemo()).configureManagers(); } diff --git a/java/src/jmri/jmrix/direct/simulator/SimulatorAdapter.java b/java/src/jmri/jmrix/direct/simulator/SimulatorAdapter.java index a555d653aad..5f2f7e667a9 100644 --- a/java/src/jmri/jmrix/direct/simulator/SimulatorAdapter.java +++ b/java/src/jmri/jmrix/direct/simulator/SimulatorAdapter.java @@ -115,7 +115,7 @@ public void configure() { // do the common manager config ((jmri.jmrix.direct.DirectSystemConnectionMemo)getSystemConnectionMemo()).configureManagers(); - // start the simulator + // start the simulator: Notice that normally, transmission is not a threaded operation! sourceThread = new Thread(this); sourceThread.setName("Direct Simulator"); // NOI18N sourceThread.setPriority(Thread.MIN_PRIORITY); diff --git a/java/src/jmri/jmrix/ieee802154/xbee/XBeeSensor.java b/java/src/jmri/jmrix/ieee802154/xbee/XBeeSensor.java index 8c3246bc69c..f56a3823444 100644 --- a/java/src/jmri/jmrix/ieee802154/xbee/XBeeSensor.java +++ b/java/src/jmri/jmrix/ieee802154/xbee/XBeeSensor.java @@ -137,7 +137,7 @@ public void requestUpdateFromLayout() { @Override public synchronized void ioSampleReceived(RemoteXBeeDevice remoteDevice,IOSample ioSample) { if (log.isDebugEnabled()) { - log.debug("recieved io sample {} from {}",ioSample,remoteDevice); + log.debug("received io sample {} from {}", ioSample, remoteDevice); } XBeeNode sourcenode = (XBeeNode) tc.getNodeFromXBeeDevice(remoteDevice); diff --git a/java/src/jmri/jmrix/loconet/locormi/LnMessageClientPollThread.java b/java/src/jmri/jmrix/loconet/locormi/LnMessageClientPollThread.java index d739c6350d0..bdf9c982a5d 100644 --- a/java/src/jmri/jmrix/loconet/locormi/LnMessageClientPollThread.java +++ b/java/src/jmri/jmrix/loconet/locormi/LnMessageClientPollThread.java @@ -28,7 +28,7 @@ public void run() { if (lnMessages != null) { - log.debug("Recieved Message Array Size: " + lnMessages.length); + log.debug("Received Message Array Size: {}", lnMessages.length); for (int lnMessageIndex = 0; lnMessageIndex < lnMessages.length; lnMessageIndex++) { LocoNetMessage message = (LocoNetMessage) lnMessages[lnMessageIndex]; parent.message(message); @@ -36,7 +36,7 @@ public void run() { } } } catch (Exception ex) { - log.warn("Exception: " + ex); + log.warn("Exception: ", ex); } } } diff --git a/java/src/jmri/jmrix/mrc/MrcPacketizer.java b/java/src/jmri/jmrix/mrc/MrcPacketizer.java index 8275a741c96..522e3eaa145 100644 --- a/java/src/jmri/jmrix/mrc/MrcPacketizer.java +++ b/java/src/jmri/jmrix/mrc/MrcPacketizer.java @@ -402,7 +402,7 @@ public void run() { transmitLock.notify(); } break; - case MrcPackets.GOODCMDRECIEVEDCODE: //Possibly shouldn't change the state, as we wait for further confirmation. + case MrcPackets.GOODCMDRECEIVEDCODE: //Possibly shouldn't change the state, as we wait for further confirmation. if (mCurrentState == CONFIRMATIONONLY) { synchronized (transmitLock) { mCurrentState = IDLESTATE; @@ -411,7 +411,7 @@ public void run() { } msg = new MrcMessage(4); break; - case MrcPackets.BADCMDRECIEVEDCODE: + case MrcPackets.BADCMDRECEIVEDCODE: mCurrentState = BADCOMMAND; msg = new MrcMessage(4); break; diff --git a/java/src/jmri/jmrix/mrc/MrcPackets.java b/java/src/jmri/jmrix/mrc/MrcPackets.java index c007c83f3f1..c4a06d92c20 100644 --- a/java/src/jmri/jmrix/mrc/MrcPackets.java +++ b/java/src/jmri/jmrix/mrc/MrcPackets.java @@ -106,11 +106,11 @@ public class MrcPackets { public static final int LOCODBLCONTROLCODE = 221; static final int[] LOCODBLCONTROL = new int[]{LOCODBLCONTROLCODE, 0, LOCODBLCONTROLCODE, 0}; //Reply indicates that another throttle also has controll of the loco - public static final int GOODCMDRECIEVEDCODE = 85; - static final int[] GOODCMDRECIEVED = new int[]{GOODCMDRECIEVEDCODE, 0, GOODCMDRECIEVEDCODE, 0}; + public static final int GOODCMDRECEIVEDCODE = 85; + static final int[] GOODCMDRECEIVED = new int[]{GOODCMDRECEIVEDCODE, 0, GOODCMDRECEIVEDCODE, 0}; - public static final int BADCMDRECIEVEDCODE = 238; //Or unable to read from decoder - static final int[] BADCMDRECIEVED = new int[]{BADCMDRECIEVEDCODE, 0, BADCMDRECIEVEDCODE, 0}; + public static final int BADCMDRECEIVEDCODE = 238; //Or unable to read from decoder + static final int[] BADCMDRECEIVED = new int[]{BADCMDRECEIVEDCODE, 0, BADCMDRECEIVEDCODE, 0}; public static final int POWERONCMD = 130; static final int[] POWERON = new int[]{POWERONCMD, 0, POWERONCMD, 0, POWERONCMD, 0, POWERONCMD, 0}; @@ -367,10 +367,10 @@ static public String toString(MrcMessage m) { txt.append(Bundle.getMessage("MrcPacketsReadCvValue")); // NOI18N txt.append(Integer.toString(m.value())); break; - case BADCMDRECIEVEDCODE: + case BADCMDRECEIVEDCODE: txt.append(Bundle.getMessage("MrcPacketBadCmdAck")); // NOI18N break; - case GOODCMDRECIEVEDCODE: + case GOODCMDRECEIVEDCODE: txt.append(Bundle.getMessage("MrcPacketGoodCmdAck")); // NOI18N break; case PROGCMDSENTCODE: diff --git a/java/src/jmri/jmrix/mrc/simulator/SimulatorAdapter.java b/java/src/jmri/jmrix/mrc/simulator/SimulatorAdapter.java index 4bedf752030..089e7bb0ea3 100644 --- a/java/src/jmri/jmrix/mrc/simulator/SimulatorAdapter.java +++ b/java/src/jmri/jmrix/mrc/simulator/SimulatorAdapter.java @@ -149,9 +149,9 @@ public void run() { // start a new thread if (m != null && m.getNumDataElements() > 4) { //Send a default good reply message MrcMessage r = new MrcMessage(4); - r.setElement(0, MrcPackets.GOODCMDRECIEVEDCODE); + r.setElement(0, MrcPackets.GOODCMDRECEIVEDCODE); r.setElement(1, 0x0); - r.setElement(2, MrcPackets.GOODCMDRECIEVEDCODE); + r.setElement(2, MrcPackets.GOODCMDRECEIVEDCODE); r.setElement(3, 0x0); writeReply(r); if (m.isReplyExpected()) { @@ -216,17 +216,17 @@ private MrcMessage loadChars() throws java.io.IOException { private MrcMessage generateReply(MrcMessage m) { MrcMessage reply = new MrcMessage(4); if (m.getNumDataElements() < 4) { - reply.setElement(0, MrcPackets.BADCMDRECIEVEDCODE); + reply.setElement(0, MrcPackets.BADCMDRECEIVEDCODE); reply.setElement(1, 0x0); - reply.setElement(2, MrcPackets.BADCMDRECIEVEDCODE); + reply.setElement(2, MrcPackets.BADCMDRECEIVEDCODE); reply.setElement(3, 0x0); return reply; } int command = m.getElement(0); if (command != m.getElement(2) && m.getElement(1) != 1) { - reply.setElement(0, MrcPackets.BADCMDRECIEVEDCODE); + reply.setElement(0, MrcPackets.BADCMDRECEIVEDCODE); reply.setElement(1, 0x0); - reply.setElement(2, MrcPackets.BADCMDRECIEVEDCODE); + reply.setElement(2, MrcPackets.BADCMDRECEIVEDCODE); reply.setElement(3, 0x0); return reply; } @@ -263,9 +263,9 @@ private MrcMessage generateReply(MrcMessage m) { break; default: // we don't know what it is but presume ok - reply.setElement(0, MrcPackets.GOODCMDRECIEVEDCODE); + reply.setElement(0, MrcPackets.GOODCMDRECEIVEDCODE); reply.setElement(1, 0x0); - reply.setElement(2, MrcPackets.GOODCMDRECIEVEDCODE); + reply.setElement(2, MrcPackets.GOODCMDRECEIVEDCODE); reply.setElement(3, 0x0); break; } diff --git a/java/src/jmri/jmrix/nce/NceTurnoutMonitor.java b/java/src/jmri/jmrix/nce/NceTurnoutMonitor.java index 092f260d17b..1dfa3c10c83 100644 --- a/java/src/jmri/jmrix/nce/NceTurnoutMonitor.java +++ b/java/src/jmri/jmrix/nce/NceTurnoutMonitor.java @@ -51,7 +51,7 @@ public class NceTurnoutMonitor implements NceListener, java.beans.PropertyChange byte[] csAccMemCopy = new byte[NUM_BLOCK * BLOCK_LEN]; // Copy of NCE CS accessory memory byte[] dataBuffer = new byte[NUM_BLOCK * BLOCK_LEN]; // place to store reply messages - private boolean recData = false; // when true, valid recieve data + private boolean recData = false; // when true, valid receive data Thread nceTurnoutMonitorThread; boolean turnoutUpdateValid = true; // keep the thread running diff --git a/java/src/jmri/jmrix/roco/z21/Z21XNetTurnout.java b/java/src/jmri/jmrix/roco/z21/Z21XNetTurnout.java index 53151464f64..ff0d3367011 100644 --- a/java/src/jmri/jmrix/roco/z21/Z21XNetTurnout.java +++ b/java/src/jmri/jmrix/roco/z21/Z21XNetTurnout.java @@ -125,7 +125,7 @@ synchronized public void message(XNetReply l) { if(internalState == COMMANDSENT) { sendOffMessage(); // turn off the repition on the track. } else if(internalState == OFFSENT ) { - /* the command was successfully recieved */ + /* the command was successfully received */ newKnownState(getCommandedState()); internalState = IDLE; } diff --git a/java/src/jmri/jmrix/roco/z21/swing/configtool/Z21ConfigFrame.java b/java/src/jmri/jmrix/roco/z21/swing/configtool/Z21ConfigFrame.java index 8ce24c8e9ae..8ec71612dab 100644 --- a/java/src/jmri/jmrix/roco/z21/swing/configtool/Z21ConfigFrame.java +++ b/java/src/jmri/jmrix/roco/z21/swing/configtool/Z21ConfigFrame.java @@ -260,7 +260,7 @@ public void reply(Z21Reply zr) { break; default: // ignore all other message types. - log.debug("unhandled op-code recieved."); + log.debug("unhandled op-code received."); } } diff --git a/java/src/jmri/jmrix/rps/Engine.java b/java/src/jmri/jmrix/rps/Engine.java index 5836a15ed3e..922c3070627 100644 --- a/java/src/jmri/jmrix/rps/Engine.java +++ b/java/src/jmri/jmrix/rps/Engine.java @@ -103,7 +103,7 @@ public int getMaxReceiverNumber() { } /** - * Get a particular reciever by address (starting at 1) + * Get a particular receiver by address (starting at 1) */ public void setReceiver(int address, Receiver receiver) { if (receivers == null) { @@ -167,7 +167,7 @@ public void notify(Reading r) { Point3d p = getReceiverPosition(i); if (p != null) { - receivers[i].setLastTime((int) r.getValue(i)); // recievers numbered from 1 + receivers[i].setLastTime((int) r.getValue(i)); // receivers numbered from 1 log.debug(" " + i + "th value min " + receivers[i].getMinTime() + " < time " + r.getValue(i) + " < max " + receivers[i].getMaxTime() + " at " + p); diff --git a/java/src/jmri/jmrix/rps/aligntable/AlignTablePane.java b/java/src/jmri/jmrix/rps/aligntable/AlignTablePane.java index 74a5aeeb7ab..59287b80595 100644 --- a/java/src/jmri/jmrix/rps/aligntable/AlignTablePane.java +++ b/java/src/jmri/jmrix/rps/aligntable/AlignTablePane.java @@ -191,7 +191,7 @@ void storeDefault() { JComboBox algorithmBox = Algorithms.algorithmBox(); /** - * Set up table for showing individual recievers + * Set up table for showing individual receivers *

    *
  1. Address *
  2. Present Y/N diff --git a/java/src/jmri/util/com/rbnb/UDPInputStream.java b/java/src/jmri/util/com/rbnb/UDPInputStream.java index 62ceb5cb60a..4e5b32d8be2 100644 --- a/java/src/jmri/util/com/rbnb/UDPInputStream.java +++ b/java/src/jmri/util/com/rbnb/UDPInputStream.java @@ -122,7 +122,7 @@ public UDPInputStream(String address, int port) ***************************************************************** */ public void open(String address, int port) throws UnknownHostException, SocketException { - //Changed by Kevin Dickerson to allow a datagram to be recieved on the broadcast address. + // Changed to allow a datagram to be received on the broadcast address. if (address != null) { dsock = new DatagramSocket(port, InetAddress.getByName(address)); } else { diff --git a/java/test/jmri/jmrix/direct/PortControllerTest.java b/java/test/jmri/jmrix/direct/PortControllerTest.java index 7dae26cf797..5a3ad7d60da 100644 --- a/java/test/jmri/jmrix/direct/PortControllerTest.java +++ b/java/test/jmri/jmrix/direct/PortControllerTest.java @@ -5,10 +5,9 @@ import org.junit.Before; /** - * JUnit tests for the PortController class - *

    + * JUnit tests for the PortController class. * - * @author Paul Bender Copyright (C) 2016 + * @author Paul Bender Copyright (C) 2016 */ public class PortControllerTest extends jmri.jmrix.AbstractSerialPortControllerTestBase { @@ -42,8 +41,8 @@ public String[] validBaudRates(){ return retval; } /** - * Open a specified port. The appname argument is to be provided to the - * underlying OS during startup so that it can show on status displays, etc + * Open a specified port. The appName argument is to be provided to the + * underlying OS during startup so that it can show on status displays, etc. */ @Override public String openPort(String portName, String appName){ diff --git a/java/test/jmri/jmrix/jmriclient/JMRIClientPowerManagerTest.java b/java/test/jmri/jmrix/jmriclient/JMRIClientPowerManagerTest.java index 7e146510aad..c0baa0752d8 100644 --- a/java/test/jmri/jmrix/jmriclient/JMRIClientPowerManagerTest.java +++ b/java/test/jmri/jmrix/jmriclient/JMRIClientPowerManagerTest.java @@ -17,7 +17,7 @@ public class JMRIClientPowerManagerTest extends jmri.jmrix.AbstractPowerManagerT private JMRIClientTrafficControlScaffold stc = null; - // service routines to simulate recieving on, off from interface + // service routines to simulate receiving on, off from interface @Override protected void hearOn() { stc.sendTestReply(new JMRIClientReply("POWER ON\n\r")); diff --git a/java/test/jmri/jmrix/lenz/XNetPacketizerTest.java b/java/test/jmri/jmrix/lenz/XNetPacketizerTest.java index a5ad904e2bc..4bf937e403b 100644 --- a/java/test/jmri/jmrix/lenz/XNetPacketizerTest.java +++ b/java/test/jmri/jmrix/lenz/XNetPacketizerTest.java @@ -97,7 +97,7 @@ public void testInterference() throws Exception { tc.connectPort(port); // We need three objects to receive messages. - // The first one recieves broadcast messages. + // The first one receives broadcast messages. // The others only receive directed messages. XNetListenerScaffold l = new XNetListenerScaffold(); XNetListenerScaffold l1 = new XNetListenerScaffold(); diff --git a/java/test/jmri/jmrix/lenz/XNetPowerManagerTest.java b/java/test/jmri/jmrix/lenz/XNetPowerManagerTest.java index 280d7e178c6..d26d8d707e0 100644 --- a/java/test/jmri/jmrix/lenz/XNetPowerManagerTest.java +++ b/java/test/jmri/jmrix/lenz/XNetPowerManagerTest.java @@ -20,7 +20,7 @@ public class XNetPowerManagerTest extends jmri.jmrix.AbstractPowerManagerTestBas private int propertyChangeCount; private java.beans.PropertyChangeListener listener = null; - // service routines to simulate recieving on, off from interface + // service routines to simulate receiving on, off from interface @Override protected void hearOn() { sendOnReply(); diff --git a/java/test/jmri/jmrix/lenz/xntcp/XnTcpXNetPacketizerTest.java b/java/test/jmri/jmrix/lenz/xntcp/XnTcpXNetPacketizerTest.java index 8b54d5f0973..11d0c38f125 100644 --- a/java/test/jmri/jmrix/lenz/xntcp/XnTcpXNetPacketizerTest.java +++ b/java/test/jmri/jmrix/lenz/xntcp/XnTcpXNetPacketizerTest.java @@ -56,7 +56,7 @@ public void testInterference() throws Exception { c.connectPort(p); // We need three objects to receive messages. - // The first one recieves broadcast messages. + // The first one receives broadcast messages. // The others only receive directed messages. XNetListenerScaffold l = new XNetListenerScaffold(); XNetListenerScaffold l1 = new XNetListenerScaffold(); diff --git a/java/test/jmri/jmrix/sprog/SprogPowerManagerTest.java b/java/test/jmri/jmrix/sprog/SprogPowerManagerTest.java index 942e7da062c..71c9bb5398f 100644 --- a/java/test/jmri/jmrix/sprog/SprogPowerManagerTest.java +++ b/java/test/jmri/jmrix/sprog/SprogPowerManagerTest.java @@ -16,7 +16,7 @@ public class SprogPowerManagerTest extends jmri.jmrix.AbstractPowerManagerTestBa private SprogTrafficControlScaffold stc = null; - // service routines to simulate recieving on, off from interface + // service routines to simulate receiving on, off from interface @Override protected void hearOn() { stc.sendTestReply(new SprogReply("+")); diff --git a/java/test/jmri/jmrix/srcp/SRCPPowerManagerTest.java b/java/test/jmri/jmrix/srcp/SRCPPowerManagerTest.java index 7f9e02ec2f3..64186c3a7ba 100644 --- a/java/test/jmri/jmrix/srcp/SRCPPowerManagerTest.java +++ b/java/test/jmri/jmrix/srcp/SRCPPowerManagerTest.java @@ -18,7 +18,7 @@ public class SRCPPowerManagerTest extends jmri.jmrix.AbstractPowerManagerTestBas private SRCPTrafficControlScaffold stc = null; - // service routines to simulate recieving on, off from interface + // service routines to simulate receiving on, off from interface @Override protected void hearOn() { stc.sendTestReply(new SRCPReply("12345678910 100 INFO 1 POWER ON hello world\n\r")); diff --git a/java/test/jmri/jmrix/xpa/XpaPowerManagerTest.java b/java/test/jmri/jmrix/xpa/XpaPowerManagerTest.java index 49a0a2c8ad5..5fde6f1b844 100644 --- a/java/test/jmri/jmrix/xpa/XpaPowerManagerTest.java +++ b/java/test/jmri/jmrix/xpa/XpaPowerManagerTest.java @@ -14,7 +14,7 @@ public class XpaPowerManagerTest extends jmri.jmrix.AbstractPowerManagerTestBase private XpaTrafficControlScaffold tc = null; - // service routines to simulate recieving on, off from interface + // service routines to simulate receiving on, off from interface @Override protected void hearOn() { } diff --git a/xml/decoders/Lenz_Plus_2010.xml b/xml/decoders/Lenz_Plus_2010.xml index 447d5f6bc20..7e9ebd91a75 100644 --- a/xml/decoders/Lenz_Plus_2010.xml +++ b/xml/decoders/Lenz_Plus_2010.xml @@ -20,7 +20,7 @@ + * @since JMRI 4.11.4 + */ +package jmri.util.com.dictiography.collections; diff --git a/java/src/jmri/util/com/package-info.java b/java/src/jmri/util/com/package-info.java new file mode 100644 index 00000000000..f62f7ec5a07 --- /dev/null +++ b/java/src/jmri/util/com/package-info.java @@ -0,0 +1,8 @@ +/** + * Holds utility classes imported to JMRI from other locations. + *

    + * Sometimes these are small segments of code from books, other + * repositories, etc. Large bodies of code should be brought + * in as libraries i.e. jar files. + */ +package jmri.util.com; diff --git a/java/src/jmri/util/package-info.java b/java/src/jmri/util/package-info.java new file mode 100644 index 00000000000..4f3f5eb3031 --- /dev/null +++ b/java/src/jmri/util/package-info.java @@ -0,0 +1,12 @@ +/** + * Contains various utilities classes that are + * useful across the entire + * JMRI library structure. + *

    + * Please put new classes into appropriate + * subpackage, i.e. for {@link jmri.util.swing} for Swing/AWT related utilities, etc. + *

    + * The {@link jmri.util.com} package contains several sets of + * imported code. + */ +package jmri.util; From 17e6017b6bd92c54dea43bcb4a91c58cd43d7feb Mon Sep 17 00:00:00 2001 From: Bob Jacobsen Date: Sat, 7 Apr 2018 12:30:19 -0700 Subject: [PATCH 35/58] annotate unchecked warnings --- .../dictiography/collections/AbstractMap.java | 2 ++ .../collections/IndexedTreeMap.java | 29 +++++++++++++++++++ .../collections/IndexedTreeSet.java | 7 +++++ 3 files changed, 38 insertions(+) diff --git a/java/src/jmri/util/com/dictiography/collections/AbstractMap.java b/java/src/jmri/util/com/dictiography/collections/AbstractMap.java index f0871469e0a..2795e8612f1 100644 --- a/java/src/jmri/util/com/dictiography/collections/AbstractMap.java +++ b/java/src/jmri/util/com/dictiography/collections/AbstractMap.java @@ -411,6 +411,7 @@ public boolean contains(Object v) { * @param o object to be compared for equality with this map * @return true if the specified object is equal to this map */ + @SuppressWarnings("unchecked") // package needs update to Java 1.8 generics public boolean equals(Object o) { if (o == this) return true; @@ -507,6 +508,7 @@ public String toString() { * * @return a shallow copy of this map */ + @SuppressWarnings("unchecked") // package needs update to Java 1.8 generics protected Object clone() throws CloneNotSupportedException { AbstractMap result = (AbstractMap) super.clone(); result.keySet = null; diff --git a/java/src/jmri/util/com/dictiography/collections/IndexedTreeMap.java b/java/src/jmri/util/com/dictiography/collections/IndexedTreeMap.java index a3301cdbd92..ceaed51cd81 100644 --- a/java/src/jmri/util/com/dictiography/collections/IndexedTreeMap.java +++ b/java/src/jmri/util/com/dictiography/collections/IndexedTreeMap.java @@ -325,6 +325,7 @@ public void putAll(Map map) { * and this map uses natural ordering, or its comparator * does not permit null keys */ + @SuppressWarnings("unchecked") // package needs update to Java 1.8 generics for maps final Entry getEntry(Object key) { // Offload comparator-based version for sake of performance if (comparator != null) @@ -351,6 +352,7 @@ else if (cmp > 0) * that are less dependent on comparator performance, but is * worthwhile here.) */ + @SuppressWarnings("unchecked") // package needs update to Java 1.8 generics for maps final Entry getEntryUsingComparator(Object key) { K k = (K) key; Comparator cpr = comparator; @@ -539,6 +541,7 @@ final Entry getLowerEntry(K key) { * and this map uses natural ordering, or its comparator * does not permit null keys */ + @SuppressWarnings("unchecked") // package needs update to Java 1.8 generics for maps public V put(K key, V value) { Entry t = root; if (t == null) { @@ -637,6 +640,7 @@ public void clear() { * * @return a shallow copy of this map */ + @SuppressWarnings("unchecked") // package needs update to Java 1.8 generics for maps public Object clone() { IndexedTreeMap clone = null; try { @@ -812,6 +816,7 @@ private K getExactKey(Entry e, int index) { return getExactKey(e.right, index - (e.left == null ? 0 : e.left.weight) - 1); } + @SuppressWarnings("unchecked") // package needs update to Java 1.8 generics for maps public int keyIndex(K key) { if (key == null) { throw new NullPointerException(); @@ -903,6 +908,7 @@ public Set keySet() { /** * @since 1.6 */ + @SuppressWarnings("unchecked") // package needs update to Java 1.8 generics for maps public NavigableSet navigableKeySet() { KeySet nks = navigableKeySet; return (nks != null) ? nks : (navigableKeySet = new KeySet(this)); @@ -958,6 +964,7 @@ public Set> entrySet() { /** * @since 1.6 */ + @SuppressWarnings("unchecked") // package needs update to Java 1.8 generics for maps public NavigableMap descendingMap() { NavigableMap km = descendingMap; return (km != null) ? km : @@ -974,6 +981,7 @@ public NavigableMap descendingMap() { * @throws IllegalArgumentException {@inheritDoc} * @since 1.6 */ + @SuppressWarnings("unchecked") // package needs update to Java 1.8 generics for maps public NavigableMap subMap(K fromKey, boolean fromInclusive, K toKey, boolean toInclusive) { return new AscendingSubMap(this, @@ -989,6 +997,7 @@ public NavigableMap subMap(K fromKey, boolean fromInclusive, * @throws IllegalArgumentException {@inheritDoc} * @since 1.6 */ + @SuppressWarnings("unchecked") // package needs update to Java 1.8 generics for maps public NavigableMap headMap(K toKey, boolean inclusive) { return new AscendingSubMap(this, true, null, true, @@ -1003,6 +1012,7 @@ public NavigableMap headMap(K toKey, boolean inclusive) { * @throws IllegalArgumentException {@inheritDoc} * @since 1.6 */ + @SuppressWarnings("unchecked") // package needs update to Java 1.8 generics for maps public NavigableMap tailMap(K fromKey, boolean inclusive) { return new AscendingSubMap(this, false, fromKey, inclusive, @@ -1078,6 +1088,7 @@ public Iterator> iterator() { return new EntryIterator(getFirstEntry()); } + @SuppressWarnings("unchecked") // package needs update to Java 1.8 generics for maps public boolean contains(Object o) { if (!(o instanceof Map.Entry)) return false; @@ -1087,6 +1098,7 @@ public boolean contains(Object o) { return p != null && valEquals(p.getValue(), value); } + @SuppressWarnings("unchecked") // package needs update to Java 1.8 generics for maps public boolean remove(Object o) { if (!(o instanceof Map.Entry)) return false; @@ -1128,6 +1140,7 @@ Iterator descendingKeyIterator() { static final class KeySet extends AbstractSet implements NavigableSet { private final NavigableMap m; + @SuppressWarnings("unchecked") // package needs update to Java 1.8 generics for maps KeySet(NavigableMap map) { m = map; } @@ -1139,6 +1152,7 @@ public Iterator iterator() { return (Iterator) (((IndexedTreeMap.NavigableSubMap) m).keyIterator()); } + @SuppressWarnings("unchecked") // package needs update to Java 1.8 generics for maps public Iterator descendingIterator() { if (m instanceof IndexedTreeMap) return ((IndexedTreeMap) m).descendingKeyIterator(); @@ -1232,6 +1246,7 @@ public SortedSet tailSet(E fromElement) { return tailSet(fromElement, true); } + @SuppressWarnings("unchecked") // package needs update to Java 1.8 generics for maps public NavigableSet descendingSet() { return new IndexedTreeSet(m.descendingMap()); } @@ -1336,6 +1351,7 @@ public K next() { /** * Compares two keys using the correct comparison method for this IndexedTreeMap. */ + @SuppressWarnings("unchecked") // package needs update to Java 1.8 generics for maps final int compare(Object k1, Object k2) { return comparator == null ? ((Comparable) k1).compareTo((K) k2) : comparator.compare((K) k1, (K) k2); @@ -1645,6 +1661,7 @@ public final Map.Entry pollLastEntry() { transient EntrySetView entrySetView = null; transient KeySet navigableKeySetView = null; + @SuppressWarnings("unchecked") // package needs update to Java 1.8 generics for maps public final NavigableSet navigableKeySet() { KeySet nksv = navigableKeySetView; return (nksv != null) ? nksv : @@ -1696,6 +1713,7 @@ public boolean isEmpty() { return n == null || tooHigh(n.key); } + @SuppressWarnings("unchecked") // package needs update to Java 1.8 generics for maps public boolean contains(Object o) { if (!(o instanceof Map.Entry)) return false; @@ -1708,6 +1726,7 @@ public boolean contains(Object o) { valEquals(node.getValue(), entry.getValue()); } + @SuppressWarnings("unchecked") // package needs update to Java 1.8 generics for maps public boolean remove(Object o) { if (!(o instanceof Map.Entry)) return false; @@ -1869,6 +1888,7 @@ public Comparator comparator() { return m.comparator(); } + @SuppressWarnings("unchecked") // package needs update to Java 1.8 generics for maps public NavigableMap subMap(K fromKey, boolean fromInclusive, K toKey, boolean toInclusive) { if (!inRange(fromKey, fromInclusive)) @@ -1880,6 +1900,7 @@ public NavigableMap subMap(K fromKey, boolean fromInclusive, false, toKey, toInclusive); } + @SuppressWarnings("unchecked") // package needs update to Java 1.8 generics for maps public NavigableMap headMap(K toKey, boolean inclusive) { if (!inRange(toKey, inclusive)) throw new IllegalArgumentException("toKey out of range"); @@ -1888,6 +1909,7 @@ public NavigableMap headMap(K toKey, boolean inclusive) { false, toKey, inclusive); } + @SuppressWarnings("unchecked") // package needs update to Java 1.8 generics for maps public NavigableMap tailMap(K fromKey, boolean inclusive) { if (!inRange(fromKey, inclusive)) throw new IllegalArgumentException("fromKey out of range"); @@ -1896,6 +1918,7 @@ public NavigableMap tailMap(K fromKey, boolean inclusive) { toEnd, hi, hiInclusive); } + @SuppressWarnings("unchecked") // package needs update to Java 1.8 generics for maps public NavigableMap descendingMap() { NavigableMap mv = descendingMapView; return (mv != null) ? mv : @@ -1968,6 +1991,7 @@ public Comparator comparator() { return reverseComparator; } + @SuppressWarnings("unchecked") // package needs update to Java 1.8 generics for maps public NavigableMap subMap(K fromKey, boolean fromInclusive, K toKey, boolean toInclusive) { if (!inRange(fromKey, fromInclusive)) @@ -1979,6 +2003,7 @@ public NavigableMap subMap(K fromKey, boolean fromInclusive, false, fromKey, fromInclusive); } + @SuppressWarnings("unchecked") // package needs update to Java 1.8 generics for maps public NavigableMap headMap(K toKey, boolean inclusive) { if (!inRange(toKey, inclusive)) throw new IllegalArgumentException("toKey out of range"); @@ -1987,6 +2012,7 @@ public NavigableMap headMap(K toKey, boolean inclusive) { toEnd, hi, hiInclusive); } + @SuppressWarnings("unchecked") // package needs update to Java 1.8 generics for maps public NavigableMap tailMap(K fromKey, boolean inclusive) { if (!inRange(fromKey, inclusive)) throw new IllegalArgumentException("fromKey out of range"); @@ -1995,6 +2021,7 @@ public NavigableMap tailMap(K fromKey, boolean inclusive) { false, fromKey, inclusive); } + @SuppressWarnings("unchecked") // package needs update to Java 1.8 generics for maps public NavigableMap descendingMap() { NavigableMap mv = descendingMapView; return (mv != null) ? mv : @@ -2057,6 +2084,7 @@ IndexedTreeMap.Entry subLower(K key) { * * @serial include */ + @SuppressWarnings("unchecked") // package needs update to Java 1.8 generics for maps private class SubMap extends AbstractMap implements SortedMap, java.io.Serializable { private static final long serialVersionUID = -6520786458950516097L; @@ -2674,6 +2702,7 @@ private void buildFromSorted(int size, Iterator it, * @param redLevel the level at which nodes should be red. * Must be equal to computeRedLevel for tree of this size. */ + @SuppressWarnings("unchecked") // package needs update to Java 1.8 generics for maps private final Entry buildFromSorted(int level, int lo, int hi, int redLevel, Iterator it, diff --git a/java/src/jmri/util/com/dictiography/collections/IndexedTreeSet.java b/java/src/jmri/util/com/dictiography/collections/IndexedTreeSet.java index 9f841d6e51c..ddd7daa6f62 100644 --- a/java/src/jmri/util/com/dictiography/collections/IndexedTreeSet.java +++ b/java/src/jmri/util/com/dictiography/collections/IndexedTreeSet.java @@ -187,6 +187,7 @@ public Iterator descendingIterator() { /** * @since 1.6 */ + @SuppressWarnings("unchecked") // package needs update to Java 1.8 generics for maps public NavigableSet descendingSet() { return new IndexedTreeSet(m.descendingMap()); } @@ -288,6 +289,7 @@ public void clear() { * if any element is null and this set uses natural ordering, or * its comparator does not permit null elements */ + @SuppressWarnings("unchecked") // package needs update to Java 1.8 generics for maps public boolean addAll(Collection c) { // Use linear-time version if applicable if (m.size() == 0 && c.size() > 0 && @@ -462,6 +464,7 @@ public E pollLast() { * * @return a shallow copy of this set */ + @SuppressWarnings("unchecked") // package needs update to Java 1.8 generics for maps public Object clone() { IndexedTreeSet clone = null; try { @@ -506,6 +509,7 @@ private void writeObject(java.io.ObjectOutputStream s) * Reconstitute the {@code IndexedTreeSet} instance from a stream (that is, * deserialize it). */ + @SuppressWarnings("unchecked") // package needs update to Java 1.8 generics for maps private void readObject(java.io.ObjectInputStream s) throws java.io.IOException, ClassNotFoundException { // Read in any hidden stuff @@ -530,15 +534,18 @@ private void readObject(java.io.ObjectInputStream s) private static final long serialVersionUID = -2479143000061671589L; + @SuppressWarnings("unchecked") // package needs update to Java 1.8 generics for maps public E exact(int index) { Map.Entry e = ((IndexedNavigableMap) m).exactEntry(index); return (e == null) ? null : e.getKey(); } + @SuppressWarnings("unchecked") // package needs update to Java 1.8 generics for maps public int entryIndex(E e) { return ((IndexedNavigableMap) m).keyIndex(e); } + @SuppressWarnings("unchecked") // package needs update to Java 1.8 generics for maps public void debug() throws Exception { IndexedTreeMap.Entry e = ((IndexedTreeMap) m).getFirstEntry(); while (e != null) { From f4ab115703de0d2cc036b11aa23d6150c1ddee78 Mon Sep 17 00:00:00 2001 From: Bob Jacobsen Date: Sat, 7 Apr 2018 12:35:40 -0700 Subject: [PATCH 36/58] annotate unchecked warnings --- .../jmri/util/com/dictiography/collections/IndexedTreeMap.java | 1 + 1 file changed, 1 insertion(+) diff --git a/java/src/jmri/util/com/dictiography/collections/IndexedTreeMap.java b/java/src/jmri/util/com/dictiography/collections/IndexedTreeMap.java index ceaed51cd81..191944c9b07 100644 --- a/java/src/jmri/util/com/dictiography/collections/IndexedTreeMap.java +++ b/java/src/jmri/util/com/dictiography/collections/IndexedTreeMap.java @@ -1145,6 +1145,7 @@ static final class KeySet extends AbstractSet implements NavigableSet { m = map; } + @SuppressWarnings("unchecked") // package needs update to Java 1.8 generics for maps public Iterator iterator() { if (m instanceof IndexedTreeMap) return ((IndexedTreeMap) m).keyIterator(); From 6511807f9291563d05115edb7a425778ce2173e0 Mon Sep 17 00:00:00 2001 From: Bob Jacobsen Date: Sat, 7 Apr 2018 12:38:37 -0700 Subject: [PATCH 37/58] remove unnecessary casts --- .../util/com/dictiography/collections/IndexedTreeMap.java | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/java/src/jmri/util/com/dictiography/collections/IndexedTreeMap.java b/java/src/jmri/util/com/dictiography/collections/IndexedTreeMap.java index 191944c9b07..94bf0740f8b 100644 --- a/java/src/jmri/util/com/dictiography/collections/IndexedTreeMap.java +++ b/java/src/jmri/util/com/dictiography/collections/IndexedTreeMap.java @@ -1150,7 +1150,7 @@ public Iterator iterator() { if (m instanceof IndexedTreeMap) return ((IndexedTreeMap) m).keyIterator(); else - return (Iterator) (((IndexedTreeMap.NavigableSubMap) m).keyIterator()); + return ((IndexedTreeMap.NavigableSubMap) m).keyIterator(); } @SuppressWarnings("unchecked") // package needs update to Java 1.8 generics for maps @@ -1158,7 +1158,7 @@ public Iterator descendingIterator() { if (m instanceof IndexedTreeMap) return ((IndexedTreeMap) m).descendingKeyIterator(); else - return (Iterator) (((IndexedTreeMap.NavigableSubMap) m).descendingKeyIterator()); + return ((IndexedTreeMap.NavigableSubMap) m).descendingKeyIterator(); } public int size() { From afa42ce798951fe3f03b1f1c097b50034d3c6a78 Mon Sep 17 00:00:00 2001 From: Bob Jacobsen Date: Sat, 7 Apr 2018 12:39:52 -0700 Subject: [PATCH 38/58] annote unused class --- .../jmri/util/com/dictiography/collections/IndexedTreeMap.java | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/java/src/jmri/util/com/dictiography/collections/IndexedTreeMap.java b/java/src/jmri/util/com/dictiography/collections/IndexedTreeMap.java index 94bf0740f8b..3757d3cfc85 100644 --- a/java/src/jmri/util/com/dictiography/collections/IndexedTreeMap.java +++ b/java/src/jmri/util/com/dictiography/collections/IndexedTreeMap.java @@ -2085,7 +2085,7 @@ IndexedTreeMap.Entry subLower(K key) { * * @serial include */ - @SuppressWarnings("unchecked") // package needs update to Java 1.8 generics for maps + @SuppressWarnings("unused") private class SubMap extends AbstractMap implements SortedMap, java.io.Serializable { private static final long serialVersionUID = -6520786458950516097L; From 7273365b468e83a42abfdc34e20b28a7cc7df2f9 Mon Sep 17 00:00:00 2001 From: Bob Jacobsen Date: Sat, 7 Apr 2018 12:53:33 -0700 Subject: [PATCH 39/58] reorg collection paragraph, add new collections --- help/en/html/doc/Technical/RP.shtml | 55 +++++++++++++++++++++++++++-- 1 file changed, 53 insertions(+), 2 deletions(-) diff --git a/help/en/html/doc/Technical/RP.shtml b/help/en/html/doc/Technical/RP.shtml index ad627f4554d..9b645ddcb8c 100644 --- a/help/en/html/doc/Technical/RP.shtml +++ b/help/en/html/doc/Technical/RP.shtml @@ -61,9 +61,21 @@ HashMap, etc) in the java.util package. - Not everything needs to be an array! A - Deque + Not everything needs to be an array! Only use a + Vector + when there's a specific reason for it such as compatibility with an existing API; + they're slow and memory-intensive compared to e.g. an + a href="https://docs.oracle.com/javase/8/docs/api/java/util/ArrayList.html">ArrayList. + A Deque can be a good default solution to holding data that won't ever contain 'null'. + Consider using a + TreeSet + for data that's best kept in some sorted order; there's are very few good reasons for + sorting data during normal running in JMRI. If you also need random access (e.g. + "The 5th element") consider + IndexedTreeSet + and + IndexedTreeMap

  3. JMRI uses + +

    Collections

    + Take a few moments to learn about the different + types of + Java collections that are available ( + List, + Deque, + HashMap, + etc) in the + java.util package. + + +
      +
    • + Please don't use fixed-size arrays for holding variable sized data in objects. + That generally ends up wasting huge amounts of space at runtime, and we + try to keep the JMRI memory footprint small when we can. + +
    • + Only use a + Vector + when there's a specific reason for it such as compatibility with an existing API; + they're slow and memory-intensive compared to e.g. an + a href="https://docs.oracle.com/javase/8/docs/api/java/util/ArrayList.html">ArrayList. +
    • + A Deque + can be a good default solution to holding data that won't ever contain 'null'. +
    • + Consider using a + TreeSet + for data that's best kept in some sorted order; there's are very few good reasons for + sorting data during normal running in JMRI. If you also need random access (e.g. + "The 5th element") consider + IndexedTreeSet + and + IndexedTreeMap +
    +

    Code Format

    The Java Code Conventions (if that link is broken, try From 48e688e0a4458118fae7b31362dbd4426970f095 Mon Sep 17 00:00:00 2001 From: Bob Jacobsen Date: Sat, 7 Apr 2018 13:11:24 -0700 Subject: [PATCH 40/58] improve typesafety --- java/src/jmri/Manager.java | 4 ++-- java/src/jmri/managers/AbstractManager.java | 6 +++--- java/src/jmri/managers/AbstractProxyManager.java | 6 +++--- 3 files changed, 8 insertions(+), 8 deletions(-) diff --git a/java/src/jmri/Manager.java b/java/src/jmri/Manager.java index 3ae0e199c19..5c3c5fbb401 100644 --- a/java/src/jmri/Manager.java +++ b/java/src/jmri/Manager.java @@ -496,12 +496,12 @@ public default String getEntryToolTip() { * Register a {@link ManagerDataListener} to hear about * adding or removing items from the list of NamedBeans */ - public void addDataListener(ManagerDataListener e); + public void addDataListener(ManagerDataListener e); /** * Unregister a previously-added {@link ManagerDataListener} */ - public void removeDataListener(ManagerDataListener e); + public void removeDataListener(ManagerDataListener e); /** * Temporarily suppress DataListener notifications. diff --git a/java/src/jmri/managers/AbstractManager.java b/java/src/jmri/managers/AbstractManager.java index 33249e2ed03..a25e89c6c3e 100644 --- a/java/src/jmri/managers/AbstractManager.java +++ b/java/src/jmri/managers/AbstractManager.java @@ -508,16 +508,16 @@ public NameValidity validSystemNameFormat(String systemName) { } /** {@inheritDoc} */ - public void addDataListener(ManagerDataListener e) { + public void addDataListener(ManagerDataListener e) { if (e != null) listeners.add(e); } /** {@inheritDoc} */ - public void removeDataListener(ManagerDataListener e) { + public void removeDataListener(ManagerDataListener e) { if (e != null) listeners.remove(e); } - final List listeners = new ArrayList<>(); + final List> listeners = new ArrayList<>(); private boolean muted = false; diff --git a/java/src/jmri/managers/AbstractProxyManager.java b/java/src/jmri/managers/AbstractProxyManager.java index 8c427c76f7a..388b2e3e29b 100644 --- a/java/src/jmri/managers/AbstractProxyManager.java +++ b/java/src/jmri/managers/AbstractProxyManager.java @@ -520,16 +520,16 @@ public SortedSet getNamedBeanSet() { } /** {@inheritDoc} */ - public void addDataListener(ManagerDataListener e) { + public void addDataListener(ManagerDataListener e) { if (e != null) listeners.add(e); } /** {@inheritDoc} */ - public void removeDataListener(ManagerDataListener e) { + public void removeDataListener(ManagerDataListener e) { if (e != null) listeners.remove(e); } - final List listeners = new ArrayList<>(); + final List> listeners = new ArrayList<>(); /** * {@inheritDoc} From deea3a0656d076ae80c7dab3ebab489456a9af1e Mon Sep 17 00:00:00 2001 From: Bob Jacobsen Date: Sat, 7 Apr 2018 13:23:40 -0700 Subject: [PATCH 41/58] remove unused --- java/src/jmri/jmrit/audio/AbstractAudioSource.java | 1 - java/src/jmri/jmrit/logix/NXFrame.java | 2 +- java/src/jmri/jmrit/withrottle/UserInterface.java | 3 +-- java/src/jmri/jmrix/mqtt/MqttConnectionConfig.java | 2 +- java/src/jmri/jmrix/roco/z21/Z21XNetOpsModeProgrammer.java | 2 +- 5 files changed, 4 insertions(+), 6 deletions(-) diff --git a/java/src/jmri/jmrit/audio/AbstractAudioSource.java b/java/src/jmri/jmrit/audio/AbstractAudioSource.java index 66be2e76d48..ce238ec13c9 100644 --- a/java/src/jmri/jmrit/audio/AbstractAudioSource.java +++ b/java/src/jmri/jmrit/audio/AbstractAudioSource.java @@ -49,7 +49,6 @@ public abstract class AbstractAudioSource extends AbstractAudio implements Audio private int fadeInTime = 1000; private int fadeOutTime = 1000; private float fadeGain = 1.0f; - private float dopplerFactor = 1.0f; private long timeOfLastFadeCheck = 0; private long timeOfLastPositionCheck = 0; private int fading = Audio.FADE_NONE; diff --git a/java/src/jmri/jmrit/logix/NXFrame.java b/java/src/jmri/jmrit/logix/NXFrame.java index 7867a1aaceb..2bac759d3d6 100644 --- a/java/src/jmri/jmrit/logix/NXFrame.java +++ b/java/src/jmri/jmrit/logix/NXFrame.java @@ -93,7 +93,7 @@ private WarrantPreferences updatePreferences() { private void init() { if (log.isDebugEnabled()) log.debug("newInstance"); - WarrantPreferences preferences = updatePreferences(); + updatePreferences(); makeMenus(); _routePanel = new JPanel(); diff --git a/java/src/jmri/jmrit/withrottle/UserInterface.java b/java/src/jmri/jmrit/withrottle/UserInterface.java index 4bcbd874e35..66fbf269a85 100644 --- a/java/src/jmri/jmrit/withrottle/UserInterface.java +++ b/java/src/jmri/jmrit/withrottle/UserInterface.java @@ -49,8 +49,6 @@ */ public class UserInterface extends JmriJFrame implements DeviceListener, RosterGroupSelector { - private final static Logger log = LoggerFactory.getLogger(UserInterface.class); - JMenuBar menuBar; JMenuItem serverOnOff; JPanel panel; @@ -321,4 +319,5 @@ public String getSelectedRosterGroup() { return rosterGroupSelector.getSelectedRosterGroup(); } + // private final static Logger log = LoggerFactory.getLogger(UserInterface.class); } diff --git a/java/src/jmri/jmrix/mqtt/MqttConnectionConfig.java b/java/src/jmri/jmrix/mqtt/MqttConnectionConfig.java index 6e254b51628..38bbd340e23 100644 --- a/java/src/jmri/jmrix/mqtt/MqttConnectionConfig.java +++ b/java/src/jmri/jmrix/mqtt/MqttConnectionConfig.java @@ -41,5 +41,5 @@ public String getManufacturer() { return(MqttConnectionTypeList.GENMAN); } - private final static Logger log = LoggerFactory.getLogger(MqttConnectionConfig.class); + // private final static Logger log = LoggerFactory.getLogger(MqttConnectionConfig.class); } diff --git a/java/src/jmri/jmrix/roco/z21/Z21XNetOpsModeProgrammer.java b/java/src/jmri/jmrix/roco/z21/Z21XNetOpsModeProgrammer.java index 4d8d2b8eb4c..e7460800de9 100644 --- a/java/src/jmri/jmrix/roco/z21/Z21XNetOpsModeProgrammer.java +++ b/java/src/jmri/jmrix/roco/z21/Z21XNetOpsModeProgrammer.java @@ -117,6 +117,6 @@ synchronized public void message(XNetReply l) { } // initialize logging - private final static Logger log = LoggerFactory.getLogger(Z21XNetOpsModeProgrammer.class); + // private final static Logger log = LoggerFactory.getLogger(Z21XNetOpsModeProgrammer.class); } From b1b41ede2cb6e0d4417bcd46ad9add7fda3530ba Mon Sep 17 00:00:00 2001 From: Bob Jacobsen Date: Sat, 7 Apr 2018 13:49:09 -0700 Subject: [PATCH 42/58] remove unused vars, flag some that seem odd --- java/src/jmri/jmrix/sprog/SprogCommandStation.java | 12 ++++++++++-- .../jmri/jmrit/blockboss/BlockBossLogicTest.java | 2 +- .../jmri/managers/InternalSensorManagerTest.java | 4 ++-- java/test/jmri/managers/ProxySensorManagerTest.java | 9 ++++----- java/test/jmri/server/json/JsonHttpServiceTest.java | 4 ++-- .../server/json/util/JsonUtilHttpServiceTest.java | 5 +++-- 6 files changed, 22 insertions(+), 14 deletions(-) diff --git a/java/src/jmri/jmrix/sprog/SprogCommandStation.java b/java/src/jmri/jmrix/sprog/SprogCommandStation.java index b550167ff6a..3821500c487 100644 --- a/java/src/jmri/jmrix/sprog/SprogCommandStation.java +++ b/java/src/jmri/jmrix/sprog/SprogCommandStation.java @@ -66,7 +66,13 @@ public class SprogCommandStation implements CommandStation, SprogListener, Runna private SprogTrafficController tc = null; final Object lock = new Object(); - private SprogReply reply; + + // it's not at all clear what the following object does. It's only + // set, with a newly created copy of a reply, in notifyReply(SprogReply m); + // it's never referenced. + @SuppressWarnings("unused") // added april 2018; should be removed? + private SprogReply reply; + private boolean waitingForReply = false; private boolean replyAvailable = false; private boolean sendSprogAddress = false; @@ -388,7 +394,6 @@ private synchronized void notifySlotListeners(SprogSlot s) { }); } - private int statusDue = 0; @Override /** * The run() method will only be called (from SprogSystemConnectionMemo @@ -542,7 +547,10 @@ public void notifyReply(SprogReply m) { log.debug("Ignore reply with mismatched id {} looking for {}", m.getId(), lastId); return; } else { + // it's not at all clear what the following line does. The "reply" + // variable is only set here, and never referenced. reply = new SprogReply(m); + log.debug("Reply received [{}]", m.toString()); // Log the reply and wake the slot thread synchronized (lock) { diff --git a/java/test/jmri/jmrit/blockboss/BlockBossLogicTest.java b/java/test/jmri/jmrit/blockboss/BlockBossLogicTest.java index 8ce16028706..f7615ebe87d 100644 --- a/java/test/jmri/jmrit/blockboss/BlockBossLogicTest.java +++ b/java/test/jmri/jmrit/blockboss/BlockBossLogicTest.java @@ -195,7 +195,7 @@ public void testSimpleBlockNoNextLimited() throws jmri.JmriException { public void testSimpleBlockNoSignal() throws jmri.JmriException { try { - BlockBossLogic p1 = new BlockBossLogic(null); + new BlockBossLogic(null); } catch (java.lang.IllegalArgumentException e) { // this is expected } diff --git a/java/test/jmri/managers/InternalSensorManagerTest.java b/java/test/jmri/managers/InternalSensorManagerTest.java index f8e4db9a27b..da3fb2ca6a6 100644 --- a/java/test/jmri/managers/InternalSensorManagerTest.java +++ b/java/test/jmri/managers/InternalSensorManagerTest.java @@ -106,7 +106,7 @@ public void testRenoveTracking() { Sensor s1 = l.provideSensor("IS1"); s1.setUserName("Sensor 1"); Sensor s2 = l.provideSensor("IS2"); - Sensor s3 = l.provideSensor("IS3"); + l.provideSensor("IS3"); l.addDataListener(this); List tlist = l.getNamedBeanList(); @@ -226,7 +226,7 @@ public void testOrderVsSorted() { @Test public void testUnmodifiable() { Sensor s1 = l.provideSensor("IS1"); - Sensor s2 = l.provideSensor("IS2"); + l.provideSensor("IS2"); List nameList = l.getSystemNameList(); List beanList = l.getNamedBeanList(); diff --git a/java/test/jmri/managers/ProxySensorManagerTest.java b/java/test/jmri/managers/ProxySensorManagerTest.java index 333c275722a..4df40a3dc03 100644 --- a/java/test/jmri/managers/ProxySensorManagerTest.java +++ b/java/test/jmri/managers/ProxySensorManagerTest.java @@ -216,7 +216,7 @@ public void testRemoveTrackingI() { Sensor s1 = l.provideSensor("IS1"); s1.setUserName("Sensor 1"); Sensor s2 = l.provideSensor("IS2"); - Sensor s3 = l.provideSensor("IS3"); + l.provideSensor("IS3"); l.addDataListener(this); List tlist = l.getNamedBeanList(); @@ -240,7 +240,7 @@ public void testRemoveTrackingJ() { Sensor s1 = l.provideSensor("JS1"); s1.setUserName("Sensor 1"); Sensor s2 = l.provideSensor("JS2"); - Sensor s3 = l.provideSensor("JS3"); + l.provideSensor("JS3"); l.addDataListener(this); List tlist = l.getNamedBeanList(); @@ -286,10 +286,9 @@ public void testRemoveTrackingJMute() { Sensor s1 = l.provideSensor("JS1"); s1.setUserName("Sensor 1"); Sensor s2 = l.provideSensor("JS2"); - Sensor s3 = l.provideSensor("JS3"); + l.provideSensor("JS3"); l.addDataListener(this); - List tlist = l.getNamedBeanList(); l.deregister(s2); @@ -407,7 +406,7 @@ public void testOrderVsSorted() { public void testUnmodifiable() { Sensor s1 = l.provideSensor("IS1"); - Sensor s2 = l.provideSensor("IS2"); + l.provideSensor("IS2"); List nameList = l.getSystemNameList(); List beanList = l.getNamedBeanList(); diff --git a/java/test/jmri/server/json/JsonHttpServiceTest.java b/java/test/jmri/server/json/JsonHttpServiceTest.java index 2c17152b884..a29f2fc5863 100644 --- a/java/test/jmri/server/json/JsonHttpServiceTest.java +++ b/java/test/jmri/server/json/JsonHttpServiceTest.java @@ -15,8 +15,6 @@ */ public class JsonHttpServiceTest { - private final static Logger log = LoggerFactory.getLogger(JsonHttpServiceTest.class); - @Before public void setUp() { JUnitUtil.setUp(); @@ -77,4 +75,6 @@ public void testDoSchema4Param() { Assert.fail("Should not have thrown exception"); } } + + // private final static Logger log = LoggerFactory.getLogger(JsonHttpServiceTest.class); } diff --git a/java/test/jmri/server/json/util/JsonUtilHttpServiceTest.java b/java/test/jmri/server/json/util/JsonUtilHttpServiceTest.java index c338daed390..e7f100e5d14 100644 --- a/java/test/jmri/server/json/util/JsonUtilHttpServiceTest.java +++ b/java/test/jmri/server/json/util/JsonUtilHttpServiceTest.java @@ -40,8 +40,6 @@ */ public class JsonUtilHttpServiceTest { - private final static Logger log = LoggerFactory.getLogger(JsonUtilHttpServiceTest.class); - public JsonUtilHttpServiceTest() { } @@ -462,4 +460,7 @@ public void testAddressForString() { Assert.assertTrue("Address is long", result.isLongAddress()); Assert.assertEquals("Address is 3", 3, result.getNumber()); } + + // private final static Logger log = LoggerFactory.getLogger(JsonUtilHttpServiceTest.class); + } From 24ab815dd4e107230f95de58f2011a05ad470a87 Mon Sep 17 00:00:00 2001 From: Bob Jacobsen Date: Sat, 7 Apr 2018 13:55:45 -0700 Subject: [PATCH 43/58] drop unnecessary casts --- java/src/jmri/jmrit/roster/RosterEntry.java | 5 ++--- java/test/jmri/server/json/JsonHttpServiceTest.java | 2 +- java/test/jmri/spi/JsonServiceFactoryTest.java | 2 +- 3 files changed, 4 insertions(+), 5 deletions(-) diff --git a/java/src/jmri/jmrit/roster/RosterEntry.java b/java/src/jmri/jmrit/roster/RosterEntry.java index 521488430a1..bad2fa522ba 100644 --- a/java/src/jmri/jmrit/roster/RosterEntry.java +++ b/java/src/jmri/jmrit/roster/RosterEntry.java @@ -1390,8 +1390,7 @@ public void printEntryLine(HardcopyWriter w) { int linesadded = -1; try { - HardcopyWriter ww = (HardcopyWriter) w; - int textSpace = ww.getCharactersPerLine() - 1; // no indent + int textSpace = w.getCharactersPerLine() - 1; // no indent String thisText =""; String thisLine = ""; @@ -1445,7 +1444,7 @@ public void printEntryLine(HardcopyWriter w) { // dateModified (type) if (dateModified != null) { if (dateModified instanceof Date) { - DateFormat.getDateTimeInstance().format((Date) dateModified); + DateFormat.getDateTimeInstance().format(dateModified); } thisText = String.format("%-" + colWidth + "s", dateModified.toString().substring(0, Math.min(dateModified.toString().length(), colWidth))); thisLine += thisText; diff --git a/java/test/jmri/server/json/JsonHttpServiceTest.java b/java/test/jmri/server/json/JsonHttpServiceTest.java index a29f2fc5863..b3888f76b77 100644 --- a/java/test/jmri/server/json/JsonHttpServiceTest.java +++ b/java/test/jmri/server/json/JsonHttpServiceTest.java @@ -31,7 +31,7 @@ public void tearDown() { @Test public void testGetObjectMapper() { ObjectMapper mapper = new ObjectMapper(); - Assert.assertEquals("get object mapper", (Object) mapper, (new JsonTestHttpService(mapper)).getObjectMapper()); + Assert.assertEquals("get object mapper", mapper, (new JsonTestHttpService(mapper)).getObjectMapper()); } /** diff --git a/java/test/jmri/spi/JsonServiceFactoryTest.java b/java/test/jmri/spi/JsonServiceFactoryTest.java index a6ff4f11637..d051a8bbf26 100644 --- a/java/test/jmri/spi/JsonServiceFactoryTest.java +++ b/java/test/jmri/spi/JsonServiceFactoryTest.java @@ -40,7 +40,7 @@ public void testJsonServiceFactories() { Assert.assertEquals("Socket has connection", connection, socket.getConnection()); Assert.assertTrue("Socket creates same HTTP service class as factory", http.getClass().equals(socket.getHttpService().getClass())); // verify HTTP service constructors are populating finals correctly - Assert.assertEquals("HTTP object mapper matches connection", (Object) connection.getObjectMapper(), http.getObjectMapper()); + Assert.assertEquals("HTTP object mapper matches connection", connection.getObjectMapper(), http.getObjectMapper()); }); } From fbdb88452dbd2570aebbaa09a1c9ee8c2731a992 Mon Sep 17 00:00:00 2001 From: Bob Jacobsen Date: Sat, 7 Apr 2018 13:58:29 -0700 Subject: [PATCH 44/58] proper typing of test class --- java/test/jmri/managers/InternalSensorManagerTest.java | 2 +- java/test/jmri/managers/ProxySensorManagerTest.java | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/java/test/jmri/managers/InternalSensorManagerTest.java b/java/test/jmri/managers/InternalSensorManagerTest.java index da3fb2ca6a6..1b81bd0808a 100644 --- a/java/test/jmri/managers/InternalSensorManagerTest.java +++ b/java/test/jmri/managers/InternalSensorManagerTest.java @@ -17,7 +17,7 @@ * * @author Bob Jacobsen Copyright 2016 */ -public class InternalSensorManagerTest extends jmri.managers.AbstractSensorMgrTestBase implements Manager.ManagerDataListener, PropertyChangeListener { +public class InternalSensorManagerTest extends jmri.managers.AbstractSensorMgrTestBase implements Manager.ManagerDataListener, PropertyChangeListener { /** {@inheritDoc} */ @Override diff --git a/java/test/jmri/managers/ProxySensorManagerTest.java b/java/test/jmri/managers/ProxySensorManagerTest.java index 4df40a3dc03..e3327c39eed 100644 --- a/java/test/jmri/managers/ProxySensorManagerTest.java +++ b/java/test/jmri/managers/ProxySensorManagerTest.java @@ -16,7 +16,7 @@ * * @author Bob Jacobsen 2003, 2006, 2008, 2014 */ -public class ProxySensorManagerTest extends TestCase implements Manager.ManagerDataListener, PropertyChangeListener { +public class ProxySensorManagerTest extends TestCase implements Manager.ManagerDataListener, PropertyChangeListener { protected ProxySensorManager l = null; // holds objects under test From 8f8c0e82f5db4fd303e4f668f33fff66c1221937 Mon Sep 17 00:00:00 2001 From: Bob Jacobsen Date: Sat, 7 Apr 2018 14:02:52 -0700 Subject: [PATCH 45/58] html format? --- help/en/html/doc/Technical/RP.shtml | 8 +++----- 1 file changed, 3 insertions(+), 5 deletions(-) diff --git a/help/en/html/doc/Technical/RP.shtml b/help/en/html/doc/Technical/RP.shtml index 9b645ddcb8c..30047e1d4cc 100644 --- a/help/en/html/doc/Technical/RP.shtml +++ b/help/en/html/doc/Technical/RP.shtml @@ -92,14 +92,12 @@ this page from the Java Tutorial.
  4. If you need to use comma-separated variable (CSV) - files, please use the javacsv API if + files, please use the javacsv API if possible. We are already using that in a number of places, and will probably use it in more. If that doesn't provide enough functionality, we might eventually move to the - - opencsv API, but since we only want to use one, the + opencsv API, + but since we only want to use one, the conversion will be a lot of work.
  5. From fe9d9dd46b022bf1791aa063349321524b61a48b Mon Sep 17 00:00:00 2001 From: Bob Jacobsen Date: Sat, 7 Apr 2018 15:55:15 -0700 Subject: [PATCH 46/58] html fix --- help/en/html/doc/Technical/RP.shtml | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/help/en/html/doc/Technical/RP.shtml b/help/en/html/doc/Technical/RP.shtml index 30047e1d4cc..65822f13f9a 100644 --- a/help/en/html/doc/Technical/RP.shtml +++ b/help/en/html/doc/Technical/RP.shtml @@ -65,7 +65,7 @@ Vector when there's a specific reason for it such as compatibility with an existing API; they're slow and memory-intensive compared to e.g. an - a href="https://docs.oracle.com/javase/8/docs/api/java/util/ArrayList.html">ArrayList. + ArrayList. A Deque can be a good default solution to holding data that won't ever contain 'null'. Consider using a @@ -125,7 +125,7 @@ Vector when there's a specific reason for it such as compatibility with an existing API; they're slow and memory-intensive compared to e.g. an - a href="https://docs.oracle.com/javase/8/docs/api/java/util/ArrayList.html">ArrayList. + ArrayList.
  6. A Deque can be a good default solution to holding data that won't ever contain 'null'. From b92194f953ae0fedd6e52c75c60e84090c25cb49 Mon Sep 17 00:00:00 2001 From: Bob Jacobsen Date: Sat, 7 Apr 2018 16:56:18 -0700 Subject: [PATCH 47/58] OPC_SW_REP INPUT AUX Closed/Thrown sets EXACT mode on initial encounter --- .../jmri/jmrix/loconet/LnTurnoutManager.java | 17 ++++++++++++++++- 1 file changed, 16 insertions(+), 1 deletion(-) diff --git a/java/src/jmri/jmrix/loconet/LnTurnoutManager.java b/java/src/jmri/jmrix/loconet/LnTurnoutManager.java index b9f8bce187e..19fd74c1964 100644 --- a/java/src/jmri/jmrix/loconet/LnTurnoutManager.java +++ b/java/src/jmri/jmrix/loconet/LnTurnoutManager.java @@ -159,7 +159,7 @@ public void message(LocoNetMessage l) { lastSWREQ = null; return; } - // reach here for loconet switch command; make sure we know about this one + // reach here for loconet switch command; make sure that a Turnout with this name exists String s = prefix + "T" + addr; // NOI18N if (getBySystemName(s) == null) { // no turnout with this address, is there a light? @@ -167,6 +167,21 @@ public void message(LocoNetMessage l) { if (jmri.InstanceManager.lightManagerInstance().getBySystemName(sx) == null) { // no light, create a turnout LnTurnout t = (LnTurnout) provideTurnout(s); + + // if this is an OPC_SW_REP INPUT message for the AUX input, + // then the actual turnout must be in EXACT feedback mode + if (l.getOpCode() == LnConstants.OPC_SW_REP) { + if ( (l.getElement(2) & LnConstants.OPC_SW_REP_INPUTS) != 0) { + // INPUT + if ( (l.getElement(2) & LnConstants.OPC_SW_REP_SW) == 0) { + // AUX - set exact feedback + log.debug("setting EXACT based on initial message: {}", l); + t.setFeedbackMode(LnTurnout.EXACT); + } + } + } + + // process the message to put the turnout in the right state t.message(l); } } From 37116c7c014205915e48c88057f7f28808ddb426 Mon Sep 17 00:00:00 2001 From: Bob Jacobsen Date: Sat, 7 Apr 2018 17:33:42 -0700 Subject: [PATCH 48/58] handle OPC_SW_REP INPUT messages on init --- java/src/jmri/jmrix/loconet/LnTurnout.java | 44 +++++++++++++++++-- .../jmri/jmrix/loconet/LnTurnoutManager.java | 14 +----- .../jmrix/loconet/LnTurnoutManagerTest.java | 10 +++++ 3 files changed, 52 insertions(+), 16 deletions(-) diff --git a/java/src/jmri/jmrix/loconet/LnTurnout.java b/java/src/jmri/jmrix/loconet/LnTurnout.java index 69e380f8f2e..5f607024465 100644 --- a/java/src/jmri/jmrix/loconet/LnTurnout.java +++ b/java/src/jmri/jmrix/loconet/LnTurnout.java @@ -1,5 +1,6 @@ package jmri.jmrix.loconet; +import javax.annotation.*; import edu.umd.cs.findbugs.annotations.SuppressFBWarnings; import jmri.NmraPacket; import jmri.implementation.AbstractTurnout; @@ -70,6 +71,26 @@ public LnTurnout(String prefix, int number, LocoNetInterface controller) throws } LocoNetInterface controller; + + /** + * True when setFeedbackMode has specified the mode; + * false when the mode is just left over from initialization. + * This is intended to indicate (when true) that a configuration + * file has set the value; message-created turnouts have it false. + */ + boolean feedbackDeliberatelySet = false; // package to allow access from LnTurnoutManager + + @Override + public void setFeedbackMode(@Nonnull String mode) throws IllegalArgumentException { + feedbackDeliberatelySet = true; + super.setFeedbackMode(mode); + } + + @Override + public void setFeedbackMode(int mode) throws IllegalArgumentException { + feedbackDeliberatelySet = true; + super.setFeedbackMode(mode); + } @SuppressFBWarnings(value = "ST_WRITE_TO_STATIC_FROM_INSTANCE_METHOD", justification = "Only used during creation of 1st turnout") // NOI18N @@ -238,8 +259,9 @@ public void message(LocoNetMessage l) { newKnownState(state); } } - break; + return; } + case LnConstants.OPC_SW_REP: { /* page 9 of Loconet PE */ @@ -297,6 +319,10 @@ public void message(LocoNetMessage l) { } else if (getFeedbackMode() == INDIRECT) { // reached closed state newKnownState(adjustStateForInversion(CLOSED)); + } else if (!feedbackDeliberatelySet) { + // don't have a defined feedback mode, but know we've reached closed state + log.debug("setting CLOSED with !feedbackDeliberatelySet"); + newKnownState(adjustStateForInversion(CLOSED)); } } else { // switch input thrown (input on) @@ -308,10 +334,22 @@ public void message(LocoNetMessage l) { } else if (getFeedbackMode() == INDIRECT) { // reached thrown state newKnownState(adjustStateForInversion(THROWN)); + } else if (!feedbackDeliberatelySet) { + // don't have a defined feedback mode, but know we're not in closed state, most likely is actually thrown + log.debug("setting THROWN with !feedbackDeliberatelySet"); + newKnownState(adjustStateForInversion(THROWN)); } } } else { // Aux input report + + // This is only valid in EXACT mode, so if we encounter it + // without a feedback mode set, we switch to EXACT + if (!feedbackDeliberatelySet) { + setFeedbackMode(EXACT); + feedbackDeliberatelySet = false; // was set when setting feedback + } + if ((sw2 & LnConstants.OPC_SW_REP_HI) != 0) { // aux input closed (off) if (getFeedbackMode() == EXACT) { @@ -331,12 +369,12 @@ public void message(LocoNetMessage l) { } } + return; } - //$FALL-THROUGH$ + default: return; } - // reach here only in error } @Override diff --git a/java/src/jmri/jmrix/loconet/LnTurnoutManager.java b/java/src/jmri/jmrix/loconet/LnTurnoutManager.java index 19fd74c1964..0f4b6fdbef3 100644 --- a/java/src/jmri/jmrix/loconet/LnTurnoutManager.java +++ b/java/src/jmri/jmrix/loconet/LnTurnoutManager.java @@ -1,5 +1,6 @@ package jmri.jmrix.loconet; +import javax.annotation.*; import jmri.Turnout; import org.slf4j.Logger; import org.slf4j.LoggerFactory; @@ -168,19 +169,6 @@ public void message(LocoNetMessage l) { // no light, create a turnout LnTurnout t = (LnTurnout) provideTurnout(s); - // if this is an OPC_SW_REP INPUT message for the AUX input, - // then the actual turnout must be in EXACT feedback mode - if (l.getOpCode() == LnConstants.OPC_SW_REP) { - if ( (l.getElement(2) & LnConstants.OPC_SW_REP_INPUTS) != 0) { - // INPUT - if ( (l.getElement(2) & LnConstants.OPC_SW_REP_SW) == 0) { - // AUX - set exact feedback - log.debug("setting EXACT based on initial message: {}", l); - t.setFeedbackMode(LnTurnout.EXACT); - } - } - } - // process the message to put the turnout in the right state t.message(l); } diff --git a/java/test/jmri/jmrix/loconet/LnTurnoutManagerTest.java b/java/test/jmri/jmrix/loconet/LnTurnoutManagerTest.java index c14935548b3..e6248a6214d 100644 --- a/java/test/jmri/jmrix/loconet/LnTurnoutManagerTest.java +++ b/java/test/jmri/jmrix/loconet/LnTurnoutManagerTest.java @@ -81,6 +81,16 @@ public void testLocoNetMessages() { Assert.assertEquals("system name list", testList, l.getSystemNameList()); } + @Test + public void testCreateFromMessage4 () { + // Turnout LT64 () Aux input is Closed (input off). + LocoNetMessage m = new LocoNetMessage(new int[]{0xb1, 0x3F, 0x50, 0x2F, 0}); + lnis.sendTestMessage(m); + Assert.assertTrue(null != l.getBySystemName("LT64")); + Assert.assertEquals("EXACT", l.getBySystemName("LT64").getFeedbackModeName()); + Assert.assertEquals(Turnout.THROWN, l.getBySystemName("LT64").getKnownState()); + } + @Test public void testAsAbstractFactory() { // ask for a Turnout, and check type From d99ca8634da05e01c99748554f0f2ce58c94490a Mon Sep 17 00:00:00 2001 From: Bob Jacobsen Date: Sun, 8 Apr 2018 10:44:20 -0700 Subject: [PATCH 49/58] some methods final to avoid bad implementations; comment others --- .../implementation/AbstractNamedBean.java | 35 ++++++++++++------- 1 file changed, 22 insertions(+), 13 deletions(-) diff --git a/java/src/jmri/implementation/AbstractNamedBean.java b/java/src/jmri/implementation/AbstractNamedBean.java index 8edfa8a6c0d..785ccee4b10 100644 --- a/java/src/jmri/implementation/AbstractNamedBean.java +++ b/java/src/jmri/implementation/AbstractNamedBean.java @@ -60,23 +60,18 @@ protected AbstractNamedBean(@Nonnull String sys, @Nullable String user) throws N } /** - * Get associated comment text. + * {@inheritDoc} */ @Override - public String getComment() { + final public String getComment() { return this.comment; } /** - * Set associated comment text. - *

    - * Comments can be any valid text. - * - * @param comment 'nulln means no comment associated. + * {@inheritDoc} */ @Override - @OverridingMethodsMustInvokeSuper - public void setComment(String comment) { + final public void setComment(String comment) { String old = this.comment; if (comment == null || comment.trim().isEmpty()) { this.comment = null; @@ -88,8 +83,12 @@ public void setComment(String comment) { private String comment; /** - * Get the name string of this object. - * + * {@inheritDoc} + *

    + * It would be good to eventually make this final to + * keep it consistent system-wide, but + * we have some existing classes to update first. + * * @return user name if not null or empty, else return system name */ @Override @@ -102,6 +101,12 @@ public String getDisplayName() { } } + /** + *

    + * It would be good to eventually make this final to + * keep it consistent system-wide, but + * we have some existing classes to update first. + */ @Override public String getFullyFormattedDisplayName() { String name = getUserName(); @@ -203,12 +208,16 @@ public synchronized PropertyChangeListener[] getPropertyChangeListeners() { } @Override - public String getSystemName() { + final public String getSystemName() { return mSystemName; } /** * {@inheritDoc} + *

    + * It would be good to eventually make this final to + * keep it consistent system-wide, but + * we have some existing classes to update first. */ @Nonnull @Override @@ -217,7 +226,7 @@ public String toString() { } @Override - public String getUserName() { + final public String getUserName() { return mUserName; } From 2068d9a593109a9e5a517c0fd965ecabd6516e03 Mon Sep 17 00:00:00 2001 From: Bob Jacobsen Date: Sun, 8 Apr 2018 10:44:43 -0700 Subject: [PATCH 50/58] comment inconsistent methods --- java/src/jmri/implementation/AbstractIdTag.java | 4 ++++ java/src/jmri/implementation/DefaultRailCom.java | 4 ++++ java/src/jmri/implementation/DefaultSignalSystem.java | 4 ++++ 3 files changed, 12 insertions(+) diff --git a/java/src/jmri/implementation/AbstractIdTag.java b/java/src/jmri/implementation/AbstractIdTag.java index 50fd6c7242d..8f79d84bc9f 100644 --- a/java/src/jmri/implementation/AbstractIdTag.java +++ b/java/src/jmri/implementation/AbstractIdTag.java @@ -57,6 +57,10 @@ public Date getWhenLastSeen() { } } + // note that this doesn't properly implement the + // contract in {@link NamedBean.toString()}, + // which means things like tables and persistance + // might not behave properly. @Override public String toString() { String userName = getUserName(); diff --git a/java/src/jmri/implementation/DefaultRailCom.java b/java/src/jmri/implementation/DefaultRailCom.java index 6d6eecd4703..e494a4c318f 100644 --- a/java/src/jmri/implementation/DefaultRailCom.java +++ b/java/src/jmri/implementation/DefaultRailCom.java @@ -284,6 +284,10 @@ public List getCVList() { Hashtable cvValues = new Hashtable<>(); + // note that this doesn't properly implement the + // contract in {@link NamedBean.toString()}, + // which means things like tables and persistance + // might not behave properly. @Override public String toString() { String comment; diff --git a/java/src/jmri/implementation/DefaultSignalSystem.java b/java/src/jmri/implementation/DefaultSignalSystem.java index 1ae4511056c..8e92238eb52 100644 --- a/java/src/jmri/implementation/DefaultSignalSystem.java +++ b/java/src/jmri/implementation/DefaultSignalSystem.java @@ -178,6 +178,10 @@ public float getMaximumLineSpeed() { protected java.util.Vector imageTypes = new java.util.Vector<>(); + // note that this doesn't properly implement the + // contract in {@link NamedBean.toString()}, + // which means things like tables and persistance + // might not behave properly. @Override public String toString() { StringBuilder retval = new StringBuilder(); From 6938e1fdc592e747aa3978623c136594a51de2cb Mon Sep 17 00:00:00 2001 From: Bob Jacobsen Date: Sun, 8 Apr 2018 10:45:33 -0700 Subject: [PATCH 51/58] comment inconsistent methods --- java/src/jmri/jmrit/audio/AbstractAudioSource.java | 4 ++++ java/src/jmri/jmrit/logix/Portal.java | 4 ++++ 2 files changed, 8 insertions(+) diff --git a/java/src/jmri/jmrit/audio/AbstractAudioSource.java b/java/src/jmri/jmrit/audio/AbstractAudioSource.java index ce238ec13c9..24447b3e442 100644 --- a/java/src/jmri/jmrit/audio/AbstractAudioSource.java +++ b/java/src/jmri/jmrit/audio/AbstractAudioSource.java @@ -832,6 +832,10 @@ protected int getFading() { return this.fading; } + // note that this doesn't properly implement the + // contract in {@link NamedBean.toString()}, + // which means things like tables and persistance + // might not behave properly. @Override public String toString() { return "Pos: " + this.getPosition().toString() diff --git a/java/src/jmri/jmrit/logix/Portal.java b/java/src/jmri/jmrit/logix/Portal.java index 065887aeede..42a37d23187 100644 --- a/java/src/jmri/jmrit/logix/Portal.java +++ b/java/src/jmri/jmrit/logix/Portal.java @@ -625,6 +625,10 @@ public String getDescription() { } @Override + // note that this doesn't properly implement the + // contract in {@link NamedBean.toString()}, + // which means things like tables and persistance + // might not behave properly. public String toString() { StringBuilder sb = new StringBuilder("Portal \""); sb.append(getUserName()); From 43c0751606f76c6a31068ef2677b52e86c1a021a Mon Sep 17 00:00:00 2001 From: Bob Jacobsen Date: Sun, 8 Apr 2018 10:45:48 -0700 Subject: [PATCH 52/58] remove unneeded overrides --- java/src/jmri/implementation/AbstractReporter.java | 6 ------ java/src/jmri/implementation/SE8cSignalHead.java | 12 ------------ 2 files changed, 18 deletions(-) diff --git a/java/src/jmri/implementation/AbstractReporter.java b/java/src/jmri/implementation/AbstractReporter.java index 227a6b7b85a..1d82a6c9386 100644 --- a/java/src/jmri/implementation/AbstractReporter.java +++ b/java/src/jmri/implementation/AbstractReporter.java @@ -31,12 +31,6 @@ public String getBeanType() { return Bundle.getMessage("BeanNameReporter"); } - // for combo boxes - @Override - public String toString() { - return getDisplayName(); - } - @Override public Object getCurrentReport() { return _currentReport; diff --git a/java/src/jmri/implementation/SE8cSignalHead.java b/java/src/jmri/implementation/SE8cSignalHead.java index 11813a5e97d..5b664d07b15 100644 --- a/java/src/jmri/implementation/SE8cSignalHead.java +++ b/java/src/jmri/implementation/SE8cSignalHead.java @@ -46,7 +46,6 @@ public SE8cSignalHead(NamedBeanHandle lowTO, super(makeSystemName(lowTO, highTO), userName); this.lowTurnout = lowTO; this.highTurnout = highTO; - systemName = makeSystemName(lowTO, highTO); init(); } @@ -62,7 +61,6 @@ public SE8cSignalHead(NamedBeanHandle lowTO, super(makeSystemName(lowTO, highTO)); this.lowTurnout = lowTO; this.highTurnout = highTO; - systemName = makeSystemName(lowTO, highTO); init(); } @@ -81,7 +79,6 @@ public SE8cSignalHead(String sname, NamedBeanHandle lowTO, super(sname, userName); this.lowTurnout = lowTO; this.highTurnout = highTO; - systemName = sname; init(); } @@ -98,7 +95,6 @@ public SE8cSignalHead(String sname, NamedBeanHandle lowTO, super(sname); this.lowTurnout = lowTO; this.highTurnout = highTO; - systemName = sname; init(); } @@ -112,7 +108,6 @@ public SE8cSignalHead(int pNumber, String userName) { super("LH" + pNumber, userName); this.lowTurnout = makeHandle(pNumber); this.highTurnout = makeHandle(pNumber + 1); - systemName = "LH" + pNumber; init(); } @@ -156,7 +151,6 @@ public SE8cSignalHead(int pNumber) { super("LH" + pNumber); this.lowTurnout = makeHandle(pNumber); this.highTurnout = makeHandle(pNumber + 1); - systemName = "LH" + pNumber; init(); } @@ -173,12 +167,6 @@ void init() { updateOutput(); } - @Override - public String getSystemName() { - return systemName; - } - String systemName; - /** * Type-specific routine to handle output to the layout hardware. * Implemented to handle a request to change state by sending a LocoNet From eeb2b81fb35110d0468a41a66427f05c98ace3f6 Mon Sep 17 00:00:00 2001 From: Bob Jacobsen Date: Sun, 8 Apr 2018 10:46:17 -0700 Subject: [PATCH 53/58] remove unneeded overrides --- java/src/jmri/jmrit/display/layoutEditor/LayoutBlock.java | 6 ------ java/src/jmri/jmrit/logix/OBlock.java | 5 ----- java/src/jmri/jmrix/loconet/SE8cSignalHead.java | 5 ----- 3 files changed, 16 deletions(-) diff --git a/java/src/jmri/jmrit/display/layoutEditor/LayoutBlock.java b/java/src/jmri/jmrit/display/layoutEditor/LayoutBlock.java index ce7878d5d54..a72ba42134c 100644 --- a/java/src/jmri/jmrit/display/layoutEditor/LayoutBlock.java +++ b/java/src/jmri/jmrit/display/layoutEditor/LayoutBlock.java @@ -212,12 +212,6 @@ protected void initializeLayoutBlockRouting() { }); } - // this should only be used for debugging... - @Override - public String toString() { - return "LayoutBlock " + getDisplayName(); - } - /* * Accessor methods */ diff --git a/java/src/jmri/jmrit/logix/OBlock.java b/java/src/jmri/jmrit/logix/OBlock.java index 4ae4d78d805..7f2e194292a 100644 --- a/java/src/jmri/jmrit/logix/OBlock.java +++ b/java/src/jmri/jmrit/logix/OBlock.java @@ -947,11 +947,6 @@ public String getDescription() { Bundle.getMessage("BlockDescription"), getDisplayName()); } - @Override - public String toString() { - return getDisplayName(); - } - @Override public String getBeanType() { return Bundle.getMessage("BeanNameOBlock"); diff --git a/java/src/jmri/jmrix/loconet/SE8cSignalHead.java b/java/src/jmri/jmrix/loconet/SE8cSignalHead.java index 43dd0318ca7..94d430e7c3b 100644 --- a/java/src/jmri/jmrix/loconet/SE8cSignalHead.java +++ b/java/src/jmri/jmrix/loconet/SE8cSignalHead.java @@ -63,11 +63,6 @@ public int getNumber() { return mNumber; } - @Override - public String getSystemName() { - return "LH" + getNumber(); // NOI18N - } - // Handle a request to change state by sending a LocoNet command @Override protected void updateOutput() { From 7b711d33c78f3a28a1a97a66690e9529301a9e1b Mon Sep 17 00:00:00 2001 From: Bob Jacobsen Date: Sun, 8 Apr 2018 10:46:35 -0700 Subject: [PATCH 54/58] make test more reliable --- java/test/jmri/jmrit/entryexit/AddEntryExitPairPanelTest.java | 2 ++ 1 file changed, 2 insertions(+) diff --git a/java/test/jmri/jmrit/entryexit/AddEntryExitPairPanelTest.java b/java/test/jmri/jmrit/entryexit/AddEntryExitPairPanelTest.java index 18cdb526ccf..74f82e4179b 100644 --- a/java/test/jmri/jmrit/entryexit/AddEntryExitPairPanelTest.java +++ b/java/test/jmri/jmrit/entryexit/AddEntryExitPairPanelTest.java @@ -60,6 +60,8 @@ public void testPanelActions() throws Exception { // Open the Options window String[] optionPath = {"Options", "Options"}; // NOI18N JMenuBarOperator nxMenu = new JMenuBarOperator(nxFrame); + + nxMenu.getTimeouts().setTimeout("JMenuOperator.WaitBeforePopupTimeout", 30L); nxMenu.pushMenu(optionPath); // Close the options window From 1531aeb0e771c544b5a0a668c17bd8f5187ddb47 Mon Sep 17 00:00:00 2001 From: Egbert Broerse Date: Mon, 9 Apr 2018 00:11:07 +0200 Subject: [PATCH 55/58] Spotbugs --- java/src/jmri/ConditionalVariable.java | 2 +- java/src/jmri/jmrit/roster/RosterEntry.java | 9 +++------ .../jmri/jmrix/maple/simulator/SimulatorAdapter.java | 10 +--------- 3 files changed, 5 insertions(+), 16 deletions(-) diff --git a/java/src/jmri/ConditionalVariable.java b/java/src/jmri/ConditionalVariable.java index 2286c1b6b96..0d01965e071 100644 --- a/java/src/jmri/ConditionalVariable.java +++ b/java/src/jmri/ConditionalVariable.java @@ -931,7 +931,7 @@ public static String getTestTypeString(int t) { case Conditional.TYPE_SIGNAL_HEAD_FLASHYELLOW: return Bundle.getMessage("SignalHeadStateFlashingYellow"); // NOI18N case Conditional.TYPE_SIGNAL_HEAD_FLASHGREEN: - Bundle.getMessage("SignalHeadStateFlashingGreen"); // NOI18N + return Bundle.getMessage("SignalHeadStateFlashingGreen"); // NOI18N case Conditional.TYPE_SIGNAL_HEAD_LIT: return Bundle.getMessage("SignalHeadStateLit"); // NOI18N case Conditional.TYPE_SIGNAL_HEAD_HELD: diff --git a/java/src/jmri/jmrit/roster/RosterEntry.java b/java/src/jmri/jmrit/roster/RosterEntry.java index bad2fa522ba..dd1080b9c1c 100644 --- a/java/src/jmri/jmrit/roster/RosterEntry.java +++ b/java/src/jmri/jmrit/roster/RosterEntry.java @@ -67,7 +67,6 @@ * @author Dennis Miller Copyright 2004 * @author Egbert Broerse Copyright (C) 2018 * @see jmri.jmrit.roster.LocoFile - * */ public class RosterEntry extends ArbitraryBean implements RosterObject, BasicRosterEntry { @@ -1387,10 +1386,10 @@ public void loadCvModel(VariableTableModel varModel, CvTableModel cvModel) { public void printEntryLine(HardcopyWriter w) { // no image // @see #printEntryDetails(w); - int linesadded = -1; try { - int textSpace = w.getCharactersPerLine() - 1; // no indent + //int textSpace = w.getCharactersPerLine() - 1; // could be used to truncate line. + // for now, text just flows to next line String thisText =""; String thisLine = ""; @@ -1443,9 +1442,7 @@ public void printEntryLine(HardcopyWriter w) { startNext += colWidth; // dateModified (type) if (dateModified != null) { - if (dateModified instanceof Date) { - DateFormat.getDateTimeInstance().format(dateModified); - } + DateFormat.getDateTimeInstance().format(dateModified); thisText = String.format("%-" + colWidth + "s", dateModified.toString().substring(0, Math.min(dateModified.toString().length(), colWidth))); thisLine += thisText; } diff --git a/java/src/jmri/jmrix/maple/simulator/SimulatorAdapter.java b/java/src/jmri/jmrix/maple/simulator/SimulatorAdapter.java index ede99e85066..fb69bb85d6b 100644 --- a/java/src/jmri/jmrix/maple/simulator/SimulatorAdapter.java +++ b/java/src/jmri/jmrix/maple/simulator/SimulatorAdapter.java @@ -41,10 +41,6 @@ public class SimulatorAdapter extends SerialPortController implements jmri.jmrix private boolean outputBufferEmpty = true; private boolean checkBuffer = true; - /** - * Simulator auto-init setting for number of banks to auto-reply on poll - */ - private int autoInit = 0; /** * Create a new SimulatorAdapter. @@ -274,10 +270,6 @@ private SerialReply generateReply(SerialMessage msg) { case "RC": // Read Coils message log.debug("Read Coils (poll) message detected"); int i = 1; - int lastNode = 1; - if (nodeAddress == 0) { // broadcast poll, reply from all existing nodes - lastNode = 99; - } // init reply log.debug("RC Reply from node {}", nodeAddress); reply.setElement(0, 0x02); // @@ -326,7 +318,7 @@ private int getStartAddress(SerialMessage msg) { } /** - * Extract the number of coils to precess from RC/WC message. + * Extract the number of coils to process from RC/WC message. * * @param msg te SerialMessage received from Simulator inpipe * @return the number of consecutive coils to read/write (decimal) From 81482cf0beab7cd13552635e4c9225b9b76d8679 Mon Sep 17 00:00:00 2001 From: Paul Bender Date: Sun, 8 Apr 2018 22:42:22 -0400 Subject: [PATCH 56/58] additonal tests for IconAdder --- .../jmrit/display/EditorIconFrameTest.java | 94 +++++++++++++++++++ .../jmri/jmrit/display/IconAdderTest.java | 57 +++++++++++ java/test/jmri/jmrit/display/PackageTest.java | 1 + 3 files changed, 152 insertions(+) create mode 100644 java/test/jmri/jmrit/display/EditorIconFrameTest.java diff --git a/java/test/jmri/jmrit/display/EditorIconFrameTest.java b/java/test/jmri/jmrit/display/EditorIconFrameTest.java new file mode 100644 index 00000000000..aa19707728e --- /dev/null +++ b/java/test/jmri/jmrit/display/EditorIconFrameTest.java @@ -0,0 +1,94 @@ +package jmri.jmrit.display; + +import java.awt.GraphicsEnvironment; +import java.util.Arrays; +import java.util.Collection; +import javax.swing.JFrame; +import jmri.util.JUnitUtil; +import org.junit.After; +import org.junit.Assert; +import org.junit.Assume; +import org.junit.Before; +import org.junit.Test; +import org.junit.runners.Parameterized; +import org.junit.runners.Parameterized.Parameters; +import org.junit.runner.RunWith; + +/** + * This is a parameterized test for Editor object's getIconFrame + * method. It tests that the method returns a vaid value for all + * expected parameters to the method. + * + * @author Paul Bender Copyright (C) 2018 + */ +@RunWith(Parameterized.class) +public class EditorIconFrameTest { + + private Editor e = null; + private EditorFrameOperator jfo; + private String inputString; + private boolean expectNull; + + public EditorIconFrameTest(String input,boolean nullExpected){ + inputString = input; + expectNull = nullExpected; + } + + @Parameterized.Parameters + public static Collection iconTypes() { + return Arrays.asList(new Object[][] { + {"Sensor",false}, + {"RightTurnout",false}, + {"LeftTurnout",false}, + {"SlipTOEditor",false}, + {"SignalHead",false}, + {"SignalMast",false}, + {"Memory",false}, + {"Reporter",false}, + {"Light",false}, + {"Background",false}, + {"MultiSensor",false}, + {"Icon",false}, + //{"Text",true}, //see note in test method. + {"BlockLabel",false}, + {"bar",true}, + }); + } + + @Test + public void checkGetIconFrame() { + Assume.assumeFalse(GraphicsEnvironment.isHeadless()); + if(expectNull) { + if(inputString == "Text" ) { + // "Text" pops up a modal JOptionPane, we need to close it. + } + JFrame frame = e.getIconFrame(inputString); + Assert.assertNull(inputString + " Editor expects null return value", frame); + } else { + JFrame frame = e.getIconFrame(inputString); + Assert.assertNotNull(inputString + " Editor available", frame ); + frame.dispose(); + } + } + + // from here down is testing infrastructure + @Before + public void setUp(){ + JUnitUtil.setUp(); + if(!GraphicsEnvironment.isHeadless()) { + e = new EditorScaffold(inputString + " IconAdder test Editor"); + e.setVisible(true); + jfo = new EditorFrameOperator(e); + } + } + + @After + public void tearDown(){ + if(!GraphicsEnvironment.isHeadless()) { + jfo.requestClose(); + } + e = null; + JUnitUtil.setUp(); + } + +} diff --git a/java/test/jmri/jmrit/display/IconAdderTest.java b/java/test/jmri/jmrit/display/IconAdderTest.java index b90078f86d7..f506b61cfb1 100644 --- a/java/test/jmri/jmrit/display/IconAdderTest.java +++ b/java/test/jmri/jmrit/display/IconAdderTest.java @@ -2,10 +2,12 @@ import java.awt.GraphicsEnvironment; import jmri.util.JUnitUtil; +import jmri.util.JmriJFrame; import org.junit.After; import org.junit.Assert; import org.junit.Assume; import org.junit.Before; +import org.junit.Ignore; import org.junit.Test; /** @@ -20,6 +22,7 @@ public void testCtor() { Assume.assumeFalse(GraphicsEnvironment.isHeadless()); IconAdder frame = new IconAdder(); Assert.assertNotNull("exists", frame ); + frame.dispose(); } @Test @@ -27,11 +30,65 @@ public void testBoolCtor() { Assume.assumeFalse(GraphicsEnvironment.isHeadless()); IconAdder frame = new IconAdder(true); Assert.assertNotNull("exists", frame ); + frame.dispose(); + } + + @Test + public void testGetNumIcons() { + Assume.assumeFalse(GraphicsEnvironment.isHeadless()); + IconAdder frame = new IconAdder("LeftTurnout"); + Assert.assertEquals("Icon count",0, frame.getNumIcons() ); + frame.dispose(); + } + + @Test + public void testAddCatalog() { + Assume.assumeFalse(GraphicsEnvironment.isHeadless()); + IconAdder frame = new IconAdder("LeftTurnout"); + JmriJFrame parentFrame = new JmriJFrame("Icon Adder Parent Frame"); + frame.setParent(parentFrame); + frame.addCatalog(); + frame.dispose(); + parentFrame.dispose(); + } + + @Test + public void testAddDirectoryToCatalog() { + Assume.assumeFalse(GraphicsEnvironment.isHeadless()); + IconAdder frame = new IconAdder("LeftTurnout"); + JmriJFrame parentFrame = new JmriJFrame("Icon Adder Parent Frame"); + frame.setParent(parentFrame); + frame.addDirectoryToCatalog(); + frame.dispose(); + parentFrame.dispose(); + } + + @Test + public void testMakeIconPanel() { + Assume.assumeFalse(GraphicsEnvironment.isHeadless()); + IconAdder frame = new IconAdder("LeftTurnout"); + JmriJFrame parentFrame = new JmriJFrame("Icon Adder Parent Frame"); + frame.setParent(parentFrame); + frame.makeIconPanel(true); + frame.dispose(); + parentFrame.dispose(); + } + + @Test + public void testReset() { + Assume.assumeFalse(GraphicsEnvironment.isHeadless()); + IconAdder frame = new IconAdder("LeftTurnout"); + JmriJFrame parentFrame = new JmriJFrame("Icon Adder Parent Frame"); + frame.setParent(parentFrame); + frame.reset(); + frame.dispose(); + parentFrame.dispose(); } @Before public void setUp() { JUnitUtil.setUp(); + jmri.InstanceManager.store(new jmri.jmrit.catalog.DefaultCatalogTreeManager(), jmri.CatalogTreeManager.class); } @After diff --git a/java/test/jmri/jmrit/display/PackageTest.java b/java/test/jmri/jmrit/display/PackageTest.java index 613e836b780..887663e8d5d 100644 --- a/java/test/jmri/jmrit/display/PackageTest.java +++ b/java/test/jmri/jmrit/display/PackageTest.java @@ -61,6 +61,7 @@ PositionablePopupUtilTest.class, PositionablePropertiesUtilTest.class, DisplayFrameTest.class, + EditorIconFrameTest.class, }) public class PackageTest { } From e5bc0de9a0069b02d405dbb5c1c31cbe3dcf4794 Mon Sep 17 00:00:00 2001 From: dsand47 Date: Sun, 8 Apr 2018 23:38:51 -0500 Subject: [PATCH 57/58] Modify SML and NX path checking --- java/src/jmri/SignalMastLogicManager.java | 9 - .../LayoutBlockConnectivityTools.java | 154 +++++++++++------- 2 files changed, 96 insertions(+), 67 deletions(-) diff --git a/java/src/jmri/SignalMastLogicManager.java b/java/src/jmri/SignalMastLogicManager.java index 39b2c059c3a..2ef246675c5 100644 --- a/java/src/jmri/SignalMastLogicManager.java +++ b/java/src/jmri/SignalMastLogicManager.java @@ -31,15 +31,6 @@ public interface SignalMastLogicManager extends Manager { */ public void automaticallyDiscoverSignallingPairs() throws JmriException; - /** - * Use the Layout Editor to check if the destination signal mast is - * reachable from the source signal mast. - * - * @param sourceMast Source Signal Mast - * @param destMast Destination Signal Mast - * @return true if valid, false if not valid - */ - // public boolean checkValidDest(SignalMast sourceMast, SignalMast destMast) throws JmriException; /** * Discover valid destination signal masts for a given source Signal Mast on * a given Layout Editor Panel. diff --git a/java/src/jmri/jmrit/display/layoutEditor/LayoutBlockConnectivityTools.java b/java/src/jmri/jmrit/display/layoutEditor/LayoutBlockConnectivityTools.java index 8d465459e08..7b4c7cb73c3 100644 --- a/java/src/jmri/jmrit/display/layoutEditor/LayoutBlockConnectivityTools.java +++ b/java/src/jmri/jmrit/display/layoutEditor/LayoutBlockConnectivityTools.java @@ -67,10 +67,16 @@ public LayoutBlockConnectivityTools() { /** * Determines if a pair of NamedBeans (Signalhead, Signalmast or Sensor) - * assigned to a block boundary are reachable. - * - * @return true if source and destination beans are reachable, or false if - * they are not + * assigned to a block boundary are reachable.
    + * Called by {@link jmri.jmrit.signalling.SignallingPanel} using MASTTOMAST. + *

    + * Search all of the layout editor panels to find the facing and protecting + * layout blocks for each bean. Call the 3 block+list version of checkValidDest() to finish the checks. + *

    + * @param sourceBean The source bean. + * @param destBean The destination bean. + * @param pathMethod Indicates the type of path: Signal head, signal mast or sensor. + * @return true if source and destination beans are reachable. * @throws jmri.JmriException if no blocks can be found that related to the * named beans. */ @@ -101,9 +107,9 @@ public boolean checkValidDest(NamedBean sourceBean, NamedBean destBean, int path destProtectBlock = lbm.getProtectingBlocksByNamedBean(destBean, layout.get(i)); } if ((destFacingBlock != null) && (facingBlock != null) && (protectingBlock != null)) { - /*Destination protecting block is allowed to be null, as the destination signalmast + /*Destination protecting block list is allowed to be empty, as the destination signalmast could be assigned to an end bumper */ - //A simple to check to see if the remote signal is in the correct direction to ours. + //A simple to check to see if the remote signal/sensor is in the correct direction to ours. try { return checkValidDest(facingBlock, protectingBlock, destFacingBlock, destProtectBlock, pathMethod); } catch (jmri.JmriException e) { @@ -124,7 +130,7 @@ public boolean checkValidDest(NamedBean sourceBean, NamedBean destBean, int path * discover a clear path from a source layout block through to a destination * layout block. By specifying the sourceLayoutBlock and * protectingLayoutBlock or sourceLayoutBlock+1, a direction of travel can - * then be termined, eg east to west, south to north etc. + * then be determined, eg east to west, south to north etc. *

    * @param sourceBean - The source bean (SignalHead, SignalMast or Sensor) * assigned to a block boundary that we are starting @@ -217,24 +223,27 @@ public List getBeansInPath(List blocklist, LayoutEditor /** * Determines if one set of blocks is reachable from another set of blocks * based upon the directions of the set of blocks. + *

      + *
    • Called by {@link jmri.implementation.DefaultSignalMastLogic} using MASTTOMAST.
    • + *
    • Called by {@link jmri.jmrit.entryexit.DestinationPoints} using SENSORTOSENSOR.
    • + *
    • Called by {@link jmri.jmrit.entryexit.EntryExitPairs} using SENSORTOSENSOR.
    • + *
    + * Convert the destination protected block to an array list. + * Call the 3 block+list version of checkValidDest() to finish the checks. *

    - * This is used to help with identifying items such as signalmasts located - * at positionable points or turnouts are facing in the same direction as - * other given signalmasts. - *

    - * Given the current block and the next block we can work out the direction - * of travel. Given the destBlock and the next block on, we can determine - * the whether the destBlock comes before the destBlock+1. - * - * @return true if destBlock comes before destBlock+1 or false if destBlock - * comes after destBlock+1 + * @param currentBlock The facing layout block for the source signal or sensor. + * @param nextBlock The protected layout block for the source signal or sensor. + * @param destBlock The facing layout block for the destination signal mast or sensor. + * @param destProBlock The protected destination block. + * @param pathMethod Indicates the type of path: Signal head, signal mast or sensor. + * @return true if a path to the destination is valid. * @throws jmri.JmriException if any Block is null; */ - public boolean checkValidDest(LayoutBlock currentBlock, LayoutBlock nextBlock, LayoutBlock destBlock, LayoutBlock destBlockn1, int pathMethod) throws jmri.JmriException { + public boolean checkValidDest(LayoutBlock currentBlock, LayoutBlock nextBlock, LayoutBlock destBlock, LayoutBlock destProBlock, int pathMethod) throws jmri.JmriException { List destList = new ArrayList<>(); - if (destBlockn1 != null) { - destList.add(destBlockn1); + if (destProBlock != null) { + destList.add(destProBlock); } try { return checkValidDest(currentBlock, nextBlock, destBlock, destList, pathMethod); @@ -244,20 +253,44 @@ public boolean checkValidDest(LayoutBlock currentBlock, LayoutBlock nextBlock, L } + /** + * Determines if one set of blocks is reachable from another set of blocks + * based upon the directions of the set of blocks. + *

    + * This is used to help with identifying items such as signalmasts located + * at positionable points or turnouts are facing in the same direction as + * other given signalmasts. + *

    + * Given the current block and the next block we can work out the direction + * of travel. Given the destBlock and the next block on, we can determine + * the whether the destBlock comes before the destBlock+1. + *

    + * Note: This version is internally called by other versions that pre-process + * external calls. + *

    + * @param currentBlock The facing layout block for the source signal or sensor. + * @param nextBlock The protected layout block for the source signal or sensor. + * @param destBlock The facing layout block for the destination signal mast or sensor. + * @param destBlockn1 A list of protected destination blocks. Can be empty if the + * destination is at an end bumper. + * @param pathMethod Indicates the type of path: Signal head, signal mast or sensor. + * @return true if a path to the destination is valid. + * @throws jmri.JmriException if any layout block is null or advanced routing is not enabled. + */ public boolean checkValidDest(LayoutBlock currentBlock, LayoutBlock nextBlock, LayoutBlock destBlock, List destBlockn1, int pathMethod) throws jmri.JmriException { LayoutBlockManager lbm = InstanceManager.getDefault(LayoutBlockManager.class); if (!lbm.isAdvancedRoutingEnabled()) { - log.info("Advanced routing has not been enabled therefore we cannot use this function"); + log.debug("Advanced routing has not been enabled therefore we cannot use this function"); throw new jmri.JmriException("Advanced routing has not been enabled therefore we cannot use this function"); } if (log.isDebugEnabled()) { try { - log.debug("faci " + currentBlock.getDisplayName()); - log.debug("next " + nextBlock.getDisplayName()); - log.debug("dest " + destBlock.getDisplayName()); + log.debug("faci {}", currentBlock.getDisplayName()); + log.debug("next {}", nextBlock.getDisplayName()); + log.debug("dest {}", destBlock.getDisplayName()); for (LayoutBlock dp : destBlockn1) { - log.debug("dest + 1 " + dp.getDisplayName()); + log.debug("dest + 1 {}", dp.getDisplayName()); } } catch (java.lang.NullPointerException e) { @@ -287,40 +320,44 @@ public boolean checkValidDest(LayoutBlock currentBlock, LayoutBlock nextBlock, L log.debug("dest {} protecting {}", desCount, proCount); } } - if (proCount > desCount && (proCount - 1) != desCount) { - /* The block that we are protecting should be one hop greater than the destination count - if it is not then the route is not valid. - */ - log.debug("Protecting is more than one hop away from destination and therefore not valid."); + + if ((proCount == -1) && (desCount == -1)) { + //The destination block and destBlock+1 are both directly connected + log.debug("Dest and dest+1 are directly connected"); return false; } - if (proCount < desCount) { - /*Need to do a more advanced check in this case as the destBlockn1 - could be reached via a different route and therefore have a smaller - hop count we need to therefore step through each block until we reach - the end. - We also need to perform a more advanced check if the destBlockn1 - is null as this indicates that the destination signal mast is assigned - on an end bumper*/ - log.debug("proCount is less than destination"); - List blockList = getLayoutBlocks(currentBlock, destBlock, nextBlock, true, pathMethod); //Was MASTTOMAST - for (LayoutBlock dp : destBlockn1) { - if (blockList.contains(dp) && currentBlock != dp) { - log.debug("Signal mast in the wrong direction"); - return false; - } + + if (proCount > desCount && (proCount - 1) == desCount) { + // The block that we are protecting should be one hop greater than the destination count. + log.debug("Protecting is one hop away from destination and therefore valid."); + return true; + } + + /*Need to do a more advanced check in this case as the destBlockn1 + could be reached via a different route and therefore have a smaller + hop count we need to therefore step through each block until we reach + the end. + The advanced check also covers cases where the route table is inconsistent. + We also need to perform a more advanced check if the destBlockn1 + is null as this indicates that the destination signal mast is assigned + on an end bumper*/ + List blockList = getLayoutBlocks(currentBlock, destBlock, nextBlock, true, pathMethod); //Was MASTTOMAST + if (log.isDebugEnabled()) { + log.debug("checkValidDest blockList for {}", destBlock.getDisplayName()); + blockList.forEach(blk -> log.debug(" block = {}", blk.getDisplayName())); + } + for (LayoutBlock dp : destBlockn1) { + log.debug("dp = {}", dp.getDisplayName()); + if (blockList.contains(dp) && currentBlock != dp) { + log.debug("Signal mast in the wrong direction"); + return false; } + } /*Work on the basis that if you get the blocks from source to dest then the dest+1 block should not be included*/ - log.debug("Signal mast in the correct direction"); - return true; - } else if ((proCount == -1) && (desCount == -1)) { - //The destination block and destBlock+1 are both directly connected - log.debug("Dest and dest+1 are directly connected"); - return false; - } - log.debug("Return true path"); + log.debug("Signal mast in the correct direction"); return true; + } else if (destBlock == null) { throw new jmri.JmriException("Block in Destination Field returns as invalid"); } else if (currentBlock == null) { @@ -333,12 +370,13 @@ public boolean checkValidDest(LayoutBlock currentBlock, LayoutBlock nextBlock, L /** * This uses the layout editor to check if the destination location is - * reachable from the source location - * + * reachable from the source location.
    + * Note: No known references to this method. + *

    * @param facing Layout Block that is considered our first block * @param protecting Layout Block that is considered first block +1 * @param dest Layout Block that we want to get to - * @return true if valid, false if not valid. + * @return true if valid. */ public boolean checkValidDest(LayoutBlock facing, LayoutBlock protecting, FacingProtecting dest, int pathMethod) throws JmriException { if (facing == null || protecting == null || dest == null) { @@ -369,7 +407,7 @@ public boolean checkValidDest(LayoutBlock facing, LayoutBlock protecting, Facing * discover a clear path from a source layout block through to a destination * layout block. By specifying the sourceLayoutBlock and * protectingLayoutBlock or sourceLayoutBlock+1, a direction of travel can - * then be termined, eg east to west, south to north etc. + * then be determined, eg east to west, south to north etc. *

    * @param sourceLayoutBlock - The layout block that we are starting * from, can also be considered as the block @@ -397,7 +435,7 @@ public List getLayoutBlocks(LayoutBlock sourceLayoutBlock, LayoutBl lastErrorMessage = "Unknown Error Occured"; LayoutBlockManager lbm = InstanceManager.getDefault(LayoutBlockManager.class); if (!lbm.isAdvancedRoutingEnabled()) { - log.info("Advanced routing has not been enabled therefore we cannot use this function"); + log.debug("Advanced routing has not been enabled therefore we cannot use this function"); throw new jmri.JmriException("Advanced routing has not been enabled therefore we cannot use this function"); } From a08f04db66aaf937dbcccfcb95b4887c68881931 Mon Sep 17 00:00:00 2001 From: n3ix Date: Mon, 9 Apr 2018 12:20:24 -0700 Subject: [PATCH 58/58] Added test cases for Create from OPC_SW_REP Input-type messages Added test cases for Exact feedback messages form 1, 2 and 3 to go with the existing test case for message form 4. --- .../jmrix/loconet/LnTurnoutManagerTest.java | 33 +++++++++++++++++-- 1 file changed, 30 insertions(+), 3 deletions(-) diff --git a/java/test/jmri/jmrix/loconet/LnTurnoutManagerTest.java b/java/test/jmri/jmrix/loconet/LnTurnoutManagerTest.java index e6248a6214d..6072d5d53a7 100644 --- a/java/test/jmri/jmrix/loconet/LnTurnoutManagerTest.java +++ b/java/test/jmri/jmrix/loconet/LnTurnoutManagerTest.java @@ -3,7 +3,6 @@ import java.util.ArrayList; import java.util.List; import jmri.Turnout; -import jmri.TurnoutManager; import jmri.util.JUnitUtil; import org.junit.After; import org.junit.Assert; @@ -75,16 +74,44 @@ public void testLocoNetMessages() { Assert.assertTrue(null != l.getBySystemName("LT22")); // check the list - List testList = new ArrayList(2); + List testList = new ArrayList<>(2); testList.add("LT21"); testList.add("LT22"); Assert.assertEquals("system name list", testList, l.getSystemNameList()); } + @Test + public void testCreateFromMessage1 () { + // Turnout LT61 () Switch input is Closed (input off). + LocoNetMessage m = new LocoNetMessage(new int[]{0xb1, 0x3C, 0x70, 0x02}); + lnis.sendTestMessage(m); + Assert.assertTrue(null != l.getBySystemName("LT61")); + Assert.assertEquals(Turnout.CLOSED, l.getBySystemName("LT61").getKnownState()); + } + + @Test + public void testCreateFromMessage2 () { + // Turnout LT62 () Switch input is Thrown (input on). + LocoNetMessage m = new LocoNetMessage(new int[]{0xb1, 0x3D, 0x60, 0x13}); + lnis.sendTestMessage(m); + Assert.assertTrue(null != l.getBySystemName("LT62")); + Assert.assertEquals(Turnout.THROWN, l.getBySystemName("LT62").getKnownState()); + } + + @Test + public void testCreateFromMessage3 () { + // Turnout LT63 () Aux input is Thrown (input ). + LocoNetMessage m = new LocoNetMessage(new int[]{0xb1, 0x3E, 0x40, 0x30}); + lnis.sendTestMessage(m); + Assert.assertTrue(null != l.getBySystemName("LT63")); + Assert.assertEquals("EXACT", l.getBySystemName("LT63").getFeedbackModeName()); + Assert.assertEquals(Turnout.INCONSISTENT, l.getBySystemName("LT63").getKnownState()); + } + @Test public void testCreateFromMessage4 () { // Turnout LT64 () Aux input is Closed (input off). - LocoNetMessage m = new LocoNetMessage(new int[]{0xb1, 0x3F, 0x50, 0x2F, 0}); + LocoNetMessage m = new LocoNetMessage(new int[]{0xb1, 0x3F, 0x50, 0x21}); lnis.sendTestMessage(m); Assert.assertTrue(null != l.getBySystemName("LT64")); Assert.assertEquals("EXACT", l.getBySystemName("LT64").getFeedbackModeName());