diff --git a/ui/org.eclipse.pde.core/src/org/eclipse/pde/internal/core/TargetPlatformHelper.java b/ui/org.eclipse.pde.core/src/org/eclipse/pde/internal/core/TargetPlatformHelper.java index 0503431f52..20ba0f1f1d 100644 --- a/ui/org.eclipse.pde.core/src/org/eclipse/pde/internal/core/TargetPlatformHelper.java +++ b/ui/org.eclipse.pde.core/src/org/eclipse/pde/internal/core/TargetPlatformHelper.java @@ -1,5 +1,5 @@ /******************************************************************************* - * Copyright (c) 2000, 2023 IBM Corporation and others. + * Copyright (c) 2000, 2024 IBM Corporation and others. * * This program and the accompanying materials * are made available under the terms of the Eclipse Public License 2.0 @@ -292,7 +292,7 @@ public static ITargetDefinition getUnresolvedRepositoryBasedWorkspaceTarget() th private static boolean containsNotEmptyIULocation(ITargetLocation[] locations) { return locations != null && Arrays.stream(locations) // .filter(IUBundleContainer.class::isInstance).map(IUBundleContainer.class::cast) - .map(IUBundleContainer::getRepositories).anyMatch(uri -> uri != null && uri.length > 0); + .map(IUBundleContainer::getRepositories).anyMatch(uri -> !uri.isEmpty()); } public static Set getApplicationNameSet() { diff --git a/ui/org.eclipse.pde.core/src/org/eclipse/pde/internal/core/target/IUBundleContainer.java b/ui/org.eclipse.pde.core/src/org/eclipse/pde/internal/core/target/IUBundleContainer.java index 94e5651475..6b37242410 100644 --- a/ui/org.eclipse.pde.core/src/org/eclipse/pde/internal/core/target/IUBundleContainer.java +++ b/ui/org.eclipse.pde.core/src/org/eclipse/pde/internal/core/target/IUBundleContainer.java @@ -1,5 +1,5 @@ /******************************************************************************* - * Copyright (c) 2009, 2021 IBM Corporation and others. + * Copyright (c) 2009, 2024 IBM Corporation and others. * * This program and the accompanying materials * are made available under the terms of the Eclipse Public License 2.0 @@ -27,13 +27,15 @@ import java.util.Comparator; import java.util.HashMap; import java.util.HashSet; -import java.util.Iterator; import java.util.LinkedHashMap; import java.util.List; import java.util.Map; +import java.util.Objects; +import java.util.Optional; import java.util.Set; import java.util.concurrent.ConcurrentHashMap; import java.util.stream.IntStream; +import java.util.stream.Stream; import javax.xml.transform.OutputKeys; import javax.xml.transform.Transformer; @@ -53,7 +55,9 @@ import org.eclipse.equinox.p2.engine.IProfile; import org.eclipse.equinox.p2.metadata.IArtifactKey; import org.eclipse.equinox.p2.metadata.IInstallableUnit; +import org.eclipse.equinox.p2.metadata.IVersionedId; import org.eclipse.equinox.p2.metadata.Version; +import org.eclipse.equinox.p2.metadata.VersionedId; import org.eclipse.equinox.p2.query.IQuery; import org.eclipse.equinox.p2.query.IQueryResult; import org.eclipse.equinox.p2.query.IQueryable; @@ -111,7 +115,6 @@ public class IUBundleContainer extends AbstractBundleContainer { */ public static final int INCLUDE_CONFIGURE_PHASE = 1 << 3; - /** * Whether this container should follow repository references. */ @@ -134,9 +137,9 @@ public class IUBundleContainer extends AbstractBundleContainer { private IInstallableUnit[] fUnits; /** - * Repositories to consider, or null if default. + * Repositories to consider, empty if default. */ - private final URI[] fRepos; + private final List fRepos; /** * A set of bitmask flags that indicate how this container gets elements from its @@ -177,11 +180,7 @@ public class IUBundleContainer extends AbstractBundleContainer { fIds = ids; fFlags = resolutionFlags; fVersions = versions; - if (repositories == null || repositories.length == 0) { - fRepos = null; - } else { - fRepos = repositories; - } + fRepos = repositories == null ? List.of() : List.of(repositories); } @Override @@ -219,7 +218,7 @@ public ITargetDefinition getTarget() { * NOTE: this method expects the synchronizer to be synchronized and is called * as a result of a synchronization operation. */ - TargetFeature[] cacheFeatures(ITargetDefinition target) throws CoreException { + private void cacheFeatures(ITargetDefinition target) throws CoreException { // Ideally we would compute the list of features specific to this container but that // would require running the slicer again to follow the dependencies from this // container's roots. Instead, here we find all features in the shared profile. This means @@ -229,7 +228,7 @@ TargetFeature[] cacheFeatures(ITargetDefinition target) throws CoreException { Set features = new HashSet<>(); IQueryResult queryResult = fSynchronizer.getProfile().query(QueryUtil.createIUAnyQuery(), null); if (queryResult.isEmpty()) { - return new TargetFeature[0]; + return; } for (IInstallableUnit unit : queryResult) { @@ -243,7 +242,7 @@ TargetFeature[] cacheFeatures(ITargetDefinition target) throws CoreException { } } if (features.isEmpty()) { - return new TargetFeature[0]; + return; } // Now get features for all known features @@ -257,8 +256,7 @@ TargetFeature[] cacheFeatures(ITargetDefinition target) throws CoreException { result.add(allFeature); } } - fFeatures = result.toArray(new TargetFeature[result.size()]); - return fFeatures; + fFeatures = result.toArray(TargetFeature[]::new); } @Override @@ -275,25 +273,19 @@ protected TargetBundle[] resolveBundles(ITargetDefinition definition, IProgressM * NOTE: this method expects the synchronizer to be synchronized and is called * as a result of a synchronization operation. */ - IInstallableUnit[] cacheIUs(ITargetDefinition target) throws CoreException { + private void cacheIUs() throws CoreException { IProfile profile = fSynchronizer.getProfile(); - ArrayList result = new ArrayList<>(); + List result = new ArrayList<>(); MultiStatus status = new MultiStatus(PDECore.PLUGIN_ID, 0, Messages.IUBundleContainer_ProblemsLoadingRepositories, null); for (int i = 0; i < fIds.length; i++) { IQuery query = QueryUtil.createIUQuery(fIds[i], fVersions[i]); - IQueryResult queryResult = profile.query(query, null); - if (queryResult.isEmpty()) { - status.add(Status.error(NLS.bind(Messages.IUBundleContainer_1, fIds[i] + " " + fVersions[i]))); //$NON-NLS-1$ - } else { - result.add(queryResult.iterator().next()); - } + addQueryResult(profile, query, i, result, status); } if (!status.isOK()) { fResolutionStatus = status; throw new CoreException(status); } fUnits = result.toArray(new IInstallableUnit[result.size()]); - return fUnits; } /** @@ -301,7 +293,7 @@ IInstallableUnit[] cacheIUs(ITargetDefinition target) throws CoreException { * NOTE: this method expects the synchronizer to be synchronized and is called * as a result of a synchronization operation. */ - TargetBundle[] cacheBundles(ITargetDefinition target) throws CoreException { + private void cacheBundles(ITargetDefinition target) throws CoreException { // slice the profile to find the bundles attributed to this container. // Look only for strict dependencies if we are using the slicer. // We can always consider all platforms since the profile wouldn't contain it if it was not interesting @@ -328,7 +320,8 @@ TargetBundle[] cacheBundles(ITargetDefinition target) throws CoreException { if (PDECore.DEBUG_TARGET_PROFILE) { System.out.println("Bundle pool repository could not be loaded"); //$NON-NLS-1$ } - return fBundles = null; + fBundles = null; + return; } Map bundles = generateResolvedBundles(slice, metadata, artifacts); @@ -340,12 +333,10 @@ TargetBundle[] cacheBundles(ITargetDefinition target) throws CoreException { // If the slicer has warnings, they probably caused there to be no bundles available throw new CoreException(slicer.getStatus()); } - - return fBundles = null; + fBundles = null; + return; } - - fBundles = bundles.values().toArray(new TargetBundle[bundles.size()]); - return fBundles; + fBundles = bundles.values().toArray(TargetBundle[]::new); } /* @@ -356,7 +347,7 @@ TargetBundle[] cacheBundles(ITargetDefinition target) throws CoreException { void synchronizerChanged(ITargetDefinition target) { try { // cache the IUs first as they are used to slice the profile for the other caches. - cacheIUs(target); + cacheIUs(); cacheBundles(target); cacheFeatures(target); } catch (CoreException e) { @@ -383,36 +374,33 @@ void synchronizerChanged(ITargetDefinition target) { */ public synchronized IUBundleContainer update(Set toUpdate, IProgressMonitor monitor) throws CoreException { SubMonitor progress = SubMonitor.convert(monitor, 100); - URI[] updateRepos = fRepos == null ? null : fRepos.clone(); - IQueryable source = P2TargetUtils.getQueryableMetadata(updateRepos, IsFollowRepositoryReferences(), + IQueryable source = P2TargetUtils.getQueryableMetadata(fRepos, isFollowRepositoryReferences(), progress.split(30)); boolean updated = false; String[] updateIDs = fIds.clone(); Version[] updateVersions = fVersions.clone(); SubMonitor loopProgress = progress.split(70).setWorkRemaining(updateIDs.length); for (int i = 0; i < updateIDs.length; i++) { - if (!toUpdate.isEmpty() && !toUpdate.contains(updateIDs[i])) { + String id = updateIDs[i]; + if (!toUpdate.isEmpty() && !toUpdate.contains(id)) { continue; } - IQuery query = QueryUtil.createLatestQuery(QueryUtil.createIUQuery(updateIDs[i])); - IQueryResult queryResult = source.query(query, loopProgress.split(1)); - Iterator it = queryResult.iterator(); - // bail if the feature is no longer available. - if (!it.hasNext()) { - throw new CoreException(Status.error(NLS.bind(Messages.IUBundleContainer_1, updateIDs[i]))); - } - IInstallableUnit iu = it.next(); + IQuery query = QueryUtil.createLatestQuery(QueryUtil.createIUQuery(id)); + Optional queryResult = queryFirst(source, query, loopProgress.split(1)); + Version updatedVersion = queryResult.map(IInstallableUnit::getVersion) + // bail if the feature is no longer available. + .orElseThrow(() -> new CoreException(Status.error(NLS.bind(Messages.IUBundleContainer_1, id)))); // if the version is different from the spec (up or down), record the change. - if (!iu.getVersion().equals(updateVersions[i])) { + if (!updatedVersion.equals(updateVersions[i])) { updated = true; // if the spec was not specific (e.g., 0.0.0) the target def itself has changed. if (!updateVersions[i].equals(Version.emptyVersion)) { - updateVersions[i] = iu.getVersion(); + updateVersions[i] = updatedVersion; } } } if (updated) { - return new IUBundleContainer(updateIDs, updateVersions, updateRepos, fFlags); + return new IUBundleContainer(updateIDs, updateVersions, fRepos.toArray(URI[]::new), fFlags); } return null; } @@ -441,9 +429,9 @@ private Map generateResolvedBundles(IQueryable sourceQuery = QueryUtil.createIUQuery(unit.getId() + ".source", unit.getVersion()); //$NON-NLS-1$ - IQueryResult result = metadata.query(sourceQuery, null); - if (!result.isEmpty()) { - generateBundle(result.iterator().next(), artifacts, bundles); + Optional result = queryFirst(metadata, sourceQuery, null); + if (result.isPresent()) { + generateBundle(result.get(), artifacts, bundles); } } } @@ -477,15 +465,8 @@ private void generateBundle(IInstallableUnit unit, IFileArtifactRepository repo, @Override public int hashCode() { - final int prime = 31; - int hash = Boolean.valueOf(getIncludeAllRequired()).hashCode(); - hash = prime * hash + Boolean.valueOf(getIncludeAllEnvironments()).hashCode(); - hash = prime * hash + Boolean.valueOf(getIncludeSource()).hashCode(); - hash = prime * hash + Boolean.valueOf(getIncludeConfigurePhase()).hashCode(); - hash = prime * hash + Arrays.hashCode(fIds); - hash = prime * hash + Arrays.hashCode(fRepos); - hash = prime * hash + Arrays.hashCode(fVersions); - return hash; + return Objects.hash(getIncludeAllRequired(), getIncludeAllEnvironments(), getIncludeSource(), + getIncludeConfigurePhase(), Arrays.asList(fIds), fRepos, Arrays.asList(fVersions)); } @Override @@ -493,43 +474,23 @@ public boolean equals(Object obj) { if (this == obj) { return true; } - if (obj == null) { - return false; - } - if (!(obj instanceof IUBundleContainer other)) { - return false; - } - if (getIncludeAllRequired() != other.getIncludeAllRequired()) { - return false; - } - if (getIncludeAllEnvironments() != other.getIncludeAllEnvironments()) { - return false; - } - if (getIncludeSource() != other.getIncludeSource()) { - return false; - } - if (getIncludeConfigurePhase() != other.getIncludeConfigurePhase()) { - return false; - } - if (!Arrays.equals(fIds, other.fIds)) { - return false; - } - if (!Arrays.equals(fRepos, other.fRepos)) { - return false; - } - if (!Arrays.equals(fVersions, other.fVersions)) { - return false; - } - return true; + return obj instanceof IUBundleContainer other // + && getIncludeAllRequired() == other.getIncludeAllRequired() + && getIncludeAllEnvironments() == other.getIncludeAllEnvironments() + && getIncludeSource() == other.getIncludeSource() + && getIncludeConfigurePhase() == other.getIncludeConfigurePhase() // + && Arrays.equals(fIds, other.fIds) // + && Arrays.equals(fVersions, other.fVersions) // + && fRepos.equals(other.fRepos); } /** * Returns the URI's identifying the metadata repositories to consider when resolving * IU's or null if the default set should be used. * - * @return metadata repository URI's or null + * @return metadata repository URI's, may be empty. */ - public URI[] getRepositories() { + public List getRepositories() { return fRepos; } @@ -620,7 +581,7 @@ public boolean getIncludeConfigurePhase() { * * @return whether or not repository references should be followed */ - public boolean IsFollowRepositoryReferences() { + public boolean isFollowRepositoryReferences() { // if this container has not been associated with a container, return // its own value if (fSynchronizer == null) { @@ -635,11 +596,11 @@ public boolean IsFollowRepositoryReferences() { * @return the discovered IUs * @exception CoreException if unable to retrieve IU's */ - public IInstallableUnit[] getInstallableUnits() throws CoreException { + public List getInstallableUnits() throws CoreException { if (fUnits == null) { - return new IInstallableUnit[0]; + return List.of(); } - return fUnits; + return Arrays.asList(fUnits); } /** @@ -697,6 +658,10 @@ protected void associateWithTarget(ITargetDefinition target) { fSynchronizer.setFollowRepositoryReferences((fFlags & FOLLOW_REPOSITORY_REFERENCES) == FOLLOW_REPOSITORY_REFERENCES); } + private static final Comparator BY_ID_THEN_VERSION = Comparator // + .comparing(IVersionedId::getId) // + .thenComparing(IVersionedId::getVersion); + @Override public String serialize() { Element containerElement; @@ -720,7 +685,7 @@ public String serialize() { // most users will never edit it. // As such, for stability, conciseness, and readability, we specifically // don't serialize its default state. - boolean includeReferences = IsFollowRepositoryReferences(); + boolean includeReferences = isFollowRepositoryReferences(); if (includeReferences) { containerElement.removeAttribute(TargetDefinitionPersistenceHelper.ATTR_FOLLOW_REPOSITORY_REFERENCES); } else { @@ -728,23 +693,23 @@ public String serialize() { Boolean.toString(includeReferences)); } - URI[] repositories = getRepositories(); - if (repositories != null) { - Arrays.sort(repositories); - for (URI repository : repositories) { - Element repo = document.createElement(TargetDefinitionPersistenceHelper.REPOSITORY); - repo.setAttribute(TargetDefinitionPersistenceHelper.LOCATION, repository.toASCIIString()); - containerElement.appendChild(repo); - } + List repositories = new ArrayList<>(getRepositories()); + repositories.sort(null); + for (URI repository : repositories) { + Element repo = document.createElement(TargetDefinitionPersistenceHelper.REPOSITORY); + repo.setAttribute(TargetDefinitionPersistenceHelper.LOCATION, repository.toASCIIString()); + containerElement.appendChild(repo); } + // Generate a predictable order of the elements String[] ids = getIds(); Version[] versions = getVersions(); - for (int i : getPredictableOrder(ids, versions)) { + Stream ius = IntStream.range(0, fIds.length).mapToObj(i -> new VersionedId(ids[0], versions[i])); + ius.sorted(BY_ID_THEN_VERSION).forEach(iu -> { Element unit = document.createElement(TargetDefinitionPersistenceHelper.INSTALLABLE_UNIT); - unit.setAttribute(TargetDefinitionPersistenceHelper.ATTR_ID, ids[i]); - unit.setAttribute(TargetDefinitionPersistenceHelper.ATTR_VERSION, versions[i].toString()); + unit.setAttribute(TargetDefinitionPersistenceHelper.ATTR_ID, iu.getId()); + unit.setAttribute(TargetDefinitionPersistenceHelper.ATTR_VERSION, iu.getVersion().toString()); containerElement.appendChild(unit); - } + }); try { document.appendChild(containerElement); StreamResult result = new StreamResult(new StringWriter()); @@ -759,43 +724,15 @@ public String serialize() { } } - /** - * Generate a predictable order of the elements. Sort order is ID followed - * by version. - * - * @param ids Installable unit identifiers - * @param versions Installable unit versions - * @return The element order to use - */ - private int[] getPredictableOrder(String[] ids, Version[] versions) { - Comparator idVersionCmp = (i1, i2) -> { - String id1 = ids[i1], id2 = ids[i2]; - Version ver1 = versions[i1], ver2 = versions[i2]; - - int c = id1.compareTo(id2); - if (c == 0) { - return ver1.compareTo(ver2); - } - return c; - }; - - return IntStream.range(0, ids.length).boxed().sorted(idVersionCmp).mapToInt(i -> i).toArray(); - } - - IInstallableUnit[] getRootIUs(ITargetDefinition definition, IProgressMonitor monitor) throws CoreException { + IInstallableUnit[] getRootIUs(IProgressMonitor monitor) throws CoreException { IQueryable repos = P2TargetUtils.getQueryableMetadata(getRepositories(), - IsFollowRepositoryReferences(), monitor); + isFollowRepositoryReferences(), monitor); MultiStatus status = new MultiStatus(PDECore.PLUGIN_ID, 0, Messages.IUBundleContainer_ProblemsLoadingRepositories, null); List result = new ArrayList<>(); for (int j = 0; j < fIds.length; j++) { // For versions such as 0.0.0, the IU query may return multiple IUs, so we check which is the latest version IQuery query = QueryUtil.createLatestQuery(QueryUtil.createIUQuery(fIds[j], fVersions[j])); - IQueryResult queryResult = repos.query(query, null); - if (queryResult.isEmpty()) { - status.add(Status.error(NLS.bind(Messages.IUBundleContainer_1, fIds[j] + " " + fVersions[j])));//$NON-NLS-1$ - } else { - result.add(queryResult.iterator().next()); - } + addQueryResult(repos, query, j, result, status); } if (!status.isOK()) { fResolutionStatus = status; @@ -804,6 +741,20 @@ IInstallableUnit[] getRootIUs(ITargetDefinition definition, IProgressMonitor mon return result.toArray(new IInstallableUnit[0]); } + private void addQueryResult(IQueryable queryable, IQuery query, int iuIndex, + List result, MultiStatus status) { + Optional queryResult = queryFirst(queryable, query, null); + if (queryResult.isEmpty()) { + status.add(Status.error(NLS.bind(Messages.IUBundleContainer_1, fIds[iuIndex] + " " + fVersions[iuIndex]))); //$NON-NLS-1$ + } else { + result.add(queryResult.get()); + } + } + + static Optional queryFirst(IQueryable queryable, IQuery query, IProgressMonitor monitor) { + return queryable.query(query, monitor).stream().findFirst(); + } + @Override public T getAdapter(Class adapter) { if (adapter.isInstance(fSynchronizer)) { @@ -814,18 +765,7 @@ public T getAdapter(Class adapter) { @Override public String toString() { - StringBuilder sb = new StringBuilder(getClass().getSimpleName()); - sb.append('['); - if (fRepos != null) { - for (int i = 0; i < fRepos.length; i++) { - sb.append(fRepos[i]); - if (i > 0) { - sb.append(','); - } - } - } - sb.append(']'); - return sb.toString(); + return getClass().getSimpleName() + fRepos; } } diff --git a/ui/org.eclipse.pde.core/src/org/eclipse/pde/internal/core/target/IULocationFactory.java b/ui/org.eclipse.pde.core/src/org/eclipse/pde/internal/core/target/IULocationFactory.java index cd33e5ec75..e160f40c99 100644 --- a/ui/org.eclipse.pde.core/src/org/eclipse/pde/internal/core/target/IULocationFactory.java +++ b/ui/org.eclipse.pde.core/src/org/eclipse/pde/internal/core/target/IULocationFactory.java @@ -89,9 +89,6 @@ public ITargetLocation getTargetLocation(String type, String serializedXML) thro } } } - String[] iuIDs = ids.toArray(new String[ids.size()]); - String[] iuVer = versions.toArray(new String[versions.size()]); - URI[] uris = repos.toArray(new URI[repos.size()]); int flags = IUBundleContainer.INCLUDE_REQUIRED; if (includeMode != null && includeMode.trim().length() > 0) { @@ -109,8 +106,8 @@ public ITargetLocation getTargetLocation(String type, String serializedXML) thro } else { flags |= Boolean.parseBoolean(followRepositoryReferences) ? IUBundleContainer.FOLLOW_REPOSITORY_REFERENCES : 0; } - return TargetPlatformService.getDefault().newIULocation(iuIDs, iuVer, uris, - flags); + return TargetPlatformService.getDefault().newIULocation( // + ids.toArray(String[]::new), versions.toArray(String[]::new), repos.toArray(URI[]::new), flags); } return null; } diff --git a/ui/org.eclipse.pde.core/src/org/eclipse/pde/internal/core/target/InstallableUnitGenerator.java b/ui/org.eclipse.pde.core/src/org/eclipse/pde/internal/core/target/InstallableUnitGenerator.java index 959a6824ec..f5797d2903 100644 --- a/ui/org.eclipse.pde.core/src/org/eclipse/pde/internal/core/target/InstallableUnitGenerator.java +++ b/ui/org.eclipse.pde.core/src/org/eclipse/pde/internal/core/target/InstallableUnitGenerator.java @@ -23,6 +23,7 @@ import java.util.Arrays; import java.util.Map.Entry; import java.util.Set; +import java.util.function.Consumer; import java.util.jar.Attributes; import java.util.jar.Manifest; import java.util.stream.Stream; @@ -57,14 +58,14 @@ public static Stream generateInstallableUnits(TargetBundle[] b return Stream.concat(generateInstallableUnits(bundles), generateInstallableUnits(features)); } - public static Stream generateInstallableUnits(TargetBundle[] bundles) { + private static Stream generateInstallableUnits(TargetBundle[] bundles) { if (bundles == null || bundles.length == 0) { return Stream.empty(); } - return Arrays.stream(bundles).flatMap(InstallableUnitGenerator::generateInstallableUnits); + return Arrays.stream(bundles).mapMulti(InstallableUnitGenerator::generateInstallableUnits); } - public static Stream generateInstallableUnits(TargetBundle targetBundle) { + private static void generateInstallableUnits(TargetBundle targetBundle, Consumer downStream) { BundleInfo bundleInfo = targetBundle.getBundleInfo(); if (bundleInfo != null) { String manifest = bundleInfo.getManifest(); @@ -87,24 +88,23 @@ public static Stream generateInstallableUnits(TargetBundle tar BundlesAction.createBundleArtifactKey(bundleDescription.getSymbolicName(), bundleDescription.getVersion().toString()), publisherInfo); - return Stream.of(iu); + downStream.accept(iu); } } catch (IOException e) { // can't use it then... } } } - return Stream.empty(); } - public static Stream generateInstallableUnits(TargetFeature[] features) { + private static Stream generateInstallableUnits(TargetFeature[] features) { if (features == null || features.length == 0) { return Stream.empty(); } return Arrays.stream(features).flatMap(InstallableUnitGenerator::generateInstallableUnits); } - public static Stream generateInstallableUnits(TargetFeature targetFeature) { + private static Stream generateInstallableUnits(TargetFeature targetFeature) { String location = targetFeature.getLocation(); if (location != null) { Feature feature = new FeatureParser().parse(new File(location)); diff --git a/ui/org.eclipse.pde.core/src/org/eclipse/pde/internal/core/target/Messages.java b/ui/org.eclipse.pde.core/src/org/eclipse/pde/internal/core/target/Messages.java index 61227d89d7..7fc442c5d4 100755 --- a/ui/org.eclipse.pde.core/src/org/eclipse/pde/internal/core/target/Messages.java +++ b/ui/org.eclipse.pde.core/src/org/eclipse/pde/internal/core/target/Messages.java @@ -19,7 +19,6 @@ public class Messages extends NLS { private static final String BUNDLE_NAME = "org.eclipse.pde.internal.core.target.Messages"; //$NON-NLS-1$ public static String AbstractBundleContainer_1; public static String AbstractBundleContainer_3; - public static String AbstractTargetHandle_0; public static String DirectoryBundleContainer_0; public static String DirectoryBundleContainer_1; public static String FeatureBundleContainer_0; diff --git a/ui/org.eclipse.pde.core/src/org/eclipse/pde/internal/core/target/Messages.properties b/ui/org.eclipse.pde.core/src/org/eclipse/pde/internal/core/target/Messages.properties index 0ca65c26be..0f6b21b9e3 100755 --- a/ui/org.eclipse.pde.core/src/org/eclipse/pde/internal/core/target/Messages.properties +++ b/ui/org.eclipse.pde.core/src/org/eclipse/pde/internal/core/target/Messages.properties @@ -14,7 +14,6 @@ AbstractBundleContainer_3=Required plug-in could not be found: {0} AbstractBundleContainer_1=Required plug-in with version {0} not found: {1} -AbstractTargetHandle_0=Profile registry service not found DirectoryBundleContainer_0=Reading bundles... DirectoryBundleContainer_1=Directory does not exist: {0} FeatureBundleContainer_0=Directory does not exist: {0} diff --git a/ui/org.eclipse.pde.core/src/org/eclipse/pde/internal/core/target/P2TargetUtils.java b/ui/org.eclipse.pde.core/src/org/eclipse/pde/internal/core/target/P2TargetUtils.java index 633d02c7e3..4721c8d42e 100644 --- a/ui/org.eclipse.pde.core/src/org/eclipse/pde/internal/core/target/P2TargetUtils.java +++ b/ui/org.eclipse.pde.core/src/org/eclipse/pde/internal/core/target/P2TargetUtils.java @@ -16,6 +16,8 @@ *******************************************************************************/ package org.eclipse.pde.internal.core.target; +import static org.eclipse.pde.internal.core.target.IUBundleContainer.queryFirst; + import java.io.File; import java.net.URI; import java.nio.file.Path; @@ -25,13 +27,13 @@ import java.util.Collections; import java.util.HashMap; import java.util.HashSet; -import java.util.Iterator; import java.util.LinkedHashSet; import java.util.List; import java.util.Map; import java.util.Set; import java.util.WeakHashMap; import java.util.concurrent.ConcurrentHashMap; +import java.util.function.Supplier; import org.eclipse.core.runtime.CoreException; import org.eclipse.core.runtime.IPath; @@ -87,7 +89,9 @@ import org.eclipse.pde.core.target.ITargetLocation; import org.eclipse.pde.core.target.ITargetPlatformService; import org.eclipse.pde.core.target.NameVersionDescriptor; +import org.eclipse.pde.internal.core.ICoreConstants; import org.eclipse.pde.internal.core.PDECore; +import org.eclipse.pde.internal.core.util.CoreUtility; import org.osgi.framework.BundleContext; import org.osgi.framework.InvalidSyntaxException; import org.osgi.framework.ServiceReference; @@ -102,7 +106,7 @@ public class P2TargetUtils { public static URI AGENT_LOCATION; static { try { - AGENT_LOCATION = URIUtil.fromString("file:" + PDECore.getDefault().getStateLocation().append(".p2")); //$NON-NLS-1$//$NON-NLS-2$ + AGENT_LOCATION = PDECore.getDefault().getStateLocation().append(".p2").toPath().toUri(); //$NON-NLS-1$ } catch (Exception e) { // should never happen } @@ -161,17 +165,17 @@ public class P2TargetUtils { /** * Table mapping {@link ITargetDefinition} to synchronizer (P2TargetUtils) instance. */ - private static Map synchronizers = new WeakHashMap<>(); + private static final Map SYNCHRONIZERS = new WeakHashMap<>(); /** * Table mapping of ITargetDefinition and IFileArtifactRepository */ - public static Map fgTargetArtifactRepo = new ConcurrentHashMap<>(); + static final Map fgTargetArtifactRepo = new ConcurrentHashMap<>(); /** * Table mapping IArtifactKey to table map of IFileArtifactRepository and IFileArtifactRepository */ - public static Map> fgArtifactKeyRepoFile = new ConcurrentHashMap<>(); + static final Map> fgArtifactKeyRepoFile = new ConcurrentHashMap<>(); /** * The profile to be synchronized @@ -232,10 +236,9 @@ public class P2TargetUtils { */ public static List cleanOrphanedTargetDefinitionProfiles() throws CoreException { List list = new ArrayList<>(); - IProfileRegistry registry = getProfileRegistry(); ITargetPlatformService tps = TargetPlatformService.getDefault(); - if (registry != null && tps != null) { - IProfile[] profiles = registry.getProfiles(); + if (tps != null) { + IProfile[] profiles = getProfileRegistry().getProfiles(); for (IProfile profile : profiles) { String id = profile.getProfileId(); if (id.startsWith(PROFILE_ID_PREFIX)) { @@ -257,20 +260,6 @@ public static List cleanOrphanedTargetDefinitionProfiles() throws CoreEx return list; } - /** - * Recursively deletes folder and files. - */ - private static void delete(File folder) { - File[] files = folder.listFiles(); - for (File file : files) { - if (file.isDirectory()) { - delete(file); - } - file.delete(); - } - folder.delete(); - } - /** * Deletes the profile associated with this target handle, if any. Returns * true if a profile existed and was deleted, otherwise false. @@ -283,17 +272,13 @@ public static void deleteProfile(ITargetHandle handle) throws CoreException { private static void deleteProfileWithId(String profileId) throws CoreException { IProfileRegistry registry = getProfileRegistry(); - if (registry != null) { - IProfile profile = registry.getProfile(profileId); - if (profile != null) { - String location = profile.getProperty(IProfile.PROP_INSTALL_FOLDER); - registry.removeProfile(profileId); - if (location != null && location.length() > 0) { - File folder = new File(location); - if (folder.exists()) { - delete(folder); - } - } + IProfile profile = registry.getProfile(profileId); + if (profile != null) { + String location = profile.getProperty(IProfile.PROP_INSTALL_FOLDER); + registry.removeProfile(profileId); + if (location != null && location.length() > 0) { + File folder = new File(location); + CoreUtility.deleteContent(folder); } } } @@ -305,9 +290,8 @@ public static void forceCheckTarget(final ITargetDefinition target) { @SuppressWarnings("restriction") private synchronized void resetProfile() { - IProfile profile = getProfile(); - if (profile instanceof org.eclipse.equinox.internal.p2.engine.Profile) { - ((org.eclipse.equinox.internal.p2.engine.Profile) profile).setProperty(PROP_SEQUENCE_NUMBER, "-1"); //$NON-NLS-1$ + if (getProfile() instanceof org.eclipse.equinox.internal.p2.engine.Profile profile) { + profile.setProperty(PROP_SEQUENCE_NUMBER, "-1"); //$NON-NLS-1$ } fProfile = null; } @@ -326,7 +310,6 @@ public static void garbageCollect() { } } catch (CoreException e) { // XXX likely should log something here. - return; } } @@ -336,31 +319,19 @@ public static void garbageCollect() { * @return environment properties */ private String generateEnvironmentProperties(ITargetDefinition target) { - // TODO: are there constants for these keys? StringBuilder env = new StringBuilder(); - String ws = target.getWS(); - if (ws == null) { - ws = Platform.getWS(); - } - env.append("osgi.ws="); //$NON-NLS-1$ - env.append(ws); + appendEnv(env, ICoreConstants.OSGI_WS, target.getWS(), Platform::getWS); env.append(","); //$NON-NLS-1$ - String os = target.getOS(); - if (os == null) { - os = Platform.getOS(); - } - env.append("osgi.os="); //$NON-NLS-1$ - env.append(os); + appendEnv(env, ICoreConstants.OSGI_OS, target.getOS(), Platform::getOS); env.append(","); //$NON-NLS-1$ - String arch = target.getArch(); - if (arch == null) { - arch = Platform.getOSArch(); - } - env.append("osgi.arch="); //$NON-NLS-1$ - env.append(arch); + appendEnv(env, ICoreConstants.OSGI_ARCH, target.getArch(), Platform::getOSArch); return env.toString(); } + private void appendEnv(StringBuilder env, String key, String value, Supplier defaultValue) { + env.append(key).append('=').append(value != null ? value : defaultValue.get()); + } + /** * Generates the NL property for this target definition's p2 profile. * @@ -368,10 +339,7 @@ private String generateEnvironmentProperties(ITargetDefinition target) { */ private String generateNLProperty(ITargetDefinition target) { String nl = target.getNL(); - if (nl == null) { - nl = Platform.getNL(); - } - return nl; + return nl != null ? nl : Platform.getNL(); } public static IProvisioningAgent getAgent() throws CoreException { @@ -404,7 +372,7 @@ public static IProvisioningAgent getAgent() throws CoreException { throw new CoreException(Status.error(Messages.IUBundleContainer_7)); } // turn off the garbage collector for the PDE agent. GC is managed on a coarser grain - GarbageCollector garbageCollector = (GarbageCollector) agent.getService(GarbageCollector.class.getName()); + GarbageCollector garbageCollector = agent.getService(GarbageCollector.class); if (garbageCollector != null) { garbageCollector.stop(); } @@ -435,11 +403,7 @@ public static IProvisioningAgent getGlobalAgent() throws CoreException { * @throws CoreException if none */ public static IAgentLocation getAgentLocation() throws CoreException { - IAgentLocation result = (IAgentLocation) getAgent().getService(IAgentLocation.SERVICE_NAME); - if (result == null) { - throw new CoreException(Status.error(Messages.IUBundleContainer_10)); - } - return result; + return getP2Service(IAgentLocation.class, Messages.IUBundleContainer_10); } /** @@ -449,11 +413,7 @@ public static IAgentLocation getAgentLocation() throws CoreException { * @throws CoreException if none */ public static IArtifactRepositoryManager getArtifactRepositoryManager() throws CoreException { - IArtifactRepositoryManager manager = (IArtifactRepositoryManager) getAgent().getService(IArtifactRepositoryManager.class.getName()); - if (manager == null) { - throw new CoreException(Status.error(Messages.IUBundleContainer_3)); - } - return manager; + return getP2Service(IArtifactRepositoryManager.class, Messages.IUBundleContainer_3); } /** @@ -483,11 +443,7 @@ public static IFileArtifactRepository getBundlePool() throws CoreException { * @throws CoreException if none */ public static IEngine getEngine() throws CoreException { - IEngine engine = (IEngine) getAgent().getService(IEngine.class.getName()); - if (engine == null) { - throw new CoreException(Status.error(Messages.IUBundleContainer_4)); - } - return engine; + return getP2Service(IEngine.class, Messages.IUBundleContainer_4); } /** @@ -497,11 +453,7 @@ public static IEngine getEngine() throws CoreException { * @throws CoreException if none */ public static GarbageCollector getGarbageCollector() throws CoreException { - GarbageCollector engine = (GarbageCollector) getAgent().getService(GarbageCollector.class.getName()); - if (engine == null) { - throw new CoreException(Status.error(Messages.IUBundleContainer_9)); - } - return engine; + return getP2Service(GarbageCollector.class, Messages.IUBundleContainer_9); } /** @@ -511,11 +463,7 @@ public static GarbageCollector getGarbageCollector() throws CoreException { * @throws CoreException if none */ public static IPlanner getPlanner() throws CoreException { - IPlanner planner = (IPlanner) getAgent().getService(IPlanner.class.getName()); - if (planner == null) { - throw new CoreException(Status.error(Messages.IUBundleContainer_5)); - } - return planner; + return getP2Service(IPlanner.class, Messages.IUBundleContainer_5); } /** @@ -531,9 +479,8 @@ public static IPreferencesService getPreferences() { * Returns whether the contents of the profile matches the expected contents of the target definition * * @return whether or not the profile and target definitions match - * @throws CoreException in unable to retrieve profile */ - private boolean checkProfile(ITargetDefinition target, final IProfile profile) throws CoreException { + private boolean checkProfile(ITargetDefinition target, final IProfile profile) { // make sure we have a profile to validate if (profile == null) { return false; @@ -557,22 +504,15 @@ private boolean checkProfile(ITargetDefinition target, final IProfile profile) t } // ensure environment & NL settings are still the same (else we need a new profile) - String property = null; - if (!all) { - property = generateEnvironmentProperties(target); - value = profile.getProperty(IProfile.PROP_ENVIRONMENTS); - if (!property.equals(value)) { - return false; - } + if (!all && !generateEnvironmentProperties(target).equals(profile.getProperty(IProfile.PROP_ENVIRONMENTS))) { + return false; } - property = generateNLProperty(target); - value = profile.getProperty(IProfile.PROP_NL); - if (!property.equals(value)) { + if (!generateNLProperty(target).equals(profile.getProperty(IProfile.PROP_NL))) { return false; } // check provisioning mode: slice versus plan - if (!getProvisionMode(target).equals(profile.getProperty(PROP_PROVISION_MODE))) { + if (!getProvisionMode().equals(profile.getProperty(PROP_PROVISION_MODE))) { return false; } @@ -589,10 +529,8 @@ private boolean checkProfile(ITargetDefinition target, final IProfile profile) t // still in the profile, we need to recreate (rather than uninstall) IUProfilePropertyQuery propertyQuery = new IUProfilePropertyQuery(PROP_INSTALLED_IU, Boolean.toString(true)); IQueryResult queryResult = profile.query(propertyQuery, null); - Iterator iterator = queryResult.iterator(); Set installedIUs = new HashSet<>(); - while (iterator.hasNext()) { - IInstallableUnit unit = iterator.next(); + for (IInstallableUnit unit : queryResult) { installedIUs.add(new NameVersionDescriptor(unit.getId(), unit.getVersion().toString())); } ITargetLocation[] containers = target.getTargetLocations(); @@ -611,12 +549,7 @@ private boolean checkProfile(ITargetDefinition target, final IProfile profile) t } } } - if (!installedIUs.isEmpty()) { - return false; - } - - // Phew! seems like the profile checks out. - return true; + return installedIUs.isEmpty(); // If empty, the profile checks out. } /** @@ -744,11 +677,7 @@ public static boolean isResolved(ITargetDefinition target) { if (synchronizer == null) { return false; } - try { - return synchronizer.checkProfile(target, synchronizer.getProfile()); - } catch (CoreException e) { - return false; - } + return synchronizer.checkProfile(target, synchronizer.getProfile()); } /** @@ -761,11 +690,7 @@ public static boolean isProfileValid(ITargetDefinition target) { if (synchronizer == null) { return false; } - try { - return synchronizer.checkProfile(target, synchronizer.updateProfileFromRegistry(target)); - } catch (CoreException e) { - return false; - } + return synchronizer.checkProfile(target, synchronizer.updateProfileFromRegistry(target)); } @@ -792,14 +717,7 @@ private synchronized IProfile updateProfileFromRegistry(ITargetDefinition target * @return the discovered or created synchronizer */ static synchronized P2TargetUtils getSynchronizer(ITargetDefinition target) { - P2TargetUtils result = synchronizers.get(target); - if (result != null) { - return result; - } - - result = new P2TargetUtils(); - synchronizers.put(target, result); - return result; + return SYNCHRONIZERS.computeIfAbsent(target, t -> new P2TargetUtils()); } /** @@ -883,12 +801,9 @@ public synchronized void synchronize(ITargetDefinition target, IProgressMonitor } } - private IProfile createProfile(ITargetDefinition target) throws CoreException, ProvisionException { + private IProfile createProfile(ITargetDefinition target) throws CoreException { // create a new profile IProfileRegistry registry = getProfileRegistry(); - if (registry == null) { - throw new CoreException(Status.error(Messages.AbstractTargetHandle_0)); - } Map properties = new HashMap<>(); properties.put(IProfile.PROP_INSTALL_FOLDER, INSTALL_FOLDERS.append(Long.toString(LocalTargetHandle.nextTimeStamp())).toOSString()); properties.put(IProfile.PROP_CACHE, BUNDLE_POOL.toOSString()); @@ -896,7 +811,7 @@ private IProfile createProfile(ITargetDefinition target) throws CoreException, P properties.put(IProfile.PROP_ENVIRONMENTS, generateEnvironmentProperties(target)); properties.put(IProfile.PROP_NL, generateNLProperty(target)); properties.put(PROP_SEQUENCE_NUMBER, Integer.toString(((TargetDefinition) target).getSequenceNumber())); - properties.put(PROP_PROVISION_MODE, getProvisionMode(target)); + properties.put(PROP_PROVISION_MODE, getProvisionMode()); properties.put(PROP_ALL_ENVIRONMENTS, Boolean.toString(getIncludeAllEnvironments())); properties.put(PROP_AUTO_INCLUDE_SOURCE, Boolean.toString(getIncludeSource())); properties.put(PROP_INCLUDE_CONFIGURE_PHASE, Boolean.toString(getIncludeConfigurePhase())); @@ -914,8 +829,8 @@ private void notify(ITargetDefinition target, IProgressMonitor monitor) { ITargetLocation[] containers = target.getTargetLocations(); if (containers != null) { for (ITargetLocation container : containers) { - if (container instanceof IUBundleContainer) { - ((IUBundleContainer) container).synchronizerChanged(target); + if (container instanceof IUBundleContainer iuContainer) { + iuContainer.synchronizerChanged(target); } } } @@ -953,24 +868,10 @@ private static String getProfileSuffix(String memento) { // length * 4 > 200 if (length > 50) { for (int i = length - 1; i >= 0; --i) { - switch (memento.charAt(i)) - { - case '\\': - case '/': - case ':': - case '*': - case '?': - case '"': - case '<': - case '>': - case '|': - case '%': { - escapedLength += 4; - } - default: { - escapedLength += 1; - } - } + escapedLength += switch (memento.charAt(i)) { + case '\\', '/', ':', '*', '?', '"', '<', '>', '|', '%' -> 4; + default -> 1; + }; if (escapedLength > 200) { return memento.substring(i + 1) + memento.hashCode(); } @@ -1000,11 +901,7 @@ public static String getProfileId(ITargetDefinition definition) { * @return profile registry or null */ public static IProfileRegistry getProfileRegistry() throws CoreException { - IProfileRegistry result = (IProfileRegistry) getAgent().getService(IProfileRegistry.SERVICE_NAME); - if (result == null) { - throw new CoreException(Status.error(Messages.IUBundleContainer_8)); - } - return result; + return getP2Service(IProfileRegistry.class, Messages.IUBundleContainer_8); } /** @@ -1013,7 +910,7 @@ public static IProfileRegistry getProfileRegistry() throws CoreException { * * @return provisioning mode or null */ - private String getProvisionMode(ITargetDefinition target) { + private String getProvisionMode() { return getIncludeAllRequired() ? TargetDefinitionPersistenceHelper.MODE_PLANNER : TargetDefinitionPersistenceHelper.MODE_SLICER; } @@ -1024,11 +921,15 @@ private String getProvisionMode(ITargetDefinition target) { * @throws CoreException if none */ public static IMetadataRepositoryManager getRepoManager() throws CoreException { - IMetadataRepositoryManager manager = (IMetadataRepositoryManager) getAgent().getService(IMetadataRepositoryManager.SERVICE_NAME); - if (manager == null) { - throw new CoreException(Status.error(Messages.IUBundleContainer_2)); + return getP2Service(IMetadataRepositoryManager.class, Messages.IUBundleContainer_2); + } + + private static T getP2Service(Class key, String absentErrorMessage) throws CoreException { + T service = getAgent().getService(key); + if (service == null) { + throw new CoreException(Status.error(absentErrorMessage)); } - return manager; + return service; } /** @@ -1040,22 +941,21 @@ public static IMetadataRepositoryManager getRepoManager() throws CoreException { * @return the set of metadata repositories found * @throws CoreException if there is a problem getting the repositories */ - static IQueryable getQueryableMetadata(URI[] repos, boolean followRepositoryReferences, IProgressMonitor monitor) throws CoreException { + static IQueryable getQueryableMetadata(Collection repos, boolean followRepositoryReferences, + IProgressMonitor monitor) throws CoreException { IMetadataRepositoryManager manager = getRepoManager(); - if (repos == null) { - repos = manager.getKnownRepositories(IRepositoryManager.REPOSITORIES_ALL); + if (repos.isEmpty()) { + repos = Arrays.asList(manager.getKnownRepositories(IRepositoryManager.REPOSITORIES_ALL)); } - - int repoCount = repos.length; - SubMonitor subMonitor = SubMonitor.convert(monitor, repoCount * 2); + SubMonitor subMonitor = SubMonitor.convert(monitor, repos.size() * 2); Set seen = new HashSet<>(); - List result = new ArrayList<>(repoCount); + List result = new ArrayList<>(repos.size()); List additional = new ArrayList<>(); MultiStatus repoStatus = new MultiStatus(PDECore.PLUGIN_ID, 0, Messages.IUBundleContainer_ProblemsLoadingRepositories, null); - for (int i = 0; i < repoCount; ++i) { + for (URI location : repos) { try { - IMetadataRepository repository = manager.loadRepository(repos[i], subMonitor.split(1)); + IMetadataRepository repository = manager.loadRepository(location, subMonitor.split(1)); result.add(repository); if (followRepositoryReferences) { addReferences(repository, additional, seen, manager, subMonitor.split(1)); @@ -1065,7 +965,7 @@ static IQueryable getQueryableMetadata(URI[] repos, boolean fo } } - if (result.size() != repos.length) { + if (result.size() != repos.size()) { throw new CoreException(repoStatus); } result.addAll(additional); @@ -1222,7 +1122,7 @@ private void computeRemovals(IProfile profile, IProfileChangeRequest request, bo // remove everything that is marked as roots. The plan will have the new roots added in anyway. IQuery query = new IUProfilePropertyQuery(PROP_INSTALLED_IU, Boolean.toString(true)); IQueryResult installedIUs = profile.query(query, null); - request.removeAll(installedIUs.toSet()); + installedIUs.forEach(request::remove); } // run a second pass of the planner to add in the source bundles for everything that's @@ -1283,7 +1183,7 @@ private IInstallableUnit createSourceIU(IQueryable queryable, // compute the set of source bundles we could possibly need for the bundles in the profile IRequirement bundleRequirement = MetadataFactory.createRequirement("org.eclipse.equinox.p2.eclipse.type", "bundle", null, null, false, false, false); //$NON-NLS-1$ //$NON-NLS-2$ IQueryResult profileIUs = queryable.query(QueryUtil.createIUAnyQuery(), null); - ArrayList requirements = new ArrayList<>(); + List requirements = new ArrayList<>(); for (IInstallableUnit profileIU : profileIUs) { if (profileIU.satisfies(bundleRequirement)) { String id = profileIU.getId() + ".source"; //$NON-NLS-1$ @@ -1308,12 +1208,7 @@ private IInstallableUnit createSourceIU(IQueryable queryable, // Lookup and return (if any) the source IU in the given queryable. private IInstallableUnit getCurrentSourceIU(IQueryable queryable) { IQuery query = QueryUtil.createIUQuery(SOURCE_IU_ID); - IQueryResult list = queryable.query(query, null); - IInstallableUnit currentSourceIU = null; - if (!list.isEmpty()) { - currentSourceIU = list.iterator().next(); - } - return currentSourceIU; + return queryFirst(queryable, query, null).orElse(null); } /** @@ -1335,8 +1230,7 @@ private void resolveWithSlicer(ITargetDefinition target, IProfile profile, IProg if (repositories.isEmpty()) { return; } - URI[] uris = repositories.toArray(URI[]::new); - IQueryable allMetadata = getQueryableMetadata(uris, isFollowRepositoryReferences(), + IQueryable allMetadata = getQueryableMetadata(repositories, isFollowRepositoryReferences(), subMonitor.split(5)); // do an initial slice to add everything the user requested @@ -1362,17 +1256,16 @@ private void resolveWithSlicer(ITargetDefinition target, IProfile profile, IProg IEngine engine = getEngine(); ProvisioningContext context = new ProvisioningContext(getAgent()); - context.setMetadataRepositories(uris); + context.setMetadataRepositories(repositories.toArray(URI[]::new)); context.setArtifactRepositories(getArtifactRepositories(target).toArray(URI[]::new)); context.setProperty(ProvisioningContext.FOLLOW_REPOSITORY_REFERENCES, Boolean.toString(isFollowRepositoryReferences())); context.setProperty(ProvisioningContext.FOLLOW_ARTIFACT_REPOSITORY_REFERENCES, Boolean.toString(isFollowRepositoryReferences())); IProvisioningPlan plan = engine.createPlan(profile, context); setPlanProperties(plan, target, TargetDefinitionPersistenceHelper.MODE_SLICER); - Set newSet = queryResult.toSet(); - Iterator itor = newSet.iterator(); - while (itor.hasNext()) { - plan.addInstallableUnit(itor.next()); + Set newSet = queryResult.toUnmodifiableSet(); + for (IInstallableUnit unit : newSet) { + plan.addInstallableUnit(unit); } for (IInstallableUnit unit : units) { plan.setInstallableUnitProfileProperty(unit, PROP_INSTALLED_IU, Boolean.toString(true)); @@ -1436,10 +1329,8 @@ private IQueryResult slice(IInstallableUnit[] units, IQueryabl // If the slicer encounters a non-error status, only report it if the slice returned no IU results // It would be better to inform the user, but we do not want to stop the location from resolving (bug 350772) - if (!sliceStatus.isOK()) { - if (queryResult != null && !queryResult.iterator().hasNext()) { - throw new CoreException(sliceStatus); - } + if (!sliceStatus.isOK() && queryResult != null && queryResult.isEmpty()) { + throw new CoreException(sliceStatus); } return queryResult; @@ -1460,14 +1351,13 @@ private Collection getArtifactRepositories(ITargetDefinition target) throws } IArtifactRepositoryManager manager = getArtifactRepositoryManager(); for (ITargetLocation container : containers) { - if (container instanceof IUBundleContainer) { - URI[] repos = ((IUBundleContainer) container).getRepositories(); - if (repos == null) { - repos = manager.getKnownRepositories(IRepositoryManager.REPOSITORIES_ALL); + if (container instanceof IUBundleContainer iuContainer) { + List repos = iuContainer.getRepositories(); + if (repos.isEmpty()) { + repos = Arrays.asList(manager.getKnownRepositories(IRepositoryManager.REPOSITORIES_ALL)); } - result.addAll(Arrays.asList(repos)); - } - if (container instanceof TargetReferenceBundleContainer targetRefContainer) { + result.addAll(repos); + } else if (container instanceof TargetReferenceBundleContainer targetRefContainer) { ITargetDefinition referencedTargetDefinition = targetRefContainer.getTargetDefinition(); result.addAll(getArtifactRepositories(referencedTargetDefinition)); } @@ -1533,7 +1423,7 @@ private void findWorkspaceRepos(Set additionalRepos) { private void findProfileRepos(Set additionalRepos) { try { // NOTE: be sure to use the global p2 agent here as we are looking for SELF. - IProfileRegistry profileRegistry = (IProfileRegistry) getGlobalAgent().getService(IProfileRegistry.SERVICE_NAME); + IProfileRegistry profileRegistry = getGlobalAgent().getService(IProfileRegistry.class); if (profileRegistry == null) { return; } @@ -1542,7 +1432,7 @@ private void findProfileRepos(Set additionalRepos) { return; } - IAgentLocation location = (IAgentLocation) getGlobalAgent().getService(IAgentLocation.SERVICE_NAME); + IAgentLocation location = getGlobalAgent().getService(IAgentLocation.class); URI dataArea = location.getDataArea("org.eclipse.equinox.p2.engine"); //$NON-NLS-1$ dataArea = URIUtil.append(dataArea, "profileRegistry/" + self.getProfileId() + ".profile"); //$NON-NLS-1$//$NON-NLS-2$ @SuppressWarnings("restriction") @@ -1555,7 +1445,6 @@ private void findProfileRepos(Set additionalRepos) { } } catch (CoreException e) { // if there is a problem, move on. Could log something here - return; } } @@ -1576,10 +1465,9 @@ private IInstallableUnit[] getRootIUs(ITargetDefinition definition, IProgressMon SubMonitor subMonitor = SubMonitor.convert(monitor, Messages.IUBundleContainer_0, containers.length * 10); MultiStatus status = new MultiStatus(PDECore.PLUGIN_ID, 0, Messages.IUBundleContainer_ProblemsLoadingRepositories, null); for (ITargetLocation container : containers) { - if (container instanceof IUBundleContainer) { + if (container instanceof IUBundleContainer iuContainer) { try { - IUBundleContainer iuContainer = (IUBundleContainer) container; - Collections.addAll(result, iuContainer.getRootIUs(definition, subMonitor.split(10))); + Collections.addAll(result, iuContainer.getRootIUs(subMonitor.split(10))); } catch (CoreException e) { status.add(e.getStatus()); } @@ -1607,11 +1495,11 @@ private Collection getMetadataRepositories(ITargetDefinition target) throws IMetadataRepositoryManager manager = getRepoManager(); for (ITargetLocation container : containers) { if (container instanceof IUBundleContainer iuContainer) { - URI[] repos = iuContainer.getRepositories(); - if (repos == null) { - repos = manager.getKnownRepositories(IRepositoryManager.REPOSITORIES_ALL); + List repos = iuContainer.getRepositories(); + if (repos.isEmpty()) { + repos = Arrays.asList(manager.getKnownRepositories(IRepositoryManager.REPOSITORIES_ALL)); } - result.addAll(Arrays.asList(repos)); + result.addAll(repos); } if (container instanceof TargetReferenceBundleContainer targetRefContainer) { ITargetDefinition referencedTargetDefinition = targetRefContainer.getTargetDefinition(); @@ -1702,9 +1590,7 @@ protected List getActions( org.eclipse.equinox.internal.p2.engine.InstallableUnitOperand operand) { IInstallableUnit unit = operand.second(); if (unit != null && unit.getTouchpointType().getId().equals(NATIVE_TYPE)) { - ArrayList list = new ArrayList<>(1); - list.add(new CollectNativesAction()); - return list; + return List.of(new CollectNativesAction()); } return null; } diff --git a/ui/org.eclipse.pde.core/src/org/eclipse/pde/internal/core/target/TargetMetadataCollector.java b/ui/org.eclipse.pde.core/src/org/eclipse/pde/internal/core/target/TargetMetadataCollector.java index 00a7906103..4e2fab5799 100644 --- a/ui/org.eclipse.pde.core/src/org/eclipse/pde/internal/core/target/TargetMetadataCollector.java +++ b/ui/org.eclipse.pde.core/src/org/eclipse/pde/internal/core/target/TargetMetadataCollector.java @@ -60,19 +60,16 @@ public static URI[] getMetadataRepositories(ITargetDefinition definition) throws ITargetLocation[] containers = definition.getTargetLocations(); if (containers != null) { for (ITargetLocation currentContainer : containers) { - if (currentContainer instanceof ProfileBundleContainer) { - File profileLocation = ((ProfileBundleContainer) currentContainer).getProfileFileLocation(); + if (currentContainer instanceof ProfileBundleContainer profileContainer) { + File profileLocation = profileContainer.getProfileFileLocation(); if (profileLocation != null) { repos.add(profileLocation.toURI()); } - } else if (currentContainer instanceof IUBundleContainer) { + } else if (currentContainer instanceof IUBundleContainer bundleContainer) { // PDE Build only wants local repositories as downloading can take as long as publishing new metadata. Currently no way to get cached/downloaded metadata. - URI[] locations = ((IUBundleContainer) currentContainer).getRepositories(); - if (locations != null) { - for (URI location : locations) { - if (URIUtil.isFileURI(location)) { - repos.add(location); - } + for (URI location : bundleContainer.getRepositories()) { + if (URIUtil.isFileURI(location)) { + repos.add(location); } } } diff --git a/ui/org.eclipse.pde.ui/src/org/eclipse/pde/internal/ui/shared/target/EditIUContainerPage.java b/ui/org.eclipse.pde.ui/src/org/eclipse/pde/internal/ui/shared/target/EditIUContainerPage.java index bffe2ff917..0823128668 100644 --- a/ui/org.eclipse.pde.ui/src/org/eclipse/pde/internal/ui/shared/target/EditIUContainerPage.java +++ b/ui/org.eclipse.pde.ui/src/org/eclipse/pde/internal/ui/shared/target/EditIUContainerPage.java @@ -18,6 +18,8 @@ import java.net.URI; import java.net.URISyntaxException; +import java.util.Arrays; +import java.util.List; import java.util.concurrent.atomic.AtomicBoolean; import org.eclipse.core.runtime.CoreException; @@ -156,8 +158,8 @@ public ITargetLocation getBundleContainer() { flags |= fIncludeSourceButton.getSelection() ? IUBundleContainer.INCLUDE_SOURCE : 0; flags |= fConfigurePhaseButton.getSelection() ? IUBundleContainer.INCLUDE_CONFIGURE_PHASE : 0; flags |= fFollowRepositoryReferencesButton.getSelection() ? IUBundleContainer.FOLLOW_REPOSITORY_REFERENCES : 0; - IUBundleContainer container = (IUBundleContainer) service.newIULocation(fAvailableIUGroup.getCheckedLeafIUs(), fRepoLocation != null ? new URI[] {fRepoLocation} : null, flags); - return container; + return service.newIULocation(fAvailableIUGroup.getCheckedLeafIUs(), + fRepoLocation != null ? new URI[] { fRepoLocation } : null, flags); } @Override @@ -212,7 +214,7 @@ private void createRepositoryComboArea(final Composite parent) { private void refreshAvailableIUArea(final Composite parent) { try { - if (fEditContainer == null || fEditContainer.getInstallableUnits().length == 0) { + if (fEditContainer == null || fEditContainer.getInstallableUnits().isEmpty()) { return; } } catch (CoreException e) { @@ -244,7 +246,7 @@ private void refreshAvailableIUArea(final Composite parent) { if (children.length > 0 && !children[0].getText().equals(pendingLabel)) { try { fAvailableIUGroup.getCheckboxTreeViewer().expandAll(); - fAvailableIUGroup.setChecked(fEditContainer.getInstallableUnits()); + fAvailableIUGroup.setChecked(fEditContainer.getInstallableUnits().toArray()); fAvailableIUGroup.getCheckboxTreeViewer().collapseAll(); } catch (CoreException e) { PDEPlugin.log(e); @@ -418,16 +420,12 @@ private void createCheckboxArea(Composite parent) { private void warnIfGlobalSettingChanged() { boolean noChange = true; - IUBundleContainer iuContainer = null; ITargetLocation[] containers = fTarget.getTargetLocations(); if (containers != null) { // Look for a IUBundleContainer to compare against. - for (ITargetLocation container : containers) { - if (container instanceof IUBundleContainer && container != fEditContainer) { - iuContainer = (IUBundleContainer) container; - break; - } - } + IUBundleContainer iuContainer = Arrays.stream(containers).filter(container -> container != fEditContainer) + .filter(IUBundleContainer.class::isInstance).map(IUBundleContainer.class::cast) // + .findFirst().orElse(null); // If there is another IU container then compare against it. No need to check them all // as they will all be set the same within one target. if (iuContainer != null) { @@ -435,7 +433,7 @@ private void warnIfGlobalSettingChanged() { noChange &= fAllPlatformsButton.getSelection() == iuContainer.getIncludeAllEnvironments(); noChange &= fIncludeSourceButton.getSelection() == iuContainer.getIncludeSource(); noChange &= fConfigurePhaseButton.getSelection() == iuContainer.getIncludeConfigurePhase(); - noChange &= fFollowRepositoryReferencesButton.getSelection() == iuContainer.IsFollowRepositoryReferences(); + noChange &= fFollowRepositoryReferencesButton.getSelection() == iuContainer.isFollowRepositoryReferences(); } } if (noChange) { @@ -541,8 +539,9 @@ private void restoreWidgetState() { // Init the checkboxes and repo selector combo if (fEditContainer != null) { - if (fEditContainer.getRepositories() != null) { - uri = fEditContainer.getRepositories()[0]; + List repositories = fEditContainer.getRepositories(); + if (!repositories.isEmpty()) { + uri = repositories.get(0); } } else if (settings != null) { String stringURI = settings.get(SETTINGS_SELECTED_REPOSITORY); @@ -580,18 +579,18 @@ private void restoreWidgetState() { fAllPlatformsButton.setSelection(fEditContainer.getIncludeAllEnvironments()); fIncludeSourceButton.setSelection(fEditContainer.getIncludeSource()); fConfigurePhaseButton.setSelection(fEditContainer.getIncludeConfigurePhase()); - fFollowRepositoryReferencesButton.setSelection(fEditContainer.IsFollowRepositoryReferences()); + fFollowRepositoryReferencesButton.setSelection(fEditContainer.isFollowRepositoryReferences()); } else { // If we are creating a new container, but there is an existing iu container we should use it's settings (otherwise we overwrite them) ITargetLocation[] knownContainers = fTarget.getTargetLocations(); if (knownContainers != null) { for (ITargetLocation knownContainer : knownContainers) { - if (knownContainer instanceof IUBundleContainer) { - fIncludeRequiredButton.setSelection(((IUBundleContainer) knownContainer).getIncludeAllRequired()); - fAllPlatformsButton.setSelection(((IUBundleContainer) knownContainer).getIncludeAllEnvironments()); - fIncludeSourceButton.setSelection(((IUBundleContainer) knownContainer).getIncludeSource()); - fConfigurePhaseButton.setSelection(((IUBundleContainer) knownContainer).getIncludeConfigurePhase()); - fFollowRepositoryReferencesButton.setSelection(((IUBundleContainer) knownContainer).IsFollowRepositoryReferences()); + if (knownContainer instanceof IUBundleContainer iuContainer) { + fIncludeRequiredButton.setSelection(iuContainer.getIncludeAllRequired()); + fAllPlatformsButton.setSelection(iuContainer.getIncludeAllEnvironments()); + fIncludeSourceButton.setSelection(iuContainer.getIncludeSource()); + fConfigurePhaseButton.setSelection(iuContainer.getIncludeConfigurePhase()); + fFollowRepositoryReferencesButton.setSelection(iuContainer.isFollowRepositoryReferences()); } } } @@ -603,9 +602,9 @@ private void restoreWidgetState() { ITargetLocation[] containers = fTarget.getTargetLocations(); if (containers != null) { for (ITargetLocation container : containers) { - if (container instanceof IUBundleContainer && container != fEditContainer) { - fIncludeRequiredButton.setSelection(((IUBundleContainer) container).getIncludeAllRequired()); - fAllPlatformsButton.setSelection(((IUBundleContainer) container).getIncludeAllEnvironments()); + if (container instanceof IUBundleContainer iuContainer && iuContainer != fEditContainer) { + fIncludeRequiredButton.setSelection(iuContainer.getIncludeAllRequired()); + fAllPlatformsButton.setSelection(iuContainer.getIncludeAllEnvironments()); break; } } @@ -625,17 +624,15 @@ private void restoreWidgetState() { // Only able to check items if we don't have categories fQueryContext.setViewType(org.eclipse.equinox.internal.p2.ui.query.IUViewQueryContext.AVAILABLE_VIEW_FLAT); fAvailableIUGroup.updateAvailableViewState(); - fAvailableIUGroup.setChecked(fEditContainer.getInstallableUnits()); + fAvailableIUGroup.setChecked(fEditContainer.getInstallableUnits().toArray()); // Make sure view is back in proper state updateViewContext(); IInstallableUnit[] units = fAvailableIUGroup.getCheckedLeafIUs(); if (units.length > 0) { fAvailableIUGroup.getCheckboxTreeViewer().setSelection(new StructuredSelection(units[0]), true); - if (units.length == 1) { - fSelectionCount.setText(NLS.bind(Messages.EditIUContainerPage_itemSelected, Integer.toString(units.length))); - } else { - fSelectionCount.setText(NLS.bind(Messages.EditIUContainerPage_itemsSelected, Integer.toString(units.length))); - } + String msg = units.length == 1 ? Messages.EditIUContainerPage_itemSelected + : Messages.EditIUContainerPage_itemsSelected; + fSelectionCount.setText(NLS.bind(msg, Integer.toString(units.length))); } else { fSelectionCount.setText(NLS.bind(Messages.EditIUContainerPage_itemsSelected, Integer.toString(0))); } diff --git a/ui/org.eclipse.pde.ui/src/org/eclipse/pde/internal/ui/shared/target/IUContentProvider.java b/ui/org.eclipse.pde.ui/src/org/eclipse/pde/internal/ui/shared/target/IUContentProvider.java index 9d57fe45e3..1ca876ecd7 100644 --- a/ui/org.eclipse.pde.ui/src/org/eclipse/pde/internal/ui/shared/target/IUContentProvider.java +++ b/ui/org.eclipse.pde.ui/src/org/eclipse/pde/internal/ui/shared/target/IUContentProvider.java @@ -14,7 +14,6 @@ *******************************************************************************/ package org.eclipse.pde.internal.ui.shared.target; -import java.util.ArrayList; import java.util.List; import org.eclipse.core.runtime.CoreException; @@ -45,13 +44,9 @@ public Object[] getChildren(Object parentElement) { if (target == null || !P2TargetUtils.isResolved(target)) { return new Object[0]; } - IInstallableUnit[] units = location.getInstallableUnits(); + List units = location.getInstallableUnits(); // Wrap the units so that they remember their parent container - List wrappedUnits = new ArrayList<>(units.length); - for (IInstallableUnit unit : units) { - wrappedUnits.add(new IUWrapper(unit, location)); - } - return wrappedUnits.toArray(); + return units.stream().map(unit -> new IUWrapper(unit, location)).toArray(); } catch (CoreException e) { return new Object[] {e.getStatus()}; } @@ -61,8 +56,8 @@ public Object[] getChildren(Object parentElement) { @Override public Object getParent(Object element) { - if (element instanceof IUWrapper) { - return ((IUWrapper) element).getParent(); + if (element instanceof IUWrapper wrapper) { + return wrapper.parent(); } return null; } @@ -76,21 +71,6 @@ public boolean hasChildren(Object element) { * Wraps an installable unit so that it knows what bundle container parent it belongs to * in the tree. */ - public static class IUWrapper { - private final IInstallableUnit fIU; - private final IUBundleContainer fParent; - - public IUWrapper(IInstallableUnit unit, IUBundleContainer parent) { - fIU = unit; - fParent = parent; - } - - public IInstallableUnit getIU() { - return fIU; - } - - public IUBundleContainer getParent() { - return fParent; - } + public static record IUWrapper(IInstallableUnit iu, IUBundleContainer parent) { } } diff --git a/ui/org.eclipse.pde.ui/src/org/eclipse/pde/internal/ui/shared/target/IUFactory.java b/ui/org.eclipse.pde.ui/src/org/eclipse/pde/internal/ui/shared/target/IUFactory.java index d0a5ed6de4..883ea07727 100644 --- a/ui/org.eclipse.pde.ui/src/org/eclipse/pde/internal/ui/shared/target/IUFactory.java +++ b/ui/org.eclipse.pde.ui/src/org/eclipse/pde/internal/ui/shared/target/IUFactory.java @@ -18,6 +18,7 @@ import java.util.Collections; import java.util.HashMap; import java.util.HashSet; +import java.util.List; import java.util.Map; import java.util.Map.Entry; import java.util.Set; @@ -54,10 +55,9 @@ public class IUFactory implements IAdapterFactory, ITargetLocationHandler { private static final Status STATUS_NO_CHANGE = new Status(IStatus.OK, PDECore.PLUGIN_ID, STATUS_CODE_NO_CHANGE, "", //$NON-NLS-1$ - null); private static final Status STATUS_FORCE_RELOAD = new Status(IStatus.OK, PDECore.PLUGIN_ID, - ITargetLocationHandler.STATUS_FORCE_RELOAD, "", null); //$NON-NLS-1$ ; + ITargetLocationHandler.STATUS_FORCE_RELOAD, "", null); //$NON-NLS-1$ private ILabelProvider fLabelProvider; private ITreeContentProvider fContentProvider; @@ -96,8 +96,8 @@ public boolean canEdit(ITargetDefinition target, TreePath path) { @Override public IWizard getEditWizard(ITargetDefinition target, TreePath path) { Object segment = path.getFirstSegment(); - if (segment instanceof IUBundleContainer) { - return new EditBundleContainerWizard(target, (ITargetLocation) segment); + if (segment instanceof IUBundleContainer container) { + return new EditBundleContainerWizard(target, container); } return null; } @@ -105,32 +105,32 @@ public IWizard getEditWizard(ITargetDefinition target, TreePath path) { @Override public IStatus update(ITargetDefinition target, TreePath[] treePaths, IProgressMonitor monitor) { Set containers = new HashSet<>(); - Map> wrappersMap = new HashMap<>(); + Map> wrappers = new HashMap<>(); for (TreePath path : treePaths) { Object lastSegment = path.getLastSegment(); - if (lastSegment instanceof IUBundleContainer) { - containers.add((IUBundleContainer) lastSegment); + if (lastSegment instanceof IUBundleContainer container) { + containers.add(container); } else if (lastSegment instanceof IUWrapper wrapper) { - wrappersMap.computeIfAbsent(wrapper.getParent(), k -> new HashSet<>()).add(wrapper.getIU().getId()); + wrappers.computeIfAbsent(wrapper.parent(), k -> new HashSet<>()).add(wrapper.iu().getId()); } } Map updatedContainer = new HashMap<>(); - SubMonitor subMonitor = SubMonitor.convert(monitor, (containers.size() + wrappersMap.size()) * 100); + SubMonitor subMonitor = SubMonitor.convert(monitor, containers.size() + wrappers.size()); for (IUBundleContainer container : containers) { try { - IUBundleContainer update = container.update(Collections.emptySet(), subMonitor.split(100)); + IUBundleContainer update = container.update(Collections.emptySet(), subMonitor.split(1)); updatedContainer.put(container, update); } catch (CoreException e) { return e.getStatus(); } } - for (Entry> entry : wrappersMap.entrySet()) { + for (Entry> entry : wrappers.entrySet()) { IUBundleContainer container = entry.getKey(); if (containers.contains(container)) { continue; } try { - IUBundleContainer update = container.update(entry.getValue(), subMonitor.split(100)); + IUBundleContainer update = container.update(entry.getValue(), subMonitor.split(1)); updatedContainer.put(container, update); } catch (CoreException e) { return e.getStatus(); @@ -177,7 +177,7 @@ public IStatus remove(ITargetDefinition target, TreePath[] treePaths) { } else if (segment instanceof IUWrapper wrapper) { // TODO check if we need to force-reload here (at least in // planner mode!) - wrapper.getParent().removeInstallableUnit(wrapper.getIU()); + wrapper.parent().removeInstallableUnit(wrapper.iu()); } } return forceReload ? STATUS_FORCE_RELOAD : Status.OK_STATUS; @@ -205,9 +205,9 @@ public IStatus reload(ITargetDefinition target, ITargetLocation[] targetLocation Messages.IUFactory_errorRefreshRepositories); for (ITargetLocation targetLocation : targetLocations) { if (targetLocation instanceof IUBundleContainer iu) { - URI[] repositories = iu.getRepositories(); - if (repositories != null) { - convert.setWorkRemaining(repositories.length * 2); + List repositories = iu.getRepositories(); + if (!repositories.isEmpty()) { + convert.setWorkRemaining(repositories.size() * 2); for (URI repositoryUri : repositories) { repositoryTracker.clearRepositoryNotFound(repositoryUri); try { diff --git a/ui/org.eclipse.pde.ui/src/org/eclipse/pde/internal/ui/shared/target/StyledBundleLabelProvider.java b/ui/org.eclipse.pde.ui/src/org/eclipse/pde/internal/ui/shared/target/StyledBundleLabelProvider.java index 6286f810bc..ab1beb49bb 100644 --- a/ui/org.eclipse.pde.ui/src/org/eclipse/pde/internal/ui/shared/target/StyledBundleLabelProvider.java +++ b/ui/org.eclipse.pde.ui/src/org/eclipse/pde/internal/ui/shared/target/StyledBundleLabelProvider.java @@ -110,8 +110,8 @@ protected StyledString getStyledString(Object element) { return null; } StyledString styledString = new StyledString(text); - if (element instanceof ITargetLocation) { - appendBundleCount(styledString, (ITargetLocation) element); + if (element instanceof ITargetLocation location) { + appendBundleCount(styledString, location); } return styledString; }); @@ -125,11 +125,11 @@ protected StyledString getStyledString(Object element) { */ private StyledString getInternalStyledString(Object element) { StyledString styledString = new StyledString(); - if (element instanceof BundleInfo) { - appendBundleInfo(styledString, ((BundleInfo) element)); - } else if (element instanceof NameVersionDescriptor) { - appendBundleInfo(styledString, new BundleInfo(((NameVersionDescriptor) element).getId(), - ((NameVersionDescriptor) element).getVersion(), null, BundleInfo.NO_LEVEL, false)); + if (element instanceof BundleInfo info) { + appendBundleInfo(styledString, info); + } else if (element instanceof NameVersionDescriptor descriptor) { + appendBundleInfo(styledString, + new BundleInfo(descriptor.getId(), descriptor.getVersion(), null, BundleInfo.NO_LEVEL, false)); } else if (element instanceof TargetBundle bundle) { if (bundle.getStatus().isOK()) { appendBundleInfo(styledString, bundle.getBundleInfo()); @@ -137,14 +137,14 @@ private StyledString getInternalStyledString(Object element) { // TODO Better error message for missing bundles styledString.append(bundle.getStatus().getMessage()); } - } else if (element instanceof IStatus) { - styledString.append(((IStatus) element).getMessage()); - } else if (element instanceof IPath) { - styledString.append(((IPath) element).removeFirstSegments(1).toString()); - } else if (element instanceof TargetFeature) { + } else if (element instanceof IStatus status) { + styledString.append(status.getMessage()); + } else if (element instanceof IPath path) { + styledString.append(path.removeFirstSegments(1).toString()); + } else if (element instanceof TargetFeature feature) { // Use a bundle info to reuse existing code - appendBundleInfo(styledString, new BundleInfo(((TargetFeature) element).getId(), - ((TargetFeature) element).getVersion(), null, BundleInfo.NO_LEVEL, false)); + appendBundleInfo(styledString, + new BundleInfo(feature.getId(), feature.getVersion(), null, BundleInfo.NO_LEVEL, false)); } else if (element instanceof FeatureBundleContainer container) { styledString.append(container.getFeatureId()); String version = container.getFeatureVersion(); @@ -180,15 +180,11 @@ private StyledString getInternalStyledString(Object element) { } appendBundleCount(styledString, container); } else if (element instanceof IUBundleContainer container) { - URI[] repos = container.getRepositories(); - if (repos == null || repos.length == 0) { - styledString.append(Messages.BundleContainerTable_8); - } else { - styledString.append(repos[0].toString()); - } + List repos = container.getRepositories(); + styledString.append(repos.isEmpty() ? Messages.BundleContainerTable_8 : repos.get(0).toString()); appendBundleCount(styledString, container); - } else if (element instanceof IUWrapper) { - styledString = getStyledString(((IUWrapper) element).getIU()); + } else if (element instanceof IUWrapper wrapper) { + styledString = getStyledString(wrapper.iu()); } else if (element instanceof IInstallableUnit iu) { @SuppressWarnings("restriction") String name = fTranslations.getIUProperty(iu, IInstallableUnit.PROP_NAME); @@ -312,14 +308,11 @@ public Image getImage(Object element) { */ private Image getInternalImage(Object element) { if (element instanceof TargetBundle bundle) { - int flag = 0; - if (bundle.getStatus().getSeverity() == IStatus.WARNING - || bundle.getStatus().getSeverity() == IStatus.INFO) { - flag = SharedLabelProvider.F_WARNING; - } else if (bundle.getStatus().getSeverity() == IStatus.ERROR) { - flag = SharedLabelProvider.F_ERROR; - } - + int flag = switch (bundle.getStatus().getSeverity()) { + case IStatus.WARNING, IStatus.INFO -> SharedLabelProvider.F_WARNING; + case IStatus.ERROR -> SharedLabelProvider.F_ERROR; + default -> 0; + }; if (bundle.getStatus().getSeverity() == IStatus.ERROR && bundle.getStatus().getCode() == TargetBundle.STATUS_FEATURE_DOES_NOT_EXIST) { // Missing features are represented by resolved bundles in the @@ -334,14 +327,14 @@ private Image getInternalImage(Object element) { } } else if (element instanceof BundleInfo) { return PDEPlugin.getDefault().getLabelProvider().get(PDEPluginImages.DESC_PLUGIN_OBJ); - } else if (element instanceof NameVersionDescriptor) { - if (((NameVersionDescriptor) element).getType() == NameVersionDescriptor.TYPE_FEATURE) { + } else if (element instanceof NameVersionDescriptor descriptor) { + if (NameVersionDescriptor.TYPE_FEATURE.equals(descriptor.getType())) { return PDEPlugin.getDefault().getLabelProvider().get(PDEPluginImages.DESC_FEATURE_OBJ); - } else if (((NameVersionDescriptor) element).getType() == NameVersionDescriptor.TYPE_PLUGIN) { + } else if (NameVersionDescriptor.TYPE_PLUGIN.equals(descriptor.getType())) { return PDEPlugin.getDefault().getLabelProvider().get(PDEPluginImages.DESC_PLUGIN_OBJ); } - } else if (element instanceof IStatus) { - int severity = ((IStatus) element).getSeverity(); + } else if (element instanceof IStatus status) { + int severity = status.getSeverity(); if (severity == IStatus.WARNING || severity == IStatus.INFO) { return PlatformUI.getWorkbench().getSharedImages().getImage(ISharedImages.IMG_OBJS_WARN_TSK); } else if (severity == IStatus.ERROR) { @@ -351,9 +344,8 @@ private Image getInternalImage(Object element) { return PlatformUI.getWorkbench().getSharedImages().getImage(ISharedImages.IMG_OBJ_FOLDER); } else if (element instanceof TargetFeature) { return PDEPlugin.getDefault().getLabelProvider().get(PDEPluginImages.DESC_FEATURE_OBJ); - } else if (element instanceof ITargetLocation) { + } else if (element instanceof ITargetLocation container) { int flag = 0; - ITargetLocation container = (ITargetLocation) element; if (container.isResolved()) { IStatus status = container.getStatus(); if (status.getSeverity() == IStatus.WARNING || status.getSeverity() == IStatus.INFO) { @@ -395,8 +387,8 @@ private Image getInternalImage(Object element) { } else if (element instanceof IUBundleContainer) { return PDEPlugin.getDefault().getLabelProvider().get(PDEPluginImages.DESC_REPOSITORY_OBJ, flag); } - } else if (element instanceof IUWrapper) { - return getImage(((IUWrapper) element).getIU()); + } else if (element instanceof IUWrapper wrapper) { + return getImage(wrapper.iu()); } else if (element instanceof IInstallableUnit) { return PDEPlugin.getDefault().getLabelProvider().get(PDEPluginImages.DESC_NOREF_FEATURE_OBJ); } diff --git a/ui/org.eclipse.pde.ui/src/org/eclipse/pde/internal/ui/shared/target/TargetLocationContentProvider.java b/ui/org.eclipse.pde.ui/src/org/eclipse/pde/internal/ui/shared/target/TargetLocationContentProvider.java index 39c506d64a..f550592bbc 100644 --- a/ui/org.eclipse.pde.ui/src/org/eclipse/pde/internal/ui/shared/target/TargetLocationContentProvider.java +++ b/ui/org.eclipse.pde.ui/src/org/eclipse/pde/internal/ui/shared/target/TargetLocationContentProvider.java @@ -98,8 +98,8 @@ public Object[] getChildren(Object parentElement) { @Override public Object getParent(Object element) { - if (element instanceof IUWrapper) { - return ((IUWrapper) element).getParent(); + if (element instanceof IUWrapper wrapper) { + return wrapper.parent(); } return null; }