Advertisement
VastMind

Untitled

Apr 17th, 2015
267
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 62.44 KB | None | 0 0
  1. package ru.nppame.netManage.gui;
  2.  
  3. import edu.umd.cs.piccolo.PCamera;
  4. import edu.umd.cs.piccolo.PLayer;
  5. import edu.umd.cs.piccolo.PNode;
  6. import edu.umd.cs.piccolo.activities.PActivity;
  7. import edu.umd.cs.piccolo.activities.PTransformActivity;
  8. import edu.umd.cs.piccolo.event.PBasicInputEventHandler;
  9. import edu.umd.cs.piccolo.event.PDragSequenceEventHandler;
  10. import edu.umd.cs.piccolo.event.PInputEvent;
  11. import edu.umd.cs.piccolo.event.PInputEventFilter;
  12. import edu.umd.cs.piccolo.event.PZoomEventHandler;
  13. import edu.umd.cs.piccolo.nodes.PPath;
  14. import edu.umd.cs.piccolo.nodes.PText;
  15. import edu.umd.cs.piccolo.util.PAffineTransform;
  16. import edu.umd.cs.piccolo.util.PBounds;
  17. import edu.umd.cs.piccolo.util.PDimension;
  18. import edu.umd.cs.piccolox.PFrame;
  19. import edu.umd.cs.piccolox.pswing.PSwing;
  20. import edu.umd.cs.piccolox.pswing.PSwingCanvas;
  21. import edu.umd.cs.piccolox.swing.PScrollPane;
  22. import java.awt.BorderLayout;
  23. import java.awt.Color;
  24. import java.awt.Component;
  25. import java.awt.Container;
  26. import java.awt.Dialog;
  27. import java.awt.Dimension;
  28. import java.awt.FlowLayout;
  29. import java.awt.Polygon;
  30. import java.awt.Rectangle;
  31. import java.awt.event.ActionEvent;
  32. import java.awt.event.ActionListener;
  33. import java.awt.event.InputEvent;
  34. import java.awt.event.WindowAdapter;
  35. import java.awt.event.WindowEvent;
  36. import java.awt.geom.Point2D;
  37. import java.awt.geom.Rectangle2D;
  38. import java.io.FileInputStream;
  39. import java.io.IOException;
  40. import java.io.InputStreamReader;
  41. import java.util.ArrayList;
  42. import java.util.Date;
  43. import java.util.List;
  44. import java.util.Properties;
  45. import java.util.Random;
  46. import java.util.Timer;
  47. import java.util.TimerTask;
  48. import java.util.Vector;
  49. import java.util.concurrent.Executors;
  50. import java.util.concurrent.ScheduledExecutorService;
  51. import java.util.concurrent.TimeUnit;
  52. import java.util.logging.Level;
  53. import java.util.logging.Logger;
  54. import javax.swing.BorderFactory;
  55. import javax.swing.JButton;
  56. import javax.swing.JDialog;
  57. import javax.swing.JFrame;
  58. import javax.swing.JLabel;
  59. import javax.swing.JMenu;
  60. import javax.swing.JMenuBar;
  61. import javax.swing.JMenuItem;
  62. import javax.swing.JOptionPane;
  63. import javax.swing.JPopupMenu;
  64. import javax.swing.JScrollPane;
  65. import javax.swing.JSlider;
  66. import javax.swing.JSplitPane;
  67. import javax.swing.JTable;
  68. import javax.swing.event.ChangeEvent;
  69. import javax.swing.event.ChangeListener;
  70. import javax.swing.event.ListSelectionEvent;
  71. import javax.swing.event.ListSelectionListener;
  72. import javax.swing.plaf.basic.BasicSplitPaneDivider;
  73. import javax.swing.plaf.basic.BasicSplitPaneUI;
  74. import javax.swing.table.DefaultTableCellRenderer;
  75. import javax.swing.table.DefaultTableModel;
  76. import javax.swing.table.TableColumn;
  77. import org.openqa.selenium.Alert;
  78. import org.openqa.selenium.By;
  79. import org.openqa.selenium.WebDriver;
  80. import org.openqa.selenium.WebElement;
  81. import org.openqa.selenium.firefox.FirefoxDriver;
  82. import ru.nppame.netManage.device.IDevice;
  83. import ru.nppame.netManage.device.impl.AccessPoint;
  84. import ru.nppame.netManage.device.impl.PhoneServer;
  85. import ru.nppame.netManage.device.state.DeviceState;
  86. import static ru.nppame.netManage.gui.Launcher.logger;
  87. import ru.nppame.netManage.snmp.SnmpHandler;
  88. import ru.nppame.tools.AppRunner;
  89.  
  90.  
  91.  
  92. /**
  93.  * The main application's frame.
  94.  *
  95.  */
  96. public class MainFrame extends PFrame {
  97.  
  98.     private static final long serialVersionUID = 1L;
  99.  
  100.     /**
  101.      * The length of the vertical leg between a device and a connecting line.
  102.      */
  103.     private static final int VERTICAL_LEG_BOTTOM = -60;
  104.  
  105.     private static final int VERTICAL_LEG_TOP = 60;
  106.  
  107.     private MainData data;
  108.     private PText tooltipNode;
  109.     private PText statTitle;
  110.     private IDevice selectedDevice;
  111.     private JTable statTable;
  112.     private PLayer nodeLayer;
  113.     private PLayer edgeLayer;
  114.     private PActivity changeRandomNodeStateActivity;
  115.     private CustomZoomHandler customZoomHandler;
  116.     private boolean autoZoom = false;
  117.    
  118.     private PSwingCanvas canvas0;
  119.     private PSwingCanvas canvas1;
  120.     private PSwingCanvas canvas2;
  121.     private PSwingCanvas canvas3;
  122.     private PSwingCanvas canvas4;
  123.  
  124.     public MainFrame(MainData data) {
  125.         super("Интерфейс МДА БСОРИ ", false, new PSwingCanvas());
  126. //        Image img = new ImageIcon(Launcher.class.getResource("./img/AME_icon.ico")).getImage();
  127. //        this.setIconImage(img);
  128.         this.data = data;
  129.         setSize(1920, 1080);
  130.         setLocation(0, 0);
  131.         setDefaultCloseOperation(DO_NOTHING_ON_CLOSE);
  132.         setVisible(true);
  133.  
  134.         this.addWindowListener(new WindowAdapter() {
  135.             public void windowClosing(WindowEvent e) {
  136.  
  137.                 Object[] options = {"Да", "Нет"};
  138.                 int result = JOptionPane.showOptionDialog(new JFrame(),
  139.                         "Вы действительно хотите выйти из программы ?", "Подтверждение выхода",
  140.                         JOptionPane.YES_NO_OPTION, JOptionPane.QUESTION_MESSAGE, null,
  141.                         options, options[1]);
  142.  
  143.                 if (result == JOptionPane.YES_OPTION) {
  144.                     try {
  145.                         // stop the polling thread pool
  146.                         //SnmpHandler.getInstance().stop();
  147.                         System.exit(0);
  148.                     } catch (Exception exc) {
  149.                         exc.printStackTrace();
  150.                     }
  151.                 } else {
  152.                     // Do nothing
  153.                 }
  154.             }
  155.         });
  156.         ScheduledExecutorService ses = Executors.newSingleThreadScheduledExecutor();
  157.         ses.scheduleAtFixedRate(new Runnable() {
  158.             PSwingCanvas[] ps = new PSwingCanvas[]{canvas0, canvas1, canvas2};
  159.  
  160.             @Override
  161.             public void run() {
  162.                 updateGraphics(ps);
  163.             }
  164.         }, 0, 1, TimeUnit.SECONDS);
  165.     }
  166.  
  167.     public static void updateGraphics(PSwingCanvas[] canvases) {
  168.  
  169.         for (int i = 0; i < canvases.length; i++) {
  170.             for (int j = 0; j < canvases[i].getComponents().length; j++) {
  171.                 canvases[i].getComponent(j).revalidate();
  172.                 canvases[i].getComponent(j).repaint();
  173.             }
  174.         }
  175.  
  176.     }
  177.     public static void updateGraphics(PSwingCanvas canvases) {
  178.         for (int i = 0; i < canvases.getComponents().length; i++) {
  179.             canvases.getComponent(i).revalidate();
  180.             canvases.getComponent(i).repaint();
  181.         }
  182.     }
  183.  
  184.     public void initialize() {
  185.         try {
  186.             createCanvas();
  187.             showInitDialog(150000); //150 sec
  188.         } catch (IOException ex) {
  189.             Logger.getLogger(MainFrame.class.getName()).log(Level.SEVERE, null, ex);
  190.         }
  191.     }
  192.    
  193.     // Drawing frame and text label for BSKP
  194.     private PNode drawShape(int[] x, int[] y, String textLabel) {
  195.  
  196.         Polygon p = new Polygon(x, y, x.length);
  197.         PNode n = new PPath(p);
  198.         PText pTextLabel = new PText(textLabel);
  199.         pTextLabel.setX(n.getX() + 45);
  200.         pTextLabel.setY(n.getY());
  201.  
  202.         n.addChild(pTextLabel);
  203.         return n;
  204.     }
  205.  
  206.     private void createCanvas() throws IOException {
  207.  
  208.         Container container = getContentPane();
  209.         container.setLayout(new BorderLayout());
  210.                
  211.         canvas0 = buildLabelTitleCanvas("");
  212.         canvas0.setPreferredSize(new Dimension(50, 50));
  213.         canvas0.setBorder(BorderFactory.createLineBorder(Color.GRAY, 1, true));
  214.         container.add(canvas0, BorderLayout.NORTH);
  215.  
  216.         canvas1 = buildMainCanvas("");
  217.         canvas1.setPreferredSize(new Dimension(800, 800));
  218.         canvas1.setBorder(BorderFactory.createLineBorder(Color.GRAY, 1, true));
  219.         PScrollPane scrollPane1 = new PScrollPane(canvas1);
  220.         //container.add(scrollPane1, BorderLayout.CENTER);
  221.  
  222.         canvas2 = buildStatTableCanvas("");
  223.         canvas2.setPreferredSize(new Dimension(1000, 800));
  224.         canvas2.setBorder(BorderFactory.createLineBorder(Color.GRAY, 1, true));
  225.         PScrollPane scrollPane2 = new PScrollPane(canvas2);
  226.         //container.add(scrollPane2, BorderLayout.NORTH);
  227.        
  228.        
  229.         final JSplitPane horizontalSplitPane = new JSplitPane(JSplitPane.HORIZONTAL_SPLIT,
  230.                 scrollPane1, scrollPane2);
  231.         horizontalSplitPane.setOneTouchExpandable(true);
  232.         horizontalSplitPane.setDividerLocation(850);
  233.         horizontalSplitPane.setDividerSize(20);
  234.         //container.add(horizontalSplitPane, BorderLayout.CENTER);
  235.  
  236.         canvas4 = buildButtonsCanvas("");
  237.         canvas4.setPreferredSize(new Dimension(1000, 250));
  238.         canvas4.setBorder(BorderFactory.createLineBorder(Color.GRAY, 1, true));
  239.         //container.add(canvas4, BorderLayout.SOUTH);
  240.         //createZoomButton(canvas4, canvas1 );
  241.         createZoomSlider(canvas4, canvas1, "Масштаб в процентах");
  242.         PScrollPane scrollPane4 = new PScrollPane(canvas4);
  243.        
  244.         JSplitPane verticalSplitPane = new JSplitPane(JSplitPane.VERTICAL_SPLIT,
  245.                 horizontalSplitPane, scrollPane4);
  246.         verticalSplitPane.setOneTouchExpandable(true);
  247.         verticalSplitPane.setDividerLocation(600);
  248.         verticalSplitPane.setDividerSize(20);
  249.         container.add(verticalSplitPane, BorderLayout.CENTER);
  250.     }
  251.    
  252.  
  253.     private PSwingCanvas buildMainCanvas(String canvasName) {
  254.         final PSwingCanvas canvas = new PSwingCanvas();
  255.         createMenu();
  256.         createNodesAndEdges(canvas);
  257.         return canvas;
  258.     }
  259.  
  260.     private PSwingCanvas buildButtonsCanvas(String canvasName) {
  261.         PSwingCanvas canvas = new PSwingCanvas();
  262.         canvas.getLayer().addChild(new PSwing(new JLabel(canvasName)));
  263.         canvas.setPanEventHandler(null);
  264.         return createButtons(canvas);
  265.     }
  266.  
  267.     private PSwingCanvas buildLabelTitleCanvas(String canvasName) {
  268.         PSwingCanvas canvas = new PSwingCanvas();
  269.         canvas.getLayer().addChild(new PSwing(new JLabel(canvasName)));
  270.         canvas.setPanEventHandler(null);
  271.         return createLabel(canvas, "Схема сетевой инфраструктуры МДА БСОРИ", 10, 10, 30);
  272.     }
  273.  
  274.     private PSwingCanvas createLabel(PSwingCanvas pSwingCanvas, String text, int x, int y, int fontSize) {
  275.         PText title = new PText(text);
  276.         title.setFont(new java.awt.Font("SansSerif", 3, fontSize));
  277.         title.setX(x);
  278.         title.setX(y);
  279.         pSwingCanvas.getLayer().addChild(title);
  280.         return pSwingCanvas;
  281.     }
  282.  
  283.     /**
  284.      * Creates and lays out nodes
  285.      */
  286.     private PSwingCanvas createNodesAndEdges(PSwingCanvas pSwingCanvas) {
  287.  
  288.         nodeLayer = getCanvas().getLayer();
  289.         edgeLayer = new PLayer();
  290.  
  291.         pSwingCanvas.getCamera().addLayer(edgeLayer);
  292.         pSwingCanvas.getCamera().addLayer(nodeLayer);
  293.  
  294.         PText title = new PText("");
  295.         title.setFont(new java.awt.Font("SansSerif", 3, 24));
  296.         title.setX(100);
  297.         nodeLayer.addChild(title);
  298.  
  299.         // create device images
  300.         List<PDeviceImage> deviceImages = new ArrayList<PDeviceImage>();
  301.         for (IDevice device : data.getAllDevices()) {
  302.             PDeviceImage deviceImage = new PDeviceImage(device);
  303.             deviceImages.add(deviceImage);
  304.             nodeLayer.addChild(deviceImage);
  305.         }
  306.  
  307.         nodeLayer.addChild(drawShape(new int[]{data.findDeviceById(51).getX() - 10, data.findDeviceById(51).getX() - 10, data.findDeviceById(51).getX() + 110, data.findDeviceById(51).getX() + 110}, new int[]{data.findDeviceById(51).getY() + 150, data.findDeviceById(51).getY() - 10, data.findDeviceById(51).getY() - 10, data.findDeviceById(51).getY() + 150}, "БСКП"));
  308.         // connect devices with lines (edges)
  309.         for (IDevice device : data.getAllDevices()) {
  310.             drawEdgesFromDeviceToChildren(device);
  311.         }
  312.  
  313.         // Create event handler to drag and drop devices
  314.         nodeLayer.addInputEventListener(new NodeDragHandler());
  315.         // add right click menu hanlder
  316.         pSwingCanvas.addInputEventListener(new CanvasInputHandler());
  317.         // Move (pan) screen with Ctrl key
  318.         pSwingCanvas.getPanEventHandler().setEventFilter(new PInputEventFilter(InputEvent.CTRL_MASK));
  319.        
  320. //        customZoomHandler = new CustomZoomHandler();
  321. //        customZoomHandler.setEventFilter(new PInputEventFilter(InputEvent.SHIFT_MASK));
  322.        
  323.         pSwingCanvas.setZoomEventHandler(customZoomHandler);
  324.        
  325.         createUpdateScreenActivity();
  326.        
  327.         createPollingActivity();
  328.        
  329.         createToolTip(pSwingCanvas);
  330.        
  331.         return pSwingCanvas;
  332.     }
  333.  
  334.     private PSwingCanvas createZoomSlider(final PSwingCanvas pSwingCanvasToAdd, final PSwingCanvas pSwingCanvasZoomable, String label) {
  335.  
  336.         //Create the label.
  337.         JLabel sliderLabel = new JLabel("Масштаб в процентах", JLabel.CENTER);
  338.  
  339.         JSlider zoomSlider = new JSlider(50, 150);
  340.  
  341.         class SliderListener implements ChangeListener {
  342.  
  343.             public void stateChanged(ChangeEvent e) {
  344.                 JSlider source = (JSlider) e.getSource();
  345.                 if (!source.getValueIsAdjusting()) {
  346.                     int sliderValue = (int) source.getValue();
  347.  
  348.                     switch (sliderValue) {
  349.                         case 50:
  350.                             pSwingCanvasZoomable.getCamera().setViewScale(0.5);
  351.                             pSwingCanvasZoomable.getCamera().setViewOffset(0, 0);
  352.                             JOptionPane.showMessageDialog(null, "Удерживайте клавишу \"Ctrl\" и перетаскивайте рисунок мышью для навигации.");
  353.                             break;
  354.                         case 100:
  355.                             pSwingCanvasZoomable.getCamera().setViewScale(1.0);
  356.                             pSwingCanvasZoomable.getCamera().setViewOffset(0, 0);
  357.                             JOptionPane.showMessageDialog(null, "Удерживайте клавишу \"Ctrl\" и перетаскивайте рисунок мышью для навигации.");
  358.                             break;
  359.                         case 150:
  360.                             pSwingCanvasZoomable.getCamera().setViewScale(1.5);
  361.                             pSwingCanvasZoomable.getCamera().setViewOffset(0, 0);
  362.                             JOptionPane.showMessageDialog(null, "Удерживайте клавишу \"Ctrl\" и перетаскивайте рисунок мышью для навигации.");
  363.                             break;
  364.                     }
  365.                 }
  366.             }
  367.         }
  368.         zoomSlider.addChangeListener(new SliderListener());
  369.         zoomSlider.setMajorTickSpacing(50);
  370.         zoomSlider.setPaintTicks(true);
  371.         zoomSlider.setPaintLabels(true);
  372.         zoomSlider.setSnapToTicks(true);
  373.  
  374.         PSwing pSwing = new PSwing(zoomSlider);
  375.         pSwing.translate(310, 20);
  376.         pSwingCanvasToAdd.getLayer().addChild(pSwing);
  377.  
  378.         PSwing pSwing2 = new PSwing(sliderLabel);
  379.         pSwingCanvasToAdd.getLayer().addChild(pSwing2);
  380.         pSwing2.translate(350, 0);
  381.  
  382.         return pSwingCanvasZoomable;
  383.     }
  384.  
  385.     private void createUpdateScreenActivity() {
  386.         PActivity updateScreenActivity = new PActivity(-1, IDevice.SCREEN_UPDATE_INTERVAL) {
  387.             protected void activityStep(long time) {
  388.                 super.activityStep(time);
  389.                 try {
  390.                     // System.out.println("update screen activity called...");
  391.                     setTableData();
  392.                 } catch (IOException ex) {
  393.                     Logger.getLogger(MainFrame.class.getName()).log(Level.SEVERE, null, ex);
  394.                 }
  395.                 if (selectedDevice != null) {
  396.                     selectDevice(selectedDevice.getDeviceImage());
  397.                 }
  398.             }
  399.         };
  400.         nodeLayer.addActivity(updateScreenActivity);
  401.     }
  402.  
  403.     private void createPollingActivity() {
  404.         PActivity pollDeviceActivity = new PActivity(-1, IDevice.DEVICE_POLL_INTERVAL) {
  405.             protected void activityStep(long time) {
  406.                 super.activityStep(time);
  407.                 //System.out.println("poll all devices...");
  408.                 System.out.println("Опрос всех устройств по snmp...");
  409.                 try {
  410.                     SnmpHandler.getInstance().pollAllDevices();
  411. //                    updateGraphics(canvas0);
  412. //                    updateGraphics(canvas1);
  413. //                    updateGraphics(canvas2);
  414. //                    updateGraphics(canvas4);
  415.                     //updateGraphics(new PSwingCanvas[] {canvas0, canvas1, canvas2, canvas4});
  416.                    
  417.                    
  418.                 } catch (Throwable ex) {
  419.                     Logger.getLogger(MainFrame.class.getName()).log(Level.SEVERE, null, ex);
  420.                 }
  421.             }
  422.         };
  423.         nodeLayer.addActivity(pollDeviceActivity);
  424.     }
  425.  
  426.     /**
  427.      * Adds buttons to the screen
  428.      */
  429.     private PSwingCanvas createButtons(final PSwingCanvas pSwingCanvas) {
  430.  
  431.         // Add the default zoom button
  432. //        JButton zoom100button = new JButton("Zoom = 100%");
  433. //        zoom100button.addActionListener(new ActionListener() {
  434. //            public void actionPerformed(final ActionEvent e) {
  435. //                pSwingCanvas.getCamera().setViewScale(1.0);
  436. //                pSwingCanvas.getCamera().setViewOffset(0, 0);
  437. //
  438. //            }
  439. //        });
  440. //        PSwing pSwing = new PSwing(zoom100button);
  441. //        pSwing.translate(50, 50);
  442. //        pSwingCanvas.getLayer().addChild(pSwing);
  443. //----------------------------------------------------------------------------------------------------------------
  444. //        JButton fullScreen = new JButton("Полный экран");
  445. //        fullScreen.addActionListener(new ActionListener() {
  446. //            public void actionPerformed(final ActionEvent e) {
  447. //                if (selectedDevice != null) {
  448. //                    System.out.println("Currently selected device: " + selectedDevice.getName());
  449. //                }
  450. //                for (IDevice device : data.getAllDevices()) {
  451. //                    if (device instanceof AccessPoint) {
  452. //                        continue;
  453. //                    }
  454. //                    System.out.println(device.getName() + " " + device.getDeviceImage().getFullBounds());
  455. //                }
  456. //                JOptionPane.showMessageDialog(null, "Switching to full screen");
  457. //                setFullScreenMode(true);
  458. //            }
  459. //        });
  460. //        PSwing pSwing = new PSwing(fullScreen);
  461. //        pSwing.translate(50, 50);
  462. //        pSwingCanvas.getLayer().addChild(pSwing);
  463. //      JButton startRandomStateButton = new JButton("Start Activity");
  464. //      startRandomStateButton.addActionListener(new ActionListener() {
  465. //          public void actionPerformed(final ActionEvent e) {
  466. //              createRandomNodeStateActivity();
  467. //          }
  468. //      });
  469. //      pSwing = new PSwing(startRandomStateButton);
  470. //      pSwing.translate(200, 600);
  471. //      getCanvas().getLayer().addChild(pSwing);       
  472. //      JButton stopRandomStateButton = new JButton("Stop Activity");
  473. //      stopRandomStateButton.addActionListener(new ActionListener() {
  474. //          public void actionPerformed(final ActionEvent e) {
  475. //              stopActivity();
  476. //          }
  477. //      });
  478. //      pSwing = new PSwing(stopRandomStateButton);
  479. //      pSwing.translate(350, 600);
  480. //      getCanvas().getLayer().addChild(pSwing);
  481. //      JButton addBskpButton = new JButton("Add BSKP");
  482. //      addBskpButton.addActionListener(new ActionListener() {
  483. //          public void actionPerformed(final ActionEvent e) {
  484. //              createNewBskp();
  485. //          }
  486. //      });
  487. //      pSwing = new PSwing(addBskpButton);
  488. //      pSwing.translate(530, 600);
  489. //      getCanvas().getLayer().addChild(pSwing);
  490. //      JButton testButton = new JButton("Test");
  491. //      testButton.addActionListener(new ActionListener() {
  492. //          public void actionPerformed(final ActionEvent e) {
  493. //              test();
  494. //          }
  495. //      });
  496. //      pSwing = new PSwing(testButton);
  497. //      pSwing.translate(730, 600);
  498. //      getCanvas().getLayer().addChild(pSwing);
  499.         JButton modeButton = new JButton("Режим");
  500.         modeButton.setEnabled(false);
  501.         modeButton.addActionListener(new ActionListener() {
  502.             public void actionPerformed(final ActionEvent e) {
  503.                 //test();
  504.             }
  505.         });
  506.         PSwing pSwing = new PSwing(modeButton);
  507.         pSwing.translate(40, 80);
  508.         pSwingCanvas.getLayer().addChild(pSwing);
  509.  
  510.         JButton diagnosticsButton = new JButton("Диагностика");
  511.         diagnosticsButton.setEnabled(true);
  512.         diagnosticsButton.addActionListener(new ActionListener() {
  513.             public void actionPerformed(final ActionEvent e) {
  514.                 try {
  515.                     managedAPList();
  516.                 } catch (InterruptedException ex) {
  517.                     Logger.getLogger(MainFrame.class.getName()).log(Level.SEVERE, null, ex);
  518.                 }
  519.             }
  520.         });
  521.         pSwing = new PSwing(diagnosticsButton);
  522.         pSwing.translate(140, 80);
  523.         pSwingCanvas.getLayer().addChild(pSwing);
  524.  
  525.         JButton offEmissionButton = new JButton("Выключение радиоизлучения всех ББПИ");
  526.         offEmissionButton.setEnabled(false);
  527.         diagnosticsButton.addActionListener(new ActionListener() {
  528.             public void actionPerformed(final ActionEvent e) {
  529.                 //test();
  530.             }
  531.         });
  532.         pSwing = new PSwing(offEmissionButton);
  533.         pSwing.translate(280, 80);
  534.         pSwingCanvas.getLayer().addChild(pSwing);
  535.  
  536.         JButton reInitProgramm = new JButton("Перезагрузка приложения");
  537.         reInitProgramm.addActionListener(new ActionListener() {
  538.             public void actionPerformed(final ActionEvent e) {
  539.                 try {
  540.                     Launcher.restartApp();
  541.                 } catch (IOException ex) {
  542.                     Logger.getLogger(MainFrame.class.getName()).log(Level.SEVERE, null, ex);
  543.                 }
  544.             }
  545.         });
  546.         pSwing = new PSwing(reInitProgramm);
  547.         pSwing.translate(620, 80);
  548.         pSwingCanvas.getLayer().addChild(pSwing);
  549.  
  550.         JButton rebootOS = new JButton("Перезагрузка ОС");
  551.         rebootOS.addActionListener(new ActionListener() {
  552.             public void actionPerformed(final ActionEvent e) {
  553.  
  554.         Object[] options = { "Yes", "No" };
  555.         int n = JOptionPane.showOptionDialog(new JFrame(),
  556.                 "Операционная система будет перезагружена!", "",
  557.                 JOptionPane.YES_NO_OPTION, JOptionPane.QUESTION_MESSAGE, null,
  558.                 options, options[1]);
  559.         if(n == JOptionPane.OK_OPTION){ // Afirmative
  560.             try {
  561.                 logger.log(Level.SEVERE,"************************ OS is restarting ************************");
  562.                 AppRunner.runShellScript("echo \"r\" | sudo -S | reboot");
  563.             } catch (IOException e1) {
  564.                 e1.printStackTrace();
  565.             }
  566.         }
  567. //                if(n == JOptionPane.NO_OPTION){ // negative
  568. //                    //....
  569. //                }
  570. //                if(n == JOptionPane.CLOSED_OPTION){ // closed the dialog
  571. //                    //....
  572. //                }
  573.  
  574.             }
  575.         });
  576.         pSwing = new PSwing(rebootOS);
  577.         pSwing.translate(650, 120);
  578.         pSwingCanvas.getLayer().addChild(pSwing);
  579.        
  580.         JButton wiButton = new JButton("Открыть web интерфейс КТД");
  581.         wiButton.setEnabled(true);
  582.         wiButton.addActionListener(new ActionListener() {
  583.             public void actionPerformed(final ActionEvent e) {
  584.                 // Actual for Windows:
  585. //                try {
  586. //                    AppRunner.webInterfaceOpener("http://10.168.2.50/login.php");
  587. //
  588. //                } catch (URISyntaxException ex) {
  589. //                    Logger.getLogger(MainFrame.class.getName()).log(Level.SEVERE, null, ex);
  590. //                }
  591.                 // For linux with firefox browser
  592.                
  593.                 loginToPage();
  594.                
  595. //                String[] commands = {"firefox", "http://10.168.2.50/login.php"};
  596. //                try {
  597. //                    Runtime.getRuntime().exec(commands);
  598. //                } catch (IOException e1) {
  599. //                    e1.printStackTrace();
  600. //                }
  601.             }
  602.         });
  603.         pSwing = new PSwing(wiButton);
  604.         pSwing.translate(860, 80);
  605.         pSwingCanvas.getLayer().addChild(pSwing);
  606.        
  607.         JButton appLogbutton = new JButton("Открыть лог приложения");
  608.         appLogbutton.setEnabled(true);
  609.         appLogbutton.addActionListener(new ActionListener() {
  610.             public void actionPerformed(final ActionEvent e) {
  611.                 //AppRunner.open("./BSORI_Net_UI_Interface_Application_Log.htm");
  612.                 String[] commands = {"firefox", "./log/BSORI_Net_UI_Interface_Application_Log.htm"};
  613.                 try {
  614.                     Runtime.getRuntime().exec(commands);
  615.                 } catch (IOException e1) {
  616.                     e1.printStackTrace();
  617.                 }
  618.             }
  619.         });
  620.         pSwing = new PSwing(appLogbutton);
  621.         pSwing.translate(1115, 80);
  622.         pSwingCanvas.getLayer().addChild(pSwing);
  623.        
  624.         JButton astButton = new JButton("Открыть Asterisk в терминале");
  625.         astButton.setEnabled(true);
  626.         astButton.addActionListener(new ActionListener() {
  627.             public void actionPerformed(final ActionEvent e) {
  628. //                try {
  629. //                    AppRunner.runShellScript("echo \"r\" | sudo -S | asterisk -rvvvcd");
  630. //
  631. //                } catch (IOException e1) {
  632. //                    e1.printStackTrace();
  633. //                }
  634.                 try {
  635.                     String[] commands = {"fly-term", "-e", "asterisk", "-rvvvcd"};
  636.                     Runtime.getRuntime().exec(commands);
  637.                 } catch (IOException e1) {
  638.                     e1.printStackTrace();
  639.                 }
  640.             }
  641.         });
  642.         pSwing = new PSwing(astButton);
  643.         pSwing.translate(1345, 80);
  644.         pSwingCanvas.getLayer().addChild(pSwing);
  645.  
  646.         JButton termButton = new JButton("Открыть терминал");
  647.         termButton.setEnabled(true);
  648.         termButton.addActionListener(new ActionListener() {
  649.             public void actionPerformed(final ActionEvent e) {
  650. //                try {
  651. //                    AppRunner.runShellScript("echo \"r\" | sudo -S | asterisk -rvvvcd");
  652. //
  653. //                } catch (IOException e1) {
  654. //                    e1.printStackTrace();
  655. //                }
  656.                 try {
  657.                     Runtime.getRuntime().exec("fly-term");
  658.                 } catch (IOException e1) {
  659.                     e1.printStackTrace();
  660.                 }
  661.             }
  662.         });
  663.         pSwing = new PSwing(termButton);
  664.         pSwing.translate(1395, 120);
  665.         pSwingCanvas.getLayer().addChild(pSwing);
  666.        
  667.         JButton manButton = new JButton("Открыть руководство");
  668.         manButton.setEnabled(true);
  669.         manButton.addActionListener(new ActionListener() {
  670.             public void actionPerformed(final ActionEvent e) {
  671.                 JOptionPane.showMessageDialog(null, "Открыть руководство:"
  672.                         + "\nРуководство оператору МПТ\n"
  673.                         + "Руководство по эксплуатации и инструкция по назначению МДА БСОРИ");
  674.             }
  675.         });
  676.         pSwing = new PSwing(manButton);
  677.         pSwing.translate(1610, 80);
  678.         pSwingCanvas.getLayer().addChild(pSwing);
  679.        
  680.         //pSwing.repaint ();
  681.             return pSwingCanvas ;
  682.  
  683.         }
  684.  
  685.     private PSwingCanvas createStatTable(PSwingCanvas pSwingCanvas) throws IOException {
  686.         statTable = new JTable();
  687.         // Code for sorting table cells
  688. //        statTable.setAutoCreateRowSorter(true);
  689. //        TableRowSorter<TableModel> sorter = new TableRowSorter<TableModel>(statTable.getModel());
  690. //        statTable.setRowSorter(sorter);
  691. //        setTableData();
  692.        
  693. //        statTable.setPreferredScrollableViewportSize(statTable.getPreferredSize());
  694. //        statTable.setFillsViewportHeight(true);
  695. //        statTable.scrollRectToVisible(statTable.getCellRect(statTable.getRowCount()-1, 0, true));
  696.        
  697.         JScrollPane pane = new JScrollPane(statTable);
  698.         pane.setPreferredSize(new Dimension(850, 650));
  699.         statTable.setDoubleBuffered(false);
  700.         //statTable.setAutoCreateRowSorter(true);
  701.         statTitle = new PText("Общая статистика БСОРИ:");
  702.         statTitle.setFont(new java.awt.Font("SansSerif", 3, 20));
  703.         statTitle.translate(250, 20);
  704.         pSwingCanvas.getLayer().addChild(statTitle);
  705.         PSwing pSwing = new PSwing(pane);
  706.         pSwing.translate(20, 50);
  707.         pSwingCanvas.getLayer().addChild(pSwing);
  708.         //pSwing.repaint();
  709.         return pSwingCanvas;
  710.     }
  711.    
  712.  
  713.  
  714.     private void setTableData() throws IOException {
  715.         Properties p = new Properties();
  716.         p.load(new InputStreamReader(new FileInputStream("./placement.properties"), "UTF-8"));
  717.         final Vector<String> columns = new Vector<String>();
  718.         columns.add("ID");
  719.         columns.add("Наименование");
  720.         columns.add("IP address");
  721.         columns.add("Расположение");//columns.add("Серийный номер");
  722.         columns.add("Состояние");
  723.         columns.add("Время работы");
  724.        
  725.         Vector<Vector> rows = new Vector<Vector>();
  726.         for (IDevice device : data.getAllDevices()) {
  727.             Vector row = new Vector();
  728.             row.add(device.getId());
  729.             row.add(device.getName());
  730.             row.add(device.getIpAddress());
  731.             row.add(p.getProperty(device.getName()));
  732.             row.add(device.getState());
  733.             row.add(device.getSysUpTime());
  734.             rows.add(row);
  735.         }
  736.  
  737.         statTable.setModel(new DefaultTableModel(rows, columns) {
  738.             Class[] types = {
  739.                 Integer.class,
  740.                 String.class,
  741.                 String.class,
  742.                 String.class,
  743.                 Integer.class,
  744.                 String.class
  745.             };
  746.  
  747.             @Override
  748.             public Class getColumnClass(int columnIndex) {
  749.                 return this.types[columnIndex];
  750.             }
  751.         });
  752.  
  753.         // set cell render for 'state' column
  754.         statTable.getColumnModel().getColumn(4).setCellRenderer(
  755.                 new DefaultTableCellRenderer() {
  756.                     protected void setValue(Object value) {
  757.                         if (value == null) {
  758.                             setText("");
  759.                         } else {
  760.                             DeviceState deviceState = (DeviceState) value;
  761.                             if (deviceState == DeviceState.ON) {
  762.                                 setText("ВКЛ.");
  763.                                 setBackground(Color.green);
  764.                             } else if (deviceState == DeviceState.OFF) {
  765.                                 setText("ВЫКЛ.");
  766.                                 setBackground(Color.RED);
  767.                             } else if (deviceState == DeviceState.BROKEN) {
  768.                                 setText("НЕ РАБОТАЕТ");
  769.                                 setBackground(Color.RED);
  770.                             }
  771.                         }
  772.                     }
  773.                 }
  774.         );
  775.  
  776.         // set cell render for 'active time' column
  777.         statTable.getColumnModel().getColumn(5).setCellRenderer(
  778.                 new DefaultTableCellRenderer() {
  779.                     protected void setValue(Object value) {
  780.                         setText(
  781.                                 (value == null)
  782.                                 ? ""
  783.                                 : String.valueOf(value)
  784.                         );
  785.                     }
  786.                 }
  787.         );
  788.  
  789.         statTable.getSelectionModel().addListSelectionListener(new ListSelectionListener() {
  790.             @Override
  791.             public void valueChanged(ListSelectionEvent e) {
  792.                 if (!e.getValueIsAdjusting()) {
  793.                     int selectedRow = statTable.getSelectedRow();
  794.                     if (selectedRow != -1) {
  795.                         selectedRow = statTable.convertRowIndexToModel(selectedRow);
  796.                         Integer deviceId = (Integer) statTable.getModel().getValueAt(selectedRow, 0);
  797.                         IDevice device = data.findDeviceById(deviceId);
  798.                         selectDeviceNode(device.getDeviceImage());
  799.  
  800.                     }
  801.                 }
  802.             }
  803.         });
  804.  
  805.         statTable.setAutoCreateRowSorter(true);
  806.         statTable.setAutoResizeMode(JTable.AUTO_RESIZE_OFF);
  807.         statTable.setRowHeight(30);
  808.         TableColumn c = statTable.getColumn(statTable.getColumnName(0));
  809.         c.setPreferredWidth(30);
  810.         c = statTable.getColumn(statTable.getColumnName(1));
  811.         c.setPreferredWidth(80);
  812.         c = statTable.getColumn(statTable.getColumnName(2));
  813.         c.setPreferredWidth(100);
  814.         c = statTable.getColumn(statTable.getColumnName(3));
  815.         c.setPreferredWidth(380);
  816.         c = statTable.getColumn(statTable.getColumnName(4));
  817.         c.setPreferredWidth(100);
  818.         c = statTable.getColumn(statTable.getColumnName(5));
  819.         c.setPreferredWidth(150);
  820.  
  821.     }
  822.  
  823.     /**
  824.      * Creates a tooltip
  825.      */
  826.     private void createToolTip(PSwingCanvas pSwingCanvas) {
  827.         final PCamera camera = pSwingCanvas.getCamera();
  828.         tooltipNode = new PText();
  829.         tooltipNode.setPaint(new Color(255, 252, 209));
  830.         tooltipNode.setPickable(false);
  831.         camera.addChild(tooltipNode);
  832.         camera.addInputEventListener(new PBasicInputEventHandler() {
  833.             public void mouseMoved(final PInputEvent event) {
  834.                 try {
  835.                     updateToolTip(event);
  836.                 } catch (IOException ex) {
  837.                     Logger.getLogger(MainFrame.class.getName()).log(Level.SEVERE, null, ex);
  838.                 }
  839.             }
  840.  
  841.             public void mouseDragged(final PInputEvent event) {
  842.                 try {
  843.                     updateToolTip(event);
  844.                 } catch (IOException ex) {
  845.                     Logger.getLogger(MainFrame.class.getName()).log(Level.SEVERE, null, ex);
  846.                 }
  847.             }
  848.  
  849.             public void updateToolTip(final PInputEvent event) throws IOException {
  850.                
  851.                 Properties p1 = new Properties();
  852.                 p1.load(new InputStreamReader(new FileInputStream("./placement.properties"), "UTF-8"));
  853.                
  854.                 PNode node = event.getPickedNode();
  855.  
  856.                 if (!(node instanceof PDeviceImage)) {
  857.                     tooltipNode.setVisible(false);
  858.                     return;
  859.                 }
  860.  
  861.                 IDevice device = ((PDeviceImage) node).getDevice();
  862.                 if (device == null) {
  863.                     return;
  864.                 }
  865.  
  866.                 tooltipNode.setVisible(true);
  867.                 String tooltipString = String.format(
  868.                         "Device name: %s%n"
  869.                         + "Device IP address: %s%n"
  870.                         + "Device state: %s%n"
  871.                         + "Device uptime: %s%n"
  872.                         + "Room: %s%n",
  873.                         device.getName(),
  874.                         device.getIpAddress(),    
  875.                         device.getState(),
  876.                         device.getSysUpTime(),
  877.                         p1.getProperty(device.getName())
  878.                        
  879.                 );
  880.  
  881.                 Point2D p = event.getCanvasPosition();
  882.                 event.getPath().canvasToLocal(p, camera);
  883.                 tooltipNode.setText(tooltipString);
  884.                 tooltipNode.setOffset(p.getX() + 8, p.getY() - 8);
  885.             }
  886.         });
  887.     }
  888.  
  889.     private void drawEdgesFromDeviceToChildren(IDevice device) {
  890.         if (device.getChildren() != null) {
  891.             for (IDevice child : device.getChildren()) {
  892.                 drawEdgesFromParentToChild(device, child);
  893.             }
  894.         }
  895.     }
  896.  
  897.     private void drawEdgesFromParentToChild(IDevice parent, IDevice child) {
  898.  
  899.         if (parent == null || child == null) {
  900.             return;
  901.         }
  902.  
  903.         PDeviceImage parentDeviceImage = parent.getDeviceImage();
  904.         PDeviceImage childDeviceImage = child.getDeviceImage();
  905.         Point2D.Double parentBounds;
  906.         Point2D.Double childBounds;
  907.  
  908.         PPath edge = childDeviceImage.getEdge();
  909.         if (edge != null) {
  910.             edge.reset();
  911.             parentBounds = (Point2D.Double) parentDeviceImage.getFullBounds().getCenter2D();
  912.             childBounds = (Point2D.Double) childDeviceImage.getFullBounds().getCenter2D();
  913.         } else {
  914.             parentBounds = (Point2D.Double) parentDeviceImage.getBounds().getCenter2D();
  915.             childBounds = (Point2D.Double) childDeviceImage.getBounds().getCenter2D();
  916.             edge = new PPath();
  917.             childDeviceImage.setEdge(edge);
  918.             edgeLayer.addChild(edge);
  919.         }
  920.  
  921.         edge.moveTo((float) parentBounds.getX(), (float) parentBounds.getY());
  922.         int offset = 0;
  923.         // draw legs for access points
  924.         if (parentBounds.getY() < childBounds.getY()) {
  925.             offset = VERTICAL_LEG_BOTTOM;
  926.         } else {
  927.             offset = VERTICAL_LEG_TOP;
  928.         }
  929.  
  930.         edge.lineTo((float) childBounds.getX(), (float) childBounds.getY() + offset);
  931.         edge.lineTo((float) childBounds.getX(), (float) childBounds.getY());
  932.  
  933.     }
  934.  
  935.     private PSwingCanvas buildStatTableCanvas(String canvasName) throws IOException {
  936.        
  937.         PSwingCanvas canvas = new PSwingCanvas();
  938.         canvas.getLayer().addChild(new PSwing(new JLabel(canvasName)));
  939.         canvas.setPanEventHandler(null);
  940.  
  941.         return createStatTable(canvas);
  942.     }
  943.    
  944.  
  945.     private void showInitDialog(int timeActiveInMillis) { // Показывает диалог на время инициализации
  946.        
  947.         if(timeActiveInMillis < 0 | timeActiveInMillis > 150000 ) timeActiveInMillis = 120000;
  948.        
  949.         class UserDefTimerTask extends TimerTask{
  950.             public JFrame jf;
  951.             public UserDefTimerTask(JFrame jf){
  952.                 this.jf = jf;
  953.             }
  954.             @Override
  955.             public void run() {
  956.                 if(jf.isShowing()){
  957.                     jf.setVisible(false);
  958.                     jf.dispose();
  959.                 }
  960.             }
  961.            
  962.         }
  963.         JFrame initDialog = new JFrame("Инициализация");
  964.         initDialog.getContentPane().setBackground(Color.lightGray);
  965.         initDialog.setBounds(300, 400, 280, 50);
  966.        
  967.         initDialog.add(new JLabel("Подождите, идет инициализация приложения... "));
  968.         initDialog.setDefaultCloseOperation(JFrame.DO_NOTHING_ON_CLOSE);
  969.        
  970.         initDialog.setAlwaysOnTop(true);
  971.         initDialog.setUndecorated(true);
  972.         initDialog.setVisible(true);
  973.        
  974.         UserDefTimerTask t = new UserDefTimerTask(initDialog);
  975.        
  976.         Timer timer = new Timer();
  977.         timer.schedule(t, timeActiveInMillis);
  978.        
  979.     }
  980.  
  981.     class CanvasInputHandler extends PBasicInputEventHandler {
  982.  
  983.         public void mouseReleased(final PInputEvent e) {
  984.             if (!(e.getPickedNode() instanceof PDeviceImage)) {
  985.                 if (e.isRightMouseButton()) {
  986.                     e.setHandled(true);
  987.                     Point2D ePos = e.getCanvasPosition();
  988.                     //ServiceRightClickMenu menu = new ServiceRightClickMenu();
  989.                     //menu.show(getCanvas(), (int) ePos.getX(), (int) ePos.getY());
  990.                 }
  991.             }
  992.         }
  993.     }
  994.  
  995.     class NodeDragHandler extends PDragSequenceEventHandler {
  996.  
  997.         public NodeDragHandler() {
  998.             //getEventFilter().setMarksAcceptedEventsAsHandled(true);
  999.         }
  1000.  
  1001.         public void mouseEntered(final PInputEvent e) {
  1002.         }
  1003.  
  1004.         public void mouseExited(final PInputEvent e) {
  1005.             if (e.getButton() == 0) {
  1006.  
  1007.                 //e.getPickedNode().setPaint(Color.white);
  1008.             }
  1009.         }
  1010.  
  1011.         public void mousePressed(final PInputEvent event) {
  1012.             super.mousePressed(event);
  1013.             setIsDragging(false);
  1014.  
  1015.         }
  1016.  
  1017.         public void mouseReleased(final PInputEvent e) {
  1018.  
  1019.             if (isDragging()) {
  1020.                 endDrag(e);
  1021.             } else {
  1022.  
  1023.                 if (!(e.getPickedNode() instanceof PDeviceImage)) {
  1024.                     return;
  1025.                 }
  1026.  
  1027.                 PDeviceImage pickedNode = (PDeviceImage) e.getPickedNode();
  1028.  
  1029.                 doZoomInOut(pickedNode);
  1030.  
  1031.                 selectDevice(pickedNode);
  1032. // Вызов всплывающего меню через правую кнопку мыши
  1033. //                if (e.isRightMouseButton()) {
  1034. //                    e.setHandled(true);
  1035. //                    Point2D ePos = e.getCanvasPosition();
  1036. //                    DeviceRightClickMenu menu = new DeviceRightClickMenu();
  1037. //                    menu.show(getCanvas(), (int) ePos.getX(), (int) ePos.getY());
  1038. //                }
  1039.  
  1040.                 // Вызов всплывающего меню через двойной клик мыши мыши - адаптировано для планшетного режима
  1041.                 if (e.getClickCount() == 1) {
  1042.                     e.setHandled(true);
  1043.                     Point2D ePos = e.getCanvasPosition();
  1044.                     DeviceRightClickMenu menu = new DeviceRightClickMenu();
  1045.                     menu.show(getCanvas(), (int) ePos.getX(), (int) ePos.getY());
  1046.                 }
  1047.             }
  1048.         }
  1049. // 12.05.14 13:30 #F256 : Prohibit dragging devices
  1050. //        public void drag(final PInputEvent e) {
  1051. //            super.drag(e);
  1052. //
  1053. //            if (!(e.getPickedNode() instanceof PDeviceImage)) {
  1054. //                return;
  1055. //            }
  1056. //
  1057. //            PDeviceImage deviceImage = (PDeviceImage) e.getPickedNode();
  1058. //            deviceImage.translate(e.getDelta().width, e.getDelta().height);
  1059. //
  1060. //            IDevice device = deviceImage.getDevice();
  1061. //            // draw edges from this device's parent to this device
  1062. //            drawEdgesFromParentToChild(device.getParent(), device);
  1063. //
  1064. //            // draw edges from node to its children          
  1065. //            drawEdgesFromDeviceToChildren(device);
  1066. //        }
  1067.     }
  1068.  
  1069.     private void selectDeviceNode(PDeviceImage newDevice) {
  1070.         // reset previous selection
  1071.         if (selectedDevice != null) {
  1072.             selectedDevice.getDeviceImage().getDeviceName().setPaint(Color.white);
  1073.         }
  1074.  
  1075.         selectedDevice = newDevice.getDevice();
  1076.         selectedDevice.getDeviceImage().getDeviceName().setPaint(Color.orange);
  1077.     }
  1078.  
  1079.     private void selectDevice(PDeviceImage pickedNode) {
  1080.         selectDeviceNode(pickedNode);
  1081.         int selectedRow = returnRowIndexForValue(selectedDevice.getId(), 0, statTable);
  1082.         statTable.setRowSelectionInterval(selectedRow, selectedRow);
  1083.  
  1084.         Rectangle rect = statTable.getCellRect(selectedRow, 1, true);
  1085.         statTable.scrollRectToVisible(rect);
  1086.     }
  1087.  
  1088.     private int returnRowIndexForValue(Object value, int columnNumber, JTable table) {
  1089.         for (int i = 0; i < table.getRowCount(); i++) {
  1090.             if (table.getValueAt(i, columnNumber).equals(value)) {
  1091.                 return i;
  1092.             }
  1093.         }
  1094.         return -1;
  1095.     }
  1096.  
  1097.     private void doZoomInOut(PDeviceImage deviceImage) {
  1098.         if (!autoZoom) {
  1099.             return;
  1100.         }
  1101.  
  1102.         PActivity panActivity = animateViewToCenterBounds(getCanvas().getCamera(), deviceImage.getFullBounds(), 2, 500);
  1103.         panActivity.setStartTime(new Date().getTime());
  1104.     }
  1105.  
  1106.     public PTransformActivity animateViewToCenterBounds(PCamera camera, final Rectangle2D centerBounds, double scale,
  1107.             final long duration) {
  1108.         final PBounds viewBounds = camera.getViewBounds();
  1109.         final PDimension delta = viewBounds.deltaRequiredToCenter(centerBounds);
  1110.         final PAffineTransform newTransform = camera.getViewTransform();
  1111.         newTransform.translate(delta.width, delta.height);
  1112.  
  1113.         if (scale != Double.POSITIVE_INFINITY && scale != 0) {
  1114.             newTransform.scaleAboutPoint(scale, centerBounds.getCenterX(), centerBounds.getCenterY());
  1115.         }
  1116.  
  1117.         return camera.animateViewToTransform(newTransform, duration);
  1118.     }
  1119.  
  1120.     /**
  1121.      * @return the data
  1122.      */
  1123.     public MainData getData() {
  1124.         return data;
  1125.     }
  1126.  
  1127.     /**
  1128.      * @param data the data to set
  1129.      */
  1130.     public void setData(MainData data) {
  1131.         this.data = data;
  1132.     }
  1133.  
  1134.     public PText getStatTitle() {
  1135.         return statTitle;
  1136.     }
  1137.  
  1138.     public void setStatTitle(PText statTitle) {
  1139.         this.statTitle = statTitle;
  1140.     }
  1141.  
  1142.     class DeviceRightClickMenu extends JPopupMenu {
  1143.  
  1144.         public DeviceRightClickMenu() {
  1145.            
  1146.  
  1147.            JMenuItem restartItem = new JMenuItem("Перезагрузить устройство");
  1148.             restartItem.setEnabled(false);
  1149.             restartItem.addActionListener(new ActionListener() {
  1150.                 @Override
  1151.                 public void actionPerformed(ActionEvent e) {
  1152.  
  1153.                 }
  1154.             });
  1155.             add(restartItem);
  1156.            
  1157.             JMenu  setEmission = new JMenu ("Установить мощность излучения ББПИ");
  1158.             setEmission.setEnabled(true);
  1159.             setEmission.addActionListener(new ActionListener() {
  1160.                 @Override
  1161.                 public void actionPerformed(ActionEvent e) {
  1162.                    
  1163.                 }
  1164.             });
  1165.            
  1166.             JMenuItem setEmissionMin = new JMenuItem ("Min");
  1167.             setEmissionMin.addActionListener(new ActionListener() {
  1168.  
  1169.                 @Override
  1170.                 public void actionPerformed(ActionEvent ae) {
  1171.                     JOptionPane.showMessageDialog(MainFrame.this,"Для того, чтобы установить минимальную мощность излучения ББПИ"
  1172.                             + "\nПерейдите в web интерфейс КТД в раздел"
  1173.                             + "\n\"Configuration\" - \"Wireless\" - \"Basic\" - \"RF Management\""
  1174.                             + "\nВыберите значение \"Default Tx Power\" = \"Minimum\"");
  1175.                     // Код ответа операции set txPower
  1176.                 }
  1177.             });
  1178.            
  1179.             JMenuItem setEmissionEighth = new JMenuItem ("Eighth");
  1180.             setEmissionEighth.addActionListener(new ActionListener() {
  1181.  
  1182.                 @Override
  1183.                 public void actionPerformed(ActionEvent ae) {
  1184.                     JOptionPane.showMessageDialog(MainFrame.this, "Для того, чтобы установить одну восьмую значения мощности излучения ББПИ"
  1185.                             + "\nПерейдите в web интерфейс КТД в раздел"
  1186.                             + "\n\"Configuration\" - \"Wireless\" - \"Basic\" - \"RF Management\""
  1187.                             + "\nВыберите значение \"Default Tx Power\" = \"Eighth\"");
  1188.                     // Код ответа операции set txPower
  1189.                 }
  1190.             });
  1191.            
  1192.             JMenuItem setEmissionQuarter = new JMenuItem ("Quarter");
  1193.             setEmissionQuarter.addActionListener(new ActionListener() {
  1194.  
  1195.                 @Override
  1196.                 public void actionPerformed(ActionEvent ae) {
  1197.                             JOptionPane.showMessageDialog(MainFrame.this, "Для того, чтобы установить значение четверти мощности излучения ББПИ"
  1198.                             + "\nПерейдите в web интерфейс КТД в раздел"
  1199.                             + "\n\"Configuration\" - \"Wireless\" - \"Basic\" - \"RF Management\""
  1200.                             + "\nВыберите значение \"Default Tx Power\" = \"Quarter\"");
  1201.                     // Код ответа операции set txPower
  1202.                 }
  1203.             });
  1204.            
  1205.             JMenuItem setEmissionHalf = new JMenuItem ("Half");
  1206.             setEmissionHalf.addActionListener(new ActionListener() {
  1207.  
  1208.                 @Override
  1209.                 public void actionPerformed(ActionEvent ae) {
  1210.                             JOptionPane.showMessageDialog(MainFrame.this, "Для того, чтобы установить значение половины мощности излучения ББПИ"
  1211.                             + "\nПерейдите в web интерфейс КТД в раздел"
  1212.                             + "\n\"Configuration\" - \"Wireless\" - \"Basic\" - \"RF Management\""
  1213.                             + "\nВыберите значение \"Default Tx Power\" = \"Half\"");
  1214.                     // Код ответа операции set txPower
  1215.                 }
  1216.             });
  1217.            
  1218.             JMenuItem setEmissionMax = new JMenuItem ("Full");
  1219.             setEmissionMax.addActionListener(new ActionListener() {
  1220.  
  1221.                 @Override
  1222.                 public void actionPerformed(ActionEvent ae) {
  1223.                             JOptionPane.showMessageDialog(MainFrame.this, "Для того, чтобы установить значение полную мощность излучения ББПИ"
  1224.                             + "\nПерейдите в web интерфейс КТД в раздел"
  1225.                             + "\n\"Configuration\" - \"Wireless\" - \"Basic\" - \"RF Management\""
  1226.                             + "\nВыберите значение \"Default Tx Power\" = \"Full\"");
  1227.                     // Код ответа операции set txPower
  1228.                     // Код ответа операции set txPower
  1229.                 }
  1230.             });
  1231.            
  1232.             setEmission.add(setEmissionMin);
  1233.             setEmission.add(setEmissionEighth);
  1234.             setEmission.add(setEmissionQuarter);
  1235.             setEmission.add(setEmissionHalf);
  1236.             setEmission.add(setEmissionMax);
  1237.  
  1238.             if(selectedDevice instanceof AccessPoint){
  1239.                 add(setEmission);
  1240.             }
  1241.            
  1242.  
  1243.             JMenuItem statisticsItem = new JMenuItem("Статистика");
  1244.             statisticsItem.setEnabled(false);
  1245.             statisticsItem.addActionListener(new ActionListener() {
  1246.                 @Override
  1247.                 public void actionPerformed(ActionEvent e) {
  1248.                     //showDeviceStatistics(device);
  1249.                 }
  1250.             });
  1251.             add(statisticsItem);
  1252.            
  1253.             JMenuItem pingItem = new JMenuItem("Выполнить команду ping");
  1254.             pingItem.setEnabled(true);
  1255.             pingItem.addActionListener(new ActionListener() {
  1256.                 @Override
  1257.                 public void actionPerformed(ActionEvent e) {
  1258.  
  1259.                     try {
  1260.                         String[] commands = {"fly-term", "-e", "ping", selectedDevice.getIpAddress()};
  1261.                         Runtime.getRuntime().exec(commands);
  1262.                     } catch (IOException e1) {
  1263.                         e1.printStackTrace();
  1264.                     }
  1265.  
  1266.                 }
  1267.             });
  1268.             add(pingItem);
  1269.  
  1270.             final JMenuItem wiItem = new JMenuItem("Открыть web интерфейс устройства");
  1271.             wiItem.setEnabled(true);
  1272.             wiItem.addActionListener(new ActionListener() {
  1273.                 @Override
  1274.                 public void actionPerformed(ActionEvent e) {
  1275.                     try {
  1276.                         String[] commands = {"firefox", "http://"+selectedDevice.getIpAddress()};
  1277.                         Runtime.getRuntime().exec(commands);
  1278.                     } catch (IOException e1) {
  1279.                         e1.printStackTrace();
  1280.                     }
  1281.                 }
  1282.             });
  1283.  
  1284.             if(!(selectedDevice instanceof PhoneServer)) {
  1285.                 add(wiItem);
  1286.             }
  1287.         }
  1288.     }
  1289.  
  1290.     private void redrawEdgesRecursively(IDevice device) {
  1291.         //device.determineEdgeStyleFromState();
  1292.         device.determineEdgeStyleFromPing();
  1293.         if (device.getChildren() != null) {
  1294.             for (IDevice childDevice : device.getChildren()) {
  1295.                 redrawEdgesRecursively(childDevice);
  1296.             }
  1297.         }
  1298.     }
  1299.    
  1300.  
  1301. //    private void createNewBskp() {
  1302. //        IDevice bskp = data.createNewBskp();
  1303. //        if (bskp == null) {
  1304. //            return;
  1305. //        }
  1306. //        PDeviceImage deviceImage = new PDeviceImage(bskp);
  1307. //        nodeLayer.addChild(deviceImage);
  1308. //
  1309. //        drawEdgesFromParentToChild(bskp.getParent(), bskp);
  1310. //        setTableData();
  1311. //        selectDevice(deviceImage);
  1312. //    }
  1313.  
  1314.     private void createRandomNodeStateActivity() {
  1315.         changeRandomNodeStateActivity = new PActivity(-1, 1000) {
  1316.             protected void activityStep(long time) {
  1317.                 super.activityStep(time);
  1318.  
  1319.                 for (int i = 0; i < 20; i++) {
  1320.                     int randomDeviceIndex = randInt(0, data.getAllDevices().size() - 1);
  1321.                     IDevice randomDevice = new ArrayList<IDevice>(
  1322.                             data.getAllDevices()).get(randomDeviceIndex);
  1323.                     int randomStateIndex = new Random().nextInt(DeviceState.values().length);
  1324.                     randomDevice.setState(DeviceState.values()[randomStateIndex]);
  1325.                     selectDevice(randomDevice.getDeviceImage());
  1326.                 }
  1327.  
  1328.                 try {
  1329.                     setTableData();
  1330.                 } catch (IOException ex) {
  1331.                     Logger.getLogger(MainFrame.class.getName()).log(Level.SEVERE, null, ex);
  1332.                 }
  1333.             }
  1334.         };
  1335.         nodeLayer.addActivity(changeRandomNodeStateActivity);
  1336.     }
  1337.  
  1338.     private void stopActivity() {
  1339.         if (changeRandomNodeStateActivity != null) {
  1340.             changeRandomNodeStateActivity.terminate();
  1341.         }
  1342.     }
  1343.  
  1344.     private void deleteDevice(IDevice device) throws IOException {
  1345.  
  1346.         // disconnect device from its parent
  1347.         if (device.getParent() != null) {
  1348.             device.getParent().getChildren().remove(device);
  1349.         }
  1350.         // disconnect device from its children
  1351.         if (device.getChildren() != null) {
  1352.             for (IDevice child : device.getChildren()) {
  1353.                 child.setParent(null);
  1354.                 edgeLayer.removeChild(child.getDeviceImage().getEdge());
  1355.                 child.getDeviceImage().setEdge(null);
  1356.             }
  1357.         }
  1358.         // delete image
  1359.         nodeLayer.removeChild(device.getDeviceImage());
  1360.         // delete parent edge
  1361.         edgeLayer.removeChild(device.getDeviceImage().getEdge());
  1362.         device.getDeviceImage().setEdge(null);
  1363.  
  1364.         data.getDevicesMap().remove(device.getId());
  1365.  
  1366.         setTableData();
  1367.         selectDevice(data.getAllDevices().iterator().next().getDeviceImage());
  1368.     }
  1369.  
  1370.     /**
  1371.      * Returns a pseudo-random number between min and max, inclusive. The
  1372.      * difference between min and max can be at most
  1373.      * <code>Integer.MAX_VALUE - 1</code>.
  1374.      *
  1375.      * @para m min Minimim value
  1376.      * @param max Maximim value. Must be greater than min.
  1377.      * @return Integer between min and max, inclusive.
  1378.      * @see java.util.Random#nextInt(int)
  1379.      */
  1380.     public static int randInt(int min, int max) {
  1381.  
  1382.         // Usually this can be a field rather than a method variable
  1383.         Random rand = new Random();
  1384.  
  1385.         // nextInt is normally exclusive of the top value,
  1386.         // so add 1 to make it inclusive
  1387.         int randomNum = rand.nextInt((max - min) + 1) + min;
  1388.  
  1389.         return randomNum;
  1390.     }
  1391.  
  1392.     private void createMenu() {
  1393.         // create menu bar
  1394.         JMenuBar menuBar = new JMenuBar();
  1395.  
  1396.         setJMenuBar(menuBar);
  1397.  
  1398.         JMenu menuSettings = new JMenu("Settings");
  1399.         menuBar.add(menuSettings);
  1400.  
  1401.         JMenuItem menuItemTest = new JMenuItem("Test");
  1402.         menuSettings.add(menuItemTest);
  1403.         menuItemTest.addActionListener(new ActionListener() {
  1404.             @Override
  1405.             public void actionPerformed(ActionEvent e) {
  1406.                 System.out.println("test");
  1407.             }
  1408.         });
  1409.  
  1410.         JMenu menuAbout = new JMenu("Help");
  1411.         menuBar.add(menuAbout);
  1412.  
  1413.         JMenuItem menuItemAbout = new JMenuItem("About");
  1414.         menuItemAbout.addActionListener(new ActionListener() {
  1415.             @Override
  1416.             public void actionPerformed(ActionEvent e) {
  1417.                 JOptionPane.showMessageDialog(MainFrame.this,
  1418.                         " Управление сетевой инфраструктурой изделия МДА БСОРИ (alpha версия 1.0.3 )\n\n"
  1419.                         + "Отправляет запросы и получает ответы по протоколу SNMP версии 2 \n"        
  1420.                         + "на коммутаторы(БСК, БСКП), сервер(БУВО), точки доступа(ББПИ)\n"
  1421.                         + "и выводит результаты на графический интерфейс пользователя\n"
  1422.                         + "Красный цвет устройств - БУВО не получает ответ от опрашиваемых устройств \n"
  1423.                         + "Зеленый цвет устройств - БУВО получает ответ от опрашиваемых устройств \n"
  1424.                         + "Щелчок правой кнопкой мыши на устройстве - позволяет манипулировать устройством: выключить, перезагрузить (В стадии теста), собрать статистику \n"
  1425.  
  1426.                 );
  1427.             }
  1428.         });
  1429.         menuAbout.add(menuItemAbout);
  1430.  
  1431.     }
  1432.  
  1433.     /**
  1434.      * Zoom handler with restrictions for max and min zoom scale.
  1435.      *
  1436.      * @author
  1437.      *
  1438.      */
  1439.     static class CustomZoomHandler extends PZoomEventHandler {
  1440.  
  1441.         /**
  1442.          * A constant used to adjust how sensitive the zooming will be to mouse
  1443.          * movement. The larger the number, the more each delta pixel will
  1444.          * affect zooming.
  1445.          */
  1446.         private static final double ZOOM_SENSITIVITY = 0.001;
  1447.         private double minScale = 0.5;
  1448.         private double maxScale = 5;
  1449.         private Point2D viewZoomPoint;
  1450.  
  1451.         /**
  1452.          * Records the start point of the zoom. Used when calculating the delta
  1453.          * for zoom speed.
  1454.          *
  1455.          * @param event event responsible for starting the zoom interaction
  1456.          */
  1457.         protected void dragActivityFirstStep(final PInputEvent event) {
  1458.             viewZoomPoint = event.getPosition();
  1459.         }
  1460.  
  1461.         protected void dragActivityStep(final PInputEvent event) {
  1462.             final PCamera camera = event.getCamera();
  1463.             final double dx = event.getCanvasPosition().getX() - getMousePressedCanvasPoint().getX();
  1464.             double scaleDelta = 1.0 + ZOOM_SENSITIVITY * dx;
  1465.  
  1466.             final double currentScale = camera.getViewScale();
  1467.             final double newScale = currentScale * scaleDelta;
  1468.  
  1469.             if (newScale < minScale) {
  1470.                 scaleDelta = minScale / currentScale;
  1471.             }
  1472.             if (maxScale > 0 && newScale > maxScale) {
  1473.                 scaleDelta = maxScale / currentScale;
  1474.             }
  1475.  
  1476.             camera.scaleViewAboutPoint(scaleDelta, viewZoomPoint.getX(), viewZoomPoint.getY());
  1477.         }
  1478.  
  1479.     }
  1480.    
  1481.     /**
  1482.      * Opens a web page using Firefox browser,
  1483.      * enters login name/password and tries to login.
  1484.      */
  1485.     private void loginToPage() {
  1486.        
  1487.         String username = "admin";
  1488.         String password = "Marine2Air";
  1489.         // Create a new instance of the Firefox driver
  1490.         // Notice that the remainder of the code relies on the interface,
  1491.         // not the implementation.
  1492.         WebDriver driver = new FirefoxDriver();
  1493.         // And now use this to visit Google
  1494.         driver.get("http://10.168.2.50/login.php");
  1495.         WebElement userNameElement = driver.findElement(By.id("user_name"));
  1496.         // Enter user name
  1497.         userNameElement.sendKeys(username);
  1498.        
  1499.         // Find the 'password' text input element by its name attribute 'j_password'
  1500.         WebElement passwordElement = driver.findElement(By.id("password"));
  1501.         // Enter password
  1502.         passwordElement.sendKeys(password);
  1503.         //Click LOGIN button
  1504.         driver.findElement(By.className("enablebuttonstyle")).click();
  1505.     }
  1506.    
  1507.         private void managedAPList() throws InterruptedException {
  1508.         boolean acceptNextAlert = true;
  1509.         String username = "admin";
  1510.         String password = "Marine2Air";
  1511.         // Create a new instance of the Firefox driver
  1512.         // Notice that the remainder of the code relies on the interface,
  1513.         // not the implementation.
  1514.         WebDriver driver = new FirefoxDriver();
  1515.         // And now use this to visit Google
  1516.         driver.get("http://10.168.2.50/login.php");
  1517.         driver.findElement(By.id("user_name")).clear();
  1518.         driver.findElement(By.id("user_name")).sendKeys("admin");
  1519.         driver.findElement(By.id("password")).clear();
  1520.         driver.findElement(By.id("password")).sendKeys("Marine2Air");
  1521.         driver.findElement(By.className("enablebuttonstyle")).click();
  1522.    
  1523.        
  1524.         try {
  1525.             Alert alert = driver.switchTo().alert();
  1526.             String alertText = alert.getText();
  1527.             if (acceptNextAlert) {
  1528.                 alert.accept();
  1529.             } else {
  1530.                 alert.dismiss();
  1531.             }
  1532.             alertText = alert.getText();
  1533.         } finally {
  1534.             acceptNextAlert = true;
  1535.         }
  1536.        
  1537.         //driver.findElement(By.cssSelector("input.enablebuttonstyle")).click();
  1538.         driver.findElement(By.linkText("Access Point")).click();
  1539.         driver.findElement(By.cssSelector("#TD_Main_2 > a.TertiaryNav > strong")).click();
  1540.         // ERROR: Caught exception [Error: locator strategy either id or name must be specified explicitly.]
  1541.         driver.findElement(By.id("ManagedAccessPoint-status")).click();
  1542.         driver.findElement(By.id("ManagedAccessPoint-status")).click();
  1543.        
  1544.     }
  1545.  
  1546. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement