Eclipse插件开发首选项篇

  • 介绍
如果你的插件需要保存一些数据(参数),比如要设置一些ip地址等等。这时候,就要用到Eclipse提供的首选项这个扩展点。 我们这里的首选项的数据类型只包括Java中的基本数据类型。
  • 扩展点 org.eclipse.core.runtime.preferences
下面这个扩展点是用来初始化首选项值的: [codesyntax lang="xml"]
<extension point="org.eclipse.core.runtime.preferences">
<initializer
    class="org.suren.littlebird.preferences.PreferenceInitializer">
</initializer>
</extension>
[/codesyntax]
  • 初始化
[codesyntax lang="java"]
package org.suren.littlebird.preferences;

import org.eclipse.core.runtime.preferences.AbstractPreferenceInitializer;
import org.eclipse.jface.preference.IPreferenceStore;

import org.suren.littlebird.Activator;

/**
 * http://surenpi.com
 * @author suren
 * @since 2015-2-2
 */
public class PreferenceInitializer extends AbstractPreferenceInitializer
{

	public void initializeDefaultPreferences()
	{
		IPreferenceStore store = Activator.getDefault().getPreferenceStore();
		store.setDefault(PreferenceConstants.P_OSGI_PORT, 9789);
		store.setDefault(PreferenceConstants.P_OSGI_FILTER, "com");

		store.setDefault(PreferenceConstants.P_BUNDLE_DIR, "/opt/gridview/bundles/application");
		store.setDefault(PreferenceConstants.P_BUNDLE_WEB_RUNDIR,
				"/opt/gridview/runner/web");

		store.setDefault(PreferenceConstants.P_SSH_PORT, 22);
		store.setDefault(PreferenceConstants.P_SSH_USER, "root");
		store.setDefault(PreferenceConstants.P_SSH_PASSWD, "");

		store.setDefault(PreferenceConstants.P_LOGGER_BRIDGE_PORT, 7896);
		store.setDefault(PreferenceConstants.P_LOGGER_LAYOUT, "%d{yyyy-MM-dd HH:mm:ss} [%p]-[ %l] %m %n");
		store.setDefault(PreferenceConstants.P_LOGGER_NO_BRIDGE_HIDDEN, true);
		store.setDefault(PreferenceConstants.P_LOGGER_FILTER, "");
	}

}
[/codesyntax]
  • 获取值
[codesyntax lang="java"]
IPreferenceStore store = Activator.getDefault().getPreferenceStore();
String filter = store.getString(PreferenceConstants.P_OSGI_FILTER);
[/codesyntax] 这里的Activator当然就是本插件中的启动类了。但是,这只能获取到本插件内部的首选项值,那怎么才能获取到其他插件的值呢?例如,您写一个插件要或者到LittleBird的首选项配置,怎么办呢?请看下面的代码片段: [codesyntax lang="java"]
String node = "org.suren.littlebird";
IEclipsePreferences pref = DefaultScope.INSTANCE.getNode(node);
System.out.println(pref.get("logger_filter", "--"));
[/codesyntax] 上面的代码您要是看明白了的话,就会有一个疑问——node是从哪里来的呢,还有后面的key值? 我给您推荐一个比较暴力的办法,就是直接用Java的反编译工具把对应的插件jar文件给翻译过来,然后找到对应的初始化类。 另外也有一个温柔的办法,从您的Eclipse工作空间目录下面找(.metadata\.plugins\org.eclipse.core.runtime\.settings)。
  • 作用域
类似变量一样,首选项也有自己的作用域,例如:有的配置项是要作用在整个工作空间上,有的是要作用在某个工程上等。而首选项作用域的不同和在操作系统中保存的位置紧密相关。下面是Eclipse平台对作用域的定义:
  1. 实例,按照工作空间或者平台实例来存储
  2. 配置,根据Eclipse的按照位置来存储,多个实例之间共享
  3. 缺省项,根据某个插件的定义来存储,一般都写死在插件内部
