Convert to the generic IProvisioningAgent.getService()

Take 2.

Change-Id: Ia6b32d8b27efbf30d7d7bd620c84e0b9e48f843a
Signed-off-by: Alexander Kurtakov <akurtako@redhat.com>
diff --git a/bundles/org.eclipse.equinox.p2.director.app/src/org/eclipse/equinox/internal/p2/director/app/DirectorApplication.java b/bundles/org.eclipse.equinox.p2.director.app/src/org/eclipse/equinox/internal/p2/director/app/DirectorApplication.java
index efb01fb..fad832d 100644
--- a/bundles/org.eclipse.equinox.p2.director.app/src/org/eclipse/equinox/internal/p2/director/app/DirectorApplication.java
+++ b/bundles/org.eclipse.equinox.p2.director.app/src/org/eclipse/equinox/internal/p2/director/app/DirectorApplication.java
@@ -1263,7 +1263,7 @@
 
 	@Override
 	public void stop() {
-		IProvisioningEventBus eventBus = (IProvisioningEventBus) targetAgent.getService(IProvisioningEventBus.class);
+		IProvisioningEventBus eventBus = targetAgent.getService(IProvisioningEventBus.class);
 		if (eventBus != null) {
 			eventBus.removeListener(this);
 		}
diff --git a/bundles/org.eclipse.equinox.p2.engine/src/org/eclipse/equinox/internal/p2/engine/DownloadManager.java b/bundles/org.eclipse.equinox.p2.engine/src/org/eclipse/equinox/internal/p2/engine/DownloadManager.java
index 6fc28a2..cc92385 100644
--- a/bundles/org.eclipse.equinox.p2.engine/src/org/eclipse/equinox/internal/p2/engine/DownloadManager.java
+++ b/bundles/org.eclipse.equinox.p2.engine/src/org/eclipse/equinox/internal/p2/engine/DownloadManager.java
@@ -32,7 +32,7 @@
 
 	/**
 	 * This Comparator sorts the repositories such that local repositories are first.
-	 * TODO: This is copied from the ProvisioningContext class. Can we combine them? 
+	 * TODO: This is copied from the ProvisioningContext class. Can we combine them?
 	 * See https://bugs.eclipse.org/335153.
 	 */
 	private static final Comparator<IArtifactRepository> LOCAL_FIRST_COMPARATOR = new Comparator<IArtifactRepository>() {
@@ -66,8 +66,8 @@
 
 	public void add(IArtifactRequest[] toAdd) {
 		Assert.isNotNull(toAdd);
-		for (int i = 0; i < toAdd.length; i++) {
-			add(toAdd[i]);
+		for (IArtifactRequest element : toAdd) {
+			add(element);
 		}
 	}
 
@@ -134,7 +134,7 @@
 	}
 
 	private void publishDownloadEvent(CollectEvent event) {
-		IProvisioningEventBus bus = (IProvisioningEventBus) agent.getService(IProvisioningEventBus.SERVICE_NAME);
+		IProvisioningEventBus bus = agent.getService(IProvisioningEventBus.class);
 		if (bus != null)
 			bus.publishEvent(event);
 	}
diff --git a/bundles/org.eclipse.equinox.p2.engine/src/org/eclipse/equinox/internal/p2/engine/Engine.java b/bundles/org.eclipse.equinox.p2.engine/src/org/eclipse/equinox/internal/p2/engine/Engine.java
index 49b7819..c752aa2 100644
--- a/bundles/org.eclipse.equinox.p2.engine/src/org/eclipse/equinox/internal/p2/engine/Engine.java
+++ b/bundles/org.eclipse.equinox.p2.engine/src/org/eclipse/equinox/internal/p2/engine/Engine.java
@@ -58,8 +58,8 @@
 		checkArguments(iprofile, phaseSet, operands);
 		if (operands.length == 0)
 			return Status.OK_STATUS;
-		SimpleProfileRegistry profileRegistry = (SimpleProfileRegistry) agent.getService(IProfileRegistry.SERVICE_NAME);
-		IProvisioningEventBus eventBus = (IProvisioningEventBus) agent.getService(IProvisioningEventBus.SERVICE_NAME);
+		SimpleProfileRegistry profileRegistry = (SimpleProfileRegistry) agent.getService(IProfileRegistry.class);
+		IProvisioningEventBus eventBus = agent.getService(IProvisioningEventBus.class);
 
 		if (context == null)
 			context = new ProvisioningContext(agent);
diff --git a/bundles/org.eclipse.equinox.p2.engine/src/org/eclipse/equinox/internal/p2/engine/EngineSession.java b/bundles/org.eclipse.equinox.p2.engine/src/org/eclipse/equinox/internal/p2/engine/EngineSession.java
index 72ddb75..b23db1e 100644
--- a/bundles/org.eclipse.equinox.p2.engine/src/org/eclipse/equinox/internal/p2/engine/EngineSession.java
+++ b/bundles/org.eclipse.equinox.p2.engine/src/org/eclipse/equinox/internal/p2/engine/EngineSession.java
@@ -7,7 +7,7 @@
  *  https://www.eclipse.org/legal/epl-2.0/
  *
  *  SPDX-License-Identifier: EPL-2.0
- * 
+ *
  *  Contributors:
  *     IBM Corporation - initial API and implementation
  *******************************************************************************/
@@ -227,7 +227,7 @@
 		MultiStatus result = new MultiStatus(EngineActivator.ID, IStatus.OK, null, null);
 		SubMonitor sub = SubMonitor.convert(monitor, 10 + 10 + 10 * actionRecords.size());
 		try {
-			phase.actionManager = (ActionManager) agent.getService(ActionManager.SERVICE_NAME);
+			phase.actionManager = agent.getService(ActionManager.class);
 
 			if (!currentPhaseActive)
 				phase.prePerform(result, this, sub.newChild(10));
diff --git a/bundles/org.eclipse.equinox.p2.engine/src/org/eclipse/equinox/internal/p2/engine/Phase.java b/bundles/org.eclipse.equinox.p2.engine/src/org/eclipse/equinox/internal/p2/engine/Phase.java
index dac10e7..0071a1d 100644
--- a/bundles/org.eclipse.equinox.p2.engine/src/org/eclipse/equinox/internal/p2/engine/Phase.java
+++ b/bundles/org.eclipse.equinox.p2.engine/src/org/eclipse/equinox/internal/p2/engine/Phase.java
@@ -7,7 +7,7 @@
  *  https://www.eclipse.org/legal/epl-2.0/
  *
  *  SPDX-License-Identifier: EPL-2.0
- * 
+ *
  *  Contributors:
  *     IBM Corporation - initial API and implementation
  *     Landmark Graphics Corporation - bug 397183
@@ -76,7 +76,7 @@
 	}
 
 	private void broadcastPhaseEvent(EngineSession session, Operand[] operands, int type) {
-		IProvisioningEventBus bus = (IProvisioningEventBus) session.getAgent().getService(IProvisioningEventBus.SERVICE_NAME);
+		IProvisioningEventBus bus = session.getAgent().getService(IProvisioningEventBus.class);
 		if (bus != null) {
 			bus.publishEvent(getPhaseEvent(operands, type));
 		}
@@ -270,8 +270,7 @@
 			}
 			operandParameters = Collections.unmodifiableMap(operandParameters);
 		}
-		for (int j = 0; j < actions.length; j++) {
-			ProvisioningAction action = actions[j];
+		for (ProvisioningAction action : actions) {
 			Map<String, Object> parameters = operandParameters;
 			Touchpoint touchpoint = action.getTouchpoint();
 			if (touchpoint != null) {
diff --git a/bundles/org.eclipse.equinox.p2.engine/src/org/eclipse/equinox/internal/p2/engine/PhaseSet.java b/bundles/org.eclipse.equinox.p2.engine/src/org/eclipse/equinox/internal/p2/engine/PhaseSet.java
index 970228f..88a289f 100644
--- a/bundles/org.eclipse.equinox.p2.engine/src/org/eclipse/equinox/internal/p2/engine/PhaseSet.java
+++ b/bundles/org.eclipse.equinox.p2.engine/src/org/eclipse/equinox/internal/p2/engine/PhaseSet.java
@@ -7,7 +7,7 @@
  *  https://www.eclipse.org/legal/epl-2.0/
  *
  *  SPDX-License-Identifier: EPL-2.0
- * 
+ *
  *  Contributors:
  *     IBM Corporation - initial API and implementation
  *******************************************************************************/
@@ -45,7 +45,7 @@
 					return status;
 				}
 				Phase phase = phases[i];
-				phase.actionManager = (ActionManager) session.getAgent().getService(ActionManager.SERVICE_NAME);
+				phase.actionManager = session.getAgent().getService(ActionManager.class);
 				try {
 					phase.perform(status, session, operands, pm.newChild(weights[i]));
 				} catch (OperationCanceledException e) {
@@ -103,12 +103,11 @@
 
 	public final IStatus validate(ActionManager actionManager, IProfile profile, Operand[] operands, ProvisioningContext context, IProgressMonitor monitor) {
 		Set<MissingAction> missingActions = new HashSet<>();
-		for (int i = 0; i < phases.length; i++) {
-			Phase phase = phases[i];
+		for (Phase phase2 : phases) {
+			Phase phase = phase2;
 			phase.actionManager = actionManager;
 			try {
-				for (int j = 0; j < operands.length; j++) {
-					Operand operand = operands[j];
+				for (Operand operand : operands) {
 					try {
 						if (!phase.isApplicable(operand))
 							continue;
@@ -148,8 +147,8 @@
 
 	private int getTotalWork(int[] weights) {
 		int sum = 0;
-		for (int i = 0; i < weights.length; i++)
-			sum += weights[i];
+		for (int weight : weights)
+			sum += weight;
 		return sum;
 	}
 
@@ -167,8 +166,8 @@
 
 	private int countApplicable(Phase phase, Operand[] operands) {
 		int count = 0;
-		for (int i = 0; i < operands.length; i++) {
-			if (phase.isApplicable(operands[i]))
+		for (Operand operand : operands) {
+			if (phase.isApplicable(operand))
 				count++;
 		}
 		return count;
diff --git a/bundles/org.eclipse.equinox.p2.engine/src/org/eclipse/equinox/internal/p2/engine/ProfileMetadataRepository.java b/bundles/org.eclipse.equinox.p2.engine/src/org/eclipse/equinox/internal/p2/engine/ProfileMetadataRepository.java
index d84b6a4..65e8abf 100644
--- a/bundles/org.eclipse.equinox.p2.engine/src/org/eclipse/equinox/internal/p2/engine/ProfileMetadataRepository.java
+++ b/bundles/org.eclipse.equinox.p2.engine/src/org/eclipse/equinox/internal/p2/engine/ProfileMetadataRepository.java
@@ -7,7 +7,7 @@
  *  https://www.eclipse.org/legal/epl-2.0/
  *
  *  SPDX-License-Identifier: EPL-2.0
- * 
+ *
  *  Contributors:
  *      IBM Corporation - initial API and implementation
  *******************************************************************************/
@@ -58,7 +58,7 @@
 	private void publishArtifactRepos() {
 		List<URI> artifactRepos = findArtifactRepos();
 
-		IProvisioningEventBus bus = (IProvisioningEventBus) getProvisioningAgent().getService(IProvisioningEventBus.SERVICE_NAME);
+		IProvisioningEventBus bus = getProvisioningAgent().getService(IProvisioningEventBus.class);
 		if (bus == null)
 			return;
 		for (URI repo : artifactRepos) {
diff --git a/bundles/org.eclipse.equinox.p2.engine/src/org/eclipse/equinox/internal/p2/engine/ProfilePreferences.java b/bundles/org.eclipse.equinox.p2.engine/src/org/eclipse/equinox/internal/p2/engine/ProfilePreferences.java
index 70cc804..ecb329b 100644
--- a/bundles/org.eclipse.equinox.p2.engine/src/org/eclipse/equinox/internal/p2/engine/ProfilePreferences.java
+++ b/bundles/org.eclipse.equinox.p2.engine/src/org/eclipse/equinox/internal/p2/engine/ProfilePreferences.java
@@ -58,7 +58,7 @@
 					e.printStackTrace();
 				}
 				//ignore - this means the provisioning agent has already been stopped, and since
-				//this job is joined during agent stop, it means this job has been scheduled after the 
+				//this job is joined during agent stop, it means this job has been scheduled after the
 				//agent stopped and therefore can't have any interesting changes to save
 			} catch (BackingStoreException e) {
 				LogHelper.log(new Status(IStatus.WARNING, EngineActivator.ID, "Exception saving profile preferences", e)); //$NON-NLS-1$
@@ -122,7 +122,7 @@
 	protected void doSave(IProvisioningAgent agent) throws BackingStoreException {
 		synchronized (((ProfilePreferences) parent).profileLock) {
 			String profileId = getProfileIdSegment();
-			IProfileRegistry registry = (IProfileRegistry) agent.getService(IProfileRegistry.SERVICE_NAME);
+			IProfileRegistry registry = agent.getService(IProfileRegistry.class);
 			//can't save anything without a profile registry
 			if (registry == null)
 				return;
@@ -176,8 +176,8 @@
 	private String encodeForFilter(String string) {
 		StringBuilder result = new StringBuilder(string.length());
 		char[] input = string.toCharArray();
-		for (int i = 0; i < input.length; i++) {
-			switch (input[i]) {
+		for (char element : input) {
+			switch (element) {
 				case '(' :
 				case ')' :
 				case '*' :
@@ -185,7 +185,7 @@
 					result.append('\\');
 					//fall through
 				default :
-					result.append(input[i]);
+					result.append(element);
 			}
 		}
 		return result.toString();
@@ -196,7 +196,7 @@
 	 */
 	private IPath getDefaultLocation(IProvisioningAgent agent) {
 		//use engine agent location for preferences if there is no self profile
-		IAgentLocation location = (IAgentLocation) agent.getService(IAgentLocation.SERVICE_NAME);
+		IAgentLocation location = agent.getService(IAgentLocation.class);
 		if (location == null) {
 			LogHelper.log(new Status(IStatus.WARNING, EngineActivator.ID, "Agent location service not available", new RuntimeException())); //$NON-NLS-1$
 			return null;
@@ -257,7 +257,7 @@
 			IProvisioningAgent agent = getAgent(getAgentLocationSegment());
 			if (agent == null)
 				return;
-			IProfileRegistry registry = (IProfileRegistry) agent.getService(IProfileRegistry.SERVICE_NAME);
+			IProfileRegistry registry = agent.getService(IProfileRegistry.class);
 			String profileId = getProfileIdSegment();
 			if (!containsProfile(registry, profileId)) {
 				//use the default location for the self profile, otherwise just do nothing and return
@@ -288,7 +288,7 @@
 	}
 
 	/**
-	 * Schedules the save job. This method is synchronized to protect lazily initialization 
+	 * Schedules the save job. This method is synchronized to protect lazily initialization
 	 * of the save job instance.
 	 */
 	@Override
diff --git a/bundles/org.eclipse.equinox.p2.engine/src/org/eclipse/equinox/internal/p2/engine/ProfileRegistryComponent.java b/bundles/org.eclipse.equinox.p2.engine/src/org/eclipse/equinox/internal/p2/engine/ProfileRegistryComponent.java
index c9445b4..d27ae5b 100644
--- a/bundles/org.eclipse.equinox.p2.engine/src/org/eclipse/equinox/internal/p2/engine/ProfileRegistryComponent.java
+++ b/bundles/org.eclipse.equinox.p2.engine/src/org/eclipse/equinox/internal/p2/engine/ProfileRegistryComponent.java
@@ -7,7 +7,7 @@
  * https://www.eclipse.org/legal/epl-2.0/
  *
  * SPDX-License-Identifier: EPL-2.0
- * 
+ *
  * Contributors:
  *     IBM Corporation - initial API and implementation
  *******************************************************************************/
@@ -26,9 +26,9 @@
 
 	@Override
 	public Object createService(IProvisioningAgent agent) {
-		IAgentLocation location = (IAgentLocation) agent.getService(IAgentLocation.SERVICE_NAME);
+		IAgentLocation location = agent.getService(IAgentLocation.class);
 		SimpleProfileRegistry registry = new SimpleProfileRegistry(agent, SimpleProfileRegistry.getDefaultRegistryDirectory(location));
-		registry.setEventBus((IProvisioningEventBus) agent.getService(IProvisioningEventBus.SERVICE_NAME));
+		registry.setEventBus(agent.getService(IProvisioningEventBus.class));
 		return registry;
 	}
 }
diff --git a/bundles/org.eclipse.equinox.p2.engine/src/org/eclipse/equinox/internal/p2/engine/SurrogateProfileHandler.java b/bundles/org.eclipse.equinox.p2.engine/src/org/eclipse/equinox/internal/p2/engine/SurrogateProfileHandler.java
index 9f910cd..0ff870c 100644
--- a/bundles/org.eclipse.equinox.p2.engine/src/org/eclipse/equinox/internal/p2/engine/SurrogateProfileHandler.java
+++ b/bundles/org.eclipse.equinox.p2.engine/src/org/eclipse/equinox/internal/p2/engine/SurrogateProfileHandler.java
@@ -7,7 +7,7 @@
  *  https://www.eclipse.org/legal/epl-2.0/
  *
  *  SPDX-License-Identifier: EPL-2.0
- * 
+ *
  *  Contributors:
  *      IBM Corporation - initial API and implementation
  *      Ericsson AB - Bug 400011 - [shared] Cleanup the SurrogateProfileHandler code
@@ -60,8 +60,7 @@
 				"profileProperties[$0] == 'true' || (touchpointType != null && touchpointType.id == $1)", //$NON-NLS-1$
 				IProfile.PROP_PROFILE_ROOT_IU, NATIVE_TOUCHPOINT_TYPE);
 		IQueryResult<IInstallableUnit> rootIUs = sharedProfile.query(rootIUQuery, null);
-		for (Iterator<IInstallableUnit> iterator = rootIUs.iterator(); iterator.hasNext();) {
-			IInstallableUnit iu = iterator.next();
+		for (IInstallableUnit iu : rootIUs) {
 			userProfile.addInstallableUnit(iu);
 			userProfile.addInstallableUnitProperties(iu, sharedProfile.getInstallableUnitProperties(iu));
 			userProfile.setInstallableUnitProperty(iu, IProfile.PROP_PROFILE_LOCKED_IU, IU_LOCKED);
@@ -86,8 +85,7 @@
 
 		ArrayList<IRequirement> iuRequirements = new ArrayList<>();
 		IQueryResult<IInstallableUnit> allIUs = sharedProfile.query(QueryUtil.createIUAnyQuery(), null);
-		for (Iterator<IInstallableUnit> iterator = allIUs.iterator(); iterator.hasNext();) {
-			IInstallableUnit iu = iterator.next();
+		for (IInstallableUnit iu : allIUs) {
 			IMatchExpression<IInstallableUnit> iuMatcher = ExpressionUtil.getFactory().matchExpression(ExpressionUtil.parse("id == $0 && version == $1"), iu.getId(), iu.getVersion()); //$NON-NLS-1$
 			iuRequirements.add(MetadataFactory.createRequirement(iuMatcher, null, 0, 1, true));
 		}
@@ -116,7 +114,7 @@
 		File configurationFolder = new File(configurationLocation.getURL().getPath());
 		userProfile.setProperty(IProfile.PROP_CONFIGURATION_FOLDER, configurationFolder.getAbsolutePath());
 
-		// We need to check that the configuration folder is not a file system root. 
+		// We need to check that the configuration folder is not a file system root.
 		// some of the profiles resources are stored as siblings to the configuration folder.
 		// also see bug 230384
 		if (configurationFolder.getParentFile() == null)
@@ -181,7 +179,7 @@
 	 */
 	private void setUpRepos() {
 		//clean old junk
-		IMetadataRepositoryManager metaManager = (IMetadataRepositoryManager) agent.getService(IMetadataRepositoryManager.SERVICE_NAME);
+		IMetadataRepositoryManager metaManager = agent.getService(IMetadataRepositoryManager.class);
 		URI[] knownRepositories = metaManager.getKnownRepositories(IRepositoryManager.REPOSITORIES_LOCAL);
 		for (URI uri : knownRepositories) {
 			if ("true".equals(metaManager.getRepositoryProperty(uri, EngineActivator.P2_FRAGMENT_PROPERTY))) { //$NON-NLS-1$
@@ -189,7 +187,7 @@
 			}
 		}
 
-		IArtifactRepositoryManager artifactManager = (IArtifactRepositoryManager) agent.getService(IArtifactRepositoryManager.SERVICE_NAME);
+		IArtifactRepositoryManager artifactManager = agent.getService(IArtifactRepositoryManager.class);
 		knownRepositories = artifactManager.getKnownRepositories(IRepositoryManager.REPOSITORIES_LOCAL);
 		for (URI uri : knownRepositories) {
 			if ("true".equals(artifactManager.getRepositoryProperty(uri, EngineActivator.P2_FRAGMENT_PROPERTY))) { //$NON-NLS-1$
@@ -226,7 +224,7 @@
 		Set<IInstallableUnit> added = new HashSet<>();
 		for (File extension : extensionLocations) {
 			try {
-				IMetadataRepositoryManager metaManager = (IMetadataRepositoryManager) agent.getService(IMetadataRepositoryManager.SERVICE_NAME);
+				IMetadataRepositoryManager metaManager = agent.getService(IMetadataRepositoryManager.class);
 				IMetadataRepository repo = metaManager.loadRepository(extension.toURI(), new NullProgressMonitor());
 				Set<IInstallableUnit> installableUnits = repo.query(QueryUtil.createIUAnyQuery(), new NullProgressMonitor()).toUnmodifiableSet();
 				for (IInstallableUnit unit : installableUnits) {
diff --git a/bundles/org.eclipse.equinox.p2.engine/src/org/eclipse/equinox/internal/p2/engine/phases/CertificateChecker.java b/bundles/org.eclipse.equinox.p2.engine/src/org/eclipse/equinox/internal/p2/engine/phases/CertificateChecker.java
index 6123172..61d9626 100644
--- a/bundles/org.eclipse.equinox.p2.engine/src/org/eclipse/equinox/internal/p2/engine/phases/CertificateChecker.java
+++ b/bundles/org.eclipse.equinox.p2.engine/src/org/eclipse/equinox/internal/p2/engine/phases/CertificateChecker.java
@@ -62,7 +62,7 @@
 	}
 
 	private IStatus checkCertificates(SignedContentFactory verifierFactory) {
-		UIServices serviceUI = (UIServices) agent.getService(UIServices.SERVICE_NAME);
+		UIServices serviceUI = agent.getService(UIServices.class);
 		SignedContent content = null;
 		SignerInfo[] signerInfo = null;
 		ArrayList<Certificate> untrusted = new ArrayList<>();
@@ -85,9 +85,9 @@
 			} catch (IOException e) {
 				return new Status(IStatus.ERROR, EngineActivator.ID, Messages.CertificateChecker_SignedContentIOError, e);
 			}
-			for (int i = 0; i < signerInfo.length; i++) {
-				if (!signerInfo[i].isTrusted()) {
-					Certificate[] certificateChain = signerInfo[i].getCertificateChain();
+			for (SignerInfo element : signerInfo) {
+				if (!element.isTrusted()) {
+					Certificate[] certificateChain = element.getCertificateChain();
 					if (!untrusted.contains(certificateChain[0])) {
 						untrusted.add(certificateChain[0]);
 						untrustedChain.add(certificateChain);
@@ -166,8 +166,8 @@
 		}
 		// Anything that was trusted should be removed from the untrusted list
 		if (trustedCertificates != null) {
-			for (int i = 0; i < trustedCertificates.length; i++) {
-				untrusted.remove(trustedCertificates[i]);
+			for (Certificate trustedCertificate : trustedCertificates) {
+				untrusted.remove(trustedCertificate);
 			}
 		}
 
@@ -230,9 +230,9 @@
 	}
 
 	public void add(Object[] toAdd) {
-		for (int i = 0; i < toAdd.length; i++) {
-			if (toAdd[i] instanceof File)
-				add((File) toAdd[i]);
+		for (Object element : toAdd) {
+			if (element instanceof File)
+				add((File) element);
 		}
 	}
 }
diff --git a/bundles/org.eclipse.equinox.p2.engine/src/org/eclipse/equinox/internal/p2/engine/phases/Collect.java b/bundles/org.eclipse.equinox.p2.engine/src/org/eclipse/equinox/internal/p2/engine/phases/Collect.java
index 3ca7c12..da57797 100644
--- a/bundles/org.eclipse.equinox.p2.engine/src/org/eclipse/equinox/internal/p2/engine/phases/Collect.java
+++ b/bundles/org.eclipse.equinox.p2.engine/src/org/eclipse/equinox/internal/p2/engine/phases/Collect.java
@@ -7,7 +7,7 @@
  *  https://www.eclipse.org/legal/epl-2.0/
  *
  *  SPDX-License-Identifier: EPL-2.0
- * 
+ *
  *  Contributors:
  *     IBM Corporation - initial API and implementation
  *     WindRiver - https://bugs.eclipse.org/bugs/show_bug.cgi?id=227372
@@ -100,12 +100,12 @@
 		List<IArtifactRequest> totalArtifactRequests = new ArrayList<>(artifactRequests.size());
 		DownloadManager dm = new DownloadManager(context, agent);
 		for (IArtifactRequest[] requests : artifactRequests) {
-			for (int i = 0; i < requests.length; i++) {
-				dm.add(requests[i]);
-				totalArtifactRequests.add(requests[i]);
+			for (IArtifactRequest request : requests) {
+				dm.add(request);
+				totalArtifactRequests.add(request);
 			}
 		}
-		IProvisioningEventBus bus = (IProvisioningEventBus) agent.getService(IProvisioningEventBus.SERVICE_NAME);
+		IProvisioningEventBus bus = agent.getService(IProvisioningEventBus.class);
 		if (bus != null)
 			bus.publishEvent(new CollectEvent(CollectEvent.TYPE_OVERALL_START, null, context, totalArtifactRequests.toArray(new IArtifactRequest[totalArtifactRequests.size()])));
 		IStatus downloadStatus = dm.start(monitor);
@@ -135,7 +135,7 @@
 	private void firePauseEventToDownloadJobs() {
 		synchronized (this) {
 			if (agent != null) {
-				IProvisioningEventBus bus = (IProvisioningEventBus) agent.getService(IProvisioningEventBus.SERVICE_NAME);
+				IProvisioningEventBus bus = agent.getService(IProvisioningEventBus.class);
 				if (bus != null)
 					bus.publishEvent(new DownloadPauseResumeEvent(isPaused ? DownloadPauseResumeEvent.TYPE_PAUSE : DownloadPauseResumeEvent.TYPE_RESUME));
 			}
diff --git a/bundles/org.eclipse.equinox.p2.engine/src/org/eclipse/equinox/internal/p2/engine/phases/Configure.java b/bundles/org.eclipse.equinox.p2.engine/src/org/eclipse/equinox/internal/p2/engine/phases/Configure.java
index 83e630c..7f85a12 100644
--- a/bundles/org.eclipse.equinox.p2.engine/src/org/eclipse/equinox/internal/p2/engine/phases/Configure.java
+++ b/bundles/org.eclipse.equinox.p2.engine/src/org/eclipse/equinox/internal/p2/engine/phases/Configure.java
@@ -38,7 +38,8 @@
 			String phaseId = (String) parameters.get(PARM_PHASE_ID);
 			IInstallableUnit iu = (IInstallableUnit) parameters.get(PARM_IU);
 			IProvisioningAgent agent = (IProvisioningAgent) parameters.get(PARM_AGENT);
-			((IProvisioningEventBus) agent.getService(IProvisioningEventBus.SERVICE_NAME)).publishEvent(new InstallableUnitEvent(phaseId, true, profile, iu, InstallableUnitEvent.CONFIGURE, getTouchpoint()));
+			agent.getService(IProvisioningEventBus.class).publishEvent(new InstallableUnitEvent(phaseId, true, profile,
+					iu, InstallableUnitEvent.CONFIGURE, getTouchpoint()));
 			return null;
 		}
 
@@ -48,7 +49,8 @@
 			String phaseId = (String) parameters.get(PARM_PHASE_ID);
 			IInstallableUnit iu = (IInstallableUnit) parameters.get(PARM_IU);
 			IProvisioningAgent agent = (IProvisioningAgent) parameters.get(PARM_AGENT);
-			((IProvisioningEventBus) agent.getService(IProvisioningEventBus.SERVICE_NAME)).publishEvent(new InstallableUnitEvent(phaseId, false, profile, iu, InstallableUnitEvent.UNCONFIGURE, getTouchpoint()));
+			agent.getService(IProvisioningEventBus.class).publishEvent(new InstallableUnitEvent(phaseId, false, profile,
+					iu, InstallableUnitEvent.UNCONFIGURE, getTouchpoint()));
 			return null;
 		}
 	}
@@ -61,7 +63,8 @@
 			String phaseId = (String) parameters.get(PARM_PHASE_ID);
 			IInstallableUnit iu = (IInstallableUnit) parameters.get(PARM_IU);
 			IProvisioningAgent agent = (IProvisioningAgent) parameters.get(PARM_AGENT);
-			((IProvisioningEventBus) agent.getService(IProvisioningEventBus.SERVICE_NAME)).publishEvent(new InstallableUnitEvent(phaseId, false, profile, iu, InstallableUnitEvent.CONFIGURE, getTouchpoint()));
+			agent.getService(IProvisioningEventBus.class).publishEvent(new InstallableUnitEvent(phaseId, false, profile,
+					iu, InstallableUnitEvent.CONFIGURE, getTouchpoint()));
 			return null;
 		}
 
@@ -71,7 +74,8 @@
 			String phaseId = (String) parameters.get(PARM_PHASE_ID);
 			IInstallableUnit iu = (IInstallableUnit) parameters.get(PARM_IU);
 			IProvisioningAgent agent = (IProvisioningAgent) parameters.get(PARM_AGENT);
-			((IProvisioningEventBus) agent.getService(IProvisioningEventBus.SERVICE_NAME)).publishEvent(new InstallableUnitEvent(phaseId, true, profile, iu, InstallableUnitEvent.UNCONFIGURE, getTouchpoint()));
+			agent.getService(IProvisioningEventBus.class).publishEvent(new InstallableUnitEvent(phaseId, true, profile,
+					iu, InstallableUnitEvent.UNCONFIGURE, getTouchpoint()));
 			return null;
 		}
 	}
diff --git a/bundles/org.eclipse.equinox.p2.engine/src/org/eclipse/equinox/internal/p2/engine/phases/Install.java b/bundles/org.eclipse.equinox.p2.engine/src/org/eclipse/equinox/internal/p2/engine/phases/Install.java
index 9cf05fa..2ebdfa9 100644
--- a/bundles/org.eclipse.equinox.p2.engine/src/org/eclipse/equinox/internal/p2/engine/phases/Install.java
+++ b/bundles/org.eclipse.equinox.p2.engine/src/org/eclipse/equinox/internal/p2/engine/phases/Install.java
@@ -7,7 +7,7 @@
  *  https://www.eclipse.org/legal/epl-2.0/
  *
  *  SPDX-License-Identifier: EPL-2.0
- * 
+ *
  *  Contributors:
  *     IBM Corporation - initial API and implementation
  *******************************************************************************/
@@ -37,7 +37,8 @@
 			String phaseId = (String) parameters.get(PARM_PHASE_ID);
 			IInstallableUnit iu = (IInstallableUnit) parameters.get(PARM_IU);
 			IProvisioningAgent agent = (IProvisioningAgent) parameters.get(PARM_AGENT);
-			((IProvisioningEventBus) agent.getService(IProvisioningEventBus.SERVICE_NAME)).publishEvent(new InstallableUnitEvent(phaseId, true, profile, iu, InstallableUnitEvent.INSTALL, getTouchpoint()));
+			agent.getService(IProvisioningEventBus.class).publishEvent(new InstallableUnitEvent(phaseId, true, profile,
+					iu, InstallableUnitEvent.INSTALL, getTouchpoint()));
 			return null;
 		}
 
@@ -48,7 +49,8 @@
 			IInstallableUnit iu = (IInstallableUnit) parameters.get(PARM_IU);
 			profile.removeInstallableUnit(iu);
 			IProvisioningAgent agent = (IProvisioningAgent) parameters.get(PARM_AGENT);
-			((IProvisioningEventBus) agent.getService(IProvisioningEventBus.SERVICE_NAME)).publishEvent(new InstallableUnitEvent(phaseId, false, profile, iu, InstallableUnitEvent.UNINSTALL, getTouchpoint()));
+			agent.getService(IProvisioningEventBus.class).publishEvent(new InstallableUnitEvent(phaseId, false, profile,
+					iu, InstallableUnitEvent.UNINSTALL, getTouchpoint()));
 			return null;
 		}
 	}
@@ -62,7 +64,8 @@
 			IInstallableUnit iu = (IInstallableUnit) parameters.get(PARM_IU);
 			profile.addInstallableUnit(iu);
 			IProvisioningAgent agent = (IProvisioningAgent) parameters.get(PARM_AGENT);
-			((IProvisioningEventBus) agent.getService(IProvisioningEventBus.SERVICE_NAME)).publishEvent(new InstallableUnitEvent(phaseId, false, profile, iu, InstallableUnitEvent.INSTALL, getTouchpoint()));
+			agent.getService(IProvisioningEventBus.class).publishEvent(new InstallableUnitEvent(phaseId, false, profile,
+					iu, InstallableUnitEvent.INSTALL, getTouchpoint()));
 			return null;
 		}
 
@@ -72,7 +75,8 @@
 			String phaseId = (String) parameters.get(PARM_PHASE_ID);
 			IInstallableUnit iu = (IInstallableUnit) parameters.get(PARM_IU);
 			IProvisioningAgent agent = (IProvisioningAgent) parameters.get(PARM_AGENT);
-			((IProvisioningEventBus) agent.getService(IProvisioningEventBus.SERVICE_NAME)).publishEvent(new InstallableUnitEvent(phaseId, true, profile, iu, InstallableUnitEvent.UNINSTALL, getTouchpoint()));
+			agent.getService(IProvisioningEventBus.class).publishEvent(new InstallableUnitEvent(phaseId, true, profile,
+					iu, InstallableUnitEvent.UNINSTALL, getTouchpoint()));
 			return null;
 		}
 	}
diff --git a/bundles/org.eclipse.equinox.p2.engine/src/org/eclipse/equinox/internal/p2/engine/phases/Unconfigure.java b/bundles/org.eclipse.equinox.p2.engine/src/org/eclipse/equinox/internal/p2/engine/phases/Unconfigure.java
index 7f0a31b..9915266 100644
--- a/bundles/org.eclipse.equinox.p2.engine/src/org/eclipse/equinox/internal/p2/engine/phases/Unconfigure.java
+++ b/bundles/org.eclipse.equinox.p2.engine/src/org/eclipse/equinox/internal/p2/engine/phases/Unconfigure.java
@@ -7,7 +7,7 @@
  *  https://www.eclipse.org/legal/epl-2.0/
  *
  *  SPDX-License-Identifier: EPL-2.0
- * 
+ *
  *  Contributors:
  *     IBM Corporation - initial API and implementation
  *     Wind River - ongoing development
@@ -37,7 +37,8 @@
 			String phaseId = (String) parameters.get(PARM_PHASE_ID);
 			IInstallableUnit iu = (IInstallableUnit) parameters.get(PARM_IU);
 			IProvisioningAgent agent = (IProvisioningAgent) parameters.get(PARM_AGENT);
-			((IProvisioningEventBus) agent.getService(IProvisioningEventBus.SERVICE_NAME)).publishEvent(new InstallableUnitEvent(phaseId, true, profile, iu, InstallableUnitEvent.UNCONFIGURE, getTouchpoint()));
+			agent.getService(IProvisioningEventBus.class).publishEvent(new InstallableUnitEvent(phaseId, true, profile,
+					iu, InstallableUnitEvent.UNCONFIGURE, getTouchpoint()));
 			return null;
 		}
 
@@ -47,7 +48,8 @@
 			String phaseId = (String) parameters.get(PARM_PHASE_ID);
 			IInstallableUnit iu = (IInstallableUnit) parameters.get(PARM_IU);
 			IProvisioningAgent agent = (IProvisioningAgent) parameters.get(PARM_AGENT);
-			((IProvisioningEventBus) agent.getService(IProvisioningEventBus.SERVICE_NAME)).publishEvent(new InstallableUnitEvent(phaseId, false, profile, iu, InstallableUnitEvent.CONFIGURE, getTouchpoint()));
+			agent.getService(IProvisioningEventBus.class).publishEvent(new InstallableUnitEvent(phaseId, false, profile,
+					iu, InstallableUnitEvent.CONFIGURE, getTouchpoint()));
 			return null;
 		}
 	}
@@ -60,7 +62,8 @@
 			String phaseId = (String) parameters.get(PARM_PHASE_ID);
 			IInstallableUnit iu = (IInstallableUnit) parameters.get(PARM_IU);
 			IProvisioningAgent agent = (IProvisioningAgent) parameters.get(PARM_AGENT);
-			((IProvisioningEventBus) agent.getService(IProvisioningEventBus.SERVICE_NAME)).publishEvent(new InstallableUnitEvent(phaseId, false, profile, iu, InstallableUnitEvent.UNCONFIGURE, getTouchpoint()));
+			agent.getService(IProvisioningEventBus.class).publishEvent(new InstallableUnitEvent(phaseId, false, profile,
+					iu, InstallableUnitEvent.UNCONFIGURE, getTouchpoint()));
 			return null;
 		}
 
@@ -70,7 +73,8 @@
 			String phaseId = (String) parameters.get(PARM_PHASE_ID);
 			IInstallableUnit iu = (IInstallableUnit) parameters.get(PARM_IU);
 			IProvisioningAgent agent = (IProvisioningAgent) parameters.get(PARM_AGENT);
-			((IProvisioningEventBus) agent.getService(IProvisioningEventBus.SERVICE_NAME)).publishEvent(new InstallableUnitEvent(phaseId, true, profile, iu, InstallableUnitEvent.CONFIGURE, getTouchpoint()));
+			agent.getService(IProvisioningEventBus.class).publishEvent(new InstallableUnitEvent(phaseId, true, profile,
+					iu, InstallableUnitEvent.CONFIGURE, getTouchpoint()));
 			return null;
 		}
 	}
diff --git a/bundles/org.eclipse.equinox.p2.engine/src/org/eclipse/equinox/internal/p2/engine/phases/Uninstall.java b/bundles/org.eclipse.equinox.p2.engine/src/org/eclipse/equinox/internal/p2/engine/phases/Uninstall.java
index 36c1859..0b8bfab 100644
--- a/bundles/org.eclipse.equinox.p2.engine/src/org/eclipse/equinox/internal/p2/engine/phases/Uninstall.java
+++ b/bundles/org.eclipse.equinox.p2.engine/src/org/eclipse/equinox/internal/p2/engine/phases/Uninstall.java
@@ -7,7 +7,7 @@
  *  https://www.eclipse.org/legal/epl-2.0/
  *
  *  SPDX-License-Identifier: EPL-2.0
- * 
+ *
  *  Contributors:
  *     IBM Corporation - initial API and implementation
  *******************************************************************************/
@@ -35,7 +35,8 @@
 			String phaseId = (String) parameters.get(PARM_PHASE_ID);
 			IInstallableUnit iu = (IInstallableUnit) parameters.get(PARM_IU);
 			IProvisioningAgent agent = (IProvisioningAgent) parameters.get(PARM_AGENT);
-			((IProvisioningEventBus) agent.getService(IProvisioningEventBus.SERVICE_NAME)).publishEvent(new InstallableUnitEvent(phaseId, true, profile, iu, InstallableUnitEvent.UNINSTALL, getTouchpoint()));
+			agent.getService(IProvisioningEventBus.class).publishEvent(new InstallableUnitEvent(phaseId, true, profile,
+					iu, InstallableUnitEvent.UNINSTALL, getTouchpoint()));
 			return null;
 		}
 
@@ -46,7 +47,8 @@
 			IInstallableUnit iu = (IInstallableUnit) parameters.get(PARM_IU);
 			profile.addInstallableUnit(iu);
 			IProvisioningAgent agent = (IProvisioningAgent) parameters.get(PARM_AGENT);
-			((IProvisioningEventBus) agent.getService(IProvisioningEventBus.SERVICE_NAME)).publishEvent(new InstallableUnitEvent(phaseId, false, profile, iu, InstallableUnitEvent.INSTALL, getTouchpoint()));
+			agent.getService(IProvisioningEventBus.class).publishEvent(new InstallableUnitEvent(phaseId, false, profile,
+					iu, InstallableUnitEvent.INSTALL, getTouchpoint()));
 			return null;
 		}
 	}
@@ -59,7 +61,8 @@
 			IInstallableUnit iu = (IInstallableUnit) parameters.get(PARM_IU);
 			profile.removeInstallableUnit(iu);
 			IProvisioningAgent agent = (IProvisioningAgent) parameters.get(PARM_AGENT);
-			((IProvisioningEventBus) agent.getService(IProvisioningEventBus.SERVICE_NAME)).publishEvent(new InstallableUnitEvent(phaseId, false, profile, iu, InstallableUnitEvent.UNINSTALL, getTouchpoint()));
+			agent.getService(IProvisioningEventBus.class).publishEvent(new InstallableUnitEvent(phaseId, false, profile,
+					iu, InstallableUnitEvent.UNINSTALL, getTouchpoint()));
 			return null;
 		}
 
@@ -69,7 +72,8 @@
 			String phaseId = (String) parameters.get(PARM_PHASE_ID);
 			IInstallableUnit iu = (IInstallableUnit) parameters.get(PARM_IU);
 			IProvisioningAgent agent = (IProvisioningAgent) parameters.get(PARM_AGENT);
-			((IProvisioningEventBus) agent.getService(IProvisioningEventBus.SERVICE_NAME)).publishEvent(new InstallableUnitEvent(phaseId, true, profile, iu, InstallableUnitEvent.INSTALL, getTouchpoint()));
+			agent.getService(IProvisioningEventBus.class).publishEvent(new InstallableUnitEvent(phaseId, true, profile,
+					iu, InstallableUnitEvent.INSTALL, getTouchpoint()));
 			return null;
 		}
 	}
diff --git a/bundles/org.eclipse.equinox.p2.engine/src/org/eclipse/equinox/p2/engine/ProvisioningContext.java b/bundles/org.eclipse.equinox.p2.engine/src/org/eclipse/equinox/p2/engine/ProvisioningContext.java
index 26e8c06..cf36000 100644
--- a/bundles/org.eclipse.equinox.p2.engine/src/org/eclipse/equinox/p2/engine/ProvisioningContext.java
+++ b/bundles/org.eclipse.equinox.p2.engine/src/org/eclipse/equinox/p2/engine/ProvisioningContext.java
@@ -66,27 +66,23 @@
 	/**
 	 * This Comparator sorts the repositories such that local repositories are first
 	 */
-	private static final Comparator<URI> LOCAL_FIRST_COMPARATOR = new Comparator<URI>() {
+	private static final Comparator<URI> LOCAL_FIRST_COMPARATOR = (arg0, arg1) -> {
+		String protocol0 = arg0.getScheme();
+		String protocol1 = arg1.getScheme();
 
-		@Override
-		public int compare(URI arg0, URI arg1) {
-			String protocol0 = arg0.getScheme();
-			String protocol1 = arg1.getScheme();
-
-			if (FILE_PROTOCOL.equals(protocol0) && !FILE_PROTOCOL.equals(protocol1))
-				return -1;
-			if (!FILE_PROTOCOL.equals(protocol0) && FILE_PROTOCOL.equals(protocol1))
-				return 1;
-			return 0;
-		}
+		if (FILE_PROTOCOL.equals(protocol0) && !FILE_PROTOCOL.equals(protocol1))
+			return -1;
+		if (!FILE_PROTOCOL.equals(protocol0) && FILE_PROTOCOL.equals(protocol1))
+			return 1;
+		return 0;
 	};
 
 	/**
-	 * Instructs the provisioning context to follow metadata repository references when 
+	 * Instructs the provisioning context to follow metadata repository references when
 	 * providing queryables for obtaining metadata and artifacts.  When this property is set to
-	 * "true", then metadata repository references that are encountered while loading the 
+	 * "true", then metadata repository references that are encountered while loading the
 	 * specified metadata repositories will be included in the provisioning
-	 * context.  
+	 * context.
 	 *
 	 * @see #getMetadata(IProgressMonitor)
 	 * @see #setMetadataRepositories(URI[])
@@ -157,14 +153,13 @@
 	 * Return an array of loaded artifact repositories.
 	 */
 	private List<IArtifactRepository> getLoadedArtifactRepositories(IProgressMonitor monitor) {
-		IArtifactRepositoryManager repoManager = (IArtifactRepositoryManager) agent.getService(IArtifactRepositoryManager.SERVICE_NAME);
+		IArtifactRepositoryManager repoManager = agent.getService(IArtifactRepositoryManager.class);
 		URI[] repositories = artifactRepositories == null ? repoManager.getKnownRepositories(IRepositoryManager.REPOSITORIES_ALL) : artifactRepositories;
 		Arrays.sort(repositories, LOCAL_FIRST_COMPARATOR);
 
 		List<IArtifactRepository> repos = new ArrayList<>();
 		SubMonitor sub = SubMonitor.convert(monitor, (repositories.length + 1) * 100);
-		for (int i = 0; i < repositories.length; i++) {
-			URI location = repositories[i];
+		for (URI location : repositories) {
 			getLoadedRepository(location, repoManager, repos, sub);
 			// Remove this URI from the list of extra references if it is there.
 			if (referencedArtifactRepositories != null && location != null) {
@@ -202,7 +197,7 @@
 	}
 
 	private Set<IMetadataRepository> getLoadedMetadataRepositories(IProgressMonitor monitor) {
-		IMetadataRepositoryManager repoManager = (IMetadataRepositoryManager) agent.getService(IMetadataRepositoryManager.SERVICE_NAME);
+		IMetadataRepositoryManager repoManager = agent.getService(IMetadataRepositoryManager.class);
 		URI[] repositories = metadataRepositories == null ? repoManager.getKnownRepositories(IRepositoryManager.REPOSITORIES_ALL) : metadataRepositories;
 
 		HashMap<String, IMetadataRepository> repos = new HashMap<>();
@@ -210,10 +205,10 @@
 
 		// Clear out the list of remembered artifact repositories
 		referencedArtifactRepositories = new HashMap<>();
-		for (int i = 0; i < repositories.length; i++) {
+		for (URI repositorie : repositories) {
 			if (sub.isCanceled())
 				throw new OperationCanceledException();
-			loadMetadataRepository(repoManager, repositories[i], repos, shouldFollowReferences(), sub.newChild(100));
+			loadMetadataRepository(repoManager, repositorie, repos, shouldFollowReferences(), sub.newChild(100));
 		}
 		Set<IMetadataRepository> set = new HashSet<>();
 		set.addAll(repos.values());
@@ -247,7 +242,7 @@
 		// We always load artifact repositories referenced by this repository.  We might load
 		// metadata repositories
 		if (references.size() > 0) {
-			IArtifactRepositoryManager artifactManager = (IArtifactRepositoryManager) agent.getService(IArtifactRepositoryManager.SERVICE_NAME);
+			IArtifactRepositoryManager artifactManager = agent.getService(IArtifactRepositoryManager.class);
 			SubMonitor repoSubMon = SubMonitor.convert(sub.newChild(500), 100 * references.size());
 			for (IRepositoryReference ref : references) {
 				try {
@@ -287,7 +282,7 @@
 	/**
 	 * Returns a queryable that can be used to obtain any metadata (installable units)
 	 * that are needed for the provisioning operation.
-	 * 
+	 *
 	 * The provisioning context has a distinct lifecycle, whereby the metadata
 	 * and artifact repositories to be used are determined when the client retrieves
 	 * retrieves the metadata queryable.  Clients should not reset the list of
@@ -340,7 +335,7 @@
 	 * Sets the artifact repositories to consult when performing an operation.
 	 * <p>
 	 * The provisioning context has a distinct lifecycle, whereby the metadata
-	 * and artifact repositories to be used are determined when the client 
+	 * and artifact repositories to be used are determined when the client
 	 * retrieves the metadata queryable.  Clients should not reset the list of
 	 * artifact repository locations once the metadata queryable has been retrieved.
 	 *
@@ -354,7 +349,7 @@
 	 * Sets the metadata repositories to consult when performing an operation.
 	 * <p>
 	 * The provisioning context has a distinct lifecycle, whereby the metadata
-	 * and artifact repositories to be used are determined when the client 
+	 * and artifact repositories to be used are determined when the client
 	 * retrieves the metadata queryable.  Clients should not reset the list of
 	 * metadata repository locations once the metadata queryable has been retrieved.
 	 * @param metadataRepositories the metadata repository locations
diff --git a/bundles/org.eclipse.equinox.p2.garbagecollector/src/org/eclipse/equinox/internal/p2/garbagecollector/Application.java b/bundles/org.eclipse.equinox.p2.garbagecollector/src/org/eclipse/equinox/internal/p2/garbagecollector/Application.java
index 160b9be..bb1cc4b 100644
--- a/bundles/org.eclipse.equinox.p2.garbagecollector/src/org/eclipse/equinox/internal/p2/garbagecollector/Application.java
+++ b/bundles/org.eclipse.equinox.p2.garbagecollector/src/org/eclipse/equinox/internal/p2/garbagecollector/Application.java
@@ -1,13 +1,13 @@
 /*******************************************************************************
  * Copyright (c) 2008, 2017 IBM Corporation and others.
  *
- * This program and the accompanying materials 
+ * This program and the accompanying materials
  * are made available under the terms of the Eclipse Public License 2.0
  * which accompanies this distribution, and is available at
  * https://www.eclipse.org/legal/epl-2.0/
  *
  * SPDX-License-Identifier: EPL-2.0
- * 
+ *
  * Contributors:
  *     IBM Corporation - initial API and implementation
  *******************************************************************************/
@@ -32,7 +32,7 @@
 	 * Return the profile with the given id, or null if not found.
 	 */
 	private IProfile getProfile(String id) {
-		IProfileRegistry profileRegistry = (IProfileRegistry) agent.getService(IProfileRegistry.SERVICE_NAME);
+		IProfileRegistry profileRegistry = agent.getService(IProfileRegistry.class);
 		return profileRegistry == null ? null : profileRegistry.getProfile(id);
 	}
 
@@ -49,7 +49,7 @@
 		IProfile profile = getProfile(profileId);
 		if (profile == null)
 			throw new IllegalArgumentException("\"" + profileId + "\" is not a valid profile identifier."); //$NON-NLS-1$//$NON-NLS-2$
-		GarbageCollector gc = (GarbageCollector) agent.getService(GarbageCollector.SERVICE_NAME);
+		GarbageCollector gc = agent.getService(GarbageCollector.class);
 		gc.runGC(profile);
 		agent.stop();
 		return null;
@@ -73,7 +73,7 @@
 			return;
 		for (int i = 0; i < args.length; i++) {
 			String opt = args[i];
-			// check for args with parameters. If we are at the last argument or if the next 
+			// check for args with parameters. If we are at the last argument or if the next
 			// one has a '-' as the first character, then we can't have an arg with a parm so continue.
 			if (i == args.length - 1 || args[i + 1].startsWith("-")) //$NON-NLS-1$
 				continue;
diff --git a/bundles/org.eclipse.equinox.p2.garbagecollector/src/org/eclipse/equinox/internal/p2/garbagecollector/GarbageCollector.java b/bundles/org.eclipse.equinox.p2.garbagecollector/src/org/eclipse/equinox/internal/p2/garbagecollector/GarbageCollector.java
index 72b4ffa..719cdf6 100644
--- a/bundles/org.eclipse.equinox.p2.garbagecollector/src/org/eclipse/equinox/internal/p2/garbagecollector/GarbageCollector.java
+++ b/bundles/org.eclipse.equinox.p2.garbagecollector/src/org/eclipse/equinox/internal/p2/garbagecollector/GarbageCollector.java
@@ -7,7 +7,7 @@
  *  https://www.eclipse.org/legal/epl-2.0/
  *
  *  SPDX-License-Identifier: EPL-2.0
- * 
+ *
  *  Contributors:
  *     IBM Corporation - initial API and implementation
  *******************************************************************************/
@@ -31,13 +31,13 @@
 /**
  * The main control point for the p2 garbage collector.  Takes a Profile and runs the CoreGarbageCollector with the
  * appropriate MarkSets for the repositories used by that Profile.
- * 
+ *
  * Takes the profile passed in and creates a set (markSet) that maps the artifact repositories it uses to the
  * artifact keys its IUs hold.  This is done by getting MarkSets from all registered IMarkSetProviders.
- * 
+ *
  * Then, the MarkSets are obtained for every other registered Profile in a similar fashion.  Each MarkSet is
- * checked to see if its artifact repository is already a key in markSet.  If so, that MarkSet's artifact keys 
- * are added to the list that is mapped to by the artifact repository. 
+ * checked to see if its artifact repository is already a key in markSet.  If so, that MarkSet's artifact keys
+ * are added to the list that is mapped to by the artifact repository.
  */
 public class GarbageCollector implements SynchronousProvisioningListener, IAgentService {
 	/**
@@ -80,7 +80,7 @@
 	private static final String PT_MARKSET = GCActivator.ID + ".marksetproviders"; //$NON-NLS-1$
 	final IProvisioningAgent agent;
 
-	//The GC is triggered when an uninstall event occurred during a "transaction" and the transaction is committed.   
+	//The GC is triggered when an uninstall event occurred during a "transaction" and the transaction is committed.
 	String uninstallEventProfileId = null;
 
 	/**
@@ -93,8 +93,8 @@
 	}
 
 	private void addKeys(Collection<IArtifactKey> keyList, IArtifactKey[] keyArray) {
-		for (int i = 0; i < keyArray.length; i++)
-			keyList.add(keyArray[i]);
+		for (IArtifactKey element : keyArray)
+			keyList.add(element);
 	}
 
 	private void contributeMarkSets(IConfigurationElement runAttribute, IProfile profile, boolean addRepositories) {
@@ -104,19 +104,19 @@
 		if (aProfileMarkSets == null || aProfileMarkSets.length == 0 || aProfileMarkSets[0] == null)
 			return;
 
-		for (int i = 0; i < aProfileMarkSets.length; i++) {
-			if (aProfileMarkSets[i] == null) {
+		for (MarkSet aProfileMarkSet : aProfileMarkSets) {
+			if (aProfileMarkSet == null) {
 				continue;
 			}
-			Collection<IArtifactKey> keys = markSet.get(aProfileMarkSets[i].getRepo());
+			Collection<IArtifactKey> keys = markSet.get(aProfileMarkSet.getRepo());
 			if (keys == null) {
 				if (addRepositories) {
 					keys = new HashSet<>();
-					markSet.put(aProfileMarkSets[i].getRepo(), keys);
-					addKeys(keys, aProfileMarkSets[i].getKeys());
+					markSet.put(aProfileMarkSet.getRepo(), keys);
+					addKeys(keys, aProfileMarkSet.getKeys());
 				}
 			} else {
-				addKeys(keys, aProfileMarkSets[i].getKeys());
+				addKeys(keys, aProfileMarkSet.getKeys());
 			}
 		}
 	}
@@ -174,7 +174,7 @@
 
 	@Override
 	public void start() {
-		IProvisioningEventBus eventBus = (IProvisioningEventBus) agent.getService(IProvisioningEventBus.SERVICE_NAME);
+		IProvisioningEventBus eventBus = agent.getService(IProvisioningEventBus.class);
 		if (eventBus == null)
 			return;
 		eventBus.addListener(this);
@@ -182,7 +182,7 @@
 
 	@Override
 	public void stop() {
-		IProvisioningEventBus eventBus = (IProvisioningEventBus) agent.getService(IProvisioningEventBus.SERVICE_NAME);
+		IProvisioningEventBus eventBus = agent.getService(IProvisioningEventBus.class);
 		if (eventBus != null)
 			eventBus.removeListener(this);
 	}
@@ -218,13 +218,13 @@
 				continue;
 			}
 
-			IProfileRegistry profileRegistry = (IProfileRegistry) agent.getService(IProfileRegistry.SERVICE_NAME);
+			IProfileRegistry profileRegistry = agent.getService(IProfileRegistry.class);
 			if (profileRegistry == null)
 				return;
 			IProfile[] registeredProfiles = profileRegistry.getProfiles();
 
-			for (int j = 0; j < registeredProfiles.length; j++) {
-				contributeMarkSets(runAttribute, registeredProfiles[j], false);
+			for (IProfile registeredProfile : registeredProfiles) {
+				contributeMarkSets(runAttribute, registeredProfile, false);
 			}
 		}
 	}
diff --git a/bundles/org.eclipse.equinox.p2.installer/src/org/eclipse/equinox/internal/p2/installer/InstallUpdateProductOperation.java b/bundles/org.eclipse.equinox.p2.installer/src/org/eclipse/equinox/internal/p2/installer/InstallUpdateProductOperation.java
index 2e9942e..8595fe4 100644
--- a/bundles/org.eclipse.equinox.p2.installer/src/org/eclipse/equinox/internal/p2/installer/InstallUpdateProductOperation.java
+++ b/bundles/org.eclipse.equinox.p2.installer/src/org/eclipse/equinox/internal/p2/installer/InstallUpdateProductOperation.java
@@ -56,13 +56,13 @@
 	}
 
 	/**
-	 * Determine what top level installable units should be installed by the director
+	 * Determine what top level installable units should be installed by the
+	 * director
 	 */
 	private Collection<IInstallableUnit> computeUnitsToInstall() throws CoreException {
 		ArrayList<IInstallableUnit> units = new ArrayList<>();
 		IVersionedId roots[] = installDescription.getRoots();
-		for (int i = 0; i < roots.length; i++) {
-			IVersionedId root = roots[i];
+		for (IVersionedId root : roots) {
 			IInstallableUnit iu = findUnit(root);
 			if (iu != null)
 				units.add(iu);
@@ -71,7 +71,8 @@
 	}
 
 	/**
-	 * This profile is being updated; return the units to uninstall from the profile.
+	 * This profile is being updated; return the units to uninstall from the
+	 * profile.
 	 */
 	private IQueryResult<IInstallableUnit> computeUnitsToUninstall(IProfile p) {
 		return p.query(QueryUtil.createIUAnyQuery(), null);
@@ -85,7 +86,8 @@
 		if (profile == null) {
 			Map<String, String> properties = new HashMap<>();
 			properties.put(IProfile.PROP_INSTALL_FOLDER, installDescription.getInstallLocation().toString());
-			EnvironmentInfo info = ServiceHelper.getService(InstallerActivator.getDefault().getContext(), EnvironmentInfo.class);
+			EnvironmentInfo info = ServiceHelper.getService(InstallerActivator.getDefault().getContext(),
+					EnvironmentInfo.class);
 			String env = "osgi.os=" + info.getOS() + ",osgi.ws=" + info.getWS() + ",osgi.arch=" + info.getOSArch(); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
 			properties.put(IProfile.PROP_ENVIRONMENTS, env);
 			properties.put(IProfile.PROP_NAME, installDescription.getProductName());
@@ -99,7 +101,7 @@
 	}
 
 	IPlanner getPlanner() {
-		return (IPlanner) agent.getService(IPlanner.SERVICE_NAME);
+		return agent.getService(IPlanner.class);
 	}
 
 	/**
@@ -177,7 +179,8 @@
 	}
 
 	/**
-	 * Returns the id of the profile to use for install/update based on this operation's install description.
+	 * Returns the id of the profile to use for install/update based on this
+	 * operation's install description.
 	 */
 	private String getProfileId() {
 		IPath location = installDescription.getInstallLocation();
@@ -187,8 +190,8 @@
 	}
 
 	/**
-	 * Returns the result of the install operation, or <code>null</code> if
-	 * no install operation has been run.
+	 * Returns the result of the install operation, or <code>null</code> if no
+	 * install operation has been run.
 	 */
 	public IStatus getResult() {
 		return result;
@@ -209,7 +212,8 @@
 				preInstall();
 				isInstall = getProfile() == null;
 				doInstall(monitor);
-				result = new Status(IStatus.OK, InstallerActivator.PI_INSTALLER, isInstall ? Messages.Op_InstallComplete : Messages.Op_UpdateComplete, null);
+				result = new Status(IStatus.OK, InstallerActivator.PI_INSTALLER,
+						isInstall ? Messages.Op_InstallComplete : Messages.Op_UpdateComplete, null);
 				monitor.setTaskName(Messages.Op_Cleanup);
 			} finally {
 				postInstall();
@@ -223,19 +227,19 @@
 	}
 
 	/**
-	 * Returns whether this operation represents the product being installed
-	 * for the first time, in a new profile.
+	 * Returns whether this operation represents the product being installed for the
+	 * first time, in a new profile.
 	 */
 	public boolean isFirstInstall() {
 		return isInstall;
 	}
 
 	private void postInstall() {
-		//nothing to do
+		// nothing to do
 	}
 
 	private void preInstall() throws CoreException {
-		//obtain required services
+		// obtain required services
 		director = (IDirector) getService(IDirector.SERVICE_NAME);
 		metadataRepoMan = (IMetadataRepositoryManager) getService(IMetadataRepositoryManager.SERVICE_NAME);
 		artifactRepoMan = (IArtifactRepositoryManager) getService(IArtifactRepositoryManager.SERVICE_NAME);
@@ -248,10 +252,11 @@
 			return;
 
 		// Repositories must be registered before they are loaded
-		// This is to avoid them being possibly overridden with the configuration as a referenced repository
-		for (int i = 0; i < repos.length; i++) {
-			artifactRepoMan.addRepository(repos[i]);
-			artifactRepoMan.loadRepository(repos[i], null);
+		// This is to avoid them being possibly overridden with the configuration as a
+		// referenced repository
+		for (URI repo : repos) {
+			artifactRepoMan.addRepository(repo);
+			artifactRepoMan.loadRepository(repo, null);
 		}
 	}
 
@@ -261,10 +266,11 @@
 			return;
 
 		// Repositories must be registered before they are loaded
-		// This is to avoid them being possibly overridden with the configuration as a referenced repository
-		for (int i = 0; i < repos.length; i++) {
-			metadataRepoMan.addRepository(repos[i]);
-			metadataRepoMan.loadRepository(repos[i], null);
+		// This is to avoid them being possibly overridden with the configuration as a
+		// referenced repository
+		for (URI repo : repos) {
+			metadataRepoMan.addRepository(repo);
+			metadataRepoMan.loadRepository(repo, null);
 		}
 	}
 }
diff --git a/bundles/org.eclipse.equinox.p2.metadata.repository/src/org/eclipse/equinox/internal/p2/metadata/repository/CompositeMetadataRepository.java b/bundles/org.eclipse.equinox.p2.metadata.repository/src/org/eclipse/equinox/internal/p2/metadata/repository/CompositeMetadataRepository.java
index 1a15d97..5e8e73c 100644
--- a/bundles/org.eclipse.equinox.p2.metadata.repository/src/org/eclipse/equinox/internal/p2/metadata/repository/CompositeMetadataRepository.java
+++ b/bundles/org.eclipse.equinox.p2.metadata.repository/src/org/eclipse/equinox/internal/p2/metadata/repository/CompositeMetadataRepository.java
@@ -7,7 +7,7 @@
  * https://www.eclipse.org/legal/epl-2.0/
  *
  * SPDX-License-Identifier: EPL-2.0
- * 
+ *
  * Contributors:
  *     IBM Corporation - initial API and implementation
  *     EclipseSource - ongoing development
@@ -62,11 +62,11 @@
 	public static CompositeMetadataRepository createMemoryComposite(IProvisioningAgent agent) {
 		if (agent == null)
 			return null;
-		IMetadataRepositoryManager repoManager = (IMetadataRepositoryManager) agent.getService(IMetadataRepositoryManager.SERVICE_NAME);
+		IMetadataRepositoryManager repoManager = agent.getService(IMetadataRepositoryManager.class);
 		if (repoManager == null)
 			return null;
 		try {
-			//create a unique opaque URI 
+			//create a unique opaque URI
 			long time = System.currentTimeMillis();
 			URI repositoryURI = new URI("memory:" + String.valueOf(time)); //$NON-NLS-1$
 			while (repoManager.contains(repositoryURI))
diff --git a/bundles/org.eclipse.equinox.p2.metadata.repository/src/org/eclipse/equinox/internal/p2/metadata/repository/CompositeMetadataRepositoryFactory.java b/bundles/org.eclipse.equinox.p2.metadata.repository/src/org/eclipse/equinox/internal/p2/metadata/repository/CompositeMetadataRepositoryFactory.java
index 2debef1..2b5fd1b 100644
--- a/bundles/org.eclipse.equinox.p2.metadata.repository/src/org/eclipse/equinox/internal/p2/metadata/repository/CompositeMetadataRepositoryFactory.java
+++ b/bundles/org.eclipse.equinox.p2.metadata.repository/src/org/eclipse/equinox/internal/p2/metadata/repository/CompositeMetadataRepositoryFactory.java
@@ -45,7 +45,7 @@
 
 	private IMetadataRepositoryManager getManager() {
 		if (getAgent() != null)
-			return (IMetadataRepositoryManager) getAgent().getService(IMetadataRepositoryManager.SERVICE_NAME);
+			return getAgent().getService(IMetadataRepositoryManager.class);
 		return null;
 	}
 
@@ -71,7 +71,7 @@
 			throw new ProvisionException(new Status(IStatus.ERROR, Activator.ID, ProvisionException.REPOSITORY_NOT_FOUND, msg, null));
 		}
 		//file is not local, create a cache of the repository metadata
-		CacheManager cache = (CacheManager) getAgent().getService(CacheManager.SERVICE_NAME);
+		CacheManager cache = getAgent().getService(CacheManager.class);
 		if (cache == null)
 			throw new IllegalArgumentException("Cache manager service not available"); //$NON-NLS-1$
 		localFile = cache.createCache(location, CONTENT_FILENAME, monitor);
@@ -124,7 +124,7 @@
 				CompositeMetadataRepository result = new CompositeMetadataRepository(getManager(), resultState, sub.newChild(200));
 				if (Tracing.DEBUG_METADATA_PARSING) {
 					time += System.currentTimeMillis();
-					Tracing.debug(debugMsg + "time (ms): " + time); //$NON-NLS-1$ 
+					Tracing.debug(debugMsg + "time (ms): " + time); //$NON-NLS-1$
 				}
 				return result;
 			} finally {
diff --git a/bundles/org.eclipse.equinox.p2.metadata.repository/src/org/eclipse/equinox/internal/p2/metadata/repository/LocalMetadataRepository.java b/bundles/org.eclipse.equinox.p2.metadata.repository/src/org/eclipse/equinox/internal/p2/metadata/repository/LocalMetadataRepository.java
index 905ed96..af080a0 100644
--- a/bundles/org.eclipse.equinox.p2.metadata.repository/src/org/eclipse/equinox/internal/p2/metadata/repository/LocalMetadataRepository.java
+++ b/bundles/org.eclipse.equinox.p2.metadata.repository/src/org/eclipse/equinox/internal/p2/metadata/repository/LocalMetadataRepository.java
@@ -7,7 +7,7 @@
  *  https://www.eclipse.org/legal/epl-2.0/
  *
  *  SPDX-License-Identifier: EPL-2.0
- * 
+ *
  *  Contributors:
  *     IBM Corporation - initial API and implementation
  *     Prashant Deva - Bug 194674 [prov] Provide write access to metadata repository
@@ -177,7 +177,7 @@
 	 * Broadcast discovery events for all repositories referenced by this repository.
 	 */
 	public void publishRepositoryReferences() {
-		IProvisioningEventBus bus = (IProvisioningEventBus) getProvisioningAgent().getService(IProvisioningEventBus.SERVICE_NAME);
+		IProvisioningEventBus bus = getProvisioningAgent().getService(IProvisioningEventBus.class);
 		if (bus == null)
 			return;
 
@@ -300,7 +300,8 @@
 				save();
 			}
 			//force repository manager to reload this repository because it caches properties
-			MetadataRepositoryManager manager = (MetadataRepositoryManager) getProvisioningAgent().getService(IMetadataRepositoryManager.SERVICE_NAME);
+			MetadataRepositoryManager manager = (MetadataRepositoryManager) getProvisioningAgent()
+					.getService(IMetadataRepositoryManager.class);
 			if (manager.removeRepository(getLocation()))
 				manager.addRepository(this);
 			return oldValue;
diff --git a/bundles/org.eclipse.equinox.p2.metadata.repository/src/org/eclipse/equinox/internal/p2/metadata/repository/SimpleMetadataRepositoryFactory.java b/bundles/org.eclipse.equinox.p2.metadata.repository/src/org/eclipse/equinox/internal/p2/metadata/repository/SimpleMetadataRepositoryFactory.java
index 9647ae8..58760f9 100644
--- a/bundles/org.eclipse.equinox.p2.metadata.repository/src/org/eclipse/equinox/internal/p2/metadata/repository/SimpleMetadataRepositoryFactory.java
+++ b/bundles/org.eclipse.equinox.p2.metadata.repository/src/org/eclipse/equinox/internal/p2/metadata/repository/SimpleMetadataRepositoryFactory.java
@@ -7,7 +7,7 @@
  *  https://www.eclipse.org/legal/epl-2.0/
  *
  *  SPDX-License-Identifier: EPL-2.0
- * 
+ *
  *  Contributors:
  *     IBM Corporation - initial API and implementation
  *     Sonatype Inc - ongoing development
@@ -63,7 +63,7 @@
 			throw new ProvisionException(new Status(IStatus.ERROR, Activator.ID, ProvisionException.REPOSITORY_NOT_FOUND, msg, null));
 		}
 		// file is not local, create a cache of the repository metadata
-		CacheManager cache = (CacheManager) getAgent().getService(CacheManager.SERVICE_NAME);
+		CacheManager cache = getAgent().getService(CacheManager.class);
 		if (cache == null)
 			throw new IllegalArgumentException("Cache manager service not available"); //$NON-NLS-1$
 		localFile = cache.createCache(location, URLMetadataRepository.CONTENT_FILENAME, monitor);
@@ -114,7 +114,7 @@
 					((URLMetadataRepository) result).initializeAfterLoad(location);
 				if (Tracing.DEBUG_METADATA_PARSING) {
 					time += System.currentTimeMillis();
-					Tracing.debug(debugMsg + "time (ms): " + time); //$NON-NLS-1$ 
+					Tracing.debug(debugMsg + "time (ms): " + time); //$NON-NLS-1$
 				}
 				return result;
 			} finally {
diff --git a/bundles/org.eclipse.equinox.p2.metadata.repository/src/org/eclipse/equinox/internal/p2/metadata/repository/XZedSimpleMetadataRepositoryFactory.java b/bundles/org.eclipse.equinox.p2.metadata.repository/src/org/eclipse/equinox/internal/p2/metadata/repository/XZedSimpleMetadataRepositoryFactory.java
index ebe68cc..1e8ae4d 100644
--- a/bundles/org.eclipse.equinox.p2.metadata.repository/src/org/eclipse/equinox/internal/p2/metadata/repository/XZedSimpleMetadataRepositoryFactory.java
+++ b/bundles/org.eclipse.equinox.p2.metadata.repository/src/org/eclipse/equinox/internal/p2/metadata/repository/XZedSimpleMetadataRepositoryFactory.java
@@ -54,7 +54,7 @@
 			throw new ProvisionException(new Status(IStatus.ERROR, Activator.ID, ProvisionException.REPOSITORY_NOT_FOUND, msg, null));
 		}
 		// file is not local, create a cache of the repository metadata
-		CacheManager cache = (CacheManager) getAgent().getService(CacheManager.SERVICE_NAME);
+		CacheManager cache = getAgent().getService(CacheManager.class);
 		if (cache == null)
 			throw new IllegalArgumentException("Cache manager service not available"); //$NON-NLS-1$
 		localFile = cache.createCacheFromFile(URIUtil.append(location, REPOSITORY_FILENAME), monitor);
@@ -92,7 +92,7 @@
 					((URLMetadataRepository) result).initializeAfterLoad(location);
 				if (Tracing.DEBUG_METADATA_PARSING) {
 					time += System.currentTimeMillis();
-					Tracing.debug(debugMsg + "time (ms): " + time); //$NON-NLS-1$ 
+					Tracing.debug(debugMsg + "time (ms): " + time); //$NON-NLS-1$
 				}
 				return result;
 			} finally {
diff --git a/bundles/org.eclipse.equinox.p2.metadata.repository/src_ant/org/eclipse/equinox/internal/p2/metadata/repository/ant/AddChildTask.java b/bundles/org.eclipse.equinox.p2.metadata.repository/src_ant/org/eclipse/equinox/internal/p2/metadata/repository/ant/AddChildTask.java
index 6dba31d..bd40bb0 100644
--- a/bundles/org.eclipse.equinox.p2.metadata.repository/src_ant/org/eclipse/equinox/internal/p2/metadata/repository/ant/AddChildTask.java
+++ b/bundles/org.eclipse.equinox.p2.metadata.repository/src_ant/org/eclipse/equinox/internal/p2/metadata/repository/ant/AddChildTask.java
@@ -32,7 +32,7 @@
 	@Override
 	public void execute() {
 		validate();
-		IMetadataRepositoryManager manager = (IMetadataRepositoryManager) getAgent().getService(IMetadataRepositoryManager.SERVICE_NAME);
+		IMetadataRepositoryManager manager = getAgent().getService(IMetadataRepositoryManager.class);
 		if (manager == null)
 			throw new BuildException("Unable to aquire metadata repository manager service.");
 
diff --git a/bundles/org.eclipse.equinox.p2.metadata.repository/src_ant/org/eclipse/equinox/internal/p2/metadata/repository/ant/CreateCompositeMetadataRepositoryTask.java b/bundles/org.eclipse.equinox.p2.metadata.repository/src_ant/org/eclipse/equinox/internal/p2/metadata/repository/ant/CreateCompositeMetadataRepositoryTask.java
index e10a0e1..d1f4806 100644
--- a/bundles/org.eclipse.equinox.p2.metadata.repository/src_ant/org/eclipse/equinox/internal/p2/metadata/repository/ant/CreateCompositeMetadataRepositoryTask.java
+++ b/bundles/org.eclipse.equinox.p2.metadata.repository/src_ant/org/eclipse/equinox/internal/p2/metadata/repository/ant/CreateCompositeMetadataRepositoryTask.java
@@ -40,7 +40,7 @@
 
 	@Override
 	public void execute() {
-		IMetadataRepositoryManager manager = (IMetadataRepositoryManager) getAgent().getService(IMetadataRepositoryManager.SERVICE_NAME);
+		IMetadataRepositoryManager manager = getAgent().getService(IMetadataRepositoryManager.class);
 		if (manager == null)
 			throw new BuildException("Unable to aquire metadata repository manager service.");
 
diff --git a/bundles/org.eclipse.equinox.p2.metadata.repository/src_ant/org/eclipse/equinox/internal/p2/metadata/repository/ant/RemoveChildTask.java b/bundles/org.eclipse.equinox.p2.metadata.repository/src_ant/org/eclipse/equinox/internal/p2/metadata/repository/ant/RemoveChildTask.java
index feaa3ac..2cec610 100644
--- a/bundles/org.eclipse.equinox.p2.metadata.repository/src_ant/org/eclipse/equinox/internal/p2/metadata/repository/ant/RemoveChildTask.java
+++ b/bundles/org.eclipse.equinox.p2.metadata.repository/src_ant/org/eclipse/equinox/internal/p2/metadata/repository/ant/RemoveChildTask.java
@@ -1,13 +1,13 @@
 /*******************************************************************************
  * Copyright (c) 2008, 2017 IBM Corporation and others.
  *
- * This program and the accompanying materials 
+ * This program and the accompanying materials
  * are made available under the terms of the Eclipse Public License 2.0
  * which accompanies this distribution, and is available at
  * https://www.eclipse.org/legal/epl-2.0/
  *
  * SPDX-License-Identifier: EPL-2.0
- * 
+ *
  * Contributors:
  *     IBM Corporation - initial API and implementation
  *******************************************************************************/
@@ -22,7 +22,7 @@
 import org.eclipse.equinox.p2.repository.metadata.IMetadataRepositoryManager;
 
 /**
- * Ant task to remove a specific child repository (or all the children repositories) 
+ * Ant task to remove a specific child repository (or all the children repositories)
  * from a composite metadata repository.
  */
 public class RemoveChildTask extends AbstractMDRTask {
@@ -33,7 +33,7 @@
 
 	@Override
 	public void execute() {
-		IMetadataRepositoryManager manager = (IMetadataRepositoryManager) getAgent().getService(IMetadataRepositoryManager.SERVICE_NAME);
+		IMetadataRepositoryManager manager = getAgent().getService(IMetadataRepositoryManager.class);
 		if (manager == null)
 			throw new BuildException("Unable to aquire metadata repository manager service.");
 
diff --git a/bundles/org.eclipse.equinox.p2.operations/src/org/eclipse/equinox/internal/p2/operations/PlannerResolutionJob.java b/bundles/org.eclipse.equinox.p2.operations/src/org/eclipse/equinox/internal/p2/operations/PlannerResolutionJob.java
index 9eae9fa..c1ec0a1 100644
--- a/bundles/org.eclipse.equinox.p2.operations/src/org/eclipse/equinox/internal/p2/operations/PlannerResolutionJob.java
+++ b/bundles/org.eclipse.equinox.p2.operations/src/org/eclipse/equinox/internal/p2/operations/PlannerResolutionJob.java
@@ -7,7 +7,7 @@
  *  https://www.eclipse.org/legal/epl-2.0/
  *
  *  SPDX-License-Identifier: EPL-2.0
- * 
+ *
  *  Contributors:
  *     IBM Corporation - initial API and implementation
  *******************************************************************************/
@@ -77,7 +77,7 @@
 			sub = SubMonitor.convert(monitor, 500);
 		}
 
-		plan = ((IPlanner) getSession().getProvisioningAgent().getService(IPlanner.SERVICE_NAME)).getProvisioningPlan(request, firstPass, sub.newChild(500));
+		plan = getSession().getProvisioningAgent().getService(IPlanner.class).getProvisioningPlan(request, firstPass, sub.newChild(500));
 		IStatus status;
 		if (plan == null) {
 			status = new Status(IStatus.ERROR, Constants.BUNDLE_ID, Messages.PlannerResolutionJob_NullProvisioningPlan);
@@ -97,7 +97,8 @@
 			return status;
 
 		successful = secondPass;
-		plan = ((IPlanner) getSession().getProvisioningAgent().getService(IPlanner.SERVICE_NAME)).getProvisioningPlan(request, secondPass, sub.newChild(500));
+		plan = getSession().getProvisioningAgent().getService(IPlanner.class).getProvisioningPlan(request, secondPass,
+				sub.newChild(500));
 		if (plan == null) {
 			status = new Status(IStatus.ERROR, Constants.BUNDLE_ID, Messages.PlannerResolutionJob_NullProvisioningPlan);
 			additionalStatus.add(status);
diff --git a/bundles/org.eclipse.equinox.p2.operations/src/org/eclipse/equinox/p2/operations/OperationFactory.java b/bundles/org.eclipse.equinox.p2.operations/src/org/eclipse/equinox/p2/operations/OperationFactory.java
index 1b7457a..716035a 100644
--- a/bundles/org.eclipse.equinox.p2.operations/src/org/eclipse/equinox/p2/operations/OperationFactory.java
+++ b/bundles/org.eclipse.equinox.p2.operations/src/org/eclipse/equinox/p2/operations/OperationFactory.java
@@ -7,7 +7,7 @@
  *  https://www.eclipse.org/legal/epl-2.0/
  *
  *  SPDX-License-Identifier: EPL-2.0
- * 
+ *
  *  Contributors:
  *     Sonatype, Inc. - initial API and implementation
  *     IBM Corporation - Ongoing development
@@ -33,7 +33,7 @@
  * OperationFactory provides a set of helpers to simplify dealing with the running installation.
  * Among other things, it simplifies the installation, un-installation and update.
  * If the system you are trying to modify is not the running one, you need to directly use the various subclass of {@link ProfileChangeOperation}.
- * @since 2.1  
+ * @since 2.1
  */
 public class OperationFactory {
 
@@ -84,7 +84,7 @@
 	}
 
 	/**
-	 * This factory method creates an {@link InstallOperation} to install all the elements listed from the specified repositories. 
+	 * This factory method creates an {@link InstallOperation} to install all the elements listed from the specified repositories.
 	 * @param toInstall the elements to install. This can not be null.
 	 * @param repos the repositories to install the elements from. If null is passed, it will use all previously registered repositories.
 	 * @param monitor the progress monitor
@@ -106,9 +106,9 @@
 	}
 
 	/**
-	 * Create an {@link UninstallOperation} that will uninstall the listed elements from the running instance. 
+	 * Create an {@link UninstallOperation} that will uninstall the listed elements from the running instance.
 	 * @param toUninstall the elements to uninstall. This can not be null.
-	 * @param repos the repositories to install the elements from. If null is passed, it will use all previously registered repositories. 
+	 * @param repos the repositories to install the elements from. If null is passed, it will use all previously registered repositories.
 	 * @param monitor the progress monitor
 	 * @return an operation to uninstall
 	 */
@@ -134,7 +134,7 @@
 	 *     cannot be accessed
 	 */
 	public IQueryResult<IInstallableUnit> listInstalledElements(boolean rootsOnly, IProgressMonitor monitor) {
-		IProfileRegistry registry = (IProfileRegistry) getAgent().getService(IProfileRegistry.SERVICE_NAME);
+		IProfileRegistry registry = getAgent().getService(IProfileRegistry.class);
 		IProfile profile = registry.getProfile(IProfileRegistry.SELF);
 		if (profile == null)
 			return new CollectionResult<>(null);
@@ -145,7 +145,7 @@
 
 	/**
 	 * Create an {@link UpdateOperation} that will update the elements specified.
-	 * @param toUpdate The elements to update.Passing null will result in looking for an update to all the installed. Note that you can pass the results of {@link OperationFactory#listInstalledElements(boolean, IProgressMonitor)} to this 
+	 * @param toUpdate The elements to update.Passing null will result in looking for an update to all the installed. Note that you can pass the results of {@link OperationFactory#listInstalledElements(boolean, IProgressMonitor)} to this
 	 * method if you wish to update all elements installed in the running instance of eclipse.
 	 * @param repos the repositories to update the elements from. If null is passed, it will use all previously registered repositories.
 	 * @param monitor the progress monitor
diff --git a/bundles/org.eclipse.equinox.p2.operations/src/org/eclipse/equinox/p2/operations/ProvisioningSession.java b/bundles/org.eclipse.equinox.p2.operations/src/org/eclipse/equinox/p2/operations/ProvisioningSession.java
index f6cd7d3..e3ff8ba 100644
--- a/bundles/org.eclipse.equinox.p2.operations/src/org/eclipse/equinox/p2/operations/ProvisioningSession.java
+++ b/bundles/org.eclipse.equinox.p2.operations/src/org/eclipse/equinox/p2/operations/ProvisioningSession.java
@@ -40,7 +40,7 @@
  * ProvisioningSession provides the context for a provisioning session, including
  * the provisioning services that should be used.  It also provides utility
  * methods for commonly performed provisioning tasks.
- * 
+ *
  * @since 2.0
  * @noextend This class is not intended to be subclassed by clients.
  */
@@ -71,7 +71,7 @@
 	 * @return the agent location
 	 */
 	IAgentLocation getAgentLocation() {
-		return (IAgentLocation) agent.getService(IAgentLocation.SERVICE_NAME);
+		return agent.getService(IAgentLocation.class);
 	}
 
 	/**
@@ -79,7 +79,7 @@
 	 * @return the repository manager
 	 */
 	IArtifactRepositoryManager getArtifactRepositoryManager() {
-		return (IArtifactRepositoryManager) agent.getService(IArtifactRepositoryManager.SERVICE_NAME);
+		return agent.getService(IArtifactRepositoryManager.class);
 	}
 
 	/**
@@ -87,11 +87,11 @@
 	 * @return the repository manager
 	 */
 	IMetadataRepositoryManager getMetadataRepositoryManager() {
-		return (IMetadataRepositoryManager) agent.getService(IMetadataRepositoryManager.SERVICE_NAME);
+		return agent.getService(IMetadataRepositoryManager.class);
 	}
 
 	IProfileRegistry getProfileRegistry() {
-		return (IProfileRegistry) agent.getService(IProfileRegistry.SERVICE_NAME);
+		return agent.getService(IProfileRegistry.class);
 	}
 
 	/**
@@ -99,7 +99,7 @@
 	 * @return the provisioning engine
 	 */
 	IEngine getEngine() {
-		return (IEngine) agent.getService(IEngine.SERVICE_NAME);
+		return agent.getService(IEngine.class);
 	}
 
 	/**
@@ -107,7 +107,7 @@
 	 * @return the event bus
 	 */
 	IProvisioningEventBus getProvisioningEventBus() {
-		return (IProvisioningEventBus) agent.getService(IProvisioningEventBus.SERVICE_NAME);
+		return agent.getService(IProvisioningEventBus.class);
 	}
 
 	/**
@@ -115,12 +115,12 @@
 	 * @return the planner
 	 */
 	IPlanner getPlanner() {
-		return (IPlanner) agent.getService(IPlanner.SERVICE_NAME);
+		return agent.getService(IPlanner.class);
 	}
 
 	/**
 	 * Perform the specified provisioning plan.
-	 * 
+	 *
 	 * @param plan the provisioning plan to be performed
 	 * @param phaseSet the phase set to be used for the plan
 	 * @param context the provisioning context to be used during provisioning
@@ -140,7 +140,7 @@
 
 		// see https://bugs.eclipse.org/bugs/show_bug.cgi?id=272355
 		// The exact profile instance used in the profile change request and passed to the engine must be used for all
-		// of these operations, otherwise we can get profile out of synch errors.	
+		// of these operations, otherwise we can get profile out of synch errors.
 		IProfile profile = plan.getProfile();
 
 		if (plan.getInstallerPlan() != null) {
@@ -183,8 +183,8 @@
 
 	private boolean doesPhaseSetIncludeDownload(IPhaseSet set) {
 		String[] phaseIds = set.getPhaseIds();
-		for (int i = 0; i < phaseIds.length; i++)
-			if (phaseIds[i].equals(PhaseSetFactory.PHASE_COLLECT))
+		for (String phaseId : phaseIds)
+			if (phaseId.equals(PhaseSetFactory.PHASE_COLLECT))
 				return true;
 		return false;
 	}
@@ -192,7 +192,7 @@
 	/**
 	 * Return a boolean indicating whether any other provisioning operations are
 	 * scheduled for the specified profile.
-	 * 
+	 *
 	 * @param profileId the id of the profile in question
 	 * @return <code>true</code> if there are pending provisioning operations for
 	 * this profile, <code>false</code> if there are not.
@@ -200,9 +200,9 @@
 	 */
 	public boolean hasScheduledOperationsFor(String profileId) {
 		Job[] jobs = getScheduledJobs();
-		for (int i = 0; i < jobs.length; i++) {
-			if (jobs[i] instanceof IProfileChangeJob) {
-				String id = ((IProfileChangeJob) jobs[i]).getProfileId();
+		for (Job job : jobs) {
+			if (job instanceof IProfileChangeJob) {
+				String id = ((IProfileChangeJob) job).getProfileId();
 				if (profileId.equals(id))
 					return true;
 			}
@@ -220,7 +220,7 @@
 	 * Remember the specified job.  Remembered jobs are
 	 * checked when callers want to know what work is scheduled for
 	 * a particular profile.
-	 * 
+	 *
 	 * @param job the job to be remembered
 	 * @see #hasScheduledOperationsFor(String)
 	 */
diff --git a/bundles/org.eclipse.equinox.p2.reconciler.dropins/src/org/eclipse/equinox/internal/p2/reconciler/dropins/Activator.java b/bundles/org.eclipse.equinox.p2.reconciler.dropins/src/org/eclipse/equinox/internal/p2/reconciler/dropins/Activator.java
index 2603ef0..ed2e411 100644
--- a/bundles/org.eclipse.equinox.p2.reconciler.dropins/src/org/eclipse/equinox/internal/p2/reconciler/dropins/Activator.java
+++ b/bundles/org.eclipse.equinox.p2.reconciler.dropins/src/org/eclipse/equinox/internal/p2/reconciler/dropins/Activator.java
@@ -7,9 +7,9 @@
  * https://www.eclipse.org/legal/epl-2.0/
  *
  * SPDX-License-Identifier: EPL-2.0
- * 
- * Contributors: 
- * IBM Corporation - initial implementation and ideas 
+ *
+ * Contributors:
+ * IBM Corporation - initial implementation and ideas
  * Red Hat Inc. - Bug 460967
  ******************************************************************************/
 package org.eclipse.equinox.internal.p2.reconciler.dropins;
@@ -60,17 +60,17 @@
 	private Collection<File> filesToCheck = null;
 
 	/**
-	 * Helper method to create an extension location metadata repository at the given URI. 
+	 * Helper method to create an extension location metadata repository at the given URI.
 	 * If one already exists at that location then an exception will be thrown.
-	 * 
+	 *
 	 * This method never returns <code>null</code>.
-	 * 
+	 *
 	 * @throws IllegalStateException
-	 * @throws ProvisionException 
+	 * @throws ProvisionException
 	 */
 	public static IMetadataRepository createExtensionLocationMetadataRepository(URI location, String name, Map<String, String> properties) throws ProvisionException {
 		IProvisioningAgent agent = getAgent();
-		IMetadataRepositoryManager manager = (IMetadataRepositoryManager) agent.getService(IMetadataRepositoryManager.SERVICE_NAME);
+		IMetadataRepositoryManager manager = agent.getService(IMetadataRepositoryManager.class);
 		if (manager == null)
 			throw new IllegalStateException("MetadataRepositoryManager not registered."); //$NON-NLS-1$
 		ExtensionLocationMetadataRepositoryFactory factory = new ExtensionLocationMetadataRepositoryFactory();
@@ -93,12 +93,12 @@
 
 	/**
 	 * Helper method to load an extension location metadata repository from the given URL.
-	 * 
+	 *
 	 * @throws IllegalStateException
 	 * @throws ProvisionException
 	 */
 	public static IMetadataRepository loadMetadataRepository(URI location, IProgressMonitor monitor) throws ProvisionException {
-		IMetadataRepositoryManager manager = (IMetadataRepositoryManager) getAgent().getService(IMetadataRepositoryManager.SERVICE_NAME);
+		IMetadataRepositoryManager manager = getAgent().getService(IMetadataRepositoryManager.class);
 		if (manager == null)
 			throw new IllegalStateException("MetadataRepositoryManager not registered."); //$NON-NLS-1$
 		IMetadataRepository repository = manager.loadRepository(location, monitor);
@@ -107,17 +107,17 @@
 	}
 
 	/**
-	 * Helper method to create an extension location artifact repository at the given URL. 
+	 * Helper method to create an extension location artifact repository at the given URL.
 	 * If one already exists at that location then an exception will be thrown.
-	 * 
+	 *
 	 * This method never returns <code>null</code>.
-	 * 
+	 *
 	 * @throws IllegalStateException
-	 * @throws ProvisionException 
+	 * @throws ProvisionException
 	 */
 	public static IArtifactRepository createExtensionLocationArtifactRepository(URI location, String name, Map<String, String> properties) throws ProvisionException {
 		IProvisioningAgent agent = getAgent();
-		IArtifactRepositoryManager manager = (IArtifactRepositoryManager) agent.getService(IArtifactRepositoryManager.SERVICE_NAME);
+		IArtifactRepositoryManager manager = agent.getService(IArtifactRepositoryManager.class);
 		if (manager == null)
 			throw new IllegalStateException("ArtifactRepositoryManager not registered."); //$NON-NLS-1$
 		ExtensionLocationArtifactRepositoryFactory factory = new ExtensionLocationArtifactRepositoryFactory();
@@ -136,12 +136,12 @@
 
 	/**
 	 * Helper method to load an extension location metadata repository from the given URL.
-	 * 
+	 *
 	 * @throws IllegalStateException
 	 * @throws ProvisionException
 	 */
 	public static IArtifactRepository loadArtifactRepository(URI location, IProgressMonitor monitor) throws ProvisionException {
-		IArtifactRepositoryManager manager = (IArtifactRepositoryManager) getAgent().getService(IArtifactRepositoryManager.SERVICE_NAME);
+		IArtifactRepositoryManager manager = getAgent().getService(IArtifactRepositoryManager.class);
 		if (manager == null)
 			throw new IllegalStateException("ArtifactRepositoryManager not registered."); //$NON-NLS-1$
 		IArtifactRepository repository = manager.loadRepository(location, monitor);
@@ -242,8 +242,7 @@
 
 		// gather the list of files/folders that we need to check
 		Collection<File> files = getFilesToCheck();
-		for (Iterator<File> iter = files.iterator(); iter.hasNext();) {
-			File file = iter.next();
+		for (File file : files) {
 			String key = file.getAbsolutePath();
 			String timestamp = timestamps.getProperty(key);
 			if (timestamp == null) {
@@ -269,8 +268,8 @@
 		} else {
 			if (Tracing.DEBUG_RECONCILER) {
 				trace("Found extra values in cached timestamp file: "); //$NON-NLS-1$
-				for (Iterator<Object> iter = timestamps.keySet().iterator(); iter.hasNext();)
-					trace(iter.next());
+				for (Object object : timestamps.keySet())
+					trace(object);
 				trace("Performing reconciliation. "); //$NON-NLS-1$
 			}
 		}
@@ -292,8 +291,7 @@
 			LogHelper.log(new Status(IStatus.ERROR, Activator.ID, "Error occurred while reading cached timestamps for reconciliation.", e)); //$NON-NLS-1$
 		}
 		if (Tracing.DEBUG_RECONCILER) {
-			for (Iterator<Object> iter = result.keySet().iterator(); iter.hasNext();) {
-				Object key = iter.next();
+			for (Object key : result.keySet()) {
 				Object value = result.get(key);
 				trace(key.toString() + '=' + value);
 			}
@@ -350,16 +348,16 @@
 	}
 
 	/*
-	 * Iterate over the given collection of files (could be dropins or links folders) and 
+	 * Iterate over the given collection of files (could be dropins or links folders) and
 	 * return a collection of files that might be interesting to check the timestamps of.
 	 */
 	private Collection<File> getDropinsToCheck(File[] files) {
 		Collection<File> result = new HashSet<>();
-		for (int outer = 0; outer < files.length; outer++) {
+		for (File file : files) {
 			// add top-level file/folder
-			result.add(files[outer]);
+			result.add(file);
 
-			File[] children = files[outer].listFiles();
+			File[] children = file.listFiles();
 			for (int inner = 0; children != null && inner < children.length; inner++) {
 				File child = children[inner];
 				if (child.isFile() && child.getName().toLowerCase().endsWith(EXT_LINK)) {
@@ -384,7 +382,7 @@
 				} else if (child.isDirectory()) {
 					// look for "dropins/foo/plugins" (and "features") and
 					// "dropins/foo/eclipse/plugins" (and "features")
-					// Note: we could have a directory-based bundle here but we 
+					// Note: we could have a directory-based bundle here but we
 					// will still add it since it won't hurt anything (one extra timestamp check)
 					result.add(child);
 					File parent;
@@ -413,8 +411,7 @@
 	private void writeTimestamps() {
 		Properties timestamps = new Properties();
 		Collection<File> files = getFilesToCheck();
-		for (Iterator<File> iter = files.iterator(); iter.hasNext();) {
-			File file = iter.next();
+		for (File file : files) {
 			timestamps.put(file.getAbsolutePath(), Long.toString(file.lastModified()));
 		}
 
@@ -425,8 +422,7 @@
 		try (OutputStream output = new BufferedOutputStream(new FileOutputStream(file))) {
 			timestamps.store(output, null);
 			if (Tracing.DEBUG_RECONCILER) {
-				for (Iterator<Object> iter = timestamps.keySet().iterator(); iter.hasNext();) {
-					Object key = iter.next();
+				for (Object key : timestamps.keySet()) {
 					Object value = timestamps.get(key);
 					trace(key.toString() + '=' + value);
 				}
@@ -500,7 +496,7 @@
 	}
 
 	/*
-	 * Create a new directory watcher with a repository listener on the drop-ins folder. 
+	 * Create a new directory watcher with a repository listener on the drop-ins folder.
 	 */
 	private void watchDropins() {
 		List<File> directories = new ArrayList<>();
@@ -678,7 +674,7 @@
 	 */
 	public static IProfile getCurrentProfile(BundleContext context) {
 		IProvisioningAgent agent = getAgent();
-		IProfileRegistry profileRegistry = (IProfileRegistry) agent.getService(IProfileRegistry.SERVICE_NAME);
+		IProfileRegistry profileRegistry = agent.getService(IProfileRegistry.class);
 		if (profileRegistry == null)
 			return null;
 		return profileRegistry.getProfile(IProfileRegistry.SELF);
diff --git a/bundles/org.eclipse.equinox.p2.reconciler.dropins/src/org/eclipse/equinox/internal/p2/reconciler/dropins/DropinsRepositoryListener.java b/bundles/org.eclipse.equinox.p2.reconciler.dropins/src/org/eclipse/equinox/internal/p2/reconciler/dropins/DropinsRepositoryListener.java
index 60d8bc6..9c073c6 100644
--- a/bundles/org.eclipse.equinox.p2.reconciler.dropins/src/org/eclipse/equinox/internal/p2/reconciler/dropins/DropinsRepositoryListener.java
+++ b/bundles/org.eclipse.equinox.p2.reconciler.dropins/src/org/eclipse/equinox/internal/p2/reconciler/dropins/DropinsRepositoryListener.java
@@ -1,13 +1,13 @@
 /*******************************************************************************
  * Copyright (c) 2008, 2017 IBM Corporation and others.
  *
- * This program and the accompanying materials 
+ * This program and the accompanying materials
  * are made available under the terms of the Eclipse Public License 2.0
  * which accompanies this distribution, and is available at
  * https://www.eclipse.org/legal/epl-2.0/
  *
  * SPDX-License-Identifier: EPL-2.0
- * 
+ *
  * Contributors:
  *     IBM Corporation - initial API and implementation
  *     Code 9 - ongoing development
@@ -106,7 +106,7 @@
 	public boolean changed(File file) {
 		if (super.changed(file)) {
 			if (Tracing.DEBUG_RECONCILER)
-				Tracing.debug(PREFIX + "Interesting feature or bundle changed: " + file); //$NON-NLS-1$			
+				Tracing.debug(PREFIX + "Interesting feature or bundle changed: " + file); //$NON-NLS-1$
 			return true;
 		}
 		addRepository(file);
@@ -248,8 +248,8 @@
 		Tracing.debug(PREFIX + "Repository created " + repository.getLocation()); //$NON-NLS-1$
 		// Print out a list of all the IUs in the repository
 		IQueryResult<IInstallableUnit> result = repository.query(QueryUtil.createIUAnyQuery(), new NullProgressMonitor());
-		for (Iterator<IInstallableUnit> iter = result.iterator(); iter.hasNext();)
-			Tracing.debug(PREFIX + "\t" + iter.next()); //$NON-NLS-1$
+		for (IInstallableUnit iInstallableUnit : result)
+			Tracing.debug(PREFIX + "\t" + iInstallableUnit); //$NON-NLS-1$
 	}
 
 	public void getArtifactRepository(URI repoURL, Map<String, String> properties) {
@@ -277,13 +277,11 @@
 
 	private void synchronizeDropinMetadataRepositories() {
 		List<String> currentRepositories = new ArrayList<>();
-		for (Iterator<IMetadataRepository> it = metadataRepositories.iterator(); it.hasNext();) {
-			IMetadataRepository repository = it.next();
+		for (IMetadataRepository repository : metadataRepositories) {
 			currentRepositories.add(repository.getLocation().toString());
 		}
 		List<String> previousRepositories = getListRepositoryProperty(getMetadataRepository(), DROPIN_METADATA_REPOSITORIES);
-		for (Iterator<String> iterator = previousRepositories.iterator(); iterator.hasNext();) {
-			String repository = iterator.next();
+		for (String repository : previousRepositories) {
 			if (!currentRepositories.contains(repository))
 				removeMetadataRepository(repository);
 		}
@@ -291,7 +289,7 @@
 	}
 
 	private void removeMetadataRepository(String urlString) {
-		IMetadataRepositoryManager manager = (IMetadataRepositoryManager) agent.getService(IMetadataRepositoryManager.SERVICE_NAME);
+		IMetadataRepositoryManager manager = agent.getService(IMetadataRepositoryManager.class);
 		if (manager == null)
 			throw new IllegalStateException(Messages.metadata_repo_manager_not_registered);
 		try {
@@ -303,13 +301,11 @@
 
 	private void synchronizeDropinArtifactRepositories() {
 		List<String> currentRepositories = new ArrayList<>();
-		for (Iterator<IArtifactRepository> it = artifactRepositories.iterator(); it.hasNext();) {
-			IArtifactRepository repository = it.next();
+		for (IArtifactRepository repository : artifactRepositories) {
 			currentRepositories.add(repository.getLocation().toString());
 		}
 		List<String> previousRepositories = getListRepositoryProperty(getArtifactRepository(), DROPIN_ARTIFACT_REPOSITORIES);
-		for (Iterator<String> iterator = previousRepositories.iterator(); iterator.hasNext();) {
-			String repository = iterator.next();
+		for (String repository : previousRepositories) {
 			if (!currentRepositories.contains(repository))
 				removeArtifactRepository(repository);
 		}
@@ -317,7 +313,7 @@
 	}
 
 	public void removeArtifactRepository(String urlString) {
-		IArtifactRepositoryManager manager = (IArtifactRepositoryManager) agent.getService(IArtifactRepositoryManager.SERVICE_NAME);
+		IArtifactRepositoryManager manager = agent.getService(IArtifactRepositoryManager.class);
 		if (manager == null)
 			throw new IllegalStateException(Messages.artifact_repo_manager_not_registered);
 		try {
diff --git a/bundles/org.eclipse.equinox.p2.reconciler.dropins/src/org/eclipse/equinox/internal/p2/reconciler/dropins/ProfileSynchronizer.java b/bundles/org.eclipse.equinox.p2.reconciler.dropins/src/org/eclipse/equinox/internal/p2/reconciler/dropins/ProfileSynchronizer.java
index bb776bc..f44848d 100644
--- a/bundles/org.eclipse.equinox.p2.reconciler.dropins/src/org/eclipse/equinox/internal/p2/reconciler/dropins/ProfileSynchronizer.java
+++ b/bundles/org.eclipse.equinox.p2.reconciler.dropins/src/org/eclipse/equinox/internal/p2/reconciler/dropins/ProfileSynchronizer.java
@@ -7,8 +7,8 @@
  * https://www.eclipse.org/legal/epl-2.0/
  *
  * SPDX-License-Identifier: EPL-2.0
- * 
- * Contributors: 
+ *
+ * Contributors:
  * IBM Corporation - initial implementation and ideas
  *     Sonatype, Inc. - ongoing development
  *     RedHat, Inc. - Bug 397216, Bug 460967
@@ -152,7 +152,7 @@
 		// Mark the state update as hidden so it does not appear in the Installation History UI list
 		// TODO We need to determine if it is ok to use this copy of the profile.
 		// See https://bugs.eclipse.org/334670
-		IProfileRegistry profileRegistry = (IProfileRegistry) agent.getService(IProfileRegistry.SERVICE_NAME);
+		IProfileRegistry profileRegistry = agent.getService(IProfileRegistry.class);
 		if (profileRegistry != null) {
 			IStatus result = profileRegistry.setProfileStateProperty(profile.getProfileId(), profile.getTimestamp(), IProfile.STATE_PROP_HIDDEN, Boolean.TRUE.toString());
 			if (!result.isOK()) {
@@ -180,7 +180,7 @@
 	 * removal so we have to uninstall the UI-installed IU.
 	 */
 	private IStatus performAddRemove(ReconcilerProfileChangeRequest request, ProvisioningContext context, IProgressMonitor monitor) {
-		// if we have moves then we have previously removed them. 
+		// if we have moves then we have previously removed them.
 		// now we need to add them back (at the new location)
 		for (IInstallableUnit iu : request.getMoves()) {
 			request.add(iu);
@@ -195,7 +195,7 @@
 		if (additions.isEmpty() && removals.isEmpty())
 			return Status.OK_STATUS;
 
-		// TODO See bug 270195. Eventually we will attempt to remove strictly installed IUs if their 
+		// TODO See bug 270195. Eventually we will attempt to remove strictly installed IUs if their
 		// dependent bundles have been deleted.
 		boolean removeStrictRoots = false;
 		if (removeStrictRoots)
@@ -209,7 +209,7 @@
 	private IStatus performStrictRootRemoval(ReconcilerProfileChangeRequest request, ProvisioningContext context, IProgressMonitor monitor) {
 		Collection<IInstallableUnit> removals = request.getRemovals();
 		// if we don't have any removals then we don't have to worry about potentially
-		// invalidating things we already have installed, removal of roots, etc so just 
+		// invalidating things we already have installed, removal of roots, etc so just
 		// create a regular plan.
 		if (removals.isEmpty()) {
 			IProvisioningPlan plan = createProvisioningPlan(request, context, monitor);
@@ -244,7 +244,7 @@
 			// if the root wasn't uninstalled, then continue
 			if (plan.getRemovals().query(QueryUtil.createIUQuery(initialRoot), null).isEmpty())
 				continue;
-			// otherwise add its removal to the change request, along with a negation and 
+			// otherwise add its removal to the change request, along with a negation and
 			// change of strict to optional for their inclusion rule.
 			finalRequest.remove(initialRoot);
 			finalRequest.setInstallableUnitProfileProperty(initialRoot, INCLUSION_RULES, INCLUSION_OPTIONAL);
@@ -273,14 +273,14 @@
 	}
 
 	/*
-	 * If the request contains IUs to be moved then create and execute a plan which 
+	 * If the request contains IUs to be moved then create and execute a plan which
 	 * removes them. Otherwise just return.
 	 */
 	private IStatus performRemoveForMovedIUs(ReconcilerProfileChangeRequest request, ProvisioningContext context, IProgressMonitor monitor) {
 		Collection<IInstallableUnit> moves = request.getMoves();
 		if (moves.isEmpty())
 			return Status.OK_STATUS;
-		IEngine engine = (IEngine) agent.getService(IEngine.SERVICE_NAME);
+		IEngine engine = agent.getService(IEngine.class);
 		IProvisioningPlan plan = engine.createPlan(profile, context);
 		for (IInstallableUnit unit : moves)
 			plan.removeInstallableUnit(unit);
@@ -288,7 +288,7 @@
 	}
 
 	/*
-	 * Write out the timestamps of various repositories and folders/file to help 
+	 * Write out the timestamps of various repositories and folders/file to help
 	 * us cache and detect cases where we don't have to perform a reconciliation.
 	 */
 	private void writeTimestamps() {
@@ -312,8 +312,7 @@
 			try (OutputStream os = new BufferedOutputStream(new FileOutputStream(file))) {
 				CollectionUtils.storeProperties(timestamps, os, "Timestamps for " + profile.getProfileId()); //$NON-NLS-1$
 				if (Tracing.DEBUG_RECONCILER) {
-					for (Iterator<String> iter = timestamps.keySet().iterator(); iter.hasNext();) {
-						String key = iter.next();
+					for (String key : timestamps.keySet()) {
 						Object value = timestamps.get(key);
 						Activator.trace(key + '=' + value);
 					}
@@ -365,7 +364,7 @@
 
 			String key = entry.getKey();
 			String lastKnownTimestamp = timestamps.remove(key);
-			//A repo has been added 
+			//A repo has been added
 			if (lastKnownTimestamp == null) {
 				Activator.trace("No cached timestamp found for: " + key); //$NON-NLS-1$
 				Activator.trace("Performing reconciliation."); //$NON-NLS-1$
@@ -386,8 +385,8 @@
 		//A repo has been removed
 		if (Tracing.DEBUG_RECONCILER) {
 			Activator.trace("Extra values in timestamp file:"); //$NON-NLS-1$
-			for (Iterator<String> iter = timestamps.keySet().iterator(); iter.hasNext();)
-				Activator.trace(iter.next());
+			for (String string : timestamps.keySet())
+				Activator.trace(string);
 			Activator.trace("Performing reconciliation."); //$NON-NLS-1$
 		}
 		return false;
@@ -423,9 +422,9 @@
 
 	private ProvisioningContext getContext() {
 		ArrayList<URI> repoURLs = new ArrayList<>();
-		for (Iterator<String> iterator = repositoryMap.keySet().iterator(); iterator.hasNext();) {
+		for (String string : repositoryMap.keySet()) {
 			try {
-				repoURLs.add(new URI(iterator.next()));
+				repoURLs.add(new URI(string));
 			} catch (URISyntaxException e) {
 				//ignore
 			}
@@ -445,7 +444,7 @@
 		final String OSGiInstallArea;
 		try {
 			// The OSGi install area is an unencoded URL and repository locations are encoded URIs
-			// so make them the same so we can compare them. 
+			// so make them the same so we can compare them.
 			// See https://bugs.eclipse.org/346565.
 			OSGiInstallArea = URIUtil.toURI(installArea).toString() + Constants.EXTENSION_LOCATION;
 			// Sort the repositories so the extension location at the OSGi install folder is first.
@@ -516,8 +515,7 @@
 	private Map<IInstallableUnit, IInstallableUnit> getProfileIUs() {
 		IQueryResult<IInstallableUnit> profileQueryResult = profile.query(QueryUtil.createIUAnyQuery(), null);
 		Map<IInstallableUnit, IInstallableUnit> result = new HashMap<>();
-		for (Iterator<IInstallableUnit> it = profileQueryResult.iterator(); it.hasNext();) {
-			IInstallableUnit iu = it.next();
+		for (IInstallableUnit iu : profileQueryResult) {
 			result.put(iu, iu);
 		}
 		return result;
@@ -530,8 +528,7 @@
 	private Map<IInstallableUnit, IInstallableUnit> getAvailableProfileIUs() {
 		IQueryResult<IInstallableUnit> profileQueryResult = profile.available(QueryUtil.createIUAnyQuery(), null);
 		Map<IInstallableUnit, IInstallableUnit> result = new HashMap<>();
-		for (Iterator<IInstallableUnit> it = profileQueryResult.iterator(); it.hasNext();) {
-			IInstallableUnit iu = it.next();
+		for (IInstallableUnit iu : profileQueryResult) {
 			result.put(iu, iu);
 		}
 		return result;
@@ -561,7 +558,7 @@
 		// we use IProfile.available(...) here so that we also gather any shared IUs
 		Map<IInstallableUnit, IInstallableUnit> availableProfileIUs = getAvailableProfileIUs();
 
-		// get all IUs from all our repos 
+		// get all IUs from all our repos
 		IQueryResult<IInstallableUnit> allIUs = getAllIUsFromRepos();
 		for (Iterator<IInstallableUnit> iter = allIUs.iterator(); iter.hasNext();) {
 			final IInstallableUnit iu = iter.next();
@@ -594,7 +591,7 @@
 			request.setInstallableUnitInclusionRules(iu, ProfileInclusionRules.createOptionalInclusionRule(iu));
 			request.setInstallableUnitProfileProperty(iu, IProfile.PROP_PROFILE_LOCKED_IU, Integer.toString(IProfile.LOCK_UNINSTALL));
 
-			// as soon as we find something locally that needs to be installed, then 
+			// as soon as we find something locally that needs to be installed, then
 			// everything from the parent's dropins must be installed locally as well.
 			if (!foundIUsToAdd && availableProfileIUs.get(iu) == null) {
 				foundIUsToAdd = true;
@@ -604,8 +601,7 @@
 		// get all IUs from profile with marked property (existing)
 		IQueryResult<IInstallableUnit> dropinIUs = profile.query(new IUProfilePropertyQuery(PROP_FROM_DROPINS, Boolean.TRUE.toString()), null);
 		Set<IInstallableUnit> all = allIUs.toUnmodifiableSet();
-		for (Iterator<IInstallableUnit> iter = dropinIUs.iterator(); iter.hasNext();) {
-			IInstallableUnit iu = iter.next();
+		for (IInstallableUnit iu : dropinIUs) {
 			// the STRICT policy is set when we install things via the UI, we use it to differentiate between IUs installed
 			// via the dropins and the UI. (dropins are considered optional) If an IU has both properties set it means that
 			// it was initially installed via the dropins but then upgraded via the UI. (properties are copied from the old IU
@@ -646,7 +642,7 @@
 	}
 
 	/*
-	 * If in debug mode, print out information which tells us whether or not the given 
+	 * If in debug mode, print out information which tells us whether or not the given
 	 * provisioning plan matches the request.
 	 */
 	private void debug(ReconcilerProfileChangeRequest request, IProvisioningPlan plan) {
@@ -659,14 +655,12 @@
 		List<IInstallableUnit> toMove = new ArrayList<>(request.getMoves());
 
 		// remove from the request everything that is in the plan
-		for (Iterator<IInstallableUnit> iterator = plan.getRemovals().query(QueryUtil.createIUAnyQuery(), null).iterator(); iterator.hasNext();) {
-			IInstallableUnit iu = iterator.next();
+		for (IInstallableUnit iu : plan.getRemovals().query(QueryUtil.createIUAnyQuery(), null)) {
 			if (!toRemove.remove(iu)) {
 				Tracing.debug(PREFIX + iu + " will be removed"); //$NON-NLS-1$
 			}
 		}
-		for (Iterator<IInstallableUnit> iterator = plan.getAdditions().query(QueryUtil.createIUAnyQuery(), null).iterator(); iterator.hasNext();) {
-			IInstallableUnit iu = iterator.next();
+		for (IInstallableUnit iu : plan.getAdditions().query(QueryUtil.createIUAnyQuery(), null)) {
 			if (!toAdd.remove(iu)) {
 				Tracing.debug(PREFIX + iu + " will be added"); //$NON-NLS-1$
 			}
@@ -766,7 +760,7 @@
 	 * Create and return a provisioning plan for the given change request.
 	 */
 	private IProvisioningPlan createProvisioningPlan(ProfileChangeRequest request, ProvisioningContext provisioningContext, IProgressMonitor monitor) {
-		IPlanner planner = (IPlanner) agent.getService(IPlanner.SERVICE_NAME);
+		IPlanner planner = agent.getService(IPlanner.class);
 		return planner.getProvisioningPlan(request, provisioningContext, monitor);
 	}
 
@@ -774,7 +768,7 @@
 	 * Call the engine to set the given property on the profile.
 	 */
 	private IStatus setProperty(String key, String value, ProvisioningContext provisioningContext, IProgressMonitor monitor) {
-		IEngine engine = (IEngine) agent.getService(IEngine.SERVICE_NAME);
+		IEngine engine = agent.getService(IEngine.class);
 		IProvisioningPlan plan = engine.createPlan(profile, provisioningContext);
 		plan.setProfileProperty(key, value);
 		IPhaseSet phaseSet = PhaseSetFactory.createPhaseSetIncluding(new String[] {PhaseSetFactory.PHASE_PROPERTY});
@@ -785,7 +779,7 @@
 	 * Execute the given plan.
 	 */
 	private IStatus executePlan(IProvisioningPlan plan, ProvisioningContext provisioningContext, IProgressMonitor monitor) {
-		IEngine engine = (IEngine) agent.getService(IEngine.SERVICE_NAME);
+		IEngine engine = agent.getService(IEngine.class);
 		IPhaseSet phaseSet = PhaseSetFactory.createDefaultPhaseSetExcluding(new String[] {PhaseSetFactory.PHASE_COLLECT, PhaseSetFactory.PHASE_CHECK_TRUST});
 
 		if (plan.getInstallerPlan() != null) {
@@ -824,8 +818,8 @@
 		String[] args = info.getCommandLineArgs();
 		if (args == null)
 			return false;
-		for (int i = 0; i < args.length; i++) {
-			if (args[i] != null && RECONCILER_APPLICATION_ID.equals(args[i].trim()))
+		for (String arg : args) {
+			if (arg != null && RECONCILER_APPLICATION_ID.equals(arg.trim()))
 				return true;
 		}
 		return false;
diff --git a/bundles/org.eclipse.equinox.p2.repository/src/org/eclipse/equinox/internal/p2/repository/CacheManagerComponent.java b/bundles/org.eclipse.equinox.p2.repository/src/org/eclipse/equinox/internal/p2/repository/CacheManagerComponent.java
index 44b1a30..81c4128 100644
--- a/bundles/org.eclipse.equinox.p2.repository/src/org/eclipse/equinox/internal/p2/repository/CacheManagerComponent.java
+++ b/bundles/org.eclipse.equinox.p2.repository/src/org/eclipse/equinox/internal/p2/repository/CacheManagerComponent.java
@@ -7,7 +7,7 @@
  *  https://www.eclipse.org/legal/epl-2.0/

  *

  *  SPDX-License-Identifier: EPL-2.0

- * 

+ *

  *  Contributors:

  *     Sonatype, Inc. - initial API and implementation

  *******************************************************************************/

@@ -22,8 +22,9 @@
 

 	@Override

 	public Object createService(IProvisioningAgent agent) {

-		final IProvisioningEventBus eventBus = (IProvisioningEventBus) agent.getService(IProvisioningEventBus.SERVICE_NAME);

-		CacheManager cache = new CacheManager((IAgentLocation) agent.getService(IAgentLocation.SERVICE_NAME), (Transport) agent.getService(Transport.SERVICE_NAME));

+		final IProvisioningEventBus eventBus = agent.getService(IProvisioningEventBus.class);

+		CacheManager cache = new CacheManager(agent.getService(IAgentLocation.class),

+				agent.getService(Transport.class));

 		cache.setEventBus(eventBus);

 		return cache;

 	}

diff --git a/bundles/org.eclipse.equinox.p2.repository/src/org/eclipse/equinox/internal/p2/repository/Credentials.java b/bundles/org.eclipse.equinox.p2.repository/src/org/eclipse/equinox/internal/p2/repository/Credentials.java
index 48ecf12..cae79e9 100644
--- a/bundles/org.eclipse.equinox.p2.repository/src/org/eclipse/equinox/internal/p2/repository/Credentials.java
+++ b/bundles/org.eclipse.equinox.p2.repository/src/org/eclipse/equinox/internal/p2/repository/Credentials.java
@@ -28,7 +28,7 @@
 /**
  * Credentials handles AuthenticationInfo that can be used to established an
  * ECF connection context. An AuthenticationInfo is obtained for a URI buy looking
- * in a store, if none is provided the user is optionally prompted for the information. 
+ * in a store, if none is provided the user is optionally prompted for the information.
  */
 public class Credentials {
 	public static class LoginCanceledException extends Exception {
@@ -36,7 +36,7 @@
 
 	}
 
-	/** 
+	/**
 	 * Cache of auth information that is not persisted, and modified auth info.
 	 */
 	private static final Map<String, UIServices.AuthenticationInfo> savedAuthInfo = Collections.synchronizedMap(new HashMap<String, UIServices.AuthenticationInfo>());
@@ -47,16 +47,16 @@
 	 */
 	private static Map<String, HostEntry> remembered;
 
-	/** 
-	 * Serializes pop up of login/password prompt 
+	/**
+	 * Serializes pop up of login/password prompt
 	 */
 	private static final Object promptLock = new Object();
 
 	/**
 	 * Returns the AuthenticationInfo for the given URI. This may prompt the
 	 * user for user name and password as required.
-	 * 
-	 * If the URI is opaque, the entire URI is used as the key. For non opaque URIs, 
+	 *
+	 * If the URI is opaque, the entire URI is used as the key. For non opaque URIs,
 	 * the key is based on the host name, using a host name of "localhost" if host name is
 	 * missing.
 	 *
@@ -75,14 +75,14 @@
 	/**
 	 * Returns the AuthenticationInfo for the given URI. This may prompt the
 	 * user for user name and password as required.
-	 * 
-	 * If the URI is opaque, the entire URI is used as the key. For non opaque URIs, 
+	 *
+	 * If the URI is opaque, the entire URI is used as the key. For non opaque URIs,
 	 * the key is based on the host name, using a host name of "localhost" if host name is
 	 * missing.
-	 * 
+	 *
 	 * This method allows passing a previously used AuthenticationInfo. If set, the user interface
 	 * may present the information "on file" to the user for editing.
-	 * 
+	 *
 	 * @param location - the location for which to obtain authentication information
 	 * @param prompt - if true, user will be prompted for information
 	 * @param lastUsed - optional information used in an previous attempt to login
@@ -98,7 +98,7 @@
 		} catch (UnsupportedEncodingException e2) {
 			// fall back to default platform encoding
 			try {
-				// Uses getProperty "file.encoding" instead of using deprecated URLEncoder.encode(String location) 
+				// Uses getProperty "file.encoding" instead of using deprecated URLEncoder.encode(String location)
 				// which does the same, but throws NPE on missing property.
 				String enc = System.getProperty("file.encoding");//$NON-NLS-1$
 				if (enc == null)
@@ -207,7 +207,7 @@
 					if (getPromptCount(host) >= RepositoryPreferences.getLoginRetryCount()) {
 						if (lastUsed == null && latest == null)
 							DebugHelper.debug("Credentials", "forLocation:NO INFO - SYNTHETIC CANCEL", // //$NON-NLS-1$ //$NON-NLS-2$
-									new Object[] {"host", location}); //$NON-NLS-1$ 
+									new Object[] {"host", location}); //$NON-NLS-1$
 						return latest == null ? lastUsed : latest; // keep client failing on the latest known
 					}
 					DebugHelper.debug("Credentials", "forLocation:LATER INFO AVAILABLE - RETURNING IT", // //$NON-NLS-1$ //$NON-NLS-2$
@@ -220,14 +220,14 @@
 					return latest == null ? lastUsed : latest; // keep client failing on the latest known
 				}
 				IProvisioningAgent agent = ServiceHelper.getService(Activator.getContext(), IProvisioningAgent.class);
-				UIServices adminUIService = (UIServices) agent.getService(UIServices.SERVICE_NAME);
+				UIServices adminUIService = agent.getService(UIServices.class);
 
 				if (adminUIService != null)
 					synchronized (promptLock) {
 						try {
 							if (DebugHelper.DEBUG_REPOSITORY_CREDENTIALS) {
 								DebugHelper.debug("Credentials", "forLocation:PROMPTLOCK OBTAINED", // //$NON-NLS-1$ //$NON-NLS-2$
-										new Object[] {"host", location}); //$NON-NLS-1$ 					
+										new Object[] {"host", location}); //$NON-NLS-1$
 							}
 
 							// serialize the popping of the dialog itself
@@ -236,7 +236,7 @@
 							if (DebugHelper.DEBUG_REPOSITORY_CREDENTIALS) {
 								if (loginDetails == UIServices.AUTHENTICATION_PROMPT_CANCELED)
 									DebugHelper.debug("Credentials", "forLocation:PROMPTED - USER CANCELED (PROMPT LOCK RELEASED)", // //$NON-NLS-1$ //$NON-NLS-2$
-											new Object[] {"host", location}); //$NON-NLS-1$					
+											new Object[] {"host", location}); //$NON-NLS-1$
 							}
 							if (loginDetails == UIServices.AUTHENTICATION_PROMPT_CANCELED) {
 								rememberCancel(host);
@@ -248,7 +248,7 @@
 							if (DebugHelper.DEBUG_REPOSITORY_CREDENTIALS) {
 								if (loginDetails.saveResult())
 									DebugHelper.debug("Credentials", "forLocation:SAVING RESULT", // //$NON-NLS-1$ //$NON-NLS-2$
-											new Object[] {"host", location}); //$NON-NLS-1$					
+											new Object[] {"host", location}); //$NON-NLS-1$
 							}
 
 							if (loginDetails.saveResult()) {
@@ -268,7 +268,7 @@
 								if (securePreferences.nodeExists(nodeName)) {
 									if (DebugHelper.DEBUG_REPOSITORY_CREDENTIALS) {
 										DebugHelper.debug("Credentials", "forLocation:REMOVING PREVIOUSLY SAVED INFO", // //$NON-NLS-1$ //$NON-NLS-2$
-												new Object[] {"host", location}); //$NON-NLS-1$					
+												new Object[] {"host", location}); //$NON-NLS-1$
 									}
 
 									prefNode = securePreferences.node(nodeName);
@@ -284,7 +284,7 @@
 						} finally {
 							if (DebugHelper.DEBUG_REPOSITORY_CREDENTIALS) {
 								DebugHelper.debug("Credentials", "forLocation:PROMPTLOCK RELEASED", // //$NON-NLS-1$ //$NON-NLS-2$
-										new Object[] {"host", location}); //$NON-NLS-1$					
+										new Object[] {"host", location}); //$NON-NLS-1$
 							}
 						}
 					}
@@ -292,7 +292,7 @@
 			} finally {
 				if (DebugHelper.DEBUG_REPOSITORY_CREDENTIALS) {
 					DebugHelper.debug("Credentials", "forLocation:HOSTLOCK RELEASED", // //$NON-NLS-1$ //$NON-NLS-2$
-							new Object[] {"host", location}); //$NON-NLS-1$					
+							new Object[] {"host", location}); //$NON-NLS-1$
 				}
 			}
 
@@ -359,7 +359,7 @@
 				if (((HostEntry) x).isCanceled()) {
 					if (DebugHelper.DEBUG_REPOSITORY_CREDENTIALS) {
 						DebugHelper.debug("Credentials", "checkRememberCancel:PREVIOUSLY CANCELED", // //$NON-NLS-1$ //$NON-NLS-2$
-								new Object[] {"host", host}); //$NON-NLS-1$ 
+								new Object[] {"host", host}); //$NON-NLS-1$
 					}
 
 					throw new LoginCanceledException();
@@ -430,7 +430,7 @@
 
 	/**
 	 * Clears the cached information for host about prompts for login/password and
-	 * canceled logins. 
+	 * canceled logins.
 	 * @param host a host as returned from uriToHost for a location
 	 */
 	public static synchronized void clearPromptCache(String host) {
diff --git a/bundles/org.eclipse.equinox.p2.repository/src/org/eclipse/equinox/internal/p2/repository/ProgressStatistics.java b/bundles/org.eclipse.equinox.p2.repository/src/org/eclipse/equinox/internal/p2/repository/ProgressStatistics.java
index 0c8e375..3ca4f8b 100644
--- a/bundles/org.eclipse.equinox.p2.repository/src/org/eclipse/equinox/internal/p2/repository/ProgressStatistics.java
+++ b/bundles/org.eclipse.equinox.p2.repository/src/org/eclipse/equinox/internal/p2/repository/ProgressStatistics.java
@@ -7,7 +7,7 @@
  *  https://www.eclipse.org/legal/epl-2.0/
  *
  *  SPDX-License-Identifier: EPL-2.0
- * 
+ *
  *  Contributors:
  * 	Cloudsmith Inc - initial API and implementation
  * 	IBM Corporation - ongoing development
@@ -50,7 +50,7 @@
 
 	private void publishEvent(DownloadProgressEvent event) {
 		if (m_agent != null) {
-			IProvisioningEventBus eventBus = (IProvisioningEventBus) m_agent.getService(IProvisioningEventBus.SERVICE_NAME);
+			IProvisioningEventBus eventBus = m_agent.getService(IProvisioningEventBus.class);
 			if (eventBus != null) {
 				eventBus.publishEvent(event);
 			}
diff --git a/bundles/org.eclipse.equinox.p2.repository/src/org/eclipse/equinox/internal/p2/repository/helpers/AbstractRepositoryManager.java b/bundles/org.eclipse.equinox.p2.repository/src/org/eclipse/equinox/internal/p2/repository/helpers/AbstractRepositoryManager.java
index c2001ef..32ce41d 100644
--- a/bundles/org.eclipse.equinox.p2.repository/src/org/eclipse/equinox/internal/p2/repository/helpers/AbstractRepositoryManager.java
+++ b/bundles/org.eclipse.equinox.p2.repository/src/org/eclipse/equinox/internal/p2/repository/helpers/AbstractRepositoryManager.java
@@ -7,7 +7,7 @@
  * https://www.eclipse.org/legal/epl-2.0/
  *
  * SPDX-License-Identifier: EPL-2.0
- * 
+ *
  * Contributors:
  *     IBM Corporation - initial API and implementation
  *     Wind River - fix for bug 299227
@@ -102,8 +102,8 @@
 	protected AbstractRepositoryManager(IProvisioningAgent agent) {
 		super();
 		this.agent = agent;
-		agentLocation = (IAgentLocation) agent.getService(IAgentLocation.SERVICE_NAME);
-		eventBus = (IProvisioningEventBus) agent.getService(IProvisioningEventBus.SERVICE_NAME);
+		agentLocation = agent.getService(IAgentLocation.class);
+		eventBus = agent.getService(IProvisioningEventBus.class);
 		eventBus.addListener(this);
 	}
 
@@ -149,11 +149,11 @@
 	}
 
 	/**
-	 * Adds the repository to the list of known repositories. 
+	 * Adds the repository to the list of known repositories.
 	 * @param location The repository location
 	 * @param isEnabled Whether the repository should be enabled
 	 * @param signalAdd Whether a repository add event should be broadcast
-	 * @return <code>true</code> if the repository was actually added, and 
+	 * @return <code>true</code> if the repository was actually added, and
 	 * <code>false</code> otherwise.
 	 */
 	private boolean addRepository(URI location, boolean isEnabled, boolean signalAdd) {
@@ -303,10 +303,10 @@
 	 */
 	protected Object createExecutableExtension(IExtension extension, String element) {
 		IConfigurationElement[] elements = extension.getConfigurationElements();
-		for (int i = 0; i < elements.length; i++) {
-			if (elements[i].getName().equals(element)) {
+		for (IConfigurationElement element2 : elements) {
+			if (element2.getName().equals(element)) {
 				try {
-					return elements[i].createExecutableExtension("class"); //$NON-NLS-1$
+					return element2.createExecutableExtension("class"); //$NON-NLS-1$
 				} catch (CoreException e) {
 					log("Error loading repository extension: " + extension.getUniqueIdentifier(), e); //$NON-NLS-1$
 					return null;
@@ -321,10 +321,10 @@
 	 * Obtains an exclusive right to load a repository at the given location. Blocks
 	 * if another thread is currently loading at that location. Invocation of this
 	 * method must be followed by a subsequent call to {@link #exitLoad(URI)}.
-	 * 
+	 *
 	 * To avoid deadlock between the loadLock and repositoryLock, this method
 	 * must not be called when repositoryLock is held.
-	 * 
+	 *
 	 * @param location The location to lock
 	 */
 	private void enterLoad(URI location, IProgressMonitor monitor) {
@@ -415,9 +415,9 @@
 			}
 		}
 		IExtension[] results = new IExtension[count];
-		for (int i = 0; i < elt.length; i++) {
-			if (elt[i] != null)
-				results[--count] = elt[i].getDeclaringExtension();
+		for (IConfigurationElement element : elt) {
+			if (element != null)
+				results[--count] = element.getDeclaringExtension();
 		}
 		return results;
 	}
@@ -431,9 +431,9 @@
 		IConfigurationElement[] elements = registry.getConfigurationElementsFor(getRepositoryProviderExtensionPointId());
 		ArrayList<String> result = new ArrayList<>(elements.length);
 		result.add(getDefaultSuffix());
-		for (int i = 0; i < elements.length; i++) {
-			if (elements[i].getName().equals(EL_FILTER)) {
-				String suffix = elements[i].getAttribute(ATTR_SUFFIX);
+		for (IConfigurationElement element : elements) {
+			if (element.getName().equals(EL_FILTER)) {
+				String suffix = element.getAttribute(ATTR_SUFFIX);
 				if (!result.contains(suffix))
 					result.add(suffix);
 			}
@@ -667,17 +667,17 @@
 			sub = SubMonitor.convert(sub, NLS.bind(Messages.repoMan_adding, location), suffixes.length * 100);
 			ProvisionException failure = null;
 			try {
-				for (int i = 0; i < suffixes.length; i++) {
+				for (String suffixe : suffixes) {
 					if (sub.isCanceled())
 						throw new OperationCanceledException();
 					try {
-						result = loadRepository(location, suffixes[i], type, flags, sub.newChild(100));
+						result = loadRepository(location, suffixe, type, flags, sub.newChild(100));
 					} catch (ProvisionException e) {
 						failure = e;
 						break;
 					}
 					if (result != null) {
-						addRepository(result, false, suffixes[i]);
+						addRepository(result, false, suffixe);
 						break;
 					}
 				}
@@ -768,9 +768,9 @@
 		IExtension[] providers = findMatchingRepositoryExtensions(suffix, type);
 		// Loop over the candidates and return the first one that successfully loads
 		monitor.beginTask(null, providers.length * 10);
-		for (int i = 0; i < providers.length; i++)
+		for (IExtension provider : providers)
 			try {
-				IRepository<T> repo = factoryLoad(location, providers[i], flags, monitor);
+				IRepository<T> repo = factoryLoad(location, provider, flags, monitor);
 				if (repo != null)
 					return repo;
 			} catch (ProvisionException e) {
@@ -781,10 +781,10 @@
 				throw e;
 			} catch (Exception e) {
 				//catch and log unexpected errors and move onto the next factory
-				log("Unexpected error loading extension: " + providers[i].getUniqueIdentifier(), e); //$NON-NLS-1$
+				log("Unexpected error loading extension: " + provider.getUniqueIdentifier(), e); //$NON-NLS-1$
 			} catch (LinkageError e) {
 				//catch and log unexpected errors and move onto the next factory
-				log("Unexpected error loading extension: " + providers[i].getUniqueIdentifier(), e); //$NON-NLS-1$
+				log("Unexpected error loading extension: " + provider.getUniqueIdentifier(), e); //$NON-NLS-1$
 			}
 		return null;
 	}
@@ -872,7 +872,7 @@
 
 	/**
 	 * Writes the state of the repository information into the appropriate preference node.
-	 * 
+	 *
 	 * @param info The info to write to the preference node
 	 * @param flush <code>true</code> if the preference node should be flushed to
 	 * disk, and <code>false</code> otherwise
@@ -969,8 +969,8 @@
 			log("Error restoring repositories from preferences", e); //$NON-NLS-1$
 			return;
 		}
-		for (int i = 0; i < children.length; i++) {
-			Preferences child = node.node(children[i]);
+		for (String element : children) {
+			Preferences child = node.node(element);
 			URI location = getRepositoryLocation(child);
 			if (location == null) {
 				try {
@@ -1084,7 +1084,7 @@
 	}
 
 	/**
-	 * Optimize the order in which repository suffixes are searched by trying 
+	 * Optimize the order in which repository suffixes are searched by trying
 	 * the last successfully loaded suffix first.
 	 * @nooverride This method is not intended to be re-implemented or extended by clients.
 	 * @noreference This method is not intended to be referenced by clients.
@@ -1111,8 +1111,7 @@
 			// Now make sure that anything in the "preferredOrder" is at the top
 			if (preferredOrder != null) {
 				int priority = 0;
-				for (int i = 0; i < preferredOrder.length; i++) {
-					String currentSuffix = preferredOrder[i];
+				for (String currentSuffix : preferredOrder) {
 					if (LocationProperties.END.equals(currentSuffix.trim())) {
 						// All suffixes from here on should be ignored
 						String[] tmp = new String[priority];
@@ -1136,8 +1135,8 @@
 	}
 
 	/**
-	 * Performs a query against the contents of each known 
-	 * repository, accumulating any objects that satisfy the query in the 
+	 * Performs a query against the contents of each known
+	 * repository, accumulating any objects that satisfy the query in the
 	 * provided collector.
 	 * <p>
 	 * Note that using this method can be quite expensive, as every known
@@ -1147,8 +1146,8 @@
 	 * loaded and then query each of the returned repositories.
 	 * <p>
 	 * This method is long-running; progress and cancellation are provided
-	 * by the given progress monitor. 
-	 * 
+	 * by the given progress monitor.
+	 *
 	 * @param query The query to perform against each element in each known repository
 	 * @param monitor a progress monitor, or <code>null</code> if progress
 	 *    reporting is not desired
@@ -1159,11 +1158,11 @@
 		URI[] locations = getKnownRepositories(REPOSITORIES_ALL);
 		List<IRepository<T>> queryables = new ArrayList<>(locations.length); // use a list since we don't know exactly how many will load
 		SubMonitor sub = SubMonitor.convert(monitor, locations.length * 10);
-		for (int i = 0; i < locations.length; i++) {
+		for (URI location : locations) {
 			try {
 				if (sub.isCanceled())
 					throw new OperationCanceledException();
-				queryables.add(loadRepository(locations[i], sub.newChild(9), null, 0));
+				queryables.add(loadRepository(location, sub.newChild(9), null, 0));
 			} catch (ProvisionException e) {
 				//ignore this repository for this query
 			}
@@ -1185,15 +1184,14 @@
 	}
 
 	protected Transport getTransport() {
-		return (Transport) agent.getService(Transport.SERVICE_NAME);
+		return agent.getService(Transport.class);
 	}
 
 	public void flushCache() {
 		synchronized (repositoryLock) {
 			if (repositories != null) {
 				Collection<RepositoryInfo<T>> repos = repositories.values();
-				for (Iterator<RepositoryInfo<T>> iterator = repos.iterator(); iterator.hasNext();) {
-					RepositoryInfo<T> repositoryInfo = iterator.next();
+				for (RepositoryInfo<T> repositoryInfo : repos) {
 					repositoryInfo.repository = null;
 				}
 			}
diff --git a/bundles/org.eclipse.equinox.p2.tests/src/org/eclipse/equinox/p2/tests/TestAgentProvider.java b/bundles/org.eclipse.equinox.p2.tests/src/org/eclipse/equinox/p2/tests/TestAgentProvider.java
index 11c87de..cc12d18 100644
--- a/bundles/org.eclipse.equinox.p2.tests/src/org/eclipse/equinox/p2/tests/TestAgentProvider.java
+++ b/bundles/org.eclipse.equinox.p2.tests/src/org/eclipse/equinox/p2/tests/TestAgentProvider.java
@@ -25,7 +25,8 @@
 import org.osgi.framework.ServiceReference;
 
 /**
- * Provides {@link IProvisioningAgent} instances for tests. Use as JUnit 4 {@link Rule}.
+ * Provides {@link IProvisioningAgent} instances for tests. Use as JUnit 4
+ * {@link Rule}.
  */
 public final class TestAgentProvider extends ExternalResource {
 	private final TemporaryFolder tempManager;
@@ -49,8 +50,9 @@
 	}
 
 	/**
-	 * Returns an instance of an {@link IProvisioningAgent}. If this class is used as a JUnit method
-	 * {@link Rule}, a separate instance is returned per test method.
+	 * Returns an instance of an {@link IProvisioningAgent}. If this class is used
+	 * as a JUnit method {@link Rule}, a separate instance is returned per test
+	 * method.
 	 */
 	public IProvisioningAgent getAgent() throws ProvisionException {
 		if (agent == null) {
@@ -65,7 +67,8 @@
 
 	private IProvisioningAgent createProvisioningAgent(File location) throws ProvisionException {
 		BundleContext bundleContext = FrameworkUtil.getBundle(this.getClass()).getBundleContext();
-		ServiceReference<IProvisioningAgentProvider> serviceReference = bundleContext.getServiceReference(IProvisioningAgentProvider.class);
+		ServiceReference<IProvisioningAgentProvider> serviceReference = bundleContext
+				.getServiceReference(IProvisioningAgentProvider.class);
 		IProvisioningAgentProvider agentFactory = bundleContext.getService(serviceReference);
 		try {
 			return agentFactory.createAgent(location.toURI());
@@ -80,7 +83,7 @@
 	 * @see #getAgent()
 	 */
 	public <T> T getService(Class<T> type) throws ProvisionException {
-		return type.cast(getAgent().getService(type.getName()));
+		return getAgent().getService(type);
 	}
 
 }
diff --git a/bundles/org.eclipse.equinox.p2.tests/src/org/eclipse/equinox/p2/tests/full/AbstractEnd2EndTest.java b/bundles/org.eclipse.equinox.p2.tests/src/org/eclipse/equinox/p2/tests/full/AbstractEnd2EndTest.java
index c0021b7..a664bae 100644
--- a/bundles/org.eclipse.equinox.p2.tests/src/org/eclipse/equinox/p2/tests/full/AbstractEnd2EndTest.java
+++ b/bundles/org.eclipse.equinox.p2.tests/src/org/eclipse/equinox/p2/tests/full/AbstractEnd2EndTest.java
@@ -145,7 +145,7 @@
 	}
 
 	private void rollbackPlatformSource(IProfile profile2, File installFolder) {
-		IProfileRegistry profileRegistry = (IProfileRegistry) end2endAgent.getService(IProfileRegistry.SERVICE_NAME);
+		IProfileRegistry profileRegistry = end2endAgent.getService(IProfileRegistry.class);
 		long[] timestamps = profileRegistry.listProfileTimestamps(profile2.getProfileId());
 		assertEquals(3, timestamps.length);
 
diff --git a/bundles/org.eclipse.equinox.p2.tests/src/org/eclipse/equinox/p2/tests/planner/Bug306279f.java b/bundles/org.eclipse.equinox.p2.tests/src/org/eclipse/equinox/p2/tests/planner/Bug306279f.java
index 9cc2bc2..b4517cd 100644
--- a/bundles/org.eclipse.equinox.p2.tests/src/org/eclipse/equinox/p2/tests/planner/Bug306279f.java
+++ b/bundles/org.eclipse.equinox.p2.tests/src/org/eclipse/equinox/p2/tests/planner/Bug306279f.java
@@ -7,15 +7,20 @@
  *  https://www.eclipse.org/legal/epl-2.0/
  *
  *  SPDX-License-Identifier: EPL-2.0
- * 
+ *
  *  Contributors:
  *     Sonatype, Inc. - initial API and implementation
  *******************************************************************************/
 package org.eclipse.equinox.p2.tests.planner;
 
 import org.eclipse.core.runtime.NullProgressMonitor;
-import org.eclipse.equinox.p2.core.*;
-import org.eclipse.equinox.p2.engine.*;
+import org.eclipse.equinox.p2.core.IProvisioningAgent;
+import org.eclipse.equinox.p2.core.IProvisioningAgentProvider;
+import org.eclipse.equinox.p2.core.ProvisionException;
+import org.eclipse.equinox.p2.engine.IProfile;
+import org.eclipse.equinox.p2.engine.IProfileRegistry;
+import org.eclipse.equinox.p2.engine.IProvisioningPlan;
+import org.eclipse.equinox.p2.engine.ProvisioningContext;
 import org.eclipse.equinox.p2.planner.IPlanner;
 import org.eclipse.equinox.p2.planner.IProfileChangeRequest;
 import org.eclipse.equinox.p2.query.QueryUtil;
@@ -26,12 +31,12 @@
 	public void testInstallBabel() throws ProvisionException {
 		IProvisioningAgentProvider provider = getAgentProvider();
 		IProvisioningAgent agent = provider.createAgent(getTestData("bug306279f data", "testData/bug306279f/p2").toURI());
-		IMetadataRepositoryManager repoMgr = (IMetadataRepositoryManager) agent.getService(IMetadataRepositoryManager.SERVICE_NAME);
+		IMetadataRepositoryManager repoMgr = agent.getService(IMetadataRepositoryManager.class);
 		repoMgr.addRepository(getTestData("bug306279f data", "testData/bug306279f/repo/helios/").toURI());
 		repoMgr.addRepository(getTestData("bug306279f data", "testData/bug306279f/repo/babel").toURI());
 
-		IPlanner planner = (IPlanner) agent.getService(IPlanner.SERVICE_NAME);
-		IProfile sdkProfile = ((IProfileRegistry) agent.getService(IProfileRegistry.SERVICE_NAME)).getProfile("SDKProfile");
+		IPlanner planner = agent.getService(IPlanner.class);
+		IProfile sdkProfile = agent.getService(IProfileRegistry.class).getProfile("SDKProfile");
 		IProfileChangeRequest request = planner.createChangeRequest(sdkProfile);
 		request.add(repoMgr.query(QueryUtil.createIUQuery("org.eclipse.babel.nls_rt.rap_en_AA.feature.group"), null).iterator().next());
 
diff --git a/bundles/org.eclipse.equinox.p2.tests/src/org/eclipse/equinox/p2/tests/touchpoint/eclipse/AgentFromInstallTests.java b/bundles/org.eclipse.equinox.p2.tests/src/org/eclipse/equinox/p2/tests/touchpoint/eclipse/AgentFromInstallTests.java
index 66aa794..a7e3418 100644
--- a/bundles/org.eclipse.equinox.p2.tests/src/org/eclipse/equinox/p2/tests/touchpoint/eclipse/AgentFromInstallTests.java
+++ b/bundles/org.eclipse.equinox.p2.tests/src/org/eclipse/equinox/p2/tests/touchpoint/eclipse/AgentFromInstallTests.java
@@ -13,9 +13,8 @@
  *******************************************************************************/
 package org.eclipse.equinox.p2.tests.touchpoint.eclipse;
 
-import org.eclipse.equinox.internal.p2.touchpoint.eclipse.AgentFromInstall;
-
 import java.io.File;
+import org.eclipse.equinox.internal.p2.touchpoint.eclipse.AgentFromInstall;
 import org.eclipse.equinox.p2.core.IProvisioningAgent;
 import org.eclipse.equinox.p2.engine.IProfile;
 import org.eclipse.equinox.p2.engine.IProfileRegistry;
@@ -27,7 +26,7 @@
 		File installFolder = getTestData("normalEclipse", "testData/configAreaToAgent/normalEclipse");
 		IProvisioningAgent agent = AgentFromInstall.createAgentFrom(getAgentProvider(), installFolder, null, null);
 		assertNotNull(agent);
-		IProfile profile = ((IProfileRegistry) agent.getService(IProfileRegistry.SERVICE_NAME)).getProfile(IProfileRegistry.SELF);
+		IProfile profile = agent.getService(IProfileRegistry.class).getProfile(IProfileRegistry.SELF);
 		assertNotNull(profile);
 		assertEquals("SDKProfile", profile.getProfileId());
 	}
@@ -36,7 +35,7 @@
 		File configurationFolder = getTestData("normalEclipse", "testData/configAreaToAgent/normalEclipse/configuration");
 		IProvisioningAgent agent = AgentFromInstall.createAgentFrom(getAgentProvider(), null, configurationFolder, null);
 		assertNotNull(agent);
-		IProfile profile = ((IProfileRegistry) agent.getService(IProfileRegistry.SERVICE_NAME)).getProfile(IProfileRegistry.SELF);
+		IProfile profile = agent.getService(IProfileRegistry.class).getProfile(IProfileRegistry.SELF);
 		assertNotNull(profile);
 		assertEquals("SDKProfile", profile.getProfileId());
 	}
@@ -45,7 +44,7 @@
 		File configurationFolder = getTestData("sharedWithoutBaseAvailable", "testData/configAreaToAgent/sharedWithoutBaseAvailable");
 		IProvisioningAgent agent = AgentFromInstall.createAgentFrom(getAgentProvider(), null, configurationFolder, null);
 		assertNotNull(agent);
-		IProfile profile = ((IProfileRegistry) agent.getService(IProfileRegistry.SERVICE_NAME)).getProfile(IProfileRegistry.SELF);
+		IProfile profile = agent.getService(IProfileRegistry.class).getProfile(IProfileRegistry.SELF);
 		assertNotNull(profile);
 		assertEquals("SDKProfile", profile.getProfileId());
 	}