home *** CD-ROM | disk | FTP | other *** search
/ Tools / WinSN5.0Ver.iso / NETSCAP.50 / WIN1998.ZIP / ns / modules / edtplug / classes / netscape / test / plugin / composer / Test.java < prev    next >
Encoding:
Java Source  |  1998-04-08  |  17.9 KB  |  467 lines

  1. /* -*- Mode: Java; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 2 -*-
  2.  *
  3.  * The contents of this file are subject to the Netscape Public License
  4.  * Version 1.0 (the "NPL"); you may not use this file except in
  5.  * compliance with the NPL.  You may obtain a copy of the NPL at
  6.  * http://www.mozilla.org/NPL/
  7.  *
  8.  * Software distributed under the NPL is distributed on an "AS IS" basis,
  9.  * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the NPL
  10.  * for the specific language governing rights and limitations under the
  11.  * NPL.
  12.  *
  13.  * The Initial Developer of this code under the NPL is Netscape
  14.  * Communications Corporation.  Portions created by Netscape are
  15.  * Copyright (C) 1998 Netscape Communications Corporation.  All Rights
  16.  * Reserved.
  17.  */
  18.  
  19. package netscape.test.plugin.composer;
  20.  
  21. import netscape.plugin.composer.*;
  22. import java.io.*;
  23. import java.util.Properties;
  24. import java.net.*;
  25. import java.util.*;
  26.  
  27. /** The composer plugin testbed. Allows you to test your plugin
  28.  * seperately from the Netscape Composer.
  29.  *
  30.  * <pre>
  31.  *
  32.  * You run Test from the command line by doing this:
  33.  *
  34.  * java -classpath classPath netscape.test.plugin.composer.Test ..args..
  35.  *
  36.  * Where ..args.. are one or more of:
  37.  *
  38.  *  -plugin plugin    Use the named plugin. Defaults to
  39.  *                    netscape.plugin.composer.Plugin
  40.  *  -in file          Use the named file as the input text document.
  41.  *  -out file         Use the named file as the output text document.
  42.  *  -string string    Use the given string as the test document.
  43.  *                    Defaults to a small built-in test document.
  44.  *  -workDir dir      Use the given dir as the work directory.
  45.  *                    Defaults to java's user.dir property.
  46.  *  -eventName event  Simulate an event of the given name.
  47.  * </pre>
  48.  *
  49.  * Normally you don't derive from or instantiate Test. You just run it from the command
  50.  * line. However, for special test purposes, it might make sense to derive from Test and
  51.  * override methods like createDocument and createPlugin.
  52.  */
  53. public class Test {
  54.     /** Hook for plugins to test themselves. If you have a plugin MyPlugin, add this
  55.      * code to it to enable it to be tested in a stand-alone situation.
  56.      * <pre>
  57.      * /** Test the plugin. Not required for normal operation of the plugin.
  58.      *  * You can use this to run the plugin from the command line:
  59.      *  * java -classpath <your-class-path> <your-plugin-name> args...
  60.      *  * where args... are passed on to the Test class.
  61.      *  * You can remove this code before shipping your plugin.
  62.      *  * /
  63.      * static public void main(String[] args) {
  64.      *   Test.perform(args, new MyPlugin());
  65.      * }
  66.      * </pre>
  67.      * Note: This method calls System.exit() at the end of the test.
  68.      *       It does so because otherwise any AWT threads that may have been
  69.      *       started will not be closed down, and as a result, the application will
  70.      *       never finish running.
  71.      * <p>
  72.      * The system exit code will be 0 if the test succeded.
  73.      * 1 if the test failed.
  74.      * -1 if an uncaught exception was thrown.
  75.      */
  76.  
  77.     public static void perform(String[] args, Plugin plugin){
  78.         int status = 0;
  79.         try {
  80.             Test test = new Test(args);
  81.             test.setPlugin(plugin);
  82.             status = test.test();
  83.         } catch (Throwable t) {
  84.             System.err.println("Exception caught while running test.");
  85.             t.printStackTrace();
  86.             status = -1;
  87.         }
  88.         System.exit(status);
  89.     }
  90.  
  91.     /** Public main function. Called from outside. Creates and runs the test.
  92.      * If you derive a new class from Test, you can make your own version of
  93.      * main that looks like this:
  94.      * <pre>
  95.      * public static void main(String[] args){
  96.      *     int status = 0;
  97.      *     try {
  98.      *         MyTest test = new MyTest(args);
  99.      *         status = test.test();
  100.      *     } catch (Throwable t) {
  101.      *         t.printStackTrace();
  102.      *         status = -1;
  103.      *     }
  104.      *     System.exit(status);
  105.      * }
  106.      * </pre>
  107.      */
  108.     public static void main(String[] args){
  109.         int status = 0;
  110.         try {
  111.             Test test = new Test(args);
  112.             status = test.test();
  113.         } catch (Throwable t) {
  114.             t.printStackTrace();
  115.             status = -1;
  116.         }
  117.         System.exit(status);
  118.     }
  119.  
  120.     /** Parses the command-line arguments.
  121.      * @param args The command-line arguments.
  122.      */
  123.  
  124.     protected Test(String[] args){
  125.  
  126.         int length = args.length;
  127.         for(int i = 0; i < length; i++ ){
  128.             String s = args[i];
  129.             if ( s.equalsIgnoreCase("-plugin") ){
  130.                 argCheck(args, i, 1);
  131.                 duplicateCheck(args, i, pluginArg);
  132.                 pluginArg = args[++i];
  133.             }
  134.             else if ( s.equalsIgnoreCase("-in") ){
  135.                 argCheck(args, i, 1);
  136.                 duplicateCheck(args, i, inArg);
  137.                 inArg = args[++i];
  138.             }
  139.             else if ( s.equalsIgnoreCase("-out") ){
  140.                 argCheck(args, i, 1);
  141.                 duplicateCheck(args, i, outArg);
  142.                 outArg = args[++i];
  143.             }
  144.             else if ( s.equalsIgnoreCase("-string") ){
  145.                 argCheck(args, i, 1);
  146.                 duplicateCheck(args, i, stringArg);
  147.                 stringArg = args[++i];
  148.             }
  149.             else if ( s.equalsIgnoreCase("-workDir") ){
  150.                 argCheck(args, i, 1);
  151.                 duplicateCheck(args, i, workDirArg);
  152.                 workDirArg = args[++i];
  153.             }
  154.             else if ( s.equalsIgnoreCase("-eventName") ){
  155.                 argCheck(args, i, 1);
  156.                 duplicateCheck(args, i, eventNameArg);
  157.                 eventNameArg = args[++i];
  158.             }
  159.             else {
  160.                 usage("Don't understand argument " + s);
  161.             }
  162.         }
  163.         if ( inArg != null && stringArg != null ) {
  164.             usage("Can't specify both -in and -string. Choose one.");
  165.         }
  166.     }
  167.  
  168.     private void duplicateCheck(String[] args, int index, String arg){
  169.         if ( arg != null ) {
  170.             usage("duplicate flag not allowed. Only specify one " + args[index]);
  171.         }
  172.     }
  173.  
  174.     private void argCheck(String[] args, int index, int needed){
  175.         if ( args.length <= index + needed ) {
  176.             usage("flag " + args[index] + " needs " + needed + " arguments.");
  177.         }
  178.     }
  179.  
  180.     /** Prints usage information, and then exits.
  181.      * @param error A string to print to System.err just before printing the usage info.
  182.      */
  183.  
  184.     protected void usage(String error){
  185.         System.err.println(error);
  186.         System.err.println("usage: [-plugin plugin][-in file | -string string][-out file][-workDir dir]\n"
  187.             + "  -plugin plugin    Use the named plugin. Defaults to\n"
  188.             + "                    netscape.plugin.composer.Plugin\n"
  189.             + "  -in file          Use the named file as the input document.\n"
  190.             + "  -out file         Use the named file as the output document.\n"
  191.             + "  -string string    Use the given string as the test document.\n"
  192.             + "                    Defaults to a small built-in test document.\n"
  193.             + "  -workDir dir      Use the given dir as the work directory.\n"
  194.             + "                    Defaults to java's user.dir property.\n"
  195.             + "  -eventName event  Simulate an event of the given name.\n"
  196.         );
  197.         System.exit(-1);
  198.     }
  199.  
  200.     /** Perform the test. Override to implement an alternative test
  201.      * technique.
  202.      * @return 0 if the plug-in returned false, or 1 if the plug-in returned true.
  203.      */
  204.     protected int test() throws IOException {
  205.         int status = 0;
  206.         TestDocument document = createDocument();
  207.         Plugin plugin = createPlugin();
  208.         // plugin.setProperties(createProperties());
  209.         System.out.println("Plugin class: " + plugin.getClass().toString());
  210.         System.out.println("    category: " + plugin.getCategory());
  211.         System.out.println("        name: " + plugin.getName());
  212.         System.out.println("        hint: " + plugin.getHint());
  213.         System.out.println("-------------------------------");
  214.         System.out.println("Original Document:\n");
  215.         System.out.println("             base: " + document.getBase());
  216.         System.out.println("    workDirectory: " + document.getWorkDirectory());
  217.         System.out.println(" workDirectoryURL: " + document.getWorkDirectoryURL());
  218.         System.out.println(" documentURL: " + document.getDocumentURL());
  219.         System.out.println(" eventName: " + document.getEventName());
  220.         System.out.println("Text:\n" + document.getText());
  221.         System.out.println("-------------------------------");
  222.         System.out.println("Calling plugin...\n");
  223.         String startText = document.getText();
  224.         boolean result = plugin.perform(document);
  225.         System.out.println("-------------------------------");
  226.         System.out.println("Plugin.perform returned: " + result);
  227.         System.out.println("-------------------------------");
  228.         if ( result && outArg != null ) {
  229.             writeDoc(document.getText(), new File(outArg));
  230.         }
  231.         if ( result ) {
  232.             status = 0;
  233.         }
  234.         else {
  235.             status = 1;
  236.         }
  237.         return status;
  238.     }
  239.  
  240.     /** Writes the document text to the supplied file.
  241.      */
  242.     protected void writeDoc(String doc, File out){
  243.         try {
  244.             FileWriter s = new FileWriter(out);
  245.             s.write(doc);
  246.             s.close();
  247.         } catch(IOException e){
  248.             e.printStackTrace();
  249.         }
  250.     }
  251.  
  252.     /** Called when the plug-in that's being tested has set some new text into the test document.
  253.      * The default implementation just prints the text to System.out.
  254.      * Override this if you want to do something more sophisiticated,
  255.      * like comparing the old text with the new text.
  256.      * @param text the new text of the test document.
  257.      */
  258.  
  259.     protected void newText(String text){
  260.         System.out.println("-------------------------------");
  261.         System.out.println("New Document text:\n");
  262.         System.out.println(text);
  263.     }
  264.  
  265.     /** Called when the plug-in that's being tested has called redirectDocumentOpen.
  266.      * The default implementation just prints the new URL to System.out.
  267.      * Override this if you want to do something more sophisticated.
  268.      * @param eventName the current event. (Should always be "edit", or else the plug-in
  269.      * behaving incorrectly.)
  270.      * @param newURL the new URL that the open should be redirected to.
  271.      */
  272.     public void reportRedirectDocumentOpen(String eventName, String newURL){
  273.         System.out.println("-------------------------------");
  274.         System.out.println("redirectDocumentOpen: " + newURL);
  275.         if ( eventName == null || !eventName.equals("edit") ) {
  276.             System.out.println("Warning!!! This call has no effect, because the eventName is "
  277.                 + (eventName == null ? "null" : eventName));
  278.         }
  279.     }
  280.  
  281.     /** Override this to create your own type of document.
  282.      */
  283.     protected TestDocument createDocument() throws IOException {
  284.         String workDir = "";
  285.         URL base = null;
  286.         String text = "";
  287.         if ( workDirArg != null ) {
  288.             workDir = workDirArg;
  289.         }
  290.         workDir = new File(workDir).getAbsolutePath();
  291.         if ( stringArg != null ) {
  292.             text = stringArg;
  293.         }
  294.         else if ( inArg != null ) {
  295.             StringBuffer fileContents = new StringBuffer();
  296.             File file = new File(inArg);
  297.             file = new File(file.getAbsolutePath());
  298.             // System.err.println("file: " + file + " size: " + file.length());
  299.             /* // JDK 1.1 code
  300.             FileReader in = new FileReader(file);
  301.             int c;
  302.             try {
  303.                 while ( (c = in.read()) >= 0 ) {
  304.                     fileContents.append( (char) c);
  305.                 }
  306.             } catch (Throwable t){
  307.                 t.printStackTrace();
  308.             }
  309.             // System.err.println("file contents: " + fileContents.length() + " '" + fileContents + "'");
  310.             in.close();
  311.             text = fileContents.toString();
  312.             */
  313.             FileInputStream in = new FileInputStream(file);
  314.             int c;
  315.             try {
  316.                 while ( (c = in.read()) >= 0 ) {
  317.                     fileContents.append( (char) c);
  318.                 }
  319.             } catch (Throwable t){
  320.                 t.printStackTrace();
  321.             }
  322.             // System.err.println("file contents: " + fileContents.length() + " '" + fileContents + "'");
  323.             in.close();
  324.             text = fileContents.toString();
  325.             base = toURL(file, true);
  326.         }
  327.         else {
  328.             text = "<html><head><title>A test document</title></head>\n"
  329.                 + "<body>\n"
  330.                 + "<p><a href=\"http://www.netscape.com\">Netscape</a></p>\n"
  331.                 + "<p>The <b>quick <i>brown</i></b> fox "
  332.                 + "<!-- selection start -->"
  333.                 + "<i>jumped</i> "
  334.                 + "<!-- selection end -->"
  335.                 + "over the lazy dog.</p>\n"
  336.                 + "</body>\n"
  337.                 + "</html>\n";
  338.             base = toURL(new File(""), false);
  339.         }
  340.         URL docURL = null;
  341.         if ( inArg != null ) {
  342.             docURL = toURL(new File(inArg), false);
  343.         }
  344.         TestDocument document = new TestDocument(this, text, base, workDir,
  345.             toURL(new File(workDir), false), docURL, eventNameArg );
  346.         return document;
  347.     }
  348.  
  349.     /** Convert a File to a URL.
  350.      * @param file a file.
  351.      * @param base if true, don't include the file's name in the url, just the path. This
  352.      * is handy for creating a base URL for a file.
  353.      * @return the corresponding URL.
  354.      */
  355.  
  356.     static URL toURL(File file, boolean getBase) throws MalformedURLException {
  357.         String path = file.getAbsolutePath();
  358.         file = new File(path); /* Absolutize. */
  359.         StringTokenizer tokenizer = new StringTokenizer(path, File.separator);
  360.         StringBuffer urlBuf = new StringBuffer("file:");
  361.         boolean bEncodeIllegalCharacters = false;
  362.         String allowedInURLs = "abcdefghijklmnopqrstuvwxyz"
  363.             + "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
  364.             + "0123456789"
  365.             + "$-_@.&+-";
  366.         boolean trimLast = getBase && ! file.isDirectory();
  367.         while(tokenizer.hasMoreTokens()) {
  368.             String token =  tokenizer.nextToken();
  369.             if ( trimLast && ! tokenizer.hasMoreTokens() ) {
  370.                 break;
  371.             }
  372.             urlBuf.append("/");
  373.             if ( bEncodeIllegalCharacters ) {
  374.                 /* Escape letters not allowed in URLs */
  375.                 for(int i = 0; i < token.length(); i++){
  376.                     char c = token.charAt(i);
  377.                     if ( allowedInURLs.indexOf(c) < 0 ){
  378.                         /* Not allowed */
  379.                         urlBuf.append("%" + Integer.toHexString(c));
  380.                     }
  381.                     else {
  382.                         urlBuf.append((char) c);
  383.                     }
  384.                 }
  385.             }
  386.             else {
  387.                 urlBuf.append(token);
  388.             }
  389.         }
  390.         if ( (getBase && ! file.isDirectory())
  391.             || ( file.isDirectory() && ! urlBuf.toString().endsWith("/"))) {
  392.             urlBuf.append("/");
  393.         }
  394.         URL url = new URL(urlBuf.toString());
  395.         return url;
  396.     }
  397.     /** Used to set the plugin programmaticly. Used by the Test.perform method.
  398.      */
  399.     public void setPlugin(Plugin plugin){
  400.         this.plugin = plugin;
  401.     }
  402.     /** Override this to create your own plugin. (Normally you would
  403.      * use the -plugin command line option. Or supply the argument to
  404.      * the Test.perform method.)
  405.      */
  406.     protected Plugin createPlugin(){
  407.         if ( plugin != null ) return plugin;
  408.  
  409.         String pluginClassName = new String("netscape.plugin.composer.Plugin");
  410.         if ( pluginArg != null ) {
  411.             pluginClassName = pluginArg;
  412.         }
  413.         plugin = null;
  414.         try {
  415.             plugin = (Plugin) Class.forName(pluginClassName).newInstance();
  416.         } catch (Throwable t){
  417.             t.printStackTrace();
  418.         }
  419.         return plugin;
  420.     }
  421.  
  422.     /** Override this to create your own properties. The default is to read the
  423.      * propertiesArg
  424.      */
  425.     protected Properties createProperties(){
  426.         String propertiesFile = new String("netscape_plugin_composer.ini");
  427.         if ( propertiesArg != null ) {
  428.             propertiesFile = propertiesArg;
  429.         }
  430.         Properties properties = new Properties();
  431.         try {
  432.             FileInputStream in = new FileInputStream(propertiesFile);
  433.             properties.load(in);
  434.             in.close();
  435.         } catch (Throwable t){
  436.             t.printStackTrace();
  437.         }
  438.         return properties;
  439.     }
  440.  
  441.     /** The argument the user supplied for -properties. Null if they didn't supply one.
  442.      */
  443.     protected String propertiesArg;
  444.  
  445.     /** The argument the user supplied for -plugin. Null if they didn't supply one.
  446.      */
  447.     protected String pluginArg;
  448.     /** The argument the user supplied for -in. Null if they didn't supply one.
  449.      */
  450.     protected String inArg;
  451.     /** The argument the user supplied for -out. Null if they didn't supply one.
  452.      */
  453.     protected String outArg;
  454.     /** The argument the user supplied for -string. Null if they didn't supply one.
  455.      */
  456.     protected String stringArg;
  457.     /** The argument the user supplied for -workDir. Null if they didn't supply one.
  458.      */
  459.     protected String workDirArg;
  460.     /** The plugin the user supplied programmaticly. Null if they didn't supply one.
  461.      */
  462.     protected Plugin plugin;
  463.  
  464.     protected String eventNameArg;
  465. }
  466.  
  467.