`
popjxc
  • 浏览: 67650 次
  • 性别: Icon_minigender_1
  • 来自: 北京
社区版块
存档分类
最新评论

eclipse RCP自动更新利器----p2

阅读更多

最近基于eclipse 3.6开发RCP程序,不借用eclipse的更新UI,而是在程序启动时自动检查更新,也就是所谓的headless update.


其实这是很简单的,利用eclipse wiki上的一段代码就可以搞定,如下:

 

 

public class P2Util {

	static final String JUSTUPDATED = "update_flag"; //$NON-NLS-1$

	public static void headlessUpdate() {
		// update when startup
		final IProvisioningAgent agent = (IProvisioningAgent) ServiceHelper
				.getService(Activator.bundleContext,
						IProvisioningAgent.SERVICE_NAME);
		addSites(agent);
		if (agent == null) {
			LogHelper.log(new Status(IStatus.ERROR, Activator.PLUGIN_ID,
					Messages.getString("UpdateChecker.1"))); //$NON-NLS-1$
		}
		// XXX if we're restarting after updating, don't check again.
		final IPreferenceStore prefStore = Activator.getDefault()
				.getPreferenceStore();
		if (prefStore.getBoolean(JUSTUPDATED)) {
			prefStore.setValue(JUSTUPDATED, false);
			return;
		}

		// XXX check for updates before starting up.
		// If an update is performed, restart. Otherwise log
		// the status.
		final IRunnableWithProgress runnable = new IRunnableWithProgress() {
			public void run(IProgressMonitor monitor)
					throws InvocationTargetException, InterruptedException {
				IStatus updateStatus = P2Util.checkForUpdates(agent, monitor);
				if (updateStatus.getCode() == UpdateOperation.STATUS_NOTHING_TO_UPDATE) {
					 PlatformUI.getWorkbench().getDisplay()
					   .asyncExec(new Runnable() {
					   public void run() {
					   MessageDialog.openInformation(null,
					   "Updates", "No updates were found");
					   }
					 });
					
				} else if (updateStatus.getSeverity() != IStatus.ERROR) {
					prefStore.setValue(JUSTUPDATED, true);
					Display.getDefault().asyncExec(new Runnable() {

						@Override
						public void run() {
							PlatformUI.getWorkbench().restart();
						}
					});
				} else {
					LogHelper.log(updateStatus);
				}
			}
		};
		Display.getDefault().asyncExec(new Runnable() {

			@Override
			public void run() {
				try {
					new ProgressMonitorDialog(null).run(true, true, runnable);
				} catch (InvocationTargetException e) {
					e.printStackTrace();
				} catch (InterruptedException e) {
				}
			}
		});
	}

	// XXX Check for updates to this application and return a status.
	public static IStatus checkForUpdates(IProvisioningAgent agent,
			IProgressMonitor monitor) throws OperationCanceledException {
		ProvisioningSession session = new ProvisioningSession(agent);

		// the default update operation looks for updates to the currently
		// running profile, using the default profile root marker. To change
		// which installable units are being updated, use the more detailed
		// constructors.
		UpdateOperation operation = new UpdateOperation(session);
		SubMonitor sub = SubMonitor.convert(monitor,
				Messages.getString("P2Util.0"), 200); //$NON-NLS-1$
		IStatus status = operation.resolveModal(sub.newChild(100));
		if (status.getCode() == UpdateOperation.STATUS_NOTHING_TO_UPDATE) {
			return status;
		}
		if (status.getSeverity() == IStatus.CANCEL)
			throw new OperationCanceledException();

		if (status.getSeverity() != IStatus.ERROR) {
			// More complex status handling might include showing the user what
			// updates
			// are available if there are multiples, differentiating patches vs.
			// updates, etc.
			// In this example, we simply update as suggested by the operation.
			try {
				ProvisioningJob job = operation.getProvisioningJob(null);
				status = job.runModal(sub.newChild(100));
			} catch (Exception e) {
				throw new OperationCanceledException();
			}
			if (status.getSeverity() == IStatus.CANCEL)
				throw new OperationCanceledException();
		}
		return status;
	}
}

 

 

 

为了让程序在启动时执行这段更新代码,我们可以实现IStartup扩展点,来启动更新检查:

 

 

public class UpdateChecker implements IStartup {

	@Override
	public void earlyStartup() {
		P2Util.headlessUpdate();
	}

}

 

 

 

最后说一下更新站点地址的配置,一般情况下,eclipse是在一个p2.inf文件中配置的,这里就不多说了,因为这种方式不够灵活,p2.inf文件是在插件jar包里的,不便于用户修改,并且一旦更新地址发生变化,也不变程序自动适配。

这里我们用xml配置更新地址,可以随意添加多个,兼容性更加强一些。

xml格式很简单,如下:

 

 

<?xml version="1.0" encoding="UTF-8"?>
<sites>
	<site name="sample1" url="http://popjxc.iteye.com/update1"/>
        <site name="sample2" url="http://popjxc.iteye.com/update2"/>
</sites>
 

然后读取xml,并添加更新站点,需要在P2Util类里添加下面两个函数:

 

 

private static void addSites(IProvisioningAgent provisioningAgent) {
		SAXReader saxReader = new SAXReader();
		Document document = null;
		try {
			document = saxReader.read(new File(getUpdateSiteFile()));
			Element root = document.getRootElement();
			Iterator<?> it = root.elementIterator("site");
			String name;
			String url;
			while(it.hasNext()) {
				Element e = (Element)it.next();
				name = e.attributeValue("name");
				url = e.attributeValue("url");
				addUpdateSite(provisioningAgent, url, name);
			}
		} catch (Exception e) {
			e.printStackTrace();
			ExceptionManager.logError(e, e.getMessage());
		}
	}

	private static void addUpdateSite(IProvisioningAgent provisioningAgent, String url, String name)
			throws InvocationTargetException {
		// Load repository manager
		IMetadataRepositoryManager metadataManager = (IMetadataRepositoryManager) provisioningAgent
				.getService(IMetadataRepositoryManager.SERVICE_NAME);
		if (metadataManager == null) {
			LogMessage.logInfo("Metadata manager was null");
			Throwable throwable = new Throwable(
					"Could not load Metadata Repository Manager");
			throwable.fillInStackTrace();
			throw new InvocationTargetException(throwable);
		}

		// Load artifact manager
		IArtifactRepositoryManager artifactManager = (IArtifactRepositoryManager) provisioningAgent
				.getService(IArtifactRepositoryManager.SERVICE_NAME);
		if (artifactManager == null) {
			LogMessage.logInfo("Artifact manager was null");
			Throwable throwable = new Throwable(
					"Could not load Artifact Repository Manager");
			throwable.fillInStackTrace();
			throw new InvocationTargetException(throwable);
		}

		// Load repo
		try {
			URI repoLocation = new URI(url);
			LogMessage.logInfo("Adding repository " + repoLocation);
			metadataManager.loadRepository(repoLocation, null);
			artifactManager.loadRepository(repoLocation, null);
		} catch (ProvisionException pe) {
			LogMessage.logError("Caught provisioning exception " + pe.getMessage(), pe);
			throw new InvocationTargetException(pe);
		} catch (URISyntaxException e) {
			LogMessage.logError("Caught URI syntax exception " + e.getMessage(), e);
			throw new InvocationTargetException(e);
		}
	}
	private static String getUpdateSiteFile() {
		String path = System.getProperty("user.dir");
		path += "/configuration/UpdateSite.xml";
		return path;
	}

 

 

3
0
分享到:
评论
9 楼 kc284463759 2014-05-28  
jjyy552211@qq.com,希望能得到源码,多谢
8 楼 peixingchen 2012-12-03  
有些配置还没清楚,能给源代码源代码吗?QQ:117310722,请发QQ邮箱
7 楼 popjxc 2012-11-08  
chenqisdfx 写道
好像不行啊,在new出agent后我调用addsites(),但是在IMetadataRepositoryManager metadataManager = (IMetadataRepositoryManager) provisioningAgent  
                .getService(IMetadataRepositoryManager.SERVICE_NAME);  出错,metaDataManager总是为空。敢问能给解释以下否???

或者QQ : 36396743

chenqisdfx@163.com



抱歉各位, 本人已不做java好久了。
给各位两点建议:
1. 确认getUpdateSiteFile()得到的configuration/UpdateSite.xml文件一定要存在。
2. 在headlessUpdate()中得到agent对象后,要调用addSites(agent)。 千万不要new出agent!
6 楼 liangqiming 2012-11-03  
代码似乎不是很完整吧,可否看下完整代码,如方便可以加QQ 568428154,或者是发送完整源码到568628154@qq.com
5 楼 qq123zhz 2012-06-15  
我也没有成功,求源码例子,qq123zhz@gmail.com
4 楼 chenqisdfx 2011-09-29  
好像不行啊,在new出agent后我调用addsites(),但是在IMetadataRepositoryManager metadataManager = (IMetadataRepositoryManager) provisioningAgent  
                .getService(IMetadataRepositoryManager.SERVICE_NAME);  出错,metaDataManager总是为空。敢问能给解释以下否???

或者QQ : 36396743

chenqisdfx@163.com
3 楼 liuhuanleijava 2011-09-15  
加Q 308834143 验证身份那写:rcp ,详细讨论下
2 楼 xiehongdong 2011-05-04  
能不能把源码发出来看下啊,我的邮箱hongdongxie2008@163.com

先谢谢了……
1 楼 tianlihu 2011-04-04  
能说的更清楚一些吗?

相关推荐

    eclipse-rcp-2022-06-R-win32-x86_64.zip

    Eclipse IDE for RCP and RAP Developers(eclipse-rcp-2022-06-R-win32-x86_64.zip) 适用于Windows x86_64: A complete set of tools for developers who want to create Eclipse plug-ins, Rich Client ...

    eclipse-rcp-2022-06-R-linux-gtk-x86_64.tar.gz

    Eclipse IDE for RCP and RAP Developers(eclipse-rcp-2022-06-R-linux-gtk-x86_64.tar.gz) 适用于Linux x86_64: A complete set of tools for developers who want to create Eclipse plug-ins, Rich Client ...

    eclipse-rcp-juno-SR2-win32-x86_64.zip

    这个"eclipse-rcp-juno-SR2-win32-x86_64.zip"是一个针对Windows 64位系统的Eclipse RCP开发环境的打包文件,版本为Juno Service Release 2 (SR2)。Eclipse Juno是Eclipse IDE的第四个主要版本,发布于2012年,包含...

    eclipse-rcp-indigo-SR2-win32-x86_64

    "eclipse-rcp-indigo-SR2-win32-x86_64"是一个特定版本的Eclipse RCP平台,适用于Windows 64位操作系统。"Indigo"是Eclipse的版本代号,而"SR2"表示第二个服务释放(Service Release),意味着它是Indigo主版本的一...

    eclipse-rcp-2022-06-R-macosx-cocoa-x86_64.dmg

    Eclipse IDE for RCP and RAP Developers(eclipse-rcp-2022-06-R-macosx-cocoa-x86_64.dmg) 适用于macOS x86_64: A complete set of tools for developers who want to create Eclipse plug-ins, Rich Client ...

    eclipse-rcp-2023-12-R-linux-gtk-x86-64.tar.gz

    eclipse-rcp-2023-12-R-linux-gtk-x86_64.tar.gz 适用于Linux x86_64位系统

    eclipse-RCP-3.1.1-win32.zip

    这个“eclipse-RCP-3.1.1-win32.zip”文件是一个专门为Windows操作系统编译的Eclipse RCP版本,版本号为3.1.1。在本文中,我们将深入探讨Eclipse RCP、JFace和SWT,以及如何使用这个压缩包进行开发工作。 Eclipse ...

    Eclipse Rcp

    Eclipse RCP是一种基于Eclipse平台的富客户端平台技术,它允许开发者创建独立于Eclipse环境的Java桌面应用程序。RCP通过提供一套标准组件和API,简化了桌面应用程序的开发流程,使开发者能够专注于业务逻辑而非界面...

    RCP 开发工具 eclipse-rcp-2020-06-R-linux-x86

    这个"eclipse-rcp-2020-06-R-linux-x86"压缩包包含的"Eclipse"文件可能是Eclipse RCP的安装程序,安装后开发者将得到一个完整的开发环境,可以开始构建和调试基于Eclipse RCP的桌面应用程序。在Linux x86(AMD)平台...

    eclipse-rcp-kepler-SR2-win32-x86_64.zip

    这个“eclipse-rcp-kepler-SR2-win32-x86_64.zip”文件是Eclipse RCP的一个特定版本,适用于Windows操作系统,且是64位架构。Kepler是Eclipse IDE的第四个主要版本,发布于2013年,而SR2代表Service Release 2,是该...

    eclipse-rcp-2023-12-R-win32-x86-64.zip

    eclipse-rcp-2023-12-R-win32-x86_64.zip 适用于Windows系统

    eclipse-rcp-2022-06-R-linux-gtk-aarch64.tar.gz

    Eclipse IDE for RCP and RAP Developers(eclipse-rcp-2022-06-R-linux-gtk-aarch64.tar.gz) 适用于Linux aarch64: A complete set of tools for developers who want to create Eclipse plug-ins, Rich Client ...

    eclipse-rcp-2022-06-R-macosx-cocoa-aarch64.dmg

    Eclipse IDE for RCP and RAP Developers(eclipse-rcp-2022-06-R-macosx-cocoa-aarch64.dmg) 适用于macOS aarch64: A complete set of tools for developers who want to create Eclipse plug-ins, Rich Client ...

    eclipse-rcp-2023-12-R-linux-gtk-aarch64.tar.gz

    在2023年的最新版本"eclipse-rcp-2023-12-R"中,Eclipse团队为Linux ARM架构的用户带来了专门的版本——"linux-gtk-aarch64",这表明Eclipse RCP已经充分考虑到了多样化的硬件平台需求。 1. **Eclipse RCP核心特性*...

    eclipse-rcp-2023-09-R-linux-gtk-x86-64.tar.gz

    本压缩包“eclipse-rcp-2023-09-R-linux-gtk-x86_64.tar.gz”是专为Linux x86_64架构设计的版本,包含了最新的Eclipse RCP开发环境。 首先,我们要理解Linux x86_64,这代表了64位的Linux操作系统。与32位系统相比...

    eclipse-java-2024-03-R-win32-x86-64.zip

    4. **构建工具**:Eclipse内建的构建系统可以与Ant或Maven集成,帮助开发者自动化构建过程,包括编译、打包、测试和部署。 5. **调试器**:Eclipse的Java调试器提供了强大的断点、变量查看、调用堆栈分析等功能,...

    eclipse-jee-2018-09-win32-x86_64.zip

    8. **RCP和RAP框架**:Eclipse Rich Client Platform (RCP) 和 Rich Ajax Platform (RAP)允许开发人员构建自己的桌面应用程序和Web应用,2018-09版本可能包含相关更新和改进。 9. **持续集成**:Eclipse与Jenkins、...

    eclipse-committers-2022-06-R-win32-x86_64.zip

    Eclipse IDE for Eclipse Committers(eclipse-committers-2022-06-R-win32-x86_64.zip) 适用于Windows x86_64: Package suited for development of Eclipse itself at Eclipse.org; based on the Eclipse ...

    eclipse-rcp-europa-winter-win32.zip

    "eclipse-rcp-europa-winter-win32.zip"是一个面向Windows 32位操作系统的Eclipse RCP开发环境的发行版,属于Europa Winter版本。 Europa是Eclipse的2007年发布系列,包含了一系列集成开发环境(IDE)和工具平台的...

    eclipse-rcp-2023-12-R-macosx-cocoa-aarch64.dmg

    eclipse-rcp-2023-12-R-macosx-cocoa-aarch64.dmg 适用于macOS Arm芯片系统

Global site tag (gtag.js) - Google Analytics