这里既然提到了首选项有“作用域”,那么我们怎么才能获取到指定作用域下的值呢?这是个值得注意的问题。 Eclipse平台提供了三种作用域对应的实现类,如此便简单了,只要调用对应的实现类来或者值就ok了。 [codesyntax lang="java"]
private void print(String node, boolean export)
{
	try
	{
		IEclipsePreferences pref = DefaultScope.INSTANCE.getNode(node);
		System.out.println(Arrays.toString(pref.keys()));
		for(String key : pref.keys())
		{
			System.out.println(key + "===========" + pref.get(key, "--"));
		}
		if(export)
		{
			export(node, pref);
		}
		
		pref = ConfigurationScope.INSTANCE.getNode(node);
		System.out.println(Arrays.toString(pref.keys()));
		for(String key : pref.keys())
		{
			System.out.println(key + "===========" + pref.get(key, "--"));
		}
		if(export)
		{
			export(node, pref);
		}
		
		pref = InstanceScope.INSTANCE.getNode(node);
		System.out.println(Arrays.toString(pref.keys()));
		for(String key : pref.keys())
		{
			System.out.println(key + "===========" + pref.get(key, "--"));
		}
		if(export)
		{
			export(node, pref);
		}
	}
	catch(Exception e)
	{
		e.printStackTrace();
	}
}

private void export(String node)
{
	IEclipsePreferences pref = DefaultScope.INSTANCE.getNode(node);
	
	export(node, pref);
}

private void export(String node, IEclipsePreferences pref)
{
	try {
		OutputStream output = new FileOutputStream(new File("d:/suren/", node)){

			@Override
			public void write(int b) throws IOException {
				System.out.println("1");
				super.write(b);
			}};
		PreferencesService.getDefault().exportPreferences(pref,
				output, null);
		
		output.close();
	} catch (FileNotFoundException | CoreException e) {
		e.printStackTrace();
	} catch (IOException e) {
		e.printStackTrace();
	}
}
[/codesyntax] 从上面的代码可以看出来,一个插件所有的配置项是以上三个作用域里的值的集合。另外,默认值其实是不需要导出的。
  • 扩展点 org.eclipse.ui.preferencePages
上面的首选项扩展点只是简单的保存一些基本类型数据,页面也是固定的,那么怎么来自定义页面呢? [codesyntax lang="xml"]
<extension point="org.eclipse.ui.preferencePages">
	<page category="org.suren.littlebird.preferences.SuRenPreferencePage"
		class="org.suren.littlebird.preferences.SuRenLoggerPreferencePage"
		id="org.suren.littlebird.preferences.SuRenLoggerPreferencePage"
		name="Logger Bridge">
	</page>
</extension>
<extension point="org.eclipse.ui.preferencePages">
    <page category="org.suren.littlebird.preferences.SuRenPreferencePage"
        class="org.suren.littlebird.preferences.SuRenFileSyncPreferencePage"
        id="org.suren.littlebird.preferences.SuRenFileSyncPreferencePage"
        name="SyncFile">
    </page>
</extension>
[/codesyntax]   下面是页面的实现类: [codesyntax lang="java"]
/**
 *
 */
package org.suren.littlebird.preferences;

import org.eclipse.jface.preference.BooleanFieldEditor;
import org.eclipse.jface.preference.FieldEditorPreferencePage;
import org.eclipse.jface.preference.IntegerFieldEditor;
import org.eclipse.jface.preference.StringFieldEditor;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.ui.IWorkbench;
import org.eclipse.ui.IWorkbenchPreferencePage;
import org.suren.littlebird.Activator;

/**
 * @author suren
 * @since 2015-2-2
 */
public class SuRenLoggerPreferencePage extends FieldEditorPreferencePage
		implements IWorkbenchPreferencePage
{

	public SuRenLoggerPreferencePage()
	{
		super(GRID);
		setPreferenceStore(Activator.getDefault().getPreferenceStore());
		setDescription("Little preference page implementation");
	}

	@Override
	protected void createFieldEditors()
	{
		Composite parent = getFieldEditorParent();

		addField(new StringFieldEditor(PreferenceConstants.P_LOGGER_BRIDGE_IP,
				"Bridge IP : ", parent));
		addField(new IntegerFieldEditor(PreferenceConstants.P_LOGGER_BRIDGE_PORT,
				"Bridge Port : ", parent));
		addField(new StringFieldEditor(PreferenceConstants.P_LOGGER_LAYOUT,
				"Logger Layout : ", parent));
		addField(new BooleanFieldEditor(PreferenceConstants.P_LOGGER_NO_BRIDGE_HIDDEN,
				"Hidden When No Bridge", parent));
		addField(new StringFieldEditor(PreferenceConstants.P_LOGGER_FILTER,
				"Filter : ", parent));
	}

	@Override
	public void init(IWorkbench arg0)
	{
	}

}
[/codesyntax] [codesyntax lang="java"]
package org.suren.littlebird.preferences;

