jtutils.java

来自「cqME :java framework for TCK test.」· Java 代码 · 共 789 行 · 第 1/2 页

JAVA
789
字号
/*
 * $Id$
 *
 * Copyright 2007 Sun Microsystems, Inc. All Rights Reserved.
 * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER
 *
 * This program is free software; you can redistribute it and/or
 * modify it under the terms of the GNU General Public License version
 * 2 only, as published by the Free Software Foundation.
 *
 * This program is distributed in the hope that it will be useful, but
 * WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
 * General Public License version 2 for more details (a copy is
 * included at /legal/license.txt).
 *
 * You should have received a copy of the GNU General Public License
 * version 2 along with this work; if not, write to the Free Software
 * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
 * 02110-1301 USA
 *
 * Please contact Sun Microsystems, Inc., 4150 Network Circle, Santa
 * Clara, CA 95054 or visit www.sun.com if you need additional
 * information or have any questions.
 *
 */

package com.sun.testme;

import com.sun.javatest.JavaTestError;
import com.sun.javatest.Status;
import com.sun.javatest.TestDescription;
import com.sun.javatest.TestFinder;
import com.sun.javatest.TestResult;
import com.sun.javatest.TestResultTable;
import com.sun.javatest.WorkDirectory;
import com.sun.javatest.finder.HTMLTestFinder;
import com.sun.javatest.lib.MultiStatus;
import com.sun.javatest.util.HTMLWriter;
import com.sun.javatest.util.StringArray;
import com.sun.testme.jtharness.testsuite.JTharnessSuiteUtil;
import java.awt.Image;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import java.io.StringWriter;
import java.util.ArrayList;
import javax.swing.Icon;
import org.netbeans.api.project.Project;
import org.netbeans.api.project.ui.OpenProjects;
import org.openide.execution.ExecutorTask;
import org.openide.filesystems.FileObject;
import org.openide.filesystems.FileUtil;
import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.Properties;
import org.openide.DialogDisplayer;
import org.openide.NotifyDescriptor;
import org.openide.execution.ExecutionEngine;
import org.openide.windows.IOProvider;
import org.openide.windows.InputOutput;

/**
 *
 * @author User
 */
public class JTUtils {
    
    private static TestFinder testFinder = new HTMLTestFinder();
    private static WorkDirectory workDirectory;
    
    public static void initTestSuite(TestFinder finder, File testSuiteRoot, File workDir) {
        Project project = OpenProjects.getDefault().getMainProject();
        JTharnessSuiteUtil testSuiteInfo = (JTharnessSuiteUtil)project.getLookup().lookup(JTharnessSuiteUtil.class);
        
        workDirectory = testSuiteInfo.getWorkDirectory0();
        if (workDirectory != null) {
            testFinder = workDirectory.getTestSuite().getTestFinder();
        }
    }
    
    public static TestFinder getTestFinder() {
        return testFinder;
    }
    
    
    public static File[] getFiles(File file, boolean updateFinder) {
        if (updateFinder) {
            testFinder.read(file);
        }
        return testFinder.getFiles();
    }

    public static TestDescription[] getTests(File file, boolean updateFinder) {
        if (updateFinder) {
            testFinder.read(file);
        }
        return testFinder.getTests();
    }
    
    public static Status getStatus(TestDescription td) {
        TestResult testResult = getTestResult(td);
        return (testResult == null) ? null : testResult.getStatus();
    }
    
    private static TestResult getTestResult(TestDescription td) {
        try {
            TestResult testResult = new TestResult(td, workDirectory);
            return testResult;
        } catch (Throwable e) {
            e.printStackTrace();
        }
        return null;
    }

    public static Image getImage(Icon icon) {
        BufferedImage image = new BufferedImage(icon.getIconWidth(), icon.getIconHeight(), BufferedImage.TYPE_INT_ARGB);
        icon.paintIcon(null, image.getGraphics(), 0, 0);
        return image;
    }
    
    public static File getJTRFile(TestDescription td) {
        String relPath = getRelativePath(td);
        if (relPath == null) {
            return null;
        }
        return workDirectory.getFile(relPath);
    }
    
    private static String getRelativePath(TestDescription td) {
        Status status = getStatus(td);
        if ((status == null) || (status.getType() == Status.NOT_RUN)) {
            return null;
        }
        
        TestResult testResult = getTestResult(td);
        if (testResult == null) {
            return null;
        }
        
        String jtrPath = testResult.getWorkRelativePath(td);
        return jtrPath;
    }
    
