SLING-865 : Move to bundles
git-svn-id: https://svn.apache.org/repos/asf/incubator/sling/trunk@746693 13f79535-47bb-0310-9956-ffa450edef68
diff --git a/LICENSE b/LICENSE
new file mode 100644
index 0000000..d645695
--- /dev/null
+++ b/LICENSE
@@ -0,0 +1,202 @@
+
+ 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/NOTICE b/NOTICE
new file mode 100644
index 0000000..5e52eca
--- /dev/null
+++ b/NOTICE
@@ -0,0 +1,8 @@
+Apache Sling Adapter Manager
+Copyright 2008-2009 The Apache Software Foundation
+
+Apache Sling is based on source code originally developed
+by Day Software (http://www.day.com/).
+
+This product includes software developed at
+The Apache Software Foundation (http://www.apache.org/).
diff --git a/README.txt b/README.txt
new file mode 100644
index 0000000..d7dd783
--- /dev/null
+++ b/README.txt
@@ -0,0 +1,40 @@
+Apache Sling Adapter Manager
+
+Bundle implementing the AdapterManager and provides a convenience
+implementation of the Adaptable interface to make use of this
+AdapterManager.
+
+
+Disclaimer
+==========
+Apache Sling is an effort undergoing incubation at The Apache Software Foundation (ASF),
+sponsored by the Apache Jackrabbit PMC. Incubation is required of all newly accepted
+projects until a further review indicates that the infrastructure, communications,
+and decision making process have stabilized in a manner consistent with other
+successful ASF projects. While incubation status is not necessarily a reflection of
+the completeness or stability of the code, it does indicate that the project has yet
+to be fully endorsed by the ASF.
+
+Getting Started
+===============
+
+This component uses a Maven 2 (http://maven.apache.org/) build
+environment. It requires a Java 5 JDK (or higher) and Maven (http://maven.apache.org/)
+2.0.7 or later. We recommend to use the latest Maven version.
+
+If you have Maven 2 installed, you can compile and
+package the jar using the following command:
+
+ mvn package
+
+See the Maven 2 documentation for other build features.
+
+The latest source code for this component is available in the
+Subversion (http://subversion.tigris.org/) source repository of
+the Apache Software Foundation. If you have Subversion installed,
+you can checkout the latest source using the following command:
+
+ svn checkout http://svn.apache.org/repos/asf/incubator/sling/trunk/extensions/adapter
+
+See the Subversion documentation for other source control features.
+
diff --git a/pom.xml b/pom.xml
new file mode 100644
index 0000000..6706273
--- /dev/null
+++ b/pom.xml
@@ -0,0 +1,111 @@
+<?xml version="1.0" encoding="ISO-8859-1"?>
+<!--
+ 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/maven-v4_0_0.xsd">
+
+ <modelVersion>4.0.0</modelVersion>
+ <parent>
+ <groupId>org.apache.sling</groupId>
+ <artifactId>sling</artifactId>
+ <version>5-incubator-SNAPSHOT</version>
+ <relativePath>../../parent/pom.xml</relativePath>
+ </parent>
+
+ <artifactId>org.apache.sling.adapter</artifactId>
+ <packaging>bundle</packaging>
+ <version>2.0.3-incubator-SNAPSHOT</version>
+
+ <name>Apache Sling AdapterManager implementation</name>
+ <description>
+ Bundle implementing the AdapterManager and provides a convenience
+ implementation of the Adaptable interface to make use of this
+ AdapterManager.
+ </description>
+
+ <scm>
+ <connection>scm:svn:http://svn.apache.org/repos/asf/incubator/sling/trunk/extensions/adapter</connection>
+ <developerConnection>scm:svn:https://svn.apache.org/repos/asf/incubator/sling/trunk/extensions/adapter</developerConnection>
+ <url>http://svn.apache.org/viewvc/incubator/sling/trunk/extensions/adapter</url>
+ </scm>
+
+ <build>
+ <plugins>
+ <plugin>
+ <groupId>org.apache.felix</groupId>
+ <artifactId>maven-scr-plugin</artifactId>
+ </plugin>
+ <plugin>
+ <groupId>org.apache.felix</groupId>
+ <artifactId>maven-bundle-plugin</artifactId>
+ <extensions>true</extensions>
+ <configuration>
+ <instructions>
+ <Export-Package>
+ org.apache.sling.adapter;version=${pom.version}
+ </Export-Package>
+ <Private-Package>
+ org.apache.sling.adapter.internal
+ </Private-Package>
+ </instructions>
+ </configuration>
+ </plugin>
+ </plugins>
+ </build>
+ <reporting>
+ <plugins>
+ <plugin>
+ <groupId>org.apache.maven.plugins</groupId>
+ <artifactId>maven-javadoc-plugin</artifactId>
+ <configuration>
+ <excludePackageNames>
+ org.apache.sling.adapter.internal
+ </excludePackageNames>
+ </configuration>
+ </plugin>
+ </plugins>
+ </reporting>
+ <dependencies>
+ <dependency>
+ <groupId>org.apache.sling</groupId>
+ <artifactId>org.apache.sling.api</artifactId>
+ <version>2.0.2-incubator</version>
+ </dependency>
+ <dependency>
+ <groupId>org.apache.sling</groupId>
+ <artifactId>org.apache.sling.commons.osgi</artifactId>
+ <version>2.0.2-incubator</version>
+ </dependency>
+ <dependency>
+ <groupId>org.apache.felix</groupId>
+ <artifactId>org.osgi.core</artifactId>
+ </dependency>
+ <dependency>
+ <groupId>org.apache.felix</groupId>
+ <artifactId>org.osgi.compendium</artifactId>
+ </dependency>
+ <dependency>
+ <groupId>org.slf4j</groupId>
+ <artifactId>slf4j-api</artifactId>
+ </dependency>
+ <dependency>
+ <groupId>junit</groupId>
+ <artifactId>junit</artifactId>
+ </dependency>
+ </dependencies>
+</project>
diff --git a/src/main/java/org/apache/sling/adapter/SlingAdaptable.java b/src/main/java/org/apache/sling/adapter/SlingAdaptable.java
new file mode 100644
index 0000000..6d92fa9
--- /dev/null
+++ b/src/main/java/org/apache/sling/adapter/SlingAdaptable.java
@@ -0,0 +1,40 @@
+/*
+ * 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.adapter;
+
+import org.apache.sling.adapter.internal.AdapterManagerImpl;
+import org.apache.sling.api.adapter.Adaptable;
+
+/**
+ * The <code>SlingAdaptable</code> class is an (abstract) default
+ * implementation of the <code>Adaptable</code> interface. It just uses the
+ * default {@link org.apache.sling.api.adapter.AdapterManager} implemented in this bundle to adapt the itself
+ * to the requested type.
+ * <p>
+ * Extensions of this class may overwrite the {@link #adaptTo(Class)} method
+ * using their own knowledge of adapters and may call this base class
+ * implementation to fall back to an extended adapters.
+ */
+public abstract class SlingAdaptable implements Adaptable {
+
+ public <AdapterType> AdapterType adaptTo(Class<AdapterType> type) {
+ return AdapterManagerImpl.getInstance().getAdapter(this, type);
+ }
+
+}
diff --git a/src/main/java/org/apache/sling/adapter/internal/AdapterFactoryDescriptor.java b/src/main/java/org/apache/sling/adapter/internal/AdapterFactoryDescriptor.java
new file mode 100644
index 0000000..99fd459
--- /dev/null
+++ b/src/main/java/org/apache/sling/adapter/internal/AdapterFactoryDescriptor.java
@@ -0,0 +1,47 @@
+/*
+ * 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.adapter.internal;
+
+import org.apache.sling.api.adapter.AdapterFactory;
+
+/**
+ * The <code>AdapterFactoryDescriptor</code> is an entry in the
+ * {@link AdapterFactoryDescriptorMap} conveying the list of adapter (target)
+ * types and the respective {@link AdapterFactory}.
+ */
+public class AdapterFactoryDescriptor {
+
+ private AdapterFactory factory;
+
+ private String[] adapters;
+
+ public AdapterFactoryDescriptor(AdapterFactory factory, String[] adapters) {
+ this.factory = factory;
+ this.adapters = adapters;
+ }
+
+ public AdapterFactory getFactory() {
+ return factory;
+ }
+
+ public String[] getAdapters() {
+ return adapters;
+ }
+
+}
diff --git a/src/main/java/org/apache/sling/adapter/internal/AdapterFactoryDescriptorKey.java b/src/main/java/org/apache/sling/adapter/internal/AdapterFactoryDescriptorKey.java
new file mode 100644
index 0000000..2ec1346
--- /dev/null
+++ b/src/main/java/org/apache/sling/adapter/internal/AdapterFactoryDescriptorKey.java
@@ -0,0 +1,88 @@
+/*
+ * 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.adapter.internal;
+
+import org.apache.sling.commons.osgi.OsgiUtil;
+import org.osgi.framework.Constants;
+import org.osgi.framework.ServiceReference;
+
+/**
+ * The <code>AdapterFactoryDescriptorKey</code> provides the indexing
+ * functionality for the {@link AdapterFactoryDescriptorMap}. The key consists
+ * of the OSGi <code>service.id</code> of the
+ * {@link org.apache.sling.api.adapter.AdapterFactory} service and the ID of
+ * the the bundle providing the service.
+ * <p>
+ * Sort order among the keys is defined primarily by the bundle id and
+ * secondarily by the service id.
+ */
+public class AdapterFactoryDescriptorKey implements
+ Comparable<AdapterFactoryDescriptorKey> {
+
+ private long bundleId;
+
+ private long serviceId;
+
+ public AdapterFactoryDescriptorKey(ServiceReference ref) {
+ bundleId = ref.getBundle().getBundleId();
+ serviceId = OsgiUtil.toLong(ref.getProperty(Constants.SERVICE_ID), -1);
+ }
+
+ public int compareTo(AdapterFactoryDescriptorKey o) {
+ if (o.equals(this)) {
+ return 0;
+ }
+
+ // result for differing bundleId
+ if (bundleId < o.bundleId) {
+ return -1;
+ } else if (bundleId > o.bundleId) {
+ return 1;
+ }
+
+ // result for differing serviceId, we do not expect the two
+ // serviceId values to be equal because otherwise the equals
+ // test above would have yielded true
+ if (serviceId < o.serviceId) {
+ return -1;
+ }
+
+ // serviceId is larger than the other object's, we do not expect
+ // the two serviceId values to be equal because otherwise the equals
+ // test above would have yielded true
+ return 1;
+ }
+
+ @Override
+ public boolean equals(Object o) {
+ if (o == this) {
+ return true;
+ } else if (o instanceof AdapterFactoryDescriptorKey) {
+ AdapterFactoryDescriptorKey oKey = (AdapterFactoryDescriptorKey) o;
+ return bundleId == oKey.bundleId && serviceId == oKey.serviceId;
+ }
+
+ return false;
+ }
+
+ @Override
+ public int hashCode() {
+ return (int) (bundleId * 33 + serviceId);
+ }
+}
diff --git a/src/main/java/org/apache/sling/adapter/internal/AdapterFactoryDescriptorMap.java b/src/main/java/org/apache/sling/adapter/internal/AdapterFactoryDescriptorMap.java
new file mode 100644
index 0000000..cfa6e0c
--- /dev/null
+++ b/src/main/java/org/apache/sling/adapter/internal/AdapterFactoryDescriptorMap.java
@@ -0,0 +1,39 @@
+/*
+ * 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.adapter.internal;
+
+import java.util.TreeMap;
+
+/**
+ * The <code>AdapterFactoryDescriptorMap</code> is a sorted map of
+ * {@link AdapterFactoryDescriptor} instances indexed (and ordered) by their
+ * {@link AdapterFactoryDescriptorKey}. This map is used to organize the
+ * registered {@link org.apache.sling.api.adapter.AdapterFactory} services for
+ * a given adaptable type.
+ * <p>
+ * Each entry in the map is a {@link AdapterFactoryDescriptor} thus enabling the
+ * registration of multiple factories for the same (adaptable, adapter) type
+ * tuple. Of course only the first entry (this is the reason for having a sorted
+ * map) for such a given tuple is actually being used. If that first instance is
+ * removed the eventual second instance may actually be used instead.
+ */
+public class AdapterFactoryDescriptorMap extends
+ TreeMap<AdapterFactoryDescriptorKey, AdapterFactoryDescriptor> {
+
+}
diff --git a/src/main/java/org/apache/sling/adapter/internal/AdapterManagerImpl.java b/src/main/java/org/apache/sling/adapter/internal/AdapterManagerImpl.java
new file mode 100644
index 0000000..4be2807
--- /dev/null
+++ b/src/main/java/org/apache/sling/adapter/internal/AdapterManagerImpl.java
@@ -0,0 +1,427 @@
+/*
+ * 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.adapter.internal;
+
+import static org.apache.sling.api.adapter.AdapterFactory.ADAPTABLE_CLASSES;
+import static org.apache.sling.api.adapter.AdapterFactory.ADAPTER_CLASSES;
+
+import java.util.HashMap;
+import java.util.LinkedList;
+import java.util.List;
+import java.util.Map;
+
+import org.apache.sling.api.adapter.AdapterFactory;
+import org.apache.sling.api.adapter.AdapterManager;
+import org.apache.sling.commons.osgi.OsgiUtil;
+import org.osgi.framework.ServiceReference;
+import org.osgi.service.component.ComponentContext;
+import org.osgi.service.log.LogService;
+
+/**
+ * The <code>AdapterManagerImpl</code> class implements the
+ * {@link AdapterManager} interface and is registered as a service for that
+ * interface to be used by any clients.
+ *
+ * @scr.component metatype="no" immediate="true"
+ * @scr.property name="service.description" value="Sling Adapter Manager"
+ * @scr.property name="service.vendor" value="The Apache Software Foundation"
+ * @scr.service
+ * @scr.reference name="AdapterFactory"
+ * interface="org.apache.sling.api.adapter.AdapterFactory"
+ * cardinality="0..n" policy="dynamic"
+ */
+public class AdapterManagerImpl implements AdapterManager {
+
+ /**
+ * The singleton instance of this manager. This field is set when the
+ * instance is {@link #activate(ComponentContext) activated} and cleared
+ * when the instance is {@link #deactivate(ComponentContext) deactivated}.
+ */
+ private static AdapterManager INSTANCE;
+
+ /**
+ * Returns the instance of this class or <code>null</code> if no activate
+ * yet.
+ */
+ public static AdapterManager getInstance() {
+ return INSTANCE;
+ }
+
+ /** @scr.reference cardinality="0..1" policy="dynamic" */
+ private LogService log;
+
+ /** Whether to debug this class or not */
+ private boolean debug = false;
+
+ /**
+ * The OSGi <code>ComponentContext</code> to retrieve
+ * {@link AdapterFactory} service instances.
+ */
+ private ComponentContext context;
+
+ /**
+ * A list of {@link AdapterFactory} services bound to this manager before
+ * the manager has been activated. These bound services will be accessed as
+ * soon as the manager is being activated.
+ */
+ private List<ServiceReference> boundAdapterFactories = new LinkedList<ServiceReference>();
+
+ /**
+ * A map of {@link AdapterFactoryDescriptorMap} instances. The map is
+ * indexed by the fully qualified class names listed in the
+ * {@link AdapterFactory#ADAPTABLE_CLASSES} property of the
+ * {@link AdapterFactory} services.
+ *
+ * @see AdapterFactoryDescriptorMap
+ */
+ private Map<String, AdapterFactoryDescriptorMap> factories = new HashMap<String, AdapterFactoryDescriptorMap>();
+
+ /**
+ * Matrix of {@link AdapterFactory} instances primarily indexed by the fully
+ * qualified name of the class to be adapted and secondarily indexed by the
+ * fully qualified name of the class to adapt to (the target class).
+ * <p>
+ * This cache is built on demand by calling the
+ * {@link #getAdapterFactories(Class)} class. It is removed altogether
+ * whenever an adapter factory is registered on unregistered.
+ */
+ private Map<String, Map<String, AdapterFactory>> factoryCache;
+
+ // ---------- AdapterManager interface -------------------------------------
+
+ /**
+ * Returns the adapted <code>adaptable</code> or <code>null</code> if
+ * the object cannot be adapted.
+ */
+ public <AdapterType> AdapterType getAdapter(Object adaptable,
+ Class<AdapterType> type) {
+
+ // get the adapter factories for the type of adaptable object
+ Map<String, AdapterFactory> factories = getAdapterFactories(adaptable.getClass());
+
+ // get the factory for the target type
+ AdapterFactory factory = factories.get(type.getName());
+
+ // have the factory adapt the adaptable if the factory exists
+ if (factory != null) {
+ if (debug) {
+ log(LogService.LOG_DEBUG, "Using adapter factory " + factory
+ + " to map " + adaptable + " to " + type, null);
+ }
+
+ return factory.getAdapter(adaptable, type);
+ }
+
+ // no factory has been found, so we cannot adapt
+ if (debug) {
+ log(LogService.LOG_DEBUG, "No adapter factory found to map "
+ + adaptable + " to " + type, null);
+ }
+
+ return null;
+ }
+
+ // ----------- SCR integration ---------------------------------------------
+
+ protected synchronized void activate(ComponentContext context) {
+ this.context = context;
+
+ // register all adapter factories bound before activation
+ for (ServiceReference reference : boundAdapterFactories) {
+ registerAdapterFactory(context, reference);
+ }
+ boundAdapterFactories.clear();
+
+ // final "enable" this manager by setting the instance
+ // do not overwrite the field if already set (this is unexpected
+ // actually)
+ if (AdapterManagerImpl.INSTANCE == null) {
+ AdapterManagerImpl.INSTANCE = this;
+ } else {
+ log(LogService.LOG_WARNING,
+ "Not setting Instance field: Set to another manager "
+ + AdapterManagerImpl.INSTANCE, null);
+ }
+ }
+
+ /**
+ * @param context Not used
+ */
+ protected synchronized void deactivate(ComponentContext context) {
+ // "disable" the manager by clearing the instance
+ // do not clear the field if not set to this instance
+ if (AdapterManagerImpl.INSTANCE == this) {
+ AdapterManagerImpl.INSTANCE = null;
+ } else {
+ log(LogService.LOG_WARNING,
+ "Not clearing instance field: Set to another manager "
+ + AdapterManagerImpl.INSTANCE, null);
+ }
+
+ this.context = null;
+ }
+
+ protected synchronized void bindAdapterFactory(ServiceReference reference) {
+ if (context == null) {
+ boundAdapterFactories.add(reference);
+ } else {
+ registerAdapterFactory(context, reference);
+ }
+ }
+
+ protected synchronized void unbindAdapterFactory(ServiceReference reference) {
+ unregisterAdapterFactory(reference);
+ }
+
+ // ---------- unit testing stuff only --------------------------------------
+
+ /**
+ * Returns the active adapter factories of this manager.
+ * <p>
+ * <strong><em>THIS METHOD IS FOR UNIT TESTING ONLY. IT MAY BE REMOVED OR
+ * MODIFIED WITHOUT NOTICE.</em></strong>
+ */
+ Map<String, AdapterFactoryDescriptorMap> getFactories() {
+ return factories;
+ }
+
+ /**
+ * Returns the current adapter factory cache.
+ * <p>
+ * <strong><em>THIS METHOD IS FOR UNIT TESTING ONLY. IT MAY BE REMOVED OR
+ * MODIFIED WITHOUT NOTICE.</em></strong>
+ */
+ Map<String, Map<String, AdapterFactory>> getFactoryCache() {
+ return factoryCache;
+ }
+
+ // ---------- internal -----------------------------------------------------
+
+ private void log(int level, String message, Throwable t) {
+ LogService logger = this.log;
+ if (logger != null) {
+ logger.log(level, message, t);
+ } else {
+ System.out.println(message);
+ if (t != null) {
+ t.printStackTrace(System.out);
+ }
+ }
+ }
+
+ /**
+ * Unregisters the {@link AdapterFactory} referred to by the service
+ * <code>reference</code> from the registry.
+ */
+ private void registerAdapterFactory(ComponentContext context,
+ ServiceReference reference) {
+ String[] adaptables = OsgiUtil.toStringArray(reference.getProperty(ADAPTABLE_CLASSES));
+ String[] adapters = OsgiUtil.toStringArray(reference.getProperty(ADAPTER_CLASSES));
+
+ if (adaptables == null || adaptables.length == 0 || adapters == null
+ || adapters.length == 0) {
+ return;
+ }
+
+ AdapterFactory factory = (AdapterFactory) context.locateService(
+ "AdapterFactory", reference);
+
+ AdapterFactoryDescriptorKey factoryKey = new AdapterFactoryDescriptorKey(
+ reference);
+ AdapterFactoryDescriptor factoryDesc = new AdapterFactoryDescriptor(
+ factory, adapters);
+
+ synchronized (factories) {
+ for (String adaptable : adaptables) {
+ AdapterFactoryDescriptorMap adfMap = factories.get(adaptable);
+ if (adfMap == null) {
+ adfMap = new AdapterFactoryDescriptorMap();
+ factories.put(adaptable, adfMap);
+ }
+ adfMap.put(factoryKey, factoryDesc);
+ }
+ }
+
+ // clear the factory cache to force rebuild on next access
+ factoryCache = null;
+ }
+
+ /**
+ * Unregisters the {@link AdapterFactory} referred to by the service
+ * <code>reference</code> from the registry.
+ */
+ private void unregisterAdapterFactory(ServiceReference reference) {
+ boundAdapterFactories.remove(reference);
+
+ String[] adaptables = OsgiUtil.toStringArray(reference.getProperty(ADAPTABLE_CLASSES));
+
+ if (adaptables == null || adaptables.length == 0) {
+ return;
+ }
+
+ AdapterFactoryDescriptorKey factoryKey = new AdapterFactoryDescriptorKey(
+ reference);
+
+ boolean factoriesModified = false;
+ synchronized (factories) {
+ for (String adaptable : adaptables) {
+ AdapterFactoryDescriptorMap adfMap = factories.get(adaptable);
+ if (adfMap != null) {
+ factoriesModified |= (adfMap.remove(factoryKey) != null);
+ if (adfMap.isEmpty()) {
+ factories.remove(adaptable);
+ }
+ }
+ }
+ }
+
+ // only remove cache if some adapter factories have actually been
+ // removed
+ if (factoriesModified) {
+ factoryCache = null;
+ }
+ }
+
+ /**
+ * Returns a map of {@link AdapterFactory} instances for the given class to
+ * be adapted. The returned map is indexed by the fully qualified name of
+ * the target classes (to adapt to) registered.
+ *
+ * @param clazz The type of the object for which the registered adapter
+ * factories are requested
+ * @return The map of adapter factories. If there is no adapter factory
+ * registered for this type, the returned map is empty.
+ */
+ private Map<String, AdapterFactory> getAdapterFactories(Class<?> clazz) {
+ Map<String, Map<String, AdapterFactory>> cache = factoryCache;
+ if (cache == null) {
+ cache = new HashMap<String, Map<String, AdapterFactory>>();
+ factoryCache = cache;
+ }
+
+ synchronized (cache) {
+ return getAdapterFactories(clazz, cache);
+ }
+ }
+
+ /**
+ * Returns the map of adapter factories index by adapter (target) class name
+ * for the given adaptable <code>clazz</code>. If no adapter exists for
+ * the <code>clazz</code> and empty map is returned.
+ *
+ * @param clazz The adaptable <code>Class</code> for which to return the
+ * adapter factory map by target class name.
+ * @param cache The cache of already defined adapter factory mappings
+ * @return The map of adapter factories by target class name. The map may be
+ * empty if there is no adapter factory for the adaptable
+ * <code>clazz</code>.
+ */
+ private Map<String, AdapterFactory> getAdapterFactories(Class<?> clazz,
+ Map<String, Map<String, AdapterFactory>> cache) {
+
+ String className = clazz.getName();
+ Map<String, AdapterFactory> entry = cache.get(className);
+ if (entry == null) {
+ // create entry
+ entry = createAdapterFactoryMap(clazz, cache);
+ cache.put(className, entry);
+ }
+
+ return entry;
+ }
+
+ /**
+ * Creates a new target adapter factory map for the given <code>clazz</code>.
+ * First all factories defined to support the adaptable class by
+ * registration are taken. Next all factories for the implemented interfaces
+ * and finally all base class factories are copied. Later adapter factory
+ * entries do NOT overwrite earlier entries.
+ *
+ * @param clazz The adaptable <code>Class</code> for which to build the
+ * adapter factory map by target class name.
+ * @param cache The cache of already defined adapter factory mappings
+ * @return The map of adapter factories by target class name. The map may be
+ * empty if there is no adapter factory for the adaptable
+ * <code>clazz</code>.
+ */
+ private Map<String, AdapterFactory> createAdapterFactoryMap(Class<?> clazz,
+ Map<String, Map<String, AdapterFactory>> cache) {
+ Map<String, AdapterFactory> afm = new HashMap<String, AdapterFactory>();
+
+ // AdapterFactories for this class
+ AdapterFactoryDescriptorMap afdMap;
+ synchronized (factories) {
+ afdMap = factories.get(clazz.getName());
+ }
+ if (afdMap != null) {
+ for (AdapterFactoryDescriptor afd : afdMap.values()) {
+ String[] adapters = afd.getAdapters();
+ for (String adapter : adapters) {
+ if (!afm.containsKey(adapter)) {
+ afm.put(adapter, afd.getFactory());
+ }
+ }
+ }
+ }
+
+ // AdapterFactories for the interfaces
+ Class<?>[] interfaces = clazz.getInterfaces();
+ for (Class<?> iFace : interfaces) {
+ copyAdapterFactories(afm, iFace, cache);
+ }
+
+ // AdapterFactories for the super class
+ Class<?> superClazz = clazz.getSuperclass();
+ if (superClazz != null) {
+ copyAdapterFactories(afm, superClazz, cache);
+ }
+
+ return afm;
+ }
+
+ /**
+ * Copies all adapter factories for the given <code>clazz</code> from the
+ * <code>cache</code> to the <code>dest</code> map except for those
+ * factories whose target class already exists in the <code>dest</code>
+ * map.
+ *
+ * @param dest The map of target class name to adapter factory into which
+ * additional factories are copied. Existing factories are not
+ * replaced.
+ * @param clazz The adaptable class whose adapter factories are considered
+ * for adding into <code>dest</code>.
+ * @param cache The adapter factory cache providing the adapter factories
+ * for <code>clazz</code> to consider for copying into
+ * <code>dest</code>.
+ */
+ private void copyAdapterFactories(Map<String, AdapterFactory> dest,
+ Class<?> clazz, Map<String, Map<String, AdapterFactory>> cache) {
+
+ // get the adapter factories for the adaptable clazz
+ Map<String, AdapterFactory> scMap = getAdapterFactories(clazz, cache);
+
+ // for each target class copy the entry to dest if dest does
+ // not contain the target class already
+ for (Map.Entry<String, AdapterFactory> entry : scMap.entrySet()) {
+ if (!dest.containsKey(entry.getKey())) {
+ dest.put(entry.getKey(), entry.getValue());
+ }
+ }
+ }
+}
diff --git a/src/main/resources/META-INF/DISCLAIMER b/src/main/resources/META-INF/DISCLAIMER
new file mode 100644
index 0000000..90850c2
--- /dev/null
+++ b/src/main/resources/META-INF/DISCLAIMER
@@ -0,0 +1,7 @@
+Apache Sling is an effort undergoing incubation at The Apache Software Foundation (ASF),
+sponsored by the Apache Jackrabbit PMC. Incubation is required of all newly accepted
+projects until a further review indicates that the infrastructure, communications,
+and decision making process have stabilized in a manner consistent with other
+successful ASF projects. While incubation status is not necessarily a reflection of
+the completeness or stability of the code, it does indicate that the project has yet
+to be fully endorsed by the ASF.
\ No newline at end of file
diff --git a/src/main/resources/META-INF/LICENSE b/src/main/resources/META-INF/LICENSE
new file mode 100644
index 0000000..d645695
--- /dev/null
+++ b/src/main/resources/META-INF/LICENSE
@@ -0,0 +1,202 @@
+
+ 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/src/main/resources/META-INF/NOTICE b/src/main/resources/META-INF/NOTICE
new file mode 100644
index 0000000..5e52eca
--- /dev/null
+++ b/src/main/resources/META-INF/NOTICE
@@ -0,0 +1,8 @@
+Apache Sling Adapter Manager
+Copyright 2008-2009 The Apache Software Foundation
+
+Apache Sling is based on source code originally developed
+by Day Software (http://www.day.com/).
+
+This product includes software developed at
+The Apache Software Foundation (http://www.apache.org/).
diff --git a/src/test/java/org/apache/sling/adapter/internal/AdapterManagerTest.java b/src/test/java/org/apache/sling/adapter/internal/AdapterManagerTest.java
new file mode 100644
index 0000000..0e13738
--- /dev/null
+++ b/src/test/java/org/apache/sling/adapter/internal/AdapterManagerTest.java
@@ -0,0 +1,245 @@
+/*
+ * 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.adapter.internal;
+
+import java.util.Map;
+
+import junit.framework.TestCase;
+
+import org.apache.sling.adapter.SlingAdaptable;
+import org.apache.sling.adapter.mock.MockBundle;
+import org.apache.sling.adapter.mock.MockComponentContext;
+import org.apache.sling.adapter.mock.MockServiceReference;
+import org.apache.sling.api.adapter.AdapterFactory;
+import org.osgi.framework.Bundle;
+import org.osgi.framework.Constants;
+import org.osgi.service.component.ComponentContext;
+
+public class AdapterManagerTest extends TestCase {
+
+ private AdapterManagerImpl am;
+
+ @Override
+ protected void setUp() throws Exception {
+ super.setUp();
+
+ am = new AdapterManagerImpl();
+ }
+
+ @Override
+ protected void tearDown() throws Exception {
+ if (AdapterManagerImpl.getInstance() == am) {
+ am.deactivate(null); // not correct, but argument unused
+ }
+
+ super.tearDown();
+ }
+
+ public void testUnitialized() {
+ assertNotNull("AdapterFactoryDescriptors must not be null", am.getFactories());
+ assertTrue("AdapterFactoryDescriptors must be empty", am.getFactories().isEmpty());
+ assertNull("AdapterFactory cache must be null", am.getFactoryCache());
+ }
+
+ public void testInitialized() {
+ ComponentContext cc = new MockComponentContext();
+ am.activate(cc);
+
+ assertNotNull("AdapterFactoryDescriptors must not be null", am.getFactories());
+ assertTrue("AdapterFactoryDescriptors must be empty", am.getFactories().isEmpty());
+ assertNull("AdapterFactory cache must be null", am.getFactoryCache());
+ }
+
+ public void testBindBeforeActivate() {
+ Bundle bundle = new MockBundle(1L);
+ MockServiceReference ref = new MockServiceReference(bundle);
+ ref.setProperty(Constants.SERVICE_ID, 1L);
+ ref.setProperty(AdapterFactory.ADAPTABLE_CLASSES, new String[]{ TestSlingAdaptable.class.getName() });
+ ref.setProperty(AdapterFactory.ADAPTER_CLASSES, ITestAdapter.class.getName());
+ am.bindAdapterFactory(ref);
+
+ // no cache and no factories yet
+ assertNotNull("AdapterFactoryDescriptors must not be null", am.getFactories());
+ assertTrue("AdapterFactoryDescriptors must be empty", am.getFactories().isEmpty());
+ assertNull("AdapterFactory cache must be null", am.getFactoryCache());
+
+ // this should register the factory
+ ComponentContext cc = new MockComponentContext();
+ am.activate(cc);
+
+ // expect the factory, but cache is empty
+ assertNotNull("AdapterFactoryDescriptors must not be null", am.getFactories());
+ assertEquals("AdapterFactoryDescriptors must contain one entry", 1, am.getFactories().size());
+ assertNull("AdapterFactory cache must be null", am.getFactoryCache());
+ }
+
+ public void testBindAfterActivate() {
+ ComponentContext cc = new MockComponentContext();
+ am.activate(cc);
+
+ // no cache and no factories yet
+ assertNotNull("AdapterFactoryDescriptors must not be null", am.getFactories());
+ assertTrue("AdapterFactoryDescriptors must be empty", am.getFactories().isEmpty());
+ assertNull("AdapterFactory cache must be null", am.getFactoryCache());
+
+ Bundle bundle = new MockBundle(1L);
+ MockServiceReference ref = new MockServiceReference(bundle);
+ ref.setProperty(Constants.SERVICE_ID, 1L);
+ ref.setProperty(AdapterFactory.ADAPTABLE_CLASSES, new String[]{ TestSlingAdaptable.class.getName() });
+ ref.setProperty(AdapterFactory.ADAPTER_CLASSES, ITestAdapter.class.getName());
+ am.bindAdapterFactory(ref);
+
+ // expect the factory, but cache is empty
+ assertNotNull("AdapterFactoryDescriptors must not be null", am.getFactories());
+ assertEquals("AdapterFactoryDescriptors must contain one entry", 1, am.getFactories().size());
+ assertNull("AdapterFactory cache must be null", am.getFactoryCache());
+
+ Map<String, AdapterFactoryDescriptorMap> f = am.getFactories();
+ AdapterFactoryDescriptorMap afdm = f.get(TestSlingAdaptable.class.getName());
+ assertNotNull(afdm);
+
+ AdapterFactoryDescriptor afd = afdm.get(new AdapterFactoryDescriptorKey(ref));
+ assertNotNull(afd);
+ assertNotNull(afd.getFactory());
+ assertNotNull(afd.getAdapters());
+ assertEquals(1, afd.getAdapters().length);
+ assertEquals(ITestAdapter.class.getName(), afd.getAdapters()[0]);
+
+ assertNull(f.get(TestSlingAdaptable2.class.getName()));
+ }
+
+ public void testAdaptBase() {
+
+ ComponentContext cc = new MockComponentContext();
+ am.activate(cc);
+
+ TestSlingAdaptable data = new TestSlingAdaptable();
+ assertNull("Expect no adapter", am.getAdapter(data, ITestAdapter.class));
+
+ Bundle bundle = new MockBundle(1L);
+ MockServiceReference ref = new MockServiceReference(bundle);
+ ref.setProperty(Constants.SERVICE_ID, 1L);
+ ref.setProperty(AdapterFactory.ADAPTABLE_CLASSES, new String[]{ TestSlingAdaptable.class.getName() });
+ ref.setProperty(AdapterFactory.ADAPTER_CLASSES, ITestAdapter.class.getName());
+ am.bindAdapterFactory(ref);
+
+ Object adapter = am.getAdapter(data, ITestAdapter.class);
+ assertNotNull(adapter);
+ assertTrue(adapter instanceof ITestAdapter);
+ }
+
+ public void testAdaptExtended() {
+
+ ComponentContext cc = new MockComponentContext();
+ am.activate(cc);
+
+ TestSlingAdaptable2 data = new TestSlingAdaptable2();
+ assertNull("Expect no adapter", am.getAdapter(data, ITestAdapter.class));
+
+ Bundle bundle = new MockBundle(1L);
+ MockServiceReference ref = new MockServiceReference(bundle);
+ ref.setProperty(Constants.SERVICE_ID, 1L);
+ ref.setProperty(AdapterFactory.ADAPTABLE_CLASSES, new String[]{ TestSlingAdaptable.class.getName() });
+ ref.setProperty(AdapterFactory.ADAPTER_CLASSES, ITestAdapter.class.getName());
+ am.bindAdapterFactory(ref);
+
+ Object adapter = am.getAdapter(data, ITestAdapter.class);
+ assertNotNull(adapter);
+ assertTrue(adapter instanceof ITestAdapter);
+ }
+
+ public void testAdaptBase2() {
+
+ ComponentContext cc = new MockComponentContext();
+ am.activate(cc);
+
+ TestSlingAdaptable data = new TestSlingAdaptable();
+ assertNull("Expect no adapter", am.getAdapter(data, ITestAdapter.class));
+
+ Bundle bundle = new MockBundle(1L);
+ MockServiceReference ref = new MockServiceReference(bundle);
+ ref.setProperty(Constants.SERVICE_ID, 1L);
+ ref.setProperty(AdapterFactory.ADAPTABLE_CLASSES, new String[]{ TestSlingAdaptable.class.getName() });
+ ref.setProperty(AdapterFactory.ADAPTER_CLASSES, ITestAdapter.class.getName());
+ am.bindAdapterFactory(ref);
+
+ ref = new MockServiceReference(bundle);
+ ref.setProperty(Constants.SERVICE_ID, 2L);
+ ref.setProperty(AdapterFactory.ADAPTABLE_CLASSES, new String[]{ TestSlingAdaptable2.class.getName() });
+ ref.setProperty(AdapterFactory.ADAPTER_CLASSES, TestAdapter.class.getName());
+ am.bindAdapterFactory(ref);
+
+ Object adapter = am.getAdapter(data, ITestAdapter.class);
+ assertNotNull(adapter);
+ assertTrue(adapter instanceof ITestAdapter);
+ }
+
+ public void testAdaptExtended2() {
+
+ ComponentContext cc = new MockComponentContext();
+ am.activate(cc);
+
+ Bundle bundle = new MockBundle(1L);
+ MockServiceReference ref = new MockServiceReference(bundle);
+ ref.setProperty(Constants.SERVICE_ID, 1L);
+ ref.setProperty(AdapterFactory.ADAPTABLE_CLASSES, new String[]{ TestSlingAdaptable.class.getName() });
+ ref.setProperty(AdapterFactory.ADAPTER_CLASSES, ITestAdapter.class.getName());
+ am.bindAdapterFactory(ref);
+
+ ref = new MockServiceReference(bundle);
+ ref.setProperty(Constants.SERVICE_ID, 2L);
+ ref.setProperty(AdapterFactory.ADAPTABLE_CLASSES, new String[]{ TestSlingAdaptable2.class.getName() });
+ ref.setProperty(AdapterFactory.ADAPTER_CLASSES, TestAdapter.class.getName());
+ am.bindAdapterFactory(ref);
+
+ TestSlingAdaptable data = new TestSlingAdaptable();
+ Object adapter = am.getAdapter(data, ITestAdapter.class);
+ assertNotNull(adapter);
+ assertTrue(adapter instanceof ITestAdapter);
+ adapter = am.getAdapter(data, TestAdapter.class);
+ assertNull(adapter);
+
+ TestSlingAdaptable2 data2 = new TestSlingAdaptable2();
+ adapter = am.getAdapter(data2, ITestAdapter.class);
+ assertNotNull(adapter);
+ assertTrue(adapter instanceof ITestAdapter);
+ adapter = am.getAdapter(data2, TestAdapter.class);
+ assertNotNull(adapter);
+ assertTrue(adapter instanceof TestAdapter);
+ }
+
+ //---------- Test Adaptable and Adapter Classes ---------------------------
+
+ public static class TestSlingAdaptable extends SlingAdaptable {
+
+ }
+
+ public static class TestSlingAdaptable2 extends TestSlingAdaptable {
+
+ }
+
+ public static interface ITestAdapter {
+
+ }
+
+ public static class TestAdapter {
+
+ }
+
+}
diff --git a/src/test/java/org/apache/sling/adapter/mock/MockAdapterFactory.java b/src/test/java/org/apache/sling/adapter/mock/MockAdapterFactory.java
new file mode 100644
index 0000000..f4f403c
--- /dev/null
+++ b/src/test/java/org/apache/sling/adapter/mock/MockAdapterFactory.java
@@ -0,0 +1,53 @@
+/*
+ * 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.adapter.mock;
+
+import java.lang.reflect.InvocationHandler;
+import java.lang.reflect.Method;
+import java.lang.reflect.Proxy;
+
+import org.apache.sling.api.adapter.AdapterFactory;
+
+public class MockAdapterFactory implements AdapterFactory {
+
+ private static final InvocationHandler NOP_INVOCATION_HANDLER = new InvocationHandler() {
+ public Object invoke(Object proxy, Method method, Object[] args)
+ throws Throwable {
+ return null;
+ }
+ };
+
+ @SuppressWarnings("unchecked")
+ public <AdapterType> AdapterType getAdapter(Object adaptable,
+ Class<AdapterType> type) {
+
+ try {
+ if (type.isInterface()) {
+ return (AdapterType) Proxy.newProxyInstance(type.getClassLoader(),
+ new Class[] { type }, NOP_INVOCATION_HANDLER);
+ }
+
+ return type.newInstance();
+ } catch (Exception e) {
+ // ignore
+ }
+
+ return null;
+ }
+}
diff --git a/src/test/java/org/apache/sling/adapter/mock/MockBundle.java b/src/test/java/org/apache/sling/adapter/mock/MockBundle.java
new file mode 100644
index 0000000..137cfc0
--- /dev/null
+++ b/src/test/java/org/apache/sling/adapter/mock/MockBundle.java
@@ -0,0 +1,133 @@
+/*
+ * 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.adapter.mock;
+
+import java.io.InputStream;
+import java.net.URL;
+import java.util.Dictionary;
+import java.util.Enumeration;
+
+import org.osgi.framework.Bundle;
+import org.osgi.framework.BundleContext;
+import org.osgi.framework.BundleException;
+import org.osgi.framework.ServiceReference;
+
+public class MockBundle implements Bundle {
+
+ private long bundleId;
+
+ public MockBundle(long bundleId) {
+ this.bundleId = bundleId;
+ }
+
+ public long getBundleId() {
+ return bundleId;
+ }
+
+ public Enumeration<?> findEntries(String path, String filePattern,
+ boolean recurse) {
+ return null;
+ }
+
+ public URL getEntry(String name) {
+ return null;
+ }
+
+ public Enumeration<?> getEntryPaths(String path) {
+ return null;
+ }
+
+ public Dictionary<?, ?> getHeaders() {
+ return null;
+ }
+
+ public Dictionary<?, ?> getHeaders(String locale) {
+ return null;
+ }
+
+ public long getLastModified() {
+ return 0;
+ }
+
+ public String getLocation() {
+ return null;
+ }
+
+ public ServiceReference[] getRegisteredServices() {
+ return null;
+ }
+
+ public URL getResource(String name) {
+ return null;
+ }
+
+ public Enumeration<?> getResources(String name) {
+ return null;
+ }
+
+ public ServiceReference[] getServicesInUse() {
+ return null;
+ }
+
+ public int getState() {
+ return 0;
+ }
+
+ public String getSymbolicName() {
+ return null;
+ }
+
+ public boolean hasPermission(Object permission) {
+ return false;
+ }
+
+ public Class<?> loadClass(String name) throws ClassNotFoundException {
+ throw new ClassNotFoundException(name);
+ }
+
+ public void start() {
+
+ }
+
+ public void stop() {
+
+ }
+
+ public void uninstall() {
+
+ }
+
+ public void update() {
+
+ }
+
+ public void update(InputStream in) {
+
+ }
+
+ public BundleContext getBundleContext() {
+ return null;
+ }
+
+ public void start(int options) throws BundleException {
+ }
+
+ public void stop(int options) throws BundleException {
+ }
+}
diff --git a/src/test/java/org/apache/sling/adapter/mock/MockComponentContext.java b/src/test/java/org/apache/sling/adapter/mock/MockComponentContext.java
new file mode 100644
index 0000000..d822e1f
--- /dev/null
+++ b/src/test/java/org/apache/sling/adapter/mock/MockComponentContext.java
@@ -0,0 +1,79 @@
+/*
+ * 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.adapter.mock;
+
+import java.util.Dictionary;
+import java.util.HashMap;
+import java.util.Map;
+
+import org.apache.sling.api.adapter.AdapterFactory;
+import org.osgi.framework.Bundle;
+import org.osgi.framework.BundleContext;
+import org.osgi.framework.ServiceReference;
+import org.osgi.service.component.ComponentContext;
+import org.osgi.service.component.ComponentInstance;
+
+public class MockComponentContext implements ComponentContext {
+
+ private Map<ServiceReference, AdapterFactory> services = new HashMap<ServiceReference, AdapterFactory>();
+
+ public Object locateService(String name, ServiceReference reference) {
+ AdapterFactory af = services.get(reference);
+ if (af == null) {
+ af = new MockAdapterFactory();
+ services.put(reference, af);
+ }
+ return af;
+ }
+
+ public void disableComponent(String name) {
+ }
+
+ public void enableComponent(String name) {
+ }
+
+ public BundleContext getBundleContext() {
+ return null;
+ }
+
+ public ComponentInstance getComponentInstance() {
+ return null;
+ }
+
+ public Dictionary<?, ?> getProperties() {
+ return null;
+ }
+
+ public ServiceReference getServiceReference() {
+ return null;
+ }
+
+ public Bundle getUsingBundle() {
+ return null;
+ }
+
+ public Object locateService(String name) {
+ return null;
+ }
+
+ public Object[] locateServices(String name) {
+ return null;
+ }
+
+}
diff --git a/src/test/java/org/apache/sling/adapter/mock/MockServiceReference.java b/src/test/java/org/apache/sling/adapter/mock/MockServiceReference.java
new file mode 100644
index 0000000..93da985
--- /dev/null
+++ b/src/test/java/org/apache/sling/adapter/mock/MockServiceReference.java
@@ -0,0 +1,65 @@
+/*
+ * 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.adapter.mock;
+
+import java.util.Collections;
+import java.util.Dictionary;
+import java.util.Hashtable;
+
+import org.osgi.framework.Bundle;
+import org.osgi.framework.ServiceReference;
+
+public class MockServiceReference implements ServiceReference {
+
+ private Bundle bundle;
+ private Dictionary<String, Object> props;
+
+ public MockServiceReference(Bundle bundle) {
+ this.bundle = bundle;
+ this.props = new Hashtable<String, Object>();
+ }
+
+ public Bundle getBundle() {
+ return bundle;
+ }
+
+ public void setProperty(String key, Object value) {
+ props.put(key, value);
+ }
+
+ public Object getProperty(String key) {
+ return props.get(key);
+ }
+
+ public String[] getPropertyKeys() {
+ return Collections.list(props.keys()).toArray(new String[props.size()]);
+ }
+
+ public Bundle[] getUsingBundles() {
+ return null;
+ }
+
+ public boolean isAssignableTo(Bundle bundle, String className) {
+ return false;
+ }
+
+ public int compareTo(Object reference) {
+ return 0;
+ }
+}