import org.eclipse.jface.preference.PreferencePage;
import org.eclipse.swt.events.SelectionAdapter;
import org.eclipse.swt.events.SelectionEvent;
import org.eclipse.swt.layout.GridData;
import org.eclipse.swt.layout.GridLayout;
import org.eclipse.swt.widgets.Button;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.Control;
import org.eclipse.swt.widgets.Group;
import org.eclipse.swt.widgets.List;
import org.eclipse.ui.IWorkbench;
import org.eclipse.ui.IWorkbenchPreferencePage;
import org.eclipse.ui.dialogs.ContainerSelectionDialog;

/**
 * @author suren
 * @date 2015-4-3
 *
 * http://surenpi.com
 */
public class SuRenFileSyncPreferencePage extends PreferencePage
	implements IWorkbenchPreferencePage
{
	private Button addBut;
	private Button removebut;
	private List	syncList;

	@Override
	public void init(IWorkbench workbench)
	{
	}

	@Override
	protected Control createContents(final Composite parent)
	{
		Group syncListGroup = new Group(parent, 0);
		syncListGroup.setLayoutData(new GridData(4, 4, true, true, 2, 1));
		syncListGroup.setText("SyncFileList");

		GridLayout gridLayout = new GridLayout();
		gridLayout.numColumns = 2;
		syncListGroup.setLayout(gridLayout);

		syncList = new org.eclipse.swt.widgets.List(syncListGroup, 2050);
		syncList.setLayoutData(new GridData(4, 4, true, true, 1, 12));

		this.addBut = new Button(syncListGroup, 0);
		this.addBut.setText("Add");
		this.addBut.addSelectionListener(new SelectionAdapter(){

			@Override
			public void widgetSelected(SelectionEvent e)
			{
				ContainerSelectionDialog dialog = new ContainerSelectionDialog(parent.getShell(), null, true, "");
				if(dialog.open() == ContainerSelectionDialog.OK)
				{
					Object[] result = dialog.getResult();
					if(result != null)
					{
						for(Object path : result)
						{
							syncList.add(path.toString());
						}
					}
				}
			}
		});

		this.removebut = new Button(syncListGroup, 0);
		this.removebut.setText("Remove");
		this.removebut.addSelectionListener(new SelectionAdapter(){

			@Override
			public void widgetSelected(SelectionEvent e)
			{
				syncList.remove(syncList.getSelectionIndices());
			}
		});

		SuRenPref suRenPref = new SuRenPref();
		for(String path : suRenPref.getSyncList())
		{
			syncList.add(path);
		}

		return null;
	}

	@Override
	public boolean performOk()
	{
		String[] syncFileArray = syncList.getItems();

		return new SuRenPref().setSyncList(syncFileArray);
	}
}
[/codesyntax]  
  • 有关Eclipse的配置
Eclipse的配置其实就是首选项,作用域在workspace上的配置信息当然是在workspace目录中的.metadata中保存,全局性的配置(第一次启动时)那就应该是在Eclipse的安装根目录(configuration)中了。 configuration\.settings\org.eclipse.ui.ide.prefs这个文件描述了Eclipse在启动时寻找workspace的信息 下面介绍workspace级别的配置信息: 默认的根目录为workspace\.metadata\.plugins\org.eclipse.core.runtime\.settings org.eclipse.m2e.core.prefs 为m2e插件的配置 org.eclipse.jdt.launching.prefs 为Eclipse中使用的JDK的配置 org.eclipse.wst.server.core.prefs 为Server的配置 org.eclipse.jst.server.tomcat.core.prefs 为Tomcat的配置
  • 参考
http://blog.csdn.net/andywangcn/article/details/8026300

你可能感兴趣的:(workspace)