    private static String getRelativePath(File file) {
        FileObject rootFO = FileUtil.toFileObject(testFinder.getRootDir());
        File targetFile = (file.isDirectory()) ? file : file.getParentFile();
        FileObject targetFO = FileUtil.toFileObject(targetFile);
        return FileUtil.getRelativePath(rootFO, targetFO);
    }
    
    private static TestResultTable.TreeIterator getTreeIterator(File file) {
        TestResultTable.TreeIterator iterator = null;
        TestResultTable resultTable = workDirectory.getTestResultTable();
        resultTable.waitUntilReady();
        try {
            iterator = resultTable.getIterator(new File [] {file}, null);
        } catch (TestResultTable.Fault fault) {
            fault.printStackTrace();
        }
        return iterator;
    }
    
    public static Status getStatus(File file) {
        TestResultTable.TreeIterator iterator = getTreeIterator(file);
        MultiStatus multiStatus = new MultiStatus();

        boolean validMultiStatus = false;
        if (iterator == null) {
            return null;
        }
        while (iterator.hasNext()) {
            TestResult result = (TestResult) iterator.next();
            Status status;
            try {
                status = getStatus(result.getDescription());
                if (status == null) {
                    return null;
                }
            } catch (TestResult.Fault ex) {
                ex.printStackTrace();
                return null;
            }
            if (status.getType() != Status.NOT_RUN) {
                validMultiStatus = true;
                multiStatus.add(result.getTestName(), status);
            }
        }
        if (validMultiStatus) {
            return multiStatus.getStatus();
        } else {
            return new Status(Status.NOT_RUN, "Not Run. No test results found");
        }
    }

    public static void clearTestResult(Object obj) {
        String file = null;
        if (obj instanceof TestDescription) {
            file = getRelativePath((TestDescription) obj);
        } else if (obj instanceof File) {
            file = getRelativePath((File) obj);
        } else {
            return;
        }
        
        try {
            workDirectory.purge(file);
        } catch (Throwable e) {
            e.printStackTrace();
        }
    }
    
    public static void runTest(Object obj) {
        String tests = null;
        if (obj == null) {
        } else if (obj instanceof TestDescription) {
            tests = ((TestDescription) obj).getRootRelativePath();
        } else if (obj instanceof File) {
            tests = getRelativePath((File) obj);
        } else {
            return;
        }

        OpenProjects openProjects = OpenProjects.getDefault();
        final Project mainProject = openProjects.getMainProject();
        System.setProperty("javatestClassDir", mainProject.getProjectDirectory().getPath() + "/lib/javatest.jar");
        
        System.out.println("Run test " + tests);
        ArrayList<String> argsList = new ArrayList();
        argsList.add("-config");
        Project project = OpenProjects.getDefault().getMainProject();
        JTharnessSuiteUtil testSuiteInfo = (JTharnessSuiteUtil)project.getLookup().lookup(JTharnessSuiteUtil.class);
        argsList.add(testSuiteInfo.getInterviewFile().getPath());
        if (obj != null) {
            argsList.add("-tests");
            argsList.add(tests);
        }
        
        final Properties prop;
        try {
            FileObject fob = mainProject.getProjectDirectory().getFileObject("build/plugin.properties");
            InputStream in = fob.getInputStream();
            prop = new Properties();
            prop.load(in);
            in.close();
        } catch (Exception e) {
            e.printStackTrace();
            return;
        }
        
        argsList.add((String)prop.get("jtParams"));
        
        argsList.add("-runtests");
        final String [] args = new String[argsList.size()];
        argsList.toArray(args);
        
        final String timeOut = (String)prop.get("riTimeout");
        final String riCmd = (String)prop.get("riCmd");
        if ((timeOut == null) || ("".equals(timeOut.trim())) 
          || (riCmd == null)  || ("".equals(riCmd.trim()))) {
            DialogDisplayer.getDefault().notify(new NotifyDescriptor.Message("You need to define the following properties: \n" +
                    "  - riCmd\n" +
                    "  - riTimeout \n" +
                    "in the plugin.properties file"));
            return;
        }
        final int intTimeout;
        try {
            intTimeout = Integer.valueOf(timeOut).intValue();
        } catch (Throwable e) {
            DialogDisplayer.getDefault().notify(new NotifyDescriptor.Message("riTimeout property defined in the plugin.properties file specifies the delay in milliseconds before starting of an agent." +
                    "It should be integer."));
            return;
        }
        
        Runnable r = new Runnable() {
            public void run() {
                try {
                    Thread.sleep(intTimeout);
                    Exec.execPrint(riCmd);
                } catch (Exception ex) {
                    ex.printStackTrace();
                }
            }
        };

        Runnable r2 = new Runnable() {
            public void run() {
                //com.sun.javatest.tool.Main javatestMain = new com.sun.javatest.tool.Main();
                String sArgs = "";
                for (int i = 0; i < args.length; i++) {
                    sArgs += " " + args[i];
                }
                Exec.execPrint("java -cp " + System.getProperty("javatestClassDir") + " com.sun.javatest.tool.Main " + sArgs);
                //Exec.execPrint("java -version");
//                try {
//                    javatestMain.run(args, new PrintWriter(System.out));
//                } catch (CommandContext.Fault ex) {
//                    ex.printStackTrace();
//                } catch (Command.Fault ex) {
//                    ex.printStackTrace();
//                } catch (CommandParser.Fault ex) {
//                    ex.printStackTrace();
//                } catch (Main.Fault ex) {
//                    ex.printStackTrace();
//                }
            }
        };
        
        ExecutionEngine engine = ExecutionEngine.getDefault();
        InputOutput testIO = IOProvider.getDefault().getIO("Run tests", false);
        try {
            testIO.getOut().reset();
        } catch (IOException e) {
        }
        ExecutorTask task = engine.execute("Run tests", r2, testIO);        

        InputOutput agentIO = IOProvider.getDefault().getIO("Run agent", false);
        try {
            agentIO.getOut().reset();
        } catch (IOException e) {
        }
        engine.execute("Run agent", r, agentIO);
        task.waitFinished();
    }
    
