Skip to main content
summaryrefslogtreecommitdiffstats
blob: 49a55c5db3c2eef89f0a3a2b0499bc132e6aa35d (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
/*******************************************************************************
 * Copyright (c) 2013 BestSolution.at and others.
 * All rights reserved. This program and the accompanying materials
 * are made available under the terms of the Eclipse Public License v1.0
 * which accompanies this distribution, and is available at
 * http://www.eclipse.org/legal/epl-v10.html
 *
 * Contributors:
 *     Tom Schindl<tom.schindl@bestsolution.at> - initial API and implementation
 *******************************************************************************/
package org.eclipse.fx.core.p2;

import org.eclipse.core.runtime.IProgressMonitor;
import org.eclipse.core.runtime.IStatus;
import org.eclipse.core.runtime.NullProgressMonitor;
import org.eclipse.core.runtime.Status;
import org.eclipse.core.runtime.jobs.IJobChangeEvent;
import org.eclipse.core.runtime.jobs.Job;
import org.eclipse.core.runtime.jobs.JobChangeAdapter;
import org.eclipse.equinox.p2.core.IProvisioningAgent;
import org.eclipse.equinox.p2.core.ProvisionException;
import org.eclipse.equinox.p2.operations.ProvisioningSession;
import org.eclipse.equinox.p2.operations.UpdateOperation;
import org.eclipse.fx.core.Callback;
import org.eclipse.fx.core.ReturnValue.State;
import org.eclipse.fx.core.log.Logger;
import org.eclipse.fx.core.log.LoggerFactory;
import org.eclipse.fx.core.update.UpdateService;
import org.osgi.framework.ServiceReference;
import org.eclipse.fx.core.ReturnValue.ReturnValueImpl;

public class UpdateServiceImpl implements UpdateService {
	private Logger logger;
	private LoggerFactory factory;

	static class P2UpdateCheckRV extends ReturnValueImpl<Boolean> implements
			UpdateCheckData {
		public final UpdateOperation updateOperation;
		
		public P2UpdateCheckRV(UpdateOperation updateOperation, State state,
				String message, Boolean value, Throwable throwable) {
			super(state, message, value, throwable);
			this.updateOperation = updateOperation;
		}
	}

	static class P2UpdateRV extends ReturnValueImpl<Boolean> implements
			UpdateData {

		public P2UpdateRV(State state, String message, Boolean value,
				Throwable throwable) {
			super(state, message, value, throwable);
		}
	}

	public void setLoggerFactory(LoggerFactory factory) {
		this.factory = factory;
		if (logger != null) {
			logger = null;
		}
	}

	public void unsetLoggerFactory(LoggerFactory factory) {
		this.factory = null;
		this.logger = null;
	}

	private Logger getLogger() {
		if (logger == null) {
			logger = factory.createLogger(getClass().getName());
		}
		return logger;
	}

	@Override
	public void update(UpdateCheckData data, final Callback<UpdateData> callback) {
		Job job = ((P2UpdateCheckRV) data).updateOperation.getProvisioningJob(new NullProgressMonitor());
		job.addJobChangeListener(new JobChangeAdapter() {
			@Override
			public void done(IJobChangeEvent event) {
				IStatus s = event.getResult();
				State state = fromStatus(s);
				callback.call(new P2UpdateRV(state, s.getMessage(), State.OK == state, s.getException()));
			}
		});
		job.schedule();
	}
	
	private State fromStatus(IStatus s) {
		switch (s.getSeverity()) {
		case IStatus.CANCEL:
			return State.CANCEL;
		case IStatus.ERROR:
			return State.ERROR;
		case IStatus.WARNING:
			return State.WARNING;
		default:
			return State.OK;
		}
	}

	@Override
	public void checkUpdate(final Callback<UpdateCheckData> callback) {
		try {
			IProvisioningAgent agent = getProvisioningAgent();
			final ProvisioningSession session = new ProvisioningSession(agent);
			Job o = new Job("Check for Updates") {
				
				@Override
				protected IStatus run(IProgressMonitor monitor) {
					UpdateOperation o = new UpdateOperation(session);
					IStatus s = o.resolveModal(monitor);
					State state = fromStatus(s);
					callback.call(new P2UpdateCheckRV(o, state, s.getMessage(), state == State.OK,s.getException()));
					return Status.OK_STATUS;
				}
			};
			o.schedule();
		} catch (ProvisionException e) {
			getLogger().error(e.getMessage(), e);
			callback.call(new P2UpdateCheckRV(null, State.ERROR,"Failure while try to collect updateable units", null, e));
		}
	}

	private IProvisioningAgent getProvisioningAgent() throws ProvisionException {
		ServiceReference<?> reference = Activator.getContext()
				.getServiceReference(IProvisioningAgent.SERVICE_NAME);
		IProvisioningAgent agent = (IProvisioningAgent) Activator.getContext()
				.getService(reference);
		return agent;
	}

// TODO enable forced update support in future	
//	protected IQueryable<IInstallableUnit> collectUpdateableUnits(
//			IProvisioningAgent agent, final IProgressMonitor monitor)
//			throws ProvisionException {
//		IRepositoryManager<?> manager = (IRepositoryManager<?>) agent
//				.getService(IMetadataRepositoryManager.class.getName());
//
//		// Get update site uri's from p2.inf.
//
//		final StringBuffer siteUrlPackage = new StringBuffer();
//
//		URI[] uris = manager
//				.getKnownRepositories(IRepositoryManager.REPOSITORIES_ALL);
//
//		if (uris.length == 0) {
//			getLogger().warning("no update repositories found");
//		} else {
//			for (URI uri : uris) {
//				if (siteUrlPackage.length() > 0) {
//					siteUrlPackage.append(",");
//				}
//				// LOGGER.info( "uri found: " + uri.toString() );
//				siteUrlPackage.append(uri.toString());
//			}
//		}
//
//		if (siteUrlPackage == null || siteUrlPackage.toString().isEmpty()) {
//			throw new IllegalStateException(
//					"No site URL specified. Edit your p2.inf file.");
//		}
//
//		getLogger().info( "Synch repos: " + siteUrlPackage );
//
//		String[] siteUrlStrings = siteUrlPackage.toString().split(",");
//		URI[] siteURIs = new URI[siteUrlStrings.length];
//		for (int i = 0; i < siteURIs.length; i++) {
//			try {
//				siteURIs[i] = new URI(siteUrlStrings[i]);
//			} catch (URISyntaxException e) {
//				throw new IllegalStateException(e);
//			}
//		}
//
//		// Convert URIs into something we can query...
//		IQueryable<IInstallableUnit> allTheIUs = createIUQueryable(siteURIs,
//				agent, monitor);
//		getLogger().debug("query result: " + allTheIUs);
//
//		return allTheIUs;
//
//	}
//
//	public void installUnits(final IProvisioningAgent agent,
//			IQueryable<IInstallableUnit> allTheIUs, IProgressMonitor monitor) {
//		ProvisioningSession session = new ProvisioningSession(agent);
//		/*
//		 * Query the metadata repository(ies) for the feature(s) to install.
//		 */
//		Collection<IInstallableUnit> toInstall = allTheIUs.query(
//				QueryUtil.createIUGroupQuery(), new NullProgressMonitor())
//				.toUnmodifiableSet();
//		getLogger().info("Everything to synchronize:");
//		logQueryResults(toInstall);
//
//		SynchronizeOperation operation = new SynchronizeOperation(session,
//				toInstall);
//		IStatus opStatus = operation.resolveModal(monitor);
//		if (opStatus.isOK()) {
//			ProvisioningJob job = operation.getProvisioningJob(null);
//			opStatus = job.runModal(monitor);
//			if (opStatus.getSeverity() == IStatus.CANCEL)
//				throw new OperationCanceledException();
//		}
//	}
//
//	private void logQueryResults(Collection<IInstallableUnit> toInstall) {
//		if (getLogger().isEnabled(Level.DEBUG)) {
//			StringBuffer iuNames = new StringBuffer("IUs:\n\n ");
//			for (IInstallableUnit iu : toInstall) {
//				iuNames.append(iu.getId() + iu.getVersion() + "\n ");
//			}
//			getLogger().debug(iuNames.toString());
//		}
//	}
//
//	private IQueryable<IInstallableUnit> createIUQueryable(URI[] p2Sites,
//			IProvisioningAgent agent, IProgressMonitor monitor)
//			throws ProvisionException {
//		IMetadataRepositoryManager metadataManager = (IMetadataRepositoryManager) agent
//				.getService(IMetadataRepositoryManager.SERVICE_NAME);
//		IArtifactRepositoryManager artifactManager = (IArtifactRepositoryManager) agent
//				.getService(IArtifactRepositoryManager.SERVICE_NAME);
//
//		final Collection<IMetadataRepository> metadataReposList = new LinkedList<IMetadataRepository>();
//		for (URI uri : p2Sites) {
//			getLogger().debug("Adding metadata repo at: " + uri.toString());
//			try {
//				IMetadataRepository metadataRepo = metadataManager
//						.loadRepository(uri, monitor);
//				getLogger().debug(
//						"metadata repository loaded: " + uri.toString());
//				try {
//					artifactManager.loadRepository(uri, monitor); // load the
//																	// repo:
//																	// this
//																	// makes it
//																	// available
//																	// to us
//					metadataReposList.add(metadataRepo);
//				} catch (NullPointerException e) {
//					getLogger()
//							.warning(
//									"Repository " + uri
//											+ " not found, will be ignored", e);
//				}
//			} catch (ProvisionException e) {
//				if (e.getStatus().getCode() == ProvisionException.REPOSITORY_NOT_FOUND) {
//					getLogger()
//							.warning(
//									"Repository " + uri
//											+ " not found, will be ignored");
//				} else {
//					getLogger()
//							.warning(
//									"ProvisionException code="
//											+ e.getStatus().getCode()
//											+ ", return none");
//					throw e;
//				}
//			} catch (OperationCanceledException e) {
//				getLogger().warning("OperationCanceledException, return none");
//				throw e;
//			}
//		}
//		if (metadataReposList.isEmpty()) {
//			getLogger().debug("seems to be correct, return NONE");
//			return null;
//		} else {
//			getLogger().debug("seems to be correct, return SOME");
//			return QueryUtil.compoundQueryable(metadataReposList);
//		}
//	}
//	private Collection<IInstallableUnit> getInstalledIUs() {
//		IProfile profile = session.getProfileRegistry().getProfile(profileId);
//		if (profile == null)
//			return CollectionUtils.emptyList();
//		IQuery<IInstallableUnit> query = new UserVisibleRootQuery();
//		IQueryResult<IInstallableUnit> queryResult = profile.query(query, null);
//		return queryResult.toUnmodifiableSet();
//	}
}

Back to the top