diff --git a/.gitignore b/.gitignore index 622ef384ba..e820110b1b 100644 --- a/.gitignore +++ b/.gitignore @@ -19,6 +19,9 @@ gradle-app.setting # Avoid ignoring Gradle wrapper jar file (.jar files are usually ignored) !gradle-wrapper.jar +#Gradle-Lock files in _ext just serving as an input for lib-extra +_ext/*/gradle/dependency-locks/compileClasspath.lockfile + ### Eclipse ### *.pydevproject .metadata diff --git a/_ext/eclipse-base/LICENSE.txt b/_ext/eclipse-base/LICENSE.txt new file mode 100644 index 0000000000..3d967aee74 --- /dev/null +++ b/_ext/eclipse-base/LICENSE.txt @@ -0,0 +1,70 @@ +Eclipse Public License - v 1.0 + +THE ACCOMPANYING PROGRAM IS PROVIDED UNDER THE TERMS OF THIS ECLIPSE PUBLIC LICENSE ("AGREEMENT"). ANY USE, REPRODUCTION OR DISTRIBUTION OF THE PROGRAM CONSTITUTES RECIPIENT'S ACCEPTANCE OF THIS AGREEMENT. + +1. DEFINITIONS + +"Contribution" means: + +a) in the case of the initial Contributor, the initial code and documentation distributed under this Agreement, and +b) in the case of each subsequent Contributor: +i) changes to the Program, and +ii) additions to the Program; +where such changes and/or additions to the Program originate from and are distributed by that particular Contributor. A Contribution 'originates' from a Contributor if it was added to the Program by such Contributor itself or anyone acting on such Contributor's behalf. Contributions do not include additions to the Program which: (i) are separate modules of software distributed in conjunction with the Program under their own license agreement, and (ii) are not derivative works of the Program. +"Contributor" means any person or entity that distributes the Program. + +"Licensed Patents" mean patent claims licensable by a Contributor which are necessarily infringed by the use or sale of its Contribution alone or when combined with the Program. + +"Program" means the Contributions distributed in accordance with this Agreement. + +"Recipient" means anyone who receives the Program under this Agreement, including all Contributors. + +2. GRANT OF RIGHTS + +a) Subject to the terms of this Agreement, each Contributor hereby grants Recipient a non-exclusive, worldwide, royalty-free copyright license to reproduce, prepare derivative works of, publicly display, publicly perform, distribute and sublicense the Contribution of such Contributor, if any, and such derivative works, in source code and object code form. +b) Subject to the terms of this Agreement, each Contributor hereby grants Recipient a non-exclusive, worldwide, royalty-free patent license under Licensed Patents to make, use, sell, offer to sell, import and otherwise transfer the Contribution of such Contributor, if any, in source code and object code form. This patent license shall apply to the combination of the Contribution and the Program if, at the time the Contribution is added by the Contributor, such addition of the Contribution causes such combination to be covered by the Licensed Patents. The patent license shall not apply to any other combinations which include the Contribution. No hardware per se is licensed hereunder. +c) Recipient understands that although each Contributor grants the licenses to its Contributions set forth herein, no assurances are provided by any Contributor that the Program does not infringe the patent or other intellectual property rights of any other entity. Each Contributor disclaims any liability to Recipient for claims brought by any other entity based on infringement of intellectual property rights or otherwise. As a condition to exercising the rights and licenses granted hereunder, each Recipient hereby assumes sole responsibility to secure any other intellectual property rights needed, if any. For example, if a third party patent license is required to allow Recipient to distribute the Program, it is Recipient's responsibility to acquire that license before distributing the Program. +d) Each Contributor represents that to its knowledge it has sufficient copyright rights in its Contribution, if any, to grant the copyright license set forth in this Agreement. +3. REQUIREMENTS + +A Contributor may choose to distribute the Program in object code form under its own license agreement, provided that: + +a) it complies with the terms and conditions of this Agreement; and +b) its license agreement: +i) effectively disclaims on behalf of all Contributors all warranties and conditions, express and implied, including warranties or conditions of title and non-infringement, and implied warranties or conditions of merchantability and fitness for a particular purpose; +ii) effectively excludes on behalf of all Contributors all liability for damages, including direct, indirect, special, incidental and consequential damages, such as lost profits; +iii) states that any provisions which differ from this Agreement are offered by that Contributor alone and not by any other party; and +iv) states that source code for the Program is available from such Contributor, and informs licensees how to obtain it in a reasonable manner on or through a medium customarily used for software exchange. +When the Program is made available in source code form: + +a) it must be made available under this Agreement; and +b) a copy of this Agreement must be included with each copy of the Program. +Contributors may not remove or alter any copyright notices contained within the Program. + +Each Contributor must identify itself as the originator of its Contribution, if any, in a manner that reasonably allows subsequent Recipients to identify the originator of the Contribution. + +4. COMMERCIAL DISTRIBUTION + +Commercial distributors of software may accept certain responsibilities with respect to end users, business partners and the like. While this license is intended to facilitate the commercial use of the Program, the Contributor who includes the Program in a commercial product offering should do so in a manner which does not create potential liability for other Contributors. Therefore, if a Contributor includes the Program in a commercial product offering, such Contributor ("Commercial Contributor") hereby agrees to defend and indemnify every other Contributor ("Indemnified Contributor") against any losses, damages and costs (collectively "Losses") arising from claims, lawsuits and other legal actions brought by a third party against the Indemnified Contributor to the extent caused by the acts or omissions of such Commercial Contributor in connection with its distribution of the Program in a commercial product offering. The obligations in this section do not apply to any claims or Losses relating to any actual or alleged intellectual property infringement. In order to qualify, an Indemnified Contributor must: a) promptly notify the Commercial Contributor in writing of such claim, and b) allow the Commercial Contributor to control, and cooperate with the Commercial Contributor in, the defense and any related settlement negotiations. The Indemnified Contributor may participate in any such claim at its own expense. + +For example, a Contributor might include the Program in a commercial product offering, Product X. That Contributor is then a Commercial Contributor. If that Commercial Contributor then makes performance claims, or offers warranties related to Product X, those performance claims and warranties are such Commercial Contributor's responsibility alone. Under this section, the Commercial Contributor would have to defend claims against the other Contributors related to those performance claims and warranties, and if a court requires any other Contributor to pay any damages as a result, the Commercial Contributor must pay those damages. + +5. NO WARRANTY + +EXCEPT AS EXPRESSLY SET FORTH IN THIS AGREEMENT, THE PROGRAM IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, EITHER EXPRESS OR IMPLIED INCLUDING, WITHOUT LIMITATION, ANY WARRANTIES OR CONDITIONS OF TITLE, NON-INFRINGEMENT, MERCHANTABILITY OR FITNESS FOR A PARTICULAR PURPOSE. Each Recipient is solely responsible for determining the appropriateness of using and distributing the Program and assumes all risks associated with its exercise of rights under this Agreement , including but not limited to the risks and costs of program errors, compliance with applicable laws, damage to or loss of data, programs or equipment, and unavailability or interruption of operations. + +6. DISCLAIMER OF LIABILITY + +EXCEPT AS EXPRESSLY SET FORTH IN THIS AGREEMENT, NEITHER RECIPIENT NOR ANY CONTRIBUTORS SHALL HAVE ANY LIABILITY FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING WITHOUT LIMITATION LOST PROFITS), HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OR DISTRIBUTION OF THE PROGRAM OR THE EXERCISE OF ANY RIGHTS GRANTED HEREUNDER, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGES. + +7. GENERAL + +If any provision of this Agreement is invalid or unenforceable under applicable law, it shall not affect the validity or enforceability of the remainder of the terms of this Agreement, and without further action by the parties hereto, such provision shall be reformed to the minimum extent necessary to make such provision valid and enforceable. + +If Recipient institutes patent litigation against any entity (including a cross-claim or counterclaim in a lawsuit) alleging that the Program itself (excluding combinations of the Program with other software or hardware) infringes such Recipient's patent(s), then such Recipient's rights granted under Section 2(b) shall terminate as of the date such litigation is filed. + +All Recipient's rights under this Agreement shall terminate if it fails to comply with any of the material terms or conditions of this Agreement and does not cure such failure in a reasonable period of time after becoming aware of such noncompliance. If all Recipient's rights under this Agreement terminate, Recipient agrees to cease use and distribution of the Program as soon as reasonably practicable. However, Recipient's obligations under this Agreement and any licenses granted by Recipient relating to the Program shall continue and survive. + +Everyone is permitted to copy and distribute copies of this Agreement, but in order to avoid inconsistency the Agreement is copyrighted and may only be modified in the following manner. The Agreement Steward reserves the right to publish new versions (including revisions) of this Agreement from time to time. No one other than the Agreement Steward has the right to modify this Agreement. The Eclipse Foundation is the initial Agreement Steward. The Eclipse Foundation may assign the responsibility to serve as the Agreement Steward to a suitable separate entity. Each new version of the Agreement will be given a distinguishing version number. The Program (including Contributions) may always be distributed subject to the version of the Agreement under which it was received. In addition, after a new version of the Agreement is published, Contributor may elect to distribute the Program (including its Contributions) under the new version. Except as expressly stated in Sections 2(a) and 2(b) above, Recipient receives no rights or licenses to the intellectual property of any Contributor under this Agreement, whether expressly, by implication, estoppel or otherwise. All rights in the Program not expressly granted under this Agreement are reserved. + +This Agreement is governed by the laws of the State of New York and the intellectual property laws of the United States of America. No party to this Agreement will bring a legal action under this Agreement more than one year after the cause of action arose. Each party waives its rights to a jury trial in any resulting litigation. \ No newline at end of file diff --git a/_ext/eclipse-base/README.md b/_ext/eclipse-base/README.md new file mode 100644 index 0000000000..9f038db79a --- /dev/null +++ b/_ext/eclipse-base/README.md @@ -0,0 +1,66 @@ +# spotless-eclipse-base + +Eclipse formatters are embedded in plugins serving multiple purposes and not necessarily supporting headless builds. Hence the plugin interfaces are depending on various Eclipse plugins and services not required for the formatting purpose. + +Spotless provides its own plugin framework with `com.diffplug.spotless.JarState`. This allows Spotless to use different Eclipse versions in parallel. + + +The `com.diffplug.gradle.spotless:spotless-eclipse-base` artifact mocks the redundant Eclipse OSGI/plugin framework for Spotless. Furthermore it provides Eclipse services adapted for Spotless's own use, which avoids for example the creation of a permanent Eclipse workspace and reduces dependencies on Eclipse modules unused by the Eclipse code formatters. + +## Usage + +Include the artifact in your Spotless Eclipse formatter project, where the major version must match the Eclipse core version your formatter supports. The exact default version should be selected by the **lib-extra**. +Minor versions indicate a change in the minimum Eclipse (core/resource) dependencies. +Patch versions are always backward compatible. + + +```Gradle +dependencies { + compile "com.diffplug.spotless:spotless-eclipse-base:3.+" +} +``` + +In the constructor of your formatter, the Spotless Eclipse Framework can be configured depending on your formatter's requirements. For example the JDT formatter can be configured like: + +```Java +public EclipseFormatterStepImpl(Properties settings) throws Exception { + SpotlessEclipseFramework.setup(plugins -> { + plugins.applyDefault(); + plugins.add(new org.eclipse.jdt.core.JavaCore()); + }); + ... +``` + +The framework also supports fat JARs, providing multiple plugins. +In this cases the resources required by plugins, especially the `META-INF` and plugin information, must be located in locations unique +to the plugin. +For this purpose the framework expects that these resources are stored in a sub-directory +which has the name of the package containing the plugin. For example in case the JDT plugin +is included in your formatter fat JAR, the directory structure should be: + +``` ++ resources +| ++--+ org.eclipse.jdt.core +| | +| +--+ META-INF +| | | +| | +-- MANIFEST.MF +| | +| +--- plugin.properties +| | +| +--- plugin.xml + +``` + + +## Build + +``` +gradlew -b _ext/eclipse-base/build.gradle publish +``` + + +## License + +Spotless at large is under the Apache 2.0 license, but this jar is under the EPL v1. diff --git a/_ext/eclipse-base/build.gradle b/_ext/eclipse-base/build.gradle new file mode 100644 index 0000000000..97473ead19 --- /dev/null +++ b/_ext/eclipse-base/build.gradle @@ -0,0 +1,30 @@ +apply from: rootProject.file('../gradle/java-setup.gradle') +apply from: rootProject.file('../gradle/java-publish.gradle') + +ext { + developers = [ + fvgh: [ name: 'Frank Vennemeyer', email: 'frankgh@zoho.com' ] + ] +} + +dependencies { + compile("org.eclipse.platform:org.eclipse.core.resources:${VER_ECLIPSE_CORE_RESOURCES}") { + exclude group: 'org.eclipse.platform', module: 'org.eclipse.ant.core' + exclude group: 'org.eclipse.platform', module: 'org.eclipse.core.expressions' + exclude group: 'org.eclipse.platform', module: 'org.eclipse.core.filesystem' + } +} + +jar { + manifest { + from 'src/main/resources/META-INF/MANIFEST.MF' + } +} + +////////// +// Test // +////////// +sourceSets { + // Use JAR file with all resources for Eclipse-Base integration-tests + test.runtimeClasspath = jar.outputs.files + sourceSets.test.output + sourceSets.test.compileClasspath +} diff --git a/_ext/eclipse-base/gradle.properties b/_ext/eclipse-base/gradle.properties new file mode 100644 index 0000000000..693aa62383 --- /dev/null +++ b/_ext/eclipse-base/gradle.properties @@ -0,0 +1,15 @@ +# Mayor version correspond to the required Eclipse core version. +# Minor version changes in case the minimum Eclipse core dependencies are raised due to incompatibilities of their internal interfaces. +# Patch version is incremented in case of bug-fixes and evolutions. +ext_version=3.0.0-SNAPSHOT +ext_artifactId=spotless-eclipse-base +ext_description=Eclipse bundle controller and services for Spotless + +ext_org=diffplug +ext_group=com.diffplug.spotless + +# Build requirements +ext_VER_JAVA=1.8 + +# Compile dependencies +VER_ECLIPSE_CORE_RESOURCES=[3.11.0,4.0.0[ diff --git a/_ext/eclipse-base/src/main/java/com/diffplug/spotless/extra/eclipse/base/SpotlessEclipseCoreConfig.java b/_ext/eclipse-base/src/main/java/com/diffplug/spotless/extra/eclipse/base/SpotlessEclipseCoreConfig.java new file mode 100644 index 0000000000..f481c667cd --- /dev/null +++ b/_ext/eclipse-base/src/main/java/com/diffplug/spotless/extra/eclipse/base/SpotlessEclipseCoreConfig.java @@ -0,0 +1,52 @@ +/* + * Copyright 2016 DiffPlug + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package com.diffplug.spotless.extra.eclipse.base; + +import org.osgi.framework.BundleActivator; + +import com.diffplug.spotless.extra.eclipse.base.SpotlessEclipseFramework.DefaultBundles; +import com.diffplug.spotless.extra.eclipse.base.osgi.BundleConfig; + +/** + * Configuration of core bundles which shall be provided by the + * {@link SpotlessEclipseFramework}. + *