    public static String createSectionSummary(TestResult.Section section) {
	StringWriter sw = new StringWriter();
	try {
	    HTMLWriter out = new HTMLWriter(sw);
	    out.startTag(HTMLWriter.HTML);
	    out.startTag(HTMLWriter.BODY);
	    //out.writeStyleAttr(bodyStyle);

	    // generate a table showing the size of the various output streams
	    out.startTag(HTMLWriter.H3);
	    out.writeStyleAttr("margin-top: 0");
	    out.write("Output Summary");
	    out.endTag(HTMLWriter.H3);
	    out.write("The following output was recorded");
	    out.startTag(HTMLWriter.TABLE);
	    out.writeAttr(HTMLWriter.BORDER, "0");
	    //out.writeStyleAttr(tableStyle);
	    out.startTag(HTMLWriter.TR);
	    out.startTag(HTMLWriter.TH);
	    out.writeAttr(HTMLWriter.ALIGN, HTMLWriter.LEFT);
	    out.write("Name");
	    out.endTag(HTMLWriter.TH);
	    out.startTag(HTMLWriter.TH);
	    out.writeAttr(HTMLWriter.ALIGN, HTMLWriter.LEFT);
	    out.writeStyleAttr("margin-left:10");
	    out.write("Size (chars)");
	    out.endTag(HTMLWriter.TH);
	    out.endTag(HTMLWriter.TR);
	    String[] names = section.getOutputNames();
	    for (int i = 0; i < names.length; i++) {
		String name = names[i];
		String text = section.getOutput(name);
		out.startTag(HTMLWriter.TR);
		out.startTag(HTMLWriter.TD);
		if (text.length() == 0)
		    out.write(name);
		else 
		    out.writeLink("#" + name, name/*, linkStyle*/);
		out.endTag(HTMLWriter.TD);
		out.startTag(HTMLWriter.TD);
		out.writeStyleAttr("margin-left:10");
		if (text.length() == 0)
		    out.write("(empty)");
		else
		    out.write(String.valueOf(text.length()));
		out.endTag(HTMLWriter.TD);
		out.endTag(HTMLWriter.TR);
	    }
	    out.endTag(HTMLWriter.TABLE);
	    
	    // if there is a status, show it
	    Status s = section.getStatus();
	    if (s != null) {
		out.startTag(HTMLWriter.H3);
		//out.writeStyleAttr(h3Style);
		out.write("Result");
		out.endTag(HTMLWriter.H3);
		out.write("The result of this section was:");
		out.startTag(HTMLWriter.P);
		out.writeStyleAttr("margin-left:30; margin-top:0; font-size: 12pt");
		out.startTag(HTMLWriter.OBJECT);
		out.writeAttr(HTMLWriter.CLASSID, "com.sun.javatest.tool.IconLabel");
		out.writeParam("type", "testSection");
		out.writeParam("state", getStatusKey(s.getType()));
		out.endTag(HTMLWriter.OBJECT);
		out.write(s.toString());
		out.endTag(HTMLWriter.P);
	    }

⌨️ 快捷键说明

复制代码Ctrl + C
搜索代码Ctrl + F
全屏模式F11
增大字号Ctrl + =
减小字号Ctrl + -
显示快捷键?