zoukankan      html  css  js  c++  java
  • NetBeans IDE 6.1 插件开发示例

    转载请保留作者信息:

    作者:88250

    Bloghttp:/blog.csdn.net/DL88250

    MSN & Gmail & QQDL88250@gmail.com

    NetBeans IDE 是基于NetBeans Platform搭建的,它的所有功能都是以插件的方式实现的。我们也可以基于NetBeans Platform实现自己的应用,这一点,与Eclipse RCP是等同的。首先,我们先来熟悉一下NetBeans Module的开发 :-)。这个例子是一个用于配置NetBeans启动参数的插件,用它可以使用图形界面配置NetBeans启动参数。当然了,这这是一个例子,Bugs比较多,要使用同种功能的插件,看这里

    准备

    点此访问NetBeans下载站点。下载最新的Java基本开发套件就可以了。

    开始

    1. 创建工程

    新建工程,选择模块开发:


    工程命名为CustomStartup,其他的使用默认配置。

    2. 编写测试用例

    插件随小,无脏俱全哦~ 再说,本着TDD的原则,我们还是先编写一下测试用例吧。

    测试代码如下:


    /*
     * @(#)NBConfFileJUnitTest.java
     * Author: 88250 <DL88250@gmail.com>, 
    http://blog.csdn.net/DL88250
     * Created on May 17, 2008, 11:19:21 AM
     * 
     * This program is free software; you can redistribute it and/or modify
     * it under the terms of the GNU General Public License as published by
     * the Free Software Foundation; either version 3 of the License, or
     * (at your option) any later version.
     * 
     * 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 Library General Public License for more details.
     * 
     * You should have received a copy of the GNU General Public License
     * along with this program; if not, write to the Free Software
     * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
     
    */
    package cn.edu.ynu.sei.customstartup.test;

    import java.io.BufferedReader;
    import java.io.File;
    import java.io.FileReader;
    import java.io.IOException;
    import java.util.Enumeration;
    import java.util.List;
    import java.util.Properties;
    import org.junit.After;
    import org.junit.AfterClass;
    import org.junit.Before;
    import org.junit.BeforeClass;
    import org.junit.Test;
    import org.openide.util.Exceptions;
    import static org.junit.Assert.*;

    /**
     * NBConfFile Test Case.
     * 
    @author 88250 <DL88250@gmail.com>, http://blog.csdn.net/DL88250
     * 
    @version 1.0.0.0, May 17, 2008
     
    */
    public class NBConfFileJUnitTest {

        
    private static cn.edu.ynu.sei.customstartup.NBConfFile instance;

        
    public NBConfFileJUnitTest() {
            instance 
    = new cn.edu.ynu.sei.customstartup.NBConfFile();

        }

        @BeforeClass
        
    public static void setUpClass() throws Exception {
            
    // simulate the NetBeans luncher to set system property
            System.setProperty("netbeans.home",
                               
    "/home/daniel/Work/netbeans-6.1/platform8");
        }

        @AfterClass
        
    public static void tearDownClass() throws Exception {
        }

        @Before
        
    public void setUp() {
        }

        @After
        
    public void tearDown() {
        }

        @Test
        
    public void getLocation() {
            System.out.println(
    "getLocation");
            assertEquals(
    "/home/daniel/Work/netbeans-6.1/etc/netbeans.conf",
                         instance.getLocation());
        }

        @Test
        
    public void getFile() {
            System.out.println(
    "getFile");
            File netbeans_conf 
    = instance.getFile();
            assertTrue(netbeans_conf.exists());
            assertEquals(
    "netbeans.conf", netbeans_conf.getName());
            BufferedReader reader;
            
    //String expect =
            
    //      "# ${HOME} will be replaced by JVM user.home system property";
            String expect = "### properties written by CustomStartup module";
            String actual 
    = null;
            
    try {
                reader 
    = new BufferedReader(new FileReader(netbeans_conf));
                actual 
    = reader.readLine();
            } 
    catch (IOException ex) {
                Exceptions.printStackTrace(ex);
            }
            assertEquals(expect, actual);
        }

        @Test
        
    public void backupConfFile() {
            System.out.println(
    "backupConfFile");
            instance.backupConfFile();
            assertTrue(instance.getBackupFile().exists());
        }

        @Test
        
    public void getBackupFile() {
            System.out.println(
    "getBackupFile");
            File actual 
    = instance.getBackupFile();
            assertEquals(
    "netbeans.conf.backup", actual.getName());
        }

        @Test
        
    public void getParameters() {
            System.out.println(
    "getParameters");
            Properties paras 
    = instance.getParameters();
            Enumeration
    <?> keys = paras.propertyNames();
            
    while (keys.hasMoreElements()) {
                String key 
    = keys.nextElement().toString();
                String value 
    = paras.getProperty(key);
                System.out.println(key 
    + "=" + value);
            }

            assertEquals(
    ""${HOME}/.netbeans/6.1"",
                         paras.getProperty(
    "netbeans_default_userdir"));
        }

        @Test
        
    public void getNetBeansDefaultOptions() {
            System.out.println(
    "getNetBeansDefaultOptions");
            List
    <String> options = instance.getNetBeansDefaultOptions();
            
    for (String option : options) {
                System.out.println(option);
            }

            assertEquals(
    "-J-client", options.get(0));
            assertEquals(
    "--fontsize 10", options.get(options.size() - 1));
        }

        @Test
        
    public void getNetBeansJDKHome() {
            System.out.println(
    "getNetBeansJDKHome");
            String expect 
    = "/usr/lib/jvm/java-6-sun/";
            String actual 
    = instance.getNetBeansJDKHome();
            assertEquals(expect, actual);
        }

        @Test
        
    public void setNetBeansJDKHome() {
            System.out.println(
    "setNetBeansJDKHome");
            String jdkHome 
    = "/usr/lib/jvm/java-6-sun/";
            instance.setNetBeansJDKHome(jdkHome);

            assertEquals(jdkHome, instance.getNetBeansJDKHome());
        }

        @Test
        
    public void addNetBeansDefaultOptions() {
            System.out.println(
    "addNetBeansDefaultOptions");
            String para 
    = "--fontsize 15";
            instance.addNetBeansDefaultOptions(para);
            assertEquals(para, instance.getNetBeansDefaultOptions().get(instance.
                                                                        getNetBeansDefaultOptions().
                                                                        size() 
    - 1));
        }

        @Test
        
    public void removeNetBeansDefaultOptions() {
            System.out.println(
    "removeNetBeansDefaultOptions");
            instance.removeNetBeansDefaultOptions(
    0);
            assertEquals(
    "-J-Xss16m", instance.getNetBeansDefaultOptions().get(0));
        }

        @Test
        
    public void editNetBeansDefaultOptions() {
            System.out.println(
    "editNetBeansDefaultOptions");
            instance.editNetBeansDefaultOptions(
    0"--test 10");
            assertEquals(
    "--test 10", instance.getNetBeansDefaultOptions().get(0));
        }
    }

    3. 编写逻辑实现代码

    /*
     * @(#)NBConfFile.java
     * Author: 88250 <DL88250@gmail.com>, 
    http://blog.csdn.net/DL88250
     * Created on May 17, 2008, 11:23:53 AM
     * 
     * This program is free software; you can redistribute it and/or modify
     * it under the terms of the GNU General Public License as published by
     * the Free Software Foundation; either version 3 of the License, or
     * (at your option) any later version.
     * 
     * 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 Library General Public License for more details.
     * 
     * You should have received a copy of the GNU General Public License
     * along with this program; if not, write to the Free Software
     * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
     
    */
    package cn.edu.ynu.sei.customstartup;

    import java.io.BufferedReader;
    import java.io.BufferedWriter;
    import java.io.File;
    import java.io.FileInputStream;
    import java.io.FileOutputStream;
    import java.io.FileReader;
    import java.io.FileWriter;
    import java.io.IOException;
    import java.io.InputStream;
    import java.io.OutputStream;
    import java.util.ArrayList;
    import java.util.Enumeration;
    import java.util.List;
    import java.util.Properties;
    import org.openide.util.Exceptions;

    /**
     * NetBeans startup configuration file description.
     * 
    @author 88250 <DL88250@gmail.com>, http://blog.csdn.net/DL88250
     * 
    @version 1.0.0.0, May 17, 2008
     
    */
    public class NBConfFile {

        
    /**
         * configuration file location(full path, full name)
         
    */
        
    private String location;
        
    /**
         * configuration file
         
    */
        
    private File self;

        
    /**
         * Default constructor.
         
    */
        
    public NBConfFile() {
            initLocation();
        }

        
    /**
         * Add a new NetBeans startup parameter.
         * 
    @param para the new parameter to be added
         
    */
        
    public void addNetBeansDefaultOptions(String para) {
            List
    <String> options = getNetBeansDefaultOptions();
            options.add(para);
            persistNBOptions(options);
        }

        
    /**
         * Edit a NetBeans startup parameter.
         * 
    @param index parameter index
         * 
    @param newValue the new parameter value
         
    */
        
    public void editNetBeansDefaultOptions(int index, String newValue) {
            List
    <String> options = getNetBeansDefaultOptions();
            
    if (index >= options.size()) {
                
    return;
            }
            options.set(index, newValue);
            persistNBOptions(options);
        }

        
    /**
         * Remove a NetBeans startup parameter.
         * 
    @param index a parameter to be deleted
         
    */
        
    public void removeNetBeansDefaultOptions(int index) {
            List
    <String> options = getNetBeansDefaultOptions();
            
    if (index >= options.size()) {
                
    return;
            }
            options.remove(index);
            persistNBOptions(options);
        }

        
    /**
         * Backup configuration file. The backup named "netbeans.conf.backup", and 
         * in the same path with original.
         
    */
        
    public void backupConfFile() {
            InputStream inFile 
    = null;
            OutputStream outFile 
    = null;
            
    try {
                inFile 
    = new FileInputStream(location);
                outFile 
    = new FileOutputStream(location + ".backup");
                org.openide.filesystems.FileUtil.copy(inFile, outFile);
            } 
    catch (IOException ex) {
                Exceptions.printStackTrace(ex);
            } 
    finally {
                
    try {
                    inFile.close();
                    outFile.close();
                } 
    catch (IOException ex) {
                    Exceptions.printStackTrace(ex);
                }
            }
        }

        
    /**
         * Get the configuration backup file.
         * 
    @return a file named "netbeans.conf.backup"
         
    */
        
    public File getBackupFile() {
            File ret 
    = new File(location + ".backup");
            
    if (ret.exists()) {
                
    return ret;
            } 
    else {
                
    throw new RuntimeException("netbeans.conf.backup inexists!");
            }
        }

        
    /**
         * Get the configuration file.
         * 
    @return {@link #self}
         
    */
        
    public File getFile() {
            self 
    = new File(location);
            
    if (self.exists()) {
                
    return self;
            } 
    else {
                
    throw new RuntimeException("netbeans.conf inexists!");
            }
        }

        
    /**
         * Get the configuration file location.
         * 
    @return {@link #location}
         
    */
        
    public String getLocation() {
            
    return location;
        }

        
    /**
         * Get all values described in "netbeans_default_options", file "netbeans.conf".
         * 
    @return if netbeans_default_options="-J-client -J-Xss16m -J-Xms128m -J-XX:PermSize=256m <b>--fontsize 10</b> ...", 
         * return a list like this: {"-J-client", "-J-Xss16m", "-J-Xms128m", "-J-XX:PermSize=256m", <b>"--fontsize 10"</b>...}
         
    */
        
    public List<String> getNetBeansDefaultOptions() {
            String[] allOptions 
    = getParameters().getProperty(
                    
    "netbeans_default_options").split("/s");
            
    int last = allOptions.length - 1;
            
    // remove the first double quotation
            allOptions[0= allOptions[0].substring(1, allOptions[0].length());
            
    // remove the last double quotation
            allOptions[last] =
                    allOptions[last].substring(
    0,
                                               allOptions[last].length() 
    - 1);
            List
    <String> ret = new ArrayList<String>();

            
    for (int i = 0; i < allOptions.length; i++) {
                String item 
    = allOptions[i];
                
    // confirm the startup parameter's beginning
                if (item.length() >= 2) {
                    String beginning 
    = item.substring(02);

                    
    if (beginning.equals("-J")) {
                        
    // JVM Parameters
                        ret.add(item);
                    } 
    else if (beginning.equals("--")) {
                        
    // IDE Parameters
                        if (item.startsWith("--laf")) {
                            
    // --laf ui_class_name: Use a given class as the IDE's look and feel.
                            ret.add(item + " " + allOptions[i + 1]);
                        } 
    else if (item.startsWith("--fontsize")) {
                            
    // --fontsize size: Use a given size in points as the basic font size for the IDE user interface.
                            ret.add(item + " " + allOptions[i + 1]);
                        }
                    } 
    else {
                        
    // TODO other's conditions
                    }
                }
            }

            
    return ret;
        }

        
    /**
         * Get JDK HOME by NetBeans using.
         * 
    @return the JDK HOME path, such as "/usr/lib/jvm/java-6-sun/"
         
    */
        
    public String getNetBeansJDKHome() {
            String ret 
    = getParameters().getProperty("netbeans_jdkhome");
            
    // remove the double quotation
            ret = ret.substring(1, ret.length() - 1);

            
    return ret;
        }

        
    /**
         * Get all startup parameters in file "netbeans.conf". Every parameter like this:
         * <p>
         * -J-Xss16m
         * -J-XX:PermSize=256m
         * -J-Xverify:none
         * --laf javax.swing.plaf.metal.MetalLookAndFeel
         * --fontsize 10
         * </p>
         * 
    @return
         
    */
        
    public Properties getParameters() {
            Properties paras 
    = new Properties();
            BufferedReader nb_confReader 
    = null;
            
    try {
                nb_confReader 
    = new BufferedReader(new FileReader(getFile()));

                String aLine 
    = null;
                
    while ((aLine = nb_confReader.readLine()) != null) {
                    
    if (aLine == null || aLine.equals(""|| aLine.charAt(0== '#') {
                        
    continue;
                    }
                    String key 
    = aLine.substring(0, aLine.indexOf('='));
                    String value 
    = aLine.substring(aLine.indexOf('='+ 1,
                                                   aLine.length());
                    paras.setProperty(key, value);
                }
            } 
    catch (IOException ex) {
                Exceptions.printStackTrace(ex);
                
    throw new RuntimeException("netbeans.conf read error!!");
            }

            
    return paras;
        }

        
    /**
         * Set NetBEans JDK Home path.
         * <p>
         * NOTE: the specified  jdkHome path is full path withou double quotation.
         * , such as <center>/usr/lib/jvm/java-6-sun/</center>
         * </p>
         * 
    @param jdkHome JDK Home path
         
    */
        
    public void setNetBeansJDKHome(String jdkHome) {
            Properties paras 
    = getParameters();
            paras.setProperty(
    "netbeans_jdkhome"""" + jdkHome + """);
            setParameters(paras);
        }

        
    /**
         * Persist NetBeans Options.
         * 
    @param options options list
         
    */
        
    private void persistNBOptions(List<String> options) {

            Properties paras 
    = getParameters();
            String optionsStr 
    = "";
            
    for (String option : options) {
                optionsStr 
    += option + " ";
            }
            optionsStr 
    = optionsStr.trim();

            paras.setProperty(
    "netbeans_default_options"""" + optionsStr + """);
            setParameters(paras);
        }

        
    /**
         * Set all startup parameters in file "netbeans.conf".
         * 
    @param paras the parameters store by a <code>Properties<code>
         
    */
        
    private void setParameters(Properties paras) {
            BufferedWriter writer;
            
    try {
                writer 
    = new BufferedWriter(new FileWriter(location));
                writer.write(
    "### properties written by CustomStartup module");
                writer.newLine();
                Enumeration
    <?> keys = paras.propertyNames();
                
    while (keys.hasMoreElements()) {
                    String key 
    = keys.nextElement().toString();
                    String value 
    = paras.getProperty(key);
                    writer.write(key 
    + "=" + value);
                    writer.newLine();
                }
                writer.close();
            } 
    catch (IOException ex) {
                Exceptions.printStackTrace(ex);
            }
        }

        
    /**
         * Initialize netbeans.conf's location.
         
    */
        
    private void initLocation() {
            location 
    = System.getProperty("netbeans.home");

            
    // remove "/platform8"
            location = location.substring(0, location.lastIndexOf(File.separator));
            
    // add "/etc/netbeans.conf"
            location += File.separator + "etc" + File.separator + "netbeans.conf";
        
    // TODO OS settings
        
    //System.out.println(org.openide.util.Utilities.isUnix());
        
    //System.out.println(org.openide.util.Utilities.isWindows());
        }
    }

    4. 开始插件咯~

    好了,上面贴了很多代码,貌似和NetBeans的插件开发没什么联系。现在我们正式开始介绍插件开发(模块开发)!

    a. 添加需要的依赖库,也就是Platform的一些APIs:


    b.建立Options Panel类型的文件:



    c. 打开Panel,设计界面:



    d. 主要事件处理代码:


    private void confirmJDKHomeBtnActionPerformed(java.awt.event.ActionEvent evt) {                                                  
        String jdkHomeInput 
    = jdkHomeTextField.getText();

        nBConfFile.setNetBeansJDKHome(jdkHomeInput);
    }                                                 

    private void addParasBtnActionPerformed(java.awt.event.ActionEvent evt) {                                            
        String newValue 
    = (String) this.argumentsTbl.getCellEditor(
                
    this.argumentsTbl.getEditingRow(), 0).getCellEditorValue();
        Vector
    <String> newRow = new Vector<String>();
        newRow.add(newValue);
        
    this.argsTblModel.addRow(newRow);

    }                                           

    private void removeParasBtnActionPerformed(java.awt.event.ActionEvent evt) {                                               
        
    int selectedRow = this.argumentsTbl.getSelectedRow();
        
    this.argsTblModel.removeRow(selectedRow);
        nBConfFile.removeNetBeansDefaultOptions(selectedRow);
    }                                              

    private void argumentsTblPropertyChange(java.beans.PropertyChangeEvent evt) {                                            
        
    int selectedRow = this.argumentsTbl.getSelectedRow();
        
    if (selectedRow >= 0 && selectedRow <= nBConfFile.getNetBeansDefaultOptions().
                size()) {
            
    // edit parameter
            String newValue = this.argsTblModel.getValueAt(selectedRow,
                                                           
    0).toString();
            nBConfFile.editNetBeansDefaultOptions(selectedRow, newValue);
        } 
    else if (selectedRow >= 0 && this.argsTblModel != null &&
                
    this.argsTblModel.getValueAt(selectedRow, 0!= null) {
            
    // add parameter
            String newValue = this.argsTblModel.getValueAt(selectedRow,
                                                           
    0).toString();
            nBConfFile.addNetBeansDefaultOptions(newValue);
        }
    }             

    5. 测试

    直接运行工程就可以了:

    总结

    较NetBeans与eclipse的插件开发比较,我觉得NB的要方便一些。特别是NB Platform提供的APIs比较“人性化”。而且NB在开发时要稳定一点。不过,随着JDK7里正式内置了OSGi,情况可能会有所改变。让我们拭目以待!
  • 相关阅读:
    zoj 3632 Watermelon Full of Water
    将字符串切割成数组 componentsSeparatedByString
    paip.C#.NET多线程访问 toolStripStatusLabel
    EBS后台取消死锁检查代码和取消死锁会话步骤经验
    Java泛型深入题目
    Win7下BootCamp蓝屏问题解决方案二
    一步步开发 Spring MVC 应用
    批处理获取U盘、可移动硬盘的盘符
    一种松耦合的分层插件系统的设计和实现
    分享一个开源的批量修改VC工程属性的小工具
  • 原文地址:https://www.cnblogs.com/lanzhi/p/6470271.html
Copyright © 2011-2022 走看看