+ * Core bundles are not accessed via the plugin registry, but by static methods. + * Hence they do not require a registration, which allows a lightweight + * setup. + *

+ * @see org.eclipse.core.internal.runtime.PlatformActivator + */ +public class SpotlessEclipseCoreConfig extends BundleConfig { + + SpotlessEclipseCoreConfig() {} + + @Override + public void applyDefault() { + add(SpotlessEclipseFramework.DefaultBundles.createAll()); + } + + @Override + protected BundleActivator create(DefaultBundles bundle) { + return bundle.create(); + } + + @Override + protected int getDefaultState(DefaultBundles bundle) { + return bundle.getDesiredState(); + } + +} diff --git a/_ext/eclipse-base/src/main/java/com/diffplug/spotless/extra/eclipse/base/SpotlessEclipseFramework.java b/_ext/eclipse-base/src/main/java/com/diffplug/spotless/extra/eclipse/base/SpotlessEclipseFramework.java new file mode 100644 index 0000000000..6e1006b914 --- /dev/null +++ b/_ext/eclipse-base/src/main/java/com/diffplug/spotless/extra/eclipse/base/SpotlessEclipseFramework.java @@ -0,0 +1,252 @@ +/* + * Copyright 2016 DiffPlug + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package com.diffplug.spotless.extra.eclipse.base; + +import java.lang.reflect.Constructor; +import java.lang.reflect.InvocationTargetException; +import java.util.Arrays; +import java.util.List; +import java.util.function.Consumer; +import java.util.function.Function; +import java.util.stream.Collectors; + +import javax.xml.parsers.SAXParserFactory; + +import org.osgi.framework.Bundle; +import org.osgi.framework.BundleActivator; +import org.osgi.framework.BundleContext; +import org.osgi.framework.BundleException; + +import com.diffplug.spotless.extra.eclipse.base.osgi.BundleConfig; +import com.diffplug.spotless.extra.eclipse.base.osgi.BundleController; +import com.diffplug.spotless.extra.eclipse.base.runtime.PluginRegistrar; + +/** Setup a framework for Spotless Eclipse based formatters */ +public final class SpotlessEclipseFramework { + /** Spotless demands for internal formatter chains Unix (LF) line endings. */ + public static final String LINE_DELIMITER = "\n"; + + /** + * Default core bundles required by most plugins. + */ + public enum DefaultBundles { + /** + * Plugins ask the platform whether core runtime bundle is in debug mode. + *

+ * Note that the bundle requires the + * {@link org.eclipse.osgi.service.environment.EnvironmentInfo} + * service. + *

+ *

+ * Per default, the platform is not activated. Some plugins use this information + * to determine whether they are running in a headless modes (without IDE). + *

+ */ + PLATFORM(org.eclipse.core.internal.runtime.PlatformActivator.class, Bundle.RESOLVED), + /** The Spotless {@link BundleController} wraps the OSGi layer. But the plugin/extension look-up still uses the Eclipse OSGi registry.*/ + REGISTRY(org.eclipse.core.internal.registry.osgi.Activator.class), + /** Eclipse preferences always check whether this bundle has been activated before preference are set.*/ + PREFERENCES(org.eclipse.core.internal.preferences.Activator.class), + /** The common runtime provides provides common services, like log and service adapters registry. */ + COMMON(org.eclipse.core.internal.runtime.Activator.class); + + private final Class activatorClass; + private final int state; + + private DefaultBundles(Class clazz) { + this(clazz, Bundle.ACTIVE); + } + + private DefaultBundles(Class clazz, int state) { + activatorClass = clazz; + this.state = state; + } + + /** Create new bundle activator instance. */ + public BundleActivator create() { + return createInstance(activatorClass); + } + + public int getDesiredState() { + return state; + } + + /** Create bundle activator instances for all enumerated values. */ + public static List createAll() { + return Arrays.stream(values()) + .map(value -> new BundleConfig.Entry(value.create(), value.getDesiredState())).collect(Collectors.toList()); + } + } + + /** + * Default plugins required by most Spotless formatters. + *

+ * Eclipse plugins are OSGI bundles themselves and do not necessarily derive from the Eclipse Plugin class. + * {@link BundleActivator} implementation may as well serve as plugins. + * All plugins must provide a MANIFEST.MF, plugin.properties and plugin.xml description file, + * required for the plugin registration. + *

+ */ + public enum DefaultPlugins { + /** + * The resources plugin initialized the Eclipse workspace and allows URL look-up. + * Most formatters using the workspace to resolve URLs or create + * file interfaces. + * @see org.eclipse.core.resources.IFile + */ + RESOURCES(org.eclipse.core.resources.ResourcesPlugin.class); + + private final Class pluginClass; + + DefaultPlugins(Class clazz) { + pluginClass = clazz; + } + + /** Create new plugin instance. */ + public BundleActivator create() { + return createInstance(pluginClass); + } + + /** Create plugin instances for all enumerated values. */ + public static List createAll() { + return Arrays.stream(values()).map(value -> value.create()).collect(Collectors.toList()); + } + } + + private static T createInstance(Class clazz) { + try { + Constructor ctor = clazz.getConstructor(); + return ctor.newInstance(new Object[]{}); + } catch (InstantiationException | IllegalAccessException | IllegalArgumentException | InvocationTargetException | NoSuchMethodException | SecurityException e) { + throw new RuntimeException("Failed to create instance for: " + clazz.getCanonicalName(), e); + } + } + + private static SpotlessEclipseFramework INSTANCE = null; + + /** + * Creates and configures a new {@link SpotlessEclipseFramework} using + * {@link DefaultBundles}, {@link DefaultPlugins} and default {@link SpotlessEclipseServiceConfig}. + * If there is already a an instance, the call is ignored. + * @return False if the {@link SpotlessEclipseFramework} instance already exists, true otherwise. + * @throws BundleException Throws exception in case the setup failed. + */ + public synchronized static boolean setup() throws BundleException { + return setup(plugins -> plugins.applyDefault()); + } + + /** + * Creates and configures a new {@link SpotlessEclipseFramework} using + * {@link DefaultBundles} and {@link DefaultPlugins}. + * If there is already a an instance, the call is ignored. + * @param plugins Eclipse plugins (which are also OSGi bundles) to start + * @return False if the {@link SpotlessEclipseFramework} instance already exists, true otherwise. + * @throws BundleException Throws exception in case the setup failed. + */ + public synchronized static boolean setup(Consumer plugins) throws BundleException { + return setup(config -> config.applyDefault(), plugins); + } + + /** + * Creates and configures a new {@link SpotlessEclipseFramework} using {@link DefaultBundles}. + * If there is already a an instance, the call is ignored. + * @param config Framework service configuration + * @param plugins Eclipse plugins (which are also OSGi bundles) to start + * @return False if the {@link SpotlessEclipseFramework} instance already exists, true otherwise. + * @throws BundleException Throws exception in case the setup failed. + */ + public synchronized static boolean setup(Consumer config, Consumer plugins) throws BundleException { + return setup(core -> core.applyDefault(), config, plugins); + } + + /** + * Creates and configures a new {@link SpotlessEclipseFramework} if there is none. + * If there is already a an instance, the call is ignored. + * @param core Activators of core bundles + * @param config Framework service configuration + * @param plugins Eclipse plugins to start + * @return False if the {@link SpotlessEclipseFramework} instance already exists, true otherwise. + * @throws BundleException Throws exception in case the setup failed. + */ + public synchronized static boolean setup(Consumer core, Consumer config, Consumer plugins) throws BundleException { + if (null != INSTANCE) { + return false; + } + + SpotlessEclipseCoreConfig coreConfig = new SpotlessEclipseCoreConfig(); + core.accept(coreConfig); + + INSTANCE = new SpotlessEclipseFramework(coreConfig); + config.accept(INSTANCE.getServiceConfig()); + + SpotlessEclipsePluginConfig pluginConfig = new SpotlessEclipsePluginConfig(); + plugins.accept(pluginConfig); + for (BundleConfig.Entry plugin : pluginConfig.get()) { + INSTANCE.addPlugin(plugin.state, plugin.activator); + } + return true; + } + + private final Function registry; + private final BundleController controller; + private final SpotlessEclipseCoreConfig coreConfig; + private boolean coreConfigStarted; + + private SpotlessEclipseFramework(SpotlessEclipseCoreConfig coreConfig) throws BundleException { + + controller = new BundleController(); + registry = (pluginBundle) -> { + return PluginRegistrar.register(pluginBundle); + }; + + this.coreConfig = coreConfig; + coreConfigStarted = false; + } + + /** Get framework service configuration */ + private SpotlessEclipseServiceConfig getServiceConfig() { + return controller.getServices(); + } + + /** Add a plugin to the framework. */ + private void addPlugin(int state, BundleActivator plugin) throws BundleException { + if (!coreConfigStarted) { + //The SAXParserFactory.class is required for parsing the plugin XML files + addMandatoryServiceIfMissing(SAXParserFactory.class, SAXParserFactory.newInstance()); + startFrameworkBundles(); + coreConfigStarted = true; + } + controller.addBundle(state, plugin, registry); + } + + private void addMandatoryServiceIfMissing(Class interfaceClass, S service) { + if (null == controller.getServiceReference(interfaceClass)) { + controller.getServices().add(interfaceClass, service); + } + } + + private void startFrameworkBundles() throws BundleException { + for (BundleConfig.Entry coreBundle : coreConfig.get()) { + try { + BundleContext context = controller.createContext(coreBundle.state); + coreBundle.activator.start(context); + } catch (Exception e) { + throw new BundleException(String.format("Failed to start %s", coreBundle.activator.getClass().getName()), BundleException.ACTIVATOR_ERROR, e); + } + } + } + +} diff --git a/_ext/eclipse-base/src/main/java/com/diffplug/spotless/extra/eclipse/base/SpotlessEclipsePluginConfig.java b/_ext/eclipse-base/src/main/java/com/diffplug/spotless/extra/eclipse/base/SpotlessEclipsePluginConfig.java new file mode 100644 index 0000000000..183e333c0a --- /dev/null +++ b/_ext/eclipse-base/src/main/java/com/diffplug/spotless/extra/eclipse/base/SpotlessEclipsePluginConfig.java @@ -0,0 +1,52 @@ +/* + * Copyright 2016 DiffPlug + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package com.diffplug.spotless.extra.eclipse.base; + +import org.osgi.framework.Bundle; +import org.osgi.framework.BundleActivator; + +import com.diffplug.spotless.extra.eclipse.base.SpotlessEclipseFramework.DefaultPlugins; +import com.diffplug.spotless.extra.eclipse.base.osgi.BundleConfig; + +/** + * Configuration of plugins which shall be provided by the + * {@link SpotlessEclipseFramework}. + *

+ * Plugins are registered via the Eclipse registry. Therefore they + * required a {@code plugin.xml} configuration description. + * Note that a plugin does not necessarily derive from the + * Eclipse {@link org.eclipse.core.runtime.Plugin} class. + *

+ * @see org.eclipse.core.runtime.RegistryFactory + */ +public class SpotlessEclipsePluginConfig extends BundleConfig { + + @Override + public void applyDefault() { + add(SpotlessEclipseFramework.DefaultPlugins.createAll()); + } + + @Override + protected BundleActivator create(DefaultPlugins bundle) { + return bundle.create(); + } + + @Override + protected int getDefaultState(DefaultPlugins bundle) { + return Bundle.ACTIVE; + } + +} diff --git a/_ext/eclipse-base/src/main/java/com/diffplug/spotless/extra/eclipse/base/SpotlessEclipseServiceConfig.java b/_ext/eclipse-base/src/main/java/com/diffplug/spotless/extra/eclipse/base/SpotlessEclipseServiceConfig.java new file mode 100644 index 0000000000..5edec30da4 --- /dev/null +++ b/_ext/eclipse-base/src/main/java/com/diffplug/spotless/extra/eclipse/base/SpotlessEclipseServiceConfig.java @@ -0,0 +1,116 @@ +/* + * Copyright 2016 DiffPlug + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package com.diffplug.spotless.extra.eclipse.base; + +import static com.diffplug.spotless.extra.eclipse.base.SpotlessEclipseFramework.LINE_DELIMITER; + +import java.util.Map; + +import org.eclipse.core.runtime.content.IContentTypeManager; +import org.eclipse.core.runtime.preferences.IPreferencesService; +import org.eclipse.osgi.service.datalocation.Location; +import org.eclipse.osgi.service.debug.DebugOptions; +import org.eclipse.osgi.service.environment.EnvironmentInfo; + +import com.diffplug.spotless.extra.eclipse.base.service.*; + +/** + * Configuration/Provision of services which shall be provided by the {@link SpotlessEclipseFramework}. + *

+ * The services provide basic functions/configuration to the {@link SpotlessEclipseFramework} bundles use the services. + * Hence the services can be used to customize the behavior of core bundles and plugins configured + * in the {@link SpotlessEclipseCoreConfig} and {@link SpotlessEclipsePluginConfig}. + *

+ */ +public interface SpotlessEclipseServiceConfig { + + /** Sets property/preference value available to all bundles, plugins and services. */ + void set(String key, String value); + + /** Sets property/preference values available to all bundles, plugins and services. */ + default void set(Map properties) { + properties.forEach((k, v) -> this.set(k, v)); + } + + /** + * Add custom service to collection. + *

+ * Only one service per interface is allowed. + * A service instance implementing multiple interfaces, can be added for each interface. + *

+ * Please refer to the default method implementation for examples. + * + * @param interfaceClass Service interface + * @param service Service instance + */ + public void add(Class interfaceClass, S service); + + /** + * Spotless formatters should not be configured by environment variables, and + * they shall be OS independent. + */ + default public void hideEnvironment() { + add(EnvironmentInfo.class, new HiddenEnvironment()); + } + + /** + * Eclipse provides means to lookup the file content type, e.g. by file name extensions. + * This possibility is not required by most Spotless formatters. + */ + default public void ignoreContentType() { + add(IContentTypeManager.class, new NoContentTypeSpecificHandling()); + } + + /** Disable Eclipse internal debugging. */ + default public void disableDebugging() { + add(DebugOptions.class, new NoDebugging()); + } + + /** Ignore accesses of unsupported preference. */ + default public void ignoreUnsupportedPreferences() { + add(IPreferencesService.class, new NoEclipsePreferences()); + } + + /** + * Use temporary locations in case plugins require to store file. + * These files (for example workspace preferences) will be deleted + * as soon as the application terminates. + */ + default public void useTemporaryLocations() { + add(Location.class, new TemporaryLocation()); + } + + /** + * In case the string which will be formatted does not contain any + * line delimiter (single line), Eclipse falls back to use the + * system property. + * Change the system default to the UNIX line separator as required + * by Spotless. + */ + default public void changeSystemLineSeparator() { + System.setProperty("line.separator", LINE_DELIMITER); + } + + /** Applies the default configurations. */ + default public void applyDefault() { + hideEnvironment(); + ignoreContentType(); + disableDebugging(); + ignoreUnsupportedPreferences(); + useTemporaryLocations(); + changeSystemLineSeparator(); + } +} diff --git a/_ext/eclipse-base/src/main/java/com/diffplug/spotless/extra/eclipse/base/osgi/BundleConfig.java b/_ext/eclipse-base/src/main/java/com/diffplug/spotless/extra/eclipse/base/osgi/BundleConfig.java new file mode 100644 index 0000000000..90bfafc8e4 --- /dev/null +++ b/_ext/eclipse-base/src/main/java/com/diffplug/spotless/extra/eclipse/base/osgi/BundleConfig.java @@ -0,0 +1,95 @@ +/* + * Copyright 2016 DiffPlug + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package com.diffplug.spotless.extra.eclipse.base.osgi; + +import java.util.ArrayList; +import java.util.Arrays; +import java.util.Collection; +import java.util.List; + +import org.osgi.framework.Bundle; +import org.osgi.framework.BundleActivator; + +/** A bundle configuration is given by its activator and the desired state */ +public abstract class BundleConfig> { + public static class Entry { + public final BundleActivator activator; + public final int state; + + public Entry(BundleActivator activator, int state) { + this.activator = activator; + this.state = state; + } + } + + private final List config; + + protected BundleConfig() { + config = new ArrayList(); + } + + /** + * Activates a bundle with a certain state. A non-active state is used by + * some bundles to allow a slim instantiation (for example in a headless + * Eclipse). + */ + public void add(BundleActivator activator, int state) { + config.add(new Entry(activator, state)); + } + + /** Returns the current configuration */ + public List get() { + return config; + } + + /** Activates a set of bundles with certain states */ + public void add(List config) { + this.config.addAll(config); + } + + /** Add a bundle in active state, which is the nominal choice */ + public void add(BundleActivator activator) { + add(activator, Bundle.ACTIVE); + } + + /** Activates a set of bundles with in active state */ + public void add(Collection config) { + config.stream().forEach(entry -> add(entry)); + } + + /** Add a default bundle with its default state */ + public void add(T bundle) { + add(create(bundle), getDefaultState(bundle)); + } + + /** Add a set of default bundles with their default states */ + public void add(@SuppressWarnings("unchecked") T... bundles) { + Arrays.asList(bundles).forEach(bundle -> add(bundle)); + } + + /** Add a default bundle with a custom state */ + public void add(T bundle, int state) { + add(create(bundle), state); + } + + /** Applies the default configurations. */ + public abstract void applyDefault(); + + protected abstract BundleActivator create(T bundle); + + protected abstract int getDefaultState(T bundle); + +} diff --git a/_ext/eclipse-base/src/main/java/com/diffplug/spotless/extra/eclipse/base/osgi/BundleController.java b/_ext/eclipse-base/src/main/java/com/diffplug/spotless/extra/eclipse/base/osgi/BundleController.java new file mode 100644 index 0000000000..8ee9b8c7be --- /dev/null +++ b/_ext/eclipse-base/src/main/java/com/diffplug/spotless/extra/eclipse/base/osgi/BundleController.java @@ -0,0 +1,211 @@ +/* + * Copyright 2016 DiffPlug + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package com.diffplug.spotless.extra.eclipse.base.osgi; + +import java.util.Collection; +import java.util.HashMap; +import java.util.Map; +import java.util.function.Function; + +import org.osgi.framework.Bundle; +import org.osgi.framework.BundleActivator; +import org.osgi.framework.BundleContext; +import org.osgi.framework.BundleException; +import org.osgi.framework.Constants; +import org.osgi.framework.Filter; +import org.osgi.framework.InvalidSyntaxException; +import org.osgi.framework.ServiceReference; + +/** + * OSGi bundle controller allowing a minimal Eclipse platform setup + * by bypassing the Eclipse internal platform. + * + * Bundles are loaded by the same class loader, sharing the same context. + * Services do not provide individual properties, but making use of the framework properties. + * All bundles have a persistent state. The OSGi life-cycle is not supported. + */ +public final class BundleController implements StaticBundleContext { + private static final String ECLIPSE_LAUNCHER_SYMBOLIC_NAME = "org.eclipse.osgi"; + + private final SimpleBundle systemBundle; + private final Map properties; + private final ServiceCollection services; + private final BundleSet bundles; + + @SuppressWarnings("deprecation") + public BundleController() throws BundleException { + this.properties = new HashMap(); + //Don't activate all plugin bundles. Activation is triggered by this controller where needed. + properties.put(org.eclipse.core.internal.runtime.InternalPlatform.PROP_ACTIVATE_PLUGINS, Boolean.toString(false)); + /* + * Used to set-up an internal member of the Eclipse runtime FindSupport, + * which is used during resources look-up from different version of bundles. + * Since the concept of the Spotless Eclipse framework does not allow multiple versions + * for a bundle, this property is never used. + */ + properties.put(org.eclipse.core.internal.runtime.FindSupport.PROP_NL, ""); + + bundles = new BundleSet(); + systemBundle = new SimpleBundle(this, Bundle.ACTIVE); + bundles.add(systemBundle); + + services = new ServiceCollection(systemBundle, properties); + //Eclipse core (InternalPlatform) still uses PackageAdmin for looking up bundles + services.add(org.osgi.service.packageadmin.PackageAdmin.class, new EclipseBundleLookup(bundles)); + + //Redirect framework activator requests to the the org.eclipse.osgi bundle to this instance. + bundles.add(new SimpleBundle(systemBundle, ECLIPSE_LAUNCHER_SYMBOLIC_NAME, Bundle.ACTIVE)); + } + + public ServiceCollection getServices() { + return services; + } + + /** Adds and starts a new bundle. */ + public void addBundle(int bundleState, BundleActivator activator, Function register) throws BundleException { + BundleContext contextFacade = new BundleControllerContextFacade(this, bundleState, activator); + bundles.add(contextFacade.getBundle()); + BundleException exception = register.apply(contextFacade.getBundle()); + if (null != exception) + throw exception; + try { + activator.start(contextFacade); + } catch (Exception e) { + throw new BundleException(String.format("Failed do start %s.", activator.getClass().getName()), BundleException.ACTIVATOR_ERROR, e); + } + } + + /** Creates a context with an individual state if required. */ + public BundleContext createContext(int state) { + if (state == systemBundle.getState()) { + return this; + } + return new BundleControllerContextFacade(systemBundle, state); + } + + @Override + public String getProperty(String key) { + return properties.get(key); + } + + @Override + public Bundle getBundle() { + return systemBundle; + } + + @Override + public Bundle[] getBundles() { + Collection shallowCopy = bundles.getAll(); + return shallowCopy.toArray(new Bundle[shallowCopy.size()]); + } + + @Override + public Bundle getBundle(long id) { + return bundles.get(id); + } + + @Override + public Bundle getBundle(String location) { + if (Constants.SYSTEM_BUNDLE_LOCATION.equals(location)) { + return systemBundle; + } + return null; + } + + @Override + public ServiceReference[] getAllServiceReferences(String clazz, String filter) throws InvalidSyntaxException { + //Filters are based on class names + String interfaceClassName = (null == clazz) ? filter : clazz; + return services.getReferences(interfaceClassName); + } + + @Override + public S getService(ServiceReference reference) { + return services.getService(reference); + } + + @Override + public Filter createFilter(String filter) throws InvalidSyntaxException { + return services.createFilter(filter); + } + + /** + * Facade providing access to an existing controller for a bundle + *

+ * All bundles have unrestricted access to the framework services and properties. + * However, each bundle and its context needs to maintain its individual + * symbolic name for look-up. + *

+ */ + private static class BundleControllerContextFacade implements StaticBundleContext { + + private final BundleContext context; + private final Bundle bundle; + + private BundleControllerContextFacade(BundleContext context, int bundleState, BundleActivator activator) throws BundleException { + this.context = context; + bundle = new SimpleBundle(this, bundleState, activator); + } + + /** Fakes an individual bundle state */ + private BundleControllerContextFacade(SimpleBundle bundle, int bundleState) { + this.context = bundle.getBundleContext(); + this.bundle = new SimpleBundle(bundle, bundleState); + } + + @Override + public String getProperty(String key) { + return context.getProperty(key); + } + + @Override + public Bundle getBundle() { + return bundle; + } + + @Override + public Bundle[] getBundles() { + return context.getBundles(); + } + + @Override + public Bundle getBundle(long id) { + return context.getBundle(id); + } + + @Override + public Bundle getBundle(String location) { + return context.getBundle(location); + } + + @Override + public ServiceReference[] getAllServiceReferences(String clazz, String filter) throws InvalidSyntaxException { + return context.getAllServiceReferences(clazz, filter); + } + + @Override + public S getService(ServiceReference reference) { + return context.getService(reference); + } + + @Override + public Filter createFilter(String filter) throws InvalidSyntaxException { + return context.createFilter(filter); + } + + } + +} diff --git a/_ext/eclipse-base/src/main/java/com/diffplug/spotless/extra/eclipse/base/osgi/BundleSet.java b/_ext/eclipse-base/src/main/java/com/diffplug/spotless/extra/eclipse/base/osgi/BundleSet.java new file mode 100644 index 0000000000..59e15929fd --- /dev/null +++ b/_ext/eclipse-base/src/main/java/com/diffplug/spotless/extra/eclipse/base/osgi/BundleSet.java @@ -0,0 +1,71 @@ +/* + * Copyright 2016 DiffPlug + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package com.diffplug.spotless.extra.eclipse.base.osgi; + +import java.util.Collection; +import java.util.Map; +import java.util.concurrent.ConcurrentHashMap; + +import org.osgi.framework.Bundle; +import org.osgi.framework.BundleException; + +/** Thread save set of bundles, whereas each bundle has a unique symbolic name and a unique ID. */ +class BundleSet { + private final Map symbolicName2bundle; + private final Map id2bundle; + + BundleSet() { + symbolicName2bundle = new ConcurrentHashMap(); + id2bundle = new ConcurrentHashMap(); + } + + /** Get all bundles in collection */ + Collection getAll() { + return symbolicName2bundle.values(); + } + + /** Get bundle by symbolic name or null if collection does not contain the corresponding bundle. */ + Bundle get(String symbolicName) { + return symbolicName2bundle.get(symbolicName); + } + + /** Get bundle by its ID or null if collection does not contain the corresponding bundle. */ + Bundle get(long id) { + return id2bundle.get(id); + } + + /** Add bundle to collection. + * @throws BundleException */ + void add(Bundle bundle) throws BundleException { + Bundle existingBundle = symbolicName2bundle.put(bundle.getSymbolicName(), bundle); + if (null != existingBundle) { + throw new BundleException( + String.format("Bundle '%s' (ID: %d) is already part of collection with ID %d.", + bundle.getSymbolicName(), bundle.getBundleId(), existingBundle.getBundleId()), + BundleException.DUPLICATE_BUNDLE_ERROR); + } + Bundle bundleWithSameID = id2bundle.put(bundle.getBundleId(), bundle); + if (null != bundleWithSameID) { + throw new BundleException( + String.format("Bundle ID '%d' for '%s' is already used by '%s'.", + bundle.getBundleId(), + bundle.getSymbolicName(), + bundleWithSameID.getSymbolicName()), + BundleException.DUPLICATE_BUNDLE_ERROR); + } + } + +} diff --git a/_ext/eclipse-base/src/main/java/com/diffplug/spotless/extra/eclipse/base/osgi/EclipseBundleLookup.java b/_ext/eclipse-base/src/main/java/com/diffplug/spotless/extra/eclipse/base/osgi/EclipseBundleLookup.java new file mode 100644 index 0000000000..601825bbfd --- /dev/null +++ b/_ext/eclipse-base/src/main/java/com/diffplug/spotless/extra/eclipse/base/osgi/EclipseBundleLookup.java @@ -0,0 +1,100 @@ +/* + * Copyright 2016 DiffPlug + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package com.diffplug.spotless.extra.eclipse.base.osgi; + +import org.osgi.framework.Bundle; +import org.osgi.service.packageadmin.ExportedPackage; +import org.osgi.service.packageadmin.PackageAdmin; +import org.osgi.service.packageadmin.RequiredBundle; + +/** + * {@link PackageAdmin} service for bundle look-up and bypassing wiring. + *

+ * The wiring information will always claim that all required bundles are present. + * Other functionality is not supported. + * Unsupported methods are marked as deprecated and throw an {@link UnsupportedOperationException}. + *

+ * Interface is deprecated, but for example the InternalPlatform still uses PackageAdmin. + */ +@SuppressWarnings("deprecation") +class EclipseBundleLookup implements PackageAdmin { + + private final BundleSet bundles; + + EclipseBundleLookup(final BundleSet bundles) { + this.bundles = bundles; + } + + @Override + @Deprecated + public ExportedPackage[] getExportedPackages(Bundle bundle) { + return null; + } + + @Override + @Deprecated + public ExportedPackage[] getExportedPackages(String name) { + return null; + } + + @Override + @Deprecated + public ExportedPackage getExportedPackage(String name) { + return null; + } + + @Override + @Deprecated + public void refreshPackages(Bundle[] bundles) {} + + @Override + public boolean resolveBundles(Bundle[] bundles) { + return true; //All required bundles can be considered available (to be confirmed by UT) + } + + @Override + public RequiredBundle[] getRequiredBundles(String symbolicName) { + return null; // No unresolved required bundles exist + } + + @Override + public Bundle[] getBundles(String symbolicName, String versionRange) { + //Bundles with different versions cannot be supported due to the usage of same class-loader + Bundle bundle = bundles.get(symbolicName); + return (null == bundle) ? null : new Bundle[]{bundle}; + } + + @Override + public Bundle[] getFragments(Bundle bundle) { + return null; //No fragments + } + + @Override + public Bundle[] getHosts(Bundle bundle) { + return null; //No fragments + } + + @Override + public Bundle getBundle(@SuppressWarnings("rawtypes") Class clazz) { + return bundles.get(clazz.getName()); + } + + @Override + public int getBundleType(Bundle bundle) { + return 0; //No fragments + } + +} diff --git a/_ext/eclipse-base/src/main/java/com/diffplug/spotless/extra/eclipse/base/osgi/ResourceAccessor.java b/_ext/eclipse-base/src/main/java/com/diffplug/spotless/extra/eclipse/base/osgi/ResourceAccessor.java new file mode 100644 index 0000000000..8bad77d010 --- /dev/null +++ b/_ext/eclipse-base/src/main/java/com/diffplug/spotless/extra/eclipse/base/osgi/ResourceAccessor.java @@ -0,0 +1,132 @@ +/* + * Copyright 2016 DiffPlug + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package com.diffplug.spotless.extra.eclipse.base.osgi; + +import java.io.File; +import java.io.IOException; +import java.net.URL; +import java.util.Enumeration; +import java.util.jar.JarFile; +import java.util.jar.Manifest; + +import org.eclipse.osgi.storage.bundlefile.BundleEntry; +import org.eclipse.osgi.storage.bundlefile.BundleFile; +import org.eclipse.osgi.storage.bundlefile.DirBundleFile; +import org.eclipse.osgi.storage.bundlefile.ZipBundleFile; +import org.eclipse.osgi.util.ManifestElement; +import org.osgi.framework.BundleException; +import org.osgi.framework.Constants; + +/** + * Helper to access resources. + *

+ * Spotless Eclipse formatters using in many cases fat JARs, compressing multiple + * bundles within one JAR. Their resources can get overridden in a fat JAR. + * Hence they provided under the bundle activators path name. + *

+ *

+ * The resource overriding prevention is required in case the Spotless + * Eclipse formatters integrate third party JARs, not available via M2. + * Additionally it can be used in case existing third party Eclipse plugins + * are mocked by Spotless, requiring the provision of multiple customized + * plugin information (META-INF, plugin.xml) within one JAR. + *

+ */ +class ResourceAccessor { + /** + */ + private final String fatJarResourcePath; + private final BundleFile bundleFile; + + /** Resources are located in the SpotlessFramework JAR */ + ResourceAccessor() throws BundleException { + this(ResourceAccessor.class); + } + + /** Resources are located in the JAR of the given class + * @throws BundleException */ + ResourceAccessor(Class clazz) throws BundleException { + String bundleObjPath = clazz.getName(); + fatJarResourcePath = bundleObjPath.substring(0, bundleObjPath.lastIndexOf('.')); + try { + bundleFile = getBundlFile(clazz); + } catch (BundleException e) { + throw new BundleException(String.format("Failed to locate resources for bunlde '%s'.", clazz.getName()), e); + } + } + + private static BundleFile getBundlFile(Class clazz) throws BundleException { + URL objUrl = clazz.getProtectionDomain().getCodeSource().getLocation(); + File jarOrDirectory = new File(objUrl.getPath()); + if (!(jarOrDirectory.exists() && jarOrDirectory.canRead())) { + throw new BundleException(String.format("Path '%s' for '%s' is not accessible exist on local file system.", objUrl, clazz.getName()), BundleException.READ_ERROR); + } + try { + return jarOrDirectory.isDirectory() ? new DirBundleFile(jarOrDirectory, false) : new ZipBundleFile(jarOrDirectory, null, null, null); + } catch (IOException e) { + throw new BundleException(String.format("Cannot access bundle at '%s'.", jarOrDirectory), BundleException.READ_ERROR, e); + } + } + + /** Get the manifest name from the resources. */ + String getManifestName() throws BundleException { + URL manifestUrl = getEntry(JarFile.MANIFEST_NAME); + if (null != manifestUrl) { + try { + Manifest manifest = new Manifest(manifestUrl.openStream()); + String headerValue = manifest.getMainAttributes().getValue(Constants.BUNDLE_SYMBOLICNAME); + if (null == headerValue) { + throw new BundleException(String.format("Symbolic values not found in '%s'.", manifestUrl), BundleException.MANIFEST_ERROR); + } + ManifestElement[] elements = ManifestElement.parseHeader(Constants.BUNDLE_SYMBOLICNAME, headerValue); + if (null == elements) { + throw new BundleException(String.format("Symbolic name not found '%s'. Value is '%s'.", manifestUrl, headerValue), BundleException.MANIFEST_ERROR); + } + //The parser already checked that at least one value exists + return elements[0].getValueComponents()[0]; + + } catch (IOException e) { + throw new BundleException(String.format("Failed to parse Manifest '%s' in '%s'.", manifestUrl, bundleFile.toString()), BundleException.MANIFEST_ERROR, e); + } + } + throw new BundleException(String.format("'%s' in '%s' not found. Tried also fat JAR location '%s'.", JarFile.MANIFEST_NAME, bundleFile.toString(), fatJarResourcePath), BundleException.MANIFEST_ERROR); + } + + /** Get resource URL for relative path, or null if the path is not present */ + URL getEntry(String path) { + BundleEntry entry = bundleFile.getEntry(getFatJarPath(path)); + if (null == entry) { + entry = bundleFile.getEntry(path); + } + return null == entry ? null : entry.getLocalURL(); + } + + /** + * Enumeration of Strings that indicate the paths found or null if the path does not exist. + */ + Enumeration getEntries(String path) { + Enumeration entries = bundleFile.getEntryPaths(getFatJarPath(path)); + if (null == entries) { + entries = bundleFile.getEntryPaths(path); + } + return entries; + } + + private String getFatJarPath(String path) { + return fatJarResourcePath + "/" + path; + } + +} diff --git a/_ext/eclipse-base/src/main/java/com/diffplug/spotless/extra/eclipse/base/osgi/ServiceCollection.java b/_ext/eclipse-base/src/main/java/com/diffplug/spotless/extra/eclipse/base/osgi/ServiceCollection.java new file mode 100644 index 0000000000..7dc5947c00 --- /dev/null +++ b/_ext/eclipse-base/src/main/java/com/diffplug/spotless/extra/eclipse/base/osgi/ServiceCollection.java @@ -0,0 +1,192 @@ +/* + * Copyright 2016 DiffPlug + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package com.diffplug.spotless.extra.eclipse.base.osgi; + +import java.util.Collection; +import java.util.Dictionary; +import java.util.HashMap; +import java.util.Map; +import java.util.Optional; + +import org.osgi.framework.Bundle; +import org.osgi.framework.Filter; +import org.osgi.framework.ServiceException; +import org.osgi.framework.ServiceReference; + +import com.diffplug.spotless.extra.eclipse.base.SpotlessEclipseServiceConfig; + +/** + * Collection of services. + * Note that the collection access is not thread save, since it is expected + * that the collection is completed before starting any bundles. + */ +public class ServiceCollection implements SpotlessEclipseServiceConfig { + private final Map> className2Service; + private final Bundle systemBundle; + private final Map properties; + + /** + * Collection of services + * @param systemBundle All services will belong to the system bundles + * @param All services share the same properties + */ + ServiceCollection(Bundle systemBundle, Map properties) { + className2Service = new HashMap>(); + this.systemBundle = systemBundle; + this.properties = properties; + } + + @Override + public void set(String key, String value) { + properties.put(key, value); + } + + @Override + public void add(Class interfaceClass, S service) { + String className = interfaceClass.getName(); + if (null != className2Service.put(interfaceClass.getName(), new FrameworkServiceReference(className, service))) { + throw new ServiceException( + String.format("Service '%s' is already registered.", interfaceClass.getName()), ServiceException.FACTORY_ERROR); + } + } + + /** Creates filter object suitable to lookup service by its interface name. */ + Filter createFilter(String filterDescr) { + Optional serviceClassName = className2Service.keySet().stream().filter(serviceClazzName -> filterDescr.contains(serviceClazzName)).findFirst(); + return new ClassNameBasedFilter(serviceClassName); + } + + /** + * Get reference matching interface class name or all references + * @param interfaceClassName Class name filter. All references are returned in case filter is null + * @return Matching or all interfaces. If no interface is matching the filter, null is returned. + */ + ServiceReference[] getReferences(String interfaceClassName) { + if (null == interfaceClassName) { + Collection> allServices = className2Service.values(); + return allServices.toArray(new ServiceReference[allServices.size()]); + } + ServiceReference singleService = className2Service.get(interfaceClassName); + return (null == singleService) ? null : new ServiceReference[]{singleService}; + } + + /** + * Return service for reference if it belongs to the system bundle. + * @param reference Service reference + * @return null, if service does not belong to the system bundle + */ + S getService(ServiceReference reference) { + if (systemBundle == reference.getBundle()) { + return ((FrameworkServiceReference) reference).getService(); + } + return null; + } + + /** References to static services (not modifiable at run-time */ + private class FrameworkServiceReference implements ServiceReference { + + private final String className; + private final S service; + + private FrameworkServiceReference(String className, S service) { + this.className = className; + this.service = service; + } + + private S getService() { + return service; + } + + @Override + public java.lang.Object getProperty(String key) { + return properties.get(key); + } + + @Override + public String[] getPropertyKeys() { + return properties.keySet().toArray(new String[properties.size()]); + } + + @Override + public Bundle getBundle() { + return systemBundle; + } + + @Override + public Bundle[] getUsingBundles() { + return new Bundle[]{systemBundle}; + } + + @Override + public boolean isAssignableTo(Bundle bundle, String className) { + // Since only one class loader is used, same class come from the same package + return this.className.equals(className); + } + + @Override + @edu.umd.cs.findbugs.annotations.SuppressFBWarnings(value = "EQ_COMPARETO_USE_OBJECT_EQUALS") + public int compareTo(Object reference) { + return (this == reference) ? 0 : 1; + } + + } + + /** + * Class name based service filter + *

+ * Dictionary and capability look-ups are not supported and marked as deprecated. + */ + private class ClassNameBasedFilter implements Filter { + + private final static String NO_MATCH_CLASS_NAME = ""; + + private final String className; + + private ClassNameBasedFilter(Optional className) { + this.className = className.orElse(NO_MATCH_CLASS_NAME); + } + + @Override + public boolean match(ServiceReference reference) { + return reference.isAssignableTo(systemBundle, className); + } + + @Override + @Deprecated + public boolean match(Dictionary dictionary) { + throw new UnsupportedOperationException("Dictionary based service look-up is not supported."); + } + + @Override + @Deprecated + public boolean matchCase(Dictionary dictionary) { + throw new UnsupportedOperationException("Dictionary based service look-up is not supported."); + } + + @Override + @Deprecated + public boolean matches(Map map) { + throw new UnsupportedOperationException("Capability based service look-up is not supported."); + } + + @Override + public String toString() { + return className; + } + + } + +} diff --git a/_ext/eclipse-base/src/main/java/com/diffplug/spotless/extra/eclipse/base/osgi/SimpleBundle.java b/_ext/eclipse-base/src/main/java/com/diffplug/spotless/extra/eclipse/base/osgi/SimpleBundle.java new file mode 100644 index 0000000000..3a7e305975 --- /dev/null +++ b/_ext/eclipse-base/src/main/java/com/diffplug/spotless/extra/eclipse/base/osgi/SimpleBundle.java @@ -0,0 +1,111 @@ +/* + * Copyright 2016 DiffPlug + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package com.diffplug.spotless.extra.eclipse.base.osgi; + +import java.net.URL; +import java.util.Enumeration; + +import org.osgi.framework.BundleActivator; +import org.osgi.framework.BundleContext; +import org.osgi.framework.BundleException; +import org.osgi.framework.InvalidSyntaxException; +import org.osgi.framework.ServiceReference; + +/** Fixed state simple bundle. */ +class SimpleBundle implements StaticBundle, TemporaryBundle { + private final String name; + private final int state; + private final BundleContext context; + private final int id; + private final ResourceAccessor resources; + + /** System bundle corresponding to the SpotlessFramework JARs manifest */ + SimpleBundle(BundleContext context, int state) throws BundleException { + this(context, state, new ResourceAccessor()); + } + + /** System bundle for a dedicated bundle activator */ + SimpleBundle(BundleContext context, int state, BundleActivator activator) throws BundleException { + this(context, state, new ResourceAccessor(activator.getClass())); + } + + /** Internal constructor */ + private SimpleBundle(BundleContext context, int state, ResourceAccessor resources) throws BundleException { + this.state = state; + this.context = context; + this.resources = resources; + id = context.getBundles().length; + name = resources.getManifestName(); + } + + /** Additional bundle with a different symbolic name and state */ + SimpleBundle(SimpleBundle master, String name, int state) { + this.name = name; + this.state = state; + context = master.context; + resources = master.resources; + id = context.getBundles().length; + } + + /** Bundle clone with a different state */ + SimpleBundle(SimpleBundle master, int state) { + this.state = state; + context = master.context; + resources = master.resources; + id = master.id; + name = master.name; + } + + @Override + public int getState() { + return state; + } + + @Override + public long getBundleId() { + return id; + } + + @Override + public ServiceReference[] getRegisteredServices() { + try { + return context.getAllServiceReferences(null, null); + } catch (InvalidSyntaxException e) { + throw new RuntimeException(e); //Filter 'null' is valid for 'select all'. + } + } + + @Override + public String getSymbolicName() { + return name; + } + + @Override + public BundleContext getBundleContext() { + return context; + } + + @Override + public Enumeration getEntryPaths(String path) { + return resources.getEntries(path); + } + + @Override + public URL getEntry(String path) { + return resources.getEntry(path); + } + +} diff --git a/_ext/eclipse-base/src/main/java/com/diffplug/spotless/extra/eclipse/base/osgi/StaticBundle.java b/_ext/eclipse-base/src/main/java/com/diffplug/spotless/extra/eclipse/base/osgi/StaticBundle.java new file mode 100644 index 0000000000..282804a332 --- /dev/null +++ b/_ext/eclipse-base/src/main/java/com/diffplug/spotless/extra/eclipse/base/osgi/StaticBundle.java @@ -0,0 +1,79 @@ +/* + * Copyright 2016 DiffPlug + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package com.diffplug.spotless.extra.eclipse.base.osgi; + +import java.io.InputStream; + +import org.osgi.framework.Bundle; +import org.osgi.framework.BundleException; +import org.osgi.framework.ServiceReference; + +/** + * Unmodifiable bundle with a fixed life-cycle. + *

+ * All state related modifications are ignored. + * Installation related methods (update/uninstall) are unsupported. + * Unsupported methods are marked as deprecated and causing an exception. + */ +public interface StaticBundle extends Bundle { + + @Override + default public void start(int options) throws BundleException {} + + @Override + default public void start() throws BundleException {} + + @Override + default public void stop(int options) throws BundleException {} + + @Override + default public void stop() throws BundleException {} + + @Override + @Deprecated + default public void update(InputStream input) throws BundleException { + update(); + } + + @Override + @Deprecated + default public void update() throws BundleException { + throw new UnsupportedOperationException("Bundle modifications are not supported."); + } + + @Override + @Deprecated + default public void uninstall() throws BundleException { + throw new UnsupportedOperationException("Bundles cannot be uninstalled."); + } + + @Override + default public long getLastModified() { + return 0; + } + + @Override + @Deprecated + default public String getLocation() { + throw new UnsupportedOperationException("Bundle lookup by location only required for installation/update."); + } + + @Override + default public ServiceReference[] getServicesInUse() { + return getRegisteredServices(); //There is no distinction between available services and services in use. + } + +} diff --git a/_ext/eclipse-base/src/main/java/com/diffplug/spotless/extra/eclipse/base/osgi/StaticBundleContext.java b/_ext/eclipse-base/src/main/java/com/diffplug/spotless/extra/eclipse/base/osgi/StaticBundleContext.java new file mode 100644 index 0000000000..040ef98444 --- /dev/null +++ b/_ext/eclipse-base/src/main/java/com/diffplug/spotless/extra/eclipse/base/osgi/StaticBundleContext.java @@ -0,0 +1,166 @@ +/* + * Copyright 2016 DiffPlug + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package com.diffplug.spotless.extra.eclipse.base.osgi; + +import java.io.File; +import java.io.InputStream; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.Collection; +import java.util.Dictionary; +import java.util.Objects; +import java.util.stream.Collectors; + +import org.osgi.framework.Bundle; +import org.osgi.framework.BundleContext; +import org.osgi.framework.BundleException; +import org.osgi.framework.BundleListener; +import org.osgi.framework.FrameworkListener; +import org.osgi.framework.InvalidSyntaxException; +import org.osgi.framework.ServiceFactory; +import org.osgi.framework.ServiceListener; +import org.osgi.framework.ServiceObjects; +import org.osgi.framework.ServiceReference; +import org.osgi.framework.ServiceRegistration; + +/** + * Restriction of the {@link BundleContext} interface rejecting run-time provision of bundles. + * Services provided at run-time are ignored. + *

+ * Multiple service instances per class are not supported, hence the services can be filtered by class name. + * Unsupported methods are marked as deprecated an causing an exception. + * Registration and removal of bundle/service listeners are ignored, since a run-time + * provision of bundles or services is not supported. + */ +interface StaticBundleContext extends BundleContext { + + @Override + @Deprecated + default public Bundle installBundle(String location, InputStream input) throws BundleException { + throw new UnsupportedOperationException("Run-time installation of bundles is not supported."); + } + + @Override + @Deprecated + default public Bundle installBundle(String location) throws BundleException { + throw new UnsupportedOperationException("Run-time installation of bundles is not supported."); + } + + @Override + default public void addServiceListener(ServiceListener listener, String filter) throws InvalidSyntaxException {} + + @Override + default public void addServiceListener(ServiceListener listener) {} + + @Override + default public void removeServiceListener(ServiceListener listener) {} + + @Override + default public void addBundleListener(BundleListener listener) {} + + @Override + default public void removeBundleListener(BundleListener listener) {} + + @Override + default public void addFrameworkListener(FrameworkListener listener) {} + + @Override + default public void removeFrameworkListener(FrameworkListener listener) {} + + @Override + @Deprecated + default public ServiceRegistration registerService(String[] clazzes, Object service, Dictionary properties) { + throw new UnsupportedOperationException("Run-time provision of services is not supported."); + } + + @Override + @Deprecated + default public ServiceRegistration registerService(String clazz, Object service, Dictionary properties) { + return null; //Ignore additional services + } + + @Deprecated + @Override + default public ServiceRegistration registerService(Class clazz, S service, Dictionary properties) { + return null; //Ignore additional services + } + + @Override + @Deprecated + default public ServiceRegistration registerService(Class clazz, ServiceFactory factory, Dictionary properties) { + return null; //Ignore additional services + } + + @SuppressWarnings("unchecked") + @Override + default public ServiceReference getServiceReference(Class clazz) { + Objects.requireNonNull(clazz, "The class under whose name the service was registered must not be null."); + return (ServiceReference) getServiceReference(clazz.getName()); + } + + @Override + default public ServiceReference getServiceReference(String clazz) { + Objects.requireNonNull(clazz, "The class under whose name the service was registered must not be null."); + ServiceReference[] references; + try { + references = getServiceReferences(clazz, null); + } catch (InvalidSyntaxException e) { + throw new RuntimeException(e); //null is always valid + } + return (null == references) ? null : references[0]; + } + + @Override + default public ServiceReference[] getServiceReferences(String clazz, String filter) throws InvalidSyntaxException { + return getAllServiceReferences(clazz, filter); //Services are always considered compatible + } + + @Override + default public ServiceReference[] getAllServiceReferences(String clazz, String filter) throws InvalidSyntaxException { + //Filters are based on class names + ServiceReference reference = (null == clazz) ? getServiceReference(filter) : getServiceReference(clazz); + return (reference == null) ? null : new ServiceReference[]{reference}; + } + + @SuppressWarnings("unchecked") + @Override + default public Collection> getServiceReferences(Class clazz, String filter) throws InvalidSyntaxException { + ServiceReference[] references = getServiceReferences(clazz.getName(), filter); + Collection> result = new ArrayList>(0); + if (null != references) { + result = Arrays.stream(references).map(r -> (ServiceReference) r).collect(Collectors.toList()); + } + return result; + } + + @Override + default public boolean ungetService(ServiceReference reference) { + return true; //Services are persistent and never unregistered + } + + @Override + @Deprecated + default public ServiceObjects getServiceObjects(ServiceReference reference) { + throw new UnsupportedOperationException("Service specific objects are not supported."); + } + + @Override + @Deprecated + default public File getDataFile(String filename) { + throw new UnsupportedOperationException("Persistent data storage provision is handled by the Location service."); + } + +} diff --git a/_ext/eclipse-base/src/main/java/com/diffplug/spotless/extra/eclipse/base/osgi/TemporaryBundle.java b/_ext/eclipse-base/src/main/java/com/diffplug/spotless/extra/eclipse/base/osgi/TemporaryBundle.java new file mode 100644 index 0000000000..24cfadc8c2 --- /dev/null +++ b/_ext/eclipse-base/src/main/java/com/diffplug/spotless/extra/eclipse/base/osgi/TemporaryBundle.java @@ -0,0 +1,107 @@ +/* + * Copyright 2016 DiffPlug + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package com.diffplug.spotless.extra.eclipse.base.osgi; + +import java.io.File; +import java.io.IOException; +import java.net.URL; +import java.security.cert.X509Certificate; +import java.util.Dictionary; +import java.util.Enumeration; +import java.util.HashMap; +import java.util.List; +import java.util.Map; + +import org.osgi.framework.Bundle; +import org.osgi.framework.Version; + +/** + * Temporary bundle loaded by common class loader and added temporarily. + * It shall not be recognized as a Eclipse plugin (providing plugin.xml) + * but as a mere OSGI bundle. + *

+ * META data look-ups are not supported (only required for Eclipse plugins). + * Entry look-up in the bundle space (findEntries) is not supported. + * Installation related methods (update/uninstall) are not supported. + * Unsupported methods are marked as deprecated and causing an exception. + */ +public interface TemporaryBundle extends Bundle { + + @Override + default public Version getVersion() { + return Version.emptyVersion; //Cannot support multiple version using single class loader. + } + + @Override + default public int compareTo(Bundle o) { + //Symbolic name is sufficient to distinguish bundles + return getSymbolicName().compareTo(o.getSymbolicName()); + } + + @Override + default public A adapt(Class type) { + return null; //Adaptation is not successful + } + + @Override + @Deprecated + default public Dictionary getHeaders() { + throw new UnsupportedOperationException("Bundle META information is not available."); + } + + @Override + @Deprecated + default public Dictionary getHeaders(String locale) { + return getHeaders(); + } + + @Override + default public URL getResource(String name) { + return getClass().getClassLoader().getResource(name); + } + + @Override + default public Enumeration getResources(String name) throws IOException { + return getClass().getClassLoader().getResources(name); + } + + @Override + @Deprecated + default public Enumeration findEntries(String path, String filePattern, boolean recurse) { + return null; //Local JAR look-up are not supported per default + } + + @Override + default public Class loadClass(String name) throws ClassNotFoundException { + return getClass().getClassLoader().loadClass(name); + } + + @Override + default public boolean hasPermission(Object permission) { + return true; //Dedicated permissions are not supported + } + + @Override + default public Map> getSignerCertificates(int signersType) { + return new HashMap>(0); //Bundle is not signed + } + + @Override + default public File getDataFile(String filename) { + return null; //No file system support for persistent files + } + +} diff --git a/_ext/eclipse-base/src/main/java/com/diffplug/spotless/extra/eclipse/base/osgi/package-info.java b/_ext/eclipse-base/src/main/java/com/diffplug/spotless/extra/eclipse/base/osgi/package-info.java new file mode 100644 index 0000000000..da74c0471e --- /dev/null +++ b/_ext/eclipse-base/src/main/java/com/diffplug/spotless/extra/eclipse/base/osgi/package-info.java @@ -0,0 +1,17 @@ +/* + * Copyright 2016 DiffPlug + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** Simplified OSGIi implementation bypassing Equinox module layer. */ +package com.diffplug.spotless.extra.eclipse.base.osgi; diff --git a/_ext/eclipse-base/src/main/java/com/diffplug/spotless/extra/eclipse/base/package-info.java b/_ext/eclipse-base/src/main/java/com/diffplug/spotless/extra/eclipse/base/package-info.java new file mode 100644 index 0000000000..b82e4d40ca --- /dev/null +++ b/_ext/eclipse-base/src/main/java/com/diffplug/spotless/extra/eclipse/base/package-info.java @@ -0,0 +1,24 @@ +/* + * Copyright 2016 DiffPlug + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * Common Spotless Eclipse Equinox setup classes. + * Please refer to the {@code eclipse-base} {@code README.md} for + * usage instructions. + */ +@ParametersAreNonnullByDefault +package com.diffplug.spotless.extra.eclipse.base; + +import javax.annotation.ParametersAreNonnullByDefault; diff --git a/_ext/eclipse-base/src/main/java/com/diffplug/spotless/extra/eclipse/base/runtime/PluginRegistrar.java b/_ext/eclipse-base/src/main/java/com/diffplug/spotless/extra/eclipse/base/runtime/PluginRegistrar.java new file mode 100644 index 0000000000..cdee9893dc --- /dev/null +++ b/_ext/eclipse-base/src/main/java/com/diffplug/spotless/extra/eclipse/base/runtime/PluginRegistrar.java @@ -0,0 +1,103 @@ +/* + * Copyright 2016 DiffPlug + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package com.diffplug.spotless.extra.eclipse.base.runtime; + +import java.io.ByteArrayInputStream; +import java.io.IOException; +import java.io.InputStream; +import java.net.URL; +import java.util.PropertyResourceBundle; +import java.util.ResourceBundle; + +import org.eclipse.core.internal.registry.ExtensionRegistry; +import org.eclipse.core.runtime.IContributor; +import org.eclipse.core.runtime.IExtensionRegistry; +import org.eclipse.core.runtime.RegistryFactory; +import org.eclipse.core.runtime.spi.RegistryContributor; +import org.osgi.framework.Bundle; +import org.osgi.framework.BundleException; + +/** Registers Eclipse plugins at runtime based on a loaded bundle. + *

+ * Note that the functionality provided by this class uses incubation features of the Eclipse core. + */ +public class PluginRegistrar { + private static final String PLUGIN_XML = "plugin.xml"; + private static final String PLUGIN_PROPERTIES = "plugin.properties"; + + public static BundleException register(Bundle bundle) { + PluginRegistrar registrar = new PluginRegistrar(bundle); + try { + registrar.register(); + } catch (BundleException e) { + return e; + } + return null; + } + + private final Bundle bundle; + + private PluginRegistrar(Bundle bundle) { + this.bundle = bundle; + } + + private void register() throws BundleException { + IExtensionRegistry reg = RegistryFactory.getRegistry(); + Object registryUser = ((ExtensionRegistry) reg).getTemporaryUserToken(); + if (!reg.addContribution(getStreamForEntry(PLUGIN_XML), createContributor(), false, null, getPluginProperties(), registryUser)) { + throw new BundleException("Could not add plugin: " + bundle.getSymbolicName(), BundleException.REJECTED_BY_HOOK); + } + } + + private IContributor createContributor() { + return new RegistryContributor( + Long.toString(bundle.getBundleId()), + bundle.getSymbolicName(), + // Local host + null, + null); + } + + private ResourceBundle getPluginProperties() throws BundleException { + //Some plugins, like the org.codehaus.groovy.eclipse.core, do not provide a property file. + InputStream is = entryExists(PLUGIN_PROPERTIES) ? getStreamForEntry(PLUGIN_PROPERTIES) : new ByteArrayInputStream(new byte[0]); + try { + return new PropertyResourceBundle(is); + } catch (IOException e) { + throw new BundleException(String.format("Bund resource '%s' is not encoded with ISO-8859-1.", PLUGIN_PROPERTIES), BundleException.MANIFEST_ERROR, e); + } + } + + private InputStream getStreamForEntry(String path) throws BundleException { + try { + return getEntry(path).openStream(); + } catch (IOException e) { + throw new BundleException(String.format("Cannot access mandatory resource '%s'.", path), BundleException.MANIFEST_ERROR, e); + } + } + + private URL getEntry(String path) throws BundleException { + URL url = bundle.getEntry(path); + if (null == url) { + throw new BundleException(String.format("Cannot find mandatory resource '%s'.", path), BundleException.MANIFEST_ERROR); + } + return url; + } + + private boolean entryExists(String path) { + return null != bundle.getEntry(path); + } +} diff --git a/_ext/eclipse-base/src/main/java/com/diffplug/spotless/extra/eclipse/base/runtime/package-info.java b/_ext/eclipse-base/src/main/java/com/diffplug/spotless/extra/eclipse/base/runtime/package-info.java new file mode 100644 index 0000000000..5ed08616b9 --- /dev/null +++ b/_ext/eclipse-base/src/main/java/com/diffplug/spotless/extra/eclipse/base/runtime/package-info.java @@ -0,0 +1,19 @@ +/* + * Copyright 2016 DiffPlug + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * Eclipse Core Runtime adapters allowing runtime modifications which normally requires an Eclipse restart. + */ +package com.diffplug.spotless.extra.eclipse.base.runtime; diff --git a/_ext/eclipse-base/src/main/java/com/diffplug/spotless/extra/eclipse/base/service/HiddenEnvironment.java b/_ext/eclipse-base/src/main/java/com/diffplug/spotless/extra/eclipse/base/service/HiddenEnvironment.java new file mode 100644 index 0000000000..8c9c1a6c91 --- /dev/null +++ b/_ext/eclipse-base/src/main/java/com/diffplug/spotless/extra/eclipse/base/service/HiddenEnvironment.java @@ -0,0 +1,81 @@ +/* + * Copyright 2016 DiffPlug + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package com.diffplug.spotless.extra.eclipse.base.service; + +import java.util.Locale; + +import org.eclipse.osgi.service.environment.Constants; +import org.eclipse.osgi.service.environment.EnvironmentInfo; + +/** Empty default Eclipse environment. No system information is accessible. */ +public class HiddenEnvironment implements EnvironmentInfo { + + @Override + public String[] getCommandLineArgs() { + return new String[0]; + } + + @Override + public String[] getFrameworkArgs() { + return new String[0]; + } + + @Override + public String[] getNonFrameworkArgs() { + return new String[0]; + } + + @Override + public String getOSArch() { + return System.getProperty("os.arch"); + } + + @Override + public String getNL() { + return Locale.getDefault().getLanguage(); + } + + @Override + public String getOS() { + return Constants.OS_UNKNOWN; + } + + @Override + public String getWS() { + return null; //No window system + } + + @Override + public boolean inDebugMode() { + return false; + } + + @Override + public boolean inDevelopmentMode() { + return false; + } + + @Override + public String setProperty(String key, String value) { + return value; //Launcher information is not stored + } + + @Override + public String getProperty(String key) { + return null; //Launcher information/configuration is not required + } + +} diff --git a/_ext/eclipse-base/src/main/java/com/diffplug/spotless/extra/eclipse/base/service/NoContentTypeSpecificHandling.java b/_ext/eclipse-base/src/main/java/com/diffplug/spotless/extra/eclipse/base/service/NoContentTypeSpecificHandling.java new file mode 100644 index 0000000000..87e1f2f91b --- /dev/null +++ b/_ext/eclipse-base/src/main/java/com/diffplug/spotless/extra/eclipse/base/service/NoContentTypeSpecificHandling.java @@ -0,0 +1,95 @@ +/* + * Copyright 2016 DiffPlug + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package com.diffplug.spotless.extra.eclipse.base.service; + +import java.io.IOException; +import java.io.InputStream; +import java.io.Reader; + +import org.eclipse.core.runtime.CoreException; +import org.eclipse.core.runtime.QualifiedName; +import org.eclipse.core.runtime.content.IContentDescription; +import org.eclipse.core.runtime.content.IContentType; +import org.eclipse.core.runtime.content.IContentTypeManager; +import org.eclipse.core.runtime.content.IContentTypeMatcher; +import org.eclipse.core.runtime.preferences.IScopeContext; + +/** No content type specific handling is supported. */ +public class NoContentTypeSpecificHandling implements IContentTypeManager { + + @Override + public IContentType findContentTypeFor(InputStream contents, String fileName) throws IOException { + return null; + } + + @Override + public IContentType findContentTypeFor(String fileName) { + return null; + } + + @Override + public IContentType[] findContentTypesFor(InputStream contents, String fileName) throws IOException { + return null; + } + + @Override + public IContentType[] findContentTypesFor(String fileName) { + return null; + } + + @Override + public IContentDescription getDescriptionFor(InputStream contents, String fileName, QualifiedName[] options) throws IOException { + return null; + } + + @Override + public IContentDescription getDescriptionFor(Reader contents, String fileName, QualifiedName[] options) throws IOException { + return null; + } + + @Override + public void addContentTypeChangeListener(IContentTypeChangeListener listener) {} + + @Override + public IContentType[] getAllContentTypes() { + return null; + } + + @Override + public IContentType getContentType(String contentTypeIdentifier) { + return null; + } + + @Override + public IContentTypeMatcher getMatcher(ISelectionPolicy customPolicy, IScopeContext context) { + return null; + } + + @Override + public void removeContentTypeChangeListener(IContentTypeChangeListener listener) { + + } + + @Override + public IContentType addContentType(String contentTypeIdentifier, String name, IContentType baseType) + throws CoreException { + return null; + } + + @Override + public void removeContentType(String contentTypeIdentifier) throws CoreException {} + +} diff --git a/_ext/eclipse-base/src/main/java/com/diffplug/spotless/extra/eclipse/base/service/NoDebugging.java b/_ext/eclipse-base/src/main/java/com/diffplug/spotless/extra/eclipse/base/service/NoDebugging.java new file mode 100644 index 0000000000..095be889e9 --- /dev/null +++ b/_ext/eclipse-base/src/main/java/com/diffplug/spotless/extra/eclipse/base/service/NoDebugging.java @@ -0,0 +1,87 @@ +/* + * Copyright 2016 DiffPlug + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package com.diffplug.spotless.extra.eclipse.base.service; + +import java.io.File; +import java.util.Map; + +import org.eclipse.osgi.service.debug.DebugOptions; +import org.eclipse.osgi.service.debug.DebugTrace; + +/** No debugging shall be performed */ +public class NoDebugging implements DebugOptions { + + @Override + public boolean getBooleanOption(String option, boolean defaultValue) { + return false; + } + + @Override + public String getOption(String option) { + return null; + } + + @Override + public String getOption(String option, String defaultValue) { + return null; + } + + @Override + public int getIntegerOption(String option, int defaultValue) { + return 0; + } + + @Override + public Map getOptions() { + return null; + } + + @Override + public void setOption(String option, String value) {} + + @Override + public void setOptions(Map options) {} + + @Override + public void removeOption(String option) {} + + @Override + public boolean isDebugEnabled() { + return false; + } + + @Override + public void setDebugEnabled(boolean value) {} + + @Override + public void setFile(File newFile) {} + + @Override + public File getFile() { + return null; + } + + @Override + public DebugTrace newDebugTrace(String bundleSymbolicName) { + return null; + } + + @Override + public DebugTrace newDebugTrace(String bundleSymbolicName, Class traceEntryClass) { + return null; + } + +} diff --git a/_ext/eclipse-base/src/main/java/com/diffplug/spotless/extra/eclipse/base/service/NoEclipsePreferences.java b/_ext/eclipse-base/src/main/java/com/diffplug/spotless/extra/eclipse/base/service/NoEclipsePreferences.java new file mode 100644 index 0000000000..7f6bed44ed --- /dev/null +++ b/_ext/eclipse-base/src/main/java/com/diffplug/spotless/extra/eclipse/base/service/NoEclipsePreferences.java @@ -0,0 +1,129 @@ +/* + * Copyright 2016 DiffPlug + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package com.diffplug.spotless.extra.eclipse.base.service; + +import java.io.InputStream; +import java.io.OutputStream; + +import org.eclipse.core.runtime.CoreException; +import org.eclipse.core.runtime.IStatus; +import org.eclipse.core.runtime.preferences.DefaultScope; +import org.eclipse.core.runtime.preferences.IEclipsePreferences; +import org.eclipse.core.runtime.preferences.IExportedPreferences; +import org.eclipse.core.runtime.preferences.IPreferenceFilter; +import org.eclipse.core.runtime.preferences.IPreferencesService; +import org.eclipse.core.runtime.preferences.IScopeContext; +import org.osgi.service.prefs.Preferences; + +/** + * The formatters dependents on plugins which access Eclipse core functionality, + * configurable by preferences. This functionality is never used by the formatters itself. + * Hence modifications are ignored and default values are provided on request. + */ +public class NoEclipsePreferences implements IPreferencesService { + private static final String UNUSED = "unused"; + + @Override + public IEclipsePreferences getRootNode() { + //Return value is not effectively used. + return DefaultScope.INSTANCE.getNode(UNUSED); + } + + @Override + public String get(String key, String defaultValue, Preferences[] nodes) { + return null; + } + + @Override + public boolean getBoolean(String qualifier, String key, boolean defaultValue, IScopeContext[] contexts) { + return false; + } + + @Override + public byte[] getByteArray(String qualifier, String key, byte[] defaultValue, IScopeContext[] contexts) { + return null; + } + + @Override + public double getDouble(String qualifier, String key, double defaultValue, IScopeContext[] contexts) { + return 0; + } + + @Override + public float getFloat(String qualifier, String key, float defaultValue, IScopeContext[] contexts) { + return 0; + } + + @Override + public int getInt(String qualifier, String key, int defaultValue, IScopeContext[] contexts) { + return 0; + } + + @Override + public long getLong(String qualifier, String key, long defaultValue, IScopeContext[] contexts) { + return 0; + } + + @Override + public String getString(String qualifier, String key, String defaultValue, IScopeContext[] contexts) { + return null; + } + + @Override + public IStatus exportPreferences(IEclipsePreferences node, OutputStream output, String[] excludesList) throws CoreException { + return null; + } + + @Override + public IStatus importPreferences(InputStream input) throws CoreException { + return null; + } + + @Override + public IStatus applyPreferences(IExportedPreferences preferences) throws CoreException { + return null; + } + + @Override + public IExportedPreferences readPreferences(InputStream input) throws CoreException { + return null; + } + + @Override + public String[] getDefaultLookupOrder(String qualifier, String key) { + return null; + } + + @Override + public String[] getLookupOrder(String qualifier, String key) { + return null; + } + + @Override + public void setDefaultLookupOrder(String qualifier, String key, String[] order) {} + + @Override + public void exportPreferences(IEclipsePreferences node, IPreferenceFilter[] filters, OutputStream output) throws CoreException {} + + @Override + public IPreferenceFilter[] matches(IEclipsePreferences node, IPreferenceFilter[] filters) throws CoreException { + return null; + } + + @Override + public void applyPreferences(IEclipsePreferences node, IPreferenceFilter[] filters) throws CoreException {} + +} diff --git a/_ext/eclipse-base/src/main/java/com/diffplug/spotless/extra/eclipse/base/service/TemporaryLocation.java b/_ext/eclipse-base/src/main/java/com/diffplug/spotless/extra/eclipse/base/service/TemporaryLocation.java new file mode 100644 index 0000000000..ac960cc369 --- /dev/null +++ b/_ext/eclipse-base/src/main/java/com/diffplug/spotless/extra/eclipse/base/service/TemporaryLocation.java @@ -0,0 +1,128 @@ +/* + * Copyright 2016 DiffPlug + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package com.diffplug.spotless.extra.eclipse.base.service; + +import java.io.IOError; +import java.io.IOException; +import java.net.URISyntaxException; +import java.net.URL; +import java.nio.file.Files; +import java.nio.file.Path; +import java.nio.file.Paths; + +import org.eclipse.osgi.service.datalocation.Location; + +/** All files generated at runtime are stored in a temporary location. */ +public class TemporaryLocation implements Location { + private static final String TEMP_PREFIX = "com_diffplug_spotless_extra_eclipse"; + private final URL location; + private Location parent; + + public TemporaryLocation() { + this(null, createTemporaryDirectory()); + } + + private TemporaryLocation(Location parent, URL defaultValue) { + this.location = defaultValue; + this.parent = parent; + } + + private static URL createTemporaryDirectory() { + try { + Path locationPath = Files.createTempDirectory(TEMP_PREFIX); + locationPath.toFile().deleteOnExit(); + return locationPath.toUri().toURL(); + } catch (IOException e) { + throw new IOError(e); + } + } + + @Override + public boolean allowsDefault() { + return false; + } + + @Override + public URL getDefault() { + return null; + } + + @Override + public Location getParentLocation() { + return parent; + } + + @Override + public URL getURL() { + return location; + } + + @Override + public boolean isSet() { + return true; + } + + @Override + public boolean isReadOnly() { + return false; + } + + @Override + public boolean setURL(URL value, boolean lock) throws IllegalStateException { + throw new IllegalStateException("URL not modifyable."); + } + + @Override + public boolean set(URL value, boolean lock) throws IllegalStateException, IOException { + throw new IllegalStateException("URL not modifyable."); + } + + @Override + public boolean set(URL value, boolean lock, String lockFilePath) throws IllegalStateException, IOException { + throw new IllegalStateException("URL not modifyable."); + } + + @Override + public boolean lock() throws IOException { + return false; //Lock not supported + } + + @Override + public void release() { + //Lock not supported + } + + @Override + public boolean isLocked() throws IOException { + return false; //Lock not supported + } + + @Override + public Location createLocation(Location parent, URL defaultValue, boolean readonly) { + return new TemporaryLocation(parent, defaultValue); + } + + @Override + public URL getDataArea(String path) throws IOException { + try { + Path locationPath = Paths.get(location.toURI()); + return locationPath.resolve(path).toUri().toURL(); + } catch (URISyntaxException e) { + throw new IOException("Location not correctly formatted.", e); + } + } + +} diff --git a/_ext/eclipse-base/src/main/java/com/diffplug/spotless/extra/eclipse/base/service/package-info.java b/_ext/eclipse-base/src/main/java/com/diffplug/spotless/extra/eclipse/base/service/package-info.java new file mode 100644 index 0000000000..b444c0c76a --- /dev/null +++ b/_ext/eclipse-base/src/main/java/com/diffplug/spotless/extra/eclipse/base/service/package-info.java @@ -0,0 +1,17 @@ +/* + * Copyright 2016 DiffPlug + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** Mocking Eclipse Equinox OSGi services. */ +package com.diffplug.spotless.extra.eclipse.base.service; diff --git a/_ext/eclipse-base/src/main/resources/META-INF/MANIFEST.MF b/_ext/eclipse-base/src/main/resources/META-INF/MANIFEST.MF new file mode 100644 index 0000000000..348dc4c453 --- /dev/null +++ b/_ext/eclipse-base/src/main/resources/META-INF/MANIFEST.MF @@ -0,0 +1,3 @@ +Manifest-Version: 1.0 +Bundle-ManifestVersion: 2 +Bundle-SymbolicName: com.diffplug.gradle.spotless.eclipse; singleton:=true diff --git a/_ext/eclipse-base/src/test/java/com/diffplug/spotless/extra/eclipse/base/SpotlessEclipseFrameworkTest.java b/_ext/eclipse-base/src/test/java/com/diffplug/spotless/extra/eclipse/base/SpotlessEclipseFrameworkTest.java new file mode 100644 index 0000000000..fc2b685caf --- /dev/null +++ b/_ext/eclipse-base/src/test/java/com/diffplug/spotless/extra/eclipse/base/SpotlessEclipseFrameworkTest.java @@ -0,0 +1,29 @@ +/* + * Copyright 2016 DiffPlug + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package com.diffplug.spotless.extra.eclipse.base; + +import org.junit.Test; +import org.osgi.framework.BundleException; + +/** Smoke tests */ +public class SpotlessEclipseFrameworkTest { + + @Test + public void testSetup() throws BundleException { + SpotlessEclipseFramework.setup(); + } + +} diff --git a/_ext/eclipse-base/src/test/java/com/diffplug/spotless/extra/eclipse/base/osgi/BundleSetTest.java b/_ext/eclipse-base/src/test/java/com/diffplug/spotless/extra/eclipse/base/osgi/BundleSetTest.java new file mode 100644 index 0000000000..1530411560 --- /dev/null +++ b/_ext/eclipse-base/src/test/java/com/diffplug/spotless/extra/eclipse/base/osgi/BundleSetTest.java @@ -0,0 +1,90 @@ +/* + * Copyright 2016 DiffPlug + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package com.diffplug.spotless.extra.eclipse.base.osgi; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.junit.Assert.*; + +import java.util.Arrays; + +import org.junit.Before; +import org.junit.Test; +import org.osgi.framework.Bundle; +import org.osgi.framework.BundleException; + +public class BundleSetTest { + + BundleSet instance; + + @Before + public void initialize() { + instance = new BundleSet(); + } + + @Test + public void testAddGet() throws BundleException { + Bundle testBundle1 = new TestBundle(1, "a"); + Bundle testBundle2 = new TestBundle(2, "b"); + instance.add(testBundle1); + instance.add(testBundle2); + assertEquals("Get by ID 1", testBundle1, instance.get(1)); + assertEquals("Get by ID 2", testBundle2, instance.get(2)); + assertEquals("Get by symbolic name 'a'", testBundle1, instance.get("a")); + assertEquals("Get by symbolic name 'b'", testBundle2, instance.get("b")); + assertTrue("Contains all", instance.getAll().containsAll(Arrays.asList(testBundle1, testBundle2))); + } + + @Test + public void testSameSymbolicName() throws BundleException { + final String symbolicName = "sym.a"; + final long id1 = 12345; + final long id2 = 23456; + Bundle testBundle1 = new TestBundle(id1, symbolicName); + Bundle testBundle2 = new TestBundle(id2, symbolicName); + instance.add(testBundle1); + boolean exceptionCaught = false; + try { + instance.add(testBundle2); + } catch (BundleException e) { + exceptionCaught = true; + assertThat(e.getMessage()).as("BundleException does not contain symbolic name.").contains(symbolicName); + assertThat(e.getMessage()).as("BundleException does not contain ID of exisiting bundle.").contains(Long.toString(id1)); + assertThat(e.getMessage()).as("BundleException does not contain ID of new bundle.").contains(Long.toString(id2)); + } + assertThat(exceptionCaught).as("No BundleException thrown for duplicate symblic name.").isTrue(); + } + + @Test + public void testSameID() throws BundleException { + final String symbolicName1 = "sym.a"; + final String symbolicName2 = "sym.b"; + final long id = 12345; + Bundle testBundle1 = new TestBundle(id, symbolicName1); + Bundle testBundle2 = new TestBundle(id, symbolicName2); + instance.add(testBundle1); + boolean exceptionCaught = false; + try { + instance.add(testBundle2); + } catch (BundleException e) { + exceptionCaught = true; + assertThat(e.getMessage()).as("BundleException does not contain ID.").contains(Long.toString(id)); + assertThat(e.getMessage()).as("BundleException does not contain symbolic name of exisiting bundle.").contains(symbolicName1); + assertThat(e.getMessage()).as("BundleException does not contain symbolic name of new bundle.").contains(symbolicName2); + } + assertThat(exceptionCaught).as("No BundleException thrown for duplicate symblic name.").isTrue(); + } + +} diff --git a/_ext/eclipse-base/src/test/java/com/diffplug/spotless/extra/eclipse/base/osgi/ServiceCollectionTest.java b/_ext/eclipse-base/src/test/java/com/diffplug/spotless/extra/eclipse/base/osgi/ServiceCollectionTest.java new file mode 100644 index 0000000000..4c4a2d87c3 --- /dev/null +++ b/_ext/eclipse-base/src/test/java/com/diffplug/spotless/extra/eclipse/base/osgi/ServiceCollectionTest.java @@ -0,0 +1,121 @@ +/* + * Copyright 2016 DiffPlug + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package com.diffplug.spotless.extra.eclipse.base.osgi; + +import static org.assertj.core.api.Assertions.assertThat; + +import java.util.HashMap; + +import org.assertj.core.api.AbstractAssert; +import org.junit.Before; +import org.junit.Test; +import org.osgi.framework.Bundle; +import org.osgi.framework.ServiceException; +import org.osgi.framework.ServiceReference; + +public class ServiceCollectionTest { + + ServiceCollection instance; + + @Before + public void initialize() { + Bundle systemBundle = new TestBundle(0, "test.system"); + instance = new ServiceCollection(systemBundle, new HashMap()); + } + + @Test + public void testAddGet() { + Service1 service1 = new Service1(); + Service2 service2 = new Service2(); + instance.add(Interf1.class, service1); + instance.add(Interf2a.class, service2); + instance.add(Interf2b.class, service2); + assertFor(instance).getServiceForReferences(Interf1.class).matchesService(service1); + assertFor(instance).getServiceForReferences(Interf2a.class).matchesService(service2); + assertFor(instance).getServiceForReferences(Interf2b.class).matchesService(service2); + } + + @Test + public void testMultipleServicesPerInterface() { + Service1 serviceX = new Service1(); + Service1 serviceY = new Service1(); + instance.add(Interf1.class, serviceX); + boolean exceptionCaught = false; + try { + instance.add(Interf1.class, serviceY); + } catch (ServiceException e) { + exceptionCaught = true; + assertThat(e.getMessage()).as("ServiceException does not contain interface class name.").contains(Interf1.class.getName()); + } + assertThat(exceptionCaught).as("No ServiceException thrown for duplicate interfaces.").isTrue(); + + } + + private static class ServiceReferenceAssert extends AbstractAssert { + + private final ServiceCollection actual; + private final ServiceReference reference; + + public ServiceReferenceAssert(ServiceCollection actual) { + this(actual, null); + } + + public ServiceReferenceAssert(ServiceCollection actual, ServiceReference reference) { + super(actual, ServiceReferenceAssert.class); + this.reference = reference; + this.actual = actual; + + } + + ServiceReferenceAssert getServiceForReferences(Class interfaceClass) { + ServiceReference[] references = actual.getReferences(interfaceClass.getName()); + int numberOfFoundReferences = null == references ? 0 : references.length; + if (numberOfFoundReferences != 1) { + failWithMessage("Expected to find exactly 1 reference for <%s> , but found %d.", interfaceClass.getName(), numberOfFoundReferences); + } + return new ServiceReferenceAssert(actual, references[0]); + } + + ServiceReferenceAssert matchesService(Object expected) { + if (null == reference) { + failWithMessage("No reference requested."); + } + Object serviceForRef = actual.getService(reference); + if (null == serviceForRef) { + failWithMessage("No service provided for reference."); + } + if (!serviceForRef.equals(expected)) { + failWithMessage("Unexpected service found."); + } + + return this; + } + } + + private static ServiceReferenceAssert assertFor(ServiceCollection actual) { + return new ServiceReferenceAssert(actual); + } + + private static interface Interf1 {}; + + private static interface Interf2a {}; + + private static interface Interf2b {}; + + private static class Service1 implements Interf1 {}; + + private static class Service2 implements Interf2a, Interf2b {}; +} diff --git a/_ext/eclipse-base/src/test/java/com/diffplug/spotless/extra/eclipse/base/osgi/TestBundle.java b/_ext/eclipse-base/src/test/java/com/diffplug/spotless/extra/eclipse/base/osgi/TestBundle.java new file mode 100644 index 0000000000..b849dddf5b --- /dev/null +++ b/_ext/eclipse-base/src/test/java/com/diffplug/spotless/extra/eclipse/base/osgi/TestBundle.java @@ -0,0 +1,137 @@ +/* + * Copyright 2016 DiffPlug + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package com.diffplug.spotless.extra.eclipse.base.osgi; + +import java.io.File; +import java.io.IOException; +import java.net.URL; +import java.security.cert.X509Certificate; +import java.util.Dictionary; +import java.util.Enumeration; +import java.util.List; +import java.util.Map; + +import org.osgi.framework.Bundle; +import org.osgi.framework.BundleContext; +import org.osgi.framework.ServiceReference; +import org.osgi.framework.Version; + +/** Helper for testing */ +public class TestBundle implements StaticBundle, TemporaryBundle { + private final String symbolicName; + private final long id; + + public TestBundle(long id, String symbolicName) { + this.id = id; + this.symbolicName = symbolicName; + } + + @Override + public int getState() { + return 0; + } + + @Override + public Dictionary getHeaders() { + return null; + } + + @Override + public long getBundleId() { + return id; + } + + @Override + public ServiceReference[] getRegisteredServices() { + return null; + } + + @Override + public boolean hasPermission(Object permission) { + return false; + } + + @Override + public URL getResource(String name) { + return null; + } + + @Override + public Dictionary getHeaders(String locale) { + return null; + } + + @Override + public String getSymbolicName() { + return symbolicName; + } + + @Override + public Class loadClass(String name) throws ClassNotFoundException { + return null; + } + + @Override + public Enumeration getResources(String name) throws IOException { + return null; + } + + @Override + public Enumeration getEntryPaths(String path) { + return null; + } + + @Override + public URL getEntry(String path) { + return null; + } + + @Override + public Enumeration findEntries(String path, String filePattern, boolean recurse) { + return null; + } + + @Override + public BundleContext getBundleContext() { + return null; + } + + @Override + public Map> getSignerCertificates(int signersType) { + return null; + } + + @Override + public Version getVersion() { + return null; + } + + @Override + public A adapt(Class type) { + return null; + } + + @Override + public File getDataFile(String filename) { + return null; + } + + @Override + public int compareTo(Bundle o) { + return 0; + } + +} diff --git a/_ext/gradle/java-publish.gradle b/_ext/gradle/java-publish.gradle new file mode 100644 index 0000000000..c2be64f518 --- /dev/null +++ b/_ext/gradle/java-publish.gradle @@ -0,0 +1,112 @@ +apply plugin: 'maven-publish' + +task sourcesJar(type: Jar) { + classifier = 'sources' + from sourceSets.main.allJava +} + +task javadocJar(type: Jar, dependsOn: javadoc) { + classifier = 'javadoc' + from javadoc.destinationDir +} + +def isSnapshot = ext_version.endsWith('-SNAPSHOT') +// pulls the credentials from either the environment variable or gradle.properties +def lookup = { key, defaultVal -> + if (System.env[key] != null) { + return System.env[key] + } else if (project.hasProperty(key)) { + return project[key] + } else { + return defaultVal + } +} + +model { + publishing { + publications { + mavenJava(MavenPublication) { + + groupId project.ext_group + artifactId project.ext_artifactId + version project.ext_version + from components.java + + pom.withXml { + + // add MavenCentral requirements to the POM + asNode().children().last() + { + resolveStrategy = Closure.DELEGATE_FIRST + name project.ext_artifactId + description project.ext_description + url "https://github.com/${project.ext_org}/${project.name}" + scm { + url "https://github.com/${project.ext_org}/${project.name}" + connection "scm:git:git://github.com/${project.ext_org}/${project.name}" + developerConnection "scm:git:ssh:git@github.com/${project.ext_org}/${project.name}" + } + licenses { + license { + name 'Eclipse Public License - v 1.0' + url 'https://www.eclipse.org/legal/epl-v10.html' + distribution 'repo' + } + } + developers { + project.ext.developers.each { extId, extValues -> + developer { + id extId + name extValues['name'] + email extValues['email'] + } + } + } + } + } + } + } + if (isSnapshot) { + // upload snapshots to oss.sonatype.org + repositories { + maven { + url = lookup('snapshot_url', 'https://oss.sonatype.org/content/repositories/snapshots') + credentials { + username = lookup('nexus_user', 'unknown_nexus_user') + password = lookup('nexus_pass', 'unknown_nexus_pass') + } + } } + } + } +} + +if (!isSnapshot) { + // upload releases to bintray and then mavenCentral + bintray { + user = lookup('bintray_user', 'unknown_bintray_user') + key = lookup('bintray_pass', 'unknown_bintray_pass') + publications = [ + 'mavenJava' + ] + publish = true + pkg { + repo = 'opensource' + name = project.ext_artifactId + userOrg = project.ext_org + version { + name = project.ext_version + mavenCentralSync { + user = lookup('nexus_user', 'unknown_nexus_user') + password = lookup('nexus_pass', 'unknown_nexus_user') + } + } + } + } + + publish.dependsOn(bintrayUpload) + bintrayUpload.dependsOn([ + 'generatePomFileForMavenJavaPublication', + jar, + sourcesJar, + javadocJar + ]) +} diff --git a/_ext/gradle/java-setup.gradle b/_ext/gradle/java-setup.gradle new file mode 100644 index 0000000000..ea5e5dc1f6 --- /dev/null +++ b/_ext/gradle/java-setup.gradle @@ -0,0 +1,74 @@ +////////// +// JAVA // +////////// +repositories { + mavenCentral() + jcenter() + /* Allow access of local SNAPSHOT builds. Sanity of dependencies + is guranteed by the lib-extra build. */ + mavenLocal() +} + +// setup java +apply plugin: 'java' + +sourceCompatibility = ext_VER_JAVA +targetCompatibility = ext_VER_JAVA +tasks.withType(JavaCompile) { options.encoding = 'UTF-8' } + +// Use file locking +configurations { + compileClasspath { + def gradleVersion = GradleVersion.current() + def requiredVersion = GradleVersion.version('4.8') + if (gradleVersion >= requiredVersion) { + resolutionStrategy.activateDependencyLocking() + } + } +} + + +///////////// +// ECLIPSE // +///////////// +apply plugin: 'eclipse' +eclipse { + classpath { + downloadSources true + downloadJavadoc true + } +} +// always create fresh projects +tasks.eclipse.dependsOn(cleanEclipse) + +////////////// +// FINDBUGS // +////////////// +apply plugin: 'findbugs' +findbugs { + toolVersion = '3.0.1' + sourceSets = [ + // don't check the test code + sourceSets.main + ] + ignoreFailures = false // bug free or it doesn't ship! + reportsDir = file('build/findbugs') + effort = 'max' // min|default|max + reportLevel = 'medium' // low|medium|high (low = sensitive to even minor mistakes) + omitVisitors = [] // bugs that we want to ignore +} +// HTML instead of XML +tasks.withType(FindBugs) { + reports { + xml.enabled = false + html.enabled = true + } +} +// we'll want the findbugs annotations (they don't have a 3.0.1 version) +dependencies { + compileOnly 'com.google.code.findbugs:annotations:3.0.0' + compileOnly 'com.google.code.findbugs:jsr305:3.0.0' + + testCompile 'junit:junit:4.12' + testCompile 'org.assertj:assertj-core:3.5.2' +}