ConnectionCreationPanel.java 26 KB

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