ConnectPhysical.java 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518
  1. package Connection;
  2. import java.awt.BorderLayout;
  3. import java.awt.Component;
  4. import java.awt.Dimension;
  5. import java.awt.FlowLayout;
  6. import java.awt.image.BufferedImage;
  7. import java.io.IOException;
  8. import java.net.HttpURLConnection;
  9. import java.net.MalformedURLException;
  10. import java.net.URL;
  11. import java.text.NumberFormat;
  12. import java.util.ArrayList;
  13. import java.util.List;
  14. import java.util.concurrent.Executors;
  15. import java.util.concurrent.Future;
  16. import java.util.concurrent.ScheduledExecutorService;
  17. import java.util.concurrent.TimeUnit;
  18. import java.util.stream.Collectors;
  19. import javax.swing.BorderFactory;
  20. import javax.swing.ImageIcon;
  21. import javax.swing.JButton;
  22. import javax.swing.JCheckBox;
  23. import javax.swing.JFormattedTextField;
  24. import javax.swing.JFrame;
  25. import javax.swing.JLabel;
  26. import javax.swing.JOptionPane;
  27. import javax.swing.JPanel;
  28. import javax.swing.JScrollPane;
  29. import javax.swing.JSplitPane;
  30. import javax.swing.JTextArea;
  31. import javax.swing.text.NumberFormatter;
  32. import api.Algorithm;
  33. import classes.AbstractCpsObject;
  34. import classes.CpsUpperNode;
  35. import classes.HolonElement;
  36. import classes.HolonObject;
  37. import ui.controller.Control;
  38. import ui.view.Console;
  39. /**
  40. * Easy Connection via Http Request. Repeat Request with a delay.
  41. *
  42. * @author tom
  43. *
  44. */
  45. public class ConnectPhysical implements Algorithm{
  46. //Holeg
  47. private Control control;
  48. //Gui
  49. private JPanel content = new JPanel();
  50. private Console console;
  51. private JLabel rotorLabel;
  52. private JLabel houseLabel;
  53. private boolean onlyOnChange = false;
  54. //
  55. Future<?> future;
  56. private boolean lessInformation = false;
  57. private int delay = 1000;
  58. JLabel warningLabel;
  59. public enum HolonObjectStatus{
  60. Connected , NotSelected, ObjectDeleted
  61. }
  62. public class PhysicalLinkWrapper{
  63. public HolonObject hObject;
  64. public HolonObjectStatus status;
  65. public String postAddress;
  66. PhysicalLinkWrapper(HolonObject hObject, HolonObjectStatus status, String postAddress){
  67. this.hObject = hObject;
  68. this.status = status;
  69. this.postAddress = postAddress;
  70. }
  71. }
  72. //Object to look at
  73. PhysicalLinkWrapper rotor = new PhysicalLinkWrapper(null, HolonObjectStatus.NotSelected, "/rotor/");
  74. //Because House is special
  75. PhysicalLinkWrapper house = new PhysicalLinkWrapper(null, HolonObjectStatus.NotSelected, "notUsed");
  76. String room1Address = "/room1/";
  77. String room2Address = "/room2/";
  78. //the keywords are for the sepreation in 2 rooms
  79. String room1Keyword = "room1";
  80. String room2Keyword = "room2";
  81. //OnChange
  82. int oldValueRotor = -1;
  83. int oldValueRoom1 = -1;
  84. int oldValueRoom2 = -1;
  85. public static void main(String[] args)
  86. {
  87. JFrame newFrame = new JFrame("exampleWindow");
  88. ConnectPhysical instance = new ConnectPhysical();
  89. newFrame.setContentPane(instance.getAlgorithmPanel());
  90. newFrame.pack();
  91. newFrame.setVisible(true);
  92. newFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
  93. }
  94. public ConnectPhysical() {
  95. content.setLayout(new BorderLayout());
  96. console = new Console();
  97. JScrollPane scrollPane = new JScrollPane(console);
  98. JSplitPane splitPane = new JSplitPane(JSplitPane.VERTICAL_SPLIT,
  99. createOptionPanel() , scrollPane);
  100. splitPane.setResizeWeight(0.0);
  101. content.add(splitPane, BorderLayout.CENTER);
  102. content.setPreferredSize(new Dimension(800,800));
  103. }
  104. private Component createOptionPanel() {
  105. JPanel optionPanel = new JPanel(new BorderLayout());
  106. JScrollPane scrollPane = new JScrollPane(createParameterPanel());
  107. scrollPane.setBorder(BorderFactory.createTitledBorder("Settings"));
  108. optionPanel.add(scrollPane, BorderLayout.CENTER);
  109. optionPanel.add(createButtonPanel(), BorderLayout.PAGE_END);
  110. return optionPanel;
  111. }
  112. private Component createParameterPanel() {
  113. JPanel parameterPanel = new JPanel(null);
  114. parameterPanel.setPreferredSize(new Dimension(510,300));
  115. JLabel lessInformationLabel = new JLabel("Less information in Console:");
  116. lessInformationLabel.setBounds(200, 180, 200, 20);
  117. parameterPanel.add(lessInformationLabel);
  118. JCheckBox lessInformationCheckBox = new JCheckBox();
  119. lessInformationCheckBox.setSelected(false);
  120. lessInformationCheckBox.setBounds(400, 180, 25, 20);
  121. lessInformationCheckBox.addActionListener(actionEvent -> {
  122. lessInformation = lessInformationCheckBox.isSelected();
  123. });
  124. parameterPanel.add(lessInformationCheckBox);
  125. JLabel onlyOnChangeLabel = new JLabel("OnlyOnChange:");
  126. onlyOnChangeLabel.setBounds(200, 240, 200, 20);
  127. parameterPanel.add(onlyOnChangeLabel);
  128. JCheckBox onlyOnChangeCheckBox = new JCheckBox();
  129. onlyOnChangeCheckBox.setSelected(false);
  130. onlyOnChangeCheckBox.setBounds(400, 240, 25, 20);
  131. onlyOnChangeCheckBox.addActionListener(actionEvent -> {
  132. onlyOnChange = onlyOnChangeCheckBox.isSelected();
  133. });
  134. parameterPanel.add(onlyOnChangeCheckBox);
  135. JLabel delayLabel = new JLabel("Delay:");
  136. delayLabel.setBounds(200, 210, 50, 20);
  137. parameterPanel.add(delayLabel);
  138. JLabel delayUnitLabel = new JLabel("[ms]");
  139. delayUnitLabel.setBounds(300, 210, 50, 20);
  140. parameterPanel.add(delayUnitLabel);
  141. warningLabel = new JLabel(stringToHtml(stringWithColor("You need to Stop and Run again to affect delay change.", "red")));
  142. warningLabel.setBounds(200, 280, 400, 20);
  143. warningLabel.setVisible(false);
  144. parameterPanel.add(warningLabel);
  145. //Integer formatter
  146. NumberFormat format = NumberFormat.getIntegerInstance();
  147. format.setGroupingUsed(false);
  148. format.setParseIntegerOnly(true);
  149. NumberFormatter integerFormatter = new NumberFormatter(format);
  150. integerFormatter.setMinimum(0);
  151. integerFormatter.setCommitsOnValidEdit(true);
  152. JFormattedTextField delayTextField = new JFormattedTextField(integerFormatter);
  153. delayTextField.setValue(delay);
  154. delayTextField.setToolTipText("Only positive Integer.");
  155. delayTextField.addPropertyChangeListener(actionEvent -> {
  156. delay = Integer.parseInt(delayTextField.getValue().toString());
  157. if(future != null && !future.isCancelled()) {
  158. console.println("You need to Stop and Run again to affect this change.");
  159. warningLabel.setVisible(true);
  160. }
  161. });
  162. delayTextField.setBounds(250, 210, 50, 20);
  163. parameterPanel.add(delayTextField);
  164. rotorLabel = new JLabel(stringToHtml("Rotor Status: " + statusToString(rotor.status)));
  165. rotorLabel.setBounds(200, 60, 220, 30);
  166. parameterPanel.add(rotorLabel);
  167. houseLabel = new JLabel(stringToHtml("House Status: " + statusToString(house.status)));
  168. houseLabel.setBounds(200, 90, 220, 30);
  169. parameterPanel.add(houseLabel);
  170. JLabel keywordsLabel = new JLabel("Room Seperation Keywords: " + room1Keyword + " " + room2Keyword);
  171. keywordsLabel.setBounds(200, 120, 320, 30);
  172. parameterPanel.add(keywordsLabel);
  173. JLabel keywordsHintLabel = new JLabel("HolonElements with a name that contains the Keyword count.");
  174. keywordsHintLabel.setBounds(200, 135, 450, 30);
  175. parameterPanel.add(keywordsHintLabel);
  176. JButton selectRotorButton = new JButton("Select");
  177. selectRotorButton.setBounds(420,65, 90, 20);
  178. selectRotorButton.addActionListener(actionEvent -> this.selectGroupNode(rotor));
  179. parameterPanel.add(selectRotorButton);
  180. JButton selectRoom1Button = new JButton("Select");
  181. selectRoom1Button.setBounds(420,95, 90, 20);
  182. selectRoom1Button.addActionListener(actionEvent -> this.selectGroupNode(house));
  183. parameterPanel.add(selectRoom1Button);
  184. return parameterPanel;
  185. }
  186. private String stringToHtml(String string) {
  187. return "<html>" + string + "</html>";
  188. }
  189. private String statusToString(HolonObjectStatus status) {
  190. switch(status) {
  191. case Connected:
  192. return stringWithColor("Connected", "green");
  193. case NotSelected:
  194. return stringWithColor("Not selected", "red");
  195. case ObjectDeleted:
  196. return stringWithColor("Object deleted", "red");
  197. default:
  198. return "";
  199. }
  200. }
  201. private String stringWithColor(String string, String color) {
  202. return "<font color='"+color + "'>" + string + "</font>";
  203. }
  204. private void updateStatusLabels() {
  205. rotorLabel.setText(stringToHtml("Rotor Status: " + statusToString(rotor.status)));
  206. houseLabel.setText(stringToHtml("House Status: " + statusToString(house.status)));
  207. }
  208. private Component createButtonPanel() {
  209. JPanel buttonPanel = new JPanel(new FlowLayout(FlowLayout.RIGHT));
  210. JButton clearButton = new JButton("Clear Console");
  211. clearButton.addActionListener(actionEvent -> console.clear());
  212. buttonPanel.add(clearButton);
  213. JButton stopButton = new JButton("Stop");
  214. stopButton.addActionListener(actionEvent -> stop());
  215. buttonPanel.add(stopButton);
  216. JButton runButton = new JButton("Run");
  217. runButton.addActionListener(actionEvent -> initSchedule());
  218. buttonPanel.add(runButton);
  219. return buttonPanel;
  220. }
  221. private void stop() {
  222. if(future!= null) {
  223. if(future.isCancelled()) {
  224. console.println("Is cancelled.");
  225. }
  226. else {
  227. future.cancel(true);
  228. console.println("Stopped sending Requests on localhost:2019 ...");
  229. }
  230. }
  231. else {
  232. console.println("Not started jet.");
  233. }
  234. }
  235. private void initSchedule() {
  236. if(future != null && !future.isCancelled()) {
  237. console.println("Is running.");
  238. return;
  239. }
  240. warningLabel.setVisible(false);
  241. console.println("Starting sending Requests on localhost:2019");
  242. final ScheduledExecutorService executorService = Executors.newSingleThreadScheduledExecutor();
  243. final Runnable beeper = new Runnable() {
  244. //RepeatedMethod
  245. public void run() {
  246. if(lessInformation)console.print(".");
  247. checkWrapper(rotor);
  248. checkWrapperHouseSpecial(house);
  249. }
  250. private void checkWrapper(PhysicalLinkWrapper wrapper) {
  251. if(wrapper.status == HolonObjectStatus.Connected) checkConnected(wrapper);
  252. else if(!lessInformation)console.println(wrapper.postAddress +" is not connected.");
  253. }
  254. private void checkConnected(PhysicalLinkWrapper wrapper) {
  255. if(wrapper.hObject == null) {
  256. wrapper.status = HolonObjectStatus.ObjectDeleted;
  257. updateStatusLabels();
  258. return;
  259. }
  260. if(wrapper.hObject.getNumberOfElements() > 0) {
  261. //OnlyForRotor
  262. int value = Math.round(((float)wrapper.hObject.getNumberOfActiveElements()/(float) wrapper.hObject.getNumberOfElements())*(float) 100);
  263. if(onlyOnChange) {
  264. if(oldValueRotor != value) {
  265. sendRequest(wrapper.postAddress, value);
  266. oldValueRotor = value;
  267. }
  268. }else {
  269. sendRequest(wrapper.postAddress, value);
  270. }
  271. }else {
  272. if(onlyOnChange) {
  273. if(oldValueRotor != 0) {
  274. sendRequest(wrapper.postAddress, 0);
  275. oldValueRotor = 0;
  276. }
  277. }else {
  278. sendRequest(wrapper.postAddress, 0);
  279. }
  280. }
  281. }
  282. private void sendRequest(String postAddress, int value) {
  283. if(!lessInformation)console.println("Send " + "http://localhost:2019" + postAddress + value);
  284. doHttpUrlConnectionAction("http://localhost:2019" + postAddress + value);
  285. }
  286. /**
  287. * Send A Request to a URL.
  288. *
  289. * @param desiredUrl
  290. * @return
  291. */
  292. private void doHttpUrlConnectionAction(String desiredUrl)
  293. {
  294. URL url = null;
  295. // create the HttpURLConnection
  296. try {
  297. url = new URL(desiredUrl);
  298. HttpURLConnection connection = (HttpURLConnection) url.openConnection();
  299. // just want to do an HTTP GET here
  300. connection.setRequestMethod("GET");
  301. connection.getResponseCode();
  302. // give it 15 seconds to respond
  303. connection.setReadTimeout(1000);
  304. connection.connect();
  305. } catch (MalformedURLException e) {
  306. console.println("MalformedURLException");
  307. e.printStackTrace();
  308. } catch (IOException e) {
  309. console.println("IOException: Connection refused");
  310. e.printStackTrace();
  311. }
  312. }
  313. private void checkWrapperHouseSpecial(PhysicalLinkWrapper house) {
  314. if(!(house.status == HolonObjectStatus.Connected)) {
  315. if(!lessInformation)console.println("House" + " is not connected.");
  316. return;
  317. }
  318. //House is Connected
  319. if(house.hObject == null) {
  320. house.status = HolonObjectStatus.ObjectDeleted;
  321. updateStatusLabels();
  322. return;
  323. }
  324. //House exist
  325. List<HolonElement> elementsOfRoom1 = house.hObject.getElements().stream().filter(ele -> ele.getEleName().contains(room1Keyword)).collect(Collectors.toList());
  326. List<HolonElement> elementsOfRoom2 = house.hObject.getElements().stream().filter(ele -> ele.getEleName().contains(room2Keyword)).collect(Collectors.toList());
  327. if(elementsOfRoom1.isEmpty()){
  328. if(onlyOnChange) {
  329. if(oldValueRoom1 != 0) {
  330. sendRequest(room1Address, 0);
  331. oldValueRoom1 = 0;
  332. }
  333. }else {
  334. sendRequest(room1Address, 0);
  335. }
  336. }
  337. else{
  338. int value = Math.round(((float)elementsOfRoom1.stream().filter(ele -> ele.isActive()).count()/(float) elementsOfRoom1.size())*(float) 100);
  339. if(onlyOnChange) {
  340. if(oldValueRoom1 != value) {
  341. sendRequest(room1Address, value);
  342. oldValueRoom1 = value;
  343. }
  344. }else {
  345. sendRequest(room1Address, value);
  346. }
  347. }
  348. if(elementsOfRoom2.isEmpty()){
  349. if(onlyOnChange) {
  350. if(oldValueRoom2 != 0) {
  351. sendRequest(room2Address, 0);
  352. oldValueRoom2 = 0;
  353. }
  354. }else {
  355. sendRequest(room2Address, 0);
  356. }
  357. }
  358. else{
  359. int value = Math.round(((float)elementsOfRoom2.stream().filter(ele -> ele.isActive()).count()/(float) elementsOfRoom2.size())*(float) 100);
  360. if(onlyOnChange) {
  361. if(oldValueRoom2 != value) {
  362. sendRequest(room2Address, value);
  363. oldValueRoom2 = value;
  364. }
  365. }else {
  366. sendRequest(room2Address, value);
  367. }
  368. }
  369. }
  370. };
  371. future = executorService.scheduleAtFixedRate(beeper, 0, delay, TimeUnit.MILLISECONDS);
  372. }
  373. private void addObjectToList(List<AbstractCpsObject> listToSearch, List<HolonObject> listToAdd){
  374. for (AbstractCpsObject aCps : listToSearch) {
  375. if (aCps instanceof HolonObject) listToAdd.add((HolonObject) aCps);
  376. else if(aCps instanceof CpsUpperNode) {
  377. addObjectToList(((CpsUpperNode)aCps).getNodes(),listToAdd);
  378. }
  379. }
  380. }
  381. //SelectGroupNode
  382. private void selectGroupNode(PhysicalLinkWrapper wrapper) {
  383. List<HolonObject> holonObjectList = new ArrayList<HolonObject>();
  384. addObjectToList(control.getModel().getObjectsOnCanvas(),holonObjectList);
  385. Object[] possibilities = holonObjectList.stream().map(aCps -> new Handle<HolonObject>(aCps)).toArray();
  386. @SuppressWarnings("unchecked")
  387. Handle<HolonObject> selected = (Handle<HolonObject>) JOptionPane.showInputDialog(content, "Select HolonObject:", "HolonObject?", JOptionPane.OK_OPTION,new ImageIcon(new BufferedImage(1, 1, BufferedImage.TYPE_INT_ARGB)) , possibilities, "");
  388. if(selected != null) {
  389. console.println("Selected: " + selected);
  390. wrapper.hObject = selected.object;
  391. wrapper.status = HolonObjectStatus.Connected;
  392. updateStatusLabels();
  393. }
  394. }
  395. private class Handle<T>{
  396. public T object;
  397. Handle(T object){
  398. this.object = object;
  399. }
  400. public String toString() {
  401. return object.toString();
  402. }
  403. }
  404. @Override
  405. public JPanel getAlgorithmPanel() {
  406. return content;
  407. }
  408. @Override
  409. public void setController(Control control) {
  410. this.control = control;
  411. }
  412. }