From 7dd52e7ea391261976e9b3bdc9de5b4e70372276 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?J=C3=B6rg=20Kubitz?= <51790620+jukzi@users.noreply.github.com> Date: Mon, 7 Aug 2023 06:40:21 +0200 Subject: [PATCH 01/18] Create codeql.yml --- .github/workflows/codeql.yml | 13 +++++++++++++ 1 file changed, 13 insertions(+) create mode 100644 .github/workflows/codeql.yml diff --git a/.github/workflows/codeql.yml b/.github/workflows/codeql.yml new file mode 100644 index 00000000000..0988515fe32 --- /dev/null +++ b/.github/workflows/codeql.yml @@ -0,0 +1,13 @@ +name: CodeQL call + +on: + push: + branches: [ "master" ] + pull_request: + branches: [ "master" ] + schedule: + - cron: '45 8 * * 1' + +jobs: + callCodeQLworkflow: + uses: eclipse-platform/eclipse.platform.releng.aggregator/.github/workflows/codeQLworkflow.yml@master From 0509c0ebbf8d1cfd89bb7698176e6990d8c78fab Mon Sep 17 00:00:00 2001 From: Hannes Wellmann Date: Thu, 27 Jul 2023 22:21:39 +0200 Subject: [PATCH 02/18] Reference junit and hamcrest only via Import-Package This requires to import the hamcrest packages, if they are used and those test-plugins don't rely on the re-export of hamcrest by org.junit anymore. + Only use junit-4 assertion methods and replace use of junit-3 assertions. + Remove unnecessary hard-coded references to the hamcrest bundle name --- .../META-INF/MANIFEST.MF | 11 +++++++---- .../pde/api/tools/util/tests/UtilTests.java | 16 ++++------------ .../META-INF/MANIFEST.MF | 6 ++++-- .../META-INF/MANIFEST.MF | 4 +++- ds/org.eclipse.pde.ds.tests/META-INF/MANIFEST.MF | 4 +++- ua/org.eclipse.pde.ua.tests/META-INF/MANIFEST.MF | 4 +++- .../META-INF/MANIFEST.MF | 6 ++++-- .../META-INF/MANIFEST.MF | 8 +++++--- .../META-INF/MANIFEST.MF | 5 ++++- .../META-INF/MANIFEST.MF | 5 ++++- ui/org.eclipse.pde.ui.tests/META-INF/MANIFEST.MF | 9 +++++++-- .../parts/TargetPlatformPerfTest.java | 15 ++++++++------- 12 files changed, 56 insertions(+), 37 deletions(-) diff --git a/apitools/org.eclipse.pde.api.tools.tests/META-INF/MANIFEST.MF b/apitools/org.eclipse.pde.api.tools.tests/META-INF/MANIFEST.MF index a7624e8329c..e8aa2f7ae66 100644 --- a/apitools/org.eclipse.pde.api.tools.tests/META-INF/MANIFEST.MF +++ b/apitools/org.eclipse.pde.api.tools.tests/META-INF/MANIFEST.MF @@ -5,7 +5,6 @@ Bundle-SymbolicName: org.eclipse.pde.api.tools.tests Bundle-Version: 1.3.200.qualifier Bundle-Vendor: %Bundle-Vendor Require-Bundle: org.eclipse.core.runtime, - org.junit, org.eclipse.pde.api.tools;bundle-version="1.0.600", org.eclipse.jdt.launching;bundle-version="[3.6.100,4.0.0)", org.eclipse.debug.core, @@ -33,15 +32,19 @@ Export-Package: org.eclipse.pde.api.tools.anttasks.tests, org.eclipse.pde.api.tools.builder.tests.tags, org.eclipse.pde.api.tools.builder.tests.usage, org.eclipse.pde.api.tools.comparator.tests, - org.eclipse.pde.api.tools.model.tests;uses:="junit.framework,org.eclipse.pde.api.tools.model.component", + org.eclipse.pde.api.tools.model.tests, org.eclipse.pde.api.tools.problems.tests, org.eclipse.pde.api.tools.reference.tests, org.eclipse.pde.api.tools.search.tests, org.eclipse.pde.api.tools.tests, org.eclipse.pde.api.tools.tests.util, - org.eclipse.pde.api.tools.util.tests;uses:="junit.framework" + org.eclipse.pde.api.tools.util.tests Bundle-Activator: org.eclipse.pde.api.tools.tests.ApiTestsPlugin Bundle-ActivationPolicy: lazy Eclipse-BundleShape: dir -Import-Package: org.eclipse.equinox.frameworkadmin +Import-Package: junit.framework, + org.eclipse.equinox.frameworkadmin, + org.junit, + org.junit.runner, + org.junit.runners Automatic-Module-Name: org.eclipse.pde.api.tools.tests diff --git a/apitools/org.eclipse.pde.api.tools.tests/src/org/eclipse/pde/api/tools/util/tests/UtilTests.java b/apitools/org.eclipse.pde.api.tools.tests/src/org/eclipse/pde/api/tools/util/tests/UtilTests.java index aba4dbde919..2e342027acb 100644 --- a/apitools/org.eclipse.pde.api.tools.tests/src/org/eclipse/pde/api/tools/util/tests/UtilTests.java +++ b/apitools/org.eclipse.pde.api.tools.tests/src/org/eclipse/pde/api/tools/util/tests/UtilTests.java @@ -25,8 +25,7 @@ import java.io.IOException; import java.io.InputStream; import java.nio.charset.StandardCharsets; -import java.util.ArrayList; -import java.util.List; +import java.util.stream.Stream; import java.util.zip.ZipEntry; import java.util.zip.ZipInputStream; @@ -458,8 +457,7 @@ public boolean isDisposed() { return false; } } - List allComponents = new ArrayList<>(); - String[] componentNames = new String[] { + IApiComponent[] components = Stream.of( // "org.eclipse.swt", //$NON-NLS-1$ "org.eclipse.equinox.simpleconfigurator.manipulator", //$NON-NLS-1$ "org.eclipse.team.ui", //$NON-NLS-1$ @@ -503,7 +501,6 @@ public boolean isDisposed() { "org.eclipse.jdt", //$NON-NLS-1$ "org.eclipse.osgi.util", //$NON-NLS-1$ "org.sat4j.pb", //$NON-NLS-1$ - "org.hamcrest.core", //$NON-NLS-1$ "org.eclipse.jdt.junit4.runtime", //$NON-NLS-1$ "org.eclipse.equinox.p2.artifact.repository", //$NON-NLS-1$ "org.eclipse.core.databinding.property", //$NON-NLS-1$ @@ -644,13 +641,8 @@ public boolean isDisposed() { "org.eclipse.equinox.app", //$NON-NLS-1$ "org.eclipse.ui.net", //$NON-NLS-1$ "org.eclipse.equinox.p2.publisher", //$NON-NLS-1$ - "org.eclipse.ecf.provider.filetransfer.httpclient", //$NON-NLS-1$ - }; - for (String componentName : componentNames) { - allComponents.add(new LocalApiComponent(componentName)); - } - IApiComponent[] components = new IApiComponent[allComponents.size()]; - allComponents.toArray(components); + "org.eclipse.ecf.provider.filetransfer.httpclient" //$NON-NLS-1$ + ).map(LocalApiComponent::new).toArray(IApiComponent[]::new); FilteredElements excludedElements = new FilteredElements(); try { Util.collectRegexIds(line, excludedElements, components, false); diff --git a/build/org.eclipse.pde.build.tests/META-INF/MANIFEST.MF b/build/org.eclipse.pde.build.tests/META-INF/MANIFEST.MF index 26bd5700e55..6654dbba458 100644 --- a/build/org.eclipse.pde.build.tests/META-INF/MANIFEST.MF +++ b/build/org.eclipse.pde.build.tests/META-INF/MANIFEST.MF @@ -9,7 +9,6 @@ Export-Package: org.eclipse.pde.build.internal.tests;x-internal:=true, org.eclipse.pde.build.internal.tests.p2;x-internal:=true, org.eclipse.pde.build.tests Require-Bundle: org.eclipse.core.runtime, - org.junit, org.eclipse.pde.build, org.eclipse.ant.core, org.apache.ant, @@ -29,7 +28,10 @@ Import-Package: org.eclipse.equinox.frameworkadmin;version="2.0.0", org.eclipse.equinox.p2.repository;version="[2.0.0,3.0.0)", org.eclipse.equinox.p2.repository.artifact;version="[2.0.0,3.0.0)", org.eclipse.equinox.p2.repository.metadata;version="[2.0.0,3.0.0)", - org.eclipse.equinox.simpleconfigurator.manipulator;version="2.0.0" + org.eclipse.equinox.simpleconfigurator.manipulator;version="2.0.0", + org.junit, + org.junit.runner, + org.junit.runners Bundle-ActivationPolicy: lazy Eclipse-BundleShape: dir Automatic-Module-Name: org.eclipse.pde.build.tests diff --git a/ds/org.eclipse.pde.ds.annotations.tests/META-INF/MANIFEST.MF b/ds/org.eclipse.pde.ds.annotations.tests/META-INF/MANIFEST.MF index 96cb302227d..2a13c04f098 100644 --- a/ds/org.eclipse.pde.ds.annotations.tests/META-INF/MANIFEST.MF +++ b/ds/org.eclipse.pde.ds.annotations.tests/META-INF/MANIFEST.MF @@ -10,11 +10,13 @@ Bundle-ActivationPolicy: lazy Require-Bundle: org.eclipse.pde.ds.annotations;bundle-version="[1.1.0,1.4.0)", org.eclipse.pde.ds.core;bundle-version="[1.1.0,2.0.0)", org.eclipse.pde.ui;bundle-version="[3.9.0,4.0.0)", - org.junit;bundle-version="[4.12.0,5.0.0)", org.eclipse.core.resources;bundle-version="[3.11.0,4.0.0)", org.eclipse.core.runtime;bundle-version="[3.29.0,4.0.0)", org.eclipse.text;bundle-version="[3.6.0,4.0.0)" Export-Package: org.eclipse.pde.ds.internal.annotations.tests;x-internal:=true +Import-Package: org.junit, + org.junit.runner, + org.junit.runners Eclipse-BundleShape: dir Bundle-ClassPath: tests.jar Automatic-Module-Name: org.eclipse.pde.ds.annotations.tests diff --git a/ds/org.eclipse.pde.ds.tests/META-INF/MANIFEST.MF b/ds/org.eclipse.pde.ds.tests/META-INF/MANIFEST.MF index 0893ae3591d..99a807859c8 100644 --- a/ds/org.eclipse.pde.ds.tests/META-INF/MANIFEST.MF +++ b/ds/org.eclipse.pde.ds.tests/META-INF/MANIFEST.MF @@ -5,7 +5,6 @@ Bundle-SymbolicName: org.eclipse.pde.ds.tests Bundle-Version: 1.3.100.qualifier Bundle-Activator: org.eclipse.pde.internal.ds.tests.Activator Require-Bundle: org.eclipse.core.runtime;bundle-version="[3.29.0,4.0.0)", - org.junit;bundle-version="3.8.2", org.eclipse.pde.core;bundle-version="[3.3.0,4.0.0)", org.eclipse.pde.ds.core;bundle-version="[1.0.0,2.0.0)", org.eclipse.text;bundle-version="[3.3.0,4.0.0)" @@ -14,5 +13,8 @@ Bundle-RequiredExecutionEnvironment: JavaSE-17 Bundle-Localization: plugin Bundle-Vendor: %providerName Export-Package: org.eclipse.pde.internal.ds.tests;x-internal:=true +Import-Package: org.junit, + org.junit.runner, + org.junit.runners Eclipse-BundleShape: dir Automatic-Module-Name: org.eclipse.pde.ds.tests diff --git a/ua/org.eclipse.pde.ua.tests/META-INF/MANIFEST.MF b/ua/org.eclipse.pde.ua.tests/META-INF/MANIFEST.MF index 9cad3c55378..7856f605d97 100644 --- a/ua/org.eclipse.pde.ua.tests/META-INF/MANIFEST.MF +++ b/ua/org.eclipse.pde.ua.tests/META-INF/MANIFEST.MF @@ -6,7 +6,6 @@ Bundle-Version: 1.3.100.qualifier Bundle-ClassPath: tests.jar Require-Bundle: org.eclipse.core.runtime;bundle-version="[3.29.0,4.0.0)", org.eclipse.pde.ua.core;bundle-version="[1.0.0,2.0.0)", - org.junit;bundle-version="3.8.2", org.eclipse.text;bundle-version="[3.3.0,4.0.0)", org.eclipse.pde.ui;bundle-version="[3.5.0,4.0.0)", org.eclipse.ui.workbench;bundle-version="[3.5.0,4.0.0)", @@ -27,3 +26,6 @@ Export-Package: org.eclipse.pde.internal.ua.tests;x-internal:="true", Bundle-Localization: plugin Eclipse-BundleShape: dir Automatic-Module-Name: org.eclipse.pde.ua.tests +Import-Package: org.junit, + org.junit.runner, + org.junit.runners diff --git a/ui/org.eclipse.pde.genericeditor.extension.tests/META-INF/MANIFEST.MF b/ui/org.eclipse.pde.genericeditor.extension.tests/META-INF/MANIFEST.MF index 88397caef6f..cf2d4fef176 100644 --- a/ui/org.eclipse.pde.genericeditor.extension.tests/META-INF/MANIFEST.MF +++ b/ui/org.eclipse.pde.genericeditor.extension.tests/META-INF/MANIFEST.MF @@ -5,8 +5,7 @@ Bundle-SymbolicName: org.eclipse.pde.genericeditor.extension.tests Bundle-Version: 1.2.100.qualifier Bundle-Vendor: Eclipse.org Bundle-RequiredExecutionEnvironment: JavaSE-17 -Require-Bundle: org.junit;bundle-version="4.12.0", - org.eclipse.core.runtime;bundle-version="[3.29.0,4.0.0)", +Require-Bundle: org.eclipse.core.runtime;bundle-version="[3.29.0,4.0.0)", org.eclipse.core.resources;bundle-version="3.12.0", org.eclipse.jface.text;bundle-version="3.13.0", org.eclipse.ui;bundle-version="3.109.100", @@ -16,3 +15,6 @@ Require-Bundle: org.junit;bundle-version="4.12.0", org.eclipse.equinox.p2.metadata, org.eclipse.core.filebuffers Automatic-Module-Name: org.eclipse.pde.genericeditor.extension.tests +Import-Package: org.junit, + org.junit.runner, + org.junit.runners diff --git a/ui/org.eclipse.pde.junit.runtime.tests/META-INF/MANIFEST.MF b/ui/org.eclipse.pde.junit.runtime.tests/META-INF/MANIFEST.MF index e3bb6b790d5..01daba77897 100644 --- a/ui/org.eclipse.pde.junit.runtime.tests/META-INF/MANIFEST.MF +++ b/ui/org.eclipse.pde.junit.runtime.tests/META-INF/MANIFEST.MF @@ -8,8 +8,7 @@ Bundle-RequiredExecutionEnvironment: JavaSE-17 Bundle-Vendor: Eclipse.org Bundle-ActivationPolicy: lazy Eclipse-BundleShape: dir -Require-Bundle: org.junit, - org.eclipse.core.runtime;bundle-version="3.29.0", +Require-Bundle: org.eclipse.core.runtime;bundle-version="3.29.0", org.eclipse.pde.launching;bundle-version="3.7.700", org.eclipse.core.resources;bundle-version="3.13.500", org.eclipse.pde.ui;bundle-version="3.11.100", @@ -18,4 +17,7 @@ Require-Bundle: org.junit, org.eclipse.debug.ui;bundle-version="3.14.200", org.eclipse.ui;bundle-version="3.114.0", org.eclipse.pde.ui.tests;bundle-version="3.11.500" -Import-Package: org.assertj.core.api;version="3.14.0" +Import-Package: org.assertj.core.api;version="3.14.0", + org.junit, + org.junit.runner, + org.junit.runners diff --git a/ui/org.eclipse.pde.ui.templates.tests/META-INF/MANIFEST.MF b/ui/org.eclipse.pde.ui.templates.tests/META-INF/MANIFEST.MF index a0321bd64aa..ee437a93f9d 100644 --- a/ui/org.eclipse.pde.ui.templates.tests/META-INF/MANIFEST.MF +++ b/ui/org.eclipse.pde.ui.templates.tests/META-INF/MANIFEST.MF @@ -8,7 +8,6 @@ Bundle-ClassPath: tests.jar Bundle-RequiredExecutionEnvironment: JavaSE-17 Require-Bundle: org.eclipse.pde.ui;bundle-version="3.10.0", org.eclipse.pde.ui.templates;bundle-version="3.6.0", - org.junit;bundle-version="4.13.0", org.eclipse.core.runtime;bundle-version="3.29.0", org.eclipse.core.resources;bundle-version="3.12.0", org.eclipse.ui.ide;bundle-version="3.13.0", @@ -17,3 +16,7 @@ Require-Bundle: org.eclipse.pde.ui;bundle-version="3.10.0", org.eclipse.pde.ui.tests Automatic-Module-Name: org.eclipse.pde.ui.templates.tests Eclipse-BundleShape: dir +Import-Package: org.hamcrest, + org.junit, + org.junit.runner, + org.junit.runners diff --git a/ui/org.eclipse.pde.ui.tests.smartimport/META-INF/MANIFEST.MF b/ui/org.eclipse.pde.ui.tests.smartimport/META-INF/MANIFEST.MF index 1acbe52596c..15249210cc8 100644 --- a/ui/org.eclipse.pde.ui.tests.smartimport/META-INF/MANIFEST.MF +++ b/ui/org.eclipse.pde.ui.tests.smartimport/META-INF/MANIFEST.MF @@ -18,10 +18,13 @@ Require-Bundle: org.eclipse.core.resources, org.eclipse.reddeer.workbench;bundle-version="[3.0.0,5.0.0)", org.eclipse.reddeer.workbench.core;bundle-version="[3.0.0,5.0.0)", org.eclipse.swt, - org.junit, org.eclipse.jdt.ui, org.eclipse.pde.ui Bundle-ActivationPolicy: lazy Eclipse-BundleShape: dir Bundle-RequiredExecutionEnvironment: JavaSE-17 Automatic-Module-Name: org.eclipse.pde.ui.tests.smartimport +Import-Package: org.hamcrest, + org.junit, + org.junit.runner, + org.junit.runners diff --git a/ui/org.eclipse.pde.ui.tests/META-INF/MANIFEST.MF b/ui/org.eclipse.pde.ui.tests/META-INF/MANIFEST.MF index c7a9bff0d3c..c30778eb329 100644 --- a/ui/org.eclipse.pde.ui.tests/META-INF/MANIFEST.MF +++ b/ui/org.eclipse.pde.ui.tests/META-INF/MANIFEST.MF @@ -6,8 +6,7 @@ Bundle-Version: 3.12.200.qualifier Bundle-ClassPath: tests.jar Bundle-Activator: org.eclipse.pde.ui.tests.PDETestsPlugin Bundle-Vendor: Eclipse.org -Require-Bundle: org.junit, - org.eclipse.pde.ui, +Require-Bundle: org.eclipse.pde.ui, org.eclipse.ui, org.eclipse.core.resources, org.eclipse.core.runtime, @@ -47,7 +46,13 @@ Import-Package: javax.annotation;version="[1.3.0,2.0.0)", org.assertj.core.api;version="3.14.0", org.assertj.core.presentation;version="3.21.0", org.eclipse.pde.internal.build, + org.hamcrest, + org.junit, org.junit.jupiter.api.function;version="5.8.1", + org.junit.rules, + org.junit.runner, + org.junit.runners, + org.junit.runners.model, org.osgi.service.event;version="[1.3.0,2.0.0)" Bundle-RequiredExecutionEnvironment: JavaSE-17 Eclipse-BundleShape: dir diff --git a/ui/org.eclipse.pde.ui.tests/src/org/eclipse/pde/ui/tests/performance/parts/TargetPlatformPerfTest.java b/ui/org.eclipse.pde.ui.tests/src/org/eclipse/pde/ui/tests/performance/parts/TargetPlatformPerfTest.java index a5333bc83e1..53d9bc2b39c 100644 --- a/ui/org.eclipse.pde.ui.tests/src/org/eclipse/pde/ui/tests/performance/parts/TargetPlatformPerfTest.java +++ b/ui/org.eclipse.pde.ui.tests/src/org/eclipse/pde/ui/tests/performance/parts/TargetPlatformPerfTest.java @@ -50,6 +50,7 @@ import org.eclipse.pde.ui.tests.util.TestBundleCreator; import org.eclipse.test.performance.Dimension; import org.eclipse.test.performance.PerformanceTestCase; +import org.junit.Assert; import org.osgi.framework.Version; /** @@ -117,7 +118,7 @@ public void testSearchModelRegistry() throws Exception { // Create a workspace model IWorkspace ws = ResourcesPlugin.getWorkspace(); IProject proj = ws.getRoot().getProject(SEARCH_TEST_WORKSPACE_NAME); - assertFalse("Project should not exist", proj.exists()); + Assert.assertFalse("Project should not exist", proj.exists()); IBundleProjectDescription description = service.getDescription(proj); description.setSymbolicName(SEARCH_TEST_WORKSPACE_NAME); description.setBundleVersion(new Version("1.1.1")); @@ -203,19 +204,19 @@ public void testSearchModelRegistry() throws Exception { private void executeSearchTest() { IPluginModelBase[] models; models = PluginRegistry.getAllModels(); - assertEquals(SEARCH_TEST_EXTERNAL_COUNT + 1, models.length); + Assert.assertEquals(SEARCH_TEST_EXTERNAL_COUNT + 1, models.length); models = PluginRegistry.getWorkspaceModels(); - assertEquals(1, models.length); + Assert.assertEquals(1, models.length); models = PluginRegistry.getExternalModels(); - assertEquals(SEARCH_TEST_EXTERNAL_COUNT, models.length); + Assert.assertEquals(SEARCH_TEST_EXTERNAL_COUNT, models.length); IPluginModelBase model; IWorkspace ws = ResourcesPlugin.getWorkspace(); model = PluginRegistry.findModel(SEARCH_TEST_WORKSPACE_NAME); - assertNotNull(model); + Assert.assertNotNull(model); IProject project = ws.getRoot().getProject(SEARCH_TEST_WORKSPACE_NAME); model = PluginRegistry.findModel(project); - assertNotNull(model); + Assert.assertNotNull(model); model = PluginRegistry.findModel(SEARCH_TEST_EXTERNAL_NAME); openRequiredBundles(model, new HashSet<>()); @@ -230,7 +231,7 @@ private void executeSearchTest() { * @param allBundleNames set of symbolic names that have been looked up to prevent stack overflows */ private void openRequiredBundles(IPluginModelBase model, Set allBundleNames) { - assertNotNull(model); + Assert.assertNotNull(model); BundleSpecification[] required = model.getBundleDescription().getRequiredBundles(); for (BundleSpecification element : required) { if (!allBundleNames.contains(element.getName())) { From d7228a1104020787867042c633cb1b00eebc777e Mon Sep 17 00:00:00 2001 From: Hannes Wellmann Date: Fri, 28 Jul 2023 00:14:53 +0200 Subject: [PATCH 03/18] Compute junit5 runtime Plug-ins dynamically in RequiredPlugins-Container And add support for old junit bundle names from Eclipse-Orbit. --- .../RequiredPluginsClasspathContainer.java | 41 +++++++++++++------ 1 file changed, 28 insertions(+), 13 deletions(-) diff --git a/ui/org.eclipse.pde.core/src/org/eclipse/pde/internal/core/RequiredPluginsClasspathContainer.java b/ui/org.eclipse.pde.core/src/org/eclipse/pde/internal/core/RequiredPluginsClasspathContainer.java index 45487b312b7..9bd67b371f9 100644 --- a/ui/org.eclipse.pde.core/src/org/eclipse/pde/internal/core/RequiredPluginsClasspathContainer.java +++ b/ui/org.eclipse.pde.core/src/org/eclipse/pde/internal/core/RequiredPluginsClasspathContainer.java @@ -13,6 +13,8 @@ *******************************************************************************/ package org.eclipse.pde.internal.core; +import static org.eclipse.pde.internal.core.DependencyManager.Options.INCLUDE_OPTIONAL_DEPENDENCIES; + import java.io.File; import java.util.ArrayDeque; import java.util.ArrayList; @@ -22,6 +24,7 @@ import java.util.HashSet; import java.util.List; import java.util.Map; +import java.util.Objects; import java.util.Optional; import java.util.Queue; import java.util.Set; @@ -60,13 +63,18 @@ public class RequiredPluginsClasspathContainer extends PDEClasspathContainer implements IClasspathContainer { @SuppressWarnings("nls") - private static final Collection JUNIT5_RUNTIME_PLUGINS = Set.of("org.junit", "junit-jupiter-api", - "junit-jupiter-engine", "junit-platform-commons", "junit-platform-engine", "org.hamcrest.core", - "org.opentest4j"); + private static final Set JUNIT5_RUNTIME_PLUGINS = Set.of("org.junit", // + "junit-jupiter-engine", // BSN of the bundle from Maven-Central + "org.junit.jupiter.engine"); // BSN of the bundle from Eclipse-Orbit + @SuppressWarnings("nls") + private static final Set JUNIT5_API_PLUGINS = Set.of( // + "junit-jupiter-api", // BSN of the bundle from Maven-Central + "org.junit.jupiter.api"); // BSN of the bundle from Eclipse-Orbit private final IPluginModelBase fModel; private IBuild fBuild; + private List junit5RuntimeClosure; private IClasspathEntry[] fEntries; private boolean addImportedPackages; @@ -489,18 +497,16 @@ private void addJunit5RuntimeDependencies(Set added, List added, List> rules = Map.of(desc, List.of()); addPlugin(desc, true, rules, entries); } + } + private boolean containsJunit5Dependency(Collection dependencies) { + return dependencies.stream().map(BundleDescription::getSymbolicName).anyMatch(JUNIT5_API_PLUGINS::contains); } - private static boolean containsJunit5Dependency(Collection dependencies) { - return dependencies.stream().anyMatch(desc -> "junit-jupiter-api".equals(desc.getName()) || "org.junit.jupiter.api".equals(desc.getName())); //$NON-NLS-1$ //$NON-NLS-2$ + private static List collectJunit5RuntimeRequirements() { + List roots = JUNIT5_RUNTIME_PLUGINS.stream().map(PluginRegistry::findModel) + .filter(Objects::nonNull).filter(IPluginModelBase::isEnabled) + .map(IPluginModelBase::getBundleDescription).toList(); + Set closure = DependencyManager.findRequirementsClosure(roots, + INCLUDE_OPTIONAL_DEPENDENCIES); + String systemBundleBSN = TargetPlatformHelper.getPDEState().getSystemBundle(); + return closure.stream().filter(b -> !b.getSymbolicName().equals(systemBundleBSN)).toList(); } private void addSecondaryDependencies(BundleDescription desc, Set added, From 8435fdd8949cd6673876e03c04a2325efb1258a6 Mon Sep 17 00:00:00 2001 From: Alshama M S Date: Fri, 11 Aug 2023 22:58:41 +0530 Subject: [PATCH 04/18] Code Cleanup: Java 16 instanceof pattern matching --- .../api/tools/internal/ApiAnnotations.java | 3 +-- .../tools/internal/ApiDescriptionManager.java | 6 ++---- .../tools/internal/BundleVersionRange.java | 3 +-- .../api/tools/internal/JavadocTagManager.java | 3 +-- .../RequiredComponentDescription.java | 3 +-- .../AbstractIllegalMethodReference.java | 3 +-- .../builder/AbstractProblemDetector.java | 3 +-- .../internal/builder/ApiAnalysisBuilder.java | 3 +-- .../internal/builder/BaseApiAnalyzer.java | 3 +-- .../builder/IncrementalApiBuilder.java | 3 +-- .../builder/ProblemDetectorBuilder.java | 3 +-- .../internal/builder/ReferenceExtractor.java | 21 +++++++------------ .../internal/builder/SystemApiDetector.java | 3 +-- .../api/tools/internal/builder/Validator.java | 3 +-- .../api/tools/internal/comparator/Delta.java | 3 +-- .../descriptors/FieldDescriptorImpl.java | 3 +-- .../descriptors/MethodDescriptorImpl.java | 3 +-- .../descriptors/PackageDescriptorImpl.java | 3 +-- .../ReferenceTypeDescriptorImpl.java | 3 +-- .../api/tools/internal/model/ApiBaseline.java | 6 ++---- .../api/tools/internal/model/ApiMember.java | 3 +-- .../pde/api/tools/internal/model/ApiType.java | 6 ++---- .../model/ArchiveApiTypeContainer.java | 3 +-- .../tools/internal/model/BundleComponent.java | 3 +-- .../api/tools/internal/model/MethodKey.java | 3 +-- .../internal/model/ResourceApiTypeRoot.java | 3 +-- .../model/StubArchiveApiTypeContainer.java | 3 +-- .../internal/model/TypeStructureBuilder.java | 3 +-- .../tools/internal/problems/ApiProblem.java | 3 +-- .../internal/problems/ApiProblemFilter.java | 3 +-- .../provisional/scanner/TagScanner.java | 9 +++----- .../search/ConsumerReportConvertor.java | 3 +-- .../search/MissingRefReportConverter.java | 3 +-- .../internal/search/ReferenceDescriptor.java | 3 +-- .../internal/search/UseReportConverter.java | 3 +-- .../api/tools/internal/util/Signatures.java | 3 +-- .../pde/api/tools/internal/util/Util.java | 18 ++++++---------- 37 files changed, 53 insertions(+), 106 deletions(-) diff --git a/apitools/org.eclipse.pde.api.tools/src/org/eclipse/pde/api/tools/internal/ApiAnnotations.java b/apitools/org.eclipse.pde.api.tools/src/org/eclipse/pde/api/tools/internal/ApiAnnotations.java index 74703a72282..a6ae6501d69 100644 --- a/apitools/org.eclipse.pde.api.tools/src/org/eclipse/pde/api/tools/internal/ApiAnnotations.java +++ b/apitools/org.eclipse.pde.api.tools/src/org/eclipse/pde/api/tools/internal/ApiAnnotations.java @@ -57,8 +57,7 @@ public String toString() { @Override public boolean equals(Object obj) { - if (obj instanceof ApiAnnotations) { - ApiAnnotations desc = (ApiAnnotations) obj; + if (obj instanceof ApiAnnotations desc) { return this.bits == desc.bits; } return false; diff --git a/apitools/org.eclipse.pde.api.tools/src/org/eclipse/pde/api/tools/internal/ApiDescriptionManager.java b/apitools/org.eclipse.pde.api.tools/src/org/eclipse/pde/api/tools/internal/ApiDescriptionManager.java index 7cd5641b508..ef227a61c39 100644 --- a/apitools/org.eclipse.pde.api.tools/src/org/eclipse/pde/api/tools/internal/ApiDescriptionManager.java +++ b/apitools/org.eclipse.pde.api.tools/src/org/eclipse/pde/api/tools/internal/ApiDescriptionManager.java @@ -356,8 +356,7 @@ private void restoreNode(ProjectApiDescription apiDesc, Element element, Manifes break; } case IApiXmlConstants.ELEMENT_FIELD: - if (parentNode.element instanceof IReferenceTypeDescriptor) { - IReferenceTypeDescriptor type = (IReferenceTypeDescriptor) parentNode.element; + if (parentNode.element instanceof IReferenceTypeDescriptor type) { int vis = getInt(element, IApiXmlConstants.ATTR_VISIBILITY); int res = getInt(element, IApiXmlConstants.ATTR_RESTRICTIONS); String name = element.getAttribute(IApiXmlConstants.ATTR_NAME); @@ -366,8 +365,7 @@ private void restoreNode(ProjectApiDescription apiDesc, Element element, Manifes } break; case IApiXmlConstants.ELEMENT_METHOD: - if (parentNode.element instanceof IReferenceTypeDescriptor) { - IReferenceTypeDescriptor type = (IReferenceTypeDescriptor) parentNode.element; + if (parentNode.element instanceof IReferenceTypeDescriptor type) { int vis = getInt(element, IApiXmlConstants.ATTR_VISIBILITY); int res = getInt(element, IApiXmlConstants.ATTR_RESTRICTIONS); String name = element.getAttribute(IApiXmlConstants.ATTR_NAME); diff --git a/apitools/org.eclipse.pde.api.tools/src/org/eclipse/pde/api/tools/internal/BundleVersionRange.java b/apitools/org.eclipse.pde.api.tools/src/org/eclipse/pde/api/tools/internal/BundleVersionRange.java index c641dbc753a..7f2a837c96a 100644 --- a/apitools/org.eclipse.pde.api.tools/src/org/eclipse/pde/api/tools/internal/BundleVersionRange.java +++ b/apitools/org.eclipse.pde.api.tools/src/org/eclipse/pde/api/tools/internal/BundleVersionRange.java @@ -68,8 +68,7 @@ public boolean isIncludeMinimum() { @Override public boolean equals(Object obj) { - if (obj instanceof BundleVersionRange) { - BundleVersionRange range = (BundleVersionRange) obj; + if (obj instanceof BundleVersionRange range) { return fRange.equals(range.fRange); } return false; diff --git a/apitools/org.eclipse.pde.api.tools/src/org/eclipse/pde/api/tools/internal/JavadocTagManager.java b/apitools/org.eclipse.pde.api.tools/src/org/eclipse/pde/api/tools/internal/JavadocTagManager.java index d84fa66e474..4bc9cd9a0fb 100644 --- a/apitools/org.eclipse.pde.api.tools/src/org/eclipse/pde/api/tools/internal/JavadocTagManager.java +++ b/apitools/org.eclipse.pde.api.tools/src/org/eclipse/pde/api/tools/internal/JavadocTagManager.java @@ -50,8 +50,7 @@ public Key(int t, int m) { @Override public boolean equals(Object obj) { - if (obj instanceof Key) { - Key other = (Key) obj; + if (obj instanceof Key other) { return type == other.type && member == other.member; } return super.equals(obj); diff --git a/apitools/org.eclipse.pde.api.tools/src/org/eclipse/pde/api/tools/internal/RequiredComponentDescription.java b/apitools/org.eclipse.pde.api.tools/src/org/eclipse/pde/api/tools/internal/RequiredComponentDescription.java index cf1297292dd..41e021c0a87 100644 --- a/apitools/org.eclipse.pde.api.tools/src/org/eclipse/pde/api/tools/internal/RequiredComponentDescription.java +++ b/apitools/org.eclipse.pde.api.tools/src/org/eclipse/pde/api/tools/internal/RequiredComponentDescription.java @@ -59,8 +59,7 @@ public RequiredComponentDescription(String id, IVersionRange range, boolean isOp @Override public boolean equals(Object obj) { - if (obj instanceof RequiredComponentDescription) { - RequiredComponentDescription desc = (RequiredComponentDescription) obj; + if (obj instanceof RequiredComponentDescription desc) { return fId.equals(desc.fId) && fRange.equals(desc.fRange); } return super.equals(obj); diff --git a/apitools/org.eclipse.pde.api.tools/src/org/eclipse/pde/api/tools/internal/builder/AbstractIllegalMethodReference.java b/apitools/org.eclipse.pde.api.tools/src/org/eclipse/pde/api/tools/internal/builder/AbstractIllegalMethodReference.java index e0fd2244ba4..bc2b57d84c2 100644 --- a/apitools/org.eclipse.pde.api.tools/src/org/eclipse/pde/api/tools/internal/builder/AbstractIllegalMethodReference.java +++ b/apitools/org.eclipse.pde.api.tools/src/org/eclipse/pde/api/tools/internal/builder/AbstractIllegalMethodReference.java @@ -74,8 +74,7 @@ public boolean considerReference(IReference reference, IProgressMonitor monitor) } catch (CoreException ce) { // do nothing, skip it } - if (member instanceof IApiMethod) { - IApiMethod method = (IApiMethod) member; + if (member instanceof IApiMethod method) { if (method.isDefaultMethod()) { return considerReference(reference, monitor); } diff --git a/apitools/org.eclipse.pde.api.tools/src/org/eclipse/pde/api/tools/internal/builder/AbstractProblemDetector.java b/apitools/org.eclipse.pde.api.tools/src/org/eclipse/pde/api/tools/internal/builder/AbstractProblemDetector.java index 9f15fb0f21d..34244994a38 100644 --- a/apitools/org.eclipse.pde.api.tools/src/org/eclipse/pde/api/tools/internal/builder/AbstractProblemDetector.java +++ b/apitools/org.eclipse.pde.api.tools/src/org/eclipse/pde/api/tools/internal/builder/AbstractProblemDetector.java @@ -517,8 +517,7 @@ public List createProblems(IProgressMonitor monitor) { IApiComponent component = reference.getMember().getApiComponent(); try { IApiProblem problem = null; - if (component instanceof ProjectComponent) { - ProjectComponent ppac = (ProjectComponent) component; + if (component instanceof ProjectComponent ppac) { IJavaProject project = ppac.getJavaProject(); problem = createProblem(reference, project); } else { diff --git a/apitools/org.eclipse.pde.api.tools/src/org/eclipse/pde/api/tools/internal/builder/ApiAnalysisBuilder.java b/apitools/org.eclipse.pde.api.tools/src/org/eclipse/pde/api/tools/internal/builder/ApiAnalysisBuilder.java index 4d4238e9c13..b6845ac9e00 100644 --- a/apitools/org.eclipse.pde.api.tools/src/org/eclipse/pde/api/tools/internal/builder/ApiAnalysisBuilder.java +++ b/apitools/org.eclipse.pde.api.tools/src/org/eclipse/pde/api/tools/internal/builder/ApiAnalysisBuilder.java @@ -629,10 +629,9 @@ public boolean contains(ISchedulingRule rule) { @Override public boolean isConflicting(ISchedulingRule rule) { - if (!(rule instanceof ApiAnalysisJobRule)) { + if (!(rule instanceof ApiAnalysisJobRule other)) { return false; } - ApiAnalysisJobRule other = (ApiAnalysisJobRule) rule; return project.equals(other.project); } diff --git a/apitools/org.eclipse.pde.api.tools/src/org/eclipse/pde/api/tools/internal/builder/BaseApiAnalyzer.java b/apitools/org.eclipse.pde.api.tools/src/org/eclipse/pde/api/tools/internal/builder/BaseApiAnalyzer.java index 18880b7e16a..369366baea0 100644 --- a/apitools/org.eclipse.pde.api.tools/src/org/eclipse/pde/api/tools/internal/builder/BaseApiAnalyzer.java +++ b/apitools/org.eclipse.pde.api.tools/src/org/eclipse/pde/api/tools/internal/builder/BaseApiAnalyzer.java @@ -2666,8 +2666,7 @@ public void checkBaselineMismatch(IApiBaseline baseline, IApiBaseline workspaceB * @return Java project or null */ private IJavaProject getJavaProject(IApiComponent component) { - if (component instanceof ProjectComponent) { - ProjectComponent pp = (ProjectComponent) component; + if (component instanceof ProjectComponent pp) { return pp.getJavaProject(); } return null; diff --git a/apitools/org.eclipse.pde.api.tools/src/org/eclipse/pde/api/tools/internal/builder/IncrementalApiBuilder.java b/apitools/org.eclipse.pde.api.tools/src/org/eclipse/pde/api/tools/internal/builder/IncrementalApiBuilder.java index 17409b7b6df..689145282e2 100644 --- a/apitools/org.eclipse.pde.api.tools/src/org/eclipse/pde/api/tools/internal/builder/IncrementalApiBuilder.java +++ b/apitools/org.eclipse.pde.api.tools/src/org/eclipse/pde/api/tools/internal/builder/IncrementalApiBuilder.java @@ -166,8 +166,7 @@ public boolean visit(IResourceDelta delta) throws CoreException { if (component != null) { try { IApiAnnotations annotations = component.getApiDescription().resolveAnnotations(Factory.typeDescriptor(type.replace('/', '.'))); - if (annotations instanceof TypeAnnotations) { - TypeAnnotations ta = (TypeAnnotations) annotations; + if (annotations instanceof TypeAnnotations ta) { if (ta.getBuildStamp() == BuildStamps.getBuildStamp(resource.getProject())) { // note description change in // addition to structure diff --git a/apitools/org.eclipse.pde.api.tools/src/org/eclipse/pde/api/tools/internal/builder/ProblemDetectorBuilder.java b/apitools/org.eclipse.pde.api.tools/src/org/eclipse/pde/api/tools/internal/builder/ProblemDetectorBuilder.java index f05c4ba30bd..0bb636b4166 100644 --- a/apitools/org.eclipse.pde.api.tools/src/org/eclipse/pde/api/tools/internal/builder/ProblemDetectorBuilder.java +++ b/apitools/org.eclipse.pde.api.tools/src/org/eclipse/pde/api/tools/internal/builder/ProblemDetectorBuilder.java @@ -197,8 +197,7 @@ public void setOwningComponent(IApiComponent component) { * not a {@link PluginProjectApiComponent} */ private IProject getProject(IApiComponent component) { - if (component instanceof ProjectComponent) { - ProjectComponent comp = (ProjectComponent) component; + if (component instanceof ProjectComponent comp) { return comp.getJavaProject().getProject(); } return null; diff --git a/apitools/org.eclipse.pde.api.tools/src/org/eclipse/pde/api/tools/internal/builder/ReferenceExtractor.java b/apitools/org.eclipse.pde.api.tools/src/org/eclipse/pde/api/tools/internal/builder/ReferenceExtractor.java index 2d35c700a17..3cd2fde2ab5 100644 --- a/apitools/org.eclipse.pde.api.tools/src/org/eclipse/pde/api/tools/internal/builder/ReferenceExtractor.java +++ b/apitools/org.eclipse.pde.api.tools/src/org/eclipse/pde/api/tools/internal/builder/ReferenceExtractor.java @@ -417,8 +417,7 @@ && getDefaultDefined(type, name, desc, false) != null) { @Override public void visitInvokeDynamicInsn(String name, String desc, Handle bsm, Object... bsmArgs) { for (Object arg : bsmArgs) { - if (arg instanceof Handle) { - Handle handle = (Handle) arg; + if (arg instanceof Handle handle) { Type declaringType = Type.getObjectType(handle.getOwner()); Reference reference = ReferenceExtractor.this.addMethodReference(declaringType, handle.getName(), handle.getDesc(), IReference.REF_VIRTUALMETHOD, 0); if (reference != null) { @@ -564,14 +563,12 @@ public void visitLocalVariable(String name, String desc, String signature, Label @Override public void visitLdcInsn(Object cst) { - if (cst instanceof Type) { - Type type = (Type) cst; + if (cst instanceof Type type) { Reference reference = ReferenceExtractor.this.addTypeReference(type, IReference.REF_CONSTANTPOOL); if (reference != null) { this.linePositionTracker.addLocation(reference); } - } else if (cst instanceof String) { - String str = (String) cst; + } else if (cst instanceof String str) { this.stringLiteral = (Util.EMPTY_STRING.equals(str) ? null : str); } } @@ -762,15 +759,13 @@ public void computeLineNumbers() { remainingCatchLabelInfos = remaingEntriesTemp; } } - } else if (current instanceof Reference) { - Reference ref = (Reference) current; + } else if (current instanceof Reference ref) { if (ref.getLineNumber() == -1) { ref.setLineNumber(currentLineNumber); } else { currentLineNumber = ref.getLineNumber(); } - } else if (current instanceof LineInfo) { - LineInfo lineInfo = (LineInfo) current; + } else if (current instanceof LineInfo lineInfo) { currentLineNumber = lineInfo.line; } } @@ -810,8 +805,7 @@ public int compareTo(Object o) { @Override public boolean equals(Object obj) { - if (obj instanceof LineInfo) { - LineInfo lineInfo2 = (LineInfo) obj; + if (obj instanceof LineInfo lineInfo2) { return this.line == lineInfo2.line && this.label.equals(lineInfo2.label); } return super.equals(obj); @@ -841,8 +835,7 @@ public LocalLineNumberMarker(int line, int varIndex) { @Override public boolean equals(Object obj) { - if (obj instanceof LocalLineNumberMarker) { - LocalLineNumberMarker marker = (LocalLineNumberMarker) obj; + if (obj instanceof LocalLineNumberMarker marker) { return this.lineNumber == marker.lineNumber && this.varIndex == marker.varIndex; } return false; diff --git a/apitools/org.eclipse.pde.api.tools/src/org/eclipse/pde/api/tools/internal/builder/SystemApiDetector.java b/apitools/org.eclipse.pde.api.tools/src/org/eclipse/pde/api/tools/internal/builder/SystemApiDetector.java index ded068a580a..c4e7fba1f33 100644 --- a/apitools/org.eclipse.pde.api.tools/src/org/eclipse/pde/api/tools/internal/builder/SystemApiDetector.java +++ b/apitools/org.eclipse.pde.api.tools/src/org/eclipse/pde/api/tools/internal/builder/SystemApiDetector.java @@ -393,8 +393,7 @@ public List createProblems(IProgressMonitor monitor) { try { IApiProblem problem = null; IApiComponent component = reference.getMember().getApiComponent(); - if (component instanceof ProjectComponent) { - ProjectComponent ppac = (ProjectComponent) component; + if (component instanceof ProjectComponent ppac) { IJavaProject project = ppac.getJavaProject(); problem = createProblem(reference, project); } else { diff --git a/apitools/org.eclipse.pde.api.tools/src/org/eclipse/pde/api/tools/internal/builder/Validator.java b/apitools/org.eclipse.pde.api.tools/src/org/eclipse/pde/api/tools/internal/builder/Validator.java index 54a7fd2f400..01c71c0049a 100644 --- a/apitools/org.eclipse.pde.api.tools/src/org/eclipse/pde/api/tools/internal/builder/Validator.java +++ b/apitools/org.eclipse.pde.api.tools/src/org/eclipse/pde/api/tools/internal/builder/Validator.java @@ -210,8 +210,7 @@ protected int getParentModifiers(ASTNode node) { if (node == null) { return 0; } - if (node instanceof AbstractTypeDeclaration) { - AbstractTypeDeclaration type = (AbstractTypeDeclaration) node; + if (node instanceof AbstractTypeDeclaration type) { return type.getModifiers(); } return getParentModifiers(node.getParent()); diff --git a/apitools/org.eclipse.pde.api.tools/src/org/eclipse/pde/api/tools/internal/comparator/Delta.java b/apitools/org.eclipse.pde.api.tools/src/org/eclipse/pde/api/tools/internal/comparator/Delta.java index 1f6ea1fc533..ececc8a5de1 100644 --- a/apitools/org.eclipse.pde.api.tools/src/org/eclipse/pde/api/tools/internal/comparator/Delta.java +++ b/apitools/org.eclipse.pde.api.tools/src/org/eclipse/pde/api/tools/internal/comparator/Delta.java @@ -187,10 +187,9 @@ public boolean equals(Object obj) { if (obj == null) { return false; } - if (!(obj instanceof Delta)) { + if (!(obj instanceof Delta other)) { return false; } - Delta other = (Delta) obj; if (this.elementType != other.elementType) { return false; } diff --git a/apitools/org.eclipse.pde.api.tools/src/org/eclipse/pde/api/tools/internal/descriptors/FieldDescriptorImpl.java b/apitools/org.eclipse.pde.api.tools/src/org/eclipse/pde/api/tools/internal/descriptors/FieldDescriptorImpl.java index 4a22fc67316..0981d2e6eff 100644 --- a/apitools/org.eclipse.pde.api.tools/src/org/eclipse/pde/api/tools/internal/descriptors/FieldDescriptorImpl.java +++ b/apitools/org.eclipse.pde.api.tools/src/org/eclipse/pde/api/tools/internal/descriptors/FieldDescriptorImpl.java @@ -46,8 +46,7 @@ public String toString() { @Override public boolean equals(Object obj) { - if (obj instanceof IFieldDescriptor) { - IFieldDescriptor field = (IFieldDescriptor) obj; + if (obj instanceof IFieldDescriptor field) { return getName().equals(field.getName()) && getEnclosingType().equals(field.getEnclosingType()); } return false; diff --git a/apitools/org.eclipse.pde.api.tools/src/org/eclipse/pde/api/tools/internal/descriptors/MethodDescriptorImpl.java b/apitools/org.eclipse.pde.api.tools/src/org/eclipse/pde/api/tools/internal/descriptors/MethodDescriptorImpl.java index ca63d0e8a67..7ce2b4743c8 100644 --- a/apitools/org.eclipse.pde.api.tools/src/org/eclipse/pde/api/tools/internal/descriptors/MethodDescriptorImpl.java +++ b/apitools/org.eclipse.pde.api.tools/src/org/eclipse/pde/api/tools/internal/descriptors/MethodDescriptorImpl.java @@ -53,8 +53,7 @@ public String toString() { @Override public boolean equals(Object obj) { - if (obj instanceof IMethodDescriptor) { - IMethodDescriptor method = (IMethodDescriptor) obj; + if (obj instanceof IMethodDescriptor method) { return getName().equals(method.getName()) && getEnclosingType().equals(method.getEnclosingType()) && getSignature().equals(method.getSignature()); } return false; diff --git a/apitools/org.eclipse.pde.api.tools/src/org/eclipse/pde/api/tools/internal/descriptors/PackageDescriptorImpl.java b/apitools/org.eclipse.pde.api.tools/src/org/eclipse/pde/api/tools/internal/descriptors/PackageDescriptorImpl.java index d1954a1072c..91865439702 100644 --- a/apitools/org.eclipse.pde.api.tools/src/org/eclipse/pde/api/tools/internal/descriptors/PackageDescriptorImpl.java +++ b/apitools/org.eclipse.pde.api.tools/src/org/eclipse/pde/api/tools/internal/descriptors/PackageDescriptorImpl.java @@ -41,8 +41,7 @@ public String toString() { @Override public boolean equals(Object obj) { - if (obj instanceof IPackageDescriptor) { - IPackageDescriptor pkg = (IPackageDescriptor) obj; + if (obj instanceof IPackageDescriptor pkg) { return getName().equals(pkg.getName()); } return false; diff --git a/apitools/org.eclipse.pde.api.tools/src/org/eclipse/pde/api/tools/internal/descriptors/ReferenceTypeDescriptorImpl.java b/apitools/org.eclipse.pde.api.tools/src/org/eclipse/pde/api/tools/internal/descriptors/ReferenceTypeDescriptorImpl.java index 1322d4bf50b..79b661b20ea 100644 --- a/apitools/org.eclipse.pde.api.tools/src/org/eclipse/pde/api/tools/internal/descriptors/ReferenceTypeDescriptorImpl.java +++ b/apitools/org.eclipse.pde.api.tools/src/org/eclipse/pde/api/tools/internal/descriptors/ReferenceTypeDescriptorImpl.java @@ -118,8 +118,7 @@ public synchronized String getQualifiedName() { @Override public boolean equals(Object obj) { - if (obj instanceof IReferenceTypeDescriptor) { - IReferenceTypeDescriptor refType = (IReferenceTypeDescriptor) obj; + if (obj instanceof IReferenceTypeDescriptor refType) { return getQualifiedName().equals(refType.getQualifiedName()); } return false; diff --git a/apitools/org.eclipse.pde.api.tools/src/org/eclipse/pde/api/tools/internal/model/ApiBaseline.java b/apitools/org.eclipse.pde.api.tools/src/org/eclipse/pde/api/tools/internal/model/ApiBaseline.java index 45170bc9d2f..b525cfc08c1 100644 --- a/apitools/org.eclipse.pde.api.tools/src/org/eclipse/pde/api/tools/internal/model/ApiBaseline.java +++ b/apitools/org.eclipse.pde.api.tools/src/org/eclipse/pde/api/tools/internal/model/ApiBaseline.java @@ -396,8 +396,7 @@ protected void addComponent(IApiComponent component) { } fComponentsById.put(component.getSymbolicName(), component); - if (component instanceof ProjectComponent) { - ProjectComponent projectApiComponent = (ProjectComponent) component; + if (component instanceof ProjectComponent projectApiComponent) { if (this.fComponentsByProjectNames == null) { this.fComponentsByProjectNames = new HashMap<>(); } @@ -805,8 +804,7 @@ public void setName(String name) { @Override public boolean equals(Object obj) { - if (obj instanceof IApiBaseline) { - IApiBaseline baseline = (IApiBaseline) obj; + if (obj instanceof IApiBaseline baseline) { return this.getName().equals(baseline.getName()); } return super.equals(obj); diff --git a/apitools/org.eclipse.pde.api.tools/src/org/eclipse/pde/api/tools/internal/model/ApiMember.java b/apitools/org.eclipse.pde.api.tools/src/org/eclipse/pde/api/tools/internal/model/ApiMember.java index e5a5e6dc6b9..74528182329 100644 --- a/apitools/org.eclipse.pde.api.tools/src/org/eclipse/pde/api/tools/internal/model/ApiMember.java +++ b/apitools/org.eclipse.pde.api.tools/src/org/eclipse/pde/api/tools/internal/model/ApiMember.java @@ -99,8 +99,7 @@ public String getPackageName() { @Override public boolean equals(Object obj) { - if (obj instanceof IApiElement) { - IApiElement element = (IApiElement) obj; + if (obj instanceof IApiElement element) { if (element.getType() == this.getType()) { return enclosingTypesEqual(this, element) && getName().equals(element.getName()); } diff --git a/apitools/org.eclipse.pde.api.tools/src/org/eclipse/pde/api/tools/internal/model/ApiType.java b/apitools/org.eclipse.pde.api.tools/src/org/eclipse/pde/api/tools/internal/model/ApiType.java index f124b311657..bfea24f05ae 100644 --- a/apitools/org.eclipse.pde.api.tools/src/org/eclipse/pde/api/tools/internal/model/ApiType.java +++ b/apitools/org.eclipse.pde.api.tools/src/org/eclipse/pde/api/tools/internal/model/ApiType.java @@ -321,8 +321,7 @@ private void reOrganizeComponents(IApiComponent[] components) throws CoreExcepti if (javaEE != null) { for (int i = 0; i < components.length; i++) { IApiComponent iComponent = components[i]; - if (iComponent instanceof SystemLibraryApiComponent) { - SystemLibraryApiComponent sysCom = (SystemLibraryApiComponent) iComponent; + if (iComponent instanceof SystemLibraryApiComponent sysCom) { if (sysCom.getSymbolicName().equals(javaEE)) { // swap i and 0; IApiComponent temp = components[i]; @@ -495,8 +494,7 @@ public IMemberDescriptor getHandle() { @Override public boolean equals(Object obj) { - if (obj instanceof IApiType) { - IApiType type = (IApiType) obj; + if (obj instanceof IApiType type) { if (getApiComponent() == null) { return type.getApiComponent() == null && getName().equals(type.getName()); } diff --git a/apitools/org.eclipse.pde.api.tools/src/org/eclipse/pde/api/tools/internal/model/ArchiveApiTypeContainer.java b/apitools/org.eclipse.pde.api.tools/src/org/eclipse/pde/api/tools/internal/model/ArchiveApiTypeContainer.java index 42732186ea7..6bb37240aec 100644 --- a/apitools/org.eclipse.pde.api.tools/src/org/eclipse/pde/api/tools/internal/model/ArchiveApiTypeContainer.java +++ b/apitools/org.eclipse.pde.api.tools/src/org/eclipse/pde/api/tools/internal/model/ArchiveApiTypeContainer.java @@ -81,8 +81,7 @@ public int compareTo(Object o) { @Override public boolean equals(Object obj) { - if (obj instanceof ArchiveApiTypeRoot) { - ArchiveApiTypeRoot classFile = (ArchiveApiTypeRoot) obj; + if (obj instanceof ArchiveApiTypeRoot classFile) { return this.getName().equals(classFile.getName()); } return false; diff --git a/apitools/org.eclipse.pde.api.tools/src/org/eclipse/pde/api/tools/internal/model/BundleComponent.java b/apitools/org.eclipse.pde.api.tools/src/org/eclipse/pde/api/tools/internal/model/BundleComponent.java index b837c68809b..d9a462fb164 100644 --- a/apitools/org.eclipse.pde.api.tools/src/org/eclipse/pde/api/tools/internal/model/BundleComponent.java +++ b/apitools/org.eclipse.pde.api.tools/src/org/eclipse/pde/api/tools/internal/model/BundleComponent.java @@ -260,8 +260,7 @@ public boolean isValidBundle() throws CoreException { @Override public boolean equals(Object obj) { - if (obj instanceof BundleComponent) { - BundleComponent comp = (BundleComponent) obj; + if (obj instanceof BundleComponent comp) { return getName().equals(comp.getName()) && getSymbolicName().equals(comp.getSymbolicName()) && getVersion().equals(comp.getVersion()); } return false; diff --git a/apitools/org.eclipse.pde.api.tools/src/org/eclipse/pde/api/tools/internal/model/MethodKey.java b/apitools/org.eclipse.pde.api.tools/src/org/eclipse/pde/api/tools/internal/model/MethodKey.java index 8c00687ed1d..5994c89ba9d 100644 --- a/apitools/org.eclipse.pde.api.tools/src/org/eclipse/pde/api/tools/internal/model/MethodKey.java +++ b/apitools/org.eclipse.pde.api.tools/src/org/eclipse/pde/api/tools/internal/model/MethodKey.java @@ -44,8 +44,7 @@ public MethodKey(String typename, String name, String sig, boolean considertypen @Override public boolean equals(Object obj) { - if (obj instanceof MethodKey) { - MethodKey key = (MethodKey) obj; + if (obj instanceof MethodKey key) { return fSelector.equals(key.fSelector) && signaturesEqual(fSig, key.fSig) && (fConsiderTypename ? fTypename.equals(key.fTypename) : true); } return false; diff --git a/apitools/org.eclipse.pde.api.tools/src/org/eclipse/pde/api/tools/internal/model/ResourceApiTypeRoot.java b/apitools/org.eclipse.pde.api.tools/src/org/eclipse/pde/api/tools/internal/model/ResourceApiTypeRoot.java index af7a190d554..fcc8e9e0d26 100644 --- a/apitools/org.eclipse.pde.api.tools/src/org/eclipse/pde/api/tools/internal/model/ResourceApiTypeRoot.java +++ b/apitools/org.eclipse.pde.api.tools/src/org/eclipse/pde/api/tools/internal/model/ResourceApiTypeRoot.java @@ -96,8 +96,7 @@ public int hashCode() { @Override public boolean equals(Object obj) { - if (obj instanceof IApiTypeRoot) { - IApiTypeRoot file = (IApiTypeRoot) obj; + if (obj instanceof IApiTypeRoot file) { return getName().equals(file.getTypeName()); } return super.equals(obj); diff --git a/apitools/org.eclipse.pde.api.tools/src/org/eclipse/pde/api/tools/internal/model/StubArchiveApiTypeContainer.java b/apitools/org.eclipse.pde.api.tools/src/org/eclipse/pde/api/tools/internal/model/StubArchiveApiTypeContainer.java index f609a3d8e9b..1c0062e8111 100644 --- a/apitools/org.eclipse.pde.api.tools/src/org/eclipse/pde/api/tools/internal/model/StubArchiveApiTypeContainer.java +++ b/apitools/org.eclipse.pde.api.tools/src/org/eclipse/pde/api/tools/internal/model/StubArchiveApiTypeContainer.java @@ -79,8 +79,7 @@ public int compareTo(Object o) { @Override public boolean equals(Object obj) { - if (obj instanceof ArchiveApiTypeRoot) { - ArchiveApiTypeRoot classFile = (ArchiveApiTypeRoot) obj; + if (obj instanceof ArchiveApiTypeRoot classFile) { return this.getName().equals(classFile.getName()); } return false; diff --git a/apitools/org.eclipse.pde.api.tools/src/org/eclipse/pde/api/tools/internal/model/TypeStructureBuilder.java b/apitools/org.eclipse.pde.api.tools/src/org/eclipse/pde/api/tools/internal/model/TypeStructureBuilder.java index b492b6c19d9..c4d5523c02d 100644 --- a/apitools/org.eclipse.pde.api.tools/src/org/eclipse/pde/api/tools/internal/model/TypeStructureBuilder.java +++ b/apitools/org.eclipse.pde.api.tools/src/org/eclipse/pde/api/tools/internal/model/TypeStructureBuilder.java @@ -282,8 +282,7 @@ public static IApiType buildTypeStructure(byte[] bytes, IApiComponent component, */ public static void setEnclosingMethod(IApiType enclosingType, ApiType currentAnonymousLocalType) { IApiTypeRoot typeRoot = enclosingType.getTypeRoot(); - if (typeRoot instanceof AbstractApiTypeRoot) { - AbstractApiTypeRoot abstractApiTypeRoot = (AbstractApiTypeRoot) typeRoot; + if (typeRoot instanceof AbstractApiTypeRoot abstractApiTypeRoot) { EnclosingMethodSetter visitor = new EnclosingMethodSetter(new ClassNode(), currentAnonymousLocalType.getName()); try { ClassReader classReader = new ClassReader(abstractApiTypeRoot.getContents()); diff --git a/apitools/org.eclipse.pde.api.tools/src/org/eclipse/pde/api/tools/internal/problems/ApiProblem.java b/apitools/org.eclipse.pde.api.tools/src/org/eclipse/pde/api/tools/internal/problems/ApiProblem.java index 977841be7ba..c189f0d1047 100644 --- a/apitools/org.eclipse.pde.api.tools/src/org/eclipse/pde/api/tools/internal/problems/ApiProblem.java +++ b/apitools/org.eclipse.pde.api.tools/src/org/eclipse/pde/api/tools/internal/problems/ApiProblem.java @@ -209,8 +209,7 @@ public String[] getMessageArguments() { @Override public boolean equals(Object obj) { - if (obj instanceof IApiProblem) { - IApiProblem problem = (IApiProblem) obj; + if (obj instanceof IApiProblem problem) { if (problem.getId() == fId && argumentsEqual(problem.getMessageArguments())) { String resourcePath = problem.getResourcePath(); if (resourcePath == null) { diff --git a/apitools/org.eclipse.pde.api.tools/src/org/eclipse/pde/api/tools/internal/problems/ApiProblemFilter.java b/apitools/org.eclipse.pde.api.tools/src/org/eclipse/pde/api/tools/internal/problems/ApiProblemFilter.java index e70706048d7..97da369e9f9 100644 --- a/apitools/org.eclipse.pde.api.tools/src/org/eclipse/pde/api/tools/internal/problems/ApiProblemFilter.java +++ b/apitools/org.eclipse.pde.api.tools/src/org/eclipse/pde/api/tools/internal/problems/ApiProblemFilter.java @@ -68,8 +68,7 @@ public String getComponentId() { @Override public boolean equals(Object obj) { - if (obj instanceof IApiProblemFilter) { - IApiProblemFilter filter = (IApiProblemFilter) obj; + if (obj instanceof IApiProblemFilter filter) { return elementsEqual(filter.getComponentId(), fComponentId) && filter.getUnderlyingProblem().equals(fProblem); } else if (obj instanceof IApiProblem) { return fProblem.equals(obj); diff --git a/apitools/org.eclipse.pde.api.tools/src/org/eclipse/pde/api/tools/internal/provisional/scanner/TagScanner.java b/apitools/org.eclipse.pde.api.tools/src/org/eclipse/pde/api/tools/internal/provisional/scanner/TagScanner.java index a976b3a3392..55094446bc9 100644 --- a/apitools/org.eclipse.pde.api.tools/src/org/eclipse/pde/api/tools/internal/provisional/scanner/TagScanner.java +++ b/apitools/org.eclipse.pde.api.tools/src/org/eclipse/pde/api/tools/internal/provisional/scanner/TagScanner.java @@ -245,8 +245,7 @@ void scanMethodAnnotation(String name, MethodDeclaration node) { if (JavadocTagManager.ANNOTATION_NOOVERRIDE.equals(name)) { if (!Flags.isFinal(node.getModifiers()) && !Flags.isStatic(node.getModifiers())) { ASTNode parent = node.getParent(); - if (parent instanceof TypeDeclaration) { - TypeDeclaration type = (TypeDeclaration) parent; + if (parent instanceof TypeDeclaration type) { if (type.isInterface()) { if (Flags.isDefaultMethod(node.getModifiers())) { restrictions |= RestrictionModifiers.NO_OVERRIDE; @@ -480,8 +479,7 @@ public boolean visit(PackageDeclaration node) { public boolean visit(MethodDeclaration node) { if (isNotVisible(node.getModifiers())) { ASTNode parent = node.getParent(); - if (parent instanceof TypeDeclaration) { - TypeDeclaration type = (TypeDeclaration) parent; + if (parent instanceof TypeDeclaration type) { if (!type.isInterface()) { return false; } @@ -532,8 +530,7 @@ void scanMethodJavaDoc(MethodDeclaration node) { continue; } ASTNode parent = node.getParent(); - if (parent instanceof TypeDeclaration) { - TypeDeclaration type = (TypeDeclaration) parent; + if (parent instanceof TypeDeclaration type) { if (type.isInterface()) { if (Flags.isDefaultMethod(node.getModifiers())) { restrictions |= RestrictionModifiers.NO_OVERRIDE; diff --git a/apitools/org.eclipse.pde.api.tools/src/org/eclipse/pde/api/tools/internal/search/ConsumerReportConvertor.java b/apitools/org.eclipse.pde.api.tools/src/org/eclipse/pde/api/tools/internal/search/ConsumerReportConvertor.java index 30c604f9d4b..0c3177cec88 100644 --- a/apitools/org.eclipse.pde.api.tools/src/org/eclipse/pde/api/tools/internal/search/ConsumerReportConvertor.java +++ b/apitools/org.eclipse.pde.api.tools/src/org/eclipse/pde/api/tools/internal/search/ConsumerReportConvertor.java @@ -512,8 +512,7 @@ protected void writeIndexPage(List scanResult) throws Exception { File refereehtml = null; String link = null; for (Object obj : scanResult) { - if (obj instanceof Consumer) { - Consumer consumer = (Consumer) obj; + if (obj instanceof Consumer consumer) { refereehtml = new File(getReportsRoot(), consumer.name + File.separator + "index.html"); //$NON-NLS-1$ link = extractLinkFrom(getReportsRoot(), refereehtml.getAbsolutePath()); buffer.append(getReferenceTableEntry(consumer.counts, link, consumer.name, true)); diff --git a/apitools/org.eclipse.pde.api.tools/src/org/eclipse/pde/api/tools/internal/search/MissingRefReportConverter.java b/apitools/org.eclipse.pde.api.tools/src/org/eclipse/pde/api/tools/internal/search/MissingRefReportConverter.java index 85a55ef010c..da746312edc 100644 --- a/apitools/org.eclipse.pde.api.tools/src/org/eclipse/pde/api/tools/internal/search/MissingRefReportConverter.java +++ b/apitools/org.eclipse.pde.api.tools/src/org/eclipse/pde/api/tools/internal/search/MissingRefReportConverter.java @@ -374,8 +374,7 @@ protected void writeIndexPage(List result) throws Exception { buffer.append(getProblemSummaryTable()); if (result.size() > 0) { for (Object obj : result) { - if (obj instanceof Report) { - Report report = (Report) obj; + if (obj instanceof Report report) { File refereehtml = new File(getReportsRoot(), report.name + File.separator + "index.html"); //$NON-NLS-1$ String link = extractLinkFrom(getReportsRoot(), refereehtml.getAbsolutePath()); buffer.append(getReferenceTableEntry(report, link)); diff --git a/apitools/org.eclipse.pde.api.tools/src/org/eclipse/pde/api/tools/internal/search/ReferenceDescriptor.java b/apitools/org.eclipse.pde.api.tools/src/org/eclipse/pde/api/tools/internal/search/ReferenceDescriptor.java index 879df3943dd..d4c990ad703 100644 --- a/apitools/org.eclipse.pde.api.tools/src/org/eclipse/pde/api/tools/internal/search/ReferenceDescriptor.java +++ b/apitools/org.eclipse.pde.api.tools/src/org/eclipse/pde/api/tools/internal/search/ReferenceDescriptor.java @@ -48,8 +48,7 @@ public ReferenceDescriptor(IComponentDescriptor from, IMemberDescriptor origin, @Override public boolean equals(Object obj) { - if (obj instanceof ReferenceDescriptor) { - ReferenceDescriptor rd = (ReferenceDescriptor) obj; + if (obj instanceof ReferenceDescriptor rd) { return origin.equals(rd.origin) && target.equals(rd.target) && from.equals(rd.from) && to.equals(rd.to) && line == rd.line && kind == rd.kind && visibility == rd.visibility; } return false; diff --git a/apitools/org.eclipse.pde.api.tools/src/org/eclipse/pde/api/tools/internal/search/UseReportConverter.java b/apitools/org.eclipse.pde.api.tools/src/org/eclipse/pde/api/tools/internal/search/UseReportConverter.java index a1ec2ebd4d1..549b0a830d6 100644 --- a/apitools/org.eclipse.pde.api.tools/src/org/eclipse/pde/api/tools/internal/search/UseReportConverter.java +++ b/apitools/org.eclipse.pde.api.tools/src/org/eclipse/pde/api/tools/internal/search/UseReportConverter.java @@ -1463,8 +1463,7 @@ protected void writeIndexPage(List scanResult) throws Exception { File refereehtml = null; String link = null; for (Object obj : scanResult) { - if (obj instanceof Report) { - Report report = (Report) obj; + if (obj instanceof Report report) { refereehtml = new File(getReportsRoot(), report.name + File.separator + "index.html"); //$NON-NLS-1$ link = extractLinkFrom(getReportsRoot(), refereehtml.getAbsolutePath()); buffer.append(getReferenceTableEntry(report.counts, link, report.name, true)); diff --git a/apitools/org.eclipse.pde.api.tools/src/org/eclipse/pde/api/tools/internal/util/Signatures.java b/apitools/org.eclipse.pde.api.tools/src/org/eclipse/pde/api/tools/internal/util/Signatures.java index 573b211b910..065c9a83de9 100644 --- a/apitools/org.eclipse.pde.api.tools/src/org/eclipse/pde/api/tools/internal/util/Signatures.java +++ b/apitools/org.eclipse.pde.api.tools/src/org/eclipse/pde/api/tools/internal/util/Signatures.java @@ -795,8 +795,7 @@ static void collectSyntheticParam(final MethodDeclaration method, List r } continue; } - if (parent instanceof CompilationUnit) { - CompilationUnit cunit = (CompilationUnit) parent; + if (parent instanceof CompilationUnit cunit) { PackageDeclaration pdec = cunit.getPackage(); if (pdec != null) { name.insert(0, '.'); diff --git a/apitools/org.eclipse.pde.api.tools/src/org/eclipse/pde/api/tools/internal/util/Util.java b/apitools/org.eclipse.pde.api.tools/src/org/eclipse/pde/api/tools/internal/util/Util.java index 83c5e485ffe..849b0c6c55b 100644 --- a/apitools/org.eclipse.pde.api.tools/src/org/eclipse/pde/api/tools/internal/util/Util.java +++ b/apitools/org.eclipse.pde.api.tools/src/org/eclipse/pde/api/tools/internal/util/Util.java @@ -261,8 +261,7 @@ protected IStatus run(IProgressMonitor monitor) { private void cancelBuild(Object jobfamily) { Job[] buildJobs = Job.getJobManager().find(jobfamily); for (Job curr : buildJobs) { - if (curr != this && curr instanceof BuildJob) { - BuildJob job = (BuildJob) curr; + if (curr != this && curr instanceof BuildJob job) { if (job.isCoveredBy(this)) { curr.cancel(); // cancel all other build jobs of our // kind @@ -1198,12 +1197,10 @@ public static IType updateType(String typeName, IJavaProject javaProject) throws IPath path = IPath.fromOSString(typeNameWithSeparator); IPath pathExceptLastSegment = path.removeLastSegments(1); IJavaElement packFrag = javaProject.findElement(pathExceptLastSegment, DefaultWorkingCopyOwner.PRIMARY); - if (packFrag instanceof PackageFragment) { - PackageFragment pf = (PackageFragment) packFrag; + if (packFrag instanceof PackageFragment pf) { List children = pf.getChildrenOfType(IJavaElement.COMPILATION_UNIT); for (JavaElement object : children) { - if (object instanceof CompilationUnit) { - CompilationUnit compilationUn = (CompilationUnit) object; + if (object instanceof CompilationUnit compilationUn) { ITypeRoot typeRoot = compilationUn.getTypeRoot(); if (typeRoot.findPrimaryType() == null) { continue; @@ -1216,8 +1213,7 @@ public static IType updateType(String typeName, IJavaProject javaProject) throws } List children2 = pf.getChildrenOfType(IJavaElement.CLASS_FILE); for (JavaElement object : children2) { - if (object instanceof ClassFile) { - ClassFile compilationUn = (ClassFile) object; + if (object instanceof ClassFile compilationUn) { ITypeRoot typeRoot = compilationUn.getTypeRoot(); if (typeRoot.findPrimaryType() == null) { continue; @@ -1251,8 +1247,7 @@ public static IType getTypeInSameJavaProject(IType type, String typeName, IJavaP IJavaElement ancestor = type.getAncestor(IJavaElement.JAVA_PROJECT); IType newType = null; try { - if (ancestor instanceof IJavaProject) { - IJavaProject pro = (IJavaProject) ancestor; + if (ancestor instanceof IJavaProject pro) { if (!pro.equals(javaProject)) { newType = updateType(typeName, javaProject); if (newType != null) { @@ -2853,8 +2848,7 @@ public static IType findSourceTypeinJavaProject(IJavaProject javaProject, String IType type = null; try { String pkgName = typeName.substring(0, typeName.lastIndexOf('.')); - if (javaProject instanceof JavaProject) { - JavaProject jp = (JavaProject) javaProject; + if (javaProject instanceof JavaProject jp) { NameLookup newNameLookup = null; try { newNameLookup = jp.newNameLookup(DefaultWorkingCopyOwner.PRIMARY); From 24e9bb548b0de8c8ea79ee70d28096e28202da31 Mon Sep 17 00:00:00 2001 From: Hannes Wellmann Date: Wed, 12 Jul 2023 21:20:36 +0200 Subject: [PATCH 05/18] Enhance computation of system-package provided by a ExecutionEnvironment - In the Product or OSGi-app launch validation only consider EE of the VM that will run the app, match the later runtime-behavior - For the PDEState the EE's system-package is computed with the following distinction: - for a EE that corresponds to a Java-9 or higher release, get the 'best matching' VMInstall and query the system-packages for the EE's java release version (which is possible for modular JVMs) - for a Java-8 or lower release check if there is a VMInstall selected/strictly compatible to that version and query the system-packages from that VM (i.e. its rt.jar and other libraries) - if there is no VMInstall for a for a Java-8 or lower release, combine the hard-coded list of 'java.*' packages with the set of non-java packages provided by the default VMInstall of the workspace. The default VMInstall of the WS is at the same time the JVM selected in the active target definition (which sets its selection as WS default upon loading). - In general the available system-packages are only really known at runtime. Therefore at any other time, e.g. in the workspace, one can only guess/assume what packages are available and the implemented algorithm seems to be the best trade-off between probable accuracy, convenience and the possibility to let the user control the result. - Listen to changes of available VMInstalls and ExecutionEnvironment defaults. Re-read them on changes and re-resolve the PDE-State again with a subsequent re-validation of all Plugin projects. - Adapt existing test-cases that expected some packages to be reported as present although were not. Fixes https://github.com/eclipse-pde/eclipse.pde/issues/429 --- .../api/tools/internal/model/ApiBaseline.java | 13 +- .../pde/internal/build/site/PDEState.java | 206 ++++++++++++++++-- .../pde/internal/core/MinimalState.java | 98 ++++++++- .../internal/core/TargetPlatformHelper.java | 69 +----- .../launcher/LaunchValidationOperation.java | 26 +-- .../META-INF/MANIFEST.MF | 2 + .../classpath/ClasspathResolutionTest.java | 59 ++++- .../builders/BundleErrorReporterTest.java | 14 +- .../tests/ee/ExecutionEnvironmentTests.java | 4 +- .../target/TargetEnvironmentTestCase.java | 135 +++++++++--- 10 files changed, 469 insertions(+), 157 deletions(-) diff --git a/apitools/org.eclipse.pde.api.tools/src/org/eclipse/pde/api/tools/internal/model/ApiBaseline.java b/apitools/org.eclipse.pde.api.tools/src/org/eclipse/pde/api/tools/internal/model/ApiBaseline.java index b525cfc08c1..2ec53679e3f 100644 --- a/apitools/org.eclipse.pde.api.tools/src/org/eclipse/pde/api/tools/internal/model/ApiBaseline.java +++ b/apitools/org.eclipse.pde.api.tools/src/org/eclipse/pde/api/tools/internal/model/ApiBaseline.java @@ -1,5 +1,5 @@ /******************************************************************************* - * Copyright (c) 2007, 2022 IBM Corporation and others. + * Copyright (c) 2007, 2023 IBM Corporation and others. * * This program and the accompanying materials * are made available under the terms of the Eclipse Public License 2.0 @@ -290,14 +290,9 @@ public static Properties getJavaProfileProperties(String ee) { */ @SuppressWarnings("deprecation") private void initialize(Properties profile, ExecutionEnvironmentDescription description) throws CoreException { - String value = profile.getProperty(Constants.FRAMEWORK_SYSTEMPACKAGES); - if (value == null) { - // In Java-10 and beyond, we query system-packages list from the JRE - String environmentId = description.getProperty(ExecutionEnvironmentDescription.CLASS_LIB_LEVEL); - IExecutionEnvironmentsManager manager = JavaRuntime.getExecutionEnvironmentsManager(); - IExecutionEnvironment environment = manager.getEnvironment(environmentId); - value = TargetPlatformHelper.querySystemPackages(environment); - } + String environmentId = description.getProperty(ExecutionEnvironmentDescription.CLASS_LIB_LEVEL); + IExecutionEnvironment ee = JavaRuntime.getExecutionEnvironmentsManager().getEnvironment(environmentId); + String value = TargetPlatformHelper.getSystemPackages(ee, profile); String[] systemPackages = null; if (value != null) { systemPackages = value.split(","); //$NON-NLS-1$ diff --git a/build/org.eclipse.pde.build/src/org/eclipse/pde/internal/build/site/PDEState.java b/build/org.eclipse.pde.build/src/org/eclipse/pde/internal/build/site/PDEState.java index ad4468b34f2..4616c7b147e 100644 --- a/build/org.eclipse.pde.build/src/org/eclipse/pde/internal/build/site/PDEState.java +++ b/build/org.eclipse.pde.build/src/org/eclipse/pde/internal/build/site/PDEState.java @@ -1,5 +1,5 @@ /******************************************************************************* - * Copyright (c) 2004, 2021 IBM Corporation and others. + * Copyright (c) 2004, 2023 IBM Corporation and others. * * This program and the accompanying materials * are made available under the terms of the Eclipse Public License 2.0 @@ -10,6 +10,7 @@ * * Contributors: * IBM Corporation - initial API and implementation + * Hannes Wellmann - Enhance computation of system-package provided by a ExecutionEnvironment *******************************************************************************/ package org.eclipse.pde.internal.build.site; @@ -28,10 +29,14 @@ import java.util.Hashtable; import java.util.List; import java.util.Map; +import java.util.Optional; import java.util.Properties; import java.util.Set; import java.util.TreeSet; +import java.util.function.Function; import java.util.jar.JarFile; +import java.util.regex.Pattern; +import java.util.stream.Stream; import java.util.zip.ZipEntry; import java.util.zip.ZipFile; @@ -44,6 +49,7 @@ import org.eclipse.jdt.core.JavaCore; import org.eclipse.jdt.launching.IVMInstall; import org.eclipse.jdt.launching.JavaRuntime; +import org.eclipse.jdt.launching.LibraryLocation; import org.eclipse.jdt.launching.environments.IExecutionEnvironment; import org.eclipse.osgi.service.resolver.BundleDescription; import org.eclipse.osgi.service.resolver.ExportPackageDescription; @@ -388,7 +394,6 @@ public void resolveState() { // initialize profileManager and get the JRE profiles String[] javaProfiles = getJavaProfiles(); - String systemPackages = null; String ee = null; for (Config aConfig : configs) { @@ -435,7 +440,8 @@ public void resolveState() { if (profileProps != null) { String profileName = profileProps.getProperty(ProfileManager.PROFILE_NAME); if (AbstractScriptGenerator.getImmutableAntProperty(profileName) != null || (j == 0 && !added)) { - systemPackages = profileProps.getProperty(ProfileManager.SYSTEM_PACKAGES); + IExecutionEnvironment env = JavaRuntime.getExecutionEnvironmentsManager().getEnvironment(javaProfiles[j]); + String systemPackages = getSystemPackages(env, profileProps); ee = profileProps.getProperty(Constants.FRAMEWORK_EXECUTIONENVIRONMENT); prop = new Hashtable<>(); @@ -459,7 +465,7 @@ public void resolveState() { for (String execEnvID : eeJava10AndBeyond) { prop = new Hashtable<>(); IExecutionEnvironment env = JavaRuntime.getExecutionEnvironmentsManager().getEnvironment(execEnvID); - systemPackages = querySystemPackages(env); + String systemPackages = querySystemPackages(env, null); String currentEE = previousEE + "," + execEnvID; //$NON-NLS-1$ if (systemPackages == null) { previousEE = currentEE; @@ -480,13 +486,178 @@ public void resolveState() { } } - public static String querySystemPackages(IExecutionEnvironment environment) { - // Copy of org.eclipse.pde.internal.core.TargetPlatformHelper.querySystemPackages() - IVMInstall vm = bestVmInstallFor(environment); - if (vm == null || !JavaRuntime.isModularJava(vm)) { + public static String getSystemPackages(IExecutionEnvironment environment, Properties profileProperties) { + // The pre-defined lists of system-packages are incomplete. Always overwrite, if we have a more up-to-date one. + String systemPackages = querySystemPackages(environment, profileProperties); + if (systemPackages == null && profileProperties != null) { + // Unable to compute system-packages, probably OSGi specific EE, use the those its profile + systemPackages = profileProperties.getProperty(Constants.FRAMEWORK_SYSTEMPACKAGES); + } + return systemPackages; + } + + private static final Pattern COMMA = Pattern.compile(","); //$NON-NLS-1$ + + public static String querySystemPackages(IExecutionEnvironment environment, Properties preJava9ProfileProperties) { + if (environment == null) { + return null; + } + String eeId = environment.getId(); + Integer releaseVersion = readJavaReleaseVersion(eeId); + if (releaseVersion == null) { return null; } - String release = environment.getProfileProperties().getProperty(JavaCore.COMPILER_COMPLIANCE); + Collection systemPackages; + if (releaseVersion <= 8) { + IVMInstall eeVM = bestVmInstallFor(environment, vms -> null); // Use selected VM or a perfect match + if (eeVM != null) { + // In case a VM is selected for an EE, query that VM and use its system-packages + systemPackages = querySystemPackages(eeVM, null); + } else { + // No VM selected for the non-modular EE: + // Compose list of available system-packages from the java.* packages in the predefined profiles in o.e.osgi respectively the hard-coded lists of java-packages in this class + // plus the non-java packages of this workspace's default VM. + // The reasoning for this is, that the OSGi standard only requires the java.* packages of an EE to be present, everything else is optional. + // Therefore the Workspaces default VM (which can also be set as target VM in the active target-definition) is the best guess for them. + // See also OSGi 8.0 specification chapter 3.4 Execution Environment + + List javaPackages = PRE_JAVA_9_SYSTEM_PACKAGES.get(eeId); + if (javaPackages == null) { + String profileSystemPackages = preJava9ProfileProperties.getProperty(Constants.FRAMEWORK_SYSTEMPACKAGES, ""); //$NON-NLS-1$ + if (profileSystemPackages.isBlank()) { + return null; + } + javaPackages = COMMA.splitAsStream(profileSystemPackages).filter(p -> p.startsWith("java.")).toList(); //$NON-NLS-1$ + } + IVMInstall targetVM = JavaRuntime.getDefaultVMInstall(); // Set by the Target-Definition if specified there + Collection targetVMSystemPackages = querySystemPackages(targetVM, null); + if (targetVMSystemPackages == null) { + return null; + } + Stream targetVMNonJavaPackages = targetVMSystemPackages.stream().filter(p -> !p.startsWith("java.")); //$NON-NLS-1$ + + systemPackages = Stream.concat(javaPackages.stream(), targetVMNonJavaPackages).sorted().toList(); + } + } else { + IVMInstall vm = bestVmInstallFor(environment, vms -> vms[0]); + if (vm == null) { + return null; + } + systemPackages = querySystemPackages(vm, environment); + } + return String.join(",", systemPackages); //$NON-NLS-1$ + } + + @SuppressWarnings("nls") + private static Integer readJavaReleaseVersion(String eeId) { + if (eeId.startsWith("JavaSE-")) { //$NON-NLS-1$ + try { + return Integer.parseInt(eeId.substring("JavaSE-".length())); //$NON-NLS-1$ + } catch (NumberFormatException e) { // Another EE + } + } + return switch (eeId) { + // There is no EE for Java 1.0 in OSGi + case "JRE-1.1" -> 1; + case "J2SE-1.2" -> 2; + case "J2SE-1.3" -> 3; + case "J2SE-1.4" -> 4; + case "J2SE-1.5" -> 5; + case "JavaSE-1.6" -> 6; + case "JavaSE-1.7" -> 7; + case "JavaSE-1.8" -> 8; + default -> null; + }; + } + + // Old JDKs can for example be obtained from https://www.oracle.com/java/technologies/downloads/archive/ + @SuppressWarnings("nls") + private static final Map> PRE_JAVA_9_SYSTEM_PACKAGES = Map.of(// + "JRE-1.1", List.of("java.applet", // + "java.awt", // + "java.awt.datatransfer", // + "java.awt.event", // + "java.awt.image", // + "java.awt.peer", // + "java.beans", // + "java.io", // + "java.lang", // + "java.lang.reflect", // + "java.math", // + "java.net", // + "java.rmi", // + "java.rmi.dgc", // + "java.rmi.registry", // + "java.rmi.server", // + "java.security", // + "java.security.acl", // + "java.security.interfaces", // + "java.sql", // + "java.text", // + "java.text.resources", // + "java.util", // + "java.util.zip"), + "J2SE-1.2", List.of("java.applet", // + "java.awt", // + "java.awt.color", // + "java.awt.datatransfer", // + "java.awt.dnd", // + "java.awt.dnd.peer", // + "java.awt.event", // + "java.awt.font", // + "java.awt.geom", // + "java.awt.im", // + "java.awt.image", // + "java.awt.image.renderable", // + "java.awt.peer", // + "java.awt.print", // + "java.awt.resources", // + "java.beans", // + "java.beans.beancontext", // + "java.io", // + "java.lang", // + "java.lang.ref", // + "java.lang.reflect", // + "java.math", // + "java.net", // + "java.rmi", // + "java.rmi.activation", // + "java.rmi.dgc", // + "java.rmi.registry", // + "java.rmi.server", // + "java.security", // + "java.security.acl", // + "java.security.cert", // + "java.security.interfaces", // + "java.security.spec", // + "java.sql", // + "java.text", // + "java.text.resources", // + "java.util", // + "java.util.jar", // + "java.util.zip")); + + private static Collection querySystemPackages(IVMInstall vm, IExecutionEnvironment environment) { + if (!JavaRuntime.isModularJava(vm)) { + Set classFileDirectories = new HashSet<>(); + for (LibraryLocation libLocation : JavaRuntime.getLibraryLocations(vm)) { + IPath path = libLocation.getSystemLibraryPath(); + if (path != null) { + try (ZipFile zip = new ZipFile(path.toFile())) { + // Collect names of all directories that contain a .class file + zip.stream().filter(e -> !e.isDirectory()).map(ZipEntry::getName) // + .filter(n -> n.endsWith(".class")) //$NON-NLS-1$ + .map(n -> n.substring(0, n.lastIndexOf('/'))) // + .forEach(classFileDirectories::add); + } catch (IOException e) { + ILog.get().error("Failed to read packages in JVM library for " + vm + ", at " + path, e); //$NON-NLS-1$ //$NON-NLS-2$ + } + } + } + return classFileDirectories.stream().map(n -> n.replace('/', '.')).sorted().toList(); + } + + String release = environment != null ? environment.getProfileProperties().getProperty(JavaCore.COMPILER_COMPLIANCE) : null; try { Collection packages = new TreeSet<>(); String jrtPath = "lib/" + org.eclipse.jdt.internal.compiler.util.JRTUtil.JRT_FS_JAR; //$NON-NLS-1$ @@ -503,17 +674,14 @@ public static String querySystemPackages(IExecutionEnvironment environment) { } } } - return String.join(",", packages); //$NON-NLS-1$ + return packages; } catch (CoreException e) { - ILog.of(PDEState.class).log(Status.error("failed to read system packages for " + environment, e)); //$NON-NLS-1$ + ILog.of(PDEState.class).log(Status.error("Failed to read system packages for " + environment, e)); //$NON-NLS-1$ } return null; } - private static IVMInstall bestVmInstallFor(IExecutionEnvironment environment) { - if (environment == null) { - return null; - } + private static IVMInstall bestVmInstallFor(IExecutionEnvironment environment, Function nonStrictDefaultSelector) { IVMInstall defaultVM = environment.getDefaultVM(); if (defaultVM != null) { return defaultVM; @@ -522,12 +690,8 @@ private static IVMInstall bestVmInstallFor(IExecutionEnvironment environment) { if (compatible.length == 0) { return null; } - for (IVMInstall vm : compatible) { - if (environment.isStrictlyCompatible(vm)) { - return vm; - } - } - return compatible[0]; + Optional vm = Arrays.stream(compatible).filter(environment::isStrictlyCompatible).findFirst(); + return vm.isPresent() ? vm.get() : nonStrictDefaultSelector.apply(compatible); } public State getState() { diff --git a/ui/org.eclipse.pde.core/src/org/eclipse/pde/internal/core/MinimalState.java b/ui/org.eclipse.pde.core/src/org/eclipse/pde/internal/core/MinimalState.java index 296fe280405..c91bf2bbf32 100644 --- a/ui/org.eclipse.pde.core/src/org/eclipse/pde/internal/core/MinimalState.java +++ b/ui/org.eclipse.pde.core/src/org/eclipse/pde/internal/core/MinimalState.java @@ -1,5 +1,5 @@ /******************************************************************************* - * Copyright (c) 2005, 2021 IBM Corporation and others. + * Copyright (c) 2005, 2023 IBM Corporation and others. * * This program and the accompanying materials * are made available under the terms of the Eclipse Public License 2.0 @@ -11,6 +11,7 @@ * Contributors: * IBM Corporation - initial API and implementation * EclipseSource Corporation - ongoing enhancements + * Hannes Wellmann - Enhance computation of system-package provided by a ExecutionEnvironment *******************************************************************************/ package org.eclipse.pde.internal.core; @@ -22,15 +23,26 @@ import java.util.List; import java.util.Map; +import org.eclipse.core.resources.IProject; import org.eclipse.core.resources.IResource; +import org.eclipse.core.resources.IncrementalProjectBuilder; +import org.eclipse.core.resources.ResourcesPlugin; +import org.eclipse.core.resources.WorkspaceJob; import org.eclipse.core.runtime.CoreException; +import org.eclipse.core.runtime.IProgressMonitor; +import org.eclipse.core.runtime.IStatus; import org.eclipse.core.runtime.MultiStatus; import org.eclipse.core.runtime.Platform; import org.eclipse.core.runtime.Status; +import org.eclipse.core.runtime.jobs.Job; +import org.eclipse.core.runtime.preferences.IEclipsePreferences; +import org.eclipse.core.runtime.preferences.InstanceScope; import org.eclipse.jdt.core.IJavaProject; import org.eclipse.jdt.core.JavaCore; import org.eclipse.jdt.launching.IVMInstall; +import org.eclipse.jdt.launching.IVMInstallChangedListener; import org.eclipse.jdt.launching.JavaRuntime; +import org.eclipse.jdt.launching.PropertyChangeEvent; import org.eclipse.jdt.launching.environments.IExecutionEnvironment; import org.eclipse.osgi.service.resolver.BundleDescription; import org.eclipse.osgi.service.resolver.State; @@ -242,6 +254,88 @@ protected boolean initializePlatformProperties() { return false; } + static { + // Listen to changes in the available VMInstalls and + // ExecutionEnvironment defaults + @SuppressWarnings("restriction") + String nodeQualifier = org.eclipse.jdt.internal.launching.LaunchingPlugin.ID_PLUGIN; + IEclipsePreferences launchingNode = InstanceScope.INSTANCE.getNode(nodeQualifier); + launchingNode.addPreferenceChangeListener(e -> { + if (e.getKey().equals("org.eclipse.jdt.launching.PREF_DEFAULT_ENVIRONMENTS_XML")) { //$NON-NLS-1$ + Object oldValue = e.getOldValue() == null ? "" : e.getOldValue(); //$NON-NLS-1$ + Object newValue = e.getNewValue() == null ? "" : e.getNewValue(); //$NON-NLS-1$ + if (!oldValue.equals(newValue)) { + triggerSystemPackagesReload(); + } + } + }); + JavaRuntime.addVMInstallChangedListener(new IVMInstallChangedListener() { + @Override + public void vmRemoved(IVMInstall vm) { + triggerSystemPackagesReload(); + } + + @Override + public void vmChanged(PropertyChangeEvent event) { + triggerSystemPackagesReload(); + } + + @Override + public void vmAdded(IVMInstall vm) { + triggerSystemPackagesReload(); + } + + @Override + public void defaultVMInstallChanged(IVMInstall previous, IVMInstall current) { + triggerSystemPackagesReload(); + } + }); + } + private static final String PDE_MANIFEST_BUILDER = "org.eclipse.pde.ManifestBuilder"; //$NON-NLS-1$ + + public static void triggerSystemPackagesReload() { + final String jobFamily = "pde.internal.ReresolveStateAfterVMorEEchanges"; //$NON-NLS-1$ + Job.getJobManager().cancel(jobFamily); + WorkspaceJob job = new WorkspaceJob("Re-resolve Target state after VM-Install or EE change") { //$NON-NLS-1$ + @Override + public IStatus runInWorkspace(IProgressMonitor monitor) throws CoreException { + // The list of EEs has changed: re-read all available + // VM-installs/EEs and re-resolve state with new properties + return reloadSystemPackagesIntoState(); + } + + @Override + public boolean belongsTo(Object family) { + return jobFamily.equals(family); + } + }; + job.setRule(ResourcesPlugin.getWorkspace().getRoot()); + job.schedule(200); // Small delay to bulk-handle multiple changes + } + + // Visible for testing only + public static IStatus reloadSystemPackagesIntoState() { + MinimalState state = PDECore.getDefault().getModelManager().getState(); + if (state.fNoProfile) { + return Status.OK_STATUS; + } + state.fEEListChanged = true; + StateDelta delta = state.internalResolveState(true); + if (delta.getChanges().length == 0) { + return Status.OK_STATUS; + } + // Perform PDE-Manifest build, to re-validate all Manifests + MultiStatus status = new MultiStatus(MinimalState.class, 0, "Reload of JRE system-packages encountered issues"); //$NON-NLS-1$ + for (IProject project : ResourcesPlugin.getWorkspace().getRoot().getProjects()) { + try { + project.build(IncrementalProjectBuilder.FULL_BUILD, PDE_MANIFEST_BUILDER, null, null); + } catch (CoreException e) { // ignore + status.add(e.getStatus()); + } + } + return status; + } + public void removeBundleDescription(BundleDescription description) { if (description != null) { fState.removeBundle(description); @@ -269,7 +363,7 @@ private void setExecutionEnvironments() { if (!fNoProfile) { fExecutionEnvironments = knownExecutionEnviroments; } - fEEListChanged = true; // alway indicate the list has changed + fEEListChanged = true; // always indicate the list has changed } public void addBundleDescription(BundleDescription toAdd) { 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 949274f5af4..fe0784ae4b1 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, 2022 IBM Corporation and others. + * Copyright (c) 2000, 2023 IBM Corporation and others. * * This program and the accompanying materials * are made available under the terms of the Eclipse Public License 2.0 @@ -22,7 +22,6 @@ import java.nio.file.Files; import java.util.ArrayList; import java.util.Arrays; -import java.util.Collection; import java.util.Dictionary; import java.util.HashMap; import java.util.Hashtable; @@ -45,8 +44,6 @@ import org.eclipse.core.runtime.IProgressMonitor; import org.eclipse.core.runtime.Platform; import org.eclipse.core.runtime.Status; -import org.eclipse.jdt.core.JavaCore; -import org.eclipse.jdt.launching.IVMInstall; import org.eclipse.jdt.launching.JavaRuntime; import org.eclipse.jdt.launching.environments.IExecutionEnvironment; import org.eclipse.osgi.service.resolver.BundleDescription; @@ -354,14 +351,11 @@ public static Dictionary getTargetEnvironment(MinimalState state } @SuppressWarnings("unchecked") - public static Dictionary[] getPlatformProperties(String[] profiles, MinimalState state) { - if (profiles == null || profiles.length == 0) { - return new Dictionary[] { getTargetEnvironment(state) }; - } - + public static Dictionary[] getPlatformProperties(String[] profilesArr, MinimalState state) { + List profiles = profilesArr != null ? Arrays.asList(profilesArr) : List.of(); // add java profiles for those EE's that have a .profile file in the // current system bundle - List> result = new ArrayList<>(profiles.length); + List> result = new ArrayList<>(profiles.size()); for (String profile : profiles) { IExecutionEnvironment environment = JavaRuntime.getExecutionEnvironmentsManager().getEnvironment(profile); if (environment != null) { @@ -381,10 +375,7 @@ public static Dictionary[] getPlatformProperties(String[] profil public static void addEnvironmentProperties(Dictionary properties, IExecutionEnvironment environment, Properties profileProps) { - String systemPackages = profileProps.getProperty(Constants.FRAMEWORK_SYSTEMPACKAGES); - if (systemPackages == null) { // java 10 and beyond - systemPackages = querySystemPackages(environment); - } + String systemPackages = getSystemPackages(environment, profileProps); if (systemPackages != null) { properties.put(Constants.FRAMEWORK_SYSTEMPACKAGES, systemPackages); } @@ -396,54 +387,8 @@ public static void addEnvironmentProperties(Dictionary propertie } } - @SuppressWarnings("restriction") - public static String querySystemPackages(IExecutionEnvironment environment) { - IVMInstall vm = bestVmInstallFor(environment); - if (vm == null || !JavaRuntime.isModularJava(vm)) { - return null; - } - String release = environment.getProfileProperties().getProperty(JavaCore.COMPILER_COMPLIANCE); - try { - Collection packages = new TreeSet<>(); - String jrtPath = "lib/" + org.eclipse.jdt.internal.compiler.util.JRTUtil.JRT_FS_JAR; //$NON-NLS-1$ - String path = new File(vm.getInstallLocation(), jrtPath).toString(); // $NON-NLS-1$ - var jrt = org.eclipse.jdt.internal.core.builder.ClasspathLocation.forJrtSystem(path, null, null, release); - for (String moduleName : jrt.getModuleNames(null)) { - var module = jrt.getModule(moduleName); - if (module == null) { - continue; - } - for (var packageExport : module.exports()) { - if (!packageExport.isQualified()) { - packages.add(new String(packageExport.name())); - } - } - } - return String.join(",", packages); //$NON-NLS-1$ - } catch (CoreException e) { - PDECore.logException(e, "failed to read system packages for " + environment); //$NON-NLS-1$ - } - return null; - } - - private static IVMInstall bestVmInstallFor(IExecutionEnvironment environment) { - if (environment == null) { - return null; - } - IVMInstall defaultVM = environment.getDefaultVM(); - if (defaultVM != null) { - return defaultVM; - } - IVMInstall[] compatible = environment.getCompatibleVMs(); - if (compatible.length == 0) { - return null; - } - for (IVMInstall vm : compatible) { - if (environment.isStrictlyCompatible(vm)) { - return vm; - } - } - return compatible[0]; + public static String getSystemPackages(IExecutionEnvironment environment, Properties profileProperties) { + return org.eclipse.pde.internal.build.site.PDEState.getSystemPackages(environment, profileProperties); } public static String[] getKnownExecutionEnvironments() { diff --git a/ui/org.eclipse.pde.launching/src/org/eclipse/pde/internal/launching/launcher/LaunchValidationOperation.java b/ui/org.eclipse.pde.launching/src/org/eclipse/pde/internal/launching/launcher/LaunchValidationOperation.java index 58d6b1da974..2b94d65cb08 100644 --- a/ui/org.eclipse.pde.launching/src/org/eclipse/pde/internal/launching/launcher/LaunchValidationOperation.java +++ b/ui/org.eclipse.pde.launching/src/org/eclipse/pde/internal/launching/launcher/LaunchValidationOperation.java @@ -1,5 +1,5 @@ /******************************************************************************* - * Copyright (c) 2007, 2022 IBM Corporation and others. + * Copyright (c) 2007, 2023 IBM Corporation and others. * * This program and the accompanying materials * are made available under the terms of the Eclipse Public License 2.0 @@ -10,6 +10,7 @@ * * Contributors: * IBM Corporation - initial API and implementation + * Hannes Wellmann - Enhance computation of system-package provided by a ExecutionEnvironment *******************************************************************************/ package org.eclipse.pde.internal.launching.launcher; @@ -17,10 +18,8 @@ import java.io.FileInputStream; import java.io.IOException; import java.io.InputStream; -import java.util.ArrayList; import java.util.Arrays; import java.util.Dictionary; -import java.util.List; import java.util.Map; import java.util.Properties; import java.util.Set; @@ -60,27 +59,22 @@ public void run(IProgressMonitor monitor) throws CoreException { @SuppressWarnings("unchecked") protected Dictionary[] getPlatformProperties() throws CoreException { IExecutionEnvironment[] envs = getMatchingEnvironments(); - if (envs.length == 0) { - return new Dictionary[] {TargetPlatformHelper.getTargetEnvironment()}; - } - // add java profiles for those EE's that have a .profile file in the current system bundle - List> result = new ArrayList<>(envs.length); - for (IExecutionEnvironment env : envs) { + Dictionary environmentProperties = TargetPlatformHelper.getTargetEnvironment(); + // Only add the highest EE of the supplied VM, to match the runtime's behavior + for (int i = envs.length - 1; i > 0; i--) { + IExecutionEnvironment env = envs[i]; + // add java profiles for those EE's that have a .profile file in the current system bundle Properties profileProps = getJavaProfileProperties(env.getId()); if (profileProps == null) { // Java10 onwards, we take profile via this method profileProps = env.getProfileProperties(); } if (profileProps != null) { - Dictionary props = TargetPlatformHelper.getTargetEnvironment(); - TargetPlatformHelper.addEnvironmentProperties(props, env, profileProps); - result.add(props); + TargetPlatformHelper.addEnvironmentProperties(environmentProperties, env, profileProps); + break; } } - if (!result.isEmpty()) { - return result.toArray(Dictionary[]::new); - } - return new Dictionary[] {TargetPlatformHelper.getTargetEnvironment()}; + return new Dictionary[] {environmentProperties}; } protected IExecutionEnvironment[] getMatchingEnvironments() throws CoreException { diff --git a/ui/org.eclipse.pde.ui.tests/META-INF/MANIFEST.MF b/ui/org.eclipse.pde.ui.tests/META-INF/MANIFEST.MF index c30778eb329..67664663c23 100644 --- a/ui/org.eclipse.pde.ui.tests/META-INF/MANIFEST.MF +++ b/ui/org.eclipse.pde.ui.tests/META-INF/MANIFEST.MF @@ -53,6 +53,8 @@ Import-Package: javax.annotation;version="[1.3.0,2.0.0)", org.junit.runner, org.junit.runners, org.junit.runners.model, + org.mockito, + org.mockito.stubbing, org.osgi.service.event;version="[1.3.0,2.0.0)" Bundle-RequiredExecutionEnvironment: JavaSE-17 Eclipse-BundleShape: dir diff --git a/ui/org.eclipse.pde.ui.tests/src/org/eclipse/pde/core/tests/internal/classpath/ClasspathResolutionTest.java b/ui/org.eclipse.pde.ui.tests/src/org/eclipse/pde/core/tests/internal/classpath/ClasspathResolutionTest.java index 21326623e49..e89f03d6b94 100644 --- a/ui/org.eclipse.pde.ui.tests/src/org/eclipse/pde/core/tests/internal/classpath/ClasspathResolutionTest.java +++ b/ui/org.eclipse.pde.ui.tests/src/org/eclipse/pde/core/tests/internal/classpath/ClasspathResolutionTest.java @@ -1,5 +1,5 @@ /******************************************************************************* - * Copyright (c) 2020, 2021 Red Hat Inc. and others. + * Copyright (c) 2020, 2023 Red Hat Inc. and others. * * This program and the accompanying materials * are made available under the terms of the Eclipse Public License 2.0 @@ -19,6 +19,7 @@ import java.util.Arrays; import java.util.List; +import java.util.Properties; import java.util.Set; import java.util.function.Predicate; @@ -36,8 +37,10 @@ import org.eclipse.jdt.launching.JavaRuntime; import org.eclipse.jdt.launching.environments.IExecutionEnvironment; import org.eclipse.pde.core.plugin.IPluginModelBase; +import org.eclipse.pde.internal.core.MinimalState; import org.eclipse.pde.internal.core.PDECore; import org.eclipse.pde.internal.core.RequiredPluginsClasspathContainer; +import org.eclipse.pde.internal.core.TargetPlatformHelper; import org.eclipse.pde.ui.tests.util.ProjectUtils; import org.eclipse.pde.ui.tests.util.TargetPlatformUtil; import org.junit.BeforeClass; @@ -45,6 +48,7 @@ import org.junit.Rule; import org.junit.Test; import org.junit.rules.TestRule; +import org.mockito.Mockito; import org.osgi.framework.Bundle; import org.osgi.framework.FrameworkUtil; @@ -120,22 +124,27 @@ public void testImportExternalPreviouslySystemPackageAddsExtraBundle_missingBREE @Test public void testImportSystemPackageDoesntAddExtraBundleJava8() throws Exception { loadTargetPlatform(javaxAnnotationProviderBSN); - IProject project = ProjectUtils.importTestProject("tests/projects/demoMissedSystemPackageJava8"); - // In Java 8, javax.annotation is present, so the bundle must *NOT* be - // part of classpath - List classpathEntries = getRequiredPluginContainerEntries(project); - assertThat(classpathEntries).isEmpty(); + try (var mocked = mockExtraExtraJRESystemPackages("JavaSE-1.8", List.of("javax.annotation"))) { + IProject project = ProjectUtils.importTestProject("tests/projects/demoMissedSystemPackageJava8"); + // In Java 8, javax.annotation is present, so the bundle must *NOT* + // be part of classpath + List classpathEntries = getRequiredPluginContainerEntries(project); + assertThat(classpathEntries).isEmpty(); + } } @Test public void testImportSystemPackageDoesntAddExtraBundleJava8_osgiEERequirement() throws Exception { loadTargetPlatform(javaxAnnotationProviderBSN); - IProject project = ProjectUtils.importTestProject("tests/projects/demoMissedSystemPackageJava8OsgiEERequirement"); - // bundle is build with java 11, but declares java 8 requirement via - // Require-Capability - // --> javax.annotation bundle must not be on the classpath - List classpathEntries = getRequiredPluginContainerEntries(project); - assertThat(classpathEntries).isEmpty(); + try (var mocked = mockExtraExtraJRESystemPackages("JavaSE-1.8", List.of("javax.annotation"))) { + IProject project = ProjectUtils + .importTestProject("tests/projects/demoMissedSystemPackageJava8OsgiEERequirement"); + // bundle is build with java 11, but declares java 8 requirement via + // Require-Capability + // --> javax.annotation bundle must not be on the classpath + List classpathEntries = getRequiredPluginContainerEntries(project); + assertThat(classpathEntries).isEmpty(); + } } // --- utilitiy methods --- @@ -153,4 +162,30 @@ private void loadTargetPlatform(String bundleName) throws Exception { Predicate bundleFilter = b -> bundleNames.contains(b.getSymbolicName()); TargetPlatformUtil.setRunningPlatformSubSetAsTarget("Target containing " + bundleName, bundleFilter); } + + private AutoCloseable mockExtraExtraJRESystemPackages(String eeId, List extraPackages) { + // We want to test that the packages provided by a Java-1.8 VM are + // consumed from the VM and not from another bundle in the TP. + // Unfortunately we don't have a Java-1.8 VM in the CI, it is always a + // more recent one, but more recent ones don't contain the packages we + // want anymore. Therefore we have to mock the TP system-properties and + // pretend the desired package are contained in the VM for the purpose + // of this test. + + IExecutionEnvironment ee = JavaRuntime.getExecutionEnvironmentsManager().getEnvironment(eeId); + Properties profileProps = ee.getProfileProperties(); + String mockedSystemPackages = TargetPlatformHelper.getSystemPackages(ee, profileProps) + + "," + String.join(",", extraPackages); + + var mockedPDEState = Mockito.mockStatic(TargetPlatformHelper.class, Mockito.CALLS_REAL_METHODS); + mockedPDEState.when(() -> TargetPlatformHelper.getSystemPackages(ee, profileProps)) + .thenReturn(mockedSystemPackages); + // Beware that the static mock is thread-local! + MinimalState.reloadSystemPackagesIntoState(); + mockedPDEState.verify(() -> TargetPlatformHelper.getSystemPackages(ee, profileProps), Mockito.times(1)); + return () -> { + mockedPDEState.close(); + MinimalState.reloadSystemPackagesIntoState(); + }; + } } diff --git a/ui/org.eclipse.pde.ui.tests/src/org/eclipse/pde/core/tests/internal/core/builders/BundleErrorReporterTest.java b/ui/org.eclipse.pde.ui.tests/src/org/eclipse/pde/core/tests/internal/core/builders/BundleErrorReporterTest.java index 80fda47779e..ace955cf260 100644 --- a/ui/org.eclipse.pde.ui.tests/src/org/eclipse/pde/core/tests/internal/core/builders/BundleErrorReporterTest.java +++ b/ui/org.eclipse.pde.ui.tests/src/org/eclipse/pde/core/tests/internal/core/builders/BundleErrorReporterTest.java @@ -1,5 +1,5 @@ /******************************************************************************* - * Copyright (c) 2021 Julian Honnen + * Copyright (c) 2021, 2023 Julian Honnen * * This program and the accompanying materials * are made available under the terms of the Eclipse Public License 2.0 @@ -27,7 +27,6 @@ import org.eclipse.core.runtime.IProgressMonitor; import org.eclipse.jdt.launching.JavaRuntime; import org.eclipse.pde.core.IBaseModel; -import org.eclipse.pde.internal.core.builders.CompilerFlags; import org.eclipse.pde.internal.core.builders.PDEMarkerFactory; import org.eclipse.pde.internal.core.ibundle.IBundle; import org.eclipse.pde.internal.core.ibundle.IBundlePluginModelBase; @@ -52,7 +51,7 @@ public void setup() throws Exception { @Test public void testErrorOnUnresolvedJrePackage() throws Exception { IProject project = ProjectUtils.createPluginProject(manifest.getProject().getName(), - JavaRuntime.getExecutionEnvironmentsManager().getEnvironment("JavaSE-11")).getProject(); + JavaRuntime.getExecutionEnvironmentsManager().getEnvironment("JavaSE-1.8")).getProject(); IFile manifest = project.getFile("META-INF/MANIFEST.MF"); PDEModelUtility.modifyModel(new ModelModification(manifest) { @@ -60,7 +59,7 @@ public void testErrorOnUnresolvedJrePackage() throws Exception { protected void modifyModel(IBaseModel model, IProgressMonitor monitor) throws CoreException { IBundlePluginModelBase modelBase = (IBundlePluginModelBase) model; IBundle bundle = modelBase.getBundleModel().getBundle(); - bundle.setHeader(Constants.IMPORT_PACKAGE, "javax.xml.ws"); + bundle.setHeader(Constants.IMPORT_PACKAGE, "java.lang.module"); } }, null); @@ -72,7 +71,7 @@ protected void modifyModel(IBaseModel model, IProgressMonitor monitor) throws Co protected void modifyModel(IBaseModel model, IProgressMonitor monitor) throws CoreException { IBundlePluginModelBase modelBase = (IBundlePluginModelBase) model; IBundle bundle = modelBase.getBundleModel().getBundle(); - bundle.setHeader(Constants.BUNDLE_REQUIREDEXECUTIONENVIRONMENT, "JavaSE-1.8"); + bundle.setHeader(Constants.BUNDLE_REQUIREDEXECUTIONENVIRONMENT, "JavaSE-11"); } }; PDEModelUtility.modifyModel(modification, null); @@ -82,9 +81,8 @@ protected void modifyModel(IBaseModel model, IProgressMonitor monitor) throws Co private List findUnresolvedImportsMarkers() throws CoreException { manifest.getProject().build(IncrementalProjectBuilder.FULL_BUILD, null); - return Arrays.stream(manifest.findMarkers(PDEMarkerFactory.MARKER_ID, false, 0)).filter( - m -> m.getAttribute(PDEMarkerFactory.compilerKey, "").equals(CompilerFlags.P_UNRESOLVED_IMPORTS)) - .toList(); + return Arrays.stream(manifest.findMarkers(PDEMarkerFactory.MARKER_ID, false, 0)) + .filter(m -> m.getAttribute(IMarker.SEVERITY, -1) == IMarker.SEVERITY_ERROR).toList(); } @After diff --git a/ui/org.eclipse.pde.ui.tests/src/org/eclipse/pde/ui/tests/ee/ExecutionEnvironmentTests.java b/ui/org.eclipse.pde.ui.tests/src/org/eclipse/pde/ui/tests/ee/ExecutionEnvironmentTests.java index 99bfba9e04c..df23d138344 100644 --- a/ui/org.eclipse.pde.ui.tests/src/org/eclipse/pde/ui/tests/ee/ExecutionEnvironmentTests.java +++ b/ui/org.eclipse.pde.ui.tests/src/org/eclipse/pde/ui/tests/ee/ExecutionEnvironmentTests.java @@ -1,5 +1,5 @@ /******************************************************************************* - * Copyright (c) 2008, 2022 IBM Corporation and others. + * Copyright (c) 2008, 2023 IBM Corporation and others. * * This program and the accompanying materials * are made available under the terms of the Eclipse Public License 2.0 @@ -324,7 +324,7 @@ public void testMinimumComplianceNoOverwrite() throws Exception { @Test public void testDynamicSystemPackages() throws Exception { IExecutionEnvironment env = JavaRuntime.getExecutionEnvironmentsManager().getEnvironment("JavaSE-11"); - String systemPackages = TargetPlatformHelper.querySystemPackages(env); + String systemPackages = TargetPlatformHelper.getSystemPackages(env, null); assertThat(systemPackages).isNotNull(); assertThat(systemPackages.split(",")).contains("java.lang", "javax.sql", "org.w3c.dom.css"); } diff --git a/ui/org.eclipse.pde.ui.tests/src/org/eclipse/pde/ui/tests/target/TargetEnvironmentTestCase.java b/ui/org.eclipse.pde.ui.tests/src/org/eclipse/pde/ui/tests/target/TargetEnvironmentTestCase.java index 52a57ae9a07..36aefd91867 100644 --- a/ui/org.eclipse.pde.ui.tests/src/org/eclipse/pde/ui/tests/target/TargetEnvironmentTestCase.java +++ b/ui/org.eclipse.pde.ui.tests/src/org/eclipse/pde/ui/tests/target/TargetEnvironmentTestCase.java @@ -1,5 +1,5 @@ /******************************************************************************* - * Copyright (c) 2006, 2018 IBM Corporation and others. + * Copyright (c) 2006, 2023 IBM Corporation and others. * * This program and the accompanying materials * are made available under the terms of the Eclipse Public License 2.0 @@ -14,21 +14,67 @@ package org.eclipse.pde.ui.tests.target; import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertTrue; import static org.junit.Assert.fail; +import java.util.Arrays; import java.util.Dictionary; +import java.util.List; +import java.util.Map; import java.util.Properties; - +import java.util.Set; +import java.util.stream.Collectors; +import java.util.stream.Stream; + +import org.eclipse.core.resources.IMarker; +import org.eclipse.core.resources.IProject; +import org.eclipse.core.resources.IResource; +import org.eclipse.core.resources.IncrementalProjectBuilder; +import org.eclipse.core.runtime.CoreException; import org.eclipse.core.runtime.Platform; +import org.eclipse.jdt.launching.IVMInstall; import org.eclipse.jdt.launching.JavaRuntime; import org.eclipse.jdt.launching.environments.IExecutionEnvironment; import org.eclipse.pde.core.plugin.TargetPlatform; import org.eclipse.pde.internal.core.TargetPlatformHelper; +import org.eclipse.pde.ui.tests.runtime.TestUtils; +import org.eclipse.pde.ui.tests.util.ProjectUtils; +import org.eclipse.pde.ui.tests.util.TargetPlatformUtil; +import org.junit.After; +import org.junit.Before; +import org.junit.BeforeClass; +import org.junit.ClassRule; import org.junit.Test; +import org.junit.rules.TestRule; import org.osgi.framework.Constants; public class TargetEnvironmentTestCase { + + private static final String JAVA_SE_1_7 = "JavaSE-1.7"; + + @ClassRule + public static final TestRule RESTORE_TARGET_DEFINITION = TargetPlatformUtil.RESTORE_CURRENT_TARGET_DEFINITION_AFTER; + @ClassRule + public static final TestRule CLEAR_WORKSPACE = ProjectUtils.DELETE_ALL_WORKSPACE_PROJECTS_BEFORE_AND_AFTER; + + @BeforeClass + public static void setupTargetPlatform() throws Exception { + TargetPlatformUtil.setRunningPlatformAsTarget(); + } + + private IExecutionEnvironment eeJava_1_7; + private IVMInstall eeJava_1_7DefaultVM; + + @Before + public void saveJava1_7EEDefault() { + eeJava_1_7 = JavaRuntime.getExecutionEnvironmentsManager().getEnvironment(JAVA_SE_1_7); + eeJava_1_7DefaultVM = eeJava_1_7.getDefaultVM(); + } + + @After + public void restoreJava1_7EEDefault() { + eeJava_1_7.setDefaultVM(eeJava_1_7DefaultVM); + } + @Test public void testOS() { assertEquals(Platform.getOS(), TargetPlatform.getOS()); @@ -82,13 +128,12 @@ public void testDictionaryNL() { @Test public void testResolveOptional() { Dictionary dictionary = TargetPlatformHelper.getTargetEnvironment(); - assertTrue("true".equals(dictionary.get("osgi.resolveOptional"))); + assertEquals("true", dictionary.get("osgi.resolveOptional")); } /** * Tests that the OSGi state for the PDE models has the correct properties set, based on known execution environments */ - @SuppressWarnings("deprecation") @Test public void testStateEEProperties() { Dictionary[] platformProps = TargetPlatformHelper.getState().getPlatformProperties(); @@ -100,29 +145,22 @@ public void testStateEEProperties() { Properties profileProps = environment.getProfileProperties(); if (profileProps != null) { // If we have profile properties for an execution environment, ensure that they were added to the state - String systemPackages = profileProps.getProperty(Constants.FRAMEWORK_SYSTEMPACKAGES); - if (systemPackages != null){ - boolean foundSystemPackage = false; - for (Dictionary platformProp : platformProps) { - if (systemPackages.equals(platformProp.get(Constants.FRAMEWORK_SYSTEMPACKAGES))){ - foundSystemPackage = true; - break; - } - } - if (!foundSystemPackage){ + Set profileSystemPackages = getSystemPackages(profileProps) + .filter(p -> p.startsWith("java.")).collect(Collectors.toSet()); + if (!profileSystemPackages.isEmpty()) { + String profileEE = getExecutionenvironment(profileProps); + boolean foundSystemPackage = Arrays.stream(platformProps) + .filter(pp -> profileEE.equals(getExecutionenvironment(pp))).anyMatch(pp -> { + Set packages = getSystemPackages(pp).collect(Collectors.toSet()); + return packages.containsAll(profileSystemPackages); + }); + if (!foundSystemPackage) { fail("The system packages property for EE " + profile + " was not found in the state's propeties"); } } - String ee = profileProps.getProperty(Constants.FRAMEWORK_EXECUTIONENVIRONMENT); - if (ee != null){ - boolean foundEE = false; - for (Dictionary platformProp : platformProps) { - if (ee.equals(platformProp.get(Constants.FRAMEWORK_EXECUTIONENVIRONMENT))){ - foundEE = true; - break; - } - } - if (!foundEE){ + String ee = getExecutionenvironment(profileProps); + if (ee != null) { + if (Stream.of(platformProps).map(pp -> getExecutionenvironment(pp)).noneMatch(ee::equals)) { fail("The framework EE property for EE " + profile + " was not found in the state's propeties"); } } @@ -131,4 +169,51 @@ public void testStateEEProperties() { } } + @SuppressWarnings("deprecation") + private String getExecutionenvironment(Object profile) { + return (String) ((Map) profile).get(Constants.FRAMEWORK_EXECUTIONENVIRONMENT); + } + + private static Stream getSystemPackages(Object profile) { + String platformPackages = (String) ((Map) profile).get(Constants.FRAMEWORK_SYSTEMPACKAGES); + if (platformPackages == null) { + return Stream.empty(); + } + return Arrays.stream(platformPackages.split(",")); + } + + @Test + public void testProjectWithJVMImports() throws CoreException { + // A Java-1.7 VM does not provide the java.util.function package + // introduced in 1.8. But if we say that a Java 1.8+ VM the default + // (which the one running this test and thus the workspaces default-VM + // should be), well then the system-packages of that Java 1.8+ VM should + // be used in the PDEState and thus there should not be errors. This + // might not be a good idea in production, but is a good test-case. + IProject project = ProjectUtils.createPluginProject("foo.bar", "foo.bar", "1.0.0.qualifier", (d, s) -> { + d.setExecutionEnvironments(new String[] { JAVA_SE_1_7 }); + d.setHeader(Constants.IMPORT_PACKAGE, "java.util.function"); + d.setHeader("Automatic-Module-Name", "foo.bar"); + }); + project.build(IncrementalProjectBuilder.FULL_BUILD, null); + List errorsWithoutEEDefault = findErrorMarkers(project); + assertEquals(errorsWithoutEEDefault.toString(), 1, errorsWithoutEEDefault.size()); + + eeJava_1_7.setDefaultVM(JavaRuntime.getDefaultVMInstall()); + + // await at least VMInstall/EE change delay in + // MinimalState.rereadSystemPackagesAndReloadTP() + TestUtils.waitForJobs("testProjectWithEEImports", 300, 10_000); + + List errorsWithEEDefault = findErrorMarkers(project); + assertEquals(List.of(), errorsWithEEDefault); + } + + private List findErrorMarkers(IProject project) throws CoreException { + IMarker[] markers = project.findMarkers(null, true, IResource.DEPTH_INFINITE); + List errorsWithoutEEDefault = Arrays.stream(markers) + .filter(m -> m.getAttribute(IMarker.SEVERITY, -1) == IMarker.SEVERITY_ERROR).toList(); + return errorsWithoutEEDefault; + } + } From 161d86213d7be22952308051bded36c2d9f19776 Mon Sep 17 00:00:00 2001 From: Hannes Wellmann Date: Thu, 10 Aug 2023 23:44:10 +0200 Subject: [PATCH 06/18] Remove wrong validation error about forbidden import of java.* packages java.* packages are not forbidden to import (with modular JDKs one is even encouraged to list java.* packages). Even though this error only showed up if any imported package could not be resolved, but since it is (now) perfectly fine to import them as well, there should not be a special error message for that case. This could even cause a false positive if another package is not resolved. --- .../eclipse/pde/internal/core/PDECoreMessages.java | 2 -- .../internal/core/builders/BundleErrorReporter.java | 11 +---------- .../eclipse/pde/internal/core/pderesources.properties | 3 +-- 3 files changed, 2 insertions(+), 14 deletions(-) diff --git a/ui/org.eclipse.pde.core/src/org/eclipse/pde/internal/core/PDECoreMessages.java b/ui/org.eclipse.pde.core/src/org/eclipse/pde/internal/core/PDECoreMessages.java index 94d3ac2a3a9..d9a04792ca4 100644 --- a/ui/org.eclipse.pde.core/src/org/eclipse/pde/internal/core/PDECoreMessages.java +++ b/ui/org.eclipse.pde.core/src/org/eclipse/pde/internal/core/PDECoreMessages.java @@ -229,8 +229,6 @@ public class PDECoreMessages extends NLS { public static String BundleErrorReporter_exportNoJRE; - public static String BundleErrorReporter_importNoJRE; - public static String ManifestConsistencyChecker_0; public static String ManifestConsistencyChecker_buildDoesNotExist; diff --git a/ui/org.eclipse.pde.core/src/org/eclipse/pde/internal/core/builders/BundleErrorReporter.java b/ui/org.eclipse.pde.core/src/org/eclipse/pde/internal/core/builders/BundleErrorReporter.java index 9583684f986..2f5c39f6a7e 100644 --- a/ui/org.eclipse.pde.core/src/org/eclipse/pde/internal/core/builders/BundleErrorReporter.java +++ b/ui/org.eclipse.pde.core/src/org/eclipse/pde/internal/core/builders/BundleErrorReporter.java @@ -1206,19 +1206,10 @@ private void validateImportPackage(IProgressMonitor monitor) { int length = element.getValueComponents().length; for (int j = 0; j < length; j++) { ImportPackageSpecification importSpec = imports[index++]; - String name = importSpec.getName(); - if (name.equals("java") || name.startsWith("java.")) { //$NON-NLS-1$ //$NON-NLS-2$ - IHeader jreHeader = getHeader(ICoreConstants.ECLIPSE_JREBUNDLE); - if (jreHeader == null || !"true".equals(jreHeader.getValue())) { //$NON-NLS-1$ - report(PDECoreMessages.BundleErrorReporter_importNoJRE, getPackageLine(header, element), CompilerFlags.ERROR, PDEMarkerFactory.M_JAVA_PACKAGE__PORTED, PDEMarkerFactory.CAT_FATAL); - continue; - } - } - if (importSpec.isResolved() || !isCheckUnresolvedImports()) { continue; } - + String name = importSpec.getName(); boolean optional = isOptional(element); int severity = getRequireBundleSeverity(element, optional); diff --git a/ui/org.eclipse.pde.core/src/org/eclipse/pde/internal/core/pderesources.properties b/ui/org.eclipse.pde.core/src/org/eclipse/pde/internal/core/pderesources.properties index df610bf331d..44eb4c4905c 100644 --- a/ui/org.eclipse.pde.core/src/org/eclipse/pde/internal/core/pderesources.properties +++ b/ui/org.eclipse.pde.core/src/org/eclipse/pde/internal/core/pderesources.properties @@ -176,10 +176,9 @@ BundleErrorReporter_NotExistPDE=Bundle ''{0}'' cannot be resolved BundleErrorReporter_EmptyTargetPlatform=Target Platform is not set BundleErrorReporter_ExecEnv_tooLow=Execution environment is lower than one of the plug-in''s dependencies ({1}) which has an execution environment of {0}. BundleErrorReporter_exportNoJRE=Cannot export packages prefixed with 'java' -BundleErrorReporter_importNoJRE=Cannot import packages prefixed with 'java' BundleErrorReporter_HostNotExistPDE=Host bundle ''{0}'' cannot be resolved BundleErrorReporter_HostNeeded=Fragment-Host must be defined for this fragment -BundleErrorReporter_PackageNotExported=No available bundle exports package ''{0}'' +BundleErrorReporter_PackageNotExported=Neither an available bundle nor the associated JRE export package ''{0}'' BundleErrorReporter_unresolvedExporter=Bundle ''{0}'' exporting package ''{1}'' is unresolved BundleErrorReporter_reqExecEnv_unknown=''{0}'' is not a valid Execution Environment BundleErrorReporter_InvalidSymbolicName=Bundle symbolic name contains illegal characters. Legal characters are A-Z a-z 0-9 . _ - From e621405fd950815acee1e55298761b5e5aa1c993 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Christoph=20L=C3=A4ubrich?= Date: Mon, 31 Jul 2023 20:06:11 +0200 Subject: [PATCH 07/18] Add osgi-repository target location type The OSGi Specification defines a XML format for representing a repository as defined in "132 Repository Service Specification" that allows to hold "Resources" with requirements and capabilities. Such a repository usually contains a set of bundles and is very similar to what we have today with P2 updatesites, to improve interfacing of PDE with such repositories this adds a new target location type "Repository" where content can be used as usual. --- ui/org.eclipse.pde.core/META-INF/MANIFEST.MF | 1 + ui/org.eclipse.pde.core/plugin.xml | 8 + .../target/RepositoryBundleContainer.java | 185 +++++++++++ .../target/RepositoryLocationFactory.java | 68 ++++ ui/org.eclipse.pde.ui/META-INF/MANIFEST.MF | 4 +- .../icons/dview16/memory_view.png | Bin 0 -> 346 bytes .../icons/dview16/memory_view@2x.png | Bin 0 -> 608 bytes ui/org.eclipse.pde.ui/plugin.properties | 6 +- ui/org.eclipse.pde.ui/plugin.xml | 39 ++- .../eclipse/pde/internal/ui/PDEPlugin.java | 2 + .../pde/internal/ui/PDEPluginImages.java | 2 + .../target/EditRepositoryContainerPage.java | 290 ++++++++++++++++++ .../internal/ui/shared/target/Messages.java | 5 + ...positoryBundleContainerAdapterFactory.java | 212 +++++++++++++ .../target/RepositoryLocationWizard.java | 75 +++++ .../target/SelectRepositoryContentPage.java | 192 ++++++++++++ .../ui/shared/target/messages.properties | 9 +- 17 files changed, 1091 insertions(+), 7 deletions(-) create mode 100644 ui/org.eclipse.pde.core/src/org/eclipse/pde/internal/core/target/RepositoryBundleContainer.java create mode 100644 ui/org.eclipse.pde.core/src/org/eclipse/pde/internal/core/target/RepositoryLocationFactory.java create mode 100644 ui/org.eclipse.pde.ui/icons/dview16/memory_view.png create mode 100644 ui/org.eclipse.pde.ui/icons/dview16/memory_view@2x.png create mode 100644 ui/org.eclipse.pde.ui/src/org/eclipse/pde/internal/ui/shared/target/EditRepositoryContainerPage.java create mode 100644 ui/org.eclipse.pde.ui/src/org/eclipse/pde/internal/ui/shared/target/RepositoryBundleContainerAdapterFactory.java create mode 100644 ui/org.eclipse.pde.ui/src/org/eclipse/pde/internal/ui/shared/target/RepositoryLocationWizard.java create mode 100644 ui/org.eclipse.pde.ui/src/org/eclipse/pde/internal/ui/shared/target/SelectRepositoryContentPage.java diff --git a/ui/org.eclipse.pde.core/META-INF/MANIFEST.MF b/ui/org.eclipse.pde.core/META-INF/MANIFEST.MF index 3f2bee839eb..efad311560f 100644 --- a/ui/org.eclipse.pde.core/META-INF/MANIFEST.MF +++ b/ui/org.eclipse.pde.core/META-INF/MANIFEST.MF @@ -80,6 +80,7 @@ Export-Package: org.eclipse.pde.unittest.junit", org.eclipse.pde.internal.core.variables;x-internal:=true Import-Package: aQute.bnd.build;version="[4.4.0,5.0.0)", + aQute.bnd.header;version="2.5.0", aQute.bnd.osgi;version="[5.5.0,6.0.0)", aQute.bnd.osgi.repository;version="[3.0.0,4.0.0)", aQute.bnd.osgi.resource;version="[4.3.0,5.0.0)", diff --git a/ui/org.eclipse.pde.core/plugin.xml b/ui/org.eclipse.pde.core/plugin.xml index 0db7b0acc4b..98dbd6bea98 100644 --- a/ui/org.eclipse.pde.core/plugin.xml +++ b/ui/org.eclipse.pde.core/plugin.xml @@ -437,4 +437,12 @@ class="org.eclipse.pde.internal.core.LocalMavenPluginSourcePathLocator" complexity="low"/> + + + + diff --git a/ui/org.eclipse.pde.core/src/org/eclipse/pde/internal/core/target/RepositoryBundleContainer.java b/ui/org.eclipse.pde.core/src/org/eclipse/pde/internal/core/target/RepositoryBundleContainer.java new file mode 100644 index 00000000000..7cb47c74dac --- /dev/null +++ b/ui/org.eclipse.pde.core/src/org/eclipse/pde/internal/core/target/RepositoryBundleContainer.java @@ -0,0 +1,185 @@ +/******************************************************************************* + * Copyright (c) 2023 Christoph Läubrich and others. + * + * 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: + * Christoph Läubrich - initial API and implementation + *******************************************************************************/ +package org.eclipse.pde.internal.core.target; + +import java.io.File; +import java.io.IOException; +import java.io.StringWriter; +import java.net.URI; +import java.net.URISyntaxException; +import java.util.ArrayList; +import java.util.Collection; +import java.util.List; +import java.util.Map; +import java.util.Objects; + +import javax.xml.parsers.DocumentBuilder; +import javax.xml.transform.OutputKeys; +import javax.xml.transform.Transformer; +import javax.xml.transform.TransformerFactory; +import javax.xml.transform.dom.DOMSource; +import javax.xml.transform.stream.StreamResult; + +import org.eclipse.core.runtime.CoreException; +import org.eclipse.core.runtime.FileLocator; +import org.eclipse.core.runtime.IProgressMonitor; +import org.eclipse.core.runtime.Status; +import org.eclipse.equinox.internal.p2.repository.CacheManager; +import org.eclipse.pde.core.target.ITargetDefinition; +import org.eclipse.pde.core.target.TargetBundle; +import org.eclipse.pde.core.target.TargetFeature; +import org.eclipse.pde.internal.core.PDECore; +import org.eclipse.pde.internal.core.util.PDEXmlProcessorFactory; +import org.osgi.resource.Capability; +import org.osgi.resource.Requirement; +import org.w3c.dom.Document; +import org.w3c.dom.Element; + +import aQute.bnd.osgi.repository.ResourcesRepository; +import aQute.bnd.osgi.repository.XMLResourceParser; +import aQute.bnd.osgi.resource.ResourceUtils; +import aQute.bnd.osgi.resource.ResourceUtils.ContentCapability; + +@SuppressWarnings("restriction") +public class RepositoryBundleContainer extends AbstractBundleContainer { + public static final String ATTRIBUTE_URI = "uri"; //$NON-NLS-1$ + + public static final String ELEMENT_REQUIRE = "require"; //$NON-NLS-1$ + + public static final String TYPE = "Repository"; //$NON-NLS-1$ + + private final String uri; + + private final Collection requirements; + + public RepositoryBundleContainer(String uri, Collection requirements) { + this.uri = uri; + this.requirements = requirements; + } + + @Override + protected TargetBundle[] resolveBundles(ITargetDefinition definition, IProgressMonitor monitor) + throws CoreException { + ResourcesRepository repository = getRepository(monitor); + Map> providers = repository.findProviders(getRequirements()); + List bundles = new ArrayList<>(); + List contentCapabilities = providers.values().stream().flatMap(Collection::stream) + .map(Capability::getResource).distinct().map(ResourceUtils::getContentCapability) + .filter(Objects::nonNull).toList(); + CacheManager cacheManager = getCacheManager(); + for (ContentCapability content : contentCapabilities) { + URI url = content.url(); + try { + File file; + if (cacheManager != null) { + file = cacheManager.createCacheFromFile(url, monitor); + } else { + file = new File(FileLocator.toFileURL(url.toURL()).toURI()); + } + bundles.add(new TargetBundle(file)); + } catch (IOException | URISyntaxException e) { + throw new CoreException(Status.error("Can't fetch bundle from " + url, e)); + } + } + return bundles.toArray(TargetBundle[]::new); + } + + public String getUri() { + return uri; + } + + public Collection getRequirements() { + return requirements; + } + + public ResourcesRepository getRepository(IProgressMonitor monitor) throws CoreException { + String location = getLocation(true); + try { + URI base = new URI(location); + try { + CacheManager cacheManager = getCacheManager(); + if (cacheManager != null) { + File file = cacheManager.createCacheFromFile(base, monitor); + return new ResourcesRepository(XMLResourceParser.getResources(file, base)); + } + return new ResourcesRepository(XMLResourceParser.getResources(base)); + } catch (Exception e) { + if (e instanceof CoreException core) { + throw core; + } + if (e instanceof RuntimeException runtime) { + throw runtime; + } + throw new CoreException(Status.error("Loading repository from " + location + " failed: " + e, e)); + } + } catch (URISyntaxException e) { + throw new CoreException(Status.error("Invalid URI: " + location, e)); + } + } + + private CacheManager getCacheManager() throws CoreException { + return P2TargetUtils.getAgent().getService(CacheManager.class); + } + + @Override + protected TargetFeature[] resolveFeatures(ITargetDefinition definition, IProgressMonitor monitor) + throws CoreException { + return new TargetFeature[0]; + } + + @Override + public String getType() { + return TYPE; + } + + @Override + public String getLocation(boolean resolve) throws CoreException { + if (resolve) { + return resolveVariables(uri); + } + return uri; + } + + @Override + public String serialize() { + try { + DocumentBuilder docBuilder = PDEXmlProcessorFactory.createDocumentBuilderWithErrorOnDOCTYPE(); + Document document = docBuilder.newDocument(); + Element containerElement = document.createElement(TargetDefinitionPersistenceHelper.LOCATION); + containerElement.setAttribute(TargetDefinitionPersistenceHelper.ATTR_LOCATION_TYPE, TYPE); + containerElement.setAttribute(ATTRIBUTE_URI, getUri()); + for (Requirement requirement : requirements) { + Element requireElement = document.createElement(ELEMENT_REQUIRE); + requireElement.setTextContent(requirement.toString()); + containerElement.appendChild(requireElement); + } + document.appendChild(containerElement); + StreamResult result = new StreamResult(new StringWriter()); + TransformerFactory f = PDEXmlProcessorFactory.createTransformerFactoryWithErrorOnDOCTYPE(); + Transformer transformer = f.newTransformer(); + transformer.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "yes"); //$NON-NLS-1$ + transformer.transform(new DOMSource(document), result); + String xml = result.getWriter().toString(); + return xml; + } catch (Exception e) { + PDECore.log(e); + return null; + } + } + + public void reload() { + fResolutionStatus = null; + fBundles = null; + } +} diff --git a/ui/org.eclipse.pde.core/src/org/eclipse/pde/internal/core/target/RepositoryLocationFactory.java b/ui/org.eclipse.pde.core/src/org/eclipse/pde/internal/core/target/RepositoryLocationFactory.java new file mode 100644 index 00000000000..4cdd48268a2 --- /dev/null +++ b/ui/org.eclipse.pde.core/src/org/eclipse/pde/internal/core/target/RepositoryLocationFactory.java @@ -0,0 +1,68 @@ +/******************************************************************************* + * Copyright (c) 2023 Christoph Läubrich and others. + * + * 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: + * Christoph Läubrich - initial API and implementation + *******************************************************************************/ +package org.eclipse.pde.internal.core.target; + +import java.io.ByteArrayInputStream; +import java.nio.charset.StandardCharsets; +import java.util.List; +import java.util.stream.IntStream; + +import javax.xml.parsers.DocumentBuilder; + +import org.eclipse.core.runtime.CoreException; +import org.eclipse.core.runtime.Status; +import org.eclipse.osgi.util.NLS; +import org.eclipse.pde.core.target.ITargetLocation; +import org.eclipse.pde.core.target.ITargetLocationFactory; +import org.eclipse.pde.internal.core.util.PDEXmlProcessorFactory; +import org.osgi.resource.Requirement; +import org.w3c.dom.Document; +import org.w3c.dom.Element; +import org.w3c.dom.NodeList; + +import aQute.bnd.header.Parameters; +import aQute.bnd.osgi.resource.CapReqBuilder; + +public class RepositoryLocationFactory implements ITargetLocationFactory { + + @Override + public ITargetLocation getTargetLocation(String type, String serializedXML) throws CoreException { + if (!RepositoryBundleContainer.TYPE.equals(type)) { + throw new CoreException( + Status.error(NLS.bind(Messages.TargetRefrenceLocationFactory_Unsupported_Type, type))); + } + try { + DocumentBuilder docBuilder = PDEXmlProcessorFactory.createDocumentBuilderWithErrorOnDOCTYPE(); + Document document = docBuilder + .parse(new ByteArrayInputStream(serializedXML.getBytes(StandardCharsets.UTF_8))); + Element location = document.getDocumentElement(); + NodeList childNodes = location.getChildNodes(); + List requirements = IntStream.range(0, childNodes.getLength()).mapToObj(childNodes::item) + .filter(Element.class::isInstance).map(Element.class::cast) + .filter(element -> element.getNodeName() + .equalsIgnoreCase(RepositoryBundleContainer.ELEMENT_REQUIRE)) + .flatMap(element -> { + String textContent = element.getTextContent(); + Parameters parameters = new Parameters(textContent); + return CapReqBuilder.getRequirementsFrom(parameters).stream(); + }).toList(); + return new RepositoryBundleContainer( + location.getAttribute(RepositoryBundleContainer.ATTRIBUTE_URI), requirements); + } catch (Exception e) { + throw new CoreException( + Status.error(NLS.bind(Messages.TargetRefrenceLocationFactory_Parsing_Failed, e.getMessage()), e)); + } + } + +} diff --git a/ui/org.eclipse.pde.ui/META-INF/MANIFEST.MF b/ui/org.eclipse.pde.ui/META-INF/MANIFEST.MF index f7693ec2fed..62c8423a3d4 100644 --- a/ui/org.eclipse.pde.ui/META-INF/MANIFEST.MF +++ b/ui/org.eclipse.pde.ui/META-INF/MANIFEST.MF @@ -121,7 +121,9 @@ Require-Bundle: biz.aQute.bndlib;bundle-version="6.3.1" Import-Package: org.eclipse.jdt.debug.ui.console, org.eclipse.ui.internal.genericeditor, - org.osgi.service.event;version="[1.4,2.0.0)" + org.osgi.service.event;version="[1.4,2.0.0)", + org.osgi.service.repository;version="1.1.0", + org.osgi.util.promise;version="1.3.0" Bundle-RequiredExecutionEnvironment: JavaSE-17 Bundle-ActivationPolicy: lazy Automatic-Module-Name: org.eclipse.pde.ui diff --git a/ui/org.eclipse.pde.ui/icons/dview16/memory_view.png b/ui/org.eclipse.pde.ui/icons/dview16/memory_view.png new file mode 100644 index 0000000000000000000000000000000000000000..0e09f99274cf6772e08c984ad18a1f0bed684a0f GIT binary patch literal 346 zcmV-g0j2(lP)AHT)azz50%_iS&x9@41;&3>i zC<-J=0@rn6nkE=9kbq$r*zI=HgI(95sw%W?i@L7ic^-IA0&E5NzK?PmecxjkhG~+rED;0&cuxYVs$Kx&I9>p}CjmuKNPzbwAj>id z@cw^+)oMioye9!kl1PB}B(PjANr3m?0rzaPyoO46Nvh-)z*;oe)3kysCfOYnL4}`477;X}>@B2;yl0ec#48c<3h5Pz_!#xtw z;yNcHkrWSSIOn`G&nyfx8m(5V`Il%eN+1vjJPQVcABay>K6*T!JD1A^hRZ&m??~@I z6D7aj|AI1)&LZITdf&R;?xWJ!LvcEt-y9ByL6rdYEOOFI#9}ez^LaEH4K$lgRI63g z>vi;cJ@KwkC?Fb*ihoZ;-bo8km@7a$9>;h*#&kOUiP30;!C>&)Z;3<#N?x@9_iQqm zh>B;k85WBLR;v}3%cbc3a5(%$fJf?V0<;dqDDaT8z-F_-cDqHV(?PjhMy*y8Wu{ar zArgteVzHG%7h=dD%?l}ZKKY!<0hN~{6?-)6Hx$*UIN z;be-%qG+5O<@rAq;AzTaGDxS>LWCErY5}|54u%`&q3(9On9t{83J!+@cDo(c>$O-5 zJn!vxTTB6q@RTWeX#pNaMpi({Uj?KEtX3-+Spg+~xdObIFtP$l{wi>}0%o%rjI4l? zmliOYOkiXMl>Fri7>!0SvI0u}Dj+RjFc`iP2#3R>;y)3f`vEvh+^P|Hsn_do3EtE1 zxL17q=0oXzzyBe?2Ub2A-Q3)WqZ{x4oVn+fs*4F#@RXRIRQOOn63@?eHPh*IkEz1f u^bFq%eK~22%M0Q?eSbqd`Ts7be}nHI^^IR&ueEsq0000 + + + + + + + + + + + + + + + + @@ -2246,9 +2272,18 @@ class="org.eclipse.pde.internal.ui.shared.target.TargetReferenceLocationWizard" icon="icons/obj16/target_profile_xml_obj.png" id="org.eclipse.pde.ui.TargetReferenceProvisioner" - name="%locationProvider.name"> + name="%locationProvider.reference.name"> + + %locationProvider.reference.description + + + - %locationProvider.description + %locationProvider.repository.description diff --git a/ui/org.eclipse.pde.ui/src/org/eclipse/pde/internal/ui/PDEPlugin.java b/ui/org.eclipse.pde.ui/src/org/eclipse/pde/internal/ui/PDEPlugin.java index b9d12d6edca..4430ef44e8e 100644 --- a/ui/org.eclipse.pde.ui/src/org/eclipse/pde/internal/ui/PDEPlugin.java +++ b/ui/org.eclipse.pde.ui/src/org/eclipse/pde/internal/ui/PDEPlugin.java @@ -28,6 +28,7 @@ import org.eclipse.jface.preference.IPreferenceStore; import org.eclipse.pde.internal.core.PDEPreferencesManager; import org.eclipse.pde.internal.ui.launcher.PDELogFileProvider; +import org.eclipse.pde.internal.ui.shared.target.RepositoryBundleContainerAdapterFactory; import org.eclipse.pde.internal.ui.shared.target.TargetReferenceBundleContainerAdapterFactory; import org.eclipse.pde.internal.ui.shared.target.TargetStatus; import org.eclipse.pde.internal.ui.util.SWTUtil; @@ -233,6 +234,7 @@ public void stop(BundleContext context) throws Exception { Utilities.shutdown(); super.stop(context); TargetReferenceBundleContainerAdapterFactory.LABEL_PROVIDER.dispose(); + RepositoryBundleContainerAdapterFactory.LABEL_PROVIDER.dispose(); } public PDELabelProvider getLabelProvider() { diff --git a/ui/org.eclipse.pde.ui/src/org/eclipse/pde/internal/ui/PDEPluginImages.java b/ui/org.eclipse.pde.ui/src/org/eclipse/pde/internal/ui/PDEPluginImages.java index 289bf3aabc4..265f889b230 100644 --- a/ui/org.eclipse.pde.ui/src/org/eclipse/pde/internal/ui/PDEPluginImages.java +++ b/ui/org.eclipse.pde.ui/src/org/eclipse/pde/internal/ui/PDEPluginImages.java @@ -42,6 +42,7 @@ public class PDEPluginImages { private static final String PATH_OBJ = ICONS_PATH + "obj16/"; //$NON-NLS-1$ private static final String PATH_VIEW = ICONS_PATH + "view16/"; //$NON-NLS-1$ + private static final String PATH_DVIEW = ICONS_PATH + "dview16/"; //$NON-NLS-1$ private static final String PATH_LCL = ICONS_PATH + "elcl16/"; //$NON-NLS-1$ private static final String PATH_LCL_DISABLED = ICONS_PATH + "dlcl16/"; //$NON-NLS-1$ private static final String PATH_TOOL = ICONS_PATH + "etool16/"; //$NON-NLS-1$ @@ -316,6 +317,7 @@ public class PDEPluginImages { * View */ public static final ImageDescriptor DESC_ARGUMENT_TAB = create(PATH_VIEW, "variable_tab.png"); //$NON-NLS-1$ + public static final ImageDescriptor DESC_TARGET_REPO = create(PATH_DVIEW, "memory_view.png"); //$NON-NLS-1$ private static ImageDescriptor create(String prefix, String name) { return ImageDescriptor.createFromURL(makeImageURL(prefix, name)); diff --git a/ui/org.eclipse.pde.ui/src/org/eclipse/pde/internal/ui/shared/target/EditRepositoryContainerPage.java b/ui/org.eclipse.pde.ui/src/org/eclipse/pde/internal/ui/shared/target/EditRepositoryContainerPage.java new file mode 100644 index 00000000000..667d4d516a1 --- /dev/null +++ b/ui/org.eclipse.pde.ui/src/org/eclipse/pde/internal/ui/shared/target/EditRepositoryContainerPage.java @@ -0,0 +1,290 @@ +/******************************************************************************* + * Copyright (c) 2009, 2023 IBM Corporation and others. + * + * 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 + * Christoph Läubrich - Bug 577184 - [target] Allow references to other targets inside a target-file + * Christoph Läubrich - add support for repositories + *******************************************************************************/ +package org.eclipse.pde.internal.ui.shared.target; + +import static org.eclipse.swt.events.SelectionListener.widgetSelectedAdapter; + +import java.io.File; +import java.net.MalformedURLException; +import java.net.URI; +import java.net.URISyntaxException; +import java.net.URL; +import java.util.ArrayList; +import java.util.List; + +import org.eclipse.core.runtime.CoreException; +import org.eclipse.debug.ui.StringVariableSelectionDialog; +import org.eclipse.jface.dialogs.IDialogSettings; +import org.eclipse.jface.dialogs.IMessageProvider; +import org.eclipse.jface.wizard.WizardPage; +import org.eclipse.osgi.util.NLS; +import org.eclipse.pde.core.target.ITargetLocation; +import org.eclipse.pde.internal.core.target.RemoteTargetHandle; +import org.eclipse.pde.internal.core.target.RepositoryBundleContainer; +import org.eclipse.pde.internal.ui.PDEPlugin; +import org.eclipse.pde.internal.ui.SWTFactory; +import org.eclipse.swt.SWT; +import org.eclipse.swt.layout.GridData; +import org.eclipse.swt.widgets.Button; +import org.eclipse.swt.widgets.Combo; +import org.eclipse.swt.widgets.Composite; + +/** + * Wizard page for creating a new directory bundle container. + * + * @see AddBundleContainerWizard + * @see AddBundleContainerSelectionPage + * @see ITargetLocation + */ +public class EditRepositoryContainerPage extends WizardPage implements IEditBundleContainerPage { + + /** + * How long to wait before validating the directory + */ + protected static final int TYPING_DELAY = 200; + + protected Combo furiLocation; + protected RepositoryBundleContainer fContainer; + + /** + * Dialog settings key for the most recent location + */ + private static final String SETTINGS_LOCATION_1 = "location1"; //$NON-NLS-1$ + + /** + * Dialog settings key for the second most recent location + */ + private static final String SETTINGS_LOCATION_2 = "location2"; //$NON-NLS-1$ + + /** + * Dialog settings key for the third most recent location + */ + private static final String SETTINGS_LOCATION_3 = "location3"; //$NON-NLS-1$ + + public EditRepositoryContainerPage(RepositoryBundleContainer bundleContainer) { + super("EditRepositoryContainerPage"); //$NON-NLS-1$ + fContainer = bundleContainer; + } + + @Override + public void createControl(Composite parent) { + setMessage(getDefaultMessage()); + setTitle(getDefaultTitle()); + setPageComplete(false); + Composite comp = SWTFactory.createComposite(parent, 1, 1, GridData.FILL_BOTH, 0, 0); + createLocationArea(comp); + setControl(comp); + initializeInputFields(fContainer); + } + + /** + * @return the default title for this wizard page + */ + protected String getDefaultTitle() { + if (fContainer == null) { + return Messages.EditRepositoryContainerPage_Add_Title; + } + return Messages.EditRepositoryContainerPage_Edit_Title; + } + + /** + * @return the default message for this wizard page + */ + protected String getDefaultMessage() { + return Messages.EditRepositoryContainerPage_Message; + } + + /** + * Creates the area at the top of the page. Contains an entry form for a + * location path. This method may be overridden by subclasses to provide + * custom widgets + * + * @param parent + * parent composite + */ + protected void createLocationArea(Composite parent) { + Composite locationComp = SWTFactory.createComposite(parent, 2, 1, GridData.FILL_HORIZONTAL, 0, 0); + + SWTFactory.createLabel(locationComp, Messages.AddDirectoryContainerPage_2, 1); + + furiLocation = SWTFactory.createCombo(locationComp, SWT.BORDER, 1, getLocationComboItems()); + furiLocation.addModifyListener(e -> { + setPageComplete(validateInput()); + }); + try { + String location = fContainer != null ? fContainer.getLocation(false) : ""; //$NON-NLS-1$ + furiLocation.setText(location); + } catch (CoreException e) { + setErrorMessage(e.getMessage()); + } + + Composite buttonComp = SWTFactory.createComposite(locationComp, 2, 2, GridData.CENTER, 0, 0); + GridData gd = (GridData) buttonComp.getLayoutData(); + gd.horizontalAlignment = SWT.RIGHT; + + Button variablesButton = SWTFactory.createPushButton(buttonComp, Messages.EditDirectoryContainerPage_1, null); + variablesButton.addSelectionListener(widgetSelectedAdapter(e -> { + StringVariableSelectionDialog dialog = new StringVariableSelectionDialog(getShell()); + dialog.open(); + String variable = dialog.getVariableExpression(); + if (variable != null) { + furiLocation.setText(furiLocation.getText() + variable); + } + })); + } + + /** + * Initializes the fields use to describe the container. They should be + * filled in using the given container or set to default values if the + * container is null. + * + * @param container + * bundle container being edited, possibly null + */ + protected void initializeInputFields(ITargetLocation container) { + try { + String currentLocation = fContainer != null ? fContainer.getLocation(false) : ""; //$NON-NLS-1$ + boolean found = false; + String[] items = furiLocation.getItems(); + for (String item : items) { + if (item.equals(currentLocation)) { + found = true; + break; + } + } + if (!found) { + furiLocation.add(currentLocation); + } + furiLocation.setText(currentLocation); + + setPageComplete(validateInput()); + } catch (CoreException e) { + PDEPlugin.log(e); + } + } + + @Override + public boolean isPageComplete() { + return !furiLocation.getText().isBlank(); + } + + /** + * @return a list of previous locations from settings plus the default + * location + */ + private String[] getLocationComboItems() { + List previousLocations = new ArrayList<>(4); + IDialogSettings settings = getDialogSettings(); + if (settings != null) { + String location = settings.get(SETTINGS_LOCATION_1); + if (location != null) { + previousLocations.add(location); + } + location = settings.get(SETTINGS_LOCATION_2); + if (location != null) { + previousLocations.add(location); + } + location = settings.get(SETTINGS_LOCATION_3); + if (location != null) { + previousLocations.add(location); + } + } + return previousLocations.toArray(new String[previousLocations.size()]); + } + + @Override + public void storeSettings() { + String newLocation = furiLocation.getText().trim(); + + int length = newLocation.length(); + if (length > 0 && newLocation.charAt(length - 1) == File.separatorChar) { + newLocation = newLocation.substring(0, length - 1); + } + String[] items = furiLocation.getItems(); + for (String item : items) { + if (item.equals(newLocation)) { + // Already have this location stored + return; + } + } + IDialogSettings settings = getDialogSettings(); + if (settings != null) { + String location = settings.get(SETTINGS_LOCATION_2); + if (location != null) { + settings.put(SETTINGS_LOCATION_3, location); + } + location = settings.get(SETTINGS_LOCATION_1); + if (location != null) { + settings.put(SETTINGS_LOCATION_2, location); + } + settings.put(SETTINGS_LOCATION_1, newLocation); + } + } + + @Override + public RepositoryBundleContainer getBundleContainer() { + String rawUri = furiLocation != null & !furiLocation.isDisposed() ? furiLocation.getText().trim() : ""; //$NON-NLS-1$ + return new RepositoryBundleContainer(rawUri, fContainer == null ? List.of() : fContainer.getRequirements()); + } + + /** + * Validate the input fields before a container is created/edited. The + * page's enablement, message and completion should be updated. + * + * @return whether the finish button should be enabled and container + * creation should continue + */ + protected boolean validateInput() { + if (furiLocation.isDisposed()) + return false; + + // Check if the text field is blank + if (furiLocation.getText().trim().length() == 0) { + setMessage(getDefaultMessage()); + return false; + } + + // Resolve any variables + URI location; + try { + location = RemoteTargetHandle.getEffectiveUri(furiLocation.getText().trim()); + } catch (CoreException e) { + setMessage(e.getMessage(), IMessageProvider.WARNING); + return true; + } catch (URISyntaxException e) { + setMessage(e.getMessage(), IMessageProvider.ERROR); + return false; + } + try { + // and be converted to an URL + URL url = location.toURL(); + if ("file".equalsIgnoreCase(url.getProtocol())) { //$NON-NLS-1$ + File file = new File(location); + if (!file.isFile()) { + setMessage(NLS.bind(Messages.EditTargetContainerPage_Not_A_File, file.getAbsolutePath()), + IMessageProvider.ERROR); + return true; + } + } + } catch (MalformedURLException | RuntimeException e) { + setMessage(e.getMessage(), IMessageProvider.ERROR); + return false; + } + setMessage(getDefaultMessage()); + return true; + } + +} diff --git a/ui/org.eclipse.pde.ui/src/org/eclipse/pde/internal/ui/shared/target/Messages.java b/ui/org.eclipse.pde.ui/src/org/eclipse/pde/internal/ui/shared/target/Messages.java index 7e44530752b..68fe25980ec 100644 --- a/ui/org.eclipse.pde.ui/src/org/eclipse/pde/internal/ui/shared/target/Messages.java +++ b/ui/org.eclipse.pde.ui/src/org/eclipse/pde/internal/ui/shared/target/Messages.java @@ -152,6 +152,11 @@ public class Messages extends NLS { public static String EditTargetContainerPage_Edit_Title; public static String EditTargetContainerPage_Message; public static String EditTargetContainerPage_Not_A_File; + public static String EditRepositoryContainerPage_Message; + public static String EditRepositoryContainerPage_Add_Title; + public static String EditRepositoryContainerPage_Edit_Title; + public static String SelectRepositoryContentPage_Title; + public static String SelectRepositoryContentPage_Description; static { // initialize resource bundle diff --git a/ui/org.eclipse.pde.ui/src/org/eclipse/pde/internal/ui/shared/target/RepositoryBundleContainerAdapterFactory.java b/ui/org.eclipse.pde.ui/src/org/eclipse/pde/internal/ui/shared/target/RepositoryBundleContainerAdapterFactory.java new file mode 100644 index 00000000000..46e804f28eb --- /dev/null +++ b/ui/org.eclipse.pde.ui/src/org/eclipse/pde/internal/ui/shared/target/RepositoryBundleContainerAdapterFactory.java @@ -0,0 +1,212 @@ +/******************************************************************************* + * Copyright (c) 2023 Christoph Läubrich and others. + * + * 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: + * Christoph Läubrich - initial API and implementation + *******************************************************************************/ +package org.eclipse.pde.internal.ui.shared.target; + +import org.eclipse.core.runtime.CoreException; +import org.eclipse.core.runtime.IAdapterFactory; +import org.eclipse.core.runtime.IProgressMonitor; +import org.eclipse.core.runtime.IStatus; +import org.eclipse.core.runtime.Status; +import org.eclipse.jface.viewers.ILabelProvider; +import org.eclipse.jface.viewers.ITreeContentProvider; +import org.eclipse.jface.viewers.LabelProvider; +import org.eclipse.jface.viewers.TreePath; +import org.eclipse.jface.wizard.IWizard; +import org.eclipse.pde.core.target.ITargetDefinition; +import org.eclipse.pde.core.target.ITargetLocation; +import org.eclipse.pde.internal.core.target.RepositoryBundleContainer; +import org.eclipse.pde.internal.launching.IPDEConstants; +import org.eclipse.pde.internal.ui.PDEPluginImages; +import org.eclipse.pde.ui.target.ITargetLocationHandler; +import org.eclipse.swt.graphics.Image; +import org.osgi.resource.Requirement; + +public class RepositoryBundleContainerAdapterFactory implements IAdapterFactory { + + private static final Object[] EMPTY_OBJECTS = new Object[0]; + + public static final ILabelProvider LABEL_PROVIDER = new LabelProvider() { + + private Image repositoryImage; + private Image requirementImage; + + @Override + public String getText(Object element) { + if (element instanceof RepositoryBundleContainer container) { + try { + return container.getLocation(true); + } catch (CoreException e) { + return container.getUri(); + } + } + if (element instanceof RequirementNode requirement) { + return requirement.requirement().toString(); + } + return null; + } + + @Override + public Image getImage(Object element) { + if (element instanceof RepositoryBundleContainer) { + if (repositoryImage == null) { + repositoryImage = PDEPluginImages.DESC_TARGET_REPO.createImage(); + } + return repositoryImage; + } + if (element instanceof RequirementNode) { + if (requirementImage == null) { + requirementImage = PDEPluginImages.DESC_FILTER.createImage(); + } + return requirementImage; + } + return null; + } + + @Override + public void dispose() { + super.dispose(); + if (repositoryImage != null) { + repositoryImage.dispose(); + repositoryImage = null; + } + } + }; + + private static final ITargetLocationHandler LOCATION_HANDLER = new ITargetLocationHandler() { + + @Override + public IStatus reload(ITargetDefinition target, ITargetLocation[] targetLocations, IProgressMonitor monitor) { + for (ITargetLocation location : targetLocations) { + if (location instanceof RepositoryBundleContainer container) { + container.reload(); + } + } + return Status.OK_STATUS; + } + + @Override + public IWizard getEditWizard(ITargetDefinition target, TreePath treePath) { + Object segment = treePath.getLastSegment(); + if (segment instanceof RequirementNode node) { + // TODO maybe we can support a requirements editor? + segment = node.container; + } + if (segment instanceof RepositoryBundleContainer container) { + RepositoryLocationWizard wizard = new RepositoryLocationWizard(); + wizard.setTarget(target); + wizard.setBundleContainer(container); + return wizard; + } + return null; + } + + @Override + public boolean canEdit(ITargetDefinition target, TreePath treePath) { + Object segment = treePath.getLastSegment(); + return segment instanceof RepositoryBundleContainer || segment instanceof RequirementNode; + } + + public boolean canRemove(ITargetDefinition target, TreePath treePath) { + return treePath.getLastSegment() instanceof RequirementNode; + } + + public IStatus remove(ITargetDefinition target, TreePath[] treePaths) { + boolean reload = false; + for (TreePath path : treePaths) { + Object lastSegment = path.getLastSegment(); + if (lastSegment instanceof RequirementNode node) { + RepositoryBundleContainer container = node.container; + RepositoryBundleContainer newContainer = new RepositoryBundleContainer(container.getUri(), + container.getRequirements().stream().filter(req -> req != node.requirement()).toList()); + ITargetLocation[] targetLocations = target.getTargetLocations(); + for (int i = 0; i < targetLocations.length; i++) { + ITargetLocation loc = targetLocations[i]; + if (loc == container) { + targetLocations[i] = newContainer; + } + + } + } + } + return reload + ? new Status(IStatus.OK, IPDEConstants.UI_PLUGIN_ID, ITargetLocationHandler.STATUS_FORCE_RELOAD, + "reloaded", null) //$NON-NLS-1$ + : Status.OK_STATUS; + } + }; + + private static final ITreeContentProvider TREE_CONTENT_PROVIDER = new ITreeContentProvider() { + + @Override + public boolean hasChildren(Object element) { + if (element instanceof RepositoryBundleContainer container) { + return !container.getRequirements().isEmpty(); + } + return false; + } + + @Override + public Object getParent(Object element) { + if (element instanceof RequirementNode node) { + return node.container; + } + return null; + } + + @Override + public Object[] getElements(Object inputElement) { + return EMPTY_OBJECTS; // will never be called... + } + + @Override + public Object[] getChildren(Object parentElement) { + if (parentElement instanceof RepositoryBundleContainer container) { + return container.getRequirements().stream().map(req -> new RequirementNode(req, container)).toArray(); + } + return EMPTY_OBJECTS; + } + }; + + @Override + public T getAdapter(Object adaptableObject, Class adapterType) { + if (adaptableObject instanceof RepositoryBundleContainer + || adaptableObject instanceof RequirementNode) { + if (adapterType == ILabelProvider.class) { + return adapterType.cast(LABEL_PROVIDER); + } + if (adapterType == ITargetLocationHandler.class) { + return adapterType.cast(LOCATION_HANDLER); + } + if (adapterType == ITreeContentProvider.class) { + return adapterType.cast(TREE_CONTENT_PROVIDER); + } + } + return null; + } + + @Override + public Class[] getAdapterList() { + return new Class[] { ILabelProvider.class, ITargetLocationHandler.class, ITreeContentProvider.class }; + } + + /** + * Simple wrapper class to identify it uniquly when adaption take place and + * to record the parent + */ + public static final record RequirementNode(Requirement requirement, RepositoryBundleContainer container) { + + } + + +} diff --git a/ui/org.eclipse.pde.ui/src/org/eclipse/pde/internal/ui/shared/target/RepositoryLocationWizard.java b/ui/org.eclipse.pde.ui/src/org/eclipse/pde/internal/ui/shared/target/RepositoryLocationWizard.java new file mode 100644 index 00000000000..65018a8083e --- /dev/null +++ b/ui/org.eclipse.pde.ui/src/org/eclipse/pde/internal/ui/shared/target/RepositoryLocationWizard.java @@ -0,0 +1,75 @@ +/******************************************************************************* + * Copyright (c) 2023 Christoph Läubrich and others. + * + * 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: + * Christoph Läubrich - initial API and implementation + *******************************************************************************/ +package org.eclipse.pde.internal.ui.shared.target; + +import org.eclipse.jface.wizard.Wizard; +import org.eclipse.pde.core.target.ITargetDefinition; +import org.eclipse.pde.core.target.ITargetLocation; +import org.eclipse.pde.internal.core.target.RepositoryBundleContainer; +import org.eclipse.pde.ui.target.ITargetLocationWizard; + +public class RepositoryLocationWizard extends Wizard implements ITargetLocationWizard { + + private EditRepositoryContainerPage repositoryPage; + private ITargetLocation wizardLocation; + private ITargetDefinition target; + private RepositoryBundleContainer bundleContainer; + private SelectRepositoryContentPage selectionPage; + + public RepositoryLocationWizard() { + setNeedsProgressMonitor(true); + } + + @Override + public void setTarget(ITargetDefinition target) { + this.target = target; + } + + @Override + public void addPages() { + addPage(repositoryPage = new EditRepositoryContainerPage(bundleContainer)); + addPage(selectionPage = new SelectRepositoryContentPage(repositoryPage)); + + setWindowTitle(repositoryPage.getDefaultTitle()); + } + + @Override + public ITargetLocation[] getLocations() { + if (wizardLocation == null) { + return new ITargetLocation[0]; + } + return new ITargetLocation[] { wizardLocation }; + } + + @Override + public boolean performFinish() { + wizardLocation = selectionPage.getBundleContainer(); + if (target != null && bundleContainer != null) { + ITargetLocation[] locations = target.getTargetLocations(); + for (int i = 0; i < locations.length; i++) { + ITargetLocation location = locations[i]; + if (location == bundleContainer) { + locations[i] = wizardLocation; + } + } + target.setTargetLocations(locations); + } + return true; + } + + public void setBundleContainer(RepositoryBundleContainer bundleContainer) { + this.bundleContainer = bundleContainer; + } + +} diff --git a/ui/org.eclipse.pde.ui/src/org/eclipse/pde/internal/ui/shared/target/SelectRepositoryContentPage.java b/ui/org.eclipse.pde.ui/src/org/eclipse/pde/internal/ui/shared/target/SelectRepositoryContentPage.java new file mode 100644 index 00000000000..c1646697a0f --- /dev/null +++ b/ui/org.eclipse.pde.ui/src/org/eclipse/pde/internal/ui/shared/target/SelectRepositoryContentPage.java @@ -0,0 +1,192 @@ +/******************************************************************************* + * Copyright (c) 2023 Christoph Läubrich and others. + * + * 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: + * Christoph Läubrich - initial API and implementation + *******************************************************************************/ +package org.eclipse.pde.internal.ui.shared.target; + +import java.lang.reflect.InvocationTargetException; +import java.util.Collection; +import java.util.HashSet; +import java.util.List; +import java.util.Set; +import java.util.concurrent.ConcurrentHashMap; + +import org.eclipse.core.runtime.CoreException; +import org.eclipse.jface.viewers.ArrayContentProvider; +import org.eclipse.jface.viewers.CheckStateChangedEvent; +import org.eclipse.jface.viewers.CheckboxTableViewer; +import org.eclipse.jface.viewers.ICheckStateListener; +import org.eclipse.jface.viewers.ICheckStateProvider; +import org.eclipse.jface.viewers.LabelProvider; +import org.eclipse.jface.wizard.WizardPage; +import org.eclipse.pde.core.target.ITargetLocation; +import org.eclipse.pde.internal.core.target.RepositoryBundleContainer; +import org.eclipse.pde.internal.ui.PDEPluginImages; +import org.eclipse.swt.SWT; +import org.eclipse.swt.graphics.Image; +import org.eclipse.swt.widgets.Composite; +import org.osgi.resource.Capability; +import org.osgi.resource.Requirement; +import org.osgi.resource.Resource; + +import aQute.bnd.osgi.repository.ResourcesRepository; +import aQute.bnd.osgi.resource.CapReqBuilder; +import aQute.bnd.osgi.resource.ResourceUtils; +import aQute.bnd.osgi.resource.ResourceUtils.IdentityCapability; + +public class SelectRepositoryContentPage extends WizardPage implements IEditBundleContainerPage { + + private EditRepositoryContainerPage repositoryPage; + private String lastLocation; + private CheckboxTableViewer viewer; + private Collection requirements; + private Set selected = ConcurrentHashMap.newKeySet(); + + protected SelectRepositoryContentPage(EditRepositoryContainerPage repositoryPage) { + super("SelectRepositoryContentPage"); //$NON-NLS-1$ + this.repositoryPage = repositoryPage; + setTitle(Messages.SelectRepositoryContentPage_Title); + setDescription(Messages.SelectRepositoryContentPage_Description); + } + + @Override + public void setVisible(boolean visible) { + if (visible) { + try { + RepositoryBundleContainer container = repositoryPage.getBundleContainer(); + if (requirements == null) { + // only init the requirements once... + requirements = new HashSet<>(container.getRequirements()); + } + String location = container.getLocation(true); + if (lastLocation != location) { + // Load the repository!! + getContainer().run(true, true, monitor -> { + try { + ResourcesRepository repository = container.getRepository(monitor); + selected.clear(); + List resources = repository.getResources(); + repository.findProviders(requirements).values().stream().flatMap(Collection::stream) + .map(Capability::getResource).distinct().forEach(selected::add); + if (viewer != null) { + viewer.getControl().getDisplay().execute(() -> { + if (viewer.getControl().isDisposed()) { + return; + } + viewer.setInput(resources); + }); + } + } catch (CoreException e) { + throw new InvocationTargetException(e); + } + }); + } + setErrorMessage(null); + } catch (CoreException e) { + setErrorMessage(e.getStatus().getMessage()); + } catch (InvocationTargetException e) { + setErrorMessage(e.getMessage()); + } catch (InterruptedException e) { + return; + } + } + super.setVisible(visible); + } + + @Override + public void createControl(Composite parent) { + + viewer = CheckboxTableViewer.newCheckList(parent, SWT.NONE); + viewer.setCheckStateProvider(new ICheckStateProvider() { + + @Override + public boolean isGrayed(Object element) { + return false; + } + + @Override + public boolean isChecked(Object element) { + if (element instanceof Resource resource) { + return selected.contains(resource); + } + return false; + } + }); + viewer.setContentProvider(ArrayContentProvider.getInstance()); + viewer.setLabelProvider(new LabelProvider() { + private Image pluginImage; + + @Override + public String getText(Object element) { + if (element instanceof Resource resource) { + return resource.toString(); + } + return ""; //$NON-NLS-1$ + } + + @Override + public Image getImage(Object element) { + if (element instanceof Resource resource) { + if (ResourceUtils.getBundleCapability(resource) != null) { + if (pluginImage == null) { + pluginImage = PDEPluginImages.DESC_PLUGIN_OBJ.createImage(); + viewer.getControl().addDisposeListener(e -> pluginImage.dispose()); + } + return pluginImage; + } + } + return null; + } + }); + viewer.addCheckStateListener(new ICheckStateListener() { + + @Override + public void checkStateChanged(CheckStateChangedEvent event) { + Object element = event.getElement(); + if (element instanceof Resource resource) { + Requirement requirement = getRequirement(resource); + if (requirement != null) { + if (event.getChecked()) { + selected.add(resource); + requirements.add(requirement); + } else { + selected.remove(resource); + requirements.remove(requirement); + } + } + } + } + }); + setControl(viewer.getControl()); + } + + protected Requirement getRequirement(Resource resource) { + IdentityCapability identity = ResourceUtils.getIdentityCapability(resource); + String v = identity.version().toString(); + return CapReqBuilder.createSimpleRequirement(identity.getNamespace(), identity.osgi_identity(), + String.format("[%s,%s]", v, v)) //$NON-NLS-1$ + .setResource(resource).buildRequirement(); + } + + @Override + public ITargetLocation getBundleContainer() { + RepositoryBundleContainer container = repositoryPage.getBundleContainer(); + return new RepositoryBundleContainer(container.getUri(), + requirements == null ? container.getRequirements() : List.copyOf(requirements)); + } + + @Override + public void storeSettings() { + + } + +} diff --git a/ui/org.eclipse.pde.ui/src/org/eclipse/pde/internal/ui/shared/target/messages.properties b/ui/org.eclipse.pde.ui/src/org/eclipse/pde/internal/ui/shared/target/messages.properties index 83a8650ae7e..84a8f4dee47 100644 --- a/ui/org.eclipse.pde.ui/src/org/eclipse/pde/internal/ui/shared/target/messages.properties +++ b/ui/org.eclipse.pde.ui/src/org/eclipse/pde/internal/ui/shared/target/messages.properties @@ -143,5 +143,10 @@ UpdateTargetJob_UpdateJobName=Update Target Definition UpdateTargetJob_UpdatingTarget=Updating Target EditTargetContainerPage_Add_Title=Create target reference EditTargetContainerPage_Edit_Title=Edit target reference -EditTargetContainerPage_Message=Please enter an URI to the target to be referenced -EditTargetContainerPage_Not_A_File={0} is not a file \ No newline at end of file +EditTargetContainerPage_Message=Please enter a URI to the target to be referenced +EditTargetContainerPage_Not_A_File={0} is not a file +EditRepositoryContainerPage_Message=Please enter a URI that points to the repository +EditRepositoryContainerPage_Add_Title=Create OSGi Repository Location +EditRepositoryContainerPage_Edit_Title=Edit OSGi Repository Location +SelectRepositoryContentPage_Title=Select Content +SelectRepositoryContentPage_Description=Select the content that should be included in this location \ No newline at end of file From daecf47fd3f81fbe0aa3e0bce9adc98d86ee3552 Mon Sep 17 00:00:00 2001 From: Hannes Wellmann Date: Tue, 11 Jul 2023 18:57:31 +0200 Subject: [PATCH 08/18] Various XML processing simplifications - Inline SAXParserWrapper - Remove unused code from PDEXMLHelper - Use XMLProcessorFactory from eclipse.platform in favor of a own one --- .../ApiToolingApiFreezeAntTaskTests.java | 4 +- .../tests/ApiToolingApiuseAntTaskTests.java | 4 +- .../tests/ApiToolingCompareAntTaskTests.java | 4 +- .../internal/actions/ExportSessionAction.java | 4 +- .../api/tools/internal/APIFileGenerator.java | 25 +-- .../tools/internal/ApiBaselineManager.java | 37 ++-- .../tools/internal/model/BundleComponent.java | 25 +-- .../internal/search/MissingRefParser.java | 3 +- .../tools/internal/search/SearchMessages.java | 2 - .../internal/search/UseReportConverter.java | 21 +- .../tools/internal/search/UseScanParser.java | 24 +-- .../search/XmlReferenceDescriptorWriter.java | 4 +- .../internal/search/XmlSearchReporter.java | 4 +- .../internal/search/searchmessages.properties | 2 - .../pde/api/tools/internal/util/Util.java | 37 ++-- .../APIDeprecationReportConversionTask.java | 12 +- .../tasks/APIFreezeReportConversionTask.java | 12 +- .../tasks/AnalysisReportConversionTask.java | 20 +- .../api/tools/internal/tasks/Messages.java | 2 - .../tools/internal/tasks/messages.properties | 2 - .../ds/core/builders/DefaultSAXParser.java | 8 +- .../ds/core/builders/XMLErrorReporter.java | 5 +- .../pde/internal/core/AbstractModel.java | 4 +- .../pde/internal/core/PDEAuxiliaryState.java | 14 +- .../pde/internal/core/XMLDefaultHandler.java | 5 +- .../core/builders/BuildErrorReporter.java | 9 +- .../core/builders/DefaultSAXParser.java | 7 +- .../core/builders/XMLErrorReporter.java | 4 +- .../core/exports/FeatureExportOperation.java | 14 +- .../core/plugin/AbstractExtensions.java | 15 +- .../pde/internal/core/plugin/PluginBase.java | 11 - .../internal/core/plugin/PluginHandler.java | 5 +- .../pde/internal/core/schema/Schema.java | 8 +- .../core/target/IUBundleContainer.java | 11 +- .../core/target/IULocationFactory.java | 9 +- .../target/RepositoryBundleContainer.java | 6 +- .../target/RepositoryLocationFactory.java | 5 +- .../core/target/TargetDefinition.java | 10 +- .../TargetDefinitionPersistenceHelper.java | 11 +- .../target/TargetPersistence38Helper.java | 7 +- .../target/TargetRefrenceLocationFactory.java | 9 +- .../configurator/ConfigurationParser.java | 13 +- .../update/configurator/FeatureParser.java | 22 +- .../configurator/PlatformConfiguration.java | 8 +- .../pde/internal/core/util/PDEXMLHelper.java | 100 ++------- .../core/util/PDEXmlProcessorFactory.java | 197 ------------------ .../internal/core/util/SAXParserWrapper.java | 49 ----- .../pde/internal/core/util/SchemaUtil.java | 6 +- .../core/ant/ConvertSchemaToHTML.java | 5 +- .../core/text/AbstractEditingModel.java | 3 +- .../internal/core/text/XMLEditingModel.java | 9 +- .../internal/PDEXmlProcessorFactoryTest.java | 43 ++-- .../internal/feature/FeatureDataTestCase.java | 4 +- .../parts/SchemaTraversePerfTest.java | 4 +- .../tests/target/IUBundleContainerTests.java | 4 +- .../ui/tests/util/xml/ALLXMLUtilTests.java | 24 --- .../tests/util/xml/ParserWrapperTestCase.java | 125 ----------- .../wizards/exports/FeatureExportWizard.java | 5 +- .../wizards/exports/PluginExportWizard.java | 5 +- 59 files changed, 244 insertions(+), 807 deletions(-) delete mode 100644 ui/org.eclipse.pde.core/src/org/eclipse/pde/internal/core/util/PDEXmlProcessorFactory.java delete mode 100644 ui/org.eclipse.pde.core/src/org/eclipse/pde/internal/core/util/SAXParserWrapper.java delete mode 100644 ui/org.eclipse.pde.ui.tests/src/org/eclipse/pde/ui/tests/util/xml/ALLXMLUtilTests.java delete mode 100644 ui/org.eclipse.pde.ui.tests/src/org/eclipse/pde/ui/tests/util/xml/ParserWrapperTestCase.java diff --git a/apitools/org.eclipse.pde.api.tools.tests/src/org/eclipse/pde/api/tools/anttasks/tests/ApiToolingApiFreezeAntTaskTests.java b/apitools/org.eclipse.pde.api.tools.tests/src/org/eclipse/pde/api/tools/anttasks/tests/ApiToolingApiFreezeAntTaskTests.java index df48aa177dd..51d97f24496 100644 --- a/apitools/org.eclipse.pde.api.tools.tests/src/org/eclipse/pde/api/tools/anttasks/tests/ApiToolingApiFreezeAntTaskTests.java +++ b/apitools/org.eclipse.pde.api.tools.tests/src/org/eclipse/pde/api/tools/anttasks/tests/ApiToolingApiFreezeAntTaskTests.java @@ -24,10 +24,10 @@ import javax.xml.parsers.DocumentBuilder; import javax.xml.parsers.ParserConfigurationException; +import org.eclipse.core.internal.runtime.XmlProcessorFactory; import org.eclipse.core.resources.IFile; import org.eclipse.core.resources.IFolder; import org.eclipse.core.runtime.CoreException; -import org.eclipse.pde.internal.core.util.PDEXmlProcessorFactory; import org.junit.Test; import org.w3c.dom.Document; import org.w3c.dom.Node; @@ -63,7 +63,7 @@ private void runTaskAndVerify(String resourceName) throws Exception, CoreExcepti IFile reportFile = buildFolder.getFile("report.xml"); //$NON-NLS-1$ assertTrue("report.xml must exist", reportFile.exists()); //$NON-NLS-1$ InputSource is = new InputSource(reportFile.getContents()); - DocumentBuilder db = PDEXmlProcessorFactory.createDocumentBuilderWithErrorOnDOCTYPE(); + DocumentBuilder db = XmlProcessorFactory.createDocumentBuilderWithErrorOnDOCTYPE(); Document doc = db.parse(is); NodeList elems = doc.getElementsByTagName("delta"); //$NON-NLS-1$ boolean found = false; diff --git a/apitools/org.eclipse.pde.api.tools.tests/src/org/eclipse/pde/api/tools/anttasks/tests/ApiToolingApiuseAntTaskTests.java b/apitools/org.eclipse.pde.api.tools.tests/src/org/eclipse/pde/api/tools/anttasks/tests/ApiToolingApiuseAntTaskTests.java index 808870f866d..2f4c9e24cc0 100644 --- a/apitools/org.eclipse.pde.api.tools.tests/src/org/eclipse/pde/api/tools/anttasks/tests/ApiToolingApiuseAntTaskTests.java +++ b/apitools/org.eclipse.pde.api.tools.tests/src/org/eclipse/pde/api/tools/anttasks/tests/ApiToolingApiuseAntTaskTests.java @@ -24,10 +24,10 @@ import javax.xml.parsers.DocumentBuilder; import javax.xml.parsers.ParserConfigurationException; +import org.eclipse.core.internal.runtime.XmlProcessorFactory; import org.eclipse.core.resources.IFolder; import org.eclipse.core.resources.IResource; import org.eclipse.core.runtime.CoreException; -import org.eclipse.pde.internal.core.util.PDEXmlProcessorFactory; import org.junit.Test; import org.w3c.dom.Document; import org.w3c.dom.NodeList; @@ -66,7 +66,7 @@ private IFolder runTaskAndVerify(String resourceName) throws Exception, CoreExce public void test1() throws Exception { IFolder reportFolder = runTaskAndVerify("test1"); //$NON-NLS-1$ InputSource is = new InputSource(reportFolder.getFile("not_searched.xml").getContents()); //$NON-NLS-1$ - DocumentBuilder db = PDEXmlProcessorFactory.createDocumentBuilderWithErrorOnDOCTYPE(); + DocumentBuilder db = XmlProcessorFactory.createDocumentBuilderWithErrorOnDOCTYPE(); Document doc = db.parse(is); NodeList elems = doc.getElementsByTagName("component"); //$NON-NLS-1$ diff --git a/apitools/org.eclipse.pde.api.tools.tests/src/org/eclipse/pde/api/tools/anttasks/tests/ApiToolingCompareAntTaskTests.java b/apitools/org.eclipse.pde.api.tools.tests/src/org/eclipse/pde/api/tools/anttasks/tests/ApiToolingCompareAntTaskTests.java index 3876e78b9e7..05beea6b9ee 100644 --- a/apitools/org.eclipse.pde.api.tools.tests/src/org/eclipse/pde/api/tools/anttasks/tests/ApiToolingCompareAntTaskTests.java +++ b/apitools/org.eclipse.pde.api.tools.tests/src/org/eclipse/pde/api/tools/anttasks/tests/ApiToolingCompareAntTaskTests.java @@ -22,9 +22,9 @@ import javax.xml.parsers.DocumentBuilder; import javax.xml.parsers.ParserConfigurationException; +import org.eclipse.core.internal.runtime.XmlProcessorFactory; import org.eclipse.core.resources.IFolder; import org.eclipse.core.runtime.CoreException; -import org.eclipse.pde.internal.core.util.PDEXmlProcessorFactory; import org.junit.Test; import org.w3c.dom.Document; import org.w3c.dom.NodeList; @@ -60,7 +60,7 @@ private void runTaskAndVerify(String resourceName) throws Exception, CoreExcepti assertTrue("report folder must exist", folder.exists()); //$NON-NLS-1$ assertTrue("report xml must exist", folder.getFile("compare.xml").exists()); //$NON-NLS-1$ //$NON-NLS-2$ InputSource is = new InputSource(folder.getFile("compare.xml").getContents()); //$NON-NLS-1$ - DocumentBuilder db = PDEXmlProcessorFactory.createDocumentBuilderWithErrorOnDOCTYPE(); + DocumentBuilder db = XmlProcessorFactory.createDocumentBuilderWithErrorOnDOCTYPE(); Document doc = db.parse(is); NodeList elems = doc.getElementsByTagName("delta"); //$NON-NLS-1$ boolean found = false; diff --git a/apitools/org.eclipse.pde.api.tools.ui/src/org/eclipse/pde/api/tools/ui/internal/actions/ExportSessionAction.java b/apitools/org.eclipse.pde.api.tools.ui/src/org/eclipse/pde/api/tools/ui/internal/actions/ExportSessionAction.java index ad13db74ab1..986ea4ee42e 100644 --- a/apitools/org.eclipse.pde.api.tools.ui/src/org/eclipse/pde/api/tools/ui/internal/actions/ExportSessionAction.java +++ b/apitools/org.eclipse.pde.api.tools.ui/src/org/eclipse/pde/api/tools/ui/internal/actions/ExportSessionAction.java @@ -27,6 +27,7 @@ import javax.xml.transform.stream.StreamResult; import javax.xml.transform.stream.StreamSource; +import org.eclipse.core.internal.runtime.XmlProcessorFactory; import org.eclipse.core.runtime.CoreException; import org.eclipse.core.runtime.IProgressMonitor; import org.eclipse.core.runtime.IStatus; @@ -45,7 +46,6 @@ import org.eclipse.pde.api.tools.ui.internal.ApiUIPlugin; import org.eclipse.pde.api.tools.ui.internal.IApiToolsConstants; import org.eclipse.pde.api.tools.ui.internal.views.APIToolingView; -import org.eclipse.pde.internal.core.util.PDEXmlProcessorFactory; /** * Drop-down action to select the active session. @@ -155,7 +155,7 @@ protected IStatus run(IProgressMonitor monitor) { } writer = new BufferedWriter(new FileWriter(reportFile)); Result result = new StreamResult(writer); - TransformerFactory f = PDEXmlProcessorFactory.createTransformerFactoryWithErrorOnDOCTYPE(); + TransformerFactory f = XmlProcessorFactory.createTransformerFactoryWithErrorOnDOCTYPE(); Transformer trans = f.newTransformer(xsltSource); trans.transform(xmlSource, result); } catch (TransformerException | IOException e) { diff --git a/apitools/org.eclipse.pde.api.tools/src/org/eclipse/pde/api/tools/internal/APIFileGenerator.java b/apitools/org.eclipse.pde.api.tools/src/org/eclipse/pde/api/tools/internal/APIFileGenerator.java index 377907f9e87..cfb266779dd 100644 --- a/apitools/org.eclipse.pde.api.tools/src/org/eclipse/pde/api/tools/internal/APIFileGenerator.java +++ b/apitools/org.eclipse.pde.api.tools/src/org/eclipse/pde/api/tools/internal/APIFileGenerator.java @@ -14,7 +14,6 @@ package org.eclipse.pde.api.tools.internal; import java.io.BufferedInputStream; -import java.io.BufferedReader; import java.io.File; import java.io.FileFilter; import java.io.FileInputStream; @@ -46,7 +45,6 @@ import org.eclipse.pde.api.tools.internal.provisional.model.IApiTypeContainer; import org.eclipse.pde.api.tools.internal.provisional.scanner.TagScanner; import org.eclipse.pde.api.tools.internal.util.Util; -import org.eclipse.pde.internal.core.util.PDEXmlProcessorFactory; import org.osgi.framework.BundleException; import org.osgi.framework.Constants; import org.xml.sax.Attributes; @@ -458,27 +456,16 @@ private boolean isAPIToolsNature(File dotProjectFile) { * @return true if it contains a source extension point, false otherwise */ private boolean containsAPIToolsNature(String pluginXMLContents) { - SAXParser saxParser = null; - try { - saxParser = PDEXmlProcessorFactory.createSAXParserIgnoringDOCTYPE(); - } catch (ParserConfigurationException | SAXException e) { - // ignore - } - - if (saxParser == null) { - return false; - } - - // Parse - InputSource inputSource = new InputSource(new BufferedReader(new StringReader(pluginXMLContents))); try { + @SuppressWarnings("restriction") + SAXParser saxParser = org.eclipse.core.internal.runtime.XmlProcessorFactory + .createSAXParserIgnoringDOCTYPE(); APIToolsNatureDefaultHandler defaultHandler = new APIToolsNatureDefaultHandler(); - saxParser.parse(inputSource, defaultHandler); + saxParser.parse(new InputSource(new StringReader(pluginXMLContents)), defaultHandler); return defaultHandler.isAPIToolsNature(); - } catch (SAXException | IOException e) { - // ignore + } catch (SAXException | IOException | ParserConfigurationException e) { + return false; } - return false; } } \ No newline at end of file diff --git a/apitools/org.eclipse.pde.api.tools/src/org/eclipse/pde/api/tools/internal/ApiBaselineManager.java b/apitools/org.eclipse.pde.api.tools/src/org/eclipse/pde/api/tools/internal/ApiBaselineManager.java index c60ec2e6927..b5cc11bac6b 100644 --- a/apitools/org.eclipse.pde.api.tools/src/org/eclipse/pde/api/tools/internal/ApiBaselineManager.java +++ b/apitools/org.eclipse.pde.api.tools/src/org/eclipse/pde/api/tools/internal/ApiBaselineManager.java @@ -63,7 +63,6 @@ import org.eclipse.pde.core.plugin.ModelEntry; import org.eclipse.pde.core.plugin.PluginRegistry; import org.eclipse.pde.internal.core.DependencyManager; -import org.eclipse.pde.internal.core.util.PDEXmlProcessorFactory; import org.w3c.dom.Document; import org.w3c.dom.Element; import org.w3c.dom.NodeList; @@ -373,7 +372,7 @@ private void writeBaselineDescription(IApiBaseline baseline, OutputStream stream try { stream.write(xml.getBytes(StandardCharsets.UTF_8)); } catch (IOException e) { - abort("Error writing pofile descrition", e); //$NON-NLS-1$ + throw new CoreException(Status.error("Error writing pofile descrition", e)); //$NON-NLS-1$ } } @@ -422,18 +421,6 @@ private String getProfileXML(IApiBaseline baseline) throws CoreException { return Util.serializeDocument(document); } - /** - * Throws a core exception with the given message and underlying exception, - * if any. - * - * @param message error message - * @param e underlying exception or null - * @throws CoreException - */ - private static void abort(String message, Throwable e) throws CoreException { - throw new CoreException(Status.error(message, e)); - } - /** * Restore a baseline from the given input stream (persisted baseline). * @@ -444,14 +431,8 @@ private static void abort(String message, Throwable e) throws CoreException { */ public IApiComponent[] readBaselineComponents(ApiBaseline baseline, InputStream stream) throws CoreException { long start = System.currentTimeMillis(); - DocumentBuilder parser = null; + DocumentBuilder parser = getConfiguredParser(); IApiComponent[] restored = null; - try { - parser = PDEXmlProcessorFactory.createDocumentBuilderWithErrorOnDOCTYPE(); - parser.setErrorHandler(new DefaultHandler()); - } catch (ParserConfigurationException | FactoryConfigurationError e) { - abort("Error restoring API baseline", e); //$NON-NLS-1$ - } try { Document document = parser.parse(stream); Element root = document.getDocumentElement(); @@ -505,7 +486,7 @@ public IApiComponent[] readBaselineComponents(ApiBaseline baseline, InputStream restored = components.toArray(new IApiComponent[components.size()]); } } catch (IOException | SAXException e) { - abort("Error restoring API baseline", e); //$NON-NLS-1$ + throw new CoreException(Status.error("Error restoring API baseline", e)); //$NON-NLS-1$ } if (ApiPlugin.DEBUG_BASELINE_MANAGER) { System.out.println("Time to restore a persisted baseline : " + (System.currentTimeMillis() - start) + "ms"); //$NON-NLS-1$ //$NON-NLS-2$ @@ -513,6 +494,18 @@ public IApiComponent[] readBaselineComponents(ApiBaseline baseline, InputStream return restored; } + private static DocumentBuilder getConfiguredParser() throws CoreException { + try { + @SuppressWarnings("restriction") + DocumentBuilder parser = org.eclipse.core.internal.runtime.XmlProcessorFactory + .createDocumentBuilderWithErrorOnDOCTYPE(); + parser.setErrorHandler(new DefaultHandler()); + return parser; + } catch (ParserConfigurationException | FactoryConfigurationError e) { + throw new CoreException(Status.error("Error restoring API baseline", e)); //$NON-NLS-1$ + } + } + @Override public void saving(ISaveContext context) throws CoreException { if (!fNeedsSaving) { diff --git a/apitools/org.eclipse.pde.api.tools/src/org/eclipse/pde/api/tools/internal/model/BundleComponent.java b/apitools/org.eclipse.pde.api.tools/src/org/eclipse/pde/api/tools/internal/model/BundleComponent.java index d9a462fb164..7f1bbe469cb 100644 --- a/apitools/org.eclipse.pde.api.tools/src/org/eclipse/pde/api/tools/internal/model/BundleComponent.java +++ b/apitools/org.eclipse.pde.api.tools/src/org/eclipse/pde/api/tools/internal/model/BundleComponent.java @@ -13,7 +13,6 @@ *******************************************************************************/ package org.eclipse.pde.api.tools.internal.model; -import java.io.BufferedReader; import java.io.File; import java.io.FileInputStream; import java.io.FileOutputStream; @@ -77,7 +76,6 @@ import org.eclipse.pde.api.tools.internal.util.Util; import org.eclipse.pde.internal.core.TargetWeaver; import org.eclipse.pde.internal.core.util.ManifestUtils; -import org.eclipse.pde.internal.core.util.PDEXmlProcessorFactory; import org.osgi.framework.BundleException; import org.osgi.framework.Constants; import org.osgi.framework.Version; @@ -1066,27 +1064,16 @@ private static boolean isSourceComponent(Map manifest, File loca * @return true if it contains a source extension point, false otherwise */ private static boolean containsSourceExtensionPoint(String pluginXMLContents) { - SAXParser saxParser = null; - try { - saxParser = PDEXmlProcessorFactory.createSAXParserWithErrorOnDOCTYPE(); - } catch (ParserConfigurationException | SAXException e) { - // ignore - } - - if (saxParser == null) { - return false; - } - - // Parse - InputSource inputSource = new InputSource(new BufferedReader(new StringReader(pluginXMLContents))); try { + @SuppressWarnings("restriction") + SAXParser saxParser = org.eclipse.core.internal.runtime.XmlProcessorFactory + .createSAXParserWithErrorOnDOCTYPE(); SourceDefaultHandler defaultHandler = new SourceDefaultHandler(); - saxParser.parse(inputSource, defaultHandler); + saxParser.parse(new InputSource(new StringReader(pluginXMLContents)), defaultHandler); return defaultHandler.isSource(); - } catch (SAXException | IOException e) { - // ignore + } catch (SAXException | IOException | ParserConfigurationException e) { + return false; } - return false; } @Override diff --git a/apitools/org.eclipse.pde.api.tools/src/org/eclipse/pde/api/tools/internal/search/MissingRefParser.java b/apitools/org.eclipse.pde.api.tools/src/org/eclipse/pde/api/tools/internal/search/MissingRefParser.java index f0423499002..3eb781720fd 100644 --- a/apitools/org.eclipse.pde.api.tools/src/org/eclipse/pde/api/tools/internal/search/MissingRefParser.java +++ b/apitools/org.eclipse.pde.api.tools/src/org/eclipse/pde/api/tools/internal/search/MissingRefParser.java @@ -118,7 +118,8 @@ public void parse(String xmlLocation, MissingRefVisitor visitor) throws Exceptio components = sort(components); visitor.visitScan(); - SAXParser parser = getParser(); + @SuppressWarnings("restriction") + SAXParser parser = org.eclipse.core.internal.runtime.XmlProcessorFactory.createSAXParserWithErrorOnDOCTYPE(); // Treat each top level directory as a producer component for (File component : components) { if (component.isDirectory()) { diff --git a/apitools/org.eclipse.pde.api.tools/src/org/eclipse/pde/api/tools/internal/search/SearchMessages.java b/apitools/org.eclipse.pde.api.tools/src/org/eclipse/pde/api/tools/internal/search/SearchMessages.java index b7e0c302485..ab9cd7aa34c 100644 --- a/apitools/org.eclipse.pde.api.tools/src/org/eclipse/pde/api/tools/internal/search/SearchMessages.java +++ b/apitools/org.eclipse.pde.api.tools/src/org/eclipse/pde/api/tools/internal/search/SearchMessages.java @@ -104,8 +104,6 @@ public class SearchMessages extends NLS { public static String UseReportConverter_scan_date; public static String UseReportConverter_scan_details; public static String UseReportConverter_scope_pattern; - public static String UseReportConverter_se_error_parser_handle; - public static String UseReportConverter_pce_error_getting_parser; public static String UseReportConverter_preparing_html_root; public static String UseReportConverter_preparing_report_metadata; public static String UseReportConverter_preparing_xml_root; diff --git a/apitools/org.eclipse.pde.api.tools/src/org/eclipse/pde/api/tools/internal/search/UseReportConverter.java b/apitools/org.eclipse.pde.api.tools/src/org/eclipse/pde/api/tools/internal/search/UseReportConverter.java index 549b0a830d6..32caaf12a4b 100644 --- a/apitools/org.eclipse.pde.api.tools/src/org/eclipse/pde/api/tools/internal/search/UseReportConverter.java +++ b/apitools/org.eclipse.pde.api.tools/src/org/eclipse/pde/api/tools/internal/search/UseReportConverter.java @@ -42,7 +42,6 @@ import javax.xml.transform.Source; import javax.xml.transform.Transformer; import javax.xml.transform.TransformerException; -import javax.xml.transform.TransformerFactory; import javax.xml.transform.stream.StreamResult; import javax.xml.transform.stream.StreamSource; @@ -65,7 +64,6 @@ import org.eclipse.pde.api.tools.internal.provisional.search.IMetadata; import org.eclipse.pde.api.tools.internal.util.Signatures; import org.eclipse.pde.api.tools.internal.util.Util; -import org.eclipse.pde.internal.core.util.PDEXmlProcessorFactory; import org.osgi.framework.Version; import org.w3c.dom.Element; import org.w3c.dom.NamedNodeMap; @@ -738,18 +736,10 @@ protected List parse(IProgressMonitor monitor) throws Exception { * @throws Exception forwarded general exception that can be trapped in Ant * builds */ - SAXParser getParser() throws Exception { + @SuppressWarnings("restriction") + private SAXParser getParser() throws ParserConfigurationException, SAXException { if (this.parser == null) { - try { - this.parser = PDEXmlProcessorFactory.createSAXParserWithErrorOnDOCTYPE(); - } catch (ParserConfigurationException pce) { - throw new Exception(SearchMessages.UseReportConverter_pce_error_getting_parser, pce); - } catch (SAXException se) { - throw new Exception(SearchMessages.UseReportConverter_se_error_parser_handle, se); - } - if (this.parser == null) { - throw new Exception(SearchMessages.could_not_create_sax_parser); - } + this.parser = org.eclipse.core.internal.runtime.XmlProcessorFactory.createSAXParserWithErrorOnDOCTYPE(); } return this.parser; } @@ -819,8 +809,9 @@ protected void applyXSLT(File xsltFile, File xmlfile, File htmloutput) throws Tr protected void applyXSLT(Source xslt, File xmlfile, File htmlfile) throws TransformerException { Source xml = new StreamSource(xmlfile); Result html = new StreamResult(htmlfile); - TransformerFactory factory = PDEXmlProcessorFactory.createTransformerFactoryWithErrorOnDOCTYPE(); - Transformer former = factory.newTransformer(xslt); + @SuppressWarnings("restriction") + Transformer former = org.eclipse.core.internal.runtime.XmlProcessorFactory + .createTransformerFactoryWithErrorOnDOCTYPE().newTransformer(xslt); former.transform(xml, html); } diff --git a/apitools/org.eclipse.pde.api.tools/src/org/eclipse/pde/api/tools/internal/search/UseScanParser.java b/apitools/org.eclipse.pde.api.tools/src/org/eclipse/pde/api/tools/internal/search/UseScanParser.java index 1ed33e3d82f..2fb02a1ae11 100644 --- a/apitools/org.eclipse.pde.api.tools/src/org/eclipse/pde/api/tools/internal/search/UseScanParser.java +++ b/apitools/org.eclipse.pde.api.tools/src/org/eclipse/pde/api/tools/internal/search/UseScanParser.java @@ -22,7 +22,6 @@ import java.util.Collections; import java.util.List; -import javax.xml.parsers.ParserConfigurationException; import javax.xml.parsers.SAXParser; import org.eclipse.core.runtime.IProgressMonitor; @@ -35,7 +34,6 @@ import org.eclipse.pde.api.tools.internal.provisional.descriptors.IComponentDescriptor; import org.eclipse.pde.api.tools.internal.provisional.descriptors.IMemberDescriptor; import org.eclipse.pde.api.tools.internal.util.Util; -import org.eclipse.pde.internal.core.util.PDEXmlProcessorFactory; import org.xml.sax.Attributes; import org.xml.sax.SAXException; import org.xml.sax.helpers.DefaultHandler; @@ -244,7 +242,9 @@ public void parse(String xmlLocation, IProgressMonitor monitor, UseScanVisitor u localmonitor.setWorkRemaining(referees.length); visitor.visitScan(); try { - SAXParser parser = getParser(); + @SuppressWarnings("restriction") + SAXParser parser = org.eclipse.core.internal.runtime.XmlProcessorFactory + .createSAXParserWithErrorOnDOCTYPE(); // Treat each top level directory as a producer component for (File referee : referees) { if (referee.isDirectory()) { @@ -299,24 +299,6 @@ public void parse(String xmlLocation, IProgressMonitor monitor, UseScanVisitor u } } - /** - * Returns a parser - * - * @return default parser - * @throws Exception forwarded general exception that can be trapped in Ant - * builds - */ - SAXParser getParser() throws Exception { - try { - return PDEXmlProcessorFactory.createSAXParserWithErrorOnDOCTYPE(); - - } catch (ParserConfigurationException pce) { - throw new Exception(SearchMessages.UseReportConverter_pce_error_getting_parser, pce); - } catch (SAXException se) { - throw new Exception(SearchMessages.UseReportConverter_se_error_parser_handle, se); - } - } - /** * @return the referencingComponent or null */ diff --git a/apitools/org.eclipse.pde.api.tools/src/org/eclipse/pde/api/tools/internal/search/XmlReferenceDescriptorWriter.java b/apitools/org.eclipse.pde.api.tools/src/org/eclipse/pde/api/tools/internal/search/XmlReferenceDescriptorWriter.java index 7510d089bee..c72065ce5fa 100644 --- a/apitools/org.eclipse.pde.api.tools/src/org/eclipse/pde/api/tools/internal/search/XmlReferenceDescriptorWriter.java +++ b/apitools/org.eclipse.pde.api.tools/src/org/eclipse/pde/api/tools/internal/search/XmlReferenceDescriptorWriter.java @@ -46,7 +46,6 @@ import org.eclipse.pde.api.tools.internal.provisional.model.IApiMember; import org.eclipse.pde.api.tools.internal.util.Signatures; import org.eclipse.pde.api.tools.internal.util.Util; -import org.eclipse.pde.internal.core.util.PDEXmlProcessorFactory; import org.w3c.dom.Document; import org.w3c.dom.Element; import org.w3c.dom.NodeList; @@ -84,10 +83,11 @@ public class XmlReferenceDescriptorWriter { * to write the reports to * @param debug if debugging infos should be written out to the console */ + @SuppressWarnings("restriction") public XmlReferenceDescriptorWriter(String location) { fLocation = location; try { - parser = PDEXmlProcessorFactory.createDocumentBuilderWithErrorOnDOCTYPE(); + parser = org.eclipse.core.internal.runtime.XmlProcessorFactory.createDocumentBuilderWithErrorOnDOCTYPE(); parser.setErrorHandler(new DefaultHandler()); } catch (FactoryConfigurationError | ParserConfigurationException pce) { ApiPlugin.log(pce); diff --git a/apitools/org.eclipse.pde.api.tools/src/org/eclipse/pde/api/tools/internal/search/XmlSearchReporter.java b/apitools/org.eclipse.pde.api.tools/src/org/eclipse/pde/api/tools/internal/search/XmlSearchReporter.java index aa7a2cdbc7a..bfb82c411ce 100644 --- a/apitools/org.eclipse.pde.api.tools/src/org/eclipse/pde/api/tools/internal/search/XmlSearchReporter.java +++ b/apitools/org.eclipse.pde.api.tools/src/org/eclipse/pde/api/tools/internal/search/XmlSearchReporter.java @@ -39,7 +39,6 @@ import org.eclipse.pde.api.tools.internal.provisional.search.IApiSearchReporter; import org.eclipse.pde.api.tools.internal.provisional.search.IMetadata; import org.eclipse.pde.api.tools.internal.util.Util; -import org.eclipse.pde.internal.core.util.PDEXmlProcessorFactory; import org.w3c.dom.Document; import org.w3c.dom.Element; import org.xml.sax.helpers.DefaultHandler; @@ -65,11 +64,12 @@ public class XmlSearchReporter implements IApiSearchReporter { * to write the reports to * @param debug if debugging infos should be written out to the console */ + @SuppressWarnings("restriction") public XmlSearchReporter(String location, boolean debug) { fLocation = location; this.debug = debug; try { - parser = PDEXmlProcessorFactory.createDocumentBuilderWithErrorOnDOCTYPE(); + parser = org.eclipse.core.internal.runtime.XmlProcessorFactory.createDocumentBuilderWithErrorOnDOCTYPE(); parser.setErrorHandler(new DefaultHandler()); } catch (FactoryConfigurationError | ParserConfigurationException pce) { ApiPlugin.log(pce); diff --git a/apitools/org.eclipse.pde.api.tools/src/org/eclipse/pde/api/tools/internal/search/searchmessages.properties b/apitools/org.eclipse.pde.api.tools/src/org/eclipse/pde/api/tools/internal/search/searchmessages.properties index 583fc97a0a9..6baed83d1d4 100644 --- a/apitools/org.eclipse.pde.api.tools/src/org/eclipse/pde/api/tools/internal/search/searchmessages.properties +++ b/apitools/org.eclipse.pde.api.tools/src/org/eclipse/pde/api/tools/internal/search/searchmessages.properties @@ -91,14 +91,12 @@ SkippedComponent_component_was_excluded=This component was excluded from the sea UseReportConverter_scan_date=Date of the Scan: UseReportConverter_scan_details=Scan Details UseReportConverter_scope_pattern=Scope Pattern: -UseReportConverter_se_error_parser_handle=SAXException trying to get handle to the default parser. UseReportConverter_collecting_dir_info=Collecting directory information... UseReportConverter_core_exep_reading_metadata=CoreException parsing XML file: {0} UseReportConverter_coreexception_writing_html_file=CoreException writing html file: {0} UseReportConverter_te_applying_xslt_skipped=Transformer exception applying XSLT to: not_searched.xml UseReportConverter_no_additional_scan_info=No additional scan information is available. UseReportConverter_no_xstl_specified=No XSLT file was specified. -UseReportConverter_pce_error_getting_parser=ParserConfigurationException trying to get handle to the default parser. UseReportConverter_preparing_html_root=Preparing HTML root... UseReportConverter_preparing_report_metadata=Preparing Report Metadata... UseReportConverter_preparing_xml_root=Preparing XML root... diff --git a/apitools/org.eclipse.pde.api.tools/src/org/eclipse/pde/api/tools/internal/util/Util.java b/apitools/org.eclipse.pde.api.tools/src/org/eclipse/pde/api/tools/internal/util/Util.java index 849b0c6c55b..b8ad37a1f89 100644 --- a/apitools/org.eclipse.pde.api.tools/src/org/eclipse/pde/api/tools/internal/util/Util.java +++ b/apitools/org.eclipse.pde.api.tools/src/org/eclipse/pde/api/tools/internal/util/Util.java @@ -104,7 +104,6 @@ import org.eclipse.jdt.core.JavaCore; import org.eclipse.jdt.core.JavaModelException; import org.eclipse.jdt.core.Signature; -import org.eclipse.jdt.internal.compiler.codegen.ConstantPool; import org.eclipse.jdt.internal.core.BinaryType; import org.eclipse.jdt.internal.core.ClassFile; import org.eclipse.jdt.internal.core.CompilationUnit; @@ -140,7 +139,6 @@ import org.eclipse.pde.api.tools.internal.provisional.problems.IApiProblem; import org.eclipse.pde.api.tools.internal.provisional.problems.IApiProblemTypes; import org.eclipse.pde.api.tools.internal.search.SkippedComponent; -import org.eclipse.pde.internal.core.util.PDEXmlProcessorFactory; import org.objectweb.asm.Opcodes; import org.osgi.framework.Version; import org.w3c.dom.Document; @@ -153,7 +151,6 @@ * * @since 1.0.0 */ -@SuppressWarnings("restriction") public final class Util { public static final String DOT_TGZ = ".tgz"; //$NON-NLS-1$ @@ -1769,15 +1766,13 @@ public static boolean isBinaryProject(IProject project) { * @return document * @throws CoreException if unable to create a new document */ + @SuppressWarnings("restriction") public static Document newDocument() throws CoreException { - DocumentBuilder docBuilder = null; try { - docBuilder = PDEXmlProcessorFactory.createDocumentBuilderWithErrorOnDOCTYPE(); + return org.eclipse.core.internal.runtime.XmlProcessorFactory.newDocumentWithErrorOnDOCTYPE(); } catch (ParserConfigurationException e) { throw new CoreException(Status.error("Unable to create new XML document.", e)); //$NON-NLS-1$ } - Document doc = docBuilder.newDocument(); - return doc; } /** @@ -1789,25 +1784,15 @@ public static Document newDocument() throws CoreException { * @throws CoreException if unable to parse the document */ public static Element parseDocument(String document) throws CoreException { - Element root = null; - InputStream stream = null; - try { - DocumentBuilder parser = PDEXmlProcessorFactory.createDocumentBuilderWithErrorOnDOCTYPE(); + try (InputStream stream = new ByteArrayInputStream(document.getBytes(StandardCharsets.UTF_8))) { + @SuppressWarnings("restriction") + DocumentBuilder parser = org.eclipse.core.internal.runtime.XmlProcessorFactory + .createDocumentBuilderWithErrorOnDOCTYPE(); parser.setErrorHandler(new DefaultHandler()); - stream = new ByteArrayInputStream(document.getBytes(StandardCharsets.UTF_8)); - root = parser.parse(stream).getDocumentElement(); + return parser.parse(stream).getDocumentElement(); } catch (ParserConfigurationException | FactoryConfigurationError | SAXException | IOException e) { throw new CoreException(Status.error("Unable to parse XML document.", e)); //$NON-NLS-1$ - } finally { - try { - if (stream != null) { - stream.close(); - } - } catch (IOException e) { - throw new CoreException(Status.error("Unable to parse XML document.", e)); //$NON-NLS-1$ - } } - return root; } /** @@ -1883,7 +1868,9 @@ public static InputStream getInputStreamFromString(String string) { public static String serializeDocument(Document document) throws CoreException { try { ByteArrayOutputStream s = new ByteArrayOutputStream(); - TransformerFactory factory = PDEXmlProcessorFactory.createTransformerFactoryWithErrorOnDOCTYPE(); + @SuppressWarnings("restriction") + TransformerFactory factory = org.eclipse.core.internal.runtime.XmlProcessorFactory + .createTransformerFactoryWithErrorOnDOCTYPE(); Transformer transformer = factory.newTransformer(); transformer.setOutputProperty(OutputKeys.METHOD, "xml"); //$NON-NLS-1$ transformer.setOutputProperty(OutputKeys.INDENT, "yes"); //$NON-NLS-1$ @@ -2397,7 +2384,9 @@ public static String getApiElementType(int type) { } public static boolean isConstructor(String referenceMemberName) { - return Arrays.equals(ConstantPool.Init, referenceMemberName.toCharArray()); + @SuppressWarnings("restriction") + char[] init = org.eclipse.jdt.internal.compiler.codegen.ConstantPool.Init; + return Arrays.equals(init, referenceMemberName.toCharArray()); } public static boolean isManifest(IPath path) { diff --git a/apitools/org.eclipse.pde.api.tools/src_ant/org/eclipse/pde/api/tools/internal/tasks/APIDeprecationReportConversionTask.java b/apitools/org.eclipse.pde.api.tools/src_ant/org/eclipse/pde/api/tools/internal/tasks/APIDeprecationReportConversionTask.java index 11e74449e24..fb813361f31 100644 --- a/apitools/org.eclipse.pde.api.tools/src_ant/org/eclipse/pde/api/tools/internal/tasks/APIDeprecationReportConversionTask.java +++ b/apitools/org.eclipse.pde.api.tools/src_ant/org/eclipse/pde/api/tools/internal/tasks/APIDeprecationReportConversionTask.java @@ -23,7 +23,6 @@ import java.util.List; import java.util.Map; -import javax.xml.parsers.ParserConfigurationException; import javax.xml.parsers.SAXParser; import org.apache.tools.ant.BuildException; @@ -33,7 +32,6 @@ import org.eclipse.pde.api.tools.internal.IApiXmlConstants; import org.eclipse.pde.api.tools.internal.provisional.comparator.IDelta; import org.eclipse.pde.api.tools.internal.util.Util; -import org.eclipse.pde.internal.core.util.PDEXmlProcessorFactory; import org.xml.sax.Attributes; import org.xml.sax.SAXException; import org.xml.sax.helpers.DefaultHandler; @@ -311,15 +309,7 @@ public void execute() throws BuildException { System.out.println("xmlFileLocation : " + this.xmlFileLocation); //$NON-NLS-1$ System.out.println("htmlFileLocation : " + this.htmlFileLocation); //$NON-NLS-1$ } - SAXParser parser = null; - try { - parser = PDEXmlProcessorFactory.createSAXParserWithErrorOnDOCTYPE(); - } catch (ParserConfigurationException | SAXException e) { - e.printStackTrace(); - } - if (parser == null) { - throw new BuildException(Messages.deprecationReportTask_couldNotCreateSAXParser); - } + SAXParser parser = AnalysisReportConversionTask.createSAXParser(); File file = new File(this.xmlFileLocation); if (this.htmlFileLocation == null) { diff --git a/apitools/org.eclipse.pde.api.tools/src_ant/org/eclipse/pde/api/tools/internal/tasks/APIFreezeReportConversionTask.java b/apitools/org.eclipse.pde.api.tools/src_ant/org/eclipse/pde/api/tools/internal/tasks/APIFreezeReportConversionTask.java index ee9500d9dcf..53c956c817a 100644 --- a/apitools/org.eclipse.pde.api.tools/src_ant/org/eclipse/pde/api/tools/internal/tasks/APIFreezeReportConversionTask.java +++ b/apitools/org.eclipse.pde.api.tools/src_ant/org/eclipse/pde/api/tools/internal/tasks/APIFreezeReportConversionTask.java @@ -23,7 +23,6 @@ import java.util.List; import java.util.Map; -import javax.xml.parsers.ParserConfigurationException; import javax.xml.parsers.SAXParser; import org.apache.tools.ant.BuildException; @@ -33,7 +32,6 @@ import org.eclipse.pde.api.tools.internal.IApiXmlConstants; import org.eclipse.pde.api.tools.internal.provisional.comparator.IDelta; import org.eclipse.pde.api.tools.internal.util.Util; -import org.eclipse.pde.internal.core.util.PDEXmlProcessorFactory; import org.xml.sax.Attributes; import org.xml.sax.SAXException; import org.xml.sax.helpers.DefaultHandler; @@ -491,15 +489,7 @@ public void execute() throws BuildException { } } } - SAXParser parser = null; - try { - parser = PDEXmlProcessorFactory.createSAXParserWithErrorOnDOCTYPE(); - } catch (ParserConfigurationException | SAXException e) { - e.printStackTrace(); - } - if (parser == null) { - throw new BuildException(Messages.deltaReportTask_couldNotCreateSAXParser); - } + SAXParser parser = AnalysisReportConversionTask.createSAXParser(); try { ConverterDefaultHandler defaultHandler = new ConverterDefaultHandler(this.debug); parser.parse(file, defaultHandler); diff --git a/apitools/org.eclipse.pde.api.tools/src_ant/org/eclipse/pde/api/tools/internal/tasks/AnalysisReportConversionTask.java b/apitools/org.eclipse.pde.api.tools/src_ant/org/eclipse/pde/api/tools/internal/tasks/AnalysisReportConversionTask.java index c78cedcd7e2..7ccee9bf70f 100644 --- a/apitools/org.eclipse.pde.api.tools/src_ant/org/eclipse/pde/api/tools/internal/tasks/AnalysisReportConversionTask.java +++ b/apitools/org.eclipse.pde.api.tools/src_ant/org/eclipse/pde/api/tools/internal/tasks/AnalysisReportConversionTask.java @@ -34,7 +34,6 @@ import org.eclipse.pde.api.tools.internal.IApiXmlConstants; import org.eclipse.pde.api.tools.internal.provisional.ApiPlugin; import org.eclipse.pde.api.tools.internal.util.Util; -import org.eclipse.pde.internal.core.util.PDEXmlProcessorFactory; import org.xml.sax.Attributes; import org.xml.sax.SAXException; import org.xml.sax.helpers.DefaultHandler; @@ -429,15 +428,7 @@ public void execute() throws BuildException { if (!this.reportsRoot.exists() || !this.reportsRoot.isDirectory()) { throw new BuildException(NLS.bind(Messages.invalid_directory_name, this.xmlReportsLocation)); } - SAXParser parser = null; - try { - parser = PDEXmlProcessorFactory.createSAXParserWithErrorOnDOCTYPE(); - } catch (ParserConfigurationException | SAXException e) { - e.printStackTrace(); - } - if (parser == null) { - throw new BuildException(Messages.could_not_create_sax_parser); - } + SAXParser parser = createSAXParser(); if (this.htmlReportsLocation == null) { this.htmlReportsLocation = this.xmlReportsLocation; @@ -490,6 +481,15 @@ public void execute() throws BuildException { } } + @SuppressWarnings("restriction") + static SAXParser createSAXParser() { + try { + return org.eclipse.core.internal.runtime.XmlProcessorFactory.createSAXParserWithErrorOnDOCTYPE(); + } catch (ParserConfigurationException | SAXException e) { + throw new BuildException(Messages.could_not_create_sax_parser, e); + } + } + private String extractLinkFrom(String fileName) { StringBuilder buffer = new StringBuilder(); buffer.append('.').append(fileName.substring(this.htmlRoot.getAbsolutePath().length()).replace('\\', '/')); diff --git a/apitools/org.eclipse.pde.api.tools/src_ant/org/eclipse/pde/api/tools/internal/tasks/Messages.java b/apitools/org.eclipse.pde.api.tools/src_ant/org/eclipse/pde/api/tools/internal/tasks/Messages.java index 55d8a7b6f46..4b6a41b7962 100644 --- a/apitools/org.eclipse.pde.api.tools/src_ant/org/eclipse/pde/api/tools/internal/tasks/Messages.java +++ b/apitools/org.eclipse.pde.api.tools/src_ant/org/eclipse/pde/api/tools/internal/tasks/Messages.java @@ -29,7 +29,6 @@ public class Messages extends NLS { public static String deltaReportTask_entry_major_version; public static String deltaReportTask_entry_minor_version; public static String deltaReportTask_missingXmlFileLocation; - public static String deltaReportTask_couldNotCreateSAXParser; public static String deltaReportTask_xmlFileLocationShouldHaveAnXMLExtension; public static String deltaReportTask_htmlFileLocationShouldHaveAnHtmlExtension; public static String deltaReportTask_missingXmlFile; @@ -118,7 +117,6 @@ public class Messages extends NLS { public static String ChangedElement; public static String deprecationReportTask_componentEntry; - public static String deprecationReportTask_couldNotCreateSAXParser; public static String deprecationReportTask_endComponentEntry; public static String deprecationReportTask_entry; public static String deprecationReportTask_footer; diff --git a/apitools/org.eclipse.pde.api.tools/src_ant/org/eclipse/pde/api/tools/internal/tasks/messages.properties b/apitools/org.eclipse.pde.api.tools/src_ant/org/eclipse/pde/api/tools/internal/tasks/messages.properties index 215e6409c74..318a3ba60f5 100644 --- a/apitools/org.eclipse.pde.api.tools/src_ant/org/eclipse/pde/api/tools/internal/tasks/messages.properties +++ b/apitools/org.eclipse.pde.api.tools/src_ant/org/eclipse/pde/api/tools/internal/tasks/messages.properties @@ -41,7 +41,6 @@ deltaReportTask_missingXmlFileLocation=Missing the xml file location argument deltaReportTask_missingXmlFile=The xml report file {0} does not exist deltaReportTask_xmlFileLocationMustBeAFile=The xml report file {0} must be a file and not a directory deltaReportTask_hmlFileLocationMustBeAFile=The html report file {0} must be a file and not a directory -deltaReportTask_couldNotCreateSAXParser=Could not create a sax parser missing_xml_files_location=The directory that contains xml reports must be specified invalid_directory_name=''{0}'' is not a valid directory name could_not_create_sax_parser=Could not create a sax parser @@ -204,7 +203,6 @@ RemovedElement=REMOVED ChangedElement=CHANGED deprecationReportTask_componentEntry=\n\ \ \n \n \n -deprecationReportTask_couldNotCreateSAXParser=Could not create a sax parser deprecationReportTask_endComponentEntry=
{0}
\n deprecationReportTask_entry=\ \n {0}{1}\n \n deprecationReportTask_header=\n\ diff --git a/ds/org.eclipse.pde.ds.core/src/org/eclipse/pde/internal/ds/core/builders/DefaultSAXParser.java b/ds/org.eclipse.pde.ds.core/src/org/eclipse/pde/internal/ds/core/builders/DefaultSAXParser.java index 771994f7dd5..7732776cae3 100644 --- a/ds/org.eclipse.pde.ds.core/src/org/eclipse/pde/internal/ds/core/builders/DefaultSAXParser.java +++ b/ds/org.eclipse.pde.ds.core/src/org/eclipse/pde/internal/ds/core/builders/DefaultSAXParser.java @@ -20,17 +20,21 @@ import java.io.InputStream; import javax.xml.parsers.ParserConfigurationException; +import javax.xml.parsers.SAXParser; import org.eclipse.core.resources.IFile; import org.eclipse.core.runtime.CoreException; -import org.eclipse.pde.internal.core.util.SAXParserWrapper; import org.xml.sax.SAXException; public class DefaultSAXParser { public static void parse(IFile file, XMLErrorReporter reporter) { try (InputStream stream = new BufferedInputStream(file.getContents())) { - SAXParserWrapper.parse(stream, reporter); + @SuppressWarnings("restriction") + SAXParser parser = org.eclipse.core.internal.runtime.XmlProcessorFactory + .createSAXParserWithErrorOnDOCTYPE(); + parser.parse(stream, + reporter); } catch (CoreException | SAXException | IOException | ParserConfigurationException e) { } } diff --git a/ds/org.eclipse.pde.ds.core/src/org/eclipse/pde/internal/ds/core/builders/XMLErrorReporter.java b/ds/org.eclipse.pde.ds.core/src/org/eclipse/pde/internal/ds/core/builders/XMLErrorReporter.java index 4a26b0b8793..cb464d8ebe2 100644 --- a/ds/org.eclipse.pde.ds.core/src/org/eclipse/pde/internal/ds/core/builders/XMLErrorReporter.java +++ b/ds/org.eclipse.pde.ds.core/src/org/eclipse/pde/internal/ds/core/builders/XMLErrorReporter.java @@ -35,7 +35,6 @@ import org.eclipse.jface.text.IRegion; import org.eclipse.jface.text.Position; import org.eclipse.pde.internal.core.builders.CompilerFlags; -import org.eclipse.pde.internal.core.util.PDEXmlProcessorFactory; import org.w3c.dom.Element; import org.w3c.dom.Text; import org.xml.sax.Attributes; @@ -167,10 +166,12 @@ public void warning(SAXParseException exception) throws SAXException { } @Override + @SuppressWarnings("restriction") public void startDocument() throws SAXException { try { // TODO we should be using a dom level 2 impl - fXMLDocument = PDEXmlProcessorFactory.createDocumentBuilderWithErrorOnDOCTYPE().newDocument(); + fXMLDocument = org.eclipse.core.internal.runtime.XmlProcessorFactory + .createDocumentBuilderWithErrorOnDOCTYPE().newDocument(); } catch (ParserConfigurationException e) { } } diff --git a/ui/org.eclipse.pde.core/src/org/eclipse/pde/internal/core/AbstractModel.java b/ui/org.eclipse.pde.core/src/org/eclipse/pde/internal/core/AbstractModel.java index 0879219d8aa..e7adcea368b 100644 --- a/ui/org.eclipse.pde.core/src/org/eclipse/pde/internal/core/AbstractModel.java +++ b/ui/org.eclipse.pde.core/src/org/eclipse/pde/internal/core/AbstractModel.java @@ -40,7 +40,6 @@ import org.eclipse.pde.core.IModelChangedEvent; import org.eclipse.pde.core.IModelChangedListener; import org.eclipse.pde.core.ModelChangedEvent; -import org.eclipse.pde.internal.core.util.PDEXmlProcessorFactory; import org.xml.sax.SAXException; public abstract class AbstractModel extends PlatformObject implements IModel, IModelChangeProviderExtension, Serializable { @@ -236,8 +235,9 @@ public void throwParseErrorsException(Throwable e) throws CoreException { throw new CoreException(Status.error("Error in the manifest file", e)); //$NON-NLS-1$ } + @SuppressWarnings("restriction") protected SAXParser getSaxParser() throws ParserConfigurationException, SAXException, FactoryConfigurationError { - return PDEXmlProcessorFactory.createSAXParserWithErrorOnDOCTYPE(); + return org.eclipse.core.internal.runtime.XmlProcessorFactory.createSAXParserWithErrorOnDOCTYPE(); } @Override diff --git a/ui/org.eclipse.pde.core/src/org/eclipse/pde/internal/core/PDEAuxiliaryState.java b/ui/org.eclipse.pde.core/src/org/eclipse/pde/internal/core/PDEAuxiliaryState.java index 47253f4a8ef..4ccd344d307 100644 --- a/ui/org.eclipse.pde.core/src/org/eclipse/pde/internal/core/PDEAuxiliaryState.java +++ b/ui/org.eclipse.pde.core/src/org/eclipse/pde/internal/core/PDEAuxiliaryState.java @@ -32,7 +32,6 @@ import org.eclipse.pde.core.plugin.IPluginModelBase; import org.eclipse.pde.internal.core.ibundle.IBundleModel; import org.eclipse.pde.internal.core.ibundle.IBundlePluginModelBase; -import org.eclipse.pde.internal.core.util.PDEXmlProcessorFactory; import org.osgi.framework.BundleException; import org.osgi.framework.Constants; import org.w3c.dom.Document; @@ -202,7 +201,8 @@ public boolean exportsExternalAnnotations(long bundleID) { */ protected void savePluginInfo(File dir) { try { - Document doc = PDEXmlProcessorFactory.createDocumentBuilderWithErrorOnDOCTYPE().newDocument(); + @SuppressWarnings("restriction") + Document doc = org.eclipse.core.internal.runtime.XmlProcessorFactory.newDocumentWithErrorOnDOCTYPE(); Element root = doc.createElement(ELEMENT_ROOT); Iterator iter = fPluginInfos.keySet().iterator(); @@ -261,7 +261,9 @@ protected boolean readPluginInfoCache(File dir) { File file = new File(dir, CACHE_EXTENSION); if (file.exists() && file.isFile()) { try { - DocumentBuilder documentBuilder = PDEXmlProcessorFactory.createDocumentBuilderWithErrorOnDOCTYPE(); + @SuppressWarnings("restriction") + DocumentBuilder documentBuilder = org.eclipse.core.internal.runtime.XmlProcessorFactory + .createDocumentBuilderWithErrorOnDOCTYPE(); documentBuilder.setErrorHandler(new DefaultHandler()); Document doc = documentBuilder.parse(file); Element root = doc.getDocumentElement(); @@ -300,9 +302,9 @@ protected boolean exists(File dir) { */ public static void writePluginInfo(IPluginModelBase[] models, File destination) { try { - DocumentBuilder builder = PDEXmlProcessorFactory.createDocumentBuilderWithErrorOnDOCTYPE(); - Document doc = builder.newDocument(); - + @SuppressWarnings("restriction") + Document doc = org.eclipse.core.internal.runtime.XmlProcessorFactory + .newDocumentWithErrorOnDOCTYPE(); Element root = doc.createElement(ELEMENT_ROOT); doc.appendChild(root); for (int i = 0; i < models.length; i++) { diff --git a/ui/org.eclipse.pde.core/src/org/eclipse/pde/internal/core/XMLDefaultHandler.java b/ui/org.eclipse.pde.core/src/org/eclipse/pde/internal/core/XMLDefaultHandler.java index 76f69859369..6ff85b89346 100644 --- a/ui/org.eclipse.pde.core/src/org/eclipse/pde/internal/core/XMLDefaultHandler.java +++ b/ui/org.eclipse.pde.core/src/org/eclipse/pde/internal/core/XMLDefaultHandler.java @@ -18,7 +18,6 @@ import javax.xml.parsers.ParserConfigurationException; -import org.eclipse.pde.internal.core.util.PDEXmlProcessorFactory; import org.w3c.dom.Element; import org.w3c.dom.Node; import org.w3c.dom.Text; @@ -73,9 +72,11 @@ public void setDocumentLocator(Locator locator) { } @Override + @SuppressWarnings("restriction") public void startDocument() throws SAXException { try { - fDocument = PDEXmlProcessorFactory.createDocumentBuilderWithErrorOnDOCTYPE().newDocument(); + fDocument = org.eclipse.core.internal.runtime.XmlProcessorFactory.createDocumentBuilderWithErrorOnDOCTYPE() + .newDocument(); } catch (ParserConfigurationException e) { } } diff --git a/ui/org.eclipse.pde.core/src/org/eclipse/pde/internal/core/builders/BuildErrorReporter.java b/ui/org.eclipse.pde.core/src/org/eclipse/pde/internal/core/builders/BuildErrorReporter.java index 2b230aea848..64e5895566c 100644 --- a/ui/org.eclipse.pde.core/src/org/eclipse/pde/internal/core/builders/BuildErrorReporter.java +++ b/ui/org.eclipse.pde.core/src/org/eclipse/pde/internal/core/builders/BuildErrorReporter.java @@ -70,7 +70,6 @@ import org.eclipse.pde.internal.core.text.build.BuildEntry; import org.eclipse.pde.internal.core.text.build.BuildModel; import org.eclipse.pde.internal.core.util.CoreUtility; -import org.eclipse.pde.internal.core.util.PDEXmlProcessorFactory; import org.eclipse.pde.internal.core.util.PatternConstructor; import org.osgi.framework.Constants; import org.w3c.dom.Document; @@ -691,7 +690,9 @@ private void validateBinIncludes(IBuildEntry binIncludes, List outp // if we're defining fragments, make sure they have entries in plugin.xml private void validateFragmentContributions(IBuildEntry binIncludes) { try { - DocumentBuilder newDocumentBuilder = PDEXmlProcessorFactory.createDocumentBuilderWithErrorOnDOCTYPE(); + @SuppressWarnings("restriction") + DocumentBuilder newDocumentBuilder = org.eclipse.core.internal.runtime.XmlProcessorFactory + .createDocumentBuilderWithErrorOnDOCTYPE(); newDocumentBuilder.setErrorHandler(new PDEErrorHandler()); Document doc = newDocumentBuilder.parse(PDEProject.getPluginXml(fProject).getContents()); XPath xpath = XPathFactory.newInstance().newXPath(); @@ -707,7 +708,9 @@ private void validateFragmentContributions(IBuildEntry binIncludes) { // if we're defining an application, make sure it has entries in plugin.xml private void validateApplicationContributions(IBuildEntry binIncludes) { try { - DocumentBuilder newDocumentBuilder = PDEXmlProcessorFactory.createDocumentBuilderWithErrorOnDOCTYPE(); + @SuppressWarnings("restriction") + DocumentBuilder newDocumentBuilder = org.eclipse.core.internal.runtime.XmlProcessorFactory + .createDocumentBuilderWithErrorOnDOCTYPE(); newDocumentBuilder.setErrorHandler(new PDEErrorHandler()); Document doc = newDocumentBuilder.parse(PDEProject.getPluginXml(fProject).getContents()); XPath xpath = XPathFactory.newInstance().newXPath(); diff --git a/ui/org.eclipse.pde.core/src/org/eclipse/pde/internal/core/builders/DefaultSAXParser.java b/ui/org.eclipse.pde.core/src/org/eclipse/pde/internal/core/builders/DefaultSAXParser.java index c1d9bd842dc..f7d118944be 100644 --- a/ui/org.eclipse.pde.core/src/org/eclipse/pde/internal/core/builders/DefaultSAXParser.java +++ b/ui/org.eclipse.pde.core/src/org/eclipse/pde/internal/core/builders/DefaultSAXParser.java @@ -18,17 +18,20 @@ import java.io.InputStream; import javax.xml.parsers.ParserConfigurationException; +import javax.xml.parsers.SAXParser; import org.eclipse.core.resources.IFile; import org.eclipse.core.runtime.CoreException; -import org.eclipse.pde.internal.core.util.SAXParserWrapper; import org.xml.sax.SAXException; public class DefaultSAXParser { public static void parse(IFile file, XMLErrorReporter reporter) { try (InputStream stream = new BufferedInputStream(file.getContents())) { - SAXParserWrapper.parse(stream, reporter); + @SuppressWarnings("restriction") + SAXParser parser = org.eclipse.core.internal.runtime.XmlProcessorFactory + .createSAXParserWithErrorOnDOCTYPE(); + parser.parse(stream, reporter); } catch (CoreException | SAXException | IOException | ParserConfigurationException e) { } } diff --git a/ui/org.eclipse.pde.core/src/org/eclipse/pde/internal/core/builders/XMLErrorReporter.java b/ui/org.eclipse.pde.core/src/org/eclipse/pde/internal/core/builders/XMLErrorReporter.java index 5555dae497b..842371ed691 100644 --- a/ui/org.eclipse.pde.core/src/org/eclipse/pde/internal/core/builders/XMLErrorReporter.java +++ b/ui/org.eclipse.pde.core/src/org/eclipse/pde/internal/core/builders/XMLErrorReporter.java @@ -38,7 +38,6 @@ import org.eclipse.pde.internal.core.PDECoreMessages; import org.eclipse.pde.internal.core.TargetPlatformHelper; import org.eclipse.pde.internal.core.builders.IncrementalErrorReporter.VirtualMarker; -import org.eclipse.pde.internal.core.util.PDEXmlProcessorFactory; import org.w3c.dom.Document; import org.w3c.dom.Element; import org.w3c.dom.Node; @@ -200,9 +199,10 @@ public void warning(SAXParseException exception) throws SAXException { } @Override + @SuppressWarnings("restriction") public void startDocument() throws SAXException { try { - fXMLDocument = PDEXmlProcessorFactory.createDocumentBuilderWithErrorOnDOCTYPE().newDocument(); + fXMLDocument = org.eclipse.core.internal.runtime.XmlProcessorFactory.newDocumentWithErrorOnDOCTYPE(); } catch (ParserConfigurationException e) { } } diff --git a/ui/org.eclipse.pde.core/src/org/eclipse/pde/internal/core/exports/FeatureExportOperation.java b/ui/org.eclipse.pde.core/src/org/eclipse/pde/internal/core/exports/FeatureExportOperation.java index f01ff18151f..90e474fe5cc 100644 --- a/ui/org.eclipse.pde.core/src/org/eclipse/pde/internal/core/exports/FeatureExportOperation.java +++ b/ui/org.eclipse.pde.core/src/org/eclipse/pde/internal/core/exports/FeatureExportOperation.java @@ -101,7 +101,6 @@ import org.eclipse.pde.internal.core.project.PDEProject; import org.eclipse.pde.internal.core.target.TargetMetadataCollector; import org.eclipse.pde.internal.core.util.CoreUtility; -import org.eclipse.pde.internal.core.util.PDEXmlProcessorFactory; import org.osgi.framework.InvalidSyntaxException; import org.w3c.dom.DOMException; import org.w3c.dom.Document; @@ -212,7 +211,8 @@ protected void appendMetadataToArchive(String[] configuration, IProgressMonitor try { scriptFile = createScriptFile("append.xml"); //$NON-NLS-1$ - Document doc = PDEXmlProcessorFactory.createDocumentBuilderWithErrorOnDOCTYPE().newDocument(); + @SuppressWarnings("restriction") + Document doc = org.eclipse.core.internal.runtime.XmlProcessorFactory.newDocumentWithErrorOnDOCTYPE(); Element root = doc.createElement("project"); //$NON-NLS-1$ root.setAttribute("name", "temp"); //$NON-NLS-1$ //$NON-NLS-2$ @@ -885,7 +885,8 @@ protected void cleanup(IProgressMonitor monitor) { File scriptFile = null; try { scriptFile = createScriptFile("zip.xml"); //$NON-NLS-1$ - Document doc = PDEXmlProcessorFactory.createDocumentBuilderWithErrorOnDOCTYPE().newDocument(); + @SuppressWarnings("restriction") + Document doc = org.eclipse.core.internal.runtime.XmlProcessorFactory.newDocumentWithErrorOnDOCTYPE(); Element root = doc.createElement("project"); //$NON-NLS-1$ root.setAttribute("name", "temp"); //$NON-NLS-1$ //$NON-NLS-2$ @@ -956,7 +957,9 @@ private String logName(String[] config) { private void createFeature(String featureID, String featureLocation, Object[] featuresExported, Document doc, Element root, Properties prop) throws IOException { try { if (doc == null) { - doc = PDEXmlProcessorFactory.createDocumentBuilderWithErrorOnDOCTYPE().newDocument(); + @SuppressWarnings("restriction") + Document d = org.eclipse.core.internal.runtime.XmlProcessorFactory.newDocumentWithErrorOnDOCTYPE(); + doc = d; root = doc.createElement("feature"); //$NON-NLS-1$ root.setAttribute("id", featureID); //$NON-NLS-1$ root.setAttribute("version", "1.0"); //$NON-NLS-1$ //$NON-NLS-2$ @@ -1061,7 +1064,8 @@ protected void createFeature(String featureID, String featureLocation, String[][ } try { - Document doc = PDEXmlProcessorFactory.createDocumentBuilderWithErrorOnDOCTYPE().newDocument(); + @SuppressWarnings("restriction") + Document doc = org.eclipse.core.internal.runtime.XmlProcessorFactory.newDocumentWithErrorOnDOCTYPE(); Element root = doc.createElement("feature"); //$NON-NLS-1$ root.setAttribute("id", featureID); //$NON-NLS-1$ root.setAttribute("version", "1.0"); //$NON-NLS-1$ //$NON-NLS-2$ diff --git a/ui/org.eclipse.pde.core/src/org/eclipse/pde/internal/core/plugin/AbstractExtensions.java b/ui/org.eclipse.pde.core/src/org/eclipse/pde/internal/core/plugin/AbstractExtensions.java index 7fb91887875..8727fcfb56c 100644 --- a/ui/org.eclipse.pde.core/src/org/eclipse/pde/internal/core/plugin/AbstractExtensions.java +++ b/ui/org.eclipse.pde.core/src/org/eclipse/pde/internal/core/plugin/AbstractExtensions.java @@ -23,8 +23,10 @@ import java.util.List; import javax.xml.parsers.ParserConfigurationException; +import javax.xml.parsers.SAXParser; import org.eclipse.core.resources.IFile; +import org.eclipse.core.resources.IResource; import org.eclipse.core.runtime.CoreException; import org.eclipse.pde.core.IModelChangedEvent; import org.eclipse.pde.core.plugin.IExtensions; @@ -35,7 +37,6 @@ import org.eclipse.pde.core.plugin.ISharedPluginModel; import org.eclipse.pde.internal.core.PDECore; import org.eclipse.pde.internal.core.PDECoreMessages; -import org.eclipse.pde.internal.core.util.PDEXmlProcessorFactory; import org.w3c.dom.Node; import org.xml.sax.SAXException; @@ -194,12 +195,14 @@ public String getSchemaVersion() { // since schema version is only needed on workspace models in very few situations, reading information from the file should suffice ISharedPluginModel model = getModel(); if (model != null) { - org.eclipse.core.resources.IResource res = model.getUnderlyingResource(); - if (res != null && res instanceof IFile) { - try { - InputStream stream = new BufferedInputStream(((IFile) res).getContents(true)); + IResource res = model.getUnderlyingResource(); + if (res instanceof IFile file) { + try (InputStream stream = new BufferedInputStream(file.getContents(true))) { PluginHandler handler = new PluginHandler(true); - PDEXmlProcessorFactory.createSAXParserWithErrorOnDOCTYPE().parse(stream, handler); + @SuppressWarnings("restriction") + SAXParser parser = org.eclipse.core.internal.runtime.XmlProcessorFactory + .createSAXParserWithErrorOnDOCTYPE(); + parser.parse(stream, handler); return handler.getSchemaVersion(); } catch (CoreException | SAXException | IOException | ParserConfigurationException e) { } diff --git a/ui/org.eclipse.pde.core/src/org/eclipse/pde/internal/core/plugin/PluginBase.java b/ui/org.eclipse.pde.core/src/org/eclipse/pde/internal/core/plugin/PluginBase.java index b179ab25d5d..faa76fe4f27 100644 --- a/ui/org.eclipse.pde.core/src/org/eclipse/pde/internal/core/plugin/PluginBase.java +++ b/ui/org.eclipse.pde.core/src/org/eclipse/pde/internal/core/plugin/PluginBase.java @@ -17,10 +17,6 @@ import java.util.ArrayList; import java.util.Locale; -import javax.xml.parsers.FactoryConfigurationError; -import javax.xml.parsers.ParserConfigurationException; -import javax.xml.parsers.SAXParser; - import org.eclipse.core.runtime.CoreException; import org.eclipse.osgi.service.resolver.BundleDescription; import org.eclipse.osgi.service.resolver.BundleSpecification; @@ -35,11 +31,9 @@ import org.eclipse.pde.internal.core.PDECoreMessages; import org.eclipse.pde.internal.core.PDEState; import org.eclipse.pde.internal.core.bundle.BundlePluginBase; -import org.eclipse.pde.internal.core.util.PDEXmlProcessorFactory; import org.osgi.framework.Version; import org.w3c.dom.Node; import org.w3c.dom.NodeList; -import org.xml.sax.SAXException; public abstract class PluginBase extends AbstractExtensions implements IPluginBase { private static final long serialVersionUID = 1L; @@ -403,11 +397,6 @@ protected boolean hasRequiredAttributes() { return super.hasRequiredAttributes(); } - protected SAXParser getSaxParser() throws ParserConfigurationException, SAXException, FactoryConfigurationError { - return PDEXmlProcessorFactory.createSAXParserWithErrorOnDOCTYPE(); - - } - public static int getMatchRule(VersionRange versionRange) { if (versionRange == null || versionRange.getMinimum() == null) { return IMatchRules.NONE; diff --git a/ui/org.eclipse.pde.core/src/org/eclipse/pde/internal/core/plugin/PluginHandler.java b/ui/org.eclipse.pde.core/src/org/eclipse/pde/internal/core/plugin/PluginHandler.java index 1c0b476b00c..4a24fc95f91 100644 --- a/ui/org.eclipse.pde.core/src/org/eclipse/pde/internal/core/plugin/PluginHandler.java +++ b/ui/org.eclipse.pde.core/src/org/eclipse/pde/internal/core/plugin/PluginHandler.java @@ -22,7 +22,6 @@ import org.eclipse.pde.internal.core.TargetPlatformHelper; import org.eclipse.pde.internal.core.util.IdUtil; -import org.eclipse.pde.internal.core.util.PDEXmlProcessorFactory; import org.w3c.dom.DOMException; import org.w3c.dom.Document; import org.w3c.dom.Element; @@ -98,9 +97,11 @@ public void setDocumentLocator(Locator locator) { } @Override + @SuppressWarnings("restriction") public void startDocument() throws SAXException { try { - fDocument = PDEXmlProcessorFactory.createDocumentBuilderWithErrorOnDOCTYPE().newDocument(); + fDocument = org.eclipse.core.internal.runtime.XmlProcessorFactory.createDocumentBuilderWithErrorOnDOCTYPE() + .newDocument(); } catch (ParserConfigurationException e) { } } diff --git a/ui/org.eclipse.pde.core/src/org/eclipse/pde/internal/core/schema/Schema.java b/ui/org.eclipse.pde.core/src/org/eclipse/pde/internal/core/schema/Schema.java index 0195e12f9ee..c8cb30f31f9 100644 --- a/ui/org.eclipse.pde.core/src/org/eclipse/pde/internal/core/schema/Schema.java +++ b/ui/org.eclipse.pde.core/src/org/eclipse/pde/internal/core/schema/Schema.java @@ -27,6 +27,8 @@ import java.util.Locale; import java.util.Vector; +import javax.xml.parsers.SAXParser; + import org.eclipse.core.runtime.IPath; import org.eclipse.core.runtime.ListenerList; import org.eclipse.core.runtime.PlatformObject; @@ -54,7 +56,6 @@ import org.eclipse.pde.internal.core.ischema.ISchemaSimpleType; import org.eclipse.pde.internal.core.ischema.ISchemaType; import org.eclipse.pde.internal.core.util.PDEXMLHelper; -import org.eclipse.pde.internal.core.util.SAXParserWrapper; import org.eclipse.pde.internal.core.util.SchemaUtil; import org.w3c.dom.NamedNodeMap; import org.w3c.dom.Node; @@ -450,7 +451,10 @@ public void load() { public void load(InputStream stream) { try { XMLDefaultHandler handler = new XMLDefaultHandler(fAbbreviated); - SAXParserWrapper.parse(stream, handler); + @SuppressWarnings("restriction") + SAXParser parser = org.eclipse.core.internal.runtime.XmlProcessorFactory + .createSAXParserWithErrorOnDOCTYPE(); + parser.parse(stream, handler); traverseDocumentTree(handler.getDocumentElement()); } catch (SAXException e) { // ignore parse errors - 'loaded' will be false anyway 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 c0286a66252..73ea3350427 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 @@ -39,7 +39,6 @@ import javax.xml.transform.OutputKeys; import javax.xml.transform.Transformer; import javax.xml.transform.TransformerException; -import javax.xml.transform.TransformerFactory; import javax.xml.transform.dom.DOMSource; import javax.xml.transform.stream.StreamResult; @@ -68,7 +67,6 @@ import org.eclipse.pde.core.target.TargetBundle; import org.eclipse.pde.core.target.TargetFeature; import org.eclipse.pde.internal.core.PDECore; -import org.eclipse.pde.internal.core.util.PDEXmlProcessorFactory; import org.w3c.dom.Document; import org.w3c.dom.Element; @@ -700,7 +698,9 @@ public String serialize() { Element containerElement; Document document; try { - DocumentBuilder docBuilder = PDEXmlProcessorFactory.createDocumentBuilderWithErrorOnDOCTYPE(); + @SuppressWarnings("restriction") + DocumentBuilder docBuilder = org.eclipse.core.internal.runtime.XmlProcessorFactory + .createDocumentBuilderWithErrorOnDOCTYPE(); document = docBuilder.newDocument(); } catch (Exception e) { PDECore.log(e); @@ -733,8 +733,9 @@ public String serialize() { try { document.appendChild(containerElement); StreamResult result = new StreamResult(new StringWriter()); - TransformerFactory f = PDEXmlProcessorFactory.createTransformerFactoryWithErrorOnDOCTYPE(); - Transformer transformer = f.newTransformer(); + @SuppressWarnings("restriction") + Transformer transformer = org.eclipse.core.internal.runtime.XmlProcessorFactory + .createTransformerFactoryWithErrorOnDOCTYPE().newTransformer(); transformer.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "yes"); //$NON-NLS-1$ transformer.transform(new DOMSource(document), result); return result.getWriter().toString(); 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 abc33678df5..cadfbc59233 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 @@ -20,13 +20,10 @@ import java.util.ArrayList; import java.util.List; -import javax.xml.parsers.DocumentBuilder; - import org.eclipse.core.runtime.CoreException; import org.eclipse.core.runtime.Status; import org.eclipse.pde.core.target.ITargetLocation; import org.eclipse.pde.core.target.ITargetLocationFactory; -import org.eclipse.pde.internal.core.util.PDEXmlProcessorFactory; import org.w3c.dom.Document; import org.w3c.dom.Element; import org.w3c.dom.Node; @@ -45,9 +42,9 @@ public ITargetLocation getTargetLocation(String type, String serializedXML) thro Element location; try { - DocumentBuilder docBuilder = PDEXmlProcessorFactory.createDocumentBuilderWithErrorOnDOCTYPE(); - Document document = docBuilder - .parse(new ByteArrayInputStream(serializedXML.getBytes(StandardCharsets.UTF_8))); + @SuppressWarnings("restriction") + Document document = org.eclipse.core.internal.runtime.XmlProcessorFactory + .parseWithErrorOnDOCTYPE(new ByteArrayInputStream(serializedXML.getBytes(StandardCharsets.UTF_8))); location = document.getDocumentElement(); } catch (Exception e) { throw new CoreException(Status.error(e.getMessage(), e)); diff --git a/ui/org.eclipse.pde.core/src/org/eclipse/pde/internal/core/target/RepositoryBundleContainer.java b/ui/org.eclipse.pde.core/src/org/eclipse/pde/internal/core/target/RepositoryBundleContainer.java index 7cb47c74dac..ef4b3e64b85 100644 --- a/ui/org.eclipse.pde.core/src/org/eclipse/pde/internal/core/target/RepositoryBundleContainer.java +++ b/ui/org.eclipse.pde.core/src/org/eclipse/pde/internal/core/target/RepositoryBundleContainer.java @@ -31,6 +31,7 @@ import javax.xml.transform.dom.DOMSource; import javax.xml.transform.stream.StreamResult; +import org.eclipse.core.internal.runtime.XmlProcessorFactory; import org.eclipse.core.runtime.CoreException; import org.eclipse.core.runtime.FileLocator; import org.eclipse.core.runtime.IProgressMonitor; @@ -40,7 +41,6 @@ import org.eclipse.pde.core.target.TargetBundle; import org.eclipse.pde.core.target.TargetFeature; import org.eclipse.pde.internal.core.PDECore; -import org.eclipse.pde.internal.core.util.PDEXmlProcessorFactory; import org.osgi.resource.Capability; import org.osgi.resource.Requirement; import org.w3c.dom.Document; @@ -154,7 +154,7 @@ public String getLocation(boolean resolve) throws CoreException { @Override public String serialize() { try { - DocumentBuilder docBuilder = PDEXmlProcessorFactory.createDocumentBuilderWithErrorOnDOCTYPE(); + DocumentBuilder docBuilder = XmlProcessorFactory.createDocumentBuilderWithErrorOnDOCTYPE(); Document document = docBuilder.newDocument(); Element containerElement = document.createElement(TargetDefinitionPersistenceHelper.LOCATION); containerElement.setAttribute(TargetDefinitionPersistenceHelper.ATTR_LOCATION_TYPE, TYPE); @@ -166,7 +166,7 @@ public String serialize() { } document.appendChild(containerElement); StreamResult result = new StreamResult(new StringWriter()); - TransformerFactory f = PDEXmlProcessorFactory.createTransformerFactoryWithErrorOnDOCTYPE(); + TransformerFactory f = XmlProcessorFactory.createTransformerFactoryWithErrorOnDOCTYPE(); Transformer transformer = f.newTransformer(); transformer.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "yes"); //$NON-NLS-1$ transformer.transform(new DOMSource(document), result); diff --git a/ui/org.eclipse.pde.core/src/org/eclipse/pde/internal/core/target/RepositoryLocationFactory.java b/ui/org.eclipse.pde.core/src/org/eclipse/pde/internal/core/target/RepositoryLocationFactory.java index 4cdd48268a2..b22d9734c4e 100644 --- a/ui/org.eclipse.pde.core/src/org/eclipse/pde/internal/core/target/RepositoryLocationFactory.java +++ b/ui/org.eclipse.pde.core/src/org/eclipse/pde/internal/core/target/RepositoryLocationFactory.java @@ -25,7 +25,6 @@ import org.eclipse.osgi.util.NLS; import org.eclipse.pde.core.target.ITargetLocation; import org.eclipse.pde.core.target.ITargetLocationFactory; -import org.eclipse.pde.internal.core.util.PDEXmlProcessorFactory; import org.osgi.resource.Requirement; import org.w3c.dom.Document; import org.w3c.dom.Element; @@ -43,7 +42,9 @@ public ITargetLocation getTargetLocation(String type, String serializedXML) thro Status.error(NLS.bind(Messages.TargetRefrenceLocationFactory_Unsupported_Type, type))); } try { - DocumentBuilder docBuilder = PDEXmlProcessorFactory.createDocumentBuilderWithErrorOnDOCTYPE(); + @SuppressWarnings("restriction") + DocumentBuilder docBuilder = org.eclipse.core.internal.runtime.XmlProcessorFactory + .createDocumentBuilderWithErrorOnDOCTYPE(); Document document = docBuilder .parse(new ByteArrayInputStream(serializedXML.getBytes(StandardCharsets.UTF_8))); Element location = document.getDocumentElement(); diff --git a/ui/org.eclipse.pde.core/src/org/eclipse/pde/internal/core/target/TargetDefinition.java b/ui/org.eclipse.pde.core/src/org/eclipse/pde/internal/core/target/TargetDefinition.java index 4b1020b42f4..471d276ebf1 100644 --- a/ui/org.eclipse.pde.core/src/org/eclipse/pde/internal/core/target/TargetDefinition.java +++ b/ui/org.eclipse.pde.core/src/org/eclipse/pde/internal/core/target/TargetDefinition.java @@ -62,7 +62,6 @@ import org.eclipse.pde.internal.core.ICoreConstants; import org.eclipse.pde.internal.core.PDECore; import org.eclipse.pde.internal.core.TargetPlatformHelper; -import org.eclipse.pde.internal.core.util.PDEXmlProcessorFactory; import org.w3c.dom.DOMException; import org.w3c.dom.Document; import org.w3c.dom.Element; @@ -136,8 +135,9 @@ public class TargetDefinition implements ITargetDefinition { private static Document createNewDocument() { try { - DocumentBuilder docBuilder = PDEXmlProcessorFactory.createDocumentBuilderWithErrorOnDOCTYPE(); - Document doc = docBuilder.newDocument(); + @SuppressWarnings("restriction") + Document doc = org.eclipse.core.internal.runtime.XmlProcessorFactory + .createDocumentBuilderWithErrorOnDOCTYPE().newDocument(); ProcessingInstruction instruction = doc.createProcessingInstruction( TargetDefinitionPersistenceHelper.PDE_INSTRUCTION, TargetDefinitionPersistenceHelper.ATTR_VERSION + "=\"" + ICoreConstants.TARGET38 + "\""); //$NON-NLS-1$ //$NON-NLS-2$ @@ -1170,7 +1170,9 @@ private void serializeBundleContainers(ITargetLocation[] targetLocations, Elemen List oldIUContainers = new ArrayList<>(); List oldGenericContainers = new ArrayList<>(); - DocumentBuilder docBuilder = PDEXmlProcessorFactory.createDocumentBuilderWithErrorOnDOCTYPE(); + @SuppressWarnings("restriction") + DocumentBuilder docBuilder = org.eclipse.core.internal.runtime.XmlProcessorFactory + .createDocumentBuilderWithErrorOnDOCTYPE(); for (ITargetLocation targetLocation : targetLocations) { String type = targetLocation.getType(); if (targetLocation instanceof DirectoryBundleContainer) { diff --git a/ui/org.eclipse.pde.core/src/org/eclipse/pde/internal/core/target/TargetDefinitionPersistenceHelper.java b/ui/org.eclipse.pde.core/src/org/eclipse/pde/internal/core/target/TargetDefinitionPersistenceHelper.java index d4119c7cef0..53613d2dba1 100644 --- a/ui/org.eclipse.pde.core/src/org/eclipse/pde/internal/core/target/TargetDefinitionPersistenceHelper.java +++ b/ui/org.eclipse.pde.core/src/org/eclipse/pde/internal/core/target/TargetDefinitionPersistenceHelper.java @@ -27,7 +27,6 @@ import javax.xml.transform.OutputKeys; import javax.xml.transform.Transformer; import javax.xml.transform.TransformerException; -import javax.xml.transform.TransformerFactory; import javax.xml.transform.dom.DOMSource; import javax.xml.transform.stream.StreamResult; @@ -37,7 +36,6 @@ import org.eclipse.pde.core.target.ITargetPlatformService; import org.eclipse.pde.internal.core.ICoreConstants; import org.eclipse.pde.internal.core.PDECore; -import org.eclipse.pde.internal.core.util.PDEXmlProcessorFactory; import org.w3c.dom.DOMException; import org.w3c.dom.Document; import org.w3c.dom.Element; @@ -123,8 +121,9 @@ public static void persistXML(ITargetDefinition definition, OutputStream output) return; } StreamResult outputTarget = new StreamResult(output); - TransformerFactory factory = PDEXmlProcessorFactory.createTransformerFactoryWithErrorOnDOCTYPE(); - Transformer transformer = factory.newTransformer(); + @SuppressWarnings("restriction") + Transformer transformer = org.eclipse.core.internal.runtime.XmlProcessorFactory + .createTransformerFactoryWithErrorOnDOCTYPE().newTransformer(); transformer.setOutputProperty(OutputKeys.METHOD, "xml"); //$NON-NLS-1$ transformer.setOutputProperty(OutputKeys.INDENT, "yes"); //$NON-NLS-1$ transformer.setOutputProperty(OutputKeys.STANDALONE, "no"); //$NON-NLS-1$ @@ -152,7 +151,9 @@ public static void persistXML(ITargetDefinition definition, OutputStream output) */ public static void initFromXML(ITargetDefinition definition, InputStream input) throws CoreException, ParserConfigurationException, SAXException, IOException { - DocumentBuilder parser = PDEXmlProcessorFactory.createDocumentBuilderWithErrorOnDOCTYPE(); + @SuppressWarnings("restriction") + DocumentBuilder parser = org.eclipse.core.internal.runtime.XmlProcessorFactory + .createDocumentBuilderWithErrorOnDOCTYPE(); parser.setErrorHandler(new DefaultHandler()); Document doc = parser.parse(new InputSource(input)); diff --git a/ui/org.eclipse.pde.core/src/org/eclipse/pde/internal/core/target/TargetPersistence38Helper.java b/ui/org.eclipse.pde.core/src/org/eclipse/pde/internal/core/target/TargetPersistence38Helper.java index f14981c50e9..1660660a4df 100644 --- a/ui/org.eclipse.pde.core/src/org/eclipse/pde/internal/core/target/TargetPersistence38Helper.java +++ b/ui/org.eclipse.pde.core/src/org/eclipse/pde/internal/core/target/TargetPersistence38Helper.java @@ -21,7 +21,6 @@ import javax.xml.transform.OutputKeys; import javax.xml.transform.Transformer; import javax.xml.transform.TransformerException; -import javax.xml.transform.TransformerFactory; import javax.xml.transform.TransformerFactoryConfigurationError; import javax.xml.transform.dom.DOMSource; import javax.xml.transform.stream.StreamResult; @@ -35,7 +34,6 @@ import org.eclipse.pde.core.target.ITargetLocationFactory; import org.eclipse.pde.core.target.NameVersionDescriptor; import org.eclipse.pde.internal.core.PDECore; -import org.eclipse.pde.internal.core.util.PDEXmlProcessorFactory; import org.w3c.dom.Element; import org.w3c.dom.Node; import org.w3c.dom.NodeList; @@ -251,8 +249,9 @@ private static ITargetLocation deserializeBundleContainer(Element location) thro throw new CoreException(Status.error(NLS.bind(Messages.TargetPersistence38Helper_NoTargetLocationExtension, type))); } StreamResult result = new StreamResult(new StringWriter()); - TransformerFactory factory = PDEXmlProcessorFactory.createTransformerFactoryWithErrorOnDOCTYPE(); - Transformer transformer = factory.newTransformer(); + @SuppressWarnings("restriction") + Transformer transformer = org.eclipse.core.internal.runtime.XmlProcessorFactory + .createTransformerFactoryWithErrorOnDOCTYPE().newTransformer(); transformer.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "yes"); //$NON-NLS-1$ transformer.transform(new DOMSource(location), result); container = locFactory.getTargetLocation(type, result.getWriter().toString()); diff --git a/ui/org.eclipse.pde.core/src/org/eclipse/pde/internal/core/target/TargetRefrenceLocationFactory.java b/ui/org.eclipse.pde.core/src/org/eclipse/pde/internal/core/target/TargetRefrenceLocationFactory.java index 2e585969bdd..65bc869b450 100644 --- a/ui/org.eclipse.pde.core/src/org/eclipse/pde/internal/core/target/TargetRefrenceLocationFactory.java +++ b/ui/org.eclipse.pde.core/src/org/eclipse/pde/internal/core/target/TargetRefrenceLocationFactory.java @@ -16,14 +16,11 @@ import java.io.ByteArrayInputStream; import java.nio.charset.StandardCharsets; -import javax.xml.parsers.DocumentBuilder; - import org.eclipse.core.runtime.CoreException; import org.eclipse.core.runtime.Status; import org.eclipse.osgi.util.NLS; import org.eclipse.pde.core.target.ITargetLocation; import org.eclipse.pde.core.target.ITargetLocationFactory; -import org.eclipse.pde.internal.core.util.PDEXmlProcessorFactory; import org.w3c.dom.Document; import org.w3c.dom.Element; @@ -36,9 +33,9 @@ public ITargetLocation getTargetLocation(String type, String serializedXML) thro Status.error(NLS.bind(Messages.TargetRefrenceLocationFactory_Unsupported_Type, type))); } try { - DocumentBuilder docBuilder = PDEXmlProcessorFactory.createDocumentBuilderWithErrorOnDOCTYPE(); - Document document = docBuilder - .parse(new ByteArrayInputStream(serializedXML.getBytes(StandardCharsets.UTF_8))); + @SuppressWarnings("restriction") + Document document = org.eclipse.core.internal.runtime.XmlProcessorFactory + .parseWithErrorOnDOCTYPE(new ByteArrayInputStream(serializedXML.getBytes(StandardCharsets.UTF_8))); Element location = document.getDocumentElement(); return new TargetReferenceBundleContainer( location.getAttribute(TargetReferenceBundleContainer.ATTRIBUTE_URI)); diff --git a/ui/org.eclipse.pde.core/src/org/eclipse/pde/internal/core/update/configurator/ConfigurationParser.java b/ui/org.eclipse.pde.core/src/org/eclipse/pde/internal/core/update/configurator/ConfigurationParser.java index 32296415f16..8577e94581b 100644 --- a/ui/org.eclipse.pde.core/src/org/eclipse/pde/internal/core/update/configurator/ConfigurationParser.java +++ b/ui/org.eclipse.pde.core/src/org/eclipse/pde/internal/core/update/configurator/ConfigurationParser.java @@ -17,7 +17,6 @@ import java.io.FileInputStream; import java.io.IOException; import java.io.InputStream; -import java.lang.reflect.InvocationTargetException; import java.net.MalformedURLException; import java.net.URL; import java.util.ArrayList; @@ -29,7 +28,6 @@ import org.eclipse.core.runtime.URIUtil; import org.eclipse.osgi.util.NLS; -import org.eclipse.pde.internal.core.util.PDEXmlProcessorFactory; import org.xml.sax.Attributes; import org.xml.sax.InputSource; import org.xml.sax.SAXException; @@ -54,14 +52,9 @@ class ConfigurationParser extends DefaultHandler implements IConfigurationConsta /** * Constructor for ConfigurationParser */ - public ConfigurationParser() throws InvocationTargetException { - - try { - this.parser = PDEXmlProcessorFactory.createSAXParserWithErrorOnDOCTYPE(true); - } catch (ParserConfigurationException | SAXException e) { - Utils.log(Utils.newStatus("ConfigurationParser", e)); //$NON-NLS-1$ - throw new InvocationTargetException(e); - } + @SuppressWarnings("restriction") + public ConfigurationParser() throws ParserConfigurationException, SAXException { + this.parser = org.eclipse.core.internal.runtime.XmlProcessorFactory.createSAXParserWithErrorOnDOCTYPE(true); } public Configuration parse(URL url, URL installLocation) throws Exception { diff --git a/ui/org.eclipse.pde.core/src/org/eclipse/pde/internal/core/update/configurator/FeatureParser.java b/ui/org.eclipse.pde.core/src/org/eclipse/pde/internal/core/update/configurator/FeatureParser.java index ca60d794049..09e4990fcb6 100644 --- a/ui/org.eclipse.pde.core/src/org/eclipse/pde/internal/core/update/configurator/FeatureParser.java +++ b/ui/org.eclipse.pde.core/src/org/eclipse/pde/internal/core/update/configurator/FeatureParser.java @@ -21,8 +21,8 @@ import javax.xml.parsers.ParserConfigurationException; import javax.xml.parsers.SAXParser; +import org.eclipse.core.runtime.ILog; import org.eclipse.osgi.util.NLS; -import org.eclipse.pde.internal.core.util.PDEXmlProcessorFactory; import org.xml.sax.Attributes; import org.xml.sax.InputSource; import org.xml.sax.SAXException; @@ -35,6 +35,7 @@ * @since 3.0 */ class FeatureParser extends DefaultHandler { + private static final ILog LOG = ILog.get(); private SAXParser parser; private FeatureEntry feature; @@ -43,12 +44,12 @@ class FeatureParser extends DefaultHandler { /** * Constructs a feature parser. */ + @SuppressWarnings("restriction") public FeatureParser() { - super(); try { - this.parser = PDEXmlProcessorFactory.createSAXParserWithErrorOnDOCTYPE(true); + this.parser = org.eclipse.core.internal.runtime.XmlProcessorFactory.createSAXParserWithErrorOnDOCTYPE(true); } catch (ParserConfigurationException | SAXException e) { - System.out.println(e); + LOG.error(e.getLocalizedMessage(), e); } } @@ -57,20 +58,11 @@ public FeatureParser() { */ public FeatureEntry parse(URL featureURL) { feature = null; - InputStream in = null; - try { + try (InputStream in = featureURL.openStream()) { this.url = featureURL; - in = featureURL.openStream(); parser.parse(new InputSource(in), this); } catch (SAXException | IOException e) { - } finally { - if (in != null) { - try { - in.close(); - } catch (IOException e1) { - Utils.log(e1.getLocalizedMessage()); - } - } + LOG.error(e.getLocalizedMessage(), e); } return feature; } diff --git a/ui/org.eclipse.pde.core/src/org/eclipse/pde/internal/core/update/configurator/PlatformConfiguration.java b/ui/org.eclipse.pde.core/src/org/eclipse/pde/internal/core/update/configurator/PlatformConfiguration.java index 31da9ec0378..b2efa3b9834 100644 --- a/ui/org.eclipse.pde.core/src/org/eclipse/pde/internal/core/update/configurator/PlatformConfiguration.java +++ b/ui/org.eclipse.pde.core/src/org/eclipse/pde/internal/core/update/configurator/PlatformConfiguration.java @@ -17,7 +17,6 @@ import java.io.File; import java.io.FileFilter; import java.io.IOException; -import java.lang.reflect.InvocationTargetException; import java.net.URL; import java.util.ArrayList; @@ -98,12 +97,7 @@ private Configuration loadConfig(URL url, URL installLocation) throws Exception } // try to load saved configuration file (watch for failed prior save()) - ConfigurationParser parser = null; - try { - parser = new ConfigurationParser(); - } catch (InvocationTargetException e) { - throw (Exception) e.getTargetException(); - } + ConfigurationParser parser = new ConfigurationParser(); config = null; Exception originalException = null; diff --git a/ui/org.eclipse.pde.core/src/org/eclipse/pde/internal/core/util/PDEXMLHelper.java b/ui/org.eclipse.pde.core/src/org/eclipse/pde/internal/core/util/PDEXMLHelper.java index eefa2caa6ab..3c50ab05174 100644 --- a/ui/org.eclipse.pde.core/src/org/eclipse/pde/internal/core/util/PDEXMLHelper.java +++ b/ui/org.eclipse.pde.core/src/org/eclipse/pde/internal/core/util/PDEXMLHelper.java @@ -13,29 +13,8 @@ *******************************************************************************/ package org.eclipse.pde.internal.core.util; -import javax.xml.parsers.FactoryConfigurationError; - -/** - * PDEXMLHelper - * - */ public class PDEXMLHelper { - - protected static PDEXMLHelper fPinstance; - protected static int fSAXPoolLimit; - protected static int fDOMPoolLimit; - protected static final int FMAXPOOLLIMIT = 1; - - protected PDEXMLHelper() throws FactoryConfigurationError { - fSAXPoolLimit = FMAXPOOLLIMIT; - fDOMPoolLimit = FMAXPOOLLIMIT; - } - - public static PDEXMLHelper Instance() throws FactoryConfigurationError { - if (fPinstance == null) { - fPinstance = new PDEXMLHelper(); - } - return fPinstance; + private PDEXMLHelper() { } public static String getWritableString(String source) { @@ -44,26 +23,14 @@ public static String getWritableString(String source) { } StringBuilder buf = new StringBuilder(); for (int i = 0; i < source.length(); i++) { - char c = source.charAt(i); - switch (c) { - case '&' : - buf.append("&"); //$NON-NLS-1$ - break; - case '<' : - buf.append("<"); //$NON-NLS-1$ - break; - case '>' : - buf.append(">"); //$NON-NLS-1$ - break; - case '\'' : - buf.append("'"); //$NON-NLS-1$ - break; - case '\"' : - buf.append("""); //$NON-NLS-1$ - break; - default : - buf.append(c); - break; + char character = source.charAt(i); + switch (character) { + case '&' -> buf.append("&"); //$NON-NLS-1$ + case '<' -> buf.append("<"); //$NON-NLS-1$ + case '>' -> buf.append(">"); //$NON-NLS-1$ + case '\'' -> buf.append("'"); //$NON-NLS-1$ + case '\"' -> buf.append("""); //$NON-NLS-1$ + default -> buf.append(character); } } return buf.toString(); @@ -76,55 +43,22 @@ public static String getWritableAttributeString(String source) { } // Trim the leading and trailing whitespace if any source = source.trim(); - // Translate source using a buffer StringBuilder buffer = new StringBuilder(); // Translate source character by character for (int i = 0; i < source.length(); i++) { char character = source.charAt(i); switch (character) { - case '&' : - buffer.append("&"); //$NON-NLS-1$ - break; - case '<' : - buffer.append("<"); //$NON-NLS-1$ - break; - case '>' : - buffer.append(">"); //$NON-NLS-1$ - break; - case '\'' : - buffer.append("'"); //$NON-NLS-1$ - break; - case '\"' : - buffer.append("""); //$NON-NLS-1$ - break; - case '\r' : - buffer.append(" "); //$NON-NLS-1$ - break; - case '\n' : - buffer.append(" "); //$NON-NLS-1$ - break; - default : - buffer.append(character); - break; + case '&' -> buffer.append("&"); //$NON-NLS-1$ + case '<' -> buffer.append("<"); //$NON-NLS-1$ + case '>' -> buffer.append(">"); //$NON-NLS-1$ + case '\'' -> buffer.append("'"); //$NON-NLS-1$ + case '\"' -> buffer.append("""); //$NON-NLS-1$ + case '\r' -> buffer.append(" "); //$NON-NLS-1$ + case '\n' -> buffer.append(" "); //$NON-NLS-1$ + default -> buffer.append(character); } } return buffer.toString(); } - public static int getSAXPoolLimit() { - return fSAXPoolLimit; - } - - public static void setSAXPoolLimit(int poolLimit) { - fSAXPoolLimit = poolLimit; - } - - public static int getDOMPoolLimit() { - return fDOMPoolLimit; - } - - public static void setDOMPoolLimit(int poolLimit) { - fDOMPoolLimit = poolLimit; - } - } diff --git a/ui/org.eclipse.pde.core/src/org/eclipse/pde/internal/core/util/PDEXmlProcessorFactory.java b/ui/org.eclipse.pde.core/src/org/eclipse/pde/internal/core/util/PDEXmlProcessorFactory.java deleted file mode 100644 index d7fdeddca14..00000000000 --- a/ui/org.eclipse.pde.core/src/org/eclipse/pde/internal/core/util/PDEXmlProcessorFactory.java +++ /dev/null @@ -1,197 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2023 Joerg Kubitz and others. - * - * 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 - *******************************************************************************/ -package org.eclipse.pde.internal.core.util; - -import javax.xml.XMLConstants; -import javax.xml.parsers.DocumentBuilder; -import javax.xml.parsers.DocumentBuilderFactory; -import javax.xml.parsers.ParserConfigurationException; -import javax.xml.parsers.SAXParser; -import javax.xml.parsers.SAXParserFactory; -import javax.xml.transform.TransformerFactory; - -import org.xml.sax.SAXException; -import org.xml.sax.SAXNotRecognizedException; -import org.xml.sax.SAXNotSupportedException; - -/** - * XML processing which prohibits external entities. - * - * @see RSPEC-2755 - */ -public class PDEXmlProcessorFactory { - private PDEXmlProcessorFactory() { - // static Utility only - } - - private static final DocumentBuilderFactory DOCUMENT_BUILDER_FACTORY_ERROR_ON_DOCTYPE = createDocumentBuilderFactoryWithErrorOnDOCTYPE(); - private static final DocumentBuilderFactory DOCUMENT_BUILDER_FACTORY_IGNORING_DOCTYPE = createDocumentBuilderFactoryIgnoringDOCTYPE(); - private static final SAXParserFactory SAX_FACTORY_ERROR_ON_DOCTYPE = createSAXFactoryWithErrorOnDOCTYPE(false); - private static final SAXParserFactory SAX_FACTORY_ERROR_ON_DOCTYPE_NS = createSAXFactoryWithErrorOnDOCTYPE(true); - private static final SAXParserFactory SAX_FACTORY_IGNORING_DOCTYPE = createSAXFactoryIgnoringDOCTYPE(); - - /** - * Creates TransformerFactory which throws TransformerException when - * detecting external entities. - * - * @return javax.xml.transform.TransformerFactory - */ - public static TransformerFactory createTransformerFactoryWithErrorOnDOCTYPE() { - TransformerFactory factory = TransformerFactory.newInstance(); - // prohibit the use of all protocols by external entities: - factory.setAttribute(XMLConstants.ACCESS_EXTERNAL_DTD, ""); //$NON-NLS-1$ - factory.setAttribute(XMLConstants.ACCESS_EXTERNAL_STYLESHEET, ""); //$NON-NLS-1$ - return factory; - } - - /** - * Creates DocumentBuilderFactory which throws SAXParseException when - * detecting external entities. It's magnitudes faster to call - * {@link #createDocumentBuilderWithErrorOnDOCTYPE()}. - * - * @return javax.xml.parsers.DocumentBuilderFactory - */ - public static synchronized DocumentBuilderFactory createDocumentBuilderFactoryWithErrorOnDOCTYPE() { - DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); - // completely disable DOCTYPE declaration: - try { - factory.setFeature("http://apache.org/xml/features/disallow-doctype-decl", true); //$NON-NLS-1$ - } catch (ParserConfigurationException e) { - throw new RuntimeException(e.getMessage(), e); - } - return factory; - } - - /** - * Creates DocumentBuilderFactory which ignores external entities. It's - * magnitudes faster to call - * {@link #createDocumentBuilderIgnoringDOCTYPE()}. - * - * @return javax.xml.parsers.DocumentBuilderFactory - */ - public static synchronized DocumentBuilderFactory createDocumentBuilderFactoryIgnoringDOCTYPE() { - DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); - try { - // completely disable external entities declarations: - factory.setFeature("http://xml.org/sax/features/external-general-entities", false); //$NON-NLS-1$ - factory.setFeature("http://xml.org/sax/features/external-parameter-entities", false); //$NON-NLS-1$ - } catch (ParserConfigurationException e) { - throw new RuntimeException(e.getMessage(), e); - } - return factory; - } - - /** - * Creates DocumentBuilder which throws SAXParseException when detecting - * external entities. The builder is not thread safe. - * - * @return javax.xml.parsers.DocumentBuilder - * @throws ParserConfigurationException - */ - public static DocumentBuilder createDocumentBuilderWithErrorOnDOCTYPE() throws ParserConfigurationException { - return DOCUMENT_BUILDER_FACTORY_ERROR_ON_DOCTYPE.newDocumentBuilder(); - } - - /** - * Creates DocumentBuilder which ignores external entities. The builder is - * not thread safe. - * - * @return javax.xml.parsers.DocumentBuilder - * @throws ParserConfigurationException - */ - public static DocumentBuilder createDocumentBuilderIgnoringDOCTYPE() throws ParserConfigurationException { - return DOCUMENT_BUILDER_FACTORY_IGNORING_DOCTYPE.newDocumentBuilder(); - } - - /** - * Creates DocumentBuilderFactory which throws SAXParseException when - * detecting external entities. - * - * @return javax.xml.parsers.DocumentBuilderFactory - */ - public static SAXParserFactory createSAXFactoryWithErrorOnDOCTYPE() { - SAXParserFactory f = SAXParserFactory.newInstance(); - try { - // force org.xml.sax.SAXParseException for any DOCTYPE: - f.setFeature("http://apache.org/xml/features/disallow-doctype-decl", true); //$NON-NLS-1$ - } catch (Exception e) { - throw new RuntimeException(e); - } - return f; - } - - private static synchronized SAXParserFactory createSAXFactoryWithErrorOnDOCTYPE(boolean awareness) { - SAXParserFactory f = SAXParserFactory.newInstance(); - f.setNamespaceAware(awareness); - try { - // force org.xml.sax.SAXParseException for any DOCTYPE: - f.setFeature("http://apache.org/xml/features/disallow-doctype-decl", true); //$NON-NLS-1$ - } catch (Exception e) { - throw new RuntimeException(e); - } - return f; - } - - private static synchronized SAXParserFactory createSAXFactoryIgnoringDOCTYPE() { - SAXParserFactory f = SAXParserFactory.newInstance(); - try { - // ignore DOCTYPE: - f.setFeature("http://xml.org/sax/features/external-general-entities", false); //$NON-NLS-1$ - f.setFeature("http://xml.org/sax/features/external-parameter-entities", false); //$NON-NLS-1$ - f.setFeature("http://apache.org/xml/features/nonvalidating/load-external-dtd", false); //$NON-NLS-1$ - } catch (Exception e) { - throw new RuntimeException(e); - } - return f; - } - - /** - * Creates SAXParser which throws SAXParseException when detecting external - * entities. - * - * @return javax.xml.parsers.SAXParser - */ - - public static SAXParser createSAXParserWithErrorOnDOCTYPE() throws ParserConfigurationException, SAXException { - return createSAXParserWithErrorOnDOCTYPE(false); - } - - /** - * Creates SAXParser which throws SAXParseException when detecting external - * entities. - * - * @param namespaceAware - * parameter for SAXParserFactory - * - * @return javax.xml.parsers.SAXParser - */ - public static SAXParser createSAXParserWithErrorOnDOCTYPE(boolean namespaceAware) - throws ParserConfigurationException, SAXException { - if (namespaceAware) { - return SAX_FACTORY_ERROR_ON_DOCTYPE_NS.newSAXParser(); - } - return SAX_FACTORY_ERROR_ON_DOCTYPE.newSAXParser(); - } - - /** - * Creates SAXParser which does not throw Exception when detecting external - * entities but ignores them. - * - * @return javax.xml.parsers.SAXParser - */ - public static SAXParser createSAXParserIgnoringDOCTYPE() - throws ParserConfigurationException, SAXNotRecognizedException, SAXNotSupportedException, SAXException { - SAXParser parser = SAX_FACTORY_IGNORING_DOCTYPE.newSAXParser(); - parser.setProperty(XMLConstants.ACCESS_EXTERNAL_DTD, ""); //$NON-NLS-1$ - parser.setProperty(XMLConstants.ACCESS_EXTERNAL_SCHEMA, ""); //$NON-NLS-1$ - return parser; - } -} \ No newline at end of file diff --git a/ui/org.eclipse.pde.core/src/org/eclipse/pde/internal/core/util/SAXParserWrapper.java b/ui/org.eclipse.pde.core/src/org/eclipse/pde/internal/core/util/SAXParserWrapper.java deleted file mode 100644 index 5f4455db151..00000000000 --- a/ui/org.eclipse.pde.core/src/org/eclipse/pde/internal/core/util/SAXParserWrapper.java +++ /dev/null @@ -1,49 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2000, 2008 IBM Corporation and others. - * - * 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 - *******************************************************************************/ - -package org.eclipse.pde.internal.core.util; - -import java.io.File; -import java.io.IOException; -import java.io.InputStream; - -import javax.xml.parsers.FactoryConfigurationError; -import javax.xml.parsers.ParserConfigurationException; -import javax.xml.parsers.SAXParser; - -import org.xml.sax.SAXException; -import org.xml.sax.helpers.DefaultHandler; - -/** - * SAXParserWrapper - * - */ -public class SAXParserWrapper { - - private SAXParserWrapper() { // static use only - } - - public static void parse(File f, DefaultHandler dh) - throws SAXException, IOException, ParserConfigurationException, FactoryConfigurationError { - SAXParser fParser = PDEXmlProcessorFactory.createSAXParserWithErrorOnDOCTYPE(); - fParser.parse(f, dh); - } - - public static void parse(InputStream is, DefaultHandler dh) - throws SAXException, IOException, ParserConfigurationException, FactoryConfigurationError { - SAXParser fParser = PDEXmlProcessorFactory.createSAXParserWithErrorOnDOCTYPE(); - fParser.parse(is, dh); - } - -} diff --git a/ui/org.eclipse.pde.core/src/org/eclipse/pde/internal/core/util/SchemaUtil.java b/ui/org.eclipse.pde.core/src/org/eclipse/pde/internal/core/util/SchemaUtil.java index 0335c4d9999..1a0682ca541 100644 --- a/ui/org.eclipse.pde.core/src/org/eclipse/pde/internal/core/util/SchemaUtil.java +++ b/ui/org.eclipse.pde.core/src/org/eclipse/pde/internal/core/util/SchemaUtil.java @@ -23,6 +23,7 @@ import javax.xml.parsers.FactoryConfigurationError; import javax.xml.parsers.ParserConfigurationException; +import javax.xml.parsers.SAXParser; import org.eclipse.pde.internal.core.PDECore; import org.xml.sax.SAXException; @@ -65,7 +66,10 @@ public static void parseURL(URL url, DefaultHandler handler) { try { connection = getURLConnection(url); try (InputStream input = connection.getInputStream()) { - SAXParserWrapper.parse(input, handler); + @SuppressWarnings("restriction") + SAXParser parser = org.eclipse.core.internal.runtime.XmlProcessorFactory + .createSAXParserWithErrorOnDOCTYPE(); + parser.parse(input, handler); } } catch (MalformedURLException | SAXException e) { // Ignore diff --git a/ui/org.eclipse.pde.core/src_ant/org/eclipse/pde/internal/core/ant/ConvertSchemaToHTML.java b/ui/org.eclipse.pde.core/src_ant/org/eclipse/pde/internal/core/ant/ConvertSchemaToHTML.java index 7a2107fcbe1..1bb87a7280c 100644 --- a/ui/org.eclipse.pde.core/src_ant/org/eclipse/pde/internal/core/ant/ConvertSchemaToHTML.java +++ b/ui/org.eclipse.pde.core/src_ant/org/eclipse/pde/internal/core/ant/ConvertSchemaToHTML.java @@ -48,7 +48,6 @@ import org.eclipse.pde.internal.core.schema.Schema; import org.eclipse.pde.internal.core.schema.SchemaDescriptor; import org.eclipse.pde.internal.core.util.HeaderMap; -import org.eclipse.pde.internal.core.util.SAXParserWrapper; import org.osgi.framework.Constants; /** @@ -64,6 +63,7 @@ public class ConvertSchemaToHTML extends Task { private String additionalSearchPaths; @Override + @SuppressWarnings("restriction") public void execute() throws BuildException { if (destination == null) { throw new BuildException(NLS.bind(PDECoreMessages.Builders_Convert_missingAttribute, "destination")); //$NON-NLS-1$ @@ -98,7 +98,8 @@ public void execute() throws BuildException { try { File schemaFile = new File(model.getInstallLocation(), schemaLocation); XMLDefaultHandler handler = new XMLDefaultHandler(); - SAXParserWrapper.parse(schemaFile, handler); + org.eclipse.core.internal.runtime.XmlProcessorFactory.createSAXParserWithErrorOnDOCTYPE() + .parse(schemaFile, handler); URL url = schemaFile.toURL(); SchemaDescriptor desc = new SchemaDescriptor(extPoint.getFullId(), url, searchPaths); schema = (Schema) desc.getSchema(false); diff --git a/ui/org.eclipse.pde.core/text/org/eclipse/pde/internal/core/text/AbstractEditingModel.java b/ui/org.eclipse.pde.core/text/org/eclipse/pde/internal/core/text/AbstractEditingModel.java index 3c3f791be62..35e2ad593ea 100644 --- a/ui/org.eclipse.pde.core/text/org/eclipse/pde/internal/core/text/AbstractEditingModel.java +++ b/ui/org.eclipse.pde.core/text/org/eclipse/pde/internal/core/text/AbstractEditingModel.java @@ -13,7 +13,6 @@ *******************************************************************************/ package org.eclipse.pde.internal.core.text; -import java.io.BufferedInputStream; import java.io.ByteArrayInputStream; import java.io.InputStream; import java.io.PrintWriter; @@ -163,7 +162,7 @@ public final void reconciled(IDocument document) { public abstract void adjustOffsets(IDocument document) throws CoreException; protected InputStream getInputStream(IDocument document) { - return new BufferedInputStream(new ByteArrayInputStream(document.get().getBytes(getCharset()))); + return new ByteArrayInputStream(document.get().getBytes(getCharset())); } @Override diff --git a/ui/org.eclipse.pde.core/text/org/eclipse/pde/internal/core/text/XMLEditingModel.java b/ui/org.eclipse.pde.core/text/org/eclipse/pde/internal/core/text/XMLEditingModel.java index a59bfba8b71..b31c9f915a3 100644 --- a/ui/org.eclipse.pde.core/text/org/eclipse/pde/internal/core/text/XMLEditingModel.java +++ b/ui/org.eclipse.pde.core/text/org/eclipse/pde/internal/core/text/XMLEditingModel.java @@ -33,7 +33,6 @@ import org.eclipse.pde.core.IWritable; import org.eclipse.pde.internal.core.NLResourceHelper; import org.eclipse.pde.internal.core.PDECore; -import org.eclipse.pde.internal.core.util.SAXParserWrapper; import org.xml.sax.SAXException; import org.xml.sax.helpers.DefaultHandler; @@ -46,11 +45,13 @@ public XMLEditingModel(IDocument document, boolean isReconciling) { } @Override + @SuppressWarnings("restriction") public void load(InputStream source, boolean outOfSync) { try { fLoaded = true; status = Status.OK_STATUS; - SAXParserWrapper.parse(source, createDocumentHandler(this, true)); + org.eclipse.core.internal.runtime.XmlProcessorFactory.createSAXParserWithErrorOnDOCTYPE().parse(source, + createDocumentHandler(this, true)); } catch (SAXException e) { fLoaded = false; status = Status.error(e.getMessage(), e); @@ -67,9 +68,11 @@ public IStatus getStatus() { protected abstract DefaultHandler createDocumentHandler(IModel model, boolean reconciling); @Override + @SuppressWarnings("restriction") public void adjustOffsets(IDocument document) { try { - SAXParserWrapper.parse(getInputStream(document), createDocumentHandler(this, false)); + org.eclipse.core.internal.runtime.XmlProcessorFactory.createSAXParserWithErrorOnDOCTYPE() + .parse(getInputStream(document), createDocumentHandler(this, false)); } catch (SAXException | IOException | ParserConfigurationException | FactoryConfigurationError e) { } } diff --git a/ui/org.eclipse.pde.ui.tests/src/org/eclipse/pde/core/tests/internal/PDEXmlProcessorFactoryTest.java b/ui/org.eclipse.pde.ui.tests/src/org/eclipse/pde/core/tests/internal/PDEXmlProcessorFactoryTest.java index 7ba4c684bdf..6c7cbebe5f8 100644 --- a/ui/org.eclipse.pde.ui.tests/src/org/eclipse/pde/core/tests/internal/PDEXmlProcessorFactoryTest.java +++ b/ui/org.eclipse.pde.ui.tests/src/org/eclipse/pde/core/tests/internal/PDEXmlProcessorFactoryTest.java @@ -51,7 +51,7 @@ import javax.xml.transform.stream.StreamResult; import javax.xml.transform.stream.StreamSource; -import org.eclipse.pde.internal.core.util.PDEXmlProcessorFactory; +import org.eclipse.core.internal.runtime.XmlProcessorFactory; import org.junit.Rule; import org.junit.Test; import org.junit.rules.TemporaryFolder; @@ -69,7 +69,7 @@ public class PDEXmlProcessorFactoryTest { @Test public void testParseXmlWithExternalEntity() throws Exception { - SAXParser parser = PDEXmlProcessorFactory.createSAXParserWithErrorOnDOCTYPE(); + SAXParser parser = XmlProcessorFactory.createSAXParserWithErrorOnDOCTYPE(); try { testParseXmlWithExternalEntity(parser, this::createMalciousXml); assertTrue("SAXParseException expected", false); @@ -82,19 +82,19 @@ public void testParseXmlWithExternalEntity() throws Exception { @Test public void testParseXmlWithoutExternalEntity() throws Exception { - SAXParser parser = PDEXmlProcessorFactory.createSAXParserWithErrorOnDOCTYPE(); + SAXParser parser = XmlProcessorFactory.createSAXParserWithErrorOnDOCTYPE(); testParseXmlWithExternalEntity(parser, this::createNormalXml); } @Test public void testParseXmlWithIgnoredExternalEntity() throws Exception { - SAXParser parser = PDEXmlProcessorFactory.createSAXParserIgnoringDOCTYPE(); + SAXParser parser = XmlProcessorFactory.createSAXParserIgnoringDOCTYPE(); testParseXmlWithExternalEntity(parser, this::createMalciousXml); } @Test public void testParseXmlWithoutIgnoredExternalEntity() throws Exception { - SAXParser parser = PDEXmlProcessorFactory.createSAXParserIgnoringDOCTYPE(); + SAXParser parser = XmlProcessorFactory.createSAXParserIgnoringDOCTYPE(); testParseXmlWithExternalEntity(parser, this::createNormalXml); } @@ -140,7 +140,7 @@ public InputSource resolveEntity(String publicId, String systemId) throws IOExce @Test public void testDocumentBuilderXmlWithExternalEntity() throws Exception { - DocumentBuilder documentBuilder = PDEXmlProcessorFactory.createDocumentBuilderWithErrorOnDOCTYPE(); + DocumentBuilder documentBuilder = XmlProcessorFactory.createDocumentBuilderWithErrorOnDOCTYPE(); try { testParseXmlWithExternalEntity(documentBuilder, this::createMalciousXml); assertTrue("SAXParseException expected", false); @@ -152,40 +152,37 @@ public void testDocumentBuilderXmlWithExternalEntity() throws Exception { @Test public void testDocumentBuilderFactoryWithoutExternalEntity() throws Exception { - DocumentBuilderFactory documentBuilderFactory = PDEXmlProcessorFactory - .createDocumentBuilderFactoryWithErrorOnDOCTYPE(); + DocumentBuilderFactory documentBuilderFactory = XmlProcessorFactory.createDocumentBuilderFactoryWithErrorOnDOCTYPE(); testParseXmlWithExternalEntity(documentBuilderFactory.newDocumentBuilder(), this::createNormalXml); } @Test public void testDocumentBuilderWithoutExternalEntity() throws Exception { - DocumentBuilder documentBuilder = PDEXmlProcessorFactory.createDocumentBuilderWithErrorOnDOCTYPE(); + DocumentBuilder documentBuilder = XmlProcessorFactory.createDocumentBuilderWithErrorOnDOCTYPE(); testParseXmlWithExternalEntity(documentBuilder, this::createNormalXml); } @Test public void testDocumentBuilderFactoryIgnoringDoctypeNormal() throws Exception { - DocumentBuilderFactory documentBuilderFactory = PDEXmlProcessorFactory - .createDocumentBuilderFactoryIgnoringDOCTYPE(); + DocumentBuilderFactory documentBuilderFactory = XmlProcessorFactory.createDocumentBuilderFactoryIgnoringDOCTYPE(); testParseXmlWithExternalEntity(documentBuilderFactory.newDocumentBuilder(), this::createNormalXml); } @Test public void testDocumentBuilderFactoryIgnoringDoctypeMalcious() throws Exception { - DocumentBuilderFactory documentBuilderFactory = PDEXmlProcessorFactory - .createDocumentBuilderFactoryIgnoringDOCTYPE(); + DocumentBuilderFactory documentBuilderFactory = XmlProcessorFactory.createDocumentBuilderFactoryIgnoringDOCTYPE(); testParseXmlWithExternalEntity(documentBuilderFactory.newDocumentBuilder(), this::createMalciousXml); } @Test public void testDocumentBuilderIgnoringDoctypeNormal() throws Exception { - testParseXmlWithExternalEntity(PDEXmlProcessorFactory.createDocumentBuilderIgnoringDOCTYPE(), + testParseXmlWithExternalEntity(XmlProcessorFactory.createDocumentBuilderIgnoringDOCTYPE(), this::createNormalXml); } @Test public void testDocumentBuilderIgnoringDoctypeMalcious() throws Exception { - testParseXmlWithExternalEntity(PDEXmlProcessorFactory.createDocumentBuilderIgnoringDOCTYPE(), + testParseXmlWithExternalEntity(XmlProcessorFactory.createDocumentBuilderIgnoringDOCTYPE(), this::createMalciousXml); } @@ -209,8 +206,7 @@ public void testParseXmlWithExternalEntity(DocumentBuilder builder, IntFunction< @Test public void testTransformXmlWithExternalEntity() throws Exception { - TransformerFactory transformerFactory = PDEXmlProcessorFactory - .createTransformerFactoryWithErrorOnDOCTYPE(); + TransformerFactory transformerFactory = XmlProcessorFactory.createTransformerFactoryWithErrorOnDOCTYPE(); try { testParseXmlWithExternalEntity(transformerFactory, this::createMalciousXml); assertTrue("TransformerException expected", false); @@ -222,8 +218,7 @@ public void testTransformXmlWithExternalEntity() throws Exception { @Test public void testTransformXmlWithoutExternalEntity() throws Exception { - TransformerFactory transformerFactory = PDEXmlProcessorFactory - .createTransformerFactoryWithErrorOnDOCTYPE(); + TransformerFactory transformerFactory = XmlProcessorFactory.createTransformerFactoryWithErrorOnDOCTYPE(); testParseXmlWithExternalEntity(transformerFactory, this::createNormalXml); } @@ -339,31 +334,31 @@ public static void main(String[] args) throws Exception { public static void main(String[] args) throws Exception { for (int i = 1; i < 1000; i++) { long n0 = System.nanoTime(); - sink = PDEXmlProcessorFactory.createSAXParserIgnoringDOCTYPE(); + sink = XmlProcessorFactory.createSAXParserIgnoringDOCTYPE(); long n1 = System.nanoTime(); System.out.println("createSAXParserIgnoringDOCTYPE run " + i + ": " + (n1 - n0) + "ns"); // ~ run 999: 60000ns =0,06ms n0 = System.nanoTime(); - sink = PDEXmlProcessorFactory.createDocumentBuilderFactoryWithErrorOnDOCTYPE(); + sink = XmlProcessorFactory.createDocumentBuilderFactoryWithErrorOnDOCTYPE(); n1 = System.nanoTime(); System.out.println("createDocumentBuilderFactoryWithErrorOnDOCTYPE run " + i + ": " + (n1 - n0) + "ns"); // ~ run 999: 5000000ns =5ms n0 = System.nanoTime(); - sink = PDEXmlProcessorFactory.createDocumentBuilderIgnoringDOCTYPE(); + sink = XmlProcessorFactory.createDocumentBuilderIgnoringDOCTYPE(); n1 = System.nanoTime(); System.out.println("createDocumentBuilderIgnoringDOCTYPE run " + i + ": " + (n1 - n0) + "ns"); // ~ run 999: 40000ns =0,04ms n0 = System.nanoTime(); - sink = PDEXmlProcessorFactory.createDocumentBuilderWithErrorOnDOCTYPE(); + sink = XmlProcessorFactory.createDocumentBuilderWithErrorOnDOCTYPE(); n1 = System.nanoTime(); System.out.println("createDocumentBuilderWithErrorOnDOCTYPE run " + i + ": " + (n1 - n0) + "ns"); // ~ run 999: 30000ns =0,03ms n0 = System.nanoTime(); - sink = PDEXmlProcessorFactory.createTransformerFactoryWithErrorOnDOCTYPE(); + sink = XmlProcessorFactory.createTransformerFactoryWithErrorOnDOCTYPE(); n1 = System.nanoTime(); System.out.println("createTransformerFactoryWithErrorOnDOCTYPE run " + i + ": " + (n1 - n0) + "ns"); // ~ run 999: 5000000ns =5ms diff --git a/ui/org.eclipse.pde.ui.tests/src/org/eclipse/pde/core/tests/internal/feature/FeatureDataTestCase.java b/ui/org.eclipse.pde.ui.tests/src/org/eclipse/pde/core/tests/internal/feature/FeatureDataTestCase.java index fc29f0cba64..bda388d715f 100644 --- a/ui/org.eclipse.pde.ui.tests/src/org/eclipse/pde/core/tests/internal/feature/FeatureDataTestCase.java +++ b/ui/org.eclipse.pde.ui.tests/src/org/eclipse/pde/core/tests/internal/feature/FeatureDataTestCase.java @@ -22,11 +22,11 @@ import javax.xml.parsers.DocumentBuilder; +import org.eclipse.core.internal.runtime.XmlProcessorFactory; import org.eclipse.core.runtime.CoreException; import org.eclipse.pde.internal.core.feature.FeatureData; import org.eclipse.pde.internal.core.feature.WorkspaceFeatureModel; import org.eclipse.pde.internal.core.ifeature.IFeatureModel; -import org.eclipse.pde.internal.core.util.PDEXmlProcessorFactory; import org.junit.Test; import org.w3c.dom.Document; import org.w3c.dom.Node; @@ -91,7 +91,7 @@ private String toXml(FeatureData data) { } public static FeatureData fromXml(String xml) throws Exception { - DocumentBuilder builder = PDEXmlProcessorFactory.createDocumentBuilderWithErrorOnDOCTYPE(); + DocumentBuilder builder = XmlProcessorFactory.createDocumentBuilderWithErrorOnDOCTYPE(); InputSource is = new InputSource(new StringReader(xml)); Document doc = builder.parse(is); diff --git a/ui/org.eclipse.pde.ui.tests/src/org/eclipse/pde/ui/tests/performance/parts/SchemaTraversePerfTest.java b/ui/org.eclipse.pde.ui.tests/src/org/eclipse/pde/ui/tests/performance/parts/SchemaTraversePerfTest.java index 65be6e79d14..b3142553a2e 100644 --- a/ui/org.eclipse.pde.ui.tests/src/org/eclipse/pde/ui/tests/performance/parts/SchemaTraversePerfTest.java +++ b/ui/org.eclipse.pde.ui.tests/src/org/eclipse/pde/ui/tests/performance/parts/SchemaTraversePerfTest.java @@ -18,9 +18,9 @@ import java.net.JarURLConnection; import java.net.URLConnection; +import org.eclipse.core.internal.runtime.XmlProcessorFactory; import org.eclipse.pde.internal.core.XMLDefaultHandler; import org.eclipse.pde.internal.core.schema.EditableSchema; -import org.eclipse.pde.internal.core.util.SAXParserWrapper; import org.eclipse.pde.internal.core.util.SchemaUtil; public class SchemaTraversePerfTest extends AbstractSchemaPerfTest { @@ -44,7 +44,7 @@ protected void executeTest() throws Exception { URLConnection connection = SchemaUtil.getURLConnection(fXSDFile.toURI().toURL()); try (InputStream input = connection.getInputStream()) { XMLDefaultHandler handler = new XMLDefaultHandler(true); - SAXParserWrapper.parse(input, handler); + XmlProcessorFactory.createSAXParserWithErrorOnDOCTYPE().parse(input, handler); EditableSchema schema = new EditableSchema("pluginID", "pointID", "name", true); schema.traverseDocumentTree(handler.getDocumentElement()); } finally { diff --git a/ui/org.eclipse.pde.ui.tests/src/org/eclipse/pde/ui/tests/target/IUBundleContainerTests.java b/ui/org.eclipse.pde.ui.tests/src/org/eclipse/pde/ui/tests/target/IUBundleContainerTests.java index e269ccab46f..2b0bb42162b 100644 --- a/ui/org.eclipse.pde.ui.tests/src/org/eclipse/pde/ui/tests/target/IUBundleContainerTests.java +++ b/ui/org.eclipse.pde.ui.tests/src/org/eclipse/pde/ui/tests/target/IUBundleContainerTests.java @@ -31,6 +31,7 @@ import javax.xml.parsers.DocumentBuilder; import org.eclipse.core.filesystem.URIUtil; +import org.eclipse.core.internal.runtime.XmlProcessorFactory; import org.eclipse.core.runtime.FileLocator; import org.eclipse.core.runtime.IPath; import org.eclipse.core.runtime.IStatus; @@ -51,7 +52,6 @@ import org.eclipse.pde.internal.core.target.TargetDefinition; import org.eclipse.pde.internal.core.target.TargetDefinitionPersistenceHelper; import org.eclipse.pde.internal.core.target.TargetPersistence38Helper; -import org.eclipse.pde.internal.core.util.PDEXmlProcessorFactory; import org.eclipse.pde.ui.tests.PDETestsPlugin; import org.junit.Test; import org.w3c.dom.Document; @@ -555,7 +555,7 @@ public void deserializationTest(IUBundleContainer location) throws Exception { ByteArrayOutputStream out = new ByteArrayOutputStream(); TargetDefinitionPersistenceHelper.persistXML(td, out); String xml = new String(out.toByteArray()); - DocumentBuilder parser = PDEXmlProcessorFactory.createDocumentBuilderWithErrorOnDOCTYPE(); + DocumentBuilder parser = XmlProcessorFactory.createDocumentBuilderWithErrorOnDOCTYPE(); parser.setErrorHandler(new DefaultHandler()); Document doc = parser.parse(new InputSource(new ByteArrayInputStream(xml.getBytes(StandardCharsets.UTF_8)))); diff --git a/ui/org.eclipse.pde.ui.tests/src/org/eclipse/pde/ui/tests/util/xml/ALLXMLUtilTests.java b/ui/org.eclipse.pde.ui.tests/src/org/eclipse/pde/ui/tests/util/xml/ALLXMLUtilTests.java deleted file mode 100644 index b1af49a22fa..00000000000 --- a/ui/org.eclipse.pde.ui.tests/src/org/eclipse/pde/ui/tests/util/xml/ALLXMLUtilTests.java +++ /dev/null @@ -1,24 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2006, 2017 IBM Corporation and others. - * - * 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 - *******************************************************************************/ -package org.eclipse.pde.ui.tests.util.xml; - -import org.junit.runner.RunWith; -import org.junit.runners.Suite; -import org.junit.runners.Suite.SuiteClasses; - -@RunWith(Suite.class) -@SuiteClasses({ ParserWrapperTestCase.class }) -public class ALLXMLUtilTests { - -} diff --git a/ui/org.eclipse.pde.ui.tests/src/org/eclipse/pde/ui/tests/util/xml/ParserWrapperTestCase.java b/ui/org.eclipse.pde.ui.tests/src/org/eclipse/pde/ui/tests/util/xml/ParserWrapperTestCase.java deleted file mode 100644 index 62550c049bb..00000000000 --- a/ui/org.eclipse.pde.ui.tests/src/org/eclipse/pde/ui/tests/util/xml/ParserWrapperTestCase.java +++ /dev/null @@ -1,125 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2000, 2018 IBM Corporation and others. - * - * 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 - *******************************************************************************/ - -package org.eclipse.pde.ui.tests.util.xml; - -import static org.junit.Assert.assertFalse; - -import java.io.File; -import java.io.IOException; -import java.net.URL; - -import javax.xml.parsers.FactoryConfigurationError; -import javax.xml.parsers.ParserConfigurationException; - -import org.eclipse.core.runtime.FileLocator; -import org.eclipse.pde.internal.core.XMLDefaultHandler; -import org.eclipse.pde.internal.core.util.SAXParserWrapper; -import org.eclipse.pde.ui.tests.PDETestsPlugin; -import org.junit.Before; -import org.junit.Test; -import org.osgi.framework.Bundle; -import org.xml.sax.SAXException; - -public class ParserWrapperTestCase { - - protected static final int FTHREADCOUNT = 5; - protected static final int FSAX = 0; - protected static final int FDOM = 1; - protected static File fXMLFile; - protected static final String FFILENAME = "/plugin.xml"; //$NON-NLS-1$ - - @Before - public void setUp() throws Exception { - PDETestsPlugin plugin = PDETestsPlugin.getDefault(); - if (plugin == null) - throw new Exception("ERROR: Macro plug-in uninitialized"); //$NON-NLS-1$ - Bundle bundle = plugin.getBundle(); - if (bundle == null) - throw new Exception("ERROR: Bundle uninitialized"); //$NON-NLS-1$ - URL url = bundle.getEntry(FFILENAME); - if (url == null) - throw new Exception("ERROR: URL not found: " + FFILENAME); //$NON-NLS-1$ - String path = FileLocator.resolve(url).getPath(); - if ("".equals(path)) //$NON-NLS-1$ - throw new Exception("ERROR: URL unresolved: " + FFILENAME); //$NON-NLS-1$ - fXMLFile = new File(path); - } - - @Test - public void testSAXParserWrapperConcurrency() throws Exception { - - ParserThread[] threads = new ParserThread[FTHREADCOUNT]; - - for (int x = 0; x < FTHREADCOUNT; x++) { - threads[x] = new ParserThread(FSAX, fXMLFile); - threads[x].start(); - } - - for (int x = 0; x < FTHREADCOUNT; x++) { - threads[x].join(); - assertFalse(threads[x].getError()); - } - - } - - public static class ParserThread extends Thread { - - protected final int FITERATIONS = 100; - protected File fParserXMLFile; - protected boolean fError; - protected int fParserType; - - public ParserThread(int parserType, File file) { - fError = false; - fParserType = parserType; - fParserXMLFile = file; - } - - @Override - public void run() { - - if (fParserType == ParserWrapperTestCase.FSAX) { - runSAX(); - } - } - - public void runSAX() { - - for (int x = 0; x < FITERATIONS; x++) { - - try { - XMLDefaultHandler handler = new XMLDefaultHandler(); - SAXParserWrapper.parse(fParserXMLFile, handler); - } catch (ParserConfigurationException | SAXException | FactoryConfigurationError | IOException e) { - e.printStackTrace(); - fError = true; - } - // If an error was encountered abort the thread - // Any type of exception experienced is bad - if (fError) - return; - - } - - } - - - public boolean getError() { - return fError; - } - - } - -} diff --git a/ui/org.eclipse.pde.ui/src/org/eclipse/pde/internal/ui/wizards/exports/FeatureExportWizard.java b/ui/org.eclipse.pde.ui/src/org/eclipse/pde/internal/ui/wizards/exports/FeatureExportWizard.java index 43b0d00f125..bebb7d9e770 100644 --- a/ui/org.eclipse.pde.ui/src/org/eclipse/pde/internal/ui/wizards/exports/FeatureExportWizard.java +++ b/ui/org.eclipse.pde.ui/src/org/eclipse/pde/internal/ui/wizards/exports/FeatureExportWizard.java @@ -28,7 +28,6 @@ import org.eclipse.pde.internal.core.exports.FeatureExportInfo; import org.eclipse.pde.internal.core.exports.FeatureExportOperation; import org.eclipse.pde.internal.core.ifeature.IFeatureModel; -import org.eclipse.pde.internal.core.util.PDEXmlProcessorFactory; import org.eclipse.pde.internal.ui.PDEPluginImages; import org.eclipse.pde.internal.ui.PDEUIMessages; import org.eclipse.pde.internal.ui.build.RuntimeInstallJob; @@ -133,7 +132,9 @@ public void done(IJobChangeEvent event) { @Override protected Document generateAntTask() { try { - Document doc = PDEXmlProcessorFactory.createDocumentBuilderWithErrorOnDOCTYPE().newDocument(); + @SuppressWarnings("restriction") + Document doc = org.eclipse.core.internal.runtime.XmlProcessorFactory + .createDocumentBuilderWithErrorOnDOCTYPE().newDocument(); Element root = doc.createElement("project"); //$NON-NLS-1$ root.setAttribute("name", "build"); //$NON-NLS-1$ //$NON-NLS-2$ root.setAttribute("default", "feature_export"); //$NON-NLS-1$ //$NON-NLS-2$ diff --git a/ui/org.eclipse.pde.ui/src/org/eclipse/pde/internal/ui/wizards/exports/PluginExportWizard.java b/ui/org.eclipse.pde.ui/src/org/eclipse/pde/internal/ui/wizards/exports/PluginExportWizard.java index c0af2883246..5de7b972106 100644 --- a/ui/org.eclipse.pde.ui/src/org/eclipse/pde/internal/ui/wizards/exports/PluginExportWizard.java +++ b/ui/org.eclipse.pde.ui/src/org/eclipse/pde/internal/ui/wizards/exports/PluginExportWizard.java @@ -24,7 +24,6 @@ import org.eclipse.pde.core.plugin.IPluginModelBase; import org.eclipse.pde.internal.core.exports.FeatureExportInfo; import org.eclipse.pde.internal.core.exports.PluginExportOperation; -import org.eclipse.pde.internal.core.util.PDEXmlProcessorFactory; import org.eclipse.pde.internal.ui.PDEPluginImages; import org.eclipse.pde.internal.ui.PDEUIMessages; import org.eclipse.pde.internal.ui.build.RuntimeInstallJob; @@ -103,7 +102,9 @@ public void done(IJobChangeEvent event) { @Override protected Document generateAntTask() { try { - Document doc = PDEXmlProcessorFactory.createDocumentBuilderWithErrorOnDOCTYPE().newDocument(); + @SuppressWarnings("restriction") + Document doc = org.eclipse.core.internal.runtime.XmlProcessorFactory + .createDocumentBuilderWithErrorOnDOCTYPE().newDocument(); Element root = doc.createElement("project"); //$NON-NLS-1$ root.setAttribute("name", "build"); //$NON-NLS-1$ //$NON-NLS-2$ root.setAttribute("default", "plugin_export"); //$NON-NLS-1$ //$NON-NLS-2$ From 7b86df0b12fbf72832cfdd796d2e8409437a71f1 Mon Sep 17 00:00:00 2001 From: Hannes Wellmann Date: Thu, 20 Jul 2023 19:58:54 +0200 Subject: [PATCH 09/18] Unify XMLErrorReporter/DefaultSAXParser classes and show errors --- .../internal/ds/core/builders/DSBuilder.java | 4 +- .../ds/core/builders/DSErrorReporter.java | 44 ++- .../ds/core/builders/DSMarkerFactory.java | 45 --- .../ds/core/builders/DefaultSAXParser.java | 41 -- .../ds/core/builders/XMLErrorReporter.java | 365 ------------------ .../builders/ExtensionPointSchemaBuilder.java | 2 +- .../core/builders/UpdateSiteBuilder.java | 2 +- .../core/builders/XMLErrorReporter.java | 49 +-- 8 files changed, 38 insertions(+), 514 deletions(-) delete mode 100644 ds/org.eclipse.pde.ds.core/src/org/eclipse/pde/internal/ds/core/builders/DSMarkerFactory.java delete mode 100644 ds/org.eclipse.pde.ds.core/src/org/eclipse/pde/internal/ds/core/builders/DefaultSAXParser.java delete mode 100644 ds/org.eclipse.pde.ds.core/src/org/eclipse/pde/internal/ds/core/builders/XMLErrorReporter.java diff --git a/ds/org.eclipse.pde.ds.core/src/org/eclipse/pde/internal/ds/core/builders/DSBuilder.java b/ds/org.eclipse.pde.ds.core/src/org/eclipse/pde/internal/ds/core/builders/DSBuilder.java index 2d69d1cb481..eb18e51471d 100644 --- a/ds/org.eclipse.pde.ds.core/src/org/eclipse/pde/internal/ds/core/builders/DSBuilder.java +++ b/ds/org.eclipse.pde.ds.core/src/org/eclipse/pde/internal/ds/core/builders/DSBuilder.java @@ -33,7 +33,9 @@ import org.eclipse.core.runtime.jobs.ISchedulingRule; import org.eclipse.core.runtime.jobs.MultiRule; import org.eclipse.osgi.util.NLS; +import org.eclipse.pde.internal.core.builders.DefaultSAXParser; import org.eclipse.pde.internal.core.builders.PDEBuilderHelper; +import org.eclipse.pde.internal.core.builders.PDEMarkerFactory; import org.eclipse.pde.internal.ds.core.Activator; import org.eclipse.pde.internal.ds.core.Messages; @@ -130,7 +132,7 @@ protected IProject[] build(int kind, Map args, IProgressMonitor @Override protected void clean(IProgressMonitor monitor) throws CoreException { // bug 426874 - delete markers set and files created - getProject().deleteMarkers(DSMarkerFactory.MARKER_ID, true, IResource.DEPTH_INFINITE); + getProject().deleteMarkers(PDEMarkerFactory.MARKER_ID, true, IResource.DEPTH_INFINITE); } diff --git a/ds/org.eclipse.pde.ds.core/src/org/eclipse/pde/internal/ds/core/builders/DSErrorReporter.java b/ds/org.eclipse.pde.ds.core/src/org/eclipse/pde/internal/ds/core/builders/DSErrorReporter.java index c9b781141b0..a56ffafedc4 100644 --- a/ds/org.eclipse.pde.ds.core/src/org/eclipse/pde/internal/ds/core/builders/DSErrorReporter.java +++ b/ds/org.eclipse.pde.ds.core/src/org/eclipse/pde/internal/ds/core/builders/DSErrorReporter.java @@ -27,6 +27,8 @@ import org.eclipse.jdt.core.JavaCore; import org.eclipse.jface.text.Document; import org.eclipse.osgi.util.NLS; +import org.eclipse.pde.internal.core.builders.PDEMarkerFactory; +import org.eclipse.pde.internal.core.builders.XMLErrorReporter; import org.eclipse.pde.internal.core.text.IDocumentElementNode; import org.eclipse.pde.internal.core.util.CoreUtility; import org.eclipse.pde.internal.ds.core.Activator; @@ -56,7 +58,7 @@ public DSErrorReporter(IFile file) { } @Override - public void validateContent(IProgressMonitor monitor) { + public void validate(IProgressMonitor monitor) { try { Document textDocument = CoreUtility.getTextDocument(fFile @@ -93,7 +95,7 @@ private void reportIllegalAttributeValue(Element element, Attr attr) { String message = NLS.bind(Messages.DSErrorReporter_attrValue, attr .getValue(), attr.getName()); report(message, getLine(element, attr.getName()), ERROR, - DSMarkerFactory.CAT_OTHER); + PDEMarkerFactory.CAT_OTHER); } private void validateReferenceElements(IDSReference[] references) { @@ -147,7 +149,7 @@ private void reportInvalidTarget(Element element, String target) { .getAttribute(IDSConstants.ATTRIBUTE_REFERENCE_NAME); String message = NLS.bind(Messages.DSErrorReporter_invalidTarget, name, target); - report(message, getLine(element), ERROR, DSMarkerFactory.CAT_OTHER); + report(message, getLine(element), ERROR, PDEMarkerFactory.CAT_OTHER); } private void validateReferenceElementNames(Hashtable referencedNames, @@ -171,7 +173,7 @@ private void reportDuplicateReferenceElementName(Element element, Messages.DSErrorReporter_duplicateReferenceName, name); report(message, getLine(element, IDSConstants.ATTRIBUTE_REFERENCE_NAME), ERROR, - DSMarkerFactory.CAT_OTHER); + PDEMarkerFactory.CAT_OTHER); } private void validateReferencePolicy(Element element) { @@ -203,7 +205,7 @@ private void reportIllegalPolicy(Element element, String policy) { Attr attr = element .getAttributeNode(IDSConstants.ATTRIBUTE_REFERENCE_POLICY); report(message, getLine(element, attr.getName()), ERROR, - DSMarkerFactory.CAT_OTHER); + PDEMarkerFactory.CAT_OTHER); } private void validateReferenceCardinality(Element element) { @@ -242,7 +244,7 @@ private void reportIllegalCardinality(Element element, String cardinality) { if (attr == null || attr.getValue() == null || attr.getName() == null) return; report(message, getLine(element, attr.getName()), ERROR, - DSMarkerFactory.CAT_OTHER); + PDEMarkerFactory.CAT_OTHER); } private void validatePropertiesElements(IDSProperties[] propertiesElements) { @@ -261,7 +263,7 @@ private void validatePropertiesElements(IDSProperties[] propertiesElements) { .bind( Messages.DSErrorReporter_cannotFindProperties, properties.getEntry()), getLine(element), WARNING, - DSMarkerFactory.CAT_OTHER); + PDEMarkerFactory.CAT_OTHER); } } @@ -368,7 +370,7 @@ private void reportPropertyTypeCastException(Element element, String value, String message = NLS.bind( Messages.DSErrorReporter_propertyTypeCastException, new String[] { value, type }); - report(message, getLine(element), WARNING, DSMarkerFactory.CAT_OTHER); + report(message, getLine(element), WARNING, PDEMarkerFactory.CAT_OTHER); } /** @@ -409,7 +411,7 @@ private void validatePropertyAttrValueAndBody(Element element, private void reportEmptyPropertyValue(Element element, String propertyName) { String message = NLS.bind(Messages.DSErrorReporter_emptyPropertyValue, propertyName); - report(message, getLine(element), WARNING, DSMarkerFactory.CAT_OTHER); + report(message, getLine(element), WARNING, PDEMarkerFactory.CAT_OTHER); } @@ -418,7 +420,7 @@ private void reportSingleAndMultiplePropertyValues(Element element, String message = NLS.bind( Messages.DSErrorReporter_singleAndMultipleAttrValue, propertyName, value); - report(message, getLine(element), WARNING, DSMarkerFactory.CAT_OTHER); + report(message, getLine(element), WARNING, PDEMarkerFactory.CAT_OTHER); } private void validatePropertyTypes(Element element) { @@ -485,7 +487,7 @@ private void reportMissingRequiredAttribute(Element element, String attName, int severity) { String message = NLS.bind(Messages.DSErrorReporter_requiredAttribute, attName, element.getNodeName()); - report(message, getLine(element), severity, DSMarkerFactory.CAT_OTHER); + report(message, getLine(element), severity, PDEMarkerFactory.CAT_OTHER); } /** @@ -507,7 +509,7 @@ private void reportJavaTypeNotFound(String elementConstant, Element element = (Element) elementsByTagName.item(index); report(NLS.bind(Messages.DSErrorReporter_cannotFindJavaType, resource, attributeConstant), getLine(element), WARNING, - DSMarkerFactory.CAT_OTHER); + PDEMarkerFactory.CAT_OTHER); } private void validateComponentElement(IDSComponent component) { @@ -518,7 +520,7 @@ private void validateComponentElement(IDSComponent component) { report(NLS.bind(Messages.DSErrorReporter_requiredElement, IDSConstants.ELEMENT_IMPLEMENTATION), getLine(getDocumentRoot()), ERROR, - DSMarkerFactory.CAT_OTHER); + PDEMarkerFactory.CAT_OTHER); } // validate boolean values @@ -556,7 +558,7 @@ private void validateConfigurationPolicyAttribute(Element element, report( Messages.DSErrorReporter_invalidConfigurationPolicyValue, getLine(element), WARNING, - DSMarkerFactory.CAT_OTHER); + PDEMarkerFactory.CAT_OTHER); } } } @@ -589,13 +591,13 @@ private void validateImmediateAttribute(Element element, private void reportInvalidImmediateFactory(Element element) { report(Messages.DSErrorReporter_invalidImmediateValueFactory, - getLine(element), WARNING, DSMarkerFactory.CAT_OTHER); + getLine(element), WARNING, PDEMarkerFactory.CAT_OTHER); } private void reportInvalidImmediate(Element element) { report(Messages.DSErrorReporter_invalidImmediateValue, - getLine(element), WARNING, DSMarkerFactory.CAT_OTHER); + getLine(element), WARNING, PDEMarkerFactory.CAT_OTHER); } private void validateEmpty(Element element, Attr attr) { @@ -612,7 +614,7 @@ private void reportIllegalEmptyAttributeValue(Element element, Attr attr) { String message = NLS.bind(Messages.DSErrorReporter_emptyAttrValue, attr .getName()); report(message, getLine(element, attr.getName()), ERROR, - DSMarkerFactory.CAT_OTHER); + PDEMarkerFactory.CAT_OTHER); } private void validateServiceElement(IDSService service) { @@ -635,7 +637,7 @@ private void validateServiceElement(IDSService service) { private void reportEmptyService(Element element) { report(Messages.DSErrorReporter_illegalEmptyService, getLine(element), - ERROR, DSMarkerFactory.CAT_OTHER); + ERROR, PDEMarkerFactory.CAT_OTHER); } private void validateServiceFactory(Element element, IDSService service) { @@ -658,14 +660,14 @@ private void validateServiceFactory(Element element, IDSService service) { private void reportIllegalServiceFactory_Immediate(Element element) { report(Messages.DSErrorReporter_illegalServiceFactory_Immediate, - getLine(element), ERROR, DSMarkerFactory.CAT_OTHER); + getLine(element), ERROR, PDEMarkerFactory.CAT_OTHER); } private void reportIllegalServiceFactory(Element element) { report(Messages.DSErrorReporter_illegalServiceFactory, - getLine(element), ERROR, DSMarkerFactory.CAT_OTHER); + getLine(element), ERROR, PDEMarkerFactory.CAT_OTHER); } private void validateProvideElement(IDSProvide[] providedServices) { @@ -702,7 +704,7 @@ private void validateDuplicateInterface(Hashtable providedInterf String message = NLS.bind( Messages.DSErrorReporter_duplicatedInterface, interface1); report(message, getLine(element), WARNING, - DSMarkerFactory.CAT_OTHER); + PDEMarkerFactory.CAT_OTHER); } else { providedInterfaces.put(interface1, interface1); } diff --git a/ds/org.eclipse.pde.ds.core/src/org/eclipse/pde/internal/ds/core/builders/DSMarkerFactory.java b/ds/org.eclipse.pde.ds.core/src/org/eclipse/pde/internal/ds/core/builders/DSMarkerFactory.java deleted file mode 100644 index 16919d6d755..00000000000 --- a/ds/org.eclipse.pde.ds.core/src/org/eclipse/pde/internal/ds/core/builders/DSMarkerFactory.java +++ /dev/null @@ -1,45 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2008 IBM Corporation and others. - * - * 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 - * Rafael Oliveira Nóbrega - bug 230232 - *******************************************************************************/ -package org.eclipse.pde.internal.ds.core.builders; - -import org.eclipse.core.resources.IFile; -import org.eclipse.core.resources.IMarker; -import org.eclipse.core.runtime.CoreException; - -public class DSMarkerFactory { - - public static final String MARKER_ID = "org.eclipse.pde.ds.core.problem"; //$NON-NLS-1$ - public static final int NO_RESOLUTION = -1; - - public static final String CAT_OTHER = ""; //$NON-NLS-1$ - - /** - * @param file - * @return - * @throws CoreException - */ - public IMarker createMarker(IFile file) throws CoreException { - return createMarker(file, NO_RESOLUTION, ""); //$NON-NLS-1$ - } - - public IMarker createMarker(IFile file, int id, String category) - throws CoreException { - IMarker marker = file.createMarker(MARKER_ID); - marker.setAttribute("id", id); //$NON-NLS-1$ - marker.setAttribute("categoryId", category); //$NON-NLS-1$ - return marker; - } - -} diff --git a/ds/org.eclipse.pde.ds.core/src/org/eclipse/pde/internal/ds/core/builders/DefaultSAXParser.java b/ds/org.eclipse.pde.ds.core/src/org/eclipse/pde/internal/ds/core/builders/DefaultSAXParser.java deleted file mode 100644 index 7732776cae3..00000000000 --- a/ds/org.eclipse.pde.ds.core/src/org/eclipse/pde/internal/ds/core/builders/DefaultSAXParser.java +++ /dev/null @@ -1,41 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2008 IBM Corporation and others. - * - * 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 - * Rafael Oliveira N√≥brega - bug 230232 - *******************************************************************************/ - -package org.eclipse.pde.internal.ds.core.builders; - -import java.io.BufferedInputStream; -import java.io.IOException; -import java.io.InputStream; - -import javax.xml.parsers.ParserConfigurationException; -import javax.xml.parsers.SAXParser; - -import org.eclipse.core.resources.IFile; -import org.eclipse.core.runtime.CoreException; -import org.xml.sax.SAXException; - -public class DefaultSAXParser { - - public static void parse(IFile file, XMLErrorReporter reporter) { - try (InputStream stream = new BufferedInputStream(file.getContents())) { - @SuppressWarnings("restriction") - SAXParser parser = org.eclipse.core.internal.runtime.XmlProcessorFactory - .createSAXParserWithErrorOnDOCTYPE(); - parser.parse(stream, - reporter); - } catch (CoreException | SAXException | IOException | ParserConfigurationException e) { - } - } -} diff --git a/ds/org.eclipse.pde.ds.core/src/org/eclipse/pde/internal/ds/core/builders/XMLErrorReporter.java b/ds/org.eclipse.pde.ds.core/src/org/eclipse/pde/internal/ds/core/builders/XMLErrorReporter.java deleted file mode 100644 index cb464d8ebe2..00000000000 --- a/ds/org.eclipse.pde.ds.core/src/org/eclipse/pde/internal/ds/core/builders/XMLErrorReporter.java +++ /dev/null @@ -1,365 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2008, 2015 IBM Corporation and others. - * - * 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 - *******************************************************************************/ -package org.eclipse.pde.internal.ds.core.builders; - -import java.io.StringReader; -import java.util.ArrayList; -import java.util.HashMap; -import java.util.Stack; - -import javax.xml.parsers.ParserConfigurationException; - -import org.eclipse.core.filebuffers.FileBuffers; -import org.eclipse.core.filebuffers.ITextFileBufferManager; -import org.eclipse.core.filebuffers.LocationKind; -import org.eclipse.core.resources.IFile; -import org.eclipse.core.resources.IMarker; -import org.eclipse.core.resources.IProject; -import org.eclipse.core.resources.IResource; -import org.eclipse.core.runtime.CoreException; -import org.eclipse.core.runtime.IProgressMonitor; -import org.eclipse.jface.text.BadLocationException; -import org.eclipse.jface.text.FindReplaceDocumentAdapter; -import org.eclipse.jface.text.IDocument; -import org.eclipse.jface.text.IRegion; -import org.eclipse.jface.text.Position; -import org.eclipse.pde.internal.core.builders.CompilerFlags; -import org.w3c.dom.Element; -import org.w3c.dom.Text; -import org.xml.sax.Attributes; -import org.xml.sax.InputSource; -import org.xml.sax.Locator; -import org.xml.sax.SAXException; -import org.xml.sax.SAXParseException; -import org.xml.sax.helpers.DefaultHandler; - -public class XMLErrorReporter extends DefaultHandler { - - public static final char F_ATT_PREFIX = '@'; - public static final char F_ATT_VALUE_PREFIX = '!'; - public static final char F_CHILD_SEP = '>'; - - static class ElementData { - int offset; - boolean fErrorNode; - - public ElementData(int offset) { - this.offset = offset; - } - } - - protected IFile fFile; - protected IProject fProject; - private int fErrorCount; - private DSMarkerFactory fMarkerFactory; - private org.w3c.dom.Document fXMLDocument; - private IDocument fTextDocument; - private Stack fElementStack; - private Element fRootElement; - private Locator fLocator; - private int fHighestOffset; - private HashMap fOffsetTable; - private FindReplaceDocumentAdapter fFindReplaceAdapter; - - public XMLErrorReporter(IFile file) { - ITextFileBufferManager manager = FileBuffers.getTextFileBufferManager(); - try { - fFile = file; - fProject = file.getProject(); - manager.connect(file.getFullPath(), LocationKind.NORMALIZE, null); - fTextDocument = manager.getTextFileBuffer(file.getFullPath(), LocationKind.NORMALIZE).getDocument(); - manager.disconnect(file.getFullPath(), LocationKind.NORMALIZE, null); - fFindReplaceAdapter = new FindReplaceDocumentAdapter(fTextDocument); - fOffsetTable = new HashMap<>(); - fElementStack = new Stack<>(); - removeFileMarkers(); - } catch (CoreException e) { - // TODO log message - } - } - - public IFile getFile() { - return fFile; - } - - private IMarker addMarker(String message, int lineNumber, int severity, int fixId, String category) { - try { - IMarker marker = getMarkerFactory().createMarker(fFile, fixId, category); - marker.setAttribute(IMarker.MESSAGE, message); - marker.setAttribute(IMarker.SEVERITY, severity); - if (lineNumber == -1) - lineNumber = 1; - marker.setAttribute(IMarker.LINE_NUMBER, lineNumber); - if (severity == IMarker.SEVERITY_ERROR) - fErrorCount += 1; - return marker; - } catch (CoreException e) { - // TODO log something - } - return null; - } - - private DSMarkerFactory getMarkerFactory() { - if (fMarkerFactory == null) - fMarkerFactory = new DSMarkerFactory(); - return fMarkerFactory; - } - - private void addMarker(SAXParseException e, int severity) { - addMarker(e.getMessage(), e.getLineNumber(), severity, - DSMarkerFactory.NO_RESOLUTION, DSMarkerFactory.CAT_OTHER); - } - - @Override - public void error(SAXParseException exception) throws SAXException { - addMarker(exception, IMarker.SEVERITY_ERROR); - generateErrorElementHierarchy(); - } - - @Override - public void fatalError(SAXParseException exception) throws SAXException { - addMarker(exception, IMarker.SEVERITY_ERROR); - generateErrorElementHierarchy(); - } - - public int getErrorCount() { - return fErrorCount; - } - - private void removeFileMarkers() { - try { - fFile.deleteMarkers(IMarker.PROBLEM, false, IResource.DEPTH_ZERO); - fFile.deleteMarkers(DSMarkerFactory.MARKER_ID, false, IResource.DEPTH_ZERO); - } catch (CoreException e) { - // TODO log exception - } - } - - - public IMarker report(String message, int line, int severity, int fixId, String category) { - if (severity == CompilerFlags.ERROR) - return addMarker(message, line, IMarker.SEVERITY_ERROR, fixId, category); - if (severity == CompilerFlags.WARNING) - return addMarker(message, line, IMarker.SEVERITY_WARNING, fixId, category); - return null; - } - - public IMarker report(String message, int line, int severity, String category) { - return report(message, line, severity, DSMarkerFactory.NO_RESOLUTION, - category); - } - - @Override - public void warning(SAXParseException exception) throws SAXException { - addMarker(exception, IMarker.SEVERITY_WARNING); - } - - @Override - @SuppressWarnings("restriction") - public void startDocument() throws SAXException { - try { - // TODO we should be using a dom level 2 impl - fXMLDocument = org.eclipse.core.internal.runtime.XmlProcessorFactory - .createDocumentBuilderWithErrorOnDOCTYPE().newDocument(); - } catch (ParserConfigurationException e) { - } - } - - @Override - public void endDocument() throws SAXException { - fXMLDocument.appendChild(fRootElement); - } - - @Override - public void startElement(String uri, String localName, String qName, Attributes attributes) throws SAXException { - Element element = fXMLDocument.createElement(qName); - for (int i = 0; i < attributes.getLength(); i++) { - element.setAttribute(attributes.getQName(i), attributes.getValue(i)); - } - - if (fRootElement == null) - fRootElement = element; - else - fElementStack.peek().appendChild(element); - fElementStack.push(element); - try { - if (fTextDocument != null) - fOffsetTable.put(element, new ElementData(getStartOffset(qName))); - } catch (BadLocationException e) { - } - } - - @Override - public void endElement(String uri, String localName, String qName) throws SAXException { - fElementStack.pop(); - } - - private void generateErrorElementHierarchy() { - while (!fElementStack.isEmpty()) { - ElementData data = fOffsetTable.get(fElementStack.pop()); - if (data != null) - data.fErrorNode = true; - } - } - - @Override - public void characters(char[] characters, int start, int length) throws SAXException { - StringBuilder buff = new StringBuilder(); - for (int i = 0; i < length; i++) { - buff.append(characters[start + i]); - } - Text text = fXMLDocument.createTextNode(buff.toString()); - if (fRootElement == null) - fXMLDocument.appendChild(text); - else - fElementStack.peek().appendChild(text); - } - - @Override - public void setDocumentLocator(Locator locator) { - fLocator = locator; - } - - private int getStartOffset(String elementName) throws BadLocationException { - int line = fLocator.getLineNumber(); - int col = fLocator.getColumnNumber(); - if (col < 0) - col = fTextDocument.getLineLength(line); - String text = fTextDocument.get(fHighestOffset + 1, fTextDocument.getLineOffset(line) - fHighestOffset - 1); - - ArrayList commentPositions = new ArrayList<>(); - for (int idx = 0; idx < text.length();) { - idx = text.indexOf("", idx); //$NON-NLS-1$ - if (end == -1) - break; - - commentPositions.add(new Position(idx, end - idx)); - idx = end + 1; - } - - int idx = 0; - for (; idx < text.length(); idx += 1) { - idx = text.indexOf("<" + elementName, idx); //$NON-NLS-1$ - if (idx == -1) - break; - boolean valid = true; - for (int i = 0; i < commentPositions.size(); i++) { - Position pos = commentPositions.get(i); - if (pos.includes(idx)) { - valid = false; - break; - } - } - if (valid) - break; - } - if (idx > -1) - fHighestOffset += idx + 1; - return fHighestOffset; - } - - private int getAttributeOffset(String name, String value, int offset) throws BadLocationException { - IRegion nameRegion = fFindReplaceAdapter.find(offset, name + "=\"" + getWritableString(value), true, false, false, false); //$NON-NLS-1$ - if (nameRegion != null) { - return nameRegion.getOffset(); - } - return -1; - } - - private String getWritableString(String source) { - StringBuilder buf = new StringBuilder(); - for (int i = 0; i < source.length(); i++) { - char c = source.charAt(i); - switch (c) { - case '&' : - buf.append("&"); //$NON-NLS-1$ - break; - case '<' : - buf.append("<"); //$NON-NLS-1$ - break; - case '>' : - buf.append(">"); //$NON-NLS-1$ - break; - case '\'' : - buf.append("'"); //$NON-NLS-1$ - break; - case '\"' : - buf.append("""); //$NON-NLS-1$ - break; - default : - buf.append(c); - break; - } - } - return buf.toString(); - } - - protected String getTextContent(Element element) { - ElementData data = fOffsetTable.get(element); - try { - IRegion nameRegion = fFindReplaceAdapter.find(data.offset, "", true, true, false, false); //$NON-NLS-1$ //$NON-NLS-2$ - int offset = data.offset + element.getNodeName().length() + 2; - if (nameRegion != null) - return fTextDocument.get(offset, nameRegion.getOffset() - offset).trim(); - } catch (BadLocationException e) { - } - return null; - } - - protected int getLine(Element element) { - ElementData data = fOffsetTable.get(element); - try { - return (data == null) ? 1 : fTextDocument.getLineOfOffset(data.offset) + 1; - } catch (Exception e) { - return 1; - } - } - - protected int getLine(Element element, String attName) { - ElementData data = fOffsetTable.get(element); - try { - int offset = getAttributeOffset(attName, element.getAttribute(attName), data.offset); - if (offset != -1) - return fTextDocument.getLineOfOffset(offset) + 1; - } catch (BadLocationException e) { - } - return getLine(element); - } - - public void validateContent(IProgressMonitor monitor) { - - } - - public Element getDocumentRoot() { - if (fRootElement != null) - fRootElement.normalize(); - return fRootElement; - } - - @Override - public InputSource resolveEntity(String publicId, String systemId) throws SAXException { - int x = fTextDocument.get().indexOf("!DOCTYPE"); //$NON-NLS-1$ - if (x > 0) { - // do something? - } - // Prevent the resolution of external entities in order to - // prevent the parser from accessing the Internet - // This will prevent huge workbench performance degradations and hangs - return new InputSource(new StringReader("")); //$NON-NLS-1$ - } - -} diff --git a/ui/org.eclipse.pde.core/src/org/eclipse/pde/internal/core/builders/ExtensionPointSchemaBuilder.java b/ui/org.eclipse.pde.core/src/org/eclipse/pde/internal/core/builders/ExtensionPointSchemaBuilder.java index a381b6a0983..92c27ebaa21 100644 --- a/ui/org.eclipse.pde.core/src/org/eclipse/pde/internal/core/builders/ExtensionPointSchemaBuilder.java +++ b/ui/org.eclipse.pde.core/src/org/eclipse/pde/internal/core/builders/ExtensionPointSchemaBuilder.java @@ -138,7 +138,7 @@ private void compileFile(IFile file, IProgressMonitor monitor) { SchemaErrorReporter reporter = new SchemaErrorReporter(file); DefaultSAXParser.parse(file, reporter); - reporter.validate(monitor); + reporter.validateContent(monitor); try (StringWriter swriter = new StringWriter(); PrintWriter writer = new PrintWriter(swriter)) { boolean generateDoc = CompilerFlags.getBoolean(file.getProject(), CompilerFlags.S_CREATE_DOCS); diff --git a/ui/org.eclipse.pde.core/src/org/eclipse/pde/internal/core/builders/UpdateSiteBuilder.java b/ui/org.eclipse.pde.core/src/org/eclipse/pde/internal/core/builders/UpdateSiteBuilder.java index bd0be468d81..e607025c689 100644 --- a/ui/org.eclipse.pde.core/src/org/eclipse/pde/internal/core/builders/UpdateSiteBuilder.java +++ b/ui/org.eclipse.pde.core/src/org/eclipse/pde/internal/core/builders/UpdateSiteBuilder.java @@ -97,7 +97,7 @@ private void checkFile(IFile file, IProgressMonitor monitor) { UpdateSiteErrorReporter reporter = new UpdateSiteErrorReporter(file); DefaultSAXParser.parse(file, reporter); if (reporter.getErrorCount() == 0) { - reporter.validate(monitor); + reporter.validateContent(monitor); } monitor.subTask(PDECoreMessages.Builders_updating); monitor.done(); diff --git a/ui/org.eclipse.pde.core/src/org/eclipse/pde/internal/core/builders/XMLErrorReporter.java b/ui/org.eclipse.pde.core/src/org/eclipse/pde/internal/core/builders/XMLErrorReporter.java index 842371ed691..a56694e727f 100644 --- a/ui/org.eclipse.pde.core/src/org/eclipse/pde/internal/core/builders/XMLErrorReporter.java +++ b/ui/org.eclipse.pde.core/src/org/eclipse/pde/internal/core/builders/XMLErrorReporter.java @@ -15,9 +15,11 @@ package org.eclipse.pde.internal.core.builders; import java.io.StringReader; +import java.util.ArrayDeque; import java.util.ArrayList; +import java.util.Deque; import java.util.HashMap; -import java.util.Stack; +import java.util.List; import javax.xml.parsers.ParserConfigurationException; @@ -38,6 +40,7 @@ import org.eclipse.pde.internal.core.PDECoreMessages; import org.eclipse.pde.internal.core.TargetPlatformHelper; import org.eclipse.pde.internal.core.builders.IncrementalErrorReporter.VirtualMarker; +import org.eclipse.pde.internal.core.util.PDEXMLHelper; import org.w3c.dom.Document; import org.w3c.dom.Element; import org.w3c.dom.Node; @@ -74,7 +77,7 @@ public ElementData(int offset) { private IDocument fTextDocument; - private Stack fElementStack; + private Deque fElementStack; private Element fRootElement; @@ -100,7 +103,7 @@ public XMLErrorReporter(IFile file) { manager.disconnect(file.getFullPath(), LocationKind.NORMALIZE, null); fFindReplaceAdapter = new FindReplaceDocumentAdapter(fTextDocument); fOffsetTable = new HashMap<>(); - fElementStack = new Stack<>(); + fElementStack = new ArrayDeque<>(); } catch (CoreException e) { PDECore.log(e); } @@ -268,13 +271,9 @@ public void setDocumentLocator(Locator locator) { private int getStartOffset(String elementName) throws BadLocationException { int line = fLocator.getLineNumber(); - int col = fLocator.getColumnNumber(); - if (col < 0) { - col = fTextDocument.getLineLength(line); - } String text = fTextDocument.get(fHighestOffset + 1, fTextDocument.getLineOffset(line) - fHighestOffset - 1); - ArrayList commentPositions = new ArrayList<>(); + List commentPositions = new ArrayList<>(); for (int idx = 0; idx < text.length();) { idx = text.indexOf("