deprecated the Bundle Tracker
diff --git a/.asf.yaml b/.asf.yaml new file mode 100644 index 0000000..f9cd802 --- /dev/null +++ b/.asf.yaml
@@ -0,0 +1,7 @@ +github: + description: "Apache Sling Scripting Bundle Tracker (deprecated)" + homepage: "https://sling.apache.org" + labels: + - java + - sling + - deprecated
diff --git a/CODE_OF_CONDUCT.md b/CODE_OF_CONDUCT.md deleted file mode 100644 index 0fa18e5..0000000 --- a/CODE_OF_CONDUCT.md +++ /dev/null
@@ -1,22 +0,0 @@ -<!--/*~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ - ~ Licensed to the Apache Software Foundation (ASF) under one - ~ or more contributor license agreements. See the NOTICE file - ~ distributed with this work for additional information - ~ regarding copyright ownership. The ASF licenses this file - ~ to you 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. - ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~*/--> -Apache Software Foundation Code of Conduct -==== - -Being an Apache project, Apache Sling adheres to the Apache Software Foundation's [Code of Conduct](https://www.apache.org/foundation/policies/conduct.html).
diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md deleted file mode 100644 index ac82a1a..0000000 --- a/CONTRIBUTING.md +++ /dev/null
@@ -1,24 +0,0 @@ -<!--/*~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ - ~ Licensed to the Apache Software Foundation (ASF) under one - ~ or more contributor license agreements. See the NOTICE file - ~ distributed with this work for additional information - ~ regarding copyright ownership. The ASF licenses this file - ~ to you 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. - ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~*/--> -Contributing -==== - -Thanks for choosing to contribute! - -You will find all the necessary details about how you can do this at https://sling.apache.org/contributing.html.
diff --git a/Jenkinsfile b/Jenkinsfile deleted file mode 100644 index 3882176..0000000 --- a/Jenkinsfile +++ /dev/null
@@ -1,20 +0,0 @@ -/*~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ - ~ Licensed to the Apache Software Foundation (ASF) under one - ~ or more contributor license agreements. See the NOTICE file - ~ distributed with this work for additional information - ~ regarding copyright ownership. The ASF licenses this file - ~ to you 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. - ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~*/ -// please rebuild -slingOsgiBundleBuild()
diff --git a/LICENSE b/LICENSE deleted file mode 100644 index d645695..0000000 --- a/LICENSE +++ /dev/null
@@ -1,202 +0,0 @@ - - Apache License - Version 2.0, January 2004 - http://www.apache.org/licenses/ - - TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION - - 1. Definitions. - - "License" shall mean the terms and conditions for use, reproduction, - and distribution as defined by Sections 1 through 9 of this document. - - "Licensor" shall mean the copyright owner or entity authorized by - the copyright owner that is granting the License. - - "Legal Entity" shall mean the union of the acting entity and all - other entities that control, are controlled by, or are under common - control with that entity. For the purposes of this definition, - "control" means (i) the power, direct or indirect, to cause the - direction or management of such entity, whether by contract or - otherwise, or (ii) ownership of fifty percent (50%) or more of the - outstanding shares, or (iii) beneficial ownership of such entity. - - "You" (or "Your") shall mean an individual or Legal Entity - exercising permissions granted by this License. - - "Source" form shall mean the preferred form for making modifications, - including but not limited to software source code, documentation - source, and configuration files. - - "Object" form shall mean any form resulting from mechanical - transformation or translation of a Source form, including but - not limited to compiled object code, generated documentation, - and conversions to other media types. - - "Work" shall mean the work of authorship, whether in Source or - Object form, made available under the License, as indicated by a - copyright notice that is included in or attached to the work - (an example is provided in the Appendix below). - - "Derivative Works" shall mean any work, whether in Source or Object - form, that is based on (or derived from) the Work and for which the - editorial revisions, annotations, elaborations, or other modifications - represent, as a whole, an original work of authorship. For the purposes - of this License, Derivative Works shall not include works that remain - separable from, or merely link (or bind by name) to the interfaces of, - the Work and Derivative Works thereof. - - "Contribution" shall mean any work of authorship, including - the original version of the Work and any modifications or additions - to that Work or Derivative Works thereof, that is intentionally - submitted to Licensor for inclusion in the Work by the copyright owner - or by an individual or Legal Entity authorized to submit on behalf of - the copyright owner. For the purposes of this definition, "submitted" - means any form of electronic, verbal, or written communication sent - to the Licensor or its representatives, including but not limited to - communication on electronic mailing lists, source code control systems, - and issue tracking systems that are managed by, or on behalf of, the - Licensor for the purpose of discussing and improving the Work, but - excluding communication that is conspicuously marked or otherwise - designated in writing by the copyright owner as "Not a Contribution." - - "Contributor" shall mean Licensor and any individual or Legal Entity - on behalf of whom a Contribution has been received by Licensor and - subsequently incorporated within the Work. - - 2. Grant of Copyright License. Subject to the terms and conditions of - this License, each Contributor hereby grants to You a perpetual, - worldwide, non-exclusive, no-charge, royalty-free, irrevocable - copyright license to reproduce, prepare Derivative Works of, - publicly display, publicly perform, sublicense, and distribute the - Work and such Derivative Works in Source or Object form. - - 3. Grant of Patent License. Subject to the terms and conditions of - this License, each Contributor hereby grants to You a perpetual, - worldwide, non-exclusive, no-charge, royalty-free, irrevocable - (except as stated in this section) patent license to make, have made, - use, offer to sell, sell, import, and otherwise transfer the Work, - where such license applies only to those patent claims licensable - by such Contributor that are necessarily infringed by their - Contribution(s) alone or by combination of their Contribution(s) - with the Work to which such Contribution(s) was submitted. If You - institute patent litigation against any entity (including a - cross-claim or counterclaim in a lawsuit) alleging that the Work - or a Contribution incorporated within the Work constitutes direct - or contributory patent infringement, then any patent licenses - granted to You under this License for that Work shall terminate - as of the date such litigation is filed. - - 4. Redistribution. You may reproduce and distribute copies of the - Work or Derivative Works thereof in any medium, with or without - modifications, and in Source or Object form, provided that You - meet the following conditions: - - (a) You must give any other recipients of the Work or - Derivative Works a copy of this License; and - - (b) You must cause any modified files to carry prominent notices - stating that You changed the files; and - - (c) You must retain, in the Source form of any Derivative Works - that You distribute, all copyright, patent, trademark, and - attribution notices from the Source form of the Work, - excluding those notices that do not pertain to any part of - the Derivative Works; and - - (d) If the Work includes a "NOTICE" text file as part of its - distribution, then any Derivative Works that You distribute must - include a readable copy of the attribution notices contained - within such NOTICE file, excluding those notices that do not - pertain to any part of the Derivative Works, in at least one - of the following places: within a NOTICE text file distributed - as part of the Derivative Works; within the Source form or - documentation, if provided along with the Derivative Works; or, - within a display generated by the Derivative Works, if and - wherever such third-party notices normally appear. The contents - of the NOTICE file are for informational purposes only and - do not modify the License. You may add Your own attribution - notices within Derivative Works that You distribute, alongside - or as an addendum to the NOTICE text from the Work, provided - that such additional attribution notices cannot be construed - as modifying the License. - - You may add Your own copyright statement to Your modifications and - may provide additional or different license terms and conditions - for use, reproduction, or distribution of Your modifications, or - for any such Derivative Works as a whole, provided Your use, - reproduction, and distribution of the Work otherwise complies with - the conditions stated in this License. - - 5. Submission of Contributions. Unless You explicitly state otherwise, - any Contribution intentionally submitted for inclusion in the Work - by You to the Licensor shall be under the terms and conditions of - this License, without any additional terms or conditions. - Notwithstanding the above, nothing herein shall supersede or modify - the terms of any separate license agreement you may have executed - with Licensor regarding such Contributions. - - 6. Trademarks. This License does not grant permission to use the trade - names, trademarks, service marks, or product names of the Licensor, - except as required for reasonable and customary use in describing the - origin of the Work and reproducing the content of the NOTICE file. - - 7. Disclaimer of Warranty. Unless required by applicable law or - agreed to in writing, Licensor provides the Work (and each - Contributor provides its Contributions) 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. You are solely responsible for determining the - appropriateness of using or redistributing the Work and assume any - risks associated with Your exercise of permissions under this License. - - 8. Limitation of Liability. In no event and under no legal theory, - whether in tort (including negligence), contract, or otherwise, - unless required by applicable law (such as deliberate and grossly - negligent acts) or agreed to in writing, shall any Contributor be - liable to You for damages, including any direct, indirect, special, - incidental, or consequential damages of any character arising as a - result of this License or out of the use or inability to use the - Work (including but not limited to damages for loss of goodwill, - work stoppage, computer failure or malfunction, or any and all - other commercial damages or losses), even if such Contributor - has been advised of the possibility of such damages. - - 9. Accepting Warranty or Additional Liability. While redistributing - the Work or Derivative Works thereof, You may choose to offer, - and charge a fee for, acceptance of support, warranty, indemnity, - or other liability obligations and/or rights consistent with this - License. However, in accepting such obligations, You may act only - on Your own behalf and on Your sole responsibility, not on behalf - of any other Contributor, and only if You agree to indemnify, - defend, and hold each Contributor harmless for any liability - incurred by, or claims asserted against, such Contributor by reason - of your accepting any such warranty or additional liability. - - END OF TERMS AND CONDITIONS - - APPENDIX: How to apply the Apache License to your work. - - To apply the Apache License to your work, attach the following - boilerplate notice, with the fields enclosed by brackets "[]" - replaced with your own identifying information. (Don't include - the brackets!) The text should be enclosed in the appropriate - comment syntax for the file format. We also recommend that a - file or class name and description of purpose be included on the - same "printed page" as the copyright notice for easier - identification within third-party archives. - - Copyright [yyyy] [name of copyright owner] - - 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.
diff --git a/README.md b/README.md index aafa0d3..5df35c7 100644 --- a/README.md +++ b/README.md
@@ -1,96 +1,10 @@ [](https://sling.apache.org) - [](https://ci-builds.apache.org/job/Sling/job/modules/job/sling-org-apache-sling-scripting-bundle-tracker/job/master/) [](https://ci-builds.apache.org/job/Sling/job/modules/job/sling-org-apache-sling-scripting-bundle-tracker/job/master/test/?width=800&height=600) [](https://sonarcloud.io/dashboard?id=apache_sling-org-apache-sling-scripting-bundle-tracker) [](https://sonarcloud.io/dashboard?id=apache_sling-org-apache-sling-scripting-bundle-tracker) [](https://www.javadoc.io/doc/org.apache.sling/org-apache-sling-scripting-bundle-tracker) [](https://search.maven.org/#search%7Cga%7C1%7Cg%3A%22org.apache.sling%22%20a%3A%22org.apache.sling.scripting.bundle.tracker%22) [](https://github.com/apache/sling-aggregator/blob/master/docs/group/scripting.md) [](https://www.apache.org/licenses/LICENSE-2.0) - -Apache Sling Scripting Bundle Tracker +Apache Sling Scripting Bundle Tracker (deprecated) ==== -## DEPRECATED? +This module is part of the [Apache Sling](https://sling.apache.org) project, but it is no longer maintained. -Note that this code has **moved to the [o.a.s.servlets.resolver](https://github.com/apache/sling-org-apache-sling-servlets-resolver/tree/master/src/main/java/org/apache/sling/servlets/resolver/bundle/tracker) module** - as I write this, -[discussions are ongoing](https://lists.apache.org/thread.html/r73ffc8f89706444db41cf9e3688799be58b41cd5f16c49468ab4bda5%40%3Cdev.sling.apache.org%3E) -on the Sling dev list on whether this module needs to be deprecated or repurposed. +Version 2.7.0 of the [`org.apache.sling.servlets.resolver`](https://github.com/apache/sling-org-apache-sling-servlets-resolver) and version 2.3.0 of the [`org.apache.sling.scripting.core`](https://github.com/apache/sling-org-apache-sling-scripting-core) modules provide now the same functionality. -## What -The `org.apache.sling.scripting.bundle.tracker` bundle represents an add-on module that can be deployed on a Sling 10 instance or newer to -enhance the scripting resolving capabilities. Being an add-on, the bundle hooks into Sling's current mechanisms for -content-to-servlet resolution and essentially acts as a service registration broker for bundles providing scripting -capabilities (more details in the ["How"](#how) section). - -## Why -Although traditionally scripts are deployed as content stored in the search paths of a Sling instance, this leaves very little -room for script evolution in a backwards compatible way. Furthermore, versioning scripts is a difficult process if the only -mechanism to do this is the `sling:resourceType` property, since consumers (content nodes or other resource types) have then to -explicitly mention the version expected to be executed. - -Scripts should not be considered content, since their only purpose is to actually generate the rendering for a certain content -structure. They are not consumed by users, but rather by the Sling Engine itself and have very little meaning outside this -context. As such, scripts should be handled like code: - - 1. they _provide an HTTP API_; - 2. they can evolve in a _semantical_ [1] way; - 3. they have a _developer audience_. - -## How -Being built around a `BundleTrackerCustomizer` [2], the Scripting Bundle Tracker monitors the instance's bundles wired to itself and -scans the ones providing a `sling.resourceType` capability [3]. The wiring is created by placing a `Require-Capability` header in -the bundles that provide the `sling.resourceType` capability: - -``` -osgi.extender;filter:="(&(osgi.extender=sling.scripting)(version>=1.0.0)(!(version>=2.0.0)))" -``` - - -A `sling.resourceType` capability has the following attributes: - - 1. `sling.resourceType:String` - mandatory; defines the provided resource type; its value is a valid Java package identifier, - though it does not need to correspond to one; - 2. `sling.resourceType.selectors:List` - optional; defines the list of selectors that this resource type can handle; - 3. `sling.resourceType.extensions:List` - optional; defines the list of extensions that this resource type can handle; - 4. `version:Version` - mandatory; defines the version of the provided `resourceType`; - 5. `extends:String` - optional; defines which resource type it extends; the version range of the extended resource type is defined in a - `Require-Capability`. - -The `BundleTrackerCustomizer` will register a Sling Servlet with the appropriate `sling.servlet` properties for each `sling.resourceType` -capability. The servlets will be registered using the bundle context of the bundle providing the `sling.resourceType` capability, making -sure to expose the different versions of a resource type as part of the registered servlet's properties. On top of this, a plain resource -type bound servlet will also be registered, which will be automatically wired to the highest version of `resourceType`. All the mentioned -service registrations are managed automatically by the `BundleTrackerCustomizer`. - -### So how do I deploy my scripts? -Short answer: exactly like you deploy your code, preferably right next to it. Pack your scripts using the following conventions: - - 1. create a `javax.script` folder in your bundle; - 2. each folder under `javax.script` will identify a `resourceType`; the folder name should preferably be a valid Java package identifier, - but it does not need to refer to an existing one; - 3. inside each `resourceType` folder create a `Version` folder; this has to follow the Semantic Versioning constraints described at [1]; - 4. add your scripts, using the same naming conventions that you were used to from before [4]; - 5. manually define your provide and require capabilities; just kidding; add the - [`scriptingbundle-maven-plugin`](https://github.com/apache/sling-scriptingbundle-maven-plugin) to your build section and add its required - properties in the `maven-bundle-plugin`'s instructions (check [this](https://github.com/apache/sling-org-apache-sling-scripting-bundle-tracker-it/tree/master/examples/org-apache-sling-scripting-examplebundle/pom.xml) - example); - 6. `mvn clean sling:install`. - -### Integration Tests - -The integration tests are provided by the [`org.apache.sling.scripting.bundle.tracker.it`](https://github.com/apache/sling-org-apache-sling-scripting-bundle-tracker-it) project. To run the integration tests execute the following command: - -``` -mvn clean verify -Pit -``` - -### Example - -To play around with a Sling instance on localhost port 8080 (override with -Dhttp.port=<port>) that has the [examples](https://github.com/apache/sling-org-apache-sling-scripting-bundle-tracker-it/tree/master/examples/) installed run: - -``` -mvn clean verify -Pexample -``` - -from the [`org.apache.sling.scripting.bundle.tracker.it`](https://github.com/apache/sling-org-apache-sling-scripting-bundle-tracker-it) project. - -## Resources -[1] - https://semver.org/ -[2] - https://osgi.org/javadoc/r6/core/org/osgi/util/tracker/BundleTrackerCustomizer.html -[3] - https://osgi.org/download/r6/osgi.core-6.0.0.pdf, Page 41, section 3.3.3 "Bundle Capabilities" -[4] - https://sling.apache.org/documentation/the-sling-engine/url-to-script-resolution.html +For reference or potential bugfix releases please use the [`maintenance`](https://github.com/apache/sling-org-apache-sling-scripting-bundle-tracker/tree/maintenance) branch.
diff --git a/pom.xml b/pom.xml deleted file mode 100644 index de4f3b9..0000000 --- a/pom.xml +++ /dev/null
@@ -1,201 +0,0 @@ -<?xml version="1.0" encoding="UTF-8"?> -<!--~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ - ~ Licensed to the Apache Software Foundation (ASF) under one - ~ or more contributor license agreements. See the NOTICE file - ~ distributed with this work for additional information - ~ regarding copyright ownership. The ASF licenses this file - ~ to you 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. - ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~--> -<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> - <parent> - <groupId>org.apache.sling</groupId> - <artifactId>sling-bundle-parent</artifactId> - <version>35</version> - <relativePath /> - </parent> - <modelVersion>4.0.0</modelVersion> - - <properties> - <jacoco.maven.plugin.version>0.8.2</jacoco.maven.plugin.version> - </properties> - - <artifactId>org.apache.sling.scripting.bundle.tracker</artifactId> - <version>0.1.1-SNAPSHOT</version> - <name>Apache Sling Scripting Bundle Tracker</name> - <description> - The Apache Sling Scripting Bundle Tracker bundle represents an add-on module that can be deployed on a Sling 10 instance or - newer to enhance the scripting resolving capabilities. Being an add-on, the bundle hooks into Sling's current mechanisms for - content-to-servlet resolution and essentially acts as a service registration broker for bundles providing scripting capabilities - </description> - - <scm> - <connection>scm:git:https://gitbox.apache.org/repos/asf/sling-org-apache-sling-scripting-bundle-tracker.git</connection> - <developerConnection>scm:git:https://gitbox.apache.org/repos/asf/sling-org-apache-sling-scripting-bundle-tracker.git</developerConnection> - <url>https://gitbox.apache.org/repos/asf?p=sling-org-apache-sling-scripting-bundle-tracker.git</url> - <tag>HEAD</tag> - </scm> - - <build> - <plugins> - <plugin> - <groupId>biz.aQute.bnd</groupId> - <artifactId>bnd-maven-plugin</artifactId> - </plugin> - <plugin> - <groupId>biz.aQute.bnd</groupId> - <artifactId>bnd-baseline-maven-plugin</artifactId> - <configuration> - <failOnMissing>false</failOnMissing> - </configuration> - </plugin> - <plugin> - <groupId>com.github.spotbugs</groupId> - <artifactId>spotbugs-maven-plugin</artifactId> - <version>3.1.11</version> - <configuration> - <effort>Max</effort> - <xmlOutput>true</xmlOutput> - <excludeFilterFile>src/test/resources/findbugs-exclude.xml</excludeFilterFile> - </configuration> - <executions> - <execution> - <id>find-bugs</id> - <phase>process-classes</phase> - <goals> - <goal>check</goal> - </goals> - </execution> - </executions> - </plugin> - <plugin> - <groupId>org.apache.maven.plugins</groupId> - <artifactId>maven-surefire-plugin</artifactId> - <configuration> - <argLine>@{argLine}</argLine> - </configuration> - </plugin> - - <plugin> - <groupId>org.jacoco</groupId> - <artifactId>jacoco-maven-plugin</artifactId> - <version>${jacoco.maven.plugin.version}</version> - <executions> - <execution> - <id>prepare-agent</id> - <goals> - <goal>prepare-agent</goal> - </goals> - <configuration> - <destFile>${project.build.directory}/jacoco-unit.exec</destFile> - </configuration> - </execution> - </executions> - </plugin> - </plugins> - </build> - - <dependencies> - <dependency> - <groupId>org.jetbrains</groupId> - <artifactId>annotations</artifactId> - <scope>provided</scope> - </dependency> - <dependency> - <groupId>org.apache.sling</groupId> - <artifactId>org.apache.sling.api</artifactId> - <version>2.22.0</version> - <scope>provided</scope> - </dependency> - <dependency> - <groupId>org.apache.sling</groupId> - <artifactId>org.apache.sling.commons.osgi</artifactId> - <version>2.4.0</version> - <scope>provided</scope> - </dependency> - <dependency> - <groupId>javax.servlet</groupId> - <artifactId>javax.servlet-api</artifactId> - <scope>provided</scope> - </dependency> - <dependency> - <groupId>org.osgi</groupId> - <artifactId>osgi.core</artifactId> - <scope>provided</scope> - </dependency> - <dependency> - <groupId>org.osgi</groupId> - <artifactId>osgi.cmpn</artifactId> - <scope>provided</scope> - </dependency> - <dependency> - <groupId>org.osgi</groupId> - <artifactId>org.osgi.annotation.versioning</artifactId> - <scope>provided</scope> - </dependency> - <dependency> - <groupId>org.osgi</groupId> - <artifactId>org.osgi.annotation.bundle</artifactId> - <version>1.0.0</version> - <scope>provided</scope> - </dependency> - <dependency> - <groupId>org.apache.commons</groupId> - <artifactId>commons-lang3</artifactId> - <version>3.7</version> - <scope>provided</scope> - </dependency> - <dependency> - <groupId>commons-io</groupId> - <artifactId>commons-io</artifactId> - <version>2.6</version> - <scope>provided</scope> - </dependency> - <dependency> - <groupId>org.slf4j</groupId> - <artifactId>slf4j-api</artifactId> - <scope>provided</scope> - </dependency> - <dependency> - <groupId>org.apache.sling</groupId> - <artifactId>org.apache.sling.scripting.api</artifactId> - <version>2.2.0</version> - <scope>provided</scope> - </dependency> - <dependency> - <groupId>org.apache.sling</groupId> - <artifactId>org.apache.sling.scripting.core</artifactId> - <version>2.0.54</version> - <scope>provided</scope> - </dependency> - <dependency> - <groupId>org.apache.sling</groupId> - <artifactId>org.apache.sling.commons.compiler</artifactId> - <version>2.3.7-SNAPSHOT</version> - <scope>provided</scope> - </dependency> - <!-- TESTING --> - <dependency> - <groupId>junit</groupId> - <artifactId>junit</artifactId> - <scope>test</scope> - </dependency> - - <dependency> - <groupId>org.mockito</groupId> - <artifactId>mockito-core</artifactId> - <version>2.25.1</version> - <scope>test</scope> - </dependency> - </dependencies> -</project>
diff --git a/src/main/java/org/apache/sling/scripting/bundle/tracker/BundledRenderUnit.java b/src/main/java/org/apache/sling/scripting/bundle/tracker/BundledRenderUnit.java deleted file mode 100644 index 3849a36..0000000 --- a/src/main/java/org/apache/sling/scripting/bundle/tracker/BundledRenderUnit.java +++ /dev/null
@@ -1,104 +0,0 @@ -/*~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ - ~ Licensed to the Apache Software Foundation (ASF) under one - ~ or more contributor license agreements. See the NOTICE file - ~ distributed with this work for additional information - ~ regarding copyright ownership. The ASF licenses this file - ~ to you 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 org.apache.sling.scripting.bundle.tracker; - -import java.util.Set; - -import org.jetbrains.annotations.NotNull; -import org.jetbrains.annotations.Nullable; -import org.osgi.annotation.versioning.ProviderType; -import org.osgi.framework.Bundle; - -/** - * <p> - * A {@code BundledRenderUnit} represents a pre-packaged script or precompiled script that will be executed in order to render a - * {@link org.apache.sling.api.SlingHttpServletRequest}. - * </p> - * <p> - * If the current {@link org.apache.sling.api.SlingHttpServletRequest} is served by a {@code BundledRenderUnit}, the - * {@code org.apache.sling.scripting.bundle.tracker} will set the {@code BundledRenderUnit} in the {@link javax.script.Bindings} map associated to the request, - * under the {@link #VARIABLE} key. - * </p> - */ -@ProviderType -public interface BundledRenderUnit { - - /** - * The variable available in the {@link javax.script.Bindings} associated to a {@link org.apache.sling.api.SlingHttpServletRequest} - * if that request is served by a {@code BundledRenderUnit}. - */ - String VARIABLE = BundledRenderUnit.class.getName(); - - /** - * In case this {@code BundledRenderUnit} wraps a precompiled script, this method will return an instance of that object. - * - * @return a precompiled unit, if {@code this} unit wraps a precompiled script; {@code null} otherwise - */ - @Nullable - default Object getUnit() { - return null; - } - - /** - * Returns the name of {@code this BundledRenderUnit}. This can be the name of the wrapped script or precompiled script. - * - * @return the name {@code this BundledRenderUnit} - */ - @NotNull String getName(); - - /** - * Returns the {@link Bundle} in which the script or precompiled script is packaged. This method can be useful for getting an - * instance of the bundle's classloader, when needed to load dependencies at run time. To do so the following code example can help: - * - * <pre> - * Bundle bundle = bundledRenderUnit.getBundle(); - * Classloader bundleClassloader = bundle.adapt(BundleWiring.class).getClassLoader(); - * </pre> - */ - @NotNull Bundle getBundle(); - - /** - * Returns the {@code Set} of {@link TypeProvider}s which are related to this unit. - * - * @return the set of providers; if the unit doesn't have any inheritance chains, then the set will contain only one {@link - * TypeProvider} - */ - @NotNull Set<TypeProvider> getTypeProviders(); - - /** - * Retrieves an OSGi runtime dependency of the wrapped script identified by the passed {@code className} parameter. - * - * @param className the fully qualified class name - * @param <T> the expected service type - * @return an instance of the {@link T} or {@code null} - */ - @Nullable <T> T getService(@NotNull String className); - - /** - * Retrieves multiple instances of an OSGi runtime dependency of the wrapped script identified by the passed {@code className} - * parameter, filtered according to the passed {@code filter}. - * - * @param className the fully qualified class name - * @param filter a filter expression or {@code null} if all the instances should be returned; for more details about the {@code - * filter}'s syntax check {@link org.osgi.framework.BundleContext#getServiceReferences(String, String)} - * @param <T> the expected service type - * @return an instance of the {@link T} or {@code null} - */ - @Nullable <T> T[] getServices(@NotNull String className, @Nullable String filter); -}
diff --git a/src/main/java/org/apache/sling/scripting/bundle/tracker/BundledRenderUnitCapability.java b/src/main/java/org/apache/sling/scripting/bundle/tracker/BundledRenderUnitCapability.java deleted file mode 100644 index dbda3d6..0000000 --- a/src/main/java/org/apache/sling/scripting/bundle/tracker/BundledRenderUnitCapability.java +++ /dev/null
@@ -1,91 +0,0 @@ -/*~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ - ~ Licensed to the Apache Software Foundation (ASF) under one - ~ or more contributor license agreements. See the NOTICE file - ~ distributed with this work for additional information - ~ regarding copyright ownership. The ASF licenses this file - ~ to you 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 org.apache.sling.scripting.bundle.tracker; - -import java.util.List; -import java.util.Set; - -import org.jetbrains.annotations.NotNull; -import org.jetbrains.annotations.Nullable; -import org.osgi.annotation.versioning.ProviderType; - -/** - * A {@code BundledRenderUnitCapability} encapsulates the values of a {@code Provided-Capability}, based on which {@link BundledRenderUnit}s - * are generated. - */ -@ProviderType -public interface BundledRenderUnitCapability { - - /** - * Returns the resource types to which a {@link BundledRenderUnit} described by this capability will be bound to. - * - * @return the resource types to which a {@link BundledRenderUnit} described by this capability will be bound to - */ - @NotNull Set<ResourceType> getResourceTypes(); - - /** - * Returns the path to which a {@link BundledRenderUnit} described by this capability will be bound to. - * - * @return the path to which a {@link BundledRenderUnit} described by this capability will be bound to; this can be {@code null} if the - * {@link #getResourceTypes()} doesn't return an empty set - */ - @Nullable String getPath(); - - /** - * Returns the selectors to which a {@link BundledRenderUnit} described by this capability will be bound to. - * - * @return the selectors to which a {@link BundledRenderUnit} described by this capability will be bound to - */ - @NotNull List<String> getSelectors(); - - /** - * Returns the extension to which a {@link BundledRenderUnit} described by this capability will be bound to. - * - * @return the extension to which a {@link BundledRenderUnit} described by this capability will be bound to - */ - @Nullable String getExtension(); - - /** - * Returns the resource type extended by this capability. - * - * @return the extended resource type or {@code null} - */ - @Nullable String getExtendedResourceType(); - - /** - * Returns the request method to which a {@link BundledRenderUnit} described by this capability will be bound to. - * - * @return the request method to which a {@link BundledRenderUnit} described by this capability will be bound to - */ - @Nullable String getMethod(); - - /** - * Returns the script engine short name which can be used to evaluate the {@link BundledRenderUnit} described by this capability. - * - * @return the script engine short name which can be used to evaluate the {@link BundledRenderUnit} described by this capability. - */ - @Nullable String getScriptEngineName(); - - /** - * Returns the original's script extension that was used to generate this capability. - * - * @return the original's script extension that was used to generate this capability. - */ - @Nullable String getScriptExtension(); -}
diff --git a/src/main/java/org/apache/sling/scripting/bundle/tracker/ResourceType.java b/src/main/java/org/apache/sling/scripting/bundle/tracker/ResourceType.java deleted file mode 100644 index b1399f1..0000000 --- a/src/main/java/org/apache/sling/scripting/bundle/tracker/ResourceType.java +++ /dev/null
@@ -1,161 +0,0 @@ -/*~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ - ~ Licensed to the Apache Software Foundation (ASF) under one - ~ or more contributor license agreements. See the NOTICE file - ~ distributed with this work for additional information - ~ regarding copyright ownership. The ASF licenses this file - ~ to you 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 org.apache.sling.scripting.bundle.tracker; - -import java.util.Objects; -import java.util.regex.Pattern; - -import org.apache.commons.lang3.StringUtils; -import org.jetbrains.annotations.NotNull; -import org.jetbrains.annotations.Nullable; -import org.osgi.framework.Version; - -/** - * The {@code ResourceTypeParser} provides methods for parsing resource type strings. - * - * <p>The following patterns are supported:</p> - * <ol> - * <li><tt>a/b/c</tt> - path-based</li> - * <li><tt>a/b/c/1.0.0</tt> - path-based, versioned</li> - * <li><tt>a.b.c</tt> - Java package name</li> - * <li><tt>a.b.c/1.0.0</tt> - Java package name, versioned</li> - * <li><tt>a</tt> - flat (sub-set of path-based)</li> - * </ol> - */ -public final class ResourceType { - - private static final Pattern versionPattern = Pattern.compile("[\\d\\.]+(-.*)*$"); - - private final String type; - private final String version; - private final String resourceLabel; - private final String toString; - - private ResourceType(@NotNull String type, @Nullable String version) { - this.type = type; - this.version = version; - if (type.lastIndexOf('/') != -1) { - resourceLabel = type.substring(type.lastIndexOf('/') + 1); - } else if (type.lastIndexOf('.') != -1) { - resourceLabel = type.substring(type.lastIndexOf('.') + 1); - } else { - resourceLabel = type; - } - toString = type + (version == null ? "" : "/" + version); - } - - /** - * Returns a resource type's label. The label is important for script selection, since it will provide the name of the main script - * for this resource type. For more details check the Apache Sling - * <a href="https://sling.apache.org/documentation/the-sling-engine/url-to-script-resolution.html#scripts-for-get-requests">URL to - * Script Resolution</a> page - * - * @return the resource type label - */ - @NotNull - public String getResourceLabel() { - return resourceLabel; - } - - /** - * Returns the resource type string, without any version information. - * - * @return the resource type string - */ - @NotNull - public String getType() { - return type; - } - - /** - * Returns the version, if available. - * - * @return the version, if available; {@code null} otherwise - */ - @Nullable - public String getVersion() { - return version; - } - - @Override - public String toString() { - return toString; - } - - /** - * Given a {@code resourceTypeString}, this method will extract a {@link ResourceType} object. - * <p>The accepted patterns are:</p> - * <ol> - * <li><tt>a/b/c</tt> - path-based</li> - * <li><tt>a/b/c/1.0.0</tt> - path-based, versioned</li> - * <li><tt>a.b.c</tt> - Java package name</li> - * <li><tt>a.b.c/1.0.0</tt> - Java package name, versioned</li> - * <li><tt>a</tt> - flat (sub-set of path-based)</li> - * </ol> - * - * @param resourceTypeString the resource type string to parse - * @return a {@link ResourceType} object - * @throws IllegalArgumentException if the {@code resourceTypeString} cannot be parsed - */ - @NotNull - public static ResourceType parseResourceType(@NotNull String resourceTypeString) { - String type = StringUtils.EMPTY; - String version = null; - if (StringUtils.isNotEmpty(resourceTypeString)) { - int lastSlash = resourceTypeString.lastIndexOf('/'); - if (lastSlash != -1 && !resourceTypeString.endsWith("/")) { - String versionString = resourceTypeString.substring(lastSlash + 1); - if (versionPattern.matcher(versionString).matches()) { - try { - version = Version.parseVersion(versionString).toString(); - type = resourceTypeString.substring(0, lastSlash); - } catch (IllegalArgumentException e) { - type = resourceTypeString; - } - } else { - type = resourceTypeString; - } - } else { - type = resourceTypeString; - } - } - if (StringUtils.isEmpty(type)) { - throw new IllegalArgumentException(String.format("Cannot extract a type for the resourceTypeString %s.", resourceTypeString)); - } - return new ResourceType(type, version); - } - - @Override - public int hashCode() { - return Objects.hash(type, version, resourceLabel); - } - - @Override - public boolean equals(Object obj) { - if (this == obj) { - return true; - } - if (obj instanceof ResourceType) { - ResourceType other = (ResourceType) obj; - return Objects.equals(type, other.type) && Objects.equals(version, other.version) && Objects.equals(resourceLabel, - other.resourceLabel); - } - return false; - } -}
diff --git a/src/main/java/org/apache/sling/scripting/bundle/tracker/TypeProvider.java b/src/main/java/org/apache/sling/scripting/bundle/tracker/TypeProvider.java deleted file mode 100644 index f508c52..0000000 --- a/src/main/java/org/apache/sling/scripting/bundle/tracker/TypeProvider.java +++ /dev/null
@@ -1,45 +0,0 @@ -/*~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ - ~ Licensed to the Apache Software Foundation (ASF) under one - ~ or more contributor license agreements. See the NOTICE file - ~ distributed with this work for additional information - ~ regarding copyright ownership. The ASF licenses this file - ~ to you 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 org.apache.sling.scripting.bundle.tracker; - -import org.jetbrains.annotations.NotNull; -import org.osgi.annotation.versioning.ProviderType; -import org.osgi.framework.Bundle; - -/** - * A {@code TypeProvider} keeps an association between a {@link BundledRenderUnitCapability} and the bundle that provides it. - */ -@ProviderType -public interface TypeProvider { - - /** - * Returns the {@link BundledRenderUnitCapability}. - * - * @return the {@link BundledRenderUnitCapability} - */ - @NotNull BundledRenderUnitCapability getBundledRenderUnitCapability(); - - /** - * Returns the providing bundle. - * - * @return the providing bundle - */ - @NotNull Bundle getBundle(); - -}
diff --git a/src/main/java/org/apache/sling/scripting/bundle/tracker/internal/AbstractBundledRenderUnit.java b/src/main/java/org/apache/sling/scripting/bundle/tracker/internal/AbstractBundledRenderUnit.java deleted file mode 100644 index 9362b32..0000000 --- a/src/main/java/org/apache/sling/scripting/bundle/tracker/internal/AbstractBundledRenderUnit.java +++ /dev/null
@@ -1,158 +0,0 @@ -/*~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ - ~ Licensed to the Apache Software Foundation (ASF) under one - ~ or more contributor license agreements. See the NOTICE file - ~ distributed with this work for additional information - ~ regarding copyright ownership. The ASF licenses this file - ~ to you 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 org.apache.sling.scripting.bundle.tracker.internal; - -import java.lang.reflect.Array; -import java.util.ArrayList; -import java.util.Arrays; -import java.util.Collections; -import java.util.HashMap; -import java.util.List; -import java.util.Map; -import java.util.Set; - -import org.apache.sling.scripting.bundle.tracker.TypeProvider; -import org.jetbrains.annotations.NotNull; -import org.jetbrains.annotations.Nullable; -import org.osgi.framework.Bundle; -import org.osgi.framework.BundleContext; -import org.osgi.framework.ServiceReference; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -abstract class AbstractBundledRenderUnit implements Executable { - - private static final Logger LOG = LoggerFactory.getLogger(AbstractBundledRenderUnit.class.getName()); - - private final Set<TypeProvider> providers; - private final Bundle bundle; - private final BundleContext bundleContext; - private final String path; - private final String scriptEngineName; - private List<ServiceReference<?>> references; - private Map<String, Object> services; - - - AbstractBundledRenderUnit(@NotNull Set<TypeProvider> providers, @NotNull Bundle bundle, @NotNull String path, - @NotNull String scriptEngineName) { - this.providers = providers; - this.bundle = bundle; - this.path = path; - this.scriptEngineName = scriptEngineName; - bundleContext = bundle.getBundleContext(); - } - - @Override - @NotNull - public Bundle getBundle() { - return bundle; - } - - @Override - public @NotNull Set<TypeProvider> getTypeProviders() { - return providers; - } - - @Override - public @NotNull String getPath() { - return path; - } - - @Override - public @NotNull String getScriptEngineName() { - return scriptEngineName; - } - - @Override - @Nullable - @SuppressWarnings("unchecked") - public <T> T getService(@NotNull String className) { - LOG.debug("Attempting to load class {} as an OSGi service.", className); - T result = (this.services == null ? null : (T) this.services.get(className)); - if (result == null) { - final ServiceReference<?> ref = this.bundleContext.getServiceReference(className); - if (ref != null) { - result = (T) this.bundleContext.getService(ref); - if (result != null) { - if (this.services == null) { - this.services = new HashMap<>(); - } - if (this.references == null) { - this.references = new ArrayList<>(); - } - this.references.add(ref); - this.services.put(className, result); - return result; - } - } - } - return null; - } - - @Override - @Nullable - @SuppressWarnings("unchecked") - public <T> T[] getServices(@NotNull String className, @Nullable String filter) { - T[] result = null; - try { - final ServiceReference<?>[] refs = this.bundleContext.getServiceReferences(className, filter); - - if (refs != null) { - // sort by service ranking (lowest first) (see ServiceReference#compareTo(Object)) - List<ServiceReference<?>> localReferences = Arrays.asList(refs); - Collections.sort(localReferences); - // get the highest ranking first - Collections.reverse(localReferences); - - final List<T> objects = new ArrayList<>(); - for (ServiceReference<?> reference : localReferences) { - final T service = (T) this.bundleContext.getService(reference); - if (service != null) { - if (this.references == null) { - this.references = new ArrayList<>(); - } - this.references.add(reference); - objects.add(service); - } - } - if (!objects.isEmpty()) { - T[] srv = (T[]) Array.newInstance(bundle.loadClass(className), objects.size()); - result = objects.toArray(srv); - } - } - } catch (Exception e) { - LOG.error(String.format("Unable to retrieve the services of type %s.", className), e); - } - return result; - } - - @Override - public void releaseDependencies() { - if (references != null) { - for (ServiceReference<?> reference : this.references) { - bundleContext.ungetService(reference); - } - references.clear(); - } - if (services != null) { - services.clear(); - } - } - -}
diff --git a/src/main/java/org/apache/sling/scripting/bundle/tracker/internal/BundledHooks.java b/src/main/java/org/apache/sling/scripting/bundle/tracker/internal/BundledHooks.java deleted file mode 100644 index 371df4b..0000000 --- a/src/main/java/org/apache/sling/scripting/bundle/tracker/internal/BundledHooks.java +++ /dev/null
@@ -1,57 +0,0 @@ -/*~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ - ~ Licensed to the Apache Software Foundation (ASF) under one - ~ or more contributor license agreements. See the NOTICE file - ~ distributed with this work for additional information - ~ regarding copyright ownership. The ASF licenses this file - ~ to you 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 org.apache.sling.scripting.bundle.tracker.internal; - -import java.util.Collection; -import java.util.Iterator; -import java.util.Map; - -import org.osgi.framework.BundleContext; -import org.osgi.framework.ServiceEvent; -import org.osgi.framework.ServiceReference; -import org.osgi.framework.hooks.service.EventListenerHook; -import org.osgi.framework.hooks.service.FindHook; -import org.osgi.framework.hooks.service.ListenerHook; -import org.osgi.service.component.annotations.Component; - -@Component -public class BundledHooks implements FindHook, EventListenerHook { - @Override - public void find(BundleContext context, String name, String filter, boolean allServices, Collection<ServiceReference<?>> references) { - if (!context.getBundle().getSymbolicName().equals("org.apache.sling.servlets.resolver")) { - for (Iterator<ServiceReference<?>> iter = references.iterator(); iter.hasNext();) { - if (iter.next().getProperty(BundledHooks.class.getName()) != null) { - iter.remove(); - } - } - } - } - - - @Override - public void event(ServiceEvent event, Map<BundleContext, Collection<ListenerHook.ListenerInfo>> listeners) { - if (event.getServiceReference().getProperty(BundledHooks.class.getName()) != null) { - for (Iterator<Map.Entry<BundleContext, Collection<ListenerHook.ListenerInfo>>> entries = listeners.entrySet().iterator(); entries.hasNext();) { - if (!entries.next().getKey().getBundle().getSymbolicName().equals("org.apache.sling.servlets.resolver")) { - entries.remove(); - } - } - } - } -}
diff --git a/src/main/java/org/apache/sling/scripting/bundle/tracker/internal/BundledRenderUnitCapabilityImpl.java b/src/main/java/org/apache/sling/scripting/bundle/tracker/internal/BundledRenderUnitCapabilityImpl.java deleted file mode 100644 index 469f1e5..0000000 --- a/src/main/java/org/apache/sling/scripting/bundle/tracker/internal/BundledRenderUnitCapabilityImpl.java +++ /dev/null
@@ -1,159 +0,0 @@ -/*~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ - ~ Licensed to the Apache Software Foundation (ASF) under one - ~ or more contributor license agreements. See the NOTICE file - ~ distributed with this work for additional information - ~ regarding copyright ownership. The ASF licenses this file - ~ to you 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 org.apache.sling.scripting.bundle.tracker.internal; - -import java.util.Arrays; -import java.util.Collections; -import java.util.LinkedHashSet; -import java.util.List; -import java.util.Map; -import java.util.Objects; -import java.util.Set; - -import org.apache.sling.api.servlets.ServletResolverConstants; -import org.apache.sling.commons.osgi.PropertiesUtil; -import org.apache.sling.scripting.bundle.tracker.BundledRenderUnitCapability; -import org.apache.sling.scripting.bundle.tracker.ResourceType; -import org.jetbrains.annotations.NotNull; -import org.jetbrains.annotations.Nullable; -import org.osgi.framework.Version; -import org.osgi.framework.wiring.BundleCapability; - -class BundledRenderUnitCapabilityImpl implements BundledRenderUnitCapability { - - private final Set<ResourceType> resourceTypes; - private final String path; - private final List<String> selectors; - private final String extension; - private final String method; - private final String extendedResourceType; - private final String scriptEngineName; - private final String scriptExtension; - - private BundledRenderUnitCapabilityImpl(@NotNull Set<ResourceType> resourceTypes, @Nullable String path, - @NotNull List<String> selectors, - @Nullable String extension, @Nullable String method, - @Nullable String extendedResourceType, @Nullable String scriptEngineName, - @Nullable String scriptExtension) { - this.resourceTypes = resourceTypes; - this.path = path; - this.selectors = selectors; - this.extension = extension; - this.method = method; - this.extendedResourceType = extendedResourceType; - this.scriptEngineName = scriptEngineName; - this.scriptExtension = scriptExtension; - } - - @Override - @NotNull - public Set<ResourceType> getResourceTypes() { - return Collections.unmodifiableSet(resourceTypes); - } - - @Override - @Nullable - public String getPath() { - return path; - } - - @Override - @NotNull - public List<String> getSelectors() { - return Collections.unmodifiableList(selectors); - } - - @Override - @Nullable - public String getExtension() { - return extension; - } - - @Override - @Nullable - public String getExtendedResourceType() { - return extendedResourceType; - } - - @Override - @Nullable - public String getMethod() { - return method; - } - - @Override - @Nullable - public String getScriptEngineName() { - return scriptEngineName; - } - - @Override - @Nullable - public String getScriptExtension() { - return scriptExtension; - } - - @Override - public int hashCode() { - return Objects.hash(resourceTypes, path, selectors, extension, method, extendedResourceType, scriptEngineName, scriptExtension); - } - - @Override - public boolean equals(Object obj) { - if (this == obj) { - return true; - } - if (obj instanceof BundledRenderUnitCapability) { - BundledRenderUnitCapability other = (BundledRenderUnitCapability) obj; - return Objects.equals(resourceTypes, other.getResourceTypes()) && Objects.equals(path, other.getPath()) && - Objects.equals(selectors, other.getSelectors()) && - Objects.equals(extension, other.getExtension()) && Objects.equals(method, other.getMethod()) && - Objects.equals(extendedResourceType, other.getExtendedResourceType()) && - Objects.equals(scriptEngineName, other.getScriptEngineName()) && - Objects.equals(scriptExtension, other.getScriptExtension()); - } - return false; - } - - public static BundledRenderUnitCapability fromBundleCapability(@NotNull BundleCapability capability) { - Map<String, Object> attributes = capability.getAttributes(); - Set<ResourceType> resourceTypes = new LinkedHashSet<>(); - String[] capabilityResourceTypes = - PropertiesUtil.toStringArray(attributes.get(ServletResolverConstants.SLING_SERVLET_RESOURCE_TYPES), new String[0]); - Version version = (Version) attributes.get(BundledScriptTracker.AT_VERSION); - for (String rt : capabilityResourceTypes) { - if (version == null) { - resourceTypes.add(ResourceType.parseResourceType(rt)); - } else { - resourceTypes.add(ResourceType.parseResourceType(rt + "/" + version.toString())); - } - } - return new BundledRenderUnitCapabilityImpl( - resourceTypes, - (String) attributes.get(ServletResolverConstants.SLING_SERVLET_PATHS), - Arrays.asList( - PropertiesUtil.toStringArray(attributes.get(ServletResolverConstants.SLING_SERVLET_SELECTORS), new String[0])), - (String) attributes.get(ServletResolverConstants.SLING_SERVLET_EXTENSIONS), - (String) attributes.get(ServletResolverConstants.SLING_SERVLET_METHODS), - (String) attributes.get(BundledScriptTracker.AT_EXTENDS), - (String) attributes.get(BundledScriptTracker.AT_SCRIPT_ENGINE), - (String) attributes.get(BundledScriptTracker.AT_SCRIPT_EXTENSION) - ); - } -}
diff --git a/src/main/java/org/apache/sling/scripting/bundle/tracker/internal/BundledScriptContext.java b/src/main/java/org/apache/sling/scripting/bundle/tracker/internal/BundledScriptContext.java deleted file mode 100644 index 43c5fde..0000000 --- a/src/main/java/org/apache/sling/scripting/bundle/tracker/internal/BundledScriptContext.java +++ /dev/null
@@ -1,174 +0,0 @@ -/*~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ - ~ Licensed to the Apache Software Foundation (ASF) under one - ~ or more contributor license agreements. See the NOTICE file - ~ distributed with this work for additional information - ~ regarding copyright ownership. The ASF licenses this file - ~ to you 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 org.apache.sling.scripting.bundle.tracker.internal; - -import java.io.Reader; -import java.io.Writer; -import java.util.Arrays; -import java.util.List; - -import javax.script.Bindings; -import javax.script.SimpleScriptContext; - -import org.apache.sling.api.scripting.LazyBindings; -import org.apache.sling.api.scripting.SlingScriptConstants; - -class BundledScriptContext extends SimpleScriptContext { - - private static final Integer[] SCOPES = {SlingScriptConstants.SLING_SCOPE, GLOBAL_SCOPE, ENGINE_SCOPE}; - - private Bindings globalScope = new LazyBindings(); - private Bindings engineScope = new LazyBindings(); - private Bindings slingScope = new LazyBindings(); - - @Override - public void setBindings(final Bindings bindings, final int scope) { - if (bindings == null) { - throw new NullPointerException("None of the ScriptContext scopes accepts null bindings."); - } - switch (scope) { - case SlingScriptConstants.SLING_SCOPE: - this.slingScope = bindings; - break; - case 100: - this.engineScope = bindings; - break; - case 200: - this.globalScope = bindings; - break; - default: - throw new IllegalArgumentException("Invalid scope."); - } - } - - @Override - public Bindings getBindings(final int scope) { - switch (scope) { - case SlingScriptConstants.SLING_SCOPE: - return slingScope; - case 100: - return this.engineScope; - case 200: - return this.globalScope; - } - throw new IllegalArgumentException("Invalid scope."); - } - - @Override - public void setAttribute(final String name, final Object value, final int scope) { - if (name == null) { - throw new IllegalArgumentException("Name is null."); - } - final Bindings bindings = getBindings(scope); - if (bindings != null) { - bindings.put(name, value); - } - } - - @Override - public Object getAttribute(String name) { - if (name == null) { - throw new IllegalArgumentException("Name is null"); - } - for (final int scope : SCOPES) { - final Bindings bindings = getBindings(scope); - if (bindings != null) { - final Object o = bindings.get(name); - if (o != null) { - return o; - } - } - } - return null; - } - - @Override - public Object getAttribute(final String name, final int scope) { - if (name == null) { - throw new IllegalArgumentException("Name is null."); - } - final Bindings bindings = getBindings(scope); - if (bindings != null) { - return bindings.get(name); - } - return null; - } - - @Override - public Object removeAttribute(final String name, final int scope) { - if (name == null) { - throw new IllegalArgumentException("Name is null."); - } - final Bindings bindings = getBindings(scope); - if (bindings != null) { - return bindings.remove(name); - } - return null; - } - - @Override - public int getAttributesScope(String name) { - if (name == null) { - throw new IllegalArgumentException("Name is null."); - } - for (final int scope : SCOPES) { - if ((getBindings(scope) != null) && (getBindings(scope).containsKey(name))) { - return scope; - } - } - return -1; - } - - @Override - public List<Integer> getScopes() { - return Arrays.asList(SCOPES); - } - - @Override - public Writer getWriter() { - return writer; - } - - @Override - public Writer getErrorWriter() { - return errorWriter; - } - - @Override - public void setWriter(Writer writer) { - this.writer = writer; - } - - @Override - public void setErrorWriter(Writer writer) { - this.errorWriter = writer; - } - - @Override - public Reader getReader() { - return reader; - } - - @Override - public void setReader(Reader reader) { - this.reader = reader; - } - - -}
diff --git a/src/main/java/org/apache/sling/scripting/bundle/tracker/internal/BundledScriptFinder.java b/src/main/java/org/apache/sling/scripting/bundle/tracker/internal/BundledScriptFinder.java deleted file mode 100644 index f4f44e2..0000000 --- a/src/main/java/org/apache/sling/scripting/bundle/tracker/internal/BundledScriptFinder.java +++ /dev/null
@@ -1,132 +0,0 @@ -/*~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ - ~ Licensed to the Apache Software Foundation (ASF) under one - ~ or more contributor license agreements. See the NOTICE file - ~ distributed with this work for additional information - ~ regarding copyright ownership. The ASF licenses this file - ~ to you 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 org.apache.sling.scripting.bundle.tracker.internal; - -import java.net.URL; -import java.util.ArrayList; -import java.util.Arrays; -import java.util.Collections; -import java.util.List; -import java.util.Set; - -import org.apache.commons.lang3.StringUtils; -import org.apache.sling.commons.compiler.source.JavaEscapeHelper; -import org.apache.sling.scripting.bundle.tracker.BundledRenderUnitCapability; -import org.apache.sling.scripting.bundle.tracker.ResourceType; -import org.apache.sling.scripting.bundle.tracker.TypeProvider; -import org.jetbrains.annotations.NotNull; -import org.jetbrains.annotations.Nullable; -import org.osgi.framework.Bundle; -import org.osgi.service.component.annotations.Component; - -@Component( - service = BundledScriptFinder.class -) -public class BundledScriptFinder { - - private static final String NS_JAVAX_SCRIPT_CAPABILITY = "javax.script"; - private static final String SLASH = "/"; - private static final String DOT = "."; - - Executable getScript(Set<TypeProvider> providers, Set<TypeProvider> allProviders) { - for (TypeProvider provider : providers) { - BundledRenderUnitCapability capability = provider.getBundledRenderUnitCapability(); - for (String match : buildScriptMatches(capability.getResourceTypes(), - capability.getSelectors().toArray(new String[0]), capability.getMethod(), capability.getExtension())) { - String scriptExtension = capability.getScriptExtension(); - String scriptEngineName = capability.getScriptEngineName(); - if (StringUtils.isNotEmpty(scriptExtension) && StringUtils.isNotEmpty(scriptEngineName)) { - Executable executable = getExecutable(provider.getBundle(), match, scriptEngineName, scriptExtension, allProviders); - if (executable != null) { - return executable; - } - } - } - } - return null; - } - - Executable getScript(@NotNull Bundle bundle, @NotNull String path, @NotNull String scriptEngineName, - @NotNull Set<TypeProvider> providers) { - String className = JavaEscapeHelper.makeJavaPackage(path); - try { - Class<?> clazz = bundle.loadClass(className); - return new PrecompiledScript(providers, bundle, path, clazz, scriptEngineName); - } catch (ClassNotFoundException ignored) { - URL bundledScriptURL = bundle.getEntry(NS_JAVAX_SCRIPT_CAPABILITY + (path.startsWith("/") ? "" : SLASH) + path); - if (bundledScriptURL != null) { - return new Script(providers, bundle, path, bundledScriptURL, scriptEngineName); - } // do nothing here - } - - return null; - } - - @Nullable - private Executable getExecutable(@NotNull Bundle bundle, @NotNull String match, @NotNull String scriptEngineName, - @NotNull String scriptExtension, @NotNull Set<TypeProvider> providers) { - String path = match + DOT + scriptExtension; - return getScript(bundle, path, scriptEngineName, providers); - } - - private List<String> buildScriptMatches(Set<ResourceType> resourceTypes, String[] selectors, String method, String extension) { - List<String> matches = new ArrayList<>(); - for (ResourceType resourceType : resourceTypes) { - if (selectors.length > 0) { - for (int i = selectors.length - 1; i >= 0; i--) { - String base = - resourceType.getType() + - (StringUtils.isNotEmpty(resourceType.getVersion()) ? SLASH + resourceType.getVersion() + SLASH : - SLASH) + - String.join(SLASH, Arrays.copyOf(selectors, i + 1)); - if (StringUtils.isNotEmpty(extension)) { - if (StringUtils.isNotEmpty(method)) { - matches.add(base + DOT + extension + DOT + method); - } - matches.add(base + DOT + extension); - } - if (StringUtils.isNotEmpty(method)) { - matches.add(base + DOT + method); - } - matches.add(base); - } - } - String base = resourceType.getType() + - (StringUtils.isNotEmpty(resourceType.getVersion()) ? SLASH + resourceType.getVersion() : StringUtils.EMPTY); - - if (StringUtils.isNotEmpty(extension)) { - if (StringUtils.isNotEmpty(method)) { - matches.add(base + SLASH + resourceType.getResourceLabel() + DOT + extension + DOT + method); - } - matches.add(base + SLASH + resourceType.getResourceLabel() + DOT + extension); - } - if (StringUtils.isNotEmpty(method)) { - matches.add(base + SLASH + resourceType.getResourceLabel() + DOT + method); - } - matches.add(base + SLASH + resourceType.getResourceLabel()); - if (StringUtils.isNotEmpty(method)) { - matches.add(base + SLASH + method); - } - if (StringUtils.isNotEmpty(extension)) { - matches.add(base + SLASH + extension); - } - } - return Collections.unmodifiableList(matches); - } -}
diff --git a/src/main/java/org/apache/sling/scripting/bundle/tracker/internal/BundledScriptServlet.java b/src/main/java/org/apache/sling/scripting/bundle/tracker/internal/BundledScriptServlet.java deleted file mode 100644 index bfdb35e..0000000 --- a/src/main/java/org/apache/sling/scripting/bundle/tracker/internal/BundledScriptServlet.java +++ /dev/null
@@ -1,92 +0,0 @@ -/*~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ - ~ Licensed to the Apache Software Foundation (ASF) under one - ~ or more contributor license agreements. See the NOTICE file - ~ distributed with this work for additional information - ~ regarding copyright ownership. The ASF licenses this file - ~ to you 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 org.apache.sling.scripting.bundle.tracker.internal; - -import java.io.IOException; -import java.util.Collection; -import java.util.LinkedHashSet; -import java.util.stream.Collectors; - -import javax.script.ScriptException; -import javax.servlet.GenericServlet; -import javax.servlet.ServletException; -import javax.servlet.ServletRequest; -import javax.servlet.ServletResponse; - -import org.apache.sling.api.SlingConstants; -import org.apache.sling.api.SlingHttpServletRequest; -import org.apache.sling.api.SlingHttpServletResponse; -import org.apache.sling.scripting.bundle.tracker.TypeProvider; -import org.apache.sling.scripting.bundle.tracker.internal.request.RequestWrapper; -import org.apache.sling.scripting.bundle.tracker.internal.request.ResponseWrapper; -import org.jetbrains.annotations.NotNull; - -class BundledScriptServlet extends GenericServlet { - - private final ScriptContextProvider scriptContextProvider; - private final LinkedHashSet<TypeProvider> wiredTypeProviders; - private final Executable executable; - - - BundledScriptServlet(@NotNull ScriptContextProvider scriptContextProvider, - @NotNull LinkedHashSet<TypeProvider> wiredTypeProviders, - @NotNull Executable executable) { - this.scriptContextProvider = scriptContextProvider; - this.wiredTypeProviders = wiredTypeProviders; - this.executable = executable; - } - - @Override - public void service(ServletRequest req, ServletResponse res) throws ServletException, IOException { - if ((req instanceof SlingHttpServletRequest) && (res instanceof SlingHttpServletResponse)) { - SlingHttpServletRequest request = (SlingHttpServletRequest) req; - SlingHttpServletResponse response = (SlingHttpServletResponse) res; - - if (request.getAttribute(SlingConstants.ATTR_INCLUDE_SERVLET_PATH) == null) { - final String contentType = request.getResponseContentType(); - if (contentType != null) { - response.setContentType(contentType); - if (contentType.startsWith("text/")) { - response.setCharacterEncoding("UTF-8"); - } - } - } - - RequestWrapper requestWrapper = new RequestWrapper(request, - wiredTypeProviders.stream().map(typeProvider -> typeProvider.getBundledRenderUnitCapability().getResourceTypes() - ).flatMap(Collection::stream).collect(Collectors.toSet())); - ScriptContextProvider.ExecutableContext executableContext = scriptContextProvider - .prepareScriptContext(requestWrapper, new ResponseWrapper(response), executable); - try { - executableContext.eval(); - } catch (ScriptException se) { - Throwable cause = (se.getCause() == null) ? se : se.getCause(); - throw new ServletException(String.format("Failed executing script %s: %s", executable.getName(), se.getMessage()), cause); - } finally { - executableContext.clean(); - } - } else { - throw new ServletException("Not a Sling HTTP request/response"); - } - } - - public String toString() { - return getClass().getSimpleName() + "(" + executable.getName() + ")"; - } -}
diff --git a/src/main/java/org/apache/sling/scripting/bundle/tracker/internal/BundledScriptTracker.java b/src/main/java/org/apache/sling/scripting/bundle/tracker/internal/BundledScriptTracker.java deleted file mode 100644 index f23c9bd..0000000 --- a/src/main/java/org/apache/sling/scripting/bundle/tracker/internal/BundledScriptTracker.java +++ /dev/null
@@ -1,429 +0,0 @@ -/*~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ - ~ Licensed to the Apache Software Foundation (ASF) under one - ~ or more contributor license agreements. See the NOTICE file - ~ distributed with this work for additional information - ~ regarding copyright ownership. The ASF licenses this file - ~ to you 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 org.apache.sling.scripting.bundle.tracker.internal; - -import java.io.IOException; -import java.util.ArrayList; -import java.util.Arrays; -import java.util.Collection; -import java.util.Collections; -import java.util.HashMap; -import java.util.HashSet; -import java.util.Hashtable; -import java.util.LinkedHashSet; -import java.util.List; -import java.util.Map; -import java.util.Optional; -import java.util.Set; -import java.util.function.Supplier; -import java.util.stream.Collectors; -import java.util.stream.Stream; - -import javax.servlet.GenericServlet; -import javax.servlet.RequestDispatcher; -import javax.servlet.Servlet; -import javax.servlet.ServletException; -import javax.servlet.ServletRequest; -import javax.servlet.ServletResponse; -import javax.servlet.http.HttpServletResponse; - -import org.apache.commons.lang3.StringUtils; -import org.apache.sling.api.SlingConstants; -import org.apache.sling.api.SlingHttpServletRequest; -import org.apache.sling.api.SlingHttpServletResponse; -import org.apache.sling.api.request.RequestDispatcherOptions; -import org.apache.sling.api.servlets.ServletResolverConstants; -import org.apache.sling.commons.osgi.PropertiesUtil; -import org.apache.sling.scripting.bundle.tracker.ResourceType; -import org.apache.sling.scripting.bundle.tracker.BundledRenderUnitCapability; -import org.apache.sling.scripting.bundle.tracker.TypeProvider; -import org.jetbrains.annotations.NotNull; -import org.osgi.annotation.bundle.Capability; -import org.osgi.framework.Bundle; -import org.osgi.framework.BundleContext; -import org.osgi.framework.BundleEvent; -import org.osgi.framework.Constants; -import org.osgi.framework.ServiceReference; -import org.osgi.framework.ServiceRegistration; -import org.osgi.framework.Version; -import org.osgi.framework.wiring.BundleCapability; -import org.osgi.framework.wiring.BundleRevision; -import org.osgi.framework.wiring.BundleWire; -import org.osgi.framework.wiring.BundleWiring; -import org.osgi.namespace.extender.ExtenderNamespace; -import org.osgi.service.component.annotations.Activate; -import org.osgi.service.component.annotations.Component; -import org.osgi.service.component.annotations.Deactivate; -import org.osgi.service.component.annotations.Reference; -import org.osgi.util.tracker.BundleTracker; -import org.osgi.util.tracker.BundleTrackerCustomizer; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -@Component( - service = {} -) -@Capability(namespace = ExtenderNamespace.EXTENDER_NAMESPACE, - name = BundledScriptTracker.NS_SLING_SCRIPTING_EXTENDER, - version = "1.0.0") -public class BundledScriptTracker implements BundleTrackerCustomizer<List<ServiceRegistration<Servlet>>> { - static final String NS_SLING_SCRIPTING_EXTENDER = "sling.scripting"; - - private static final Logger LOGGER = LoggerFactory.getLogger(BundledScriptTracker.class); - private static final String REGISTERING_BUNDLE = "org.apache.sling.scripting.bundle.tracker.internal.BundledScriptTracker.registering_bundle"; - public static final String NS_SLING_SERVLET = "sling.servlet"; - public static final String AT_VERSION = "version"; - public static final String AT_SCRIPT_ENGINE = "scriptEngine"; - public static final String AT_SCRIPT_EXTENSION = "scriptExtension"; - public static final String AT_EXTENDS = "extends"; - - @Reference - private BundledScriptFinder bundledScriptFinder; - - @Reference - private ScriptContextProvider scriptContextProvider; - - - private volatile BundleContext m_context; - private volatile BundleTracker<List<ServiceRegistration<Servlet>>> m_tracker; - private volatile Map<Set<String>, ServiceRegistration<Servlet>> m_dispatchers = new HashMap<>(); - - @Activate - protected void activate(BundleContext context) { - m_context = context; - m_tracker = new BundleTracker<>(context, Bundle.ACTIVE, this); - m_tracker.open(); - } - - @Deactivate - protected void deactivate() { - m_tracker.close(); - } - - @Override - public List<ServiceRegistration<Servlet>> addingBundle(Bundle bundle, BundleEvent event) { - BundleWiring bundleWiring = bundle.adapt(BundleWiring.class); - if (bundleWiring.getRequiredWires("osgi.extender").stream().map(BundleWire::getProvider).map(BundleRevision::getBundle) - .anyMatch(m_context.getBundle()::equals)) { - LOGGER.debug("Inspecting bundle {} for {} capability.", bundle.getSymbolicName(), NS_SLING_SERVLET); - List<BundleCapability> capabilities = bundleWiring.getCapabilities(NS_SLING_SERVLET); - Set<TypeProvider> requiresChain = collectRequiresChain(bundleWiring); - if (!capabilities.isEmpty()) { - List<ServiceRegistration<Servlet>> serviceRegistrations = capabilities.stream().flatMap(cap -> - { - Hashtable<String, Object> properties = new Hashtable<>(); - properties.put(ServletResolverConstants.SLING_SERVLET_NAME, BundledScriptServlet.class.getName()); - properties.put(Constants.SERVICE_DESCRIPTION, BundledScriptServlet.class.getName() + cap.getAttributes()); - BundledRenderUnitCapability bundledRenderUnitCapability = BundledRenderUnitCapabilityImpl.fromBundleCapability(cap); - Executable executable = null; - TypeProvider baseTypeProvider = new TypeProviderImpl(bundledRenderUnitCapability, bundle); - LinkedHashSet<TypeProvider> inheritanceChain = new LinkedHashSet<>(); - inheritanceChain.add(baseTypeProvider); - if (!bundledRenderUnitCapability.getResourceTypes().isEmpty()) { - String[] resourceTypesRegistrationValue = new String[bundledRenderUnitCapability.getResourceTypes().size()]; - int rtIndex = 0; - for (ResourceType resourceType : bundledRenderUnitCapability.getResourceTypes()) { - resourceTypesRegistrationValue[rtIndex++] = resourceType.toString(); - } - properties.put(ServletResolverConstants.SLING_SERVLET_RESOURCE_TYPES, resourceTypesRegistrationValue); - - String extension = bundledRenderUnitCapability.getExtension(); - if (StringUtils.isEmpty(extension)) { - extension = "html"; - } - properties.put(ServletResolverConstants.SLING_SERVLET_EXTENSIONS, extension); - - if (!bundledRenderUnitCapability.getSelectors().isEmpty()) { - properties.put(ServletResolverConstants.SLING_SERVLET_SELECTORS, bundledRenderUnitCapability.getSelectors().toArray()); - } - - if (StringUtils.isNotEmpty(bundledRenderUnitCapability.getMethod())) { - properties.put(ServletResolverConstants.SLING_SERVLET_METHODS, bundledRenderUnitCapability.getMethod()); - } - - String extendedResourceTypeString = bundledRenderUnitCapability.getExtendedResourceType(); - if (StringUtils.isNotEmpty(extendedResourceTypeString)) { - collectInheritanceChain(inheritanceChain, bundleWiring, extendedResourceTypeString); - inheritanceChain.stream().filter(typeProvider -> typeProvider.getBundledRenderUnitCapability().getResourceTypes().stream() - .anyMatch(resourceType -> resourceType.getType().equals(extendedResourceTypeString))).findFirst() - .ifPresent(typeProvider -> { - for (ResourceType type : typeProvider.getBundledRenderUnitCapability().getResourceTypes()) { - if (type.getType().equals(extendedResourceTypeString)) { - properties.put(ServletResolverConstants.SLING_SERVLET_RESOURCE_SUPER_TYPE, type.toString()); - } - } - }); - } - Set<TypeProvider> aggregate = - Stream.concat(inheritanceChain.stream(), requiresChain.stream()).collect(Collectors.toCollection(LinkedHashSet::new)); - executable = bundledScriptFinder.getScript(inheritanceChain, aggregate); - } else if (StringUtils.isNotEmpty(bundledRenderUnitCapability.getPath()) && StringUtils.isNotEmpty( - bundledRenderUnitCapability.getScriptEngineName())) { - Set<TypeProvider> aggregate = - Stream.concat(inheritanceChain.stream(), requiresChain.stream()).collect(Collectors.toCollection(LinkedHashSet::new)); - executable = bundledScriptFinder.getScript(baseTypeProvider.getBundle(), - bundledRenderUnitCapability.getPath(), bundledRenderUnitCapability.getScriptEngineName(), aggregate); - } - List<ServiceRegistration<Servlet>> regs = new ArrayList<>(); - - if (executable != null) { - Executable finalExecutable = executable; - bundledRenderUnitCapability.getResourceTypes().forEach(resourceType -> { - if (finalExecutable.getPath().startsWith(resourceType.toString() + "/")) { - properties.put(ServletResolverConstants.SLING_SERVLET_PATHS, finalExecutable.getPath()); - } - }); - if (executable.getPath().equals(bundledRenderUnitCapability.getPath())) { - properties.put(ServletResolverConstants.SLING_SERVLET_PATHS, executable.getPath()); - } - properties.put(BundledHooks.class.getName(), "true"); - regs.add( - bundle.getBundleContext().registerService( - Servlet.class, - new BundledScriptServlet(scriptContextProvider, inheritanceChain, executable), - properties - ) - ); - } else { - LOGGER.error(String.format("Unable to locate an executable for capability %s.", cap)); - } - - return regs.stream(); - }).collect(Collectors.toList()); - refreshDispatcher(serviceRegistrations); - return serviceRegistrations; - } else { - return Collections.emptyList(); - } - } else { - return Collections.emptyList(); - } - } - - private void refreshDispatcher(List<ServiceRegistration<Servlet>> regs) { - Map<Set<String>, ServiceRegistration<Servlet>> dispatchers = new HashMap<>(); - Stream.concat(m_tracker.getTracked().values().stream(), Stream.of(regs)).flatMap(List::stream) - .filter(ref -> getResourceTypeVersion(ref.getReference()) != null) - .map(this::toProperties) - .collect(Collectors.groupingBy(BundledScriptTracker::getResourceTypes)).forEach((rt, propList) -> { - Hashtable<String, Object> properties = new Hashtable<>(); - properties.put(ServletResolverConstants.SLING_SERVLET_NAME, DispatcherServlet.class.getName()); - properties.put(ServletResolverConstants.SLING_SERVLET_RESOURCE_TYPES, rt.toArray()); - Set<String> methods = propList.stream() - .map(props -> props.getOrDefault(ServletResolverConstants.SLING_SERVLET_METHODS, new String[]{"GET", "HEAD"})) - .map(PropertiesUtil::toStringArray).map(Arrays::asList).flatMap(List::stream).collect(Collectors.toSet()); - Set<String> extensions = propList.stream().map(props -> props.getOrDefault(ServletResolverConstants - .SLING_SERVLET_EXTENSIONS, new String[]{"html"})).map(PropertiesUtil::toStringArray).map(Arrays::asList).flatMap - (List::stream).collect(Collectors.toSet()); - properties.put(ServletResolverConstants.SLING_SERVLET_EXTENSIONS, extensions.toArray(new String[0])); - if (!methods.equals(new HashSet<>(Arrays.asList("GET", "HEAD")))) { - properties.put(ServletResolverConstants.SLING_SERVLET_METHODS, methods.toArray(new String[0])); - } - ServiceRegistration<Servlet> reg = m_dispatchers.remove(rt); - if (reg == null) { - Optional<BundleContext> registeringBundle = propList.stream().map(props -> { - Bundle bundle = (Bundle) props.get(REGISTERING_BUNDLE); - if (bundle != null) { - return bundle.getBundleContext(); - } - return null; - }).findFirst(); - properties.put(Constants.SERVICE_DESCRIPTION, - DispatcherServlet.class.getName() + "{" + ServletResolverConstants.SLING_SERVLET_RESOURCE_TYPES + - "=" + rt + "; " + - ServletResolverConstants.SLING_SERVLET_EXTENSIONS + "=" + extensions + "; " + - ServletResolverConstants.SLING_SERVLET_METHODS + "=" + methods + "}"); - properties.put(BundledHooks.class.getName(), "true"); - - reg = registeringBundle.orElse(m_context).registerService(Servlet.class, new DispatcherServlet(rt), properties); - } else { - if (!new HashSet<>(Arrays.asList(PropertiesUtil - .toStringArray(reg.getReference().getProperty(ServletResolverConstants.SLING_SERVLET_METHODS), new String[0]))) - .equals(methods)) { - reg.setProperties(properties); - } - } - dispatchers.put(rt, reg); - }); - m_dispatchers.values().forEach(ServiceRegistration::unregister); - m_dispatchers = dispatchers; - } - - private Hashtable<String, Object> toProperties(ServiceRegistration<?> reg) { - Hashtable<String, Object> result = new Hashtable<>(); - ServiceReference<?> ref = reg.getReference(); - - set(ServletResolverConstants.SLING_SERVLET_RESOURCE_TYPES, ref, result); - set(ServletResolverConstants.SLING_SERVLET_EXTENSIONS, ref, result); - set(ServletResolverConstants.SLING_SERVLET_SELECTORS, ref, result); - set(ServletResolverConstants.SLING_SERVLET_METHODS, ref, result); - result.put(REGISTERING_BUNDLE, reg.getReference().getBundle()); - - return result; - } - - private void set(String key, ServiceReference<?> ref, Hashtable<String, Object> props) { - Object value = ref.getProperty(key); - if (value != null) { - props.put(key, value); - } - } - - @Override - public void modifiedBundle(Bundle bundle, BundleEvent event, List<ServiceRegistration<Servlet>> regs) { - LOGGER.warn("Unexpected modified event {} for bundle {}.", event.toString(), bundle.toString()); - } - - @Override - public void removedBundle(Bundle bundle, BundleEvent event, List<ServiceRegistration<Servlet>> regs) { - LOGGER.debug("Bundle {} removed", bundle.getSymbolicName()); - regs.forEach(ServiceRegistration::unregister); - refreshDispatcher(Collections.emptyList()); - } - - private class DispatcherServlet extends GenericServlet { - private final Set<String> m_rt; - - DispatcherServlet(Set<String> rt) { - m_rt = rt; - } - - @Override - public void service(ServletRequest req, ServletResponse res) throws ServletException, IOException { - - SlingHttpServletRequest slingRequest = (SlingHttpServletRequest) req; - - Optional<ServiceRegistration<Servlet>> target = m_tracker.getTracked().values().stream().flatMap(List::stream) - .filter( - reg -> !reg.getReference().getBundle().equals(m_context.getBundle()) - ) - .filter(reg -> getResourceTypeVersion(reg.getReference()) != null) - .filter(reg -> - { - Hashtable<String, Object> props = toProperties(reg); - return getResourceTypes(props).equals(m_rt) && - Arrays.asList(PropertiesUtil - .toStringArray(props.get(ServletResolverConstants.SLING_SERVLET_METHODS), - new String[]{"GET", "HEAD"})) - .contains(slingRequest.getMethod()) && - Arrays.asList(PropertiesUtil - .toStringArray(props.get(ServletResolverConstants.SLING_SERVLET_EXTENSIONS), new String[]{"html"})) - .contains(slingRequest.getRequestPathInfo().getExtension() == null ? "html" : - slingRequest.getRequestPathInfo().getExtension()); - }).min((left, right) -> - { - boolean la = Arrays.asList(PropertiesUtil - .toStringArray(toProperties(left).get(ServletResolverConstants.SLING_SERVLET_SELECTORS), new String[0])) - .containsAll(Arrays.asList(slingRequest.getRequestPathInfo().getSelectors())); - boolean ra = Arrays.asList(PropertiesUtil - .toStringArray(toProperties(right).get(ServletResolverConstants.SLING_SERVLET_SELECTORS), new String[0])) - .containsAll(Arrays.asList(slingRequest.getRequestPathInfo().getSelectors())); - if ((la && ra) || (!la && !ra)) { - return new Version(getResourceTypeVersion(right.getReference())) - .compareTo(new Version(getResourceTypeVersion(left.getReference()))); - } else if (la) { - return -1; - } else { - return 1; - } - - }); - - if (target.isPresent()) { - String[] targetRT = - PropertiesUtil.toStringArray(target.get().getReference().getProperty(ServletResolverConstants.SLING_SERVLET_RESOURCE_TYPES)); - if (targetRT == null || targetRT.length == 0) { - ((SlingHttpServletResponse) res).sendError(HttpServletResponse.SC_NOT_FOUND); - } else { - String rt = targetRT[0]; - RequestDispatcherOptions options = new RequestDispatcherOptions(); - options.setForceResourceType(rt); - - RequestDispatcher dispatcher = slingRequest.getRequestDispatcher(slingRequest.getResource(), options); - if (dispatcher != null) { - if (slingRequest.getAttribute(SlingConstants.ATTR_INCLUDE_SERVLET_PATH) == null) { - final String contentType = slingRequest.getResponseContentType(); - if (contentType != null) { - res.setContentType(contentType); - if (contentType.startsWith("text/")) { - res.setCharacterEncoding("UTF-8"); - } - } - } - dispatcher.include(req, res); - } else { - ((SlingHttpServletResponse) res).sendError(HttpServletResponse.SC_NOT_FOUND); - } - } - } else { - ((SlingHttpServletResponse) res).sendError(HttpServletResponse.SC_NOT_FOUND); - } - } - } - - private static String getResourceTypeVersion(ServiceReference<?> ref) { - String[] values = PropertiesUtil.toStringArray(ref.getProperty(ServletResolverConstants.SLING_SERVLET_RESOURCE_TYPES)); - if (values != null) { - String resourceTypeValue = values[0]; - ResourceType resourceType = ResourceType.parseResourceType(resourceTypeValue); - return resourceType.getVersion(); - } - return null; - } - - private static Set<String> getResourceTypes(Hashtable<String, Object> props) { - Set<String> resourceTypes = new HashSet<>(); - String[] values = PropertiesUtil.toStringArray(props.get(ServletResolverConstants.SLING_SERVLET_RESOURCE_TYPES)); - for (String resourceTypeValue : values) { - resourceTypes.add(ResourceType.parseResourceType(resourceTypeValue).getType()); - } - return resourceTypes; - } - - private void collectInheritanceChain(@NotNull Set<TypeProvider> providers, @NotNull BundleWiring wiring, - @NotNull String extendedResourceType) { - for (BundleWire wire : wiring.getRequiredWires(NS_SLING_SERVLET)) { - BundledRenderUnitCapability wiredCapability = BundledRenderUnitCapabilityImpl.fromBundleCapability(wire.getCapability()); - if (wiredCapability.getSelectors().isEmpty()) { - for (ResourceType resourceType : wiredCapability.getResourceTypes()) { - if (extendedResourceType.equals(resourceType.getType())) { - Bundle providingBundle = wire.getProvider().getBundle(); - providers.add(new TypeProviderImpl(wiredCapability, providingBundle)); - String wiredExtends = wiredCapability.getExtendedResourceType(); - if (StringUtils.isNotEmpty(wiredExtends)) { - collectInheritanceChain(providers, wire.getProviderWiring(), wiredExtends); - } - } - } - } - } - } - - private Set<TypeProvider> collectRequiresChain(@NotNull BundleWiring wiring) { - Set<TypeProvider> requiresChain = new LinkedHashSet<>(); - for (BundleWire wire : wiring.getRequiredWires(NS_SLING_SERVLET)) { - BundledRenderUnitCapability wiredCapability = BundledRenderUnitCapabilityImpl.fromBundleCapability(wire.getCapability()); - if (wiredCapability.getSelectors().isEmpty()) { - Bundle providingBundle = wire.getProvider().getBundle(); - requiresChain.add(new TypeProviderImpl(wiredCapability, providingBundle)); - } - } - return requiresChain; - } -}
diff --git a/src/main/java/org/apache/sling/scripting/bundle/tracker/internal/Executable.java b/src/main/java/org/apache/sling/scripting/bundle/tracker/internal/Executable.java deleted file mode 100644 index 8797103..0000000 --- a/src/main/java/org/apache/sling/scripting/bundle/tracker/internal/Executable.java +++ /dev/null
@@ -1,60 +0,0 @@ -/*~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ - ~ Licensed to the Apache Software Foundation (ASF) under one - ~ or more contributor license agreements. See the NOTICE file - ~ distributed with this work for additional information - ~ regarding copyright ownership. The ASF licenses this file - ~ to you 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 org.apache.sling.scripting.bundle.tracker.internal; - -import javax.script.ScriptContext; -import javax.script.ScriptEngine; -import javax.script.ScriptException; - -import org.apache.sling.scripting.bundle.tracker.BundledRenderUnit; -import org.jetbrains.annotations.NotNull; - -interface Executable extends BundledRenderUnit { - - /** - * Releases all acquired dependencies which were retrieved through {@link #getService(String)} or {@link #getServices(String, String)}. - */ - void releaseDependencies(); - - /** - * Returns the path of this executable in the resource type hierarchy. The path can be relative to the search paths or absolute. - * - * @return the path of this executable in the resource type hierarchy - */ - @NotNull - String getPath(); - - /** - * Returns the short name of the {@link ScriptEngine} with which {@code this Executable} can be evaluated. - * - * @return the short name of the script engine - * @see #eval(ScriptEngine, ScriptContext) - */ - @NotNull String getScriptEngineName(); - - /** - * Provided a {@link ScriptContext}, this method will execute / evaluate the wrapped script or precompiled script. - * - * @param scriptEngine a suitable script engine; see {@link #getScriptEngineName()} in order to see what {@link ScriptEngine} - * implementation is expected - * @param context the {@link ScriptContext} - * @throws ScriptException if the execution leads to an error - */ - void eval(@NotNull ScriptEngine scriptEngine, @NotNull ScriptContext context) throws ScriptException; -}
diff --git a/src/main/java/org/apache/sling/scripting/bundle/tracker/internal/LogWriter.java b/src/main/java/org/apache/sling/scripting/bundle/tracker/internal/LogWriter.java deleted file mode 100644 index 4988a2f..0000000 --- a/src/main/java/org/apache/sling/scripting/bundle/tracker/internal/LogWriter.java +++ /dev/null
@@ -1,126 +0,0 @@ -/*~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ - ~ Licensed to the Apache Software Foundation (ASF) under one - ~ or more contributor license agreements. See the NOTICE file - ~ distributed with this work for additional information - ~ regarding copyright ownership. The ASF licenses this file - ~ to you 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 org.apache.sling.scripting.bundle.tracker.internal; - -import java.io.Writer; - -import org.slf4j.Logger; - -class LogWriter extends Writer { - - /** - * The logger to which the error messages are written - */ - final private Logger logger; - - /** - * The internal buffer to gather message data until being flushed or a CR or - * LF is encountered in the message data. - */ - final private StringBuilder lineBuffer; - - /** - * Creates a writer based on the given logger. - * - * @param logger the logger - */ - LogWriter(Logger logger) { - this.logger = logger; - this.lineBuffer = new StringBuilder(); - } - - /** - * Writes the character to the internal buffer unless the character is a CR - * or LF in which case the buffer is written to the logger as an error - * message. - */ - @Override - public void write(int c) { - if (c == '\n' || c == '\r') { - flush(); - } else { - synchronized (lineBuffer) { - lineBuffer.append((char) c); - } - } - } - - /** - * Writes the indicated characters to the internal buffer, flushing the - * buffer on any occurrence of a CR of LF. - */ - @Override - public void write(char[] cbuf, int off, int len) { - int i = off; - for (int n = 0; n < len; n++, i++) { - char c = cbuf[i]; - - // if CR/LF flush the line - if (c == '\n' || c == '\r') { - - // append upto the CR/LF - int subLen = i - off; - if (subLen > 0) { - synchronized (lineBuffer) { - lineBuffer.append(cbuf, off, subLen); - } - } - - // and flush - flush(); - - // new offset is after the CR/LF - off = i + 1; - } - } - - // remaining data in the buffer is just appended - if (off < i) { - synchronized (lineBuffer) { - lineBuffer.append(cbuf, off, i - off); - } - } - } - - /** - * Writes any data contained in the buffer to the logger as an error message. - */ - @Override - public void flush() { - - String message; - synchronized (lineBuffer) { - if (lineBuffer.length() == 0) { - return; - } - message = lineBuffer.toString(); - lineBuffer.setLength(0); - } - - logger.error(message); - } - - /** - * Just calls {@link #flush()} - */ - @Override - public void close() { - flush(); - } -}
diff --git a/src/main/java/org/apache/sling/scripting/bundle/tracker/internal/PrecompiledScript.java b/src/main/java/org/apache/sling/scripting/bundle/tracker/internal/PrecompiledScript.java deleted file mode 100644 index 980c640..0000000 --- a/src/main/java/org/apache/sling/scripting/bundle/tracker/internal/PrecompiledScript.java +++ /dev/null
@@ -1,75 +0,0 @@ -/*~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ - ~ Licensed to the Apache Software Foundation (ASF) under one - ~ or more contributor license agreements. See the NOTICE file - ~ distributed with this work for additional information - ~ regarding copyright ownership. The ASF licenses this file - ~ to you 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 org.apache.sling.scripting.bundle.tracker.internal; - -import java.io.StringReader; -import java.util.Set; - -import javax.script.ScriptContext; -import javax.script.ScriptEngine; -import javax.script.ScriptException; - -import org.apache.commons.lang3.StringUtils; -import org.apache.sling.scripting.bundle.tracker.TypeProvider; -import org.jetbrains.annotations.NotNull; -import org.osgi.framework.Bundle; - -class PrecompiledScript extends AbstractBundledRenderUnit { - - private static final StringReader EMPTY_READER = new StringReader(StringUtils.EMPTY); - private final Class<?> clazz; - private volatile Object instance; - - PrecompiledScript(@NotNull Set<TypeProvider> providers, @NotNull Bundle bundle, @NotNull String path, @NotNull Class<?> clazz, - @NotNull String scriptEngineName) { - super(providers, bundle, path, scriptEngineName); - this.clazz = clazz; - } - - @Override - @NotNull - public String getName() { - return clazz.getName(); - } - - @Override - public void eval(@NotNull ScriptEngine scriptEngine, @NotNull ScriptContext context) throws ScriptException { - scriptEngine.eval(EMPTY_READER, context); - } - - @Override - public @NotNull Object getUnit() { - Object localInstance = instance; - if (localInstance == null) { - synchronized (this) { - localInstance = instance; - if (localInstance == null) { - try { - localInstance = clazz.getDeclaredConstructor().newInstance(); - instance = localInstance; - } catch (Exception e) { - throw new IllegalStateException("Cannot instantiate class " + clazz.getName(), e); - } - } - } - } - return localInstance; - } - -}
diff --git a/src/main/java/org/apache/sling/scripting/bundle/tracker/internal/ProtectedBindings.java b/src/main/java/org/apache/sling/scripting/bundle/tracker/internal/ProtectedBindings.java deleted file mode 100644 index 3376b48..0000000 --- a/src/main/java/org/apache/sling/scripting/bundle/tracker/internal/ProtectedBindings.java +++ /dev/null
@@ -1,147 +0,0 @@ -/*~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ - ~ Licensed to the Apache Software Foundation (ASF) under one - ~ or more contributor license agreements. See the NOTICE file - ~ distributed with this work for additional information - ~ regarding copyright ownership. The ASF licenses this file - ~ to you 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 org.apache.sling.scripting.bundle.tracker.internal; - -import java.util.Collection; -import java.util.Collections; -import java.util.Map; -import java.util.Set; - -import javax.script.Bindings; - -class ProtectedBindings implements Bindings { - - private final Bindings wrapped; - private final Set<String> protectedKeys; - - ProtectedBindings(Bindings wrapped, Set<String> protectedKeys) { - this.wrapped = wrapped; - this.protectedKeys = protectedKeys; - } - - /** - * {@inheritDoc} - * - * @throws IllegalArgumentException if the key is protected - */ - public Object put(String key, Object value) { - if (protectedKeys.contains(key)) { - throw new IllegalArgumentException(String.format("Key %s is protected.", key)); - } - return wrapped.put(key, value); - } - - /** - * {@inheritDoc} - */ - public void putAll(Map<? extends String, ?> toMerge) { - for (Map.Entry<? extends String, ?> entry : toMerge.entrySet()) { - if (!protectedKeys.contains(entry.getKey())) { - wrapped.put(entry.getKey(), entry.getValue()); - } else { - throw new IllegalArgumentException(String.format("Key %s is protected.", entry.getKey())); - } - } - } - - /** - * {@inheritDoc} - * - * @throws IllegalArgumentException if the key is protected - */ - public Object remove(Object key) { - if (protectedKeys.contains(key)) { - throw new IllegalArgumentException(String.format("Key %s is protected.", key)); - } - return wrapped.remove(key); - } - - /** - * The clear operation is not supported. - */ - public void clear() { - throw new UnsupportedOperationException("ProtectedBindings does not support clear()"); - } - - /** - * {@inheritDoc} - */ - public boolean containsValue(Object value) { - return wrapped.containsValue(value); - } - - /** - * Returns a Set view of the mappings contains in this map. The Set is - * unmodifiable. - * - * @return an unmodifiable Set view of the map - */ - public Set<Entry<String, Object>> entrySet() { - return Collections.unmodifiableSet(wrapped.entrySet()); - } - - /** - * {@inheritDoc} - */ - public boolean isEmpty() { - return wrapped.isEmpty(); - } - - /** - * Returns a Set view of the keys contained in this map. The Set is - * unmodifiable. - * - * @return an unmodifiable Set view of the map's keys - */ - public Set<String> keySet() { - return Collections.unmodifiableSet(wrapped.keySet()); - } - - /** - * {@inheritDoc} - */ - public int size() { - return wrapped.size(); - } - - /** - * Returns a Collection view of the values contained in this map. The - * Collection is unmodifiable. - * - * @return an unmodifiable Collection view of the map's values - */ - public Collection<Object> values() { - return Collections.unmodifiableCollection(wrapped.values()); - } - - /** - * {@inheritDoc} - */ - public boolean containsKey(Object key) { - return wrapped.containsKey(key); - } - - /** - * {@inheritDoc} - */ - public Object get(Object key) { - return wrapped.get(key); - } - -}
diff --git a/src/main/java/org/apache/sling/scripting/bundle/tracker/internal/Script.java b/src/main/java/org/apache/sling/scripting/bundle/tracker/internal/Script.java deleted file mode 100644 index bd274b3..0000000 --- a/src/main/java/org/apache/sling/scripting/bundle/tracker/internal/Script.java +++ /dev/null
@@ -1,101 +0,0 @@ -/*~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ - ~ Licensed to the Apache Software Foundation (ASF) under one - ~ or more contributor license agreements. See the NOTICE file - ~ distributed with this work for additional information - ~ regarding copyright ownership. The ASF licenses this file - ~ to you 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 org.apache.sling.scripting.bundle.tracker.internal; - -import java.io.IOException; -import java.io.StringReader; -import java.net.URL; -import java.nio.charset.StandardCharsets; -import java.util.Set; -import java.util.concurrent.locks.Lock; -import java.util.concurrent.locks.ReentrantLock; - -import javax.script.Compilable; -import javax.script.CompiledScript; -import javax.script.ScriptContext; -import javax.script.ScriptEngine; -import javax.script.ScriptException; - -import org.apache.commons.io.IOUtils; -import org.apache.sling.scripting.bundle.tracker.TypeProvider; -import org.apache.sling.scripting.core.ScriptNameAwareReader; -import org.jetbrains.annotations.NotNull; -import org.osgi.framework.Bundle; - -class Script extends AbstractBundledRenderUnit { - - private final URL url; - private String sourceCode; - private CompiledScript compiledScript = null; - private Lock compilationLock = new ReentrantLock(); - private Lock readLock = new ReentrantLock(); - - - Script(@NotNull Set<TypeProvider> providers, @NotNull Bundle bundle, @NotNull String path, @NotNull URL url, - @NotNull String scriptEngineName) { - super(providers, bundle, path, scriptEngineName); - this.url = url; - } - - private String getSourceCode() throws IOException { - if (sourceCode == null) { - readLock.lock(); - try { - if (sourceCode == null) { - sourceCode = IOUtils.toString(url.openStream(), StandardCharsets.UTF_8); - } - } finally { - readLock.unlock(); - } - } - return sourceCode; - } - - @NotNull - @Override - public String getName() { - return url.getPath(); - } - - @Override - public void eval(@NotNull ScriptEngine scriptEngine, @NotNull ScriptContext context) throws ScriptException { - try { - if (scriptEngine instanceof Compilable && - (compiledScript == null || !scriptEngine.getFactory().equals(compiledScript.getEngine().getFactory()))) { - compilationLock.lock(); - try { - if (compiledScript == null || !scriptEngine.getFactory().equals(compiledScript.getEngine().getFactory())) { - compiledScript = - ((Compilable) scriptEngine) - .compile(new ScriptNameAwareReader(new StringReader(getSourceCode()), getName())); - } - } finally { - compilationLock.unlock(); - } - } - if (compiledScript != null) { - compiledScript.eval(context); - } else { - scriptEngine.eval(getSourceCode(), context); - } - } catch (IOException e) { - throw new ScriptException(e); - } - } -}
diff --git a/src/main/java/org/apache/sling/scripting/bundle/tracker/internal/ScriptContextProvider.java b/src/main/java/org/apache/sling/scripting/bundle/tracker/internal/ScriptContextProvider.java deleted file mode 100644 index caee87e..0000000 --- a/src/main/java/org/apache/sling/scripting/bundle/tracker/internal/ScriptContextProvider.java +++ /dev/null
@@ -1,146 +0,0 @@ -/*~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ - ~ Licensed to the Apache Software Foundation (ASF) under one - ~ or more contributor license agreements. See the NOTICE file - ~ distributed with this work for additional information - ~ regarding copyright ownership. The ASF licenses this file - ~ to you 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 org.apache.sling.scripting.bundle.tracker.internal; - -import java.io.IOException; -import java.util.Arrays; -import java.util.Collections; -import java.util.HashMap; -import java.util.HashSet; -import java.util.Map; -import java.util.Set; - -import javax.script.Bindings; -import javax.script.ScriptContext; -import javax.script.ScriptEngine; -import javax.script.ScriptEngineManager; -import javax.script.ScriptException; - -import org.apache.sling.api.SlingHttpServletRequest; -import org.apache.sling.api.SlingHttpServletResponse; -import org.apache.sling.api.scripting.LazyBindings; -import org.apache.sling.api.scripting.SlingBindings; -import org.apache.sling.api.scripting.SlingScriptConstants; -import org.apache.sling.scripting.api.BindingsValuesProvider; -import org.apache.sling.scripting.api.BindingsValuesProvidersByContext; -import org.apache.sling.scripting.api.resource.ScriptingResourceResolverProvider; -import org.apache.sling.scripting.bundle.tracker.BundledRenderUnit; -import org.apache.sling.scripting.core.ScriptHelper; -import org.osgi.service.component.annotations.Component; -import org.osgi.service.component.annotations.Reference; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -@Component( - service = ScriptContextProvider.class -) -public class ScriptContextProvider { - - private static final Set<String> PROTECTED_BINDINGS = Collections.unmodifiableSet(new HashSet<>(Arrays.asList( - SlingBindings.REQUEST, - SlingBindings.RESPONSE, - SlingBindings.READER, - SlingBindings.RESOURCE, - SlingBindings.RESOLVER, - SlingBindings.OUT, - SlingBindings.LOG, - SlingBindings.SLING, - ScriptEngine.FILENAME, - BundledRenderUnit.VARIABLE - ))); - - @Reference - private BindingsValuesProvidersByContext bvpTracker; - - @Reference - private ScriptEngineManager scriptEngineManager; - - @Reference - private ScriptingResourceResolverProvider scriptingResourceResolverProvider; - - ExecutableContext prepareScriptContext(SlingHttpServletRequest request, SlingHttpServletResponse response, Executable executable) - throws IOException { - ScriptEngine scriptEngine = scriptEngineManager.getEngineByName(executable.getScriptEngineName()); - if (scriptEngine == null) { - throw new IllegalStateException(String.format("Cannot find a script engine with name %s for executable %s.", - executable.getScriptEngineName(), executable.getPath())); - } - // prepare the SlingBindings - Bindings bindings = new LazyBindings(); - bindings.put("properties", request.getResource().getValueMap()); - bindings.put(SlingBindings.REQUEST, request); - bindings.put(SlingBindings.RESPONSE, response); - bindings.put(SlingBindings.READER, request.getReader()); - bindings.put(SlingBindings.RESOURCE, request.getResource()); - bindings.put(SlingBindings.RESOLVER, request.getResource().getResourceResolver()); - bindings.put(SlingBindings.OUT, response.getWriter()); - Logger scriptLogger = LoggerFactory.getLogger(executable.getName()); - bindings.put(SlingBindings.LOG, scriptLogger); - bindings.put(SlingBindings.SLING, new ScriptHelper(executable.getBundle().getBundleContext(), null, request, response)); - bindings.put(BundledRenderUnit.VARIABLE, executable); - bindings.put(ScriptEngine.FILENAME, executable.getName()); - bindings.put(ScriptEngine.FILENAME.replaceAll("\\.", "_"), executable.getName()); - - ProtectedBindings protectedBindings = new ProtectedBindings(bindings, PROTECTED_BINDINGS); - for (BindingsValuesProvider bindingsValuesProvider : bvpTracker.getBindingsValuesProviders(scriptEngine.getFactory(), - BindingsValuesProvider.DEFAULT_CONTEXT)) { - bindingsValuesProvider.addBindings(protectedBindings); - } - ScriptContext scriptContext = new BundledScriptContext(); - Map<String, LazyBindings.Supplier> slingBindingsSuppliers = new HashMap<>(); - slingBindingsSuppliers.put(SlingScriptConstants.ATTR_SCRIPT_RESOURCE_RESOLVER, - () -> scriptingResourceResolverProvider.getRequestScopedResourceResolver()); - LazyBindings slingScopeBindings = new LazyBindings(slingBindingsSuppliers); - scriptContext.setBindings(slingScopeBindings, SlingScriptConstants.SLING_SCOPE); - scriptContext.setBindings(bindings, ScriptContext.ENGINE_SCOPE); - scriptContext.setWriter(response.getWriter()); - scriptContext.setErrorWriter(new LogWriter(scriptLogger)); - scriptContext.setReader(request.getReader()); - return new ExecutableContext(scriptContext, executable, scriptEngine); - } - - static class ExecutableContext { - private final ScriptContext scriptContext; - private final Executable executable; - private final ScriptEngine scriptEngine; - - private ExecutableContext(ScriptContext scriptContext, Executable executable, ScriptEngine scriptEngine) { - this.scriptContext = scriptContext; - this.executable = executable; - this.scriptEngine = scriptEngine; - } - - void eval() throws ScriptException { - executable.eval(scriptEngine, scriptContext); - } - - void clean() { - Bindings engineBindings = scriptContext.getBindings(ScriptContext.ENGINE_SCOPE); - if (engineBindings != null && engineBindings.containsKey(SlingBindings.SLING)) { - Object scriptHelper = engineBindings.get(SlingBindings.SLING); - if (scriptHelper instanceof ScriptHelper) { - ((ScriptHelper) scriptHelper).cleanup(); - } - } - executable.releaseDependencies(); - } - } - - -}
diff --git a/src/main/java/org/apache/sling/scripting/bundle/tracker/internal/TypeProviderImpl.java b/src/main/java/org/apache/sling/scripting/bundle/tracker/internal/TypeProviderImpl.java deleted file mode 100644 index fe04d66..0000000 --- a/src/main/java/org/apache/sling/scripting/bundle/tracker/internal/TypeProviderImpl.java +++ /dev/null
@@ -1,70 +0,0 @@ -/*~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ - ~ Licensed to the Apache Software Foundation (ASF) under one - ~ or more contributor license agreements. See the NOTICE file - ~ distributed with this work for additional information - ~ regarding copyright ownership. The ASF licenses this file - ~ to you 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 org.apache.sling.scripting.bundle.tracker.internal; - -import java.util.Objects; - -import org.apache.sling.scripting.bundle.tracker.BundledRenderUnitCapability; -import org.jetbrains.annotations.NotNull; -import org.osgi.framework.Bundle; - -class TypeProviderImpl implements org.apache.sling.scripting.bundle.tracker.TypeProvider { - - private final BundledRenderUnitCapability bundledRenderUnitCapability; - private final Bundle bundle; - - TypeProviderImpl(BundledRenderUnitCapability bundledRenderUnitCapability, Bundle bundle) { - this.bundledRenderUnitCapability = bundledRenderUnitCapability; - this.bundle = bundle; - } - - @NotNull - @Override - public BundledRenderUnitCapability getBundledRenderUnitCapability() { - return bundledRenderUnitCapability; - } - - @NotNull - @Override - public Bundle getBundle() { - return bundle; - } - - @Override - public int hashCode() { - return Objects.hash(bundle, bundledRenderUnitCapability); - } - - @Override - public boolean equals(Object obj) { - if (this == obj) { - return true; - } - if (obj instanceof TypeProviderImpl) { - TypeProviderImpl other = (TypeProviderImpl) obj; - return Objects.equals(bundle, other.bundle) && Objects.equals(bundledRenderUnitCapability, other.bundledRenderUnitCapability); - } - return false; - } - - @Override - public String toString() { - return String.format("TypeProvider{ bundledRenderUnitCapability=%s; bundle=%s }", bundledRenderUnitCapability, bundle.getSymbolicName()); - } -}
diff --git a/src/main/java/org/apache/sling/scripting/bundle/tracker/internal/request/OnDemandReader.java b/src/main/java/org/apache/sling/scripting/bundle/tracker/internal/request/OnDemandReader.java deleted file mode 100644 index 7af2e7c..0000000 --- a/src/main/java/org/apache/sling/scripting/bundle/tracker/internal/request/OnDemandReader.java +++ /dev/null
@@ -1,97 +0,0 @@ -/*~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ - ~ Licensed to the Apache Software Foundation (ASF) under one - ~ or more contributor license agreements. See the NOTICE file - ~ distributed with this work for additional information - ~ regarding copyright ownership. The ASF licenses this file - ~ to you 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 org.apache.sling.scripting.bundle.tracker.internal.request; - -import java.io.IOException; -import java.io.Reader; -import java.nio.CharBuffer; - -import javax.servlet.ServletRequest; - -class OnDemandReader extends Reader { - - private final ServletRequest request; - - private Reader delegate; - - OnDemandReader(ServletRequest request) { - this.request = request; - } - - @Override - public void close() throws IOException { - if (delegate != null) { - delegate.close(); - } - } - - @Override - public void mark(int readAheadLimit) throws IOException { - getReader().mark(readAheadLimit); - } - - @Override - public boolean markSupported() { - return (delegate != null) && delegate.markSupported(); - } - - @Override - public int read() throws IOException { - return getReader().read(); - } - - @Override - public int read(char[] cbuf, int off, int len) throws IOException { - return getReader().read(cbuf, off, len); - } - - @Override - public int read(char[] cbuf) throws IOException { - return getReader().read(cbuf); - } - - @Override - public int read(CharBuffer target) throws IOException { - return getReader().read(target); - } - - @Override - public boolean ready() throws IOException { - return getReader().ready(); - } - - @Override - public void reset() throws IOException { - if (delegate != null) { - delegate.reset(); - } - } - - @Override - public long skip(long n) throws IOException { - return getReader().skip(n); - } - - private Reader getReader() throws IOException { - if (delegate == null) { - delegate = request.getReader(); - } - return delegate; - } -}
diff --git a/src/main/java/org/apache/sling/scripting/bundle/tracker/internal/request/OnDemandWriter.java b/src/main/java/org/apache/sling/scripting/bundle/tracker/internal/request/OnDemandWriter.java deleted file mode 100644 index c26ebba..0000000 --- a/src/main/java/org/apache/sling/scripting/bundle/tracker/internal/request/OnDemandWriter.java +++ /dev/null
@@ -1,103 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you 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 org.apache.sling.scripting.bundle.tracker.internal.request; - -import java.io.IOException; -import java.io.Writer; - -import javax.servlet.ServletResponse; - -class OnDemandWriter extends Writer { - - private final ServletResponse response; - - private Writer delegate; - - OnDemandWriter(ServletResponse response) { - this.response = response; - } - - private Writer getWriter() throws IOException { - if (delegate == null) { - delegate = response.getWriter(); - } - - return delegate; - } - - @Override - public void write(int c) throws IOException { - synchronized (lock) { - getWriter().write(c); - } - } - - @Override - public void write(char[] cbuf) throws IOException { - synchronized (lock) { - getWriter().write(cbuf); - } - } - - @Override - public void write(char[] cbuf, int off, int len) throws IOException { - synchronized (lock) { - getWriter().write(cbuf, off, len); - } - } - - @Override - public void write(String str) throws IOException { - synchronized (lock) { - getWriter().write(str); - } - } - - @Override - public void write(String str, int off, int len) throws IOException { - synchronized (lock) { - getWriter().write(str, off, len); - } - } - - @Override - public void flush() throws IOException { - synchronized (lock) { - Writer writer = delegate; - if (writer != null) { - writer.flush(); - } - } - } - - @Override - public void close() throws IOException { - synchronized (lock) { - // flush and close the delegate if existing, otherwise ignore - Writer writer = delegate; - if (writer != null) { - writer.flush(); - writer.close(); - - // drop the delegate now - delegate = null; - } - } - } -}
diff --git a/src/main/java/org/apache/sling/scripting/bundle/tracker/internal/request/RequestWrapper.java b/src/main/java/org/apache/sling/scripting/bundle/tracker/internal/request/RequestWrapper.java deleted file mode 100644 index e80663a..0000000 --- a/src/main/java/org/apache/sling/scripting/bundle/tracker/internal/request/RequestWrapper.java +++ /dev/null
@@ -1,94 +0,0 @@ -/*~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ - ~ Licensed to the Apache Software Foundation (ASF) under one - ~ or more contributor license agreements. See the NOTICE file - ~ distributed with this work for additional information - ~ regarding copyright ownership. The ASF licenses this file - ~ to you 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 org.apache.sling.scripting.bundle.tracker.internal.request; - -import java.io.BufferedReader; -import java.io.IOException; -import java.util.Set; - -import javax.servlet.RequestDispatcher; - -import org.apache.commons.lang3.StringUtils; -import org.apache.sling.api.SlingHttpServletRequest; -import org.apache.sling.api.request.RequestDispatcherOptions; -import org.apache.sling.api.resource.Resource; -import org.apache.sling.api.wrappers.SlingHttpServletRequestWrapper; -import org.apache.sling.scripting.bundle.tracker.ResourceType; - -public class RequestWrapper extends SlingHttpServletRequestWrapper { - - private final Set<ResourceType> wiredResourceTypes; - private BufferedReader reader; - - public RequestWrapper(SlingHttpServletRequest wrappedRequest, Set<ResourceType> wiredResourceTypes) { - super(wrappedRequest); - this.wiredResourceTypes = wiredResourceTypes; - } - - @Override - public RequestDispatcher getRequestDispatcher(Resource resource, RequestDispatcherOptions options) { - if (resource == null) { - return null; - } - if (options != null && StringUtils.isEmpty(options.getForceResourceType())) { - options.setForceResourceType(resource.getResourceType()); - } - RequestDispatcherOptions processedOptions = processOptions(options); - return super.getRequestDispatcher(resource, processedOptions); - } - - @Override - public RequestDispatcher getRequestDispatcher(String path, RequestDispatcherOptions options) { - if (path == null) { - return null; - } - RequestDispatcherOptions processedOptions = processOptions(options); - return super.getRequestDispatcher(path, processedOptions); - } - - @Override - public BufferedReader getReader() { - if (reader == null) { - reader = new BufferedReader(new OnDemandReader(getRequest())); - } - return reader; - } - - private RequestDispatcherOptions processOptions(RequestDispatcherOptions options) { - if (options != null) { - RequestDispatcherOptions requestDispatcherOptions = new RequestDispatcherOptions(); - requestDispatcherOptions.setForceResourceType(options.getForceResourceType()); - requestDispatcherOptions.setAddSelectors(options.getAddSelectors()); - requestDispatcherOptions.setReplaceSelectors(options.getReplaceSelectors()); - requestDispatcherOptions.setReplaceSuffix(options.getReplaceSuffix()); - String forcedResourceType = options.getForceResourceType(); - if (StringUtils.isNotEmpty(forcedResourceType)) { - for (ResourceType wiredResourceType : wiredResourceTypes) { - String type = wiredResourceType.getType(); - if (type.equals(forcedResourceType)) { - requestDispatcherOptions.setForceResourceType(wiredResourceType.toString()); - break; - } - } - } - return requestDispatcherOptions; - } - return null; - } -}
diff --git a/src/main/java/org/apache/sling/scripting/bundle/tracker/internal/request/ResponseWrapper.java b/src/main/java/org/apache/sling/scripting/bundle/tracker/internal/request/ResponseWrapper.java deleted file mode 100644 index 88714ef..0000000 --- a/src/main/java/org/apache/sling/scripting/bundle/tracker/internal/request/ResponseWrapper.java +++ /dev/null
@@ -1,50 +0,0 @@ -/*~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ - ~ Licensed to the Apache Software Foundation (ASF) under one - ~ or more contributor license agreements. See the NOTICE file - ~ distributed with this work for additional information - ~ regarding copyright ownership. The ASF licenses this file - ~ to you 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 org.apache.sling.scripting.bundle.tracker.internal.request; - -import java.io.PrintWriter; -import java.util.concurrent.atomic.AtomicReference; - -import org.apache.sling.api.SlingHttpServletResponse; -import org.apache.sling.api.wrappers.SlingHttpServletResponseWrapper; - -public class ResponseWrapper extends SlingHttpServletResponseWrapper { - private final AtomicReference<PrintWriter> writer = new AtomicReference<>(); - - /** - * Create a wrapper for the supplied wrappedRequest - * - * @param wrappedResponse The response - */ - public ResponseWrapper(SlingHttpServletResponse wrappedResponse) { - super(wrappedResponse); - } - - @Override - public PrintWriter getWriter() { - PrintWriter result = writer.get(); - if (result == null) { - result = new PrintWriter(new OnDemandWriter(getResponse())); - if (!writer.compareAndSet(null, result)) { - result = writer.get(); - } - } - return result; - } -}
diff --git a/src/main/java/org/apache/sling/scripting/bundle/tracker/package-info.java b/src/main/java/org/apache/sling/scripting/bundle/tracker/package-info.java deleted file mode 100644 index 66d51bb..0000000 --- a/src/main/java/org/apache/sling/scripting/bundle/tracker/package-info.java +++ /dev/null
@@ -1,22 +0,0 @@ -/*~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ - ~ Licensed to the Apache Software Foundation (ASF) under one - ~ or more contributor license agreements. See the NOTICE file - ~ distributed with this work for additional information - ~ regarding copyright ownership. The ASF licenses this file - ~ to you 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. - ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~*/ -@Version("0.2.0") -package org.apache.sling.scripting.bundle.tracker; - -import org.osgi.annotation.versioning.Version;
diff --git a/src/test/java/org/apache/sling/scripting/bundle/tracker/ResourceTypeTest.java b/src/test/java/org/apache/sling/scripting/bundle/tracker/ResourceTypeTest.java deleted file mode 100644 index 8f102e9..0000000 --- a/src/test/java/org/apache/sling/scripting/bundle/tracker/ResourceTypeTest.java +++ /dev/null
@@ -1,87 +0,0 @@ -/*~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ - ~ Licensed to the Apache Software Foundation (ASF) under one - ~ or more contributor license agreements. See the NOTICE file - ~ distributed with this work for additional information - ~ regarding copyright ownership. The ASF licenses this file - ~ to you 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 org.apache.sling.scripting.bundle.tracker; - -import org.apache.commons.lang3.StringUtils; -import org.junit.Test; - -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNull; - -public class ResourceTypeTest { - - @Test - public void testSlashNoVersion() { - ResourceType t1 = ResourceType.parseResourceType("a/b/c"); - assertEquals("a/b/c", t1.getType()); - assertEquals("c", t1.getResourceLabel()); - assertNull(t1.getVersion()); - } - - @Test - public void testSlashVersion() { - ResourceType t1 = ResourceType.parseResourceType("a/b/c/1.0.0"); - assertEquals("a/b/c", t1.getType()); - assertEquals("c", t1.getResourceLabel()); - assertEquals("1.0.0", t1.getVersion()); - } - - @Test - public void testOneSegmentNoVersion() { - ResourceType t1 = ResourceType.parseResourceType("a"); - assertEquals("a", t1.getType()); - assertEquals("a", t1.getResourceLabel()); - assertNull(t1.getVersion()); - } - - @Test - public void testOneSegmentVersion() { - ResourceType t1 = ResourceType.parseResourceType("a/1.2.3"); - assertEquals("a", t1.getType()); - assertEquals("a", t1.getResourceLabel()); - assertEquals("1.2.3", t1.getVersion()); - } - - @Test - public void testDotNoVersion() { - ResourceType t1 = ResourceType.parseResourceType("a.b.c"); - assertEquals("a.b.c", t1.getType()); - assertEquals("c", t1.getResourceLabel()); - assertNull(t1.getVersion()); - } - - @Test - public void testDotVersion() { - ResourceType t1 = ResourceType.parseResourceType("a.b.c/42.0.0"); - assertEquals("a.b.c", t1.getType()); - assertEquals("c", t1.getResourceLabel()); - assertEquals("42.0.0", t1.getVersion()); - } - - @Test(expected = IllegalArgumentException.class) - public void testEmptyString() { - ResourceType t1 = ResourceType.parseResourceType(StringUtils.EMPTY); - } - - @Test(expected = IllegalArgumentException.class) - public void testNull() { - ResourceType t1 = ResourceType.parseResourceType(null); - } - -}
diff --git a/src/test/java/org/apache/sling/scripting/bundle/tracker/internal/BundledHooksTest.java b/src/test/java/org/apache/sling/scripting/bundle/tracker/internal/BundledHooksTest.java deleted file mode 100644 index 1b974fb..0000000 --- a/src/test/java/org/apache/sling/scripting/bundle/tracker/internal/BundledHooksTest.java +++ /dev/null
@@ -1,130 +0,0 @@ -/*~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ - ~ Licensed to the Apache Software Foundation (ASF) under one - ~ or more contributor license agreements. See the NOTICE file - ~ distributed with this work for additional information - ~ regarding copyright ownership. The ASF licenses this file - ~ to you 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 org.apache.sling.scripting.bundle.tracker.internal; - -import java.util.ArrayList; -import java.util.Arrays; -import java.util.Collection; -import java.util.HashMap; -import java.util.List; -import java.util.Map; - -import org.junit.Assert; -import org.junit.Test; -import org.osgi.framework.Bundle; -import org.osgi.framework.BundleContext; -import org.osgi.framework.ServiceEvent; -import org.osgi.framework.ServiceReference; -import org.osgi.framework.hooks.service.ListenerHook; -import static org.mockito.Mockito.mock; -import static org.mockito.Mockito.when; - -public class BundledHooksTest { - @Test - public void testFindHookFiltersOther() { - BundledHooks hooks = new BundledHooks(); - - BundleContext context = mock(BundleContext.class); - Bundle bundle = mock(Bundle.class); - ServiceReference<?> ref = mock(ServiceReference.class); - - when(context.getBundle()).thenReturn(bundle); - when(bundle.getSymbolicName()).thenReturn("org.apache.sling.foo.bar"); - when(ref.getProperty(BundledHooks.class.getName())).thenReturn("true"); - List<ServiceReference<?>> services = new ArrayList<>(); - - services.add(ref); - hooks.find(context, null, null, true, services); - - Assert.assertTrue(services.isEmpty()); - } - - @Test - public void testFindHookDoesNotFilterResolver() { - BundledHooks hooks = new BundledHooks(); - - BundleContext context = mock(BundleContext.class); - Bundle bundle = mock(Bundle.class); - ServiceReference<?> ref = mock(ServiceReference.class); - - when(context.getBundle()).thenReturn(bundle); - when(bundle.getSymbolicName()).thenReturn("org.apache.sling.servlets.resolver"); - when(ref.getProperty(BundledHooks.class.getName())).thenReturn("true"); - List<ServiceReference<?>> services = new ArrayList<>(); - - services.add(ref); - hooks.find(context, null, null, true, services); - - Assert.assertEquals(1, services.size()); - } - - @Test - public void testEventHookFiltersOther() { - BundledHooks hooks = new BundledHooks(); - - ServiceEvent event = mock(ServiceEvent.class); - - BundleContext context = mock(BundleContext.class); - Bundle bundle = mock(Bundle.class); - ServiceReference ref = mock(ServiceReference.class); - - when(event.getServiceReference()).thenReturn(ref); - - when(context.getBundle()).thenReturn(bundle); - when(bundle.getSymbolicName()).thenReturn("org.apache.sling.foo.bar"); - when(ref.getProperty(BundledHooks.class.getName())).thenReturn("true"); - - ListenerHook.ListenerInfo info = mock(ListenerHook.ListenerInfo.class); - when(info.getBundleContext()).thenReturn(context); - Map<BundleContext, Collection<ListenerHook.ListenerInfo>> listeners = new HashMap<>(); - listeners.put(context, new ArrayList<>(Arrays.asList(info))); - - hooks.event(event, listeners); - - Assert.assertTrue(listeners.isEmpty()); - } - - @Test - public void testEventHookDoesNotFilterResolver() { - BundledHooks hooks = new BundledHooks(); - - ServiceEvent event = mock(ServiceEvent.class); - - BundleContext context = mock(BundleContext.class); - Bundle bundle = mock(Bundle.class); - ServiceReference ref = mock(ServiceReference.class); - - when(event.getServiceReference()).thenReturn(ref); - - when(context.getBundle()).thenReturn(bundle); - when(bundle.getSymbolicName()).thenReturn("org.apache.sling.servlets.resolver"); - when(ref.getProperty(BundledHooks.class.getName())).thenReturn("true"); - - ListenerHook.ListenerInfo info = mock(ListenerHook.ListenerInfo.class); - when(info.getBundleContext()).thenReturn(context); - Map<BundleContext, Collection<ListenerHook.ListenerInfo>> listeners = new HashMap<>(); - listeners.put(context, new ArrayList<>(Arrays.asList(info))); - - hooks.event(event, listeners); - - Assert.assertEquals(1, listeners.size()); - - Assert.assertEquals(1, listeners.get(context).size()); - } -}
diff --git a/src/test/java/org/apache/sling/scripting/bundle/tracker/internal/BundledScriptContextTest.java b/src/test/java/org/apache/sling/scripting/bundle/tracker/internal/BundledScriptContextTest.java deleted file mode 100644 index 0a26503..0000000 --- a/src/test/java/org/apache/sling/scripting/bundle/tracker/internal/BundledScriptContextTest.java +++ /dev/null
@@ -1,151 +0,0 @@ -/*~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ - ~ Licensed to the Apache Software Foundation (ASF) under one - ~ or more contributor license agreements. See the NOTICE file - ~ distributed with this work for additional information - ~ regarding copyright ownership. The ASF licenses this file - ~ to you 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 org.apache.sling.scripting.bundle.tracker.internal; - -import javax.script.Bindings; -import javax.script.ScriptContext; -import javax.script.SimpleBindings; - -import org.apache.sling.api.scripting.SlingScriptConstants; -import org.junit.Test; - -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertNull; -import static org.junit.Assert.assertTrue; - -public class BundledScriptContextTest { - - @Test - public void testSetAndGetBindings() { - BundledScriptContext bundledScriptContext = new BundledScriptContext(); - Bindings engineScope = new SimpleBindings(); - Bindings globalScope = new SimpleBindings(); - Bindings slingScope = new SimpleBindings(); - - bundledScriptContext.setBindings(slingScope, SlingScriptConstants.SLING_SCOPE); - bundledScriptContext.setBindings(globalScope, ScriptContext.GLOBAL_SCOPE); - bundledScriptContext.setBindings(engineScope, ScriptContext.ENGINE_SCOPE); - - assertEquals(engineScope, bundledScriptContext.getBindings(ScriptContext.ENGINE_SCOPE)); - assertEquals(globalScope, bundledScriptContext.getBindings(ScriptContext.GLOBAL_SCOPE)); - assertEquals(slingScope, bundledScriptContext.getBindings(SlingScriptConstants.SLING_SCOPE)); - - boolean invalidScopeThrowsException; - try { - bundledScriptContext.getBindings(Integer.MIN_VALUE); - invalidScopeThrowsException = false; - } catch (Exception e) { - invalidScopeThrowsException = true; - } - assertTrue(BundledScriptContext.class.getName() + " should throw exceptions for invalid scopes.", invalidScopeThrowsException); - - boolean acceptsAnyScope; - try { - bundledScriptContext.setBindings(new SimpleBindings(), Integer.MIN_VALUE); - acceptsAnyScope = true; - } catch (Exception e) { - acceptsAnyScope = false; - } - assertFalse(BundledScriptContext.class.getName() + " should not accept bindings for arbitrary scopes.", acceptsAnyScope); - - boolean acceptsNullBindings; - try { - bundledScriptContext.setBindings(null, ScriptContext.ENGINE_SCOPE); - acceptsNullBindings = true; - } catch (Exception e) { - acceptsNullBindings = false; - } - assertFalse(BundledScriptContext.class.getName() + " should not accept null bindings.", acceptsNullBindings); - } - - @Test - public void testSetAndGetAttribute() { - BundledScriptContext bundledScriptContext = new BundledScriptContext(); - boolean acceptsSettingNullAttributeNames; - try { - bundledScriptContext.setAttribute(null, 0, ScriptContext.ENGINE_SCOPE); - acceptsSettingNullAttributeNames = true; - } catch (Exception e) { - acceptsSettingNullAttributeNames = false; - } - assertFalse(BundledScriptContext.class.getName() + " should not accept null attribute names.", acceptsSettingNullAttributeNames); - - boolean acceptsRetrievingNullAttributeNamesFromScope; - try { - bundledScriptContext.getAttribute(null, ScriptContext.ENGINE_SCOPE); - acceptsRetrievingNullAttributeNamesFromScope = true; - } catch (Exception e) { - acceptsRetrievingNullAttributeNamesFromScope = false; - } - assertFalse(BundledScriptContext.class.getName() + " should not accept null attribute names.", acceptsRetrievingNullAttributeNamesFromScope); - - boolean acceptsRetrievingNullAttributeNames; - try { - bundledScriptContext.getAttribute(null); - acceptsRetrievingNullAttributeNames = true; - } catch (Exception e) { - acceptsRetrievingNullAttributeNames = false; - } - assertFalse(BundledScriptContext.class.getName() + " should not accept null attribute names.", acceptsRetrievingNullAttributeNames); - - bundledScriptContext.setAttribute("nothing", 0, ScriptContext.ENGINE_SCOPE); - assertEquals(0, bundledScriptContext.getAttribute("nothing")); - assertEquals(0, bundledScriptContext.getAttribute("nothing", ScriptContext.ENGINE_SCOPE)); - assertNull(bundledScriptContext.getAttribute("nothing", ScriptContext.GLOBAL_SCOPE)); - } - - @Test - public void testRemoveAttribute() { - BundledScriptContext bundledScriptContext = new BundledScriptContext(); - boolean acceptsNullAttributeNames; - try { - bundledScriptContext.removeAttribute(null, ScriptContext.ENGINE_SCOPE); - acceptsNullAttributeNames = true; - } catch (Exception e) { - acceptsNullAttributeNames = false; - } - assertFalse(BundledScriptContext.class.getName() + " should not accept null attribute names.", acceptsNullAttributeNames); - - bundledScriptContext.setAttribute("nothing", 0, ScriptContext.ENGINE_SCOPE); - assertEquals(0, bundledScriptContext.removeAttribute("nothing", ScriptContext.ENGINE_SCOPE)); - Bindings engineScope = bundledScriptContext.getBindings(ScriptContext.ENGINE_SCOPE); - assertTrue( engineScope != null && engineScope.size() == 0); - assertNull(bundledScriptContext.removeAttribute("nothing", ScriptContext.ENGINE_SCOPE)); - assertNull(bundledScriptContext.removeAttribute("nothing", ScriptContext.GLOBAL_SCOPE)); - } - - @Test - public void testGetAttributesScope() { - BundledScriptContext bundledScriptContext = new BundledScriptContext(); - boolean acceptsNullAttributeNames; - try { - bundledScriptContext.getAttributesScope(null); - acceptsNullAttributeNames = true; - } catch (Exception e) { - acceptsNullAttributeNames = false; - } - assertFalse(BundledScriptContext.class.getName() + " should not accept null attribute names.", acceptsNullAttributeNames); - - bundledScriptContext.setAttribute("nothing", 0, SlingScriptConstants.SLING_SCOPE); - assertEquals(SlingScriptConstants.SLING_SCOPE, bundledScriptContext.getAttributesScope("nothing")); - assertEquals(-1, bundledScriptContext.getAttributesScope("nothing here")); - } - -}
diff --git a/src/test/java/org/apache/sling/scripting/bundle/tracker/internal/BundledScriptTrackerTest.java b/src/test/java/org/apache/sling/scripting/bundle/tracker/internal/BundledScriptTrackerTest.java deleted file mode 100644 index 022ff35..0000000 --- a/src/test/java/org/apache/sling/scripting/bundle/tracker/internal/BundledScriptTrackerTest.java +++ /dev/null
@@ -1,47 +0,0 @@ -/*~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ - ~ Licensed to the Apache Software Foundation (ASF) under one - ~ or more contributor license agreements. See the NOTICE file - ~ distributed with this work for additional information - ~ regarding copyright ownership. The ASF licenses this file - ~ to you 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 org.apache.sling.scripting.bundle.tracker.internal; - -import java.util.ArrayList; -import java.util.List; - -import javax.servlet.Servlet; - -import org.junit.Test; -import org.osgi.framework.Bundle; -import org.osgi.framework.BundleContext; -import org.osgi.framework.BundleEvent; -import org.osgi.framework.ServiceRegistration; - -import static org.mockito.Mockito.mock; -import static org.mockito.Mockito.verify; - -public class BundledScriptTrackerTest { - - @Test - public void removedBundle() { - BundledScriptTracker tracker = new BundledScriptTracker(); - tracker.activate(mock(BundleContext.class)); - List<ServiceRegistration<Servlet>> registrations = new ArrayList<>(); - ServiceRegistration<Servlet> registration = mock(ServiceRegistration.class); - registrations.add(registration); - tracker.removedBundle(mock(Bundle.class), mock(BundleEvent.class), registrations); - verify(registration).unregister(); - } -}
diff --git a/src/test/java/org/apache/sling/scripting/bundle/tracker/internal/LogWriterTest.java b/src/test/java/org/apache/sling/scripting/bundle/tracker/internal/LogWriterTest.java deleted file mode 100644 index bb5fe26..0000000 --- a/src/test/java/org/apache/sling/scripting/bundle/tracker/internal/LogWriterTest.java +++ /dev/null
@@ -1,60 +0,0 @@ -/*~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ - ~ Licensed to the Apache Software Foundation (ASF) under one - ~ or more contributor license agreements. See the NOTICE file - ~ distributed with this work for additional information - ~ regarding copyright ownership. The ASF licenses this file - ~ to you 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 org.apache.sling.scripting.bundle.tracker.internal; - -import org.junit.Test; -import org.slf4j.Logger; - -import static org.mockito.Mockito.mock; -import static org.mockito.Mockito.verify; -import static org.mockito.Mockito.verifyNoMoreInteractions; - -public class LogWriterTest { - - @Test - public void testLogWriterCRLFFlush() { - Logger mockedLogger = mock(Logger.class); - LogWriter writer = new LogWriter(mockedLogger); - char[] buffer = "Test CRLF 1\nTest CRLF 2".toCharArray(); - writer.write(buffer, 0, buffer.length); - verify(mockedLogger).error("Test CRLF 1"); - writer.flush(); - verify(mockedLogger).error("Test CRLF 2"); - verifyNoMoreInteractions(mockedLogger); - writer.flush(); - writer.close(); - } - - @Test - public void testLogWriterCharWriteAndFlush() { - Logger mockedLogger = mock(Logger.class); - LogWriter writer = new LogWriter(mockedLogger); - writer.write('a'); - writer.write('\n'); - verify(mockedLogger).error("a"); - writer.write('a'); - writer.write('b'); - writer.write('c'); - writer.close(); - verify(mockedLogger).error("abc"); - } - - - -}
diff --git a/src/test/java/org/apache/sling/scripting/bundle/tracker/internal/ProtectedBindingsTest.java b/src/test/java/org/apache/sling/scripting/bundle/tracker/internal/ProtectedBindingsTest.java deleted file mode 100644 index 82d2a9a..0000000 --- a/src/test/java/org/apache/sling/scripting/bundle/tracker/internal/ProtectedBindingsTest.java +++ /dev/null
@@ -1,205 +0,0 @@ -/*~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ - ~ Licensed to the Apache Software Foundation (ASF) under one - ~ or more contributor license agreements. See the NOTICE file - ~ distributed with this work for additional information - ~ regarding copyright ownership. The ASF licenses this file - ~ to you 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 org.apache.sling.scripting.bundle.tracker.internal; - -import java.util.Arrays; -import java.util.Collection; -import java.util.Collections; -import java.util.HashMap; -import java.util.HashSet; -import java.util.Map; -import java.util.Set; - -import javax.script.Bindings; -import javax.script.SimpleBindings; - -import org.junit.Test; - -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertTrue; -import static org.mockito.Mockito.mock; -import static org.mockito.Mockito.verify; - -public class ProtectedBindingsTest { - - @Test - public void put() { - ProtectedBindings bindings = getBindingsUnderTest(); - bindings.put("d", 4); - boolean allowsOverride; - try { - bindings.put("c", 0); - allowsOverride = true; - } catch (IllegalArgumentException e) { - allowsOverride = false; - } - assertFalse("Protected keys were overwritten.", allowsOverride); - assertEquals("Expected that unprotected keys can be used.", 4, bindings.get("d")); - } - - @Test - public void putAll() { - ProtectedBindings bindings = getBindingsUnderTest(); - boolean allowsOverride; - try { - bindings.putAll(new HashMap<String, Object>(){{ - put("a", 0); - put("b", 0); - put("c", 0); - }}); - allowsOverride = true; - } catch (IllegalArgumentException e) { - allowsOverride = false; - } - assertFalse("Protected keys were overwritten", allowsOverride); - bindings.putAll(new HashMap<String, Object>(){{ - put("d", 4); - put("e", 5); - put("f", 6); - }}); - assertTrue("Expected that the bindings contain non-conflicting additions.", bindings.size() == 6 && bindings.get("d").equals(4) - && bindings.get("e").equals(5) && bindings.get("f").equals(6)); - } - - @Test - public void remove() { - ProtectedBindings bindings = getBindingsUnderTest(); - boolean allowsOverride; - try { - bindings.remove("a"); - allowsOverride = true; - } catch (IllegalArgumentException e) { - allowsOverride = false; - } - assertFalse("Protected keys were overwritten.", allowsOverride); - assertEquals("Expected that protected key was not removed.", 1, bindings.get("a")); - bindings.put("d", 4); - assertEquals(4, bindings.size()); - assertEquals(4, bindings.remove("d")); - } - - @Test - public void clear() { - ProtectedBindings bindings = getBindingsUnderTest(); - boolean hasThrownUOE = false; - try { - bindings.clear(); - } catch (UnsupportedOperationException e) { - hasThrownUOE = true; - } - assertTrue("Expected an UnsupportedOperationException.", hasThrownUOE); - assertTrue("Expected map to not be modified.", bindings.size() == 3 && bindings.get("a").equals(1) && bindings.get("b").equals(2) - && bindings.get("c").equals(3)); - } - - @Test - public void containsValue() { - Bindings bindings = mock(Bindings.class); - ProtectedBindings protectedBindings = new ProtectedBindings(bindings, Collections.emptySet()); - protectedBindings.containsValue(4); - verify(bindings).containsValue(4); - } - - @Test - public void entrySet() { - ProtectedBindings bindings = getBindingsUnderTest(); - Set<Map.Entry<String, Object>> entrySet = bindings.entrySet(); - assertEquals(3, entrySet.size()); - boolean unmodifiable; - try { - entrySet.clear(); - unmodifiable = false; - } catch (UnsupportedOperationException e) { - unmodifiable = true; - } - assertTrue("Expected an unmodifiable entry set.", unmodifiable); - } - - @Test - public void isEmpty() { - Bindings bindings = mock(Bindings.class); - ProtectedBindings protectedBindings = new ProtectedBindings(bindings, Collections.emptySet()); - protectedBindings.isEmpty(); - verify(bindings).isEmpty(); - } - - @Test - public void keySet() { - ProtectedBindings bindings = getBindingsUnderTest(); - Set<String> keySet = bindings.keySet(); - assertEquals(3, keySet.size()); - boolean unmodifiable; - try { - keySet.clear(); - unmodifiable = false; - } catch (UnsupportedOperationException e) { - unmodifiable = true; - } - assertTrue("Expected an unmodifiable key set.", unmodifiable); - } - - @Test - public void size() { - Bindings bindings = mock(Bindings.class); - ProtectedBindings protectedBindings = new ProtectedBindings(bindings, Collections.emptySet()); - protectedBindings.size(); - verify(bindings).size(); - } - - @Test - public void values() { - ProtectedBindings bindings = getBindingsUnderTest(); - Collection<Object> values = bindings.values(); - assertEquals(3, values.size()); - boolean unmodifiable; - try { - values.clear(); - unmodifiable = false; - } catch (UnsupportedOperationException e) { - unmodifiable = true; - } - assertTrue("Expected an unmodifiable values collection.", unmodifiable); - } - - @Test - public void containsKey() { - Bindings bindings = mock(Bindings.class); - ProtectedBindings protectedBindings = new ProtectedBindings(bindings, Collections.emptySet()); - protectedBindings.containsKey("a"); - verify(bindings).containsKey("a"); - } - - @Test - public void get() { - Bindings bindings = mock(Bindings.class); - ProtectedBindings protectedBindings = new ProtectedBindings(bindings, Collections.emptySet()); - protectedBindings.get("a"); - verify(bindings).get("a"); - } - - private ProtectedBindings getBindingsUnderTest() { - Bindings bindings = new SimpleBindings(); - bindings.put("a", 1); - bindings.put("b", 2); - bindings.put("c", 3); - Set<String> protectedKeys = new HashSet<>(Arrays.asList("a", "b", "c")); - return new ProtectedBindings(bindings, protectedKeys); - } -}
diff --git a/src/test/resources/findbugs-exclude.xml b/src/test/resources/findbugs-exclude.xml deleted file mode 100644 index 24ab733..0000000 --- a/src/test/resources/findbugs-exclude.xml +++ /dev/null
@@ -1,23 +0,0 @@ -<!--~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ - ~ Licensed to the Apache Software Foundation (ASF) under one - ~ or more contributor license agreements. See the NOTICE file - ~ distributed with this work for additional information - ~ regarding copyright ownership. The ASF licenses this file - ~ to you 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. - ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~--> -<FindBugsFilter> - <Match> - <Bug pattern="SE_BAD_FIELD" /> - </Match> -</FindBugsFilter>