Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- package ru.nppame.netManage.gui;
- import edu.umd.cs.piccolo.PCamera;
- import edu.umd.cs.piccolo.PLayer;
- import edu.umd.cs.piccolo.PNode;
- import edu.umd.cs.piccolo.activities.PActivity;
- import edu.umd.cs.piccolo.activities.PTransformActivity;
- import edu.umd.cs.piccolo.event.PBasicInputEventHandler;
- import edu.umd.cs.piccolo.event.PDragSequenceEventHandler;
- import edu.umd.cs.piccolo.event.PInputEvent;
- import edu.umd.cs.piccolo.event.PInputEventFilter;
- import edu.umd.cs.piccolo.event.PZoomEventHandler;
- import edu.umd.cs.piccolo.nodes.PPath;
- import edu.umd.cs.piccolo.nodes.PText;
- import edu.umd.cs.piccolo.util.PAffineTransform;
- import edu.umd.cs.piccolo.util.PBounds;
- import edu.umd.cs.piccolo.util.PDimension;
- import edu.umd.cs.piccolox.PFrame;
- import edu.umd.cs.piccolox.pswing.PSwing;
- import edu.umd.cs.piccolox.pswing.PSwingCanvas;
- import edu.umd.cs.piccolox.swing.PScrollPane;
- import java.awt.BorderLayout;
- import java.awt.Color;
- import java.awt.Component;
- import java.awt.Container;
- import java.awt.Dialog;
- import java.awt.Dimension;
- import java.awt.FlowLayout;
- import java.awt.Polygon;
- import java.awt.Rectangle;
- import java.awt.event.ActionEvent;
- import java.awt.event.ActionListener;
- import java.awt.event.InputEvent;
- import java.awt.event.WindowAdapter;
- import java.awt.event.WindowEvent;
- import java.awt.geom.Point2D;
- import java.awt.geom.Rectangle2D;
- import java.io.FileInputStream;
- import java.io.IOException;
- import java.io.InputStreamReader;
- import java.util.ArrayList;
- import java.util.Date;
- import java.util.List;
- import java.util.Properties;
- import java.util.Random;
- import java.util.Timer;
- import java.util.TimerTask;
- import java.util.Vector;
- import java.util.concurrent.Executors;
- import java.util.concurrent.ScheduledExecutorService;
- import java.util.concurrent.TimeUnit;
- import java.util.logging.Level;
- import java.util.logging.Logger;
- import javax.swing.BorderFactory;
- import javax.swing.JButton;
- import javax.swing.JDialog;
- import javax.swing.JFrame;
- import javax.swing.JLabel;
- import javax.swing.JMenu;
- import javax.swing.JMenuBar;
- import javax.swing.JMenuItem;
- import javax.swing.JOptionPane;
- import javax.swing.JPopupMenu;
- import javax.swing.JScrollPane;
- import javax.swing.JSlider;
- import javax.swing.JSplitPane;
- import javax.swing.JTable;
- import javax.swing.event.ChangeEvent;
- import javax.swing.event.ChangeListener;
- import javax.swing.event.ListSelectionEvent;
- import javax.swing.event.ListSelectionListener;
- import javax.swing.plaf.basic.BasicSplitPaneDivider;
- import javax.swing.plaf.basic.BasicSplitPaneUI;
- import javax.swing.table.DefaultTableCellRenderer;
- import javax.swing.table.DefaultTableModel;
- import javax.swing.table.TableColumn;
- import org.openqa.selenium.Alert;
- import org.openqa.selenium.By;
- import org.openqa.selenium.WebDriver;
- import org.openqa.selenium.WebElement;
- import org.openqa.selenium.firefox.FirefoxDriver;
- import ru.nppame.netManage.device.IDevice;
- import ru.nppame.netManage.device.impl.AccessPoint;
- import ru.nppame.netManage.device.impl.PhoneServer;
- import ru.nppame.netManage.device.state.DeviceState;
- import static ru.nppame.netManage.gui.Launcher.logger;
- import ru.nppame.netManage.snmp.SnmpHandler;
- import ru.nppame.tools.AppRunner;
- /**
- * The main application's frame.
- *
- */
- public class MainFrame extends PFrame {
- private static final long serialVersionUID = 1L;
- /**
- * The length of the vertical leg between a device and a connecting line.
- */
- private static final int VERTICAL_LEG_BOTTOM = -60;
- private static final int VERTICAL_LEG_TOP = 60;
- private MainData data;
- private PText tooltipNode;
- private PText statTitle;
- private IDevice selectedDevice;
- private JTable statTable;
- private PLayer nodeLayer;
- private PLayer edgeLayer;
- private PActivity changeRandomNodeStateActivity;
- private CustomZoomHandler customZoomHandler;
- private boolean autoZoom = false;
- private PSwingCanvas canvas0;
- private PSwingCanvas canvas1;
- private PSwingCanvas canvas2;
- private PSwingCanvas canvas3;
- private PSwingCanvas canvas4;
- public MainFrame(MainData data) {
- super("Интерфейс МДА БСОРИ ", false, new PSwingCanvas());
- // Image img = new ImageIcon(Launcher.class.getResource("./img/AME_icon.ico")).getImage();
- // this.setIconImage(img);
- this.data = data;
- setSize(1920, 1080);
- setLocation(0, 0);
- setDefaultCloseOperation(DO_NOTHING_ON_CLOSE);
- setVisible(true);
- this.addWindowListener(new WindowAdapter() {
- public void windowClosing(WindowEvent e) {
- Object[] options = {"Да", "Нет"};
- int result = JOptionPane.showOptionDialog(new JFrame(),
- "Вы действительно хотите выйти из программы ?", "Подтверждение выхода",
- JOptionPane.YES_NO_OPTION, JOptionPane.QUESTION_MESSAGE, null,
- options, options[1]);
- if (result == JOptionPane.YES_OPTION) {
- try {
- // stop the polling thread pool
- //SnmpHandler.getInstance().stop();
- System.exit(0);
- } catch (Exception exc) {
- exc.printStackTrace();
- }
- } else {
- // Do nothing
- }
- }
- });
- ScheduledExecutorService ses = Executors.newSingleThreadScheduledExecutor();
- ses.scheduleAtFixedRate(new Runnable() {
- PSwingCanvas[] ps = new PSwingCanvas[]{canvas0, canvas1, canvas2};
- @Override
- public void run() {
- updateGraphics(ps);
- }
- }, 0, 1, TimeUnit.SECONDS);
- }
- public static void updateGraphics(PSwingCanvas[] canvases) {
- for (int i = 0; i < canvases.length; i++) {
- for (int j = 0; j < canvases[i].getComponents().length; j++) {
- canvases[i].getComponent(j).revalidate();
- canvases[i].getComponent(j).repaint();
- }
- }
- }
- public static void updateGraphics(PSwingCanvas canvases) {
- for (int i = 0; i < canvases.getComponents().length; i++) {
- canvases.getComponent(i).revalidate();
- canvases.getComponent(i).repaint();
- }
- }
- public void initialize() {
- try {
- createCanvas();
- showInitDialog(150000); //150 sec
- } catch (IOException ex) {
- Logger.getLogger(MainFrame.class.getName()).log(Level.SEVERE, null, ex);
- }
- }
- // Drawing frame and text label for BSKP
- private PNode drawShape(int[] x, int[] y, String textLabel) {
- Polygon p = new Polygon(x, y, x.length);
- PNode n = new PPath(p);
- PText pTextLabel = new PText(textLabel);
- pTextLabel.setX(n.getX() + 45);
- pTextLabel.setY(n.getY());
- n.addChild(pTextLabel);
- return n;
- }
- private void createCanvas() throws IOException {
- Container container = getContentPane();
- container.setLayout(new BorderLayout());
- canvas0 = buildLabelTitleCanvas("");
- canvas0.setPreferredSize(new Dimension(50, 50));
- canvas0.setBorder(BorderFactory.createLineBorder(Color.GRAY, 1, true));
- container.add(canvas0, BorderLayout.NORTH);
- canvas1 = buildMainCanvas("");
- canvas1.setPreferredSize(new Dimension(800, 800));
- canvas1.setBorder(BorderFactory.createLineBorder(Color.GRAY, 1, true));
- PScrollPane scrollPane1 = new PScrollPane(canvas1);
- //container.add(scrollPane1, BorderLayout.CENTER);
- canvas2 = buildStatTableCanvas("");
- canvas2.setPreferredSize(new Dimension(1000, 800));
- canvas2.setBorder(BorderFactory.createLineBorder(Color.GRAY, 1, true));
- PScrollPane scrollPane2 = new PScrollPane(canvas2);
- //container.add(scrollPane2, BorderLayout.NORTH);
- final JSplitPane horizontalSplitPane = new JSplitPane(JSplitPane.HORIZONTAL_SPLIT,
- scrollPane1, scrollPane2);
- horizontalSplitPane.setOneTouchExpandable(true);
- horizontalSplitPane.setDividerLocation(850);
- horizontalSplitPane.setDividerSize(20);
- //container.add(horizontalSplitPane, BorderLayout.CENTER);
- canvas4 = buildButtonsCanvas("");
- canvas4.setPreferredSize(new Dimension(1000, 250));
- canvas4.setBorder(BorderFactory.createLineBorder(Color.GRAY, 1, true));
- //container.add(canvas4, BorderLayout.SOUTH);
- //createZoomButton(canvas4, canvas1 );
- createZoomSlider(canvas4, canvas1, "Масштаб в процентах");
- PScrollPane scrollPane4 = new PScrollPane(canvas4);
- JSplitPane verticalSplitPane = new JSplitPane(JSplitPane.VERTICAL_SPLIT,
- horizontalSplitPane, scrollPane4);
- verticalSplitPane.setOneTouchExpandable(true);
- verticalSplitPane.setDividerLocation(600);
- verticalSplitPane.setDividerSize(20);
- container.add(verticalSplitPane, BorderLayout.CENTER);
- }
- private PSwingCanvas buildMainCanvas(String canvasName) {
- final PSwingCanvas canvas = new PSwingCanvas();
- createMenu();
- createNodesAndEdges(canvas);
- return canvas;
- }
- private PSwingCanvas buildButtonsCanvas(String canvasName) {
- PSwingCanvas canvas = new PSwingCanvas();
- canvas.getLayer().addChild(new PSwing(new JLabel(canvasName)));
- canvas.setPanEventHandler(null);
- return createButtons(canvas);
- }
- private PSwingCanvas buildLabelTitleCanvas(String canvasName) {
- PSwingCanvas canvas = new PSwingCanvas();
- canvas.getLayer().addChild(new PSwing(new JLabel(canvasName)));
- canvas.setPanEventHandler(null);
- return createLabel(canvas, "Схема сетевой инфраструктуры МДА БСОРИ", 10, 10, 30);
- }
- private PSwingCanvas createLabel(PSwingCanvas pSwingCanvas, String text, int x, int y, int fontSize) {
- PText title = new PText(text);
- title.setFont(new java.awt.Font("SansSerif", 3, fontSize));
- title.setX(x);
- title.setX(y);
- pSwingCanvas.getLayer().addChild(title);
- return pSwingCanvas;
- }
- /**
- * Creates and lays out nodes
- */
- private PSwingCanvas createNodesAndEdges(PSwingCanvas pSwingCanvas) {
- nodeLayer = getCanvas().getLayer();
- edgeLayer = new PLayer();
- pSwingCanvas.getCamera().addLayer(edgeLayer);
- pSwingCanvas.getCamera().addLayer(nodeLayer);
- PText title = new PText("");
- title.setFont(new java.awt.Font("SansSerif", 3, 24));
- title.setX(100);
- nodeLayer.addChild(title);
- // create device images
- List<PDeviceImage> deviceImages = new ArrayList<PDeviceImage>();
- for (IDevice device : data.getAllDevices()) {
- PDeviceImage deviceImage = new PDeviceImage(device);
- deviceImages.add(deviceImage);
- nodeLayer.addChild(deviceImage);
- }
- 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}, "БСКП"));
- // connect devices with lines (edges)
- for (IDevice device : data.getAllDevices()) {
- drawEdgesFromDeviceToChildren(device);
- }
- // Create event handler to drag and drop devices
- nodeLayer.addInputEventListener(new NodeDragHandler());
- // add right click menu hanlder
- pSwingCanvas.addInputEventListener(new CanvasInputHandler());
- // Move (pan) screen with Ctrl key
- pSwingCanvas.getPanEventHandler().setEventFilter(new PInputEventFilter(InputEvent.CTRL_MASK));
- // customZoomHandler = new CustomZoomHandler();
- // customZoomHandler.setEventFilter(new PInputEventFilter(InputEvent.SHIFT_MASK));
- pSwingCanvas.setZoomEventHandler(customZoomHandler);
- createUpdateScreenActivity();
- createPollingActivity();
- createToolTip(pSwingCanvas);
- return pSwingCanvas;
- }
- private PSwingCanvas createZoomSlider(final PSwingCanvas pSwingCanvasToAdd, final PSwingCanvas pSwingCanvasZoomable, String label) {
- //Create the label.
- JLabel sliderLabel = new JLabel("Масштаб в процентах", JLabel.CENTER);
- JSlider zoomSlider = new JSlider(50, 150);
- class SliderListener implements ChangeListener {
- public void stateChanged(ChangeEvent e) {
- JSlider source = (JSlider) e.getSource();
- if (!source.getValueIsAdjusting()) {
- int sliderValue = (int) source.getValue();
- switch (sliderValue) {
- case 50:
- pSwingCanvasZoomable.getCamera().setViewScale(0.5);
- pSwingCanvasZoomable.getCamera().setViewOffset(0, 0);
- JOptionPane.showMessageDialog(null, "Удерживайте клавишу \"Ctrl\" и перетаскивайте рисунок мышью для навигации.");
- break;
- case 100:
- pSwingCanvasZoomable.getCamera().setViewScale(1.0);
- pSwingCanvasZoomable.getCamera().setViewOffset(0, 0);
- JOptionPane.showMessageDialog(null, "Удерживайте клавишу \"Ctrl\" и перетаскивайте рисунок мышью для навигации.");
- break;
- case 150:
- pSwingCanvasZoomable.getCamera().setViewScale(1.5);
- pSwingCanvasZoomable.getCamera().setViewOffset(0, 0);
- JOptionPane.showMessageDialog(null, "Удерживайте клавишу \"Ctrl\" и перетаскивайте рисунок мышью для навигации.");
- break;
- }
- }
- }
- }
- zoomSlider.addChangeListener(new SliderListener());
- zoomSlider.setMajorTickSpacing(50);
- zoomSlider.setPaintTicks(true);
- zoomSlider.setPaintLabels(true);
- zoomSlider.setSnapToTicks(true);
- PSwing pSwing = new PSwing(zoomSlider);
- pSwing.translate(310, 20);
- pSwingCanvasToAdd.getLayer().addChild(pSwing);
- PSwing pSwing2 = new PSwing(sliderLabel);
- pSwingCanvasToAdd.getLayer().addChild(pSwing2);
- pSwing2.translate(350, 0);
- return pSwingCanvasZoomable;
- }
- private void createUpdateScreenActivity() {
- PActivity updateScreenActivity = new PActivity(-1, IDevice.SCREEN_UPDATE_INTERVAL) {
- protected void activityStep(long time) {
- super.activityStep(time);
- try {
- // System.out.println("update screen activity called...");
- setTableData();
- } catch (IOException ex) {
- Logger.getLogger(MainFrame.class.getName()).log(Level.SEVERE, null, ex);
- }
- if (selectedDevice != null) {
- selectDevice(selectedDevice.getDeviceImage());
- }
- }
- };
- nodeLayer.addActivity(updateScreenActivity);
- }
- private void createPollingActivity() {
- PActivity pollDeviceActivity = new PActivity(-1, IDevice.DEVICE_POLL_INTERVAL) {
- protected void activityStep(long time) {
- super.activityStep(time);
- //System.out.println("poll all devices...");
- System.out.println("Опрос всех устройств по snmp...");
- try {
- SnmpHandler.getInstance().pollAllDevices();
- // updateGraphics(canvas0);
- // updateGraphics(canvas1);
- // updateGraphics(canvas2);
- // updateGraphics(canvas4);
- //updateGraphics(new PSwingCanvas[] {canvas0, canvas1, canvas2, canvas4});
- } catch (Throwable ex) {
- Logger.getLogger(MainFrame.class.getName()).log(Level.SEVERE, null, ex);
- }
- }
- };
- nodeLayer.addActivity(pollDeviceActivity);
- }
- /**
- * Adds buttons to the screen
- */
- private PSwingCanvas createButtons(final PSwingCanvas pSwingCanvas) {
- // Add the default zoom button
- // JButton zoom100button = new JButton("Zoom = 100%");
- // zoom100button.addActionListener(new ActionListener() {
- // public void actionPerformed(final ActionEvent e) {
- // pSwingCanvas.getCamera().setViewScale(1.0);
- // pSwingCanvas.getCamera().setViewOffset(0, 0);
- //
- // }
- // });
- // PSwing pSwing = new PSwing(zoom100button);
- // pSwing.translate(50, 50);
- // pSwingCanvas.getLayer().addChild(pSwing);
- //----------------------------------------------------------------------------------------------------------------
- // JButton fullScreen = new JButton("Полный экран");
- // fullScreen.addActionListener(new ActionListener() {
- // public void actionPerformed(final ActionEvent e) {
- // if (selectedDevice != null) {
- // System.out.println("Currently selected device: " + selectedDevice.getName());
- // }
- // for (IDevice device : data.getAllDevices()) {
- // if (device instanceof AccessPoint) {
- // continue;
- // }
- // System.out.println(device.getName() + " " + device.getDeviceImage().getFullBounds());
- // }
- // JOptionPane.showMessageDialog(null, "Switching to full screen");
- // setFullScreenMode(true);
- // }
- // });
- // PSwing pSwing = new PSwing(fullScreen);
- // pSwing.translate(50, 50);
- // pSwingCanvas.getLayer().addChild(pSwing);
- // JButton startRandomStateButton = new JButton("Start Activity");
- // startRandomStateButton.addActionListener(new ActionListener() {
- // public void actionPerformed(final ActionEvent e) {
- // createRandomNodeStateActivity();
- // }
- // });
- // pSwing = new PSwing(startRandomStateButton);
- // pSwing.translate(200, 600);
- // getCanvas().getLayer().addChild(pSwing);
- // JButton stopRandomStateButton = new JButton("Stop Activity");
- // stopRandomStateButton.addActionListener(new ActionListener() {
- // public void actionPerformed(final ActionEvent e) {
- // stopActivity();
- // }
- // });
- // pSwing = new PSwing(stopRandomStateButton);
- // pSwing.translate(350, 600);
- // getCanvas().getLayer().addChild(pSwing);
- // JButton addBskpButton = new JButton("Add BSKP");
- // addBskpButton.addActionListener(new ActionListener() {
- // public void actionPerformed(final ActionEvent e) {
- // createNewBskp();
- // }
- // });
- // pSwing = new PSwing(addBskpButton);
- // pSwing.translate(530, 600);
- // getCanvas().getLayer().addChild(pSwing);
- // JButton testButton = new JButton("Test");
- // testButton.addActionListener(new ActionListener() {
- // public void actionPerformed(final ActionEvent e) {
- // test();
- // }
- // });
- // pSwing = new PSwing(testButton);
- // pSwing.translate(730, 600);
- // getCanvas().getLayer().addChild(pSwing);
- JButton modeButton = new JButton("Режим");
- modeButton.setEnabled(false);
- modeButton.addActionListener(new ActionListener() {
- public void actionPerformed(final ActionEvent e) {
- //test();
- }
- });
- PSwing pSwing = new PSwing(modeButton);
- pSwing.translate(40, 80);
- pSwingCanvas.getLayer().addChild(pSwing);
- JButton diagnosticsButton = new JButton("Диагностика");
- diagnosticsButton.setEnabled(true);
- diagnosticsButton.addActionListener(new ActionListener() {
- public void actionPerformed(final ActionEvent e) {
- try {
- managedAPList();
- } catch (InterruptedException ex) {
- Logger.getLogger(MainFrame.class.getName()).log(Level.SEVERE, null, ex);
- }
- }
- });
- pSwing = new PSwing(diagnosticsButton);
- pSwing.translate(140, 80);
- pSwingCanvas.getLayer().addChild(pSwing);
- JButton offEmissionButton = new JButton("Выключение радиоизлучения всех ББПИ");
- offEmissionButton.setEnabled(false);
- diagnosticsButton.addActionListener(new ActionListener() {
- public void actionPerformed(final ActionEvent e) {
- //test();
- }
- });
- pSwing = new PSwing(offEmissionButton);
- pSwing.translate(280, 80);
- pSwingCanvas.getLayer().addChild(pSwing);
- JButton reInitProgramm = new JButton("Перезагрузка приложения");
- reInitProgramm.addActionListener(new ActionListener() {
- public void actionPerformed(final ActionEvent e) {
- try {
- Launcher.restartApp();
- } catch (IOException ex) {
- Logger.getLogger(MainFrame.class.getName()).log(Level.SEVERE, null, ex);
- }
- }
- });
- pSwing = new PSwing(reInitProgramm);
- pSwing.translate(620, 80);
- pSwingCanvas.getLayer().addChild(pSwing);
- JButton rebootOS = new JButton("Перезагрузка ОС");
- rebootOS.addActionListener(new ActionListener() {
- public void actionPerformed(final ActionEvent e) {
- Object[] options = { "Yes", "No" };
- int n = JOptionPane.showOptionDialog(new JFrame(),
- "Операционная система будет перезагружена!", "",
- JOptionPane.YES_NO_OPTION, JOptionPane.QUESTION_MESSAGE, null,
- options, options[1]);
- if(n == JOptionPane.OK_OPTION){ // Afirmative
- try {
- logger.log(Level.SEVERE,"************************ OS is restarting ************************");
- AppRunner.runShellScript("echo \"r\" | sudo -S | reboot");
- } catch (IOException e1) {
- e1.printStackTrace();
- }
- }
- // if(n == JOptionPane.NO_OPTION){ // negative
- // //....
- // }
- // if(n == JOptionPane.CLOSED_OPTION){ // closed the dialog
- // //....
- // }
- }
- });
- pSwing = new PSwing(rebootOS);
- pSwing.translate(650, 120);
- pSwingCanvas.getLayer().addChild(pSwing);
- JButton wiButton = new JButton("Открыть web интерфейс КТД");
- wiButton.setEnabled(true);
- wiButton.addActionListener(new ActionListener() {
- public void actionPerformed(final ActionEvent e) {
- // Actual for Windows:
- // try {
- // AppRunner.webInterfaceOpener("http://10.168.2.50/login.php");
- //
- // } catch (URISyntaxException ex) {
- // Logger.getLogger(MainFrame.class.getName()).log(Level.SEVERE, null, ex);
- // }
- // For linux with firefox browser
- loginToPage();
- // String[] commands = {"firefox", "http://10.168.2.50/login.php"};
- // try {
- // Runtime.getRuntime().exec(commands);
- // } catch (IOException e1) {
- // e1.printStackTrace();
- // }
- }
- });
- pSwing = new PSwing(wiButton);
- pSwing.translate(860, 80);
- pSwingCanvas.getLayer().addChild(pSwing);
- JButton appLogbutton = new JButton("Открыть лог приложения");
- appLogbutton.setEnabled(true);
- appLogbutton.addActionListener(new ActionListener() {
- public void actionPerformed(final ActionEvent e) {
- //AppRunner.open("./BSORI_Net_UI_Interface_Application_Log.htm");
- String[] commands = {"firefox", "./log/BSORI_Net_UI_Interface_Application_Log.htm"};
- try {
- Runtime.getRuntime().exec(commands);
- } catch (IOException e1) {
- e1.printStackTrace();
- }
- }
- });
- pSwing = new PSwing(appLogbutton);
- pSwing.translate(1115, 80);
- pSwingCanvas.getLayer().addChild(pSwing);
- JButton astButton = new JButton("Открыть Asterisk в терминале");
- astButton.setEnabled(true);
- astButton.addActionListener(new ActionListener() {
- public void actionPerformed(final ActionEvent e) {
- // try {
- // AppRunner.runShellScript("echo \"r\" | sudo -S | asterisk -rvvvcd");
- //
- // } catch (IOException e1) {
- // e1.printStackTrace();
- // }
- try {
- String[] commands = {"fly-term", "-e", "asterisk", "-rvvvcd"};
- Runtime.getRuntime().exec(commands);
- } catch (IOException e1) {
- e1.printStackTrace();
- }
- }
- });
- pSwing = new PSwing(astButton);
- pSwing.translate(1345, 80);
- pSwingCanvas.getLayer().addChild(pSwing);
- JButton termButton = new JButton("Открыть терминал");
- termButton.setEnabled(true);
- termButton.addActionListener(new ActionListener() {
- public void actionPerformed(final ActionEvent e) {
- // try {
- // AppRunner.runShellScript("echo \"r\" | sudo -S | asterisk -rvvvcd");
- //
- // } catch (IOException e1) {
- // e1.printStackTrace();
- // }
- try {
- Runtime.getRuntime().exec("fly-term");
- } catch (IOException e1) {
- e1.printStackTrace();
- }
- }
- });
- pSwing = new PSwing(termButton);
- pSwing.translate(1395, 120);
- pSwingCanvas.getLayer().addChild(pSwing);
- JButton manButton = new JButton("Открыть руководство");
- manButton.setEnabled(true);
- manButton.addActionListener(new ActionListener() {
- public void actionPerformed(final ActionEvent e) {
- JOptionPane.showMessageDialog(null, "Открыть руководство:"
- + "\nРуководство оператору МПТ\n"
- + "Руководство по эксплуатации и инструкция по назначению МДА БСОРИ");
- }
- });
- pSwing = new PSwing(manButton);
- pSwing.translate(1610, 80);
- pSwingCanvas.getLayer().addChild(pSwing);
- //pSwing.repaint ();
- return pSwingCanvas ;
- }
- private PSwingCanvas createStatTable(PSwingCanvas pSwingCanvas) throws IOException {
- statTable = new JTable();
- // Code for sorting table cells
- // statTable.setAutoCreateRowSorter(true);
- // TableRowSorter<TableModel> sorter = new TableRowSorter<TableModel>(statTable.getModel());
- // statTable.setRowSorter(sorter);
- // setTableData();
- // statTable.setPreferredScrollableViewportSize(statTable.getPreferredSize());
- // statTable.setFillsViewportHeight(true);
- // statTable.scrollRectToVisible(statTable.getCellRect(statTable.getRowCount()-1, 0, true));
- JScrollPane pane = new JScrollPane(statTable);
- pane.setPreferredSize(new Dimension(850, 650));
- statTable.setDoubleBuffered(false);
- //statTable.setAutoCreateRowSorter(true);
- statTitle = new PText("Общая статистика БСОРИ:");
- statTitle.setFont(new java.awt.Font("SansSerif", 3, 20));
- statTitle.translate(250, 20);
- pSwingCanvas.getLayer().addChild(statTitle);
- PSwing pSwing = new PSwing(pane);
- pSwing.translate(20, 50);
- pSwingCanvas.getLayer().addChild(pSwing);
- //pSwing.repaint();
- return pSwingCanvas;
- }
- private void setTableData() throws IOException {
- Properties p = new Properties();
- p.load(new InputStreamReader(new FileInputStream("./placement.properties"), "UTF-8"));
- final Vector<String> columns = new Vector<String>();
- columns.add("ID");
- columns.add("Наименование");
- columns.add("IP address");
- columns.add("Расположение");//columns.add("Серийный номер");
- columns.add("Состояние");
- columns.add("Время работы");
- Vector<Vector> rows = new Vector<Vector>();
- for (IDevice device : data.getAllDevices()) {
- Vector row = new Vector();
- row.add(device.getId());
- row.add(device.getName());
- row.add(device.getIpAddress());
- row.add(p.getProperty(device.getName()));
- row.add(device.getState());
- row.add(device.getSysUpTime());
- rows.add(row);
- }
- statTable.setModel(new DefaultTableModel(rows, columns) {
- Class[] types = {
- Integer.class,
- String.class,
- String.class,
- String.class,
- Integer.class,
- String.class
- };
- @Override
- public Class getColumnClass(int columnIndex) {
- return this.types[columnIndex];
- }
- });
- // set cell render for 'state' column
- statTable.getColumnModel().getColumn(4).setCellRenderer(
- new DefaultTableCellRenderer() {
- protected void setValue(Object value) {
- if (value == null) {
- setText("");
- } else {
- DeviceState deviceState = (DeviceState) value;
- if (deviceState == DeviceState.ON) {
- setText("ВКЛ.");
- setBackground(Color.green);
- } else if (deviceState == DeviceState.OFF) {
- setText("ВЫКЛ.");
- setBackground(Color.RED);
- } else if (deviceState == DeviceState.BROKEN) {
- setText("НЕ РАБОТАЕТ");
- setBackground(Color.RED);
- }
- }
- }
- }
- );
- // set cell render for 'active time' column
- statTable.getColumnModel().getColumn(5).setCellRenderer(
- new DefaultTableCellRenderer() {
- protected void setValue(Object value) {
- setText(
- (value == null)
- ? ""
- : String.valueOf(value)
- );
- }
- }
- );
- statTable.getSelectionModel().addListSelectionListener(new ListSelectionListener() {
- @Override
- public void valueChanged(ListSelectionEvent e) {
- if (!e.getValueIsAdjusting()) {
- int selectedRow = statTable.getSelectedRow();
- if (selectedRow != -1) {
- selectedRow = statTable.convertRowIndexToModel(selectedRow);
- Integer deviceId = (Integer) statTable.getModel().getValueAt(selectedRow, 0);
- IDevice device = data.findDeviceById(deviceId);
- selectDeviceNode(device.getDeviceImage());
- }
- }
- }
- });
- statTable.setAutoCreateRowSorter(true);
- statTable.setAutoResizeMode(JTable.AUTO_RESIZE_OFF);
- statTable.setRowHeight(30);
- TableColumn c = statTable.getColumn(statTable.getColumnName(0));
- c.setPreferredWidth(30);
- c = statTable.getColumn(statTable.getColumnName(1));
- c.setPreferredWidth(80);
- c = statTable.getColumn(statTable.getColumnName(2));
- c.setPreferredWidth(100);
- c = statTable.getColumn(statTable.getColumnName(3));
- c.setPreferredWidth(380);
- c = statTable.getColumn(statTable.getColumnName(4));
- c.setPreferredWidth(100);
- c = statTable.getColumn(statTable.getColumnName(5));
- c.setPreferredWidth(150);
- }
- /**
- * Creates a tooltip
- */
- private void createToolTip(PSwingCanvas pSwingCanvas) {
- final PCamera camera = pSwingCanvas.getCamera();
- tooltipNode = new PText();
- tooltipNode.setPaint(new Color(255, 252, 209));
- tooltipNode.setPickable(false);
- camera.addChild(tooltipNode);
- camera.addInputEventListener(new PBasicInputEventHandler() {
- public void mouseMoved(final PInputEvent event) {
- try {
- updateToolTip(event);
- } catch (IOException ex) {
- Logger.getLogger(MainFrame.class.getName()).log(Level.SEVERE, null, ex);
- }
- }
- public void mouseDragged(final PInputEvent event) {
- try {
- updateToolTip(event);
- } catch (IOException ex) {
- Logger.getLogger(MainFrame.class.getName()).log(Level.SEVERE, null, ex);
- }
- }
- public void updateToolTip(final PInputEvent event) throws IOException {
- Properties p1 = new Properties();
- p1.load(new InputStreamReader(new FileInputStream("./placement.properties"), "UTF-8"));
- PNode node = event.getPickedNode();
- if (!(node instanceof PDeviceImage)) {
- tooltipNode.setVisible(false);
- return;
- }
- IDevice device = ((PDeviceImage) node).getDevice();
- if (device == null) {
- return;
- }
- tooltipNode.setVisible(true);
- String tooltipString = String.format(
- "Device name: %s%n"
- + "Device IP address: %s%n"
- + "Device state: %s%n"
- + "Device uptime: %s%n"
- + "Room: %s%n",
- device.getName(),
- device.getIpAddress(),
- device.getState(),
- device.getSysUpTime(),
- p1.getProperty(device.getName())
- );
- Point2D p = event.getCanvasPosition();
- event.getPath().canvasToLocal(p, camera);
- tooltipNode.setText(tooltipString);
- tooltipNode.setOffset(p.getX() + 8, p.getY() - 8);
- }
- });
- }
- private void drawEdgesFromDeviceToChildren(IDevice device) {
- if (device.getChildren() != null) {
- for (IDevice child : device.getChildren()) {
- drawEdgesFromParentToChild(device, child);
- }
- }
- }
- private void drawEdgesFromParentToChild(IDevice parent, IDevice child) {
- if (parent == null || child == null) {
- return;
- }
- PDeviceImage parentDeviceImage = parent.getDeviceImage();
- PDeviceImage childDeviceImage = child.getDeviceImage();
- Point2D.Double parentBounds;
- Point2D.Double childBounds;
- PPath edge = childDeviceImage.getEdge();
- if (edge != null) {
- edge.reset();
- parentBounds = (Point2D.Double) parentDeviceImage.getFullBounds().getCenter2D();
- childBounds = (Point2D.Double) childDeviceImage.getFullBounds().getCenter2D();
- } else {
- parentBounds = (Point2D.Double) parentDeviceImage.getBounds().getCenter2D();
- childBounds = (Point2D.Double) childDeviceImage.getBounds().getCenter2D();
- edge = new PPath();
- childDeviceImage.setEdge(edge);
- edgeLayer.addChild(edge);
- }
- edge.moveTo((float) parentBounds.getX(), (float) parentBounds.getY());
- int offset = 0;
- // draw legs for access points
- if (parentBounds.getY() < childBounds.getY()) {
- offset = VERTICAL_LEG_BOTTOM;
- } else {
- offset = VERTICAL_LEG_TOP;
- }
- edge.lineTo((float) childBounds.getX(), (float) childBounds.getY() + offset);
- edge.lineTo((float) childBounds.getX(), (float) childBounds.getY());
- }
- private PSwingCanvas buildStatTableCanvas(String canvasName) throws IOException {
- PSwingCanvas canvas = new PSwingCanvas();
- canvas.getLayer().addChild(new PSwing(new JLabel(canvasName)));
- canvas.setPanEventHandler(null);
- return createStatTable(canvas);
- }
- private void showInitDialog(int timeActiveInMillis) { // Показывает диалог на время инициализации
- if(timeActiveInMillis < 0 | timeActiveInMillis > 150000 ) timeActiveInMillis = 120000;
- class UserDefTimerTask extends TimerTask{
- public JFrame jf;
- public UserDefTimerTask(JFrame jf){
- this.jf = jf;
- }
- @Override
- public void run() {
- if(jf.isShowing()){
- jf.setVisible(false);
- jf.dispose();
- }
- }
- }
- JFrame initDialog = new JFrame("Инициализация");
- initDialog.getContentPane().setBackground(Color.lightGray);
- initDialog.setBounds(300, 400, 280, 50);
- initDialog.add(new JLabel("Подождите, идет инициализация приложения... "));
- initDialog.setDefaultCloseOperation(JFrame.DO_NOTHING_ON_CLOSE);
- initDialog.setAlwaysOnTop(true);
- initDialog.setUndecorated(true);
- initDialog.setVisible(true);
- UserDefTimerTask t = new UserDefTimerTask(initDialog);
- Timer timer = new Timer();
- timer.schedule(t, timeActiveInMillis);
- }
- class CanvasInputHandler extends PBasicInputEventHandler {
- public void mouseReleased(final PInputEvent e) {
- if (!(e.getPickedNode() instanceof PDeviceImage)) {
- if (e.isRightMouseButton()) {
- e.setHandled(true);
- Point2D ePos = e.getCanvasPosition();
- //ServiceRightClickMenu menu = new ServiceRightClickMenu();
- //menu.show(getCanvas(), (int) ePos.getX(), (int) ePos.getY());
- }
- }
- }
- }
- class NodeDragHandler extends PDragSequenceEventHandler {
- public NodeDragHandler() {
- //getEventFilter().setMarksAcceptedEventsAsHandled(true);
- }
- public void mouseEntered(final PInputEvent e) {
- }
- public void mouseExited(final PInputEvent e) {
- if (e.getButton() == 0) {
- //e.getPickedNode().setPaint(Color.white);
- }
- }
- public void mousePressed(final PInputEvent event) {
- super.mousePressed(event);
- setIsDragging(false);
- }
- public void mouseReleased(final PInputEvent e) {
- if (isDragging()) {
- endDrag(e);
- } else {
- if (!(e.getPickedNode() instanceof PDeviceImage)) {
- return;
- }
- PDeviceImage pickedNode = (PDeviceImage) e.getPickedNode();
- doZoomInOut(pickedNode);
- selectDevice(pickedNode);
- // Вызов всплывающего меню через правую кнопку мыши
- // if (e.isRightMouseButton()) {
- // e.setHandled(true);
- // Point2D ePos = e.getCanvasPosition();
- // DeviceRightClickMenu menu = new DeviceRightClickMenu();
- // menu.show(getCanvas(), (int) ePos.getX(), (int) ePos.getY());
- // }
- // Вызов всплывающего меню через двойной клик мыши мыши - адаптировано для планшетного режима
- if (e.getClickCount() == 1) {
- e.setHandled(true);
- Point2D ePos = e.getCanvasPosition();
- DeviceRightClickMenu menu = new DeviceRightClickMenu();
- menu.show(getCanvas(), (int) ePos.getX(), (int) ePos.getY());
- }
- }
- }
- // 12.05.14 13:30 #F256 : Prohibit dragging devices
- // public void drag(final PInputEvent e) {
- // super.drag(e);
- //
- // if (!(e.getPickedNode() instanceof PDeviceImage)) {
- // return;
- // }
- //
- // PDeviceImage deviceImage = (PDeviceImage) e.getPickedNode();
- // deviceImage.translate(e.getDelta().width, e.getDelta().height);
- //
- // IDevice device = deviceImage.getDevice();
- // // draw edges from this device's parent to this device
- // drawEdgesFromParentToChild(device.getParent(), device);
- //
- // // draw edges from node to its children
- // drawEdgesFromDeviceToChildren(device);
- // }
- }
- private void selectDeviceNode(PDeviceImage newDevice) {
- // reset previous selection
- if (selectedDevice != null) {
- selectedDevice.getDeviceImage().getDeviceName().setPaint(Color.white);
- }
- selectedDevice = newDevice.getDevice();
- selectedDevice.getDeviceImage().getDeviceName().setPaint(Color.orange);
- }
- private void selectDevice(PDeviceImage pickedNode) {
- selectDeviceNode(pickedNode);
- int selectedRow = returnRowIndexForValue(selectedDevice.getId(), 0, statTable);
- statTable.setRowSelectionInterval(selectedRow, selectedRow);
- Rectangle rect = statTable.getCellRect(selectedRow, 1, true);
- statTable.scrollRectToVisible(rect);
- }
- private int returnRowIndexForValue(Object value, int columnNumber, JTable table) {
- for (int i = 0; i < table.getRowCount(); i++) {
- if (table.getValueAt(i, columnNumber).equals(value)) {
- return i;
- }
- }
- return -1;
- }
- private void doZoomInOut(PDeviceImage deviceImage) {
- if (!autoZoom) {
- return;
- }
- PActivity panActivity = animateViewToCenterBounds(getCanvas().getCamera(), deviceImage.getFullBounds(), 2, 500);
- panActivity.setStartTime(new Date().getTime());
- }
- public PTransformActivity animateViewToCenterBounds(PCamera camera, final Rectangle2D centerBounds, double scale,
- final long duration) {
- final PBounds viewBounds = camera.getViewBounds();
- final PDimension delta = viewBounds.deltaRequiredToCenter(centerBounds);
- final PAffineTransform newTransform = camera.getViewTransform();
- newTransform.translate(delta.width, delta.height);
- if (scale != Double.POSITIVE_INFINITY && scale != 0) {
- newTransform.scaleAboutPoint(scale, centerBounds.getCenterX(), centerBounds.getCenterY());
- }
- return camera.animateViewToTransform(newTransform, duration);
- }
- /**
- * @return the data
- */
- public MainData getData() {
- return data;
- }
- /**
- * @param data the data to set
- */
- public void setData(MainData data) {
- this.data = data;
- }
- public PText getStatTitle() {
- return statTitle;
- }
- public void setStatTitle(PText statTitle) {
- this.statTitle = statTitle;
- }
- class DeviceRightClickMenu extends JPopupMenu {
- public DeviceRightClickMenu() {
- JMenuItem restartItem = new JMenuItem("Перезагрузить устройство");
- restartItem.setEnabled(false);
- restartItem.addActionListener(new ActionListener() {
- @Override
- public void actionPerformed(ActionEvent e) {
- }
- });
- add(restartItem);
- JMenu setEmission = new JMenu ("Установить мощность излучения ББПИ");
- setEmission.setEnabled(true);
- setEmission.addActionListener(new ActionListener() {
- @Override
- public void actionPerformed(ActionEvent e) {
- }
- });
- JMenuItem setEmissionMin = new JMenuItem ("Min");
- setEmissionMin.addActionListener(new ActionListener() {
- @Override
- public void actionPerformed(ActionEvent ae) {
- JOptionPane.showMessageDialog(MainFrame.this,"Для того, чтобы установить минимальную мощность излучения ББПИ"
- + "\nПерейдите в web интерфейс КТД в раздел"
- + "\n\"Configuration\" - \"Wireless\" - \"Basic\" - \"RF Management\""
- + "\nВыберите значение \"Default Tx Power\" = \"Minimum\"");
- // Код ответа операции set txPower
- }
- });
- JMenuItem setEmissionEighth = new JMenuItem ("Eighth");
- setEmissionEighth.addActionListener(new ActionListener() {
- @Override
- public void actionPerformed(ActionEvent ae) {
- JOptionPane.showMessageDialog(MainFrame.this, "Для того, чтобы установить одну восьмую значения мощности излучения ББПИ"
- + "\nПерейдите в web интерфейс КТД в раздел"
- + "\n\"Configuration\" - \"Wireless\" - \"Basic\" - \"RF Management\""
- + "\nВыберите значение \"Default Tx Power\" = \"Eighth\"");
- // Код ответа операции set txPower
- }
- });
- JMenuItem setEmissionQuarter = new JMenuItem ("Quarter");
- setEmissionQuarter.addActionListener(new ActionListener() {
- @Override
- public void actionPerformed(ActionEvent ae) {
- JOptionPane.showMessageDialog(MainFrame.this, "Для того, чтобы установить значение четверти мощности излучения ББПИ"
- + "\nПерейдите в web интерфейс КТД в раздел"
- + "\n\"Configuration\" - \"Wireless\" - \"Basic\" - \"RF Management\""
- + "\nВыберите значение \"Default Tx Power\" = \"Quarter\"");
- // Код ответа операции set txPower
- }
- });
- JMenuItem setEmissionHalf = new JMenuItem ("Half");
- setEmissionHalf.addActionListener(new ActionListener() {
- @Override
- public void actionPerformed(ActionEvent ae) {
- JOptionPane.showMessageDialog(MainFrame.this, "Для того, чтобы установить значение половины мощности излучения ББПИ"
- + "\nПерейдите в web интерфейс КТД в раздел"
- + "\n\"Configuration\" - \"Wireless\" - \"Basic\" - \"RF Management\""
- + "\nВыберите значение \"Default Tx Power\" = \"Half\"");
- // Код ответа операции set txPower
- }
- });
- JMenuItem setEmissionMax = new JMenuItem ("Full");
- setEmissionMax.addActionListener(new ActionListener() {
- @Override
- public void actionPerformed(ActionEvent ae) {
- JOptionPane.showMessageDialog(MainFrame.this, "Для того, чтобы установить значение полную мощность излучения ББПИ"
- + "\nПерейдите в web интерфейс КТД в раздел"
- + "\n\"Configuration\" - \"Wireless\" - \"Basic\" - \"RF Management\""
- + "\nВыберите значение \"Default Tx Power\" = \"Full\"");
- // Код ответа операции set txPower
- // Код ответа операции set txPower
- }
- });
- setEmission.add(setEmissionMin);
- setEmission.add(setEmissionEighth);
- setEmission.add(setEmissionQuarter);
- setEmission.add(setEmissionHalf);
- setEmission.add(setEmissionMax);
- if(selectedDevice instanceof AccessPoint){
- add(setEmission);
- }
- JMenuItem statisticsItem = new JMenuItem("Статистика");
- statisticsItem.setEnabled(false);
- statisticsItem.addActionListener(new ActionListener() {
- @Override
- public void actionPerformed(ActionEvent e) {
- //showDeviceStatistics(device);
- }
- });
- add(statisticsItem);
- JMenuItem pingItem = new JMenuItem("Выполнить команду ping");
- pingItem.setEnabled(true);
- pingItem.addActionListener(new ActionListener() {
- @Override
- public void actionPerformed(ActionEvent e) {
- try {
- String[] commands = {"fly-term", "-e", "ping", selectedDevice.getIpAddress()};
- Runtime.getRuntime().exec(commands);
- } catch (IOException e1) {
- e1.printStackTrace();
- }
- }
- });
- add(pingItem);
- final JMenuItem wiItem = new JMenuItem("Открыть web интерфейс устройства");
- wiItem.setEnabled(true);
- wiItem.addActionListener(new ActionListener() {
- @Override
- public void actionPerformed(ActionEvent e) {
- try {
- String[] commands = {"firefox", "http://"+selectedDevice.getIpAddress()};
- Runtime.getRuntime().exec(commands);
- } catch (IOException e1) {
- e1.printStackTrace();
- }
- }
- });
- if(!(selectedDevice instanceof PhoneServer)) {
- add(wiItem);
- }
- }
- }
- private void redrawEdgesRecursively(IDevice device) {
- //device.determineEdgeStyleFromState();
- device.determineEdgeStyleFromPing();
- if (device.getChildren() != null) {
- for (IDevice childDevice : device.getChildren()) {
- redrawEdgesRecursively(childDevice);
- }
- }
- }
- // private void createNewBskp() {
- // IDevice bskp = data.createNewBskp();
- // if (bskp == null) {
- // return;
- // }
- // PDeviceImage deviceImage = new PDeviceImage(bskp);
- // nodeLayer.addChild(deviceImage);
- //
- // drawEdgesFromParentToChild(bskp.getParent(), bskp);
- // setTableData();
- // selectDevice(deviceImage);
- // }
- private void createRandomNodeStateActivity() {
- changeRandomNodeStateActivity = new PActivity(-1, 1000) {
- protected void activityStep(long time) {
- super.activityStep(time);
- for (int i = 0; i < 20; i++) {
- int randomDeviceIndex = randInt(0, data.getAllDevices().size() - 1);
- IDevice randomDevice = new ArrayList<IDevice>(
- data.getAllDevices()).get(randomDeviceIndex);
- int randomStateIndex = new Random().nextInt(DeviceState.values().length);
- randomDevice.setState(DeviceState.values()[randomStateIndex]);
- selectDevice(randomDevice.getDeviceImage());
- }
- try {
- setTableData();
- } catch (IOException ex) {
- Logger.getLogger(MainFrame.class.getName()).log(Level.SEVERE, null, ex);
- }
- }
- };
- nodeLayer.addActivity(changeRandomNodeStateActivity);
- }
- private void stopActivity() {
- if (changeRandomNodeStateActivity != null) {
- changeRandomNodeStateActivity.terminate();
- }
- }
- private void deleteDevice(IDevice device) throws IOException {
- // disconnect device from its parent
- if (device.getParent() != null) {
- device.getParent().getChildren().remove(device);
- }
- // disconnect device from its children
- if (device.getChildren() != null) {
- for (IDevice child : device.getChildren()) {
- child.setParent(null);
- edgeLayer.removeChild(child.getDeviceImage().getEdge());
- child.getDeviceImage().setEdge(null);
- }
- }
- // delete image
- nodeLayer.removeChild(device.getDeviceImage());
- // delete parent edge
- edgeLayer.removeChild(device.getDeviceImage().getEdge());
- device.getDeviceImage().setEdge(null);
- data.getDevicesMap().remove(device.getId());
- setTableData();
- selectDevice(data.getAllDevices().iterator().next().getDeviceImage());
- }
- /**
- * Returns a pseudo-random number between min and max, inclusive. The
- * difference between min and max can be at most
- * <code>Integer.MAX_VALUE - 1</code>.
- *
- * @para m min Minimim value
- * @param max Maximim value. Must be greater than min.
- * @return Integer between min and max, inclusive.
- * @see java.util.Random#nextInt(int)
- */
- public static int randInt(int min, int max) {
- // Usually this can be a field rather than a method variable
- Random rand = new Random();
- // nextInt is normally exclusive of the top value,
- // so add 1 to make it inclusive
- int randomNum = rand.nextInt((max - min) + 1) + min;
- return randomNum;
- }
- private void createMenu() {
- // create menu bar
- JMenuBar menuBar = new JMenuBar();
- setJMenuBar(menuBar);
- JMenu menuSettings = new JMenu("Settings");
- menuBar.add(menuSettings);
- JMenuItem menuItemTest = new JMenuItem("Test");
- menuSettings.add(menuItemTest);
- menuItemTest.addActionListener(new ActionListener() {
- @Override
- public void actionPerformed(ActionEvent e) {
- System.out.println("test");
- }
- });
- JMenu menuAbout = new JMenu("Help");
- menuBar.add(menuAbout);
- JMenuItem menuItemAbout = new JMenuItem("About");
- menuItemAbout.addActionListener(new ActionListener() {
- @Override
- public void actionPerformed(ActionEvent e) {
- JOptionPane.showMessageDialog(MainFrame.this,
- " Управление сетевой инфраструктурой изделия МДА БСОРИ (alpha версия 1.0.3 )\n\n"
- + "Отправляет запросы и получает ответы по протоколу SNMP версии 2 \n"
- + "на коммутаторы(БСК, БСКП), сервер(БУВО), точки доступа(ББПИ)\n"
- + "и выводит результаты на графический интерфейс пользователя\n"
- + "Красный цвет устройств - БУВО не получает ответ от опрашиваемых устройств \n"
- + "Зеленый цвет устройств - БУВО получает ответ от опрашиваемых устройств \n"
- + "Щелчок правой кнопкой мыши на устройстве - позволяет манипулировать устройством: выключить, перезагрузить (В стадии теста), собрать статистику \n"
- );
- }
- });
- menuAbout.add(menuItemAbout);
- }
- /**
- * Zoom handler with restrictions for max and min zoom scale.
- *
- * @author
- *
- */
- static class CustomZoomHandler extends PZoomEventHandler {
- /**
- * A constant used to adjust how sensitive the zooming will be to mouse
- * movement. The larger the number, the more each delta pixel will
- * affect zooming.
- */
- private static final double ZOOM_SENSITIVITY = 0.001;
- private double minScale = 0.5;
- private double maxScale = 5;
- private Point2D viewZoomPoint;
- /**
- * Records the start point of the zoom. Used when calculating the delta
- * for zoom speed.
- *
- * @param event event responsible for starting the zoom interaction
- */
- protected void dragActivityFirstStep(final PInputEvent event) {
- viewZoomPoint = event.getPosition();
- }
- protected void dragActivityStep(final PInputEvent event) {
- final PCamera camera = event.getCamera();
- final double dx = event.getCanvasPosition().getX() - getMousePressedCanvasPoint().getX();
- double scaleDelta = 1.0 + ZOOM_SENSITIVITY * dx;
- final double currentScale = camera.getViewScale();
- final double newScale = currentScale * scaleDelta;
- if (newScale < minScale) {
- scaleDelta = minScale / currentScale;
- }
- if (maxScale > 0 && newScale > maxScale) {
- scaleDelta = maxScale / currentScale;
- }
- camera.scaleViewAboutPoint(scaleDelta, viewZoomPoint.getX(), viewZoomPoint.getY());
- }
- }
- /**
- * Opens a web page using Firefox browser,
- * enters login name/password and tries to login.
- */
- private void loginToPage() {
- String username = "admin";
- String password = "Marine2Air";
- // Create a new instance of the Firefox driver
- // Notice that the remainder of the code relies on the interface,
- // not the implementation.
- WebDriver driver = new FirefoxDriver();
- // And now use this to visit Google
- driver.get("http://10.168.2.50/login.php");
- WebElement userNameElement = driver.findElement(By.id("user_name"));
- // Enter user name
- userNameElement.sendKeys(username);
- // Find the 'password' text input element by its name attribute 'j_password'
- WebElement passwordElement = driver.findElement(By.id("password"));
- // Enter password
- passwordElement.sendKeys(password);
- //Click LOGIN button
- driver.findElement(By.className("enablebuttonstyle")).click();
- }
- private void managedAPList() throws InterruptedException {
- boolean acceptNextAlert = true;
- String username = "admin";
- String password = "Marine2Air";
- // Create a new instance of the Firefox driver
- // Notice that the remainder of the code relies on the interface,
- // not the implementation.
- WebDriver driver = new FirefoxDriver();
- // And now use this to visit Google
- driver.get("http://10.168.2.50/login.php");
- driver.findElement(By.id("user_name")).clear();
- driver.findElement(By.id("user_name")).sendKeys("admin");
- driver.findElement(By.id("password")).clear();
- driver.findElement(By.id("password")).sendKeys("Marine2Air");
- driver.findElement(By.className("enablebuttonstyle")).click();
- try {
- Alert alert = driver.switchTo().alert();
- String alertText = alert.getText();
- if (acceptNextAlert) {
- alert.accept();
- } else {
- alert.dismiss();
- }
- alertText = alert.getText();
- } finally {
- acceptNextAlert = true;
- }
- //driver.findElement(By.cssSelector("input.enablebuttonstyle")).click();
- driver.findElement(By.linkText("Access Point")).click();
- driver.findElement(By.cssSelector("#TD_Main_2 > a.TertiaryNav > strong")).click();
- // ERROR: Caught exception [Error: locator strategy either id or name must be specified explicitly.]
- driver.findElement(By.id("ManagedAccessPoint-status")).click();
- driver.findElement(By.id("ManagedAccessPoint-status")).click();
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement