ConnectPhysical.java 16 KB

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