📄 scriptrunner.java
字号:
/* * Copyright (c) 2008, Swedish Institute of Computer Science. * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * 3. Neither the name of the Institute nor the names of its contributors * may be used to endorse or promote products derived from this software * without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIABLE * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF * SUCH DAMAGE. * * $Id: ScriptRunner.java,v 1.7 2008/11/05 18:17:45 fros4943 Exp $ */package se.sics.cooja.plugins;import java.awt.BorderLayout;import java.awt.Insets;import java.awt.Window;import java.awt.event.ActionEvent;import java.awt.event.ActionListener;import java.io.BufferedReader;import java.io.BufferedWriter;import java.io.File;import java.io.FileInputStream;import java.io.FileNotFoundException;import java.io.FileOutputStream;import java.io.IOException;import java.io.InputStreamReader;import java.io.OutputStreamWriter;import java.io.PrintStream;import java.io.StringReader;import java.util.*;import java.util.regex.Matcher;import java.util.regex.Pattern;import javax.swing.*;import org.apache.log4j.Logger;import org.jdom.Document;import org.jdom.Element;import org.jdom.JDOMException;import org.jdom.input.SAXBuilder;import org.jdom.output.Format;import org.jdom.output.XMLOutputter;import se.sics.cooja.*;import se.sics.cooja.dialogs.MessageList;@ClassDescription("Test Script Editor")@PluginType(PluginType.COOJA_PLUGIN)public class ScriptRunner extends VisPlugin { private static final long serialVersionUID = 1L; private static Logger logger = Logger.getLogger(ScriptRunner.class); private JTextArea scriptTextArea; private JTextArea logTextArea; private GUI gui; private LogScriptEngine scriptTester = null; private JButton toggleButton; private String oldTestName = null; private String oldInfo = null; private static String exampleScript = "/* Script is run for each mote log output, for example printf()'s */\n" + "/* Input variables: Mote mote, int id, String msg, Hashtable global */\n" + "\n" + "log.log('MOTE=' + mote + '\\n');\n" + "log.log('ID=' + id + '\\n');\n" + "log.log('TIME=' + mote.getSimulation().getSimulationTime() + '\\n');\n" + "log.log('MSG=' + msg + '\\n');\n" + "\n" + "/* Hashtable global may be used to store state across script invokes */\n" + "log.log('LAST MSG=' + global.get('lastMsg') + '\\n');\n" + "global.put('lastMsg', msg);\n" + "\n" + "/* Contiki test script example */\n" + "if (msg.startsWith('Hello, world')) {\n" + " log.testOK(); /* Report test success and quit */\n" + "} else {\n" + " log.testFailed(); /* Report test failed and quit */\n" + "}\n" + "\n" + "//mote.getSimulation().getGUI().reloadCurrentSimulation(true); /* Reload simulation */\n"; public ScriptRunner(GUI gui) { super("Test Script Editor", gui); this.gui = gui; scriptTextArea = new JTextArea(8,50); scriptTextArea.setMargin(new Insets(5,5,5,5)); scriptTextArea.setEditable(true); scriptTextArea.setCursor(null); scriptTextArea.setText(exampleScript); logTextArea = new JTextArea(8,50); logTextArea.setMargin(new Insets(5,5,5,5)); logTextArea.setEditable(true); logTextArea.setCursor(null); toggleButton = new JButton("Activate"); toggleButton.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent ev) { if (toggleButton.getText().equals("Activate")) { scriptTester = new LogScriptEngine(ScriptRunner.this.gui, scriptTextArea.getText()); scriptTester.setScriptLogObserver(new Observer() { public void update(Observable obs, Object obj) { logTextArea.append((String) obj); logTextArea.setCaretPosition(logTextArea.getText().length()); } }); scriptTester.activateScript(); toggleButton.setText("Deactivate"); scriptTextArea.setEnabled(false); } else { if (scriptTester != null) { scriptTester.deactiveScript(); scriptTester = null; } toggleButton.setText("Activate"); scriptTextArea.setEnabled(true); } } }); JButton importButton = new JButton("Import Contiki test"); importButton.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent ev) { Runnable doImport = new Runnable() { public void run() { importContikiTest(); } }; new Thread(doImport).start(); } }); JButton exportButton = new JButton("Export as Contiki test"); exportButton.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent ev) { exportAsContikiTest(); } }); JSplitPane centerPanel = new JSplitPane( JSplitPane.VERTICAL_SPLIT, new JScrollPane(scriptTextArea), new JScrollPane(logTextArea) ); centerPanel.setOneTouchExpandable(true); centerPanel.setResizeWeight(0.5); JPanel buttonPanel = new JPanel(new BorderLayout()); buttonPanel.add(BorderLayout.WEST, importButton); buttonPanel.add(BorderLayout.CENTER, toggleButton); buttonPanel.add(BorderLayout.EAST, exportButton); JPanel southPanel = new JPanel(new BorderLayout()); southPanel.add(BorderLayout.EAST, buttonPanel); getContentPane().add(BorderLayout.CENTER, centerPanel); getContentPane().add(BorderLayout.SOUTH, southPanel); pack(); try { setSelected(true); } catch (java.beans.PropertyVetoException e) { // Could not select } } private void importContikiTest() { new Thread(new Runnable() { public void run() { Simulation simulation = ScriptRunner.this.gui.getSimulation(); /* Load config from test directory */ final File proposedDir = new File(GUI.getExternalToolsSetting("PATH_CONTIKI") + "/tools/cooja/contiki_tests"); if (!proposedDir.exists()) { logger.fatal("Test directory does not exist: " + proposedDir.getPath()); return; } scriptTextArea.setText(""); logTextArea.setText(""); gui.doLoadConfig(false, true, proposedDir); Vector<File> history = gui.getFileHistory(); File cscFile = history.firstElement(); String testName = cscFile.getName().substring(0, cscFile.getName().length()-4); File testDir = cscFile.getParentFile(); File jsFile = new File(testDir, testName + ".js"); File infoFile = new File(testDir, testName + ".info"); oldTestName = testName; if (!cscFile.exists()) { logger.fatal("Can't locate config file: " + cscFile.getAbsolutePath()); return; } if (!jsFile.exists()) { logger.fatal("Can't locate .js file: " + jsFile.getAbsolutePath()); return; } /* Import .js */ try { BufferedReader reader = new BufferedReader(new InputStreamReader(new FileInputStream(jsFile))); String line; while ((line = reader.readLine()) != null) { scriptTextArea.append(line + "\n"); } reader.close(); } catch (Exception ex) { ex.printStackTrace(); return; } /* Import .info */ if (infoFile.exists()) { try { oldInfo = ""; BufferedReader reader = new BufferedReader(new InputStreamReader(new FileInputStream(infoFile))); String line; while ((line = reader.readLine()) != null) { oldInfo += line + "\n"; } reader.close(); } catch (Exception ex) { ex.printStackTrace(); return; } } } }).start(); } private void exportAsContikiTest() { Simulation simulation = ScriptRunner.this.gui.getSimulation(); if (simulation == null) { JOptionPane.showMessageDialog(GUI.getTopParentContainer(), "Create a simulation setup to test.", "No simulation to export", JOptionPane.ERROR_MESSAGE); return; } /* Confirm test directory */ File testDir = new File(GUI.getExternalToolsSetting("PATH_CONTIKI") + "/tools/cooja/contiki_tests"); String s1 = "Ok"; String s2 = "Cancel"; Object[] options = { s1, s2 }; int n = JOptionPane.showOptionDialog(GUI.getTopParentContainer(), "The current simulation config (.csc) and test script (.js)\n" + "will be stored in directory '" + testDir.getPath() + "'", "Export Contiki test", JOptionPane.YES_NO_OPTION, JOptionPane.QUESTION_MESSAGE, null, options, s1); if (n != JOptionPane.YES_OPTION) { return; } if (!testDir.exists()) { logger.fatal("Test directory does not exist: " + testDir.getPath()); return; }
⌨️ 快捷键说明
复制代码
Ctrl + C
搜索代码
Ctrl + F
全屏模式
F11
切换主题
Ctrl + Shift + D
显示快捷键
?
增大字号
Ctrl + =
减小字号
Ctrl + -