ConnectionCreationPanel.java 27 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883
  1. package de.tu_darmstadt.tk.SmartHomeNetworkSim.view.popups;
  2. import java.awt.Color;
  3. import java.awt.Dimension;
  4. import java.awt.Window;
  5. import java.awt.event.ActionEvent;
  6. import java.awt.event.ActionListener;
  7. import java.awt.event.WindowAdapter;
  8. import java.awt.event.WindowEvent;
  9. import java.util.Collection;
  10. import java.util.Iterator;
  11. import java.util.LinkedList;
  12. import java.util.concurrent.ThreadLocalRandom;
  13. import java.util.stream.Collectors;
  14. import de.tu_darmstadt.tk.SmartHomeNetworkSim.control.Controller;
  15. import de.tu_darmstadt.tk.SmartHomeNetworkSim.control.NetworkController;
  16. import de.tu_darmstadt.tk.SmartHomeNetworkSim.core.Connection;
  17. import de.tu_darmstadt.tk.SmartHomeNetworkSim.core.ConnectionPrecision;
  18. import de.tu_darmstadt.tk.SmartHomeNetworkSim.core.Link;
  19. import de.tu_darmstadt.tk.SmartHomeNetworkSim.core.Model;
  20. import de.tu_darmstadt.tk.SmartHomeNetworkSim.core.Port;
  21. import de.tu_darmstadt.tk.SmartHomeNetworkSim.core.PrecisionLink;
  22. import de.tu_darmstadt.tk.SmartHomeNetworkSim.core.Protocol;
  23. import de.tu_darmstadt.tk.SmartHomeNetworkSim.core.SmartDevice;
  24. import de.tu_darmstadt.tk.SmartHomeNetworkSim.core.protocols.MQTT_protocol;
  25. import de.tu_darmstadt.tk.SmartHomeNetworkSim.core.simpleImplementation.SimpleLink;
  26. import javax.swing.JFrame;
  27. import javax.swing.JOptionPane;
  28. import javax.swing.JPanel;
  29. import javax.swing.JLabel;
  30. import javax.swing.JScrollPane;
  31. import javax.swing.ScrollPaneConstants;
  32. import javax.swing.JTextField;
  33. import javax.swing.SwingConstants;
  34. import javax.swing.JComboBox;
  35. import javax.swing.JButton;
  36. import javax.swing.event.DocumentEvent;
  37. import javax.swing.event.DocumentListener;
  38. @SuppressWarnings("serial")
  39. public class ConnectionCreationPanel extends JScrollPane {
  40. /**
  41. * Panel which contains the content of this creation panel
  42. */
  43. private JPanel content;
  44. /**
  45. * Textfield which stores the Name of the connection
  46. */
  47. private JTextField tfName;
  48. /**
  49. * Parent window which contains this frame - for the close operation
  50. */
  51. private Window frame;
  52. /**
  53. * Connection which is edited
  54. */
  55. private Connection connection;
  56. /**
  57. * Index of the disconnected option in the cmbPortRoles Array
  58. */
  59. private int disconnectedIndex;
  60. /**
  61. * Ports which could participate in the connection
  62. */
  63. private Port[] ports;
  64. /**
  65. * ComboBox for link selection
  66. */
  67. private JComboBox<String> cmbSelectedLink;
  68. /**
  69. * ComboBox for connection selection
  70. */
  71. private JComboBox<String> cmbConnection;
  72. /**
  73. * ComboBox for the protocol selection
  74. */
  75. private JComboBox<String> cmbProtocolType;
  76. /**
  77. * ComboBoxes to allow role changes of the different Ports
  78. */
  79. private JComboBox<String>[] cmbPortRoles;
  80. /**
  81. * ComboBox for the status
  82. */
  83. private JComboBox<String> cmbStatus;
  84. /**
  85. * True if an existing connection is being edited, or false if a new one is
  86. * being created
  87. */
  88. private boolean edit;
  89. /**
  90. * True if a new Link was created for this connection
  91. */
  92. private boolean newLink = false;
  93. /**
  94. * Last index which was selected in the protocolType ComboBox, to allow
  95. * restore the selected Index in case of invalid protocols
  96. */
  97. private int lastProtocolIndex = 0;
  98. /**
  99. * Last index which was selected in the selectedLink ComboBox, to allow
  100. * restore the selected Index in case of invalid links
  101. */
  102. private int lastLinkIndex = -1;
  103. /**
  104. * Last index which was selected in the selectedConnection ComboBox, to
  105. * allow restore the selected Index in case of invalid Connection
  106. */
  107. private int lastConnectionIndex = -1;
  108. /**
  109. * Mutex for the protocol change, so the different Devices don't change
  110. * their role, while their comboBoxes are updated. True if the protocol
  111. * change is in progress and the cmbPortRoles should not update their role.
  112. */
  113. private boolean protocolChange = false;
  114. /**
  115. * Controller to manipulate the model
  116. */
  117. private Controller controller;
  118. /**
  119. * Network Controller
  120. */
  121. private NetworkController network;
  122. /**
  123. * List of available protocols: should be moved to the Model and accessed
  124. * via controller
  125. */
  126. private LinkedList<Class<? extends Protocol>> availableProtocols;
  127. /**
  128. * List of available connections
  129. */
  130. private LinkedList<Class<? extends Connection>> availableConnection;
  131. /**
  132. * Textfield for the packet loss
  133. */
  134. private JTextField tfPacketLossRate;
  135. /**
  136. * Should not update if mutex is true
  137. */
  138. private boolean mutex = true;
  139. private JTextField tfLabel;
  140. /**
  141. * Creates a new ConnectionCreation panel
  142. * @param connection connection which should be edited
  143. * @param controller controller for manipulation
  144. * @param frame parent frame
  145. * @wbp.parser.constructor
  146. */// @wbp.parser.constructor for Eclipse:WindowBuilder
  147. public ConnectionCreationPanel(Connection connection, Controller controller, Window frame) {
  148. this.controller = controller;
  149. this.connection = connection;
  150. this.network = controller.getNetworkController();
  151. this.frame = frame;
  152. ports = new Port[connection.getParticipants().size()];
  153. int i = 0;
  154. for (Port d : connection.getParticipants()) {
  155. // controller.addLinkToDevice(connection, d);
  156. this.ports[i++] = d;
  157. }
  158. edit = true;
  159. initializePanel();
  160. }
  161. public ConnectionCreationPanel(Collection<Port> ports, Link l, Controller controller, Window frame) {
  162. this.controller = controller;
  163. this.network = controller.getNetworkController();
  164. this.frame = frame;
  165. /**
  166. * if link null -> create new link
  167. */
  168. if(l == null){
  169. l = new PrecisionLink("New Link");
  170. for(Port device: ports){
  171. controller.getNetworkController().addLinkToDevice(l, device.getOwner());
  172. }
  173. newLink = true;
  174. }
  175. connection = new ConnectionPrecision(l, new MQTT_protocol());
  176. this.ports = new Port[ports.size()];
  177. int i = 0;
  178. for (Port d : ports) {
  179. // controller.addLinkToDevice(connection, d);
  180. this.ports[i++] = d;
  181. }
  182. edit = false;
  183. initializePanel();
  184. }
  185. @SuppressWarnings("unchecked")
  186. private void initializePanel() {
  187. // Init variables
  188. disconnectedIndex = connection.getProtocol().getNumberOfRoles();
  189. availableProtocols = controller.getImportController().getProtocols();
  190. availableConnection = controller.getImportController().getConnections();
  191. // Sets up window
  192. setHorizontalScrollBarPolicy(ScrollPaneConstants.HORIZONTAL_SCROLLBAR_NEVER);
  193. this.setPreferredSize(new Dimension(600, 250 + ports.length * 20));
  194. content = new JPanel();
  195. content.setPreferredSize(new Dimension(600, 240 + ports.length * 20));
  196. this.setViewportView(content);
  197. content.setLayout(null);
  198. JLabel lblDescription = new JLabel("Connection Creation");
  199. lblDescription.setBounds(12, 0, 144, 16);
  200. content.add(lblDescription);
  201. JLabel lblName = new JLabel("Name:");
  202. lblName.setHorizontalAlignment(SwingConstants.RIGHT);
  203. lblName.setBounds(10, 10, 140, 20);
  204. content.add(lblName);
  205. tfName = new JTextField();
  206. tfName.setBounds(155, 10, 290, 20);
  207. content.add(tfName);
  208. tfName.setColumns(10);
  209. tfName.addActionListener(new ActionListener() {
  210. @Override
  211. public void actionPerformed(ActionEvent e) {
  212. if (mutex) {
  213. return;
  214. }
  215. connection.setName(tfName.getText());
  216. }
  217. });
  218. JLabel lblSelectedLink = new JLabel("Selected link:");
  219. lblSelectedLink.setHorizontalAlignment(SwingConstants.RIGHT);
  220. lblSelectedLink.setBounds(10, 40, 140, 20);
  221. content.add(lblSelectedLink);
  222. // Check if model contains link
  223. if (connection.getLink() != null && !network.getLinks().contains(connection.getLink()))
  224. network.addLink(connection.getLink());
  225. cmbSelectedLink = new JComboBox<String>();
  226. cmbSelectedLink.setBounds(155, 40, 125, 20);
  227. content.add(cmbSelectedLink);
  228. cmbSelectedLink.addActionListener(a -> {
  229. if (mutex) {
  230. return;
  231. }
  232. int cmbSelectedLinkIndex = cmbSelectedLink.getSelectedIndex();
  233. if (cmbSelectedLinkIndex == -1)
  234. return;
  235. Link newLink = null;
  236. Iterator<Link> linkIterator = network.getLinks().iterator();
  237. for (int i = 0; i < cmbSelectedLinkIndex && linkIterator.hasNext(); i++) {
  238. linkIterator.next();
  239. }
  240. if (linkIterator.hasNext())
  241. newLink = linkIterator.next();
  242. if (!network.changeLinkOfConnection(connection, newLink)) {
  243. // if LinkChange failed: Restore
  244. cmbSelectedLink.setSelectedIndex(lastLinkIndex);
  245. } else {
  246. lastLinkIndex = cmbSelectedLinkIndex;
  247. }
  248. });
  249. JButton btnCreateLink = new JButton("Create Link");
  250. btnCreateLink.setBounds(290, 40, 155, 20);
  251. content.add(btnCreateLink);
  252. btnCreateLink.addActionListener(a -> {
  253. new LinkCreationDialog(
  254. connection.getParticipants().stream().map(lElem -> lElem.getOwner()).collect(Collectors.toList()),
  255. controller, content);
  256. // TODO: Refresh
  257. });
  258. JLabel lblConnectionType = new JLabel("Connection type:");
  259. lblConnectionType.setHorizontalAlignment(SwingConstants.RIGHT);
  260. lblConnectionType.setBounds(10, 70, 140, 20);
  261. content.add(lblConnectionType);
  262. cmbConnection = new JComboBox<String>();
  263. cmbConnection.setBounds(155, 70, 125, 20);
  264. content.add(cmbConnection);
  265. cmbConnection.addActionListener(a -> {
  266. if (mutex) {
  267. return;
  268. }
  269. cmbConnection.getSelectedIndex();
  270. int selectedIndex = cmbConnection.getSelectedIndex();
  271. if (lastConnectionIndex != selectedIndex && selectedIndex != -1) {
  272. Connection newConnection = network.changeConnectionType(connection,
  273. availableConnection.get(selectedIndex));
  274. if (newConnection == null) {
  275. System.out.println("Warning invalidConnection changed");
  276. cmbConnection.setSelectedIndex(lastConnectionIndex);
  277. } else {
  278. connection = newConnection;
  279. lastConnectionIndex = selectedIndex;
  280. }
  281. } else {
  282. cmbConnection.setSelectedIndex(lastConnectionIndex);
  283. }
  284. });
  285. JButton btnImportConnection = new JButton("Import Connection");
  286. btnImportConnection.setBounds(290, 70, 155, 20);
  287. content.add(btnImportConnection);
  288. btnImportConnection.addActionListener(a -> {
  289. ImportPopUp<Connection> popUp = new ImportPopUp<Connection>(this, Connection.class);
  290. try {
  291. Class<? extends Connection> imported = popUp.showPopUp();
  292. if (imported == null)
  293. return;
  294. if (controller.getImportController().addConnection(imported)) {
  295. refreshGUI();
  296. } else {
  297. JOptionPane.showMessageDialog(frame, "Import failed: Invalid Connection");
  298. }
  299. } catch (Exception e1) {
  300. JOptionPane.showMessageDialog(frame, "Import failed: " + e1.getMessage());
  301. }
  302. });
  303. JLabel lblProtocolType = new JLabel("Protocol Type:");
  304. lblProtocolType.setHorizontalAlignment(SwingConstants.RIGHT);
  305. lblProtocolType.setBounds(10, 100, 140, 20);
  306. content.add(lblProtocolType);
  307. cmbProtocolType = new JComboBox<String>();
  308. cmbProtocolType.setBounds(155, 100, 125, 20);
  309. content.add(cmbProtocolType);
  310. // Add Functionality for changing protocol
  311. cmbProtocolType.addActionListener(new ActionListener() {
  312. @Override
  313. public void actionPerformed(ActionEvent e) {
  314. if (mutex)
  315. return;
  316. /**
  317. * Old Protocol
  318. */
  319. Protocol oldProtocol = connection.getProtocol();
  320. // Set Mutex to true, to disallow changes of roles during the
  321. // editing
  322. protocolChange = true;
  323. /**
  324. * New Protocol which should be created and configured
  325. */
  326. Protocol newProtocol = null;
  327. try {
  328. // Create new Instance of the protocol
  329. newProtocol = controller.getImportController().getProtocols()
  330. .get(cmbProtocolType.getSelectedIndex()).newInstance();
  331. } catch (InstantiationException | IllegalAccessException e1) {
  332. System.out.println("WARNING: Protocol could not be initialized");
  333. }
  334. if (newProtocol == null) {
  335. cmbProtocolType.setSelectedIndex(lastProtocolIndex);
  336. System.out.println("WARNING: Invalid Protocol Selected - restore last index");
  337. } else if (connection.setProtocol(newProtocol)) {
  338. /**
  339. * New Roles as Strings
  340. */
  341. String[] newRoles = newProtocol.getRoles();
  342. /**
  343. * The old disconnected status
  344. */
  345. int oldDisconnected = oldProtocol.getNumberOfRoles();
  346. // Update to new disconnected Index
  347. disconnectedIndex = newProtocol.getNumberOfRoles();
  348. // Update Protocol
  349. // Update lastProtocolIndex to new Index
  350. lastProtocolIndex = cmbProtocolType.getSelectedIndex();
  351. // Update Boxes
  352. for (int i = 0; i < cmbPortRoles.length; i++) {
  353. /**
  354. * The previous selected Index
  355. */
  356. int oldSelected = cmbPortRoles[i].getSelectedIndex();
  357. // Update Labels of the current Box
  358. cmbPortRoles[i].removeAllItems();
  359. for (int j = 0; j < newRoles.length; j++)
  360. cmbPortRoles[i].addItem(newRoles[j]);
  361. cmbPortRoles[i].addItem("Disconnected");
  362. // Try to update the Roles
  363. if (oldSelected < 0 || oldSelected >= disconnectedIndex || oldSelected == oldDisconnected) {
  364. // Invalid Index -> Disconnected
  365. network.removeDeviceFromConnectionAndProtocol(ports[i], connection);
  366. cmbPortRoles[i].setSelectedIndex(disconnectedIndex);
  367. } else {
  368. if (network.addDeviceToConnectionAndProtocol(ports[i], connection, oldSelected)) {
  369. // Set to Box to display role
  370. cmbPortRoles[i].setSelectedIndex(oldSelected);
  371. } else {
  372. // Could not be added -> Disconnected
  373. network.removeDeviceFromConnectionAndProtocol(ports[i], connection);
  374. cmbPortRoles[i].setSelectedIndex(disconnectedIndex);
  375. }
  376. }
  377. }
  378. } else {
  379. cmbProtocolType.setSelectedIndex(lastProtocolIndex);
  380. }
  381. // Set Mutex back to false - allow changes
  382. protocolChange = false;
  383. }
  384. });
  385. JButton btnImportProtocol = new JButton("Import Protocol");
  386. btnImportProtocol.setBounds(290, 100, 155, 20);
  387. content.add(btnImportProtocol);
  388. btnImportProtocol.addActionListener(a -> {
  389. ImportPopUp<Protocol> popUp = new ImportPopUp<Protocol>(this, Protocol.class);
  390. Class<? extends Protocol> imported = null;
  391. try {
  392. imported = popUp.showPopUp();
  393. } catch (Exception e1) {
  394. JOptionPane.showMessageDialog(frame, "Import failed: " + e1.getMessage());
  395. return;
  396. }
  397. if (imported == null) {
  398. // Import cancelled
  399. return;
  400. }
  401. // Add Protocol
  402. if (controller.getImportController().addProtocol(imported)) {
  403. // Update GUI
  404. refreshGUI();
  405. } else {
  406. JOptionPane.showMessageDialog(frame, "Import failed: Invalid Protocol");
  407. return;
  408. }
  409. });
  410. JLabel lblPacketlossrate = new JLabel("PacketLossRate:");
  411. lblPacketlossrate.setHorizontalAlignment(SwingConstants.RIGHT);
  412. lblPacketlossrate.setBounds(10, 130, 140, 20);
  413. lblPacketlossrate.setToolTipText("Probability of Packet loss, should be a Double in [0.0,1.0]");
  414. content.add(lblPacketlossrate);
  415. tfPacketLossRate = new JTextField();
  416. tfPacketLossRate.setBounds(155, 130, 90, 20);
  417. content.add(tfPacketLossRate);
  418. tfPacketLossRate.setColumns(10);
  419. tfPacketLossRate.getDocument().addDocumentListener(new DocumentListener() {
  420. @Override
  421. public void removeUpdate(DocumentEvent e) {
  422. updateConnectionAndField();
  423. }
  424. @Override
  425. public void insertUpdate(DocumentEvent e) {
  426. updateConnectionAndField();
  427. }
  428. @Override
  429. public void changedUpdate(DocumentEvent e) {
  430. updateConnectionAndField();
  431. }
  432. private void updateConnectionAndField() {
  433. if(mutex)
  434. return;
  435. try {
  436. double newRate = Double.parseDouble(tfPacketLossRate.getText());
  437. if (newRate >= 0.0 && newRate <= 1.0) {
  438. connection.setPacketLossProbability(newRate);
  439. tfPacketLossRate.setBackground(Color.WHITE);
  440. } else {
  441. tfPacketLossRate.setBackground(Color.RED);
  442. }
  443. } catch (Exception exception) {
  444. tfPacketLossRate.setBackground(Color.RED);
  445. }
  446. }
  447. });
  448. JLabel lblLabel = new JLabel("Label:");
  449. lblLabel.setHorizontalAlignment(SwingConstants.RIGHT);
  450. lblLabel.setBounds(10, 160, 140, 20);
  451. content.add(lblLabel);
  452. tfLabel = new JTextField();
  453. tfLabel.setColumns(10);
  454. tfLabel.setBounds(155, 160, 90, 20);
  455. content.add(tfLabel);
  456. tfLabel.getDocument().addDocumentListener(new DocumentListener() {
  457. @Override
  458. public void removeUpdate(DocumentEvent e) {
  459. updateConnectionAndField();
  460. }
  461. @Override
  462. public void insertUpdate(DocumentEvent e) {
  463. updateConnectionAndField();
  464. }
  465. @Override
  466. public void changedUpdate(DocumentEvent e) {
  467. updateConnectionAndField();
  468. }
  469. private void updateConnectionAndField() {
  470. if(mutex)
  471. return;
  472. try {
  473. short newLabel = Short.parseShort(tfLabel.getText());
  474. connection.setLabel(newLabel);
  475. tfLabel.setBackground(Color.WHITE);
  476. } catch (Exception exception) {
  477. tfLabel.setBackground(Color.RED);
  478. }
  479. }
  480. });
  481. JLabel lblStatus = new JLabel("Status:");
  482. lblStatus.setHorizontalAlignment(SwingConstants.RIGHT);
  483. lblStatus.setBounds(250, 130, 60, 20);
  484. content.add(lblStatus);
  485. cmbStatus = new JComboBox<String>();
  486. for (int i = 0; i < 5; i++)
  487. cmbStatus.addItem(Connection.getStatusName((byte) i));
  488. cmbStatus.setBounds(320, 130, 125, 20);
  489. content.add(cmbStatus);
  490. cmbStatus.addActionListener(new ActionListener() {
  491. @Override
  492. public void actionPerformed(ActionEvent e) {
  493. if (mutex) {
  494. cmbStatus.setSelectedIndex(connection.getStatus());
  495. }
  496. if (cmbStatus.getSelectedIndex() < 0 || cmbStatus.getSelectedIndex() > 4)
  497. cmbStatus.setSelectedIndex(connection.getStatus());
  498. else
  499. connection.setStatus((byte) cmbStatus.getSelectedIndex());
  500. }
  501. });
  502. JButton btnCreate = new JButton("Verify and Create");
  503. btnCreate.setBounds(127, 186, 206, 25);
  504. content.add(btnCreate);
  505. btnCreate.addActionListener(new ActionListener() {
  506. @Override
  507. public void actionPerformed(ActionEvent e) {
  508. /**
  509. * Validate Packet loss rate
  510. */
  511. try{
  512. double d = Double.parseDouble(tfPacketLossRate.getText());
  513. if(d < 0.0 && 1.0 < d)
  514. throw new Exception("Packet loss rate out of bounds");
  515. connection.setPacketLossProbability(d);
  516. }catch(Exception e1){
  517. JOptionPane.showMessageDialog(frame, "Invalid PacketsLossProbability, should be double between 0.0 and 1.0", "Invalid Packetloss Rate",
  518. JOptionPane.WARNING_MESSAGE);
  519. return;
  520. }
  521. /**
  522. * Validate Status
  523. */
  524. if(cmbStatus.getSelectedIndex()<0){
  525. JOptionPane.showMessageDialog(frame, "Status not set", "Status invalid",
  526. JOptionPane.WARNING_MESSAGE);
  527. return;
  528. }
  529. connection.setStatus((byte)cmbStatus.getSelectedIndex());
  530. /**
  531. * Link should be set and contain connection
  532. */
  533. if (connection.getLink() == null) {
  534. JOptionPane.showMessageDialog(frame, "Link should not be null.", "Invalid Link Selected",
  535. JOptionPane.WARNING_MESSAGE);
  536. return;
  537. } else if (!connection.getLink().getConnections().contains(connection)){
  538. network.addConnectionToLink(connection, connection.getLink());
  539. }
  540. if(tfName.getText()!=null)
  541. connection.setName(tfName.getText());
  542. /**
  543. * Check each Port/Device
  544. */
  545. for (int i = 0; i < ports.length; i++) {
  546. //Add Device to Link
  547. if (connection.getProtocol().getDevices().contains(ports[i])) {
  548. /**
  549. * If Link part of protocol & connection
  550. */
  551. if (!ports[i].getOwner().getLinks().contains(connection.getLink()))
  552. network.addLinkToDevice(connection.getLink(), ports[i].getOwner());
  553. if (!connection.getParticipants().contains(ports[i]))
  554. connection.addSmartDevice(ports[i]);
  555. if (ports[i].getConnection() != connection)
  556. ports[i].setConnection(connection);
  557. if (!ports[i].getOwner().getPorts().contains(ports[i]))
  558. ports[i].getOwner().addPort(ports[i]);
  559. } else {
  560. /**
  561. * Else remove from COnnection
  562. */
  563. network.removeDeviceFromConnectionAndProtocol(ports[i], connection);
  564. if (ports[i].getOwner().getPorts().contains(ports[i]))
  565. ports[i].getOwner().removePort(ports[i]);
  566. }
  567. }
  568. /**
  569. * Connection should be in the model
  570. */
  571. if(!network.getConnections().contains(connection))
  572. network.addConnection(connection);
  573. /**
  574. * Link should be in the model
  575. */
  576. if(!network.getLinks().contains(connection.getLink())){
  577. network.addLink(connection.getLink());
  578. }
  579. edit = true;
  580. /**
  581. * Close Window
  582. */
  583. controller.notifyObservers();
  584. content.setVisible(false);
  585. setVisible(false);
  586. if (frame != null) {
  587. frame.setVisible(false);
  588. frame.dispose();
  589. }
  590. }
  591. });
  592. /**
  593. * Small Label to describe the roles
  594. */
  595. JLabel lblRole = new JLabel("Roles:");
  596. lblRole.setHorizontalAlignment(SwingConstants.CENTER);
  597. lblRole.setBounds(345, 189, 50, 18);
  598. lblRole.setToolTipText("The roles each device plays in the connection, can be defined below. It defines how the device acts.");
  599. content.add(lblRole);
  600. /**
  601. * Height of the current Box which is being created
  602. */
  603. int currentHeight = 220;
  604. cmbPortRoles = new JComboBox[ports.length];
  605. for (int i = 0; i < ports.length; i++) {
  606. // Effectively final variables for the action listener
  607. int pos = i;
  608. Port currentPort = ports[i];
  609. SmartDevice currentDevice = currentPort.getOwner();
  610. JLabel lblDevice = new JLabel(currentDevice.getName() + ":" + currentPort.getPortNumber() + ":");
  611. lblDevice.setHorizontalAlignment(SwingConstants.RIGHT);
  612. lblDevice.setBounds(10, currentHeight, 230, 18);
  613. content.add(lblDevice);
  614. cmbPortRoles[pos] = new JComboBox<String>();
  615. for (String role : connection.getProtocol().getRoles())
  616. cmbPortRoles[pos].addItem(role);
  617. cmbPortRoles[pos].addItem("Disconnected");
  618. cmbPortRoles[pos].setBounds(250, currentHeight, 240, 18);
  619. content.add(cmbPortRoles[pos]);
  620. if (edit) {
  621. int roleOfDevice = connection.getProtocol().getRoleOfDevice(currentPort);
  622. if (roleOfDevice != -1)
  623. cmbPortRoles[pos].setSelectedIndex(roleOfDevice);
  624. else
  625. cmbPortRoles[pos].setSelectedIndex(disconnectedIndex);
  626. } else {
  627. /**
  628. * Number of tries to add the Port
  629. */
  630. int n = 5;
  631. for (int j = 0; j <= n; j++) {
  632. if (j == 0) {// Try to add Router first
  633. if (network.addDeviceToConnectionAndProtocol(currentPort, connection, 0)) {
  634. cmbPortRoles[pos].setSelectedIndex(0);
  635. break;
  636. }
  637. } else if (j == n) {// If it could not be added
  638. cmbPortRoles[pos].setSelectedIndex(disconnectedIndex);
  639. network.removeDeviceFromConnectionAndProtocol(currentPort, connection);
  640. break;
  641. } else {
  642. int randomRole = ThreadLocalRandom.current().nextInt(0, disconnectedIndex);
  643. if (network.addDeviceToConnectionAndProtocol(currentPort, connection, randomRole)) {
  644. cmbPortRoles[pos].setSelectedIndex(randomRole);
  645. break;
  646. }
  647. }
  648. }
  649. }
  650. cmbPortRoles[pos].addActionListener(new ActionListener() {
  651. @Override
  652. public void actionPerformed(ActionEvent e) {
  653. if (protocolChange) {
  654. return;
  655. }
  656. /**
  657. * Selected Index of the ComboBox, which represents the new
  658. * role (or disconnected)
  659. */
  660. int selected = cmbPortRoles[pos].getSelectedIndex();
  661. /**
  662. * True if role was successfully changed
  663. */
  664. boolean successfullChange = network.changeRoleOfDevice(connection.getProtocol(), connection,
  665. ports[pos], selected);
  666. /**
  667. * Set to Disconnected, if role could not be changed
  668. */
  669. if (!successfullChange) {
  670. cmbPortRoles[pos].setSelectedIndex(connection.getProtocol().getNumberOfRoles());
  671. }
  672. }
  673. });
  674. currentHeight += 20;
  675. }
  676. frame.addWindowListener(new WindowAdapter() {
  677. @Override
  678. public void windowClosing(WindowEvent e) {
  679. if(!edit){
  680. if(newLink){
  681. network.deleteLink(connection.getLink());
  682. }
  683. network.deleteConnection(connection);
  684. }
  685. };
  686. });
  687. refreshGUI();
  688. }
  689. /**
  690. * Refreshes the GUI
  691. */
  692. private void refreshGUI() {
  693. // Set Mutex
  694. mutex = true;
  695. /*
  696. * Update Variables
  697. */
  698. disconnectedIndex = connection.getProtocol().getNumberOfRoles();
  699. availableProtocols = controller.getImportController().getProtocols();
  700. availableConnection = controller.getImportController().getConnections();
  701. /**
  702. * Update Boxes, Textfield e.g.
  703. */
  704. // Update Name Textfield
  705. tfName.setText(connection.getName());
  706. // Update packet loss field
  707. tfPacketLossRate.setText("" + connection.getPacketLossProbability());
  708. // Update Label
  709. tfLabel.setText("" + connection.getLabel());
  710. // Update Status
  711. cmbStatus.setSelectedIndex(connection.getStatus());
  712. // Update selected Connection
  713. cmbConnection.removeAllItems();
  714. for (Class<? extends Connection> c : availableConnection)
  715. cmbConnection.addItem(c.getSimpleName());
  716. // Set Index to selected Connection
  717. for (int i = 0; i < availableConnection.size(); i++)
  718. if (connection.getClass().equals(availableConnection.get(i))) {
  719. // Select the right protocol and save last index
  720. lastConnectionIndex = i;
  721. }
  722. cmbConnection.setSelectedIndex(lastConnectionIndex);
  723. // Update selected Link
  724. int linkIndex = 0;
  725. for (Link l : network.getLinks()) {
  726. cmbSelectedLink.addItem(l.getName());
  727. if (l.equals(connection.getLink())) {
  728. lastLinkIndex = linkIndex;
  729. }
  730. linkIndex++;
  731. }
  732. cmbSelectedLink.setSelectedIndex(lastLinkIndex);
  733. // Update protocol
  734. cmbProtocolType.removeAllItems();
  735. for (int i = 0; i < availableProtocols.size(); i++)
  736. try {
  737. cmbProtocolType.addItem(availableProtocols.get(i).newInstance().getName());
  738. } catch (InstantiationException | IllegalAccessException e1) {
  739. System.out.println("Protocol " + i + " is invalid");
  740. cmbProtocolType.addItem("unknown");
  741. }
  742. // Set Index to selected Protocol
  743. lastProtocolIndex = -1;
  744. for (int i = 0; i < availableProtocols.size(); i++) {
  745. if (connection.getProtocol().getClass().equals(availableProtocols.get(i))) {
  746. // Select the right protocol and save last index
  747. lastProtocolIndex = i;
  748. }
  749. }
  750. cmbProtocolType.setSelectedIndex(lastProtocolIndex);
  751. // Release mutex
  752. mutex = false;
  753. }
  754. /**
  755. * Test the Panel
  756. */
  757. private static void testGUI() {
  758. JFrame frame = new JFrame("Connection Creation Panel");
  759. frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
  760. ConnectionCreationPanel panel;
  761. Link testNet = new SimpleLink("Test Network");
  762. LinkedList<SmartDevice> devicesOfLink = new LinkedList<SmartDevice>();
  763. LinkedList<Port> ports = new LinkedList<Port>();
  764. for (int i = 0; i < 5; i++) {
  765. SmartDevice d = new SmartDevice("Device" + i);
  766. Port p = new Port(d, (short) i);
  767. d.addPort(p);
  768. devicesOfLink.add(d);
  769. ports.add(p);
  770. }
  771. Model m = new Model();
  772. m.addConnectionNetwork(testNet);
  773. m.addConnectionNetwork(new SimpleLink("Wifi"));
  774. m.addConnectionNetwork(new SimpleLink("Ethernet"));
  775. panel = new ConnectionCreationPanel(ports, testNet, new Controller(m),frame);
  776. frame.setContentPane(panel);
  777. frame.pack();
  778. frame.setVisible(true);
  779. }
  780. public static void main(String[] args) {
  781. javax.swing.SwingUtilities.invokeLater(new Runnable() {
  782. public void run() {
  783. testGUI();
  784. }
  785. });
  786. }
  787. }