backup old dm 3.2.0 to my sandbox before moving new dm4 to trunk.
git-svn-id: https://svn.apache.org/repos/asf/felix/trunk@1663055 13f79535-47bb-0310-9956-ffa450edef68
diff --git a/dependencymanager/TODO b/dependencymanager/TODO
deleted file mode 100644
index da37b21..0000000
--- a/dependencymanager/TODO
+++ /dev/null
@@ -1,5 +0,0 @@
-- test:
-
- * add test for compatibility library
-
-
diff --git a/dependencymanager/annotation/DEPENDENCIES b/dependencymanager/annotation/DEPENDENCIES
deleted file mode 100644
index daae36b..0000000
--- a/dependencymanager/annotation/DEPENDENCIES
+++ /dev/null
@@ -1,29 +0,0 @@
-Apache Felix Dependency Manager Annotation
-Copyright 2011-2014 The Apache Software Foundation
-
-This software was developed at the Apache Software Foundation
-(http://www.apache.org) and may have dependencies on other
-Apache software licensed under Apache License 2.0.
-
-I. Included Third-Party Software
-
-This product includes software from http://www.json.org.
-Copyright (c) 2002 JSON.org
-Licensed under the JSON License
-
-II. Used Third-Party Software
-
-This product uses software developed at
-The OSGi Alliance (http://www.osgi.org/).
-Copyright (c) OSGi Alliance (2000, 2014).
-Licensed under the Apache License 2.0.
-
-This product uses software developed by Peter Kriens
-(http://www.aqute.biz/Code/Bnd)
-Copyright 2006-2014 aQute, All rights reserved
-Licensed under the Apache License 2.0.
-
-III. Overall License Summary
-
-- Apache License 2.0
-- JSON License
diff --git a/dependencymanager/annotation/LICENSE b/dependencymanager/annotation/LICENSE
deleted file mode 100644
index d645695..0000000
--- a/dependencymanager/annotation/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/dependencymanager/annotation/LICENSE.json b/dependencymanager/annotation/LICENSE.json
deleted file mode 100644
index 68d19c8..0000000
--- a/dependencymanager/annotation/LICENSE.json
+++ /dev/null
@@ -1,21 +0,0 @@
-Copyright (c) 2002 JSON.org
-
-Permission is hereby granted, free of charge, to any person obtaining a copy
-of this software and associated documentation files (the "Software"), to deal
-in the Software without restriction, including without limitation the rights
-to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
-copies of the Software, and to permit persons to whom the Software is
-furnished to do so, subject to the following conditions:
-
-The above copyright notice and this permission notice shall be included in
-all copies or substantial portions of the Software.
-
-The Software shall be used for Good, not Evil.
-
-THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
-IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
-FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
-AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
-LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
-OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
-SOFTWARE.
\ No newline at end of file
diff --git a/dependencymanager/annotation/NOTICE b/dependencymanager/annotation/NOTICE
deleted file mode 100644
index 3eede0f..0000000
--- a/dependencymanager/annotation/NOTICE
+++ /dev/null
@@ -1,10 +0,0 @@
-Apache Felix Dependency Manager Annotation
-Copyright 2011-2014 The Apache Software Foundation
-
-This product includes software developed at
-The Apache Software Foundation (http://www.apache.org/).
-Licensed under the Apache License 2.0.
-
-This product includes software from http://www.json.org.
-Copyright (c) 2002 JSON.org
-Licensed under the JSON License
diff --git a/dependencymanager/annotation/doc/changelog.txt b/dependencymanager/annotation/doc/changelog.txt
deleted file mode 100644
index 2943118..0000000
--- a/dependencymanager/annotation/doc/changelog.txt
+++ /dev/null
@@ -1,34 +0,0 @@
-Release 3.2.0
--------------
-
-** Bug
-
- * [FELIX-3873] - Make the reference to json.org consistent in DM artifacts
-
-** Improvement
-
- * [FELIX-3996] - Upgrade to latest bnd version
- * [FELIX-4357] - Support types beside String/String[] in @Property annotation.
-
-Release 3.1.0
--------------
-
-** Bug
-
-** Improvement
-
- * Removed changelog.txt from root of project
- * [FELIX-2954] - annotated component factory does not allow to provide a component instance explicitly
- * [FELIX-2956] - json should be embedded in the annotation scanner plugin
- * [FELIX-2966] - Annotations should automatically generate Import-Service/Export-Service headers
- * [FELIX-2965] - Annotations should allow to enable or disable auto-configuration mode.
- * [FELIX-3863] - Generate DependencyManager Annotation MetaData In Project Folder
- * [FELIX-3865] - Update DependencyManager annotation plugin with latest bndlb
- * [FELIX-3866] - Added support for swap attribute in AspectService and AdpaterService annotations.
-
-Initial Release 3.0.0
----------------------
-
-** Bug
-
-** Improvement
diff --git a/dependencymanager/annotation/pom.xml b/dependencymanager/annotation/pom.xml
deleted file mode 100644
index daf0869..0000000
--- a/dependencymanager/annotation/pom.xml
+++ /dev/null
@@ -1,114 +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/maven-v4_0_0.xsd">
- <modelVersion>4.0.0</modelVersion>
- <parent>
- <groupId>org.apache.felix</groupId>
- <artifactId>felix-parent</artifactId>
- <version>1.2.0</version>
- <relativePath>../../pom/pom.xml</relativePath>
- </parent>
- <properties>
- <osgi.version>4.2.0</osgi.version>
- </properties>
- <name>Apache Felix Dependency Manager Annotation</name>
- <description>Dependency Manager Annotation API and corresponding scanner plugins</description>
- <artifactId>org.apache.felix.dependencymanager.annotation</artifactId>
- <version>3.2.1-SNAPSHOT</version>
- <packaging>maven-plugin</packaging>
-
- <scm>
- <connection>scm:svn:http://svn.apache.org/repos/asf/felix/trunk/dependencymanager/annotation</connection>
- <developerConnection>scm:svn:https://svn.apache.org/repos/asf/felix/trunk/dependencymanager/annotation</developerConnection>
- <url>http://svn.apache.org/repos/asf/felix/dependencymanager/annotation</url>
- </scm>
-
- <dependencies>
- <dependency>
- <groupId>org.osgi</groupId>
- <artifactId>org.osgi.core</artifactId>
- <version>${osgi.version}</version>
- </dependency>
- <dependency>
- <groupId>biz.aQute.bnd</groupId>
- <artifactId>bndlib</artifactId>
- <version>2.3.0</version>
- </dependency>
- <dependency>
- <groupId>org.apache.maven</groupId>
- <artifactId>maven-project</artifactId>
- <version>2.0.7</version>
- </dependency>
- <dependency>
- <groupId>org.apache.maven</groupId>
- <artifactId>maven-artifact</artifactId>
- <version>2.0.7</version>
- </dependency>
- <dependency>
- <groupId>org.apache.maven</groupId>
- <artifactId>maven-plugin-api</artifactId>
- <version>2.0</version>
- </dependency>
- <dependency>
- <groupId>org.json</groupId>
- <artifactId>json</artifactId>
- <version>20070829</version>
- </dependency>
- </dependencies>
- <build>
- <resources>
- <resource>
- <directory>.</directory>
- <targetPath>META-INF</targetPath>
- <includes>
- <include>LICENSE*</include>
- <include>NOTICE*</include>
- <include>DEPENDENCIES*</include>
- <include>*.txt</include>
- </includes>
- </resource>
- </resources>
- <plugins>
- <plugin>
- <groupId>org.apache.maven.plugins</groupId>
- <artifactId>maven-compiler-plugin</artifactId>
- <configuration>
- <source>1.5</source>
- <target>1.5</target>
- </configuration>
- </plugin>
- <plugin>
- <artifactId>maven-dependency-plugin</artifactId>
- <executions>
- <execution>
- <goals>
- <goal>unpack-dependencies</goal>
- </goals>
- <configuration>
- <includeArtifactIds>
- json
- </includeArtifactIds>
- <outputDirectory>
- ${project.build.outputDirectory}
- </outputDirectory>
- </configuration>
- </execution>
- </executions>
- </plugin>
- </plugins>
- </build>
-</project>
diff --git a/dependencymanager/annotation/src/main/java/org/apache/felix/dm/annotation/api/AdapterService.java b/dependencymanager/annotation/src/main/java/org/apache/felix/dm/annotation/api/AdapterService.java
deleted file mode 100644
index b02bee0..0000000
--- a/dependencymanager/annotation/src/main/java/org/apache/felix/dm/annotation/api/AdapterService.java
+++ /dev/null
@@ -1,118 +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.felix.dm.annotation.api;
-
-import java.lang.annotation.ElementType;
-import java.lang.annotation.Retention;
-import java.lang.annotation.RetentionPolicy;
-import java.lang.annotation.Target;
-
-/**
- * Annotates an Adapater service. Adapters, like {@link AspectService}, are used to "extend"
- * existing services, and can publish different services based on the existing one.
- * An example would be implementing a management interface for an existing service, etc ....
- * <p>When you annotate an adapter class with the <code>@AdapterService</code> annotation, it will be applied
- * to any service that matches the implemented interface and filter. The adapter will be registered
- * with the specified interface and existing properties from the original service plus any extra
- * properties you supply here. If you declare the original service as a member it will be injected.
- *
- * <h3>Usage Examples</h3>
- *
- * <p> Here, the AdapterService is registered into the OSGI registry each time an AdapteeService
- * is found from the registry. The AdapterImpl class adapts the AdapteeService to the AdapterService.
- * The AdapterService will also have a service property (param=value), and will also include eventual
- * service properties found from the AdapteeService:<p>
- * <blockquote>
- * <pre>
- *
- * @AdapterService(adapteeService = AdapteeService.class, properties={@Property(name="param", value="value")})
- * class AdapterImpl implements AdapterService {
- * // The service we are adapting (injected by reflection)
- * protected AdapteeService adaptee;
- *
- * public void doWork() {
- * adaptee.mehod1();
- * adaptee.method2();
- * }
- * }
- * </pre>
- * </blockquote>
- *
- * @author <a href="mailto:dev@felix.apache.org">Felix Project Team</a>
- */
-@Retention(RetentionPolicy.CLASS)
-@Target(ElementType.TYPE)
-public @interface AdapterService
-{
- /**
- * Sets the adapter service interface(s). By default, the directly implemented interface(s) is (are) used.
- */
- Class<?>[] provides() default {};
-
- /**
- * Sets some additional properties to use with the adapter service registration. By default,
- * the adapter will inherit all adaptee service properties.
- */
- Property[] properties() default {};
-
- /**
- * Sets the adaptee service interface this adapter is applying to.
- */
- Class<?> adapteeService();
-
- /**
- * Sets the filter condition to use with the adapted service interface.
- */
- String adapteeFilter() default "";
-
- /**
- * Sets the static method used to create the adapter service implementation instance.
- * By default, the default constructor of the annotated class is used.
- */
- String factoryMethod() default "";
-
- /**
- * Sets the field name where to inject the original service. By default, the original service is injected
- * in any attributes in the aspect implementation that are of the same type as the aspect interface.
- */
- String field() default "";
-
- /**
- * The callback method to be invoked when the original service is available. This attribute can't be mixed with
- * the field attribute.
- */
- String added() default "";
-
- /**
- * The callback method to be invoked when the original service properties have changed. When this attribute is used,
- * then the added attribute must also be used.
- */
- String changed() default "";
-
- /**
- * name of the callback method to invoke on swap.
- */
- String swap() default "";
-
- /**
- * The callback method to invoke when the service is lost. When this attribute is used, then the added attribute
- * must also be used.
- */
- String removed() default "";
-}
diff --git a/dependencymanager/annotation/src/main/java/org/apache/felix/dm/annotation/api/AspectService.java b/dependencymanager/annotation/src/main/java/org/apache/felix/dm/annotation/api/AspectService.java
deleted file mode 100644
index 600ba85..0000000
--- a/dependencymanager/annotation/src/main/java/org/apache/felix/dm/annotation/api/AspectService.java
+++ /dev/null
@@ -1,120 +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.felix.dm.annotation.api;
-
-import java.lang.annotation.ElementType;
-import java.lang.annotation.Retention;
-import java.lang.annotation.RetentionPolicy;
-import java.lang.annotation.Target;
-
-/**
- * Annotates an Aspect service. Aspects allow you to define an interceptor, or chain of interceptors
- * for a service (to add features like caching or logging, etc ...). The dependency manager intercepts
- * the original service, and allows you to execute some code before invoking the original service ...
- * The aspect will be applied to any service that matches the specified interface and filter and
- * will be registered with the same interface and properties as the original service, plus any
- * extra properties you supply here. It will also inherit all dependencies,
- * and if you declare the original service as a member it will be injected.<p>
- *
- * <h3>Usage Examples</h3>
- *
- * <p> Here, the AspectService is registered into the OSGI registry each time an InterceptedService
- * is found from the registry. The AspectService class intercepts the InterceptedService, and decorates
- * its "doWork()" method. This aspect uses a rank with value "10", meaning that it will intercept some
- * other eventual aspects with lower ranks. The Aspect also uses a service property (param=value), and
- * include eventual service properties found from the InterceptedService:<p>
- * <blockquote>
- * <pre>
- *
- * @AspectService(ranking=10), properties={@Property(name="param", value="value")})
- * class AspectService implements InterceptedService {
- * // The service we are intercepting (injected by reflection)
- * protected InterceptedService intercepted;
- *
- * public void doWork() {
- * intercepted.doWork();
- * }
- * }
- * </pre>
- * </blockquote>
- *
- * @author <a href="mailto:dev@felix.apache.org">Felix Project Team</a>
- */
-@Retention(RetentionPolicy.CLASS)
-@Target(ElementType.TYPE)
-public @interface AspectService
-{
- /**
- * Sets the service interface to apply the aspect to. By default, the directly implemented interface is used.
- */
- Class<?> service() default Object.class;
-
- /**
- * Sets the filter condition to use with the service interface this aspect is applying to.
- */
- String filter() default "";
-
- /**
- * Sets Additional properties to use with the aspect service registration
- */
- Property[] properties() default {};
-
- /**
- * Sets the ranking of this aspect. Since aspects are chained, the ranking defines the order in which they are chained.
- * Chain ranking is implemented as a service ranking so service lookups automatically retrieve the top of the
- * chain.
- */
- int ranking();
-
- /**
- * Sets the field name where to inject the original service. By default, the original service is injected
- * in any attributes in the aspect implementation that are of the same type as the aspect interface.
- */
- String field() default "";
-
- /**
- * The callback method to be invoked when the original service is available. This attribute can't be mixed with
- * the field attribute.
- */
- String added() default "";
-
- /**
- * The callback method to be invoked when the original service properties have changed. When this attribute is used,
- * then the added attribute must also be used.
- */
- String changed() default "";
-
- /**
- * The callback method to invoke when the service is lost. When this attribute is used, then the added attribute
- * must also be used.
- */
- String removed() default "";
-
- /**
- * name of the callback method to invoke on swap.
- */
- String swap() default "";
-
- /**
- * Sets the static method used to create the AspectService implementation instance. The
- * default constructor of the annotated class is used. The factoryMethod can be used to provide a specific
- * aspect implements, like a DynamicProxy.
- */
- String factoryMethod() default "";
-}
diff --git a/dependencymanager/annotation/src/main/java/org/apache/felix/dm/annotation/api/BundleAdapterService.java b/dependencymanager/annotation/src/main/java/org/apache/felix/dm/annotation/api/BundleAdapterService.java
deleted file mode 100644
index 7c0d5e9..0000000
--- a/dependencymanager/annotation/src/main/java/org/apache/felix/dm/annotation/api/BundleAdapterService.java
+++ /dev/null
@@ -1,96 +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.felix.dm.annotation.api;
-
-import java.lang.annotation.ElementType;
-import java.lang.annotation.Retention;
-import java.lang.annotation.RetentionPolicy;
-import java.lang.annotation.Target;
-
-import org.osgi.framework.Bundle;
-
-/**
- * Annotates a bundle adapter service class. Bundle adapters are similar to {@link AdapterService},
- * but instead of adapting a service, they adapt a bundle with a certain set of states (STARTED|INSTALLED|...),
- * and provide a service on top of it. <p>
- * The bundle adapter will be applied to any bundle that matches the specified bundle state mask and
- * filter conditions, which may match some of the bundle OSGi manifest headers. For each matching
- * bundle an adapter will be created based on the adapter implementation class. The adapter will be
- * registered with the specified interface and with service properties found from the original bundle
- * OSGi manifest headers plus any extra properties you supply here.
- * If you declare the original bundle as a member it will be injected.
- *
- * <h3>Usage Examples</h3>
- *
- * <p> In the following example, a "VideoPlayer" Service is registered into the OSGi registry each time
- * an active bundle containing a "Video-Path" manifest header is detected:
- * <p>
- * <blockquote>
- * <pre>
- * @BundleAdapterService(filter = "(Video-Path=*)", stateMask = Bundle.ACTIVE, propagate=true)
- * public class VideoPlayerImpl implements VideoPlayer {
- * Bundle bundle; // Injected by reflection
- *
- * void play() {
- * URL mpegFile = bundle.getEntry(bundle.getHeaders().get("Video-Path"));
- * // play the video provided by the bundle ...
- * }
- *
- * void stop() {}
- * }
- * </pre>
- * </blockquote>
- *
- * @author <a href="mailto:dev@felix.apache.org">Felix Project Team</a>
- */
-public @Retention(RetentionPolicy.CLASS)
-@Target(ElementType.TYPE)
-@interface BundleAdapterService
-{
- /**
- * The interface(s) to use when registering adapters. By default, the interface(s) directly implemented
- * by the annotated class is (are) used.
- */
- Class<?>[] provides() default {};
-
- /**
- * Additional properties to use with the service registration
- */
- Property[] properties() default {};
-
- /**
- * The filter used to match a given bundle.
- */
- String filter();
-
- /**
- * the bundle state mask to apply
- */
- int stateMask() default Bundle.INSTALLED | Bundle.RESOLVED | Bundle.ACTIVE;
-
- /**
- * Specifies if manifest headers from the bundle should be propagated to the service properties.
- */
- boolean propagate() default true;
-
- /**
- * Sets the static method used to create the BundleAdapterService implementation instance.
- */
- String factoryMethod() default "";
-}
diff --git a/dependencymanager/annotation/src/main/java/org/apache/felix/dm/annotation/api/BundleDependency.java b/dependencymanager/annotation/src/main/java/org/apache/felix/dm/annotation/api/BundleDependency.java
deleted file mode 100644
index 87d8204..0000000
--- a/dependencymanager/annotation/src/main/java/org/apache/felix/dm/annotation/api/BundleDependency.java
+++ /dev/null
@@ -1,107 +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.felix.dm.annotation.api;
-
-import java.lang.annotation.ElementType;
-import java.lang.annotation.Retention;
-import java.lang.annotation.RetentionPolicy;
-import java.lang.annotation.Target;
-
-import org.osgi.framework.Bundle;
-
-/**
- * Annotates a class or method for a bundle dependency. A bundle dependency allows you to
- * depend on a bundle in a certain set of states (INSTALLED|RESOLVED|STARTED|...), as
- * indicated by a state mask. You can also use a filter condition that is matched against
- * all manifest entries. When applied on a class field, optional unavailable dependencies
- * are injected with a NullObject.
- *
- * <h3>Usage Examples</h3>
- *
- * <p> In the following example, the "SCR" Component allows to track
- * all bundles containing a specific "Service-Component" OSGi header, in order to load
- * and manage all Declarative Service components specified in the SCR xml documents referenced by the header:
- * <p>
- * <blockquote>
- * <pre>
- * @Component
- * public class SCR {
- * @BundleDependency(required = false,
- * removed = "unloadServiceComponents",
- * filter = "(Service-Component=*)"
- * stateMask = Bundle.ACTIVE)
- * void loadServiceComponents(Bundle b) {
- * String descriptorPaths = (String) b.getHeaders().get("Service-Component");
- * // load all service component specified in the XML descriptorPaths files ...
- * }
- *
- * void unloadServiceComponents(Bundle b) {
- * // unload all service component we loaded from our "loadServiceComponents" method.
- * }
- * }
- * </pre>
- * </blockquote>
- *
- * @author <a href="mailto:dev@felix.apache.org">Felix Project Team</a>
- */
-@Retention(RetentionPolicy.CLASS)
-@Target(ElementType.METHOD)
-public @interface BundleDependency
-{
- /**
- * Returns the callback method to be invoked when the service have changed.
- */
- String changed() default "";
-
- /**
- * Returns the callback method to invoke when the service is lost.
- */
- String removed() default "";
-
- /**
- * Returns whether the dependency is required or not.
- */
- boolean required() default true;
-
- /**
- * Returns the filter dependency
- */
- String filter() default "";
-
- /**
- * Returns the bundle state mask
- */
- int stateMask() default Bundle.INSTALLED | Bundle.RESOLVED | Bundle.ACTIVE;
-
- /**
- * Specifies if the manifest headers from the bundle should be propagated to
- * the service properties.
- */
- boolean propagate() default false;
-
- /**
- * The name used when dynamically configuring this dependency from the init method.
- * Specifying this attribute allows to dynamically configure the dependency
- * <code>filter</code> and <code>required</code> flag from the Service's init method.
- * All unnamed dependencies will be injected before the init() method; so from the init() method, you can
- * then pick up whatever information needed from already injected (unnamed) dependencies, and configure dynamically
- * your named dependencies, which will then be calculated once the init() method returns.
- */
- String name() default "";
-}
diff --git a/dependencymanager/annotation/src/main/java/org/apache/felix/dm/annotation/api/Component.java b/dependencymanager/annotation/src/main/java/org/apache/felix/dm/annotation/api/Component.java
deleted file mode 100644
index d756b31..0000000
--- a/dependencymanager/annotation/src/main/java/org/apache/felix/dm/annotation/api/Component.java
+++ /dev/null
@@ -1,202 +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.felix.dm.annotation.api;
-
-import java.lang.annotation.ElementType;
-import java.lang.annotation.Retention;
-import java.lang.annotation.RetentionPolicy;
-import java.lang.annotation.Target;
-
-/**
- * Annotates an OSGi Component class with its dependencies. Components are the main building
- * blocks for OSGi applications. They can publish themselves as a service, and/or they can have
- * dependencies. These dependencies will influence their life cycle as component will only be
- * activated when all required dependencies are available.
- * By default, all directly implemented interfaces are registered into the OSGi registry,
- * and the component is instantiated automatically, when the component bundle is started and
- * when the component dependencies are available. If you need to take control of when and how
- * much component instances must be created, then you can use the <code>factorySet</code>
- * annotation attribute.<p>
- * If a <code>factorySet</code> attribute is set, the component is not started automatically
- * during bundle startup, and a <code>java.util.Set<Dictionary></code>
- * object is registered into the OSGi registry on behalf of the component. This Set will act
- * as a Factory API, and another component may use this Set and add some configuration
- * dictionaries in it, in order to fire some component activations (there is one component
- * instantiated per dictionary, which is passed to component instances via a configurable
- * callback method).
- *
- * <h3>Usage Examples</h3>
- *
- * <p> Here is a sample showing a X component, which depends on a configuration dependency:<p>
- * <blockquote>
- *
- * <pre>
- * /**
- * * This component will be activated once the bundle is started and when all required dependencies
- * * are available.
- * */
- * @Component
- * class X implements Z {
- * @ConfigurationDependency(pid="MyPid")
- * void configure(Dictionary conf) {
- * // Configure or reconfigure our component.
- * }
- *
- * @Start
- * void start() {
- * // Our component is starting and is about to be registered in the OSGi registry as a Z service.
- * }
- *
- * public void doService() {
- * // ...
- * }
- * }
- * </pre>
- * </blockquote>
- *
- * Here is a sample showing how a Y component may dynamically instantiate several X component instances,
- * using the {@link #factorySet()} attribute:<p>
- * <blockquote>
- *
- * <pre>
- * /**
- * * All component instances will be created/updated/removed by the "Y" component
- * */
- * @Component(factorySet="MyComponentFactory", factoryConfigure="configure")
- * class X implements Z {
- * void configure(Dictionary conf) {
- * // Configure or reconfigure our component. The conf is provided by the factory,
- * // and all public properties (which don't start with a dot) are propagated with the
- * // service properties specified in the properties annotation attribute.
- * }
- *
- * @ServiceDependency
- * void bindOtherService(OtherService other) {
- * // store this require dependency
- * }
- *
- * @Start
- * void start() {
- * // Our component is starting and is about to be registered in the OSGi registry as a Z service.
- * }
- *
- * public void doService() {
- * // ...
- * }
- * }
- *
- * /**
- * * This class will instantiate some X component instances
- * */
- * @Component
- * class Y {
- * @ServiceDependency(filter="(dm.factory.name=MyComponentFactory)")
- * Set<Dictionary> _XFactory; // This Set acts as a Factory API for creating X component instances.
- *
- * @Start
- * void start() {
- * // Instantiate a X component instance
- * Dictionary x1 = new Hashtable() {{ put("foo", "bar1"); }};
- * _XFactory.add(x1);
- *
- * // Instantiate another X component instance
- * Dictionary x2 = new Hashtable() {{ put("foo", "bar2"); }};
- * _XFactory.add(x2);
- *
- * // Update the first X component instance
- * x1.put("foo", "bar1_modified");
- * _XFactory.add(x1);
- *
- * // Instantiate a third X instance, by explicitly providing the implementation object
- * Dictionary x3 = new Hashtable() {{ put(Component.FACTORY_INSTANCE, new X()); }};
- * _XFactory.add(x3);
- *
- * // Destroy x1/x2/x3 components (Notice that invoking XFactory.clear() will destroy all X component instances).
- * _XFactory.remove(x1);
- * _XFactory.remove(x2);
- * _XFactory.remove(x3);
- * }
- * }
- * </pre>
- *
- * </blockquote>
- *
- * @author <a href="mailto:dev@felix.apache.org">Felix Project Team</a>
- */
-@Retention(RetentionPolicy.CLASS)
-@Target(ElementType.TYPE)
-public @interface Component
-{
- /**
- * Sets list of provided interfaces. By default, the directly implemented interfaces are provided.
- */
- Class<?>[] provides() default {};
-
- /**
- * Sets list of provided service properties.
- */
- Property[] properties() default {};
-
- /**
- * Returns the name of the <code>Factory Set</code> used to dynamically instantiate this component.
- * When you set this attribute, a <code>java.util.Set<java.lang.Dictionary></code> OSGi Service will
- * be provided with a <code>dm.factory.name</code> service property matching your specified <code>factorySet</code> attribute.
- * This Set will be provided once the component bundle is started, even if required dependencies are not available, and the
- * Set will be unregistered from the OSGi registry once the component bundle is stopped or being updated.<p>
- * So, basically, another component may then be injected with this set in order to dynamically instantiate some component instances:
- * <ul>
- * <li> Each time a new Dictionary is added into the Set, then a new instance of the annotated component will be instantiated.</li>
- * <li> Each time an existing Dictionary is re-added into the Set, then the corresponding component instance will be updated.</li>
- * <li> Each time an existing Dictionary is removed from the Set, then the corresponding component instance will be destroyed.</li>
- * </ul>
- *
- * <p>The dictionary registered in the Set will be provided to the created component instance using a callback method that you can
- * optionally specify in the {@link Component#factoryConfigure()} attribute. Each public properties from that dictionary
- * (which don't start with a dot) will be propagated along with the annotated component service properties.
- *
- * <p>Optionally, the dictionary registered into the factory set may provide an implementation instance for the component to be created,
- * using the {@value #FACTORY_INSTANCE} key.
- */
- String factorySet() default "";
-
- /**
- * Sets "configure" callback method name to be called with the factory configuration. This attribute only makes sense if the
- * {@link #factorySet()} attribute is used. If specified, then this attribute references a callback method, which is called
- * for providing the configuration supplied by the factory that instantiated this component. The current component service properties will be
- * also updated with all public properties (which don't start with a dot).
- */
- String factoryConfigure() default "";
-
- /**
- * Sets the static method used to create the components implementation instance.
- */
- String factoryMethod() default "";
-
- /**
- * Service property name used to match a given Factory Set.
- * @see #factorySet() for more information about factory sets.
- */
- final static String FACTORY_NAME = "dm.factory.name";
-
- /**
- * Key used when providing an implementation in a factory Set dictionary configuration.
- * @see #factorySet()
- */
- final static String FACTORY_INSTANCE = "dm.factory.instance";
-}
diff --git a/dependencymanager/annotation/src/main/java/org/apache/felix/dm/annotation/api/Composition.java b/dependencymanager/annotation/src/main/java/org/apache/felix/dm/annotation/api/Composition.java
deleted file mode 100644
index b62ac70..0000000
--- a/dependencymanager/annotation/src/main/java/org/apache/felix/dm/annotation/api/Composition.java
+++ /dev/null
@@ -1,81 +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.felix.dm.annotation.api;
-
-import java.lang.annotation.ElementType;
-import java.lang.annotation.Retention;
-import java.lang.annotation.RetentionPolicy;
-import java.lang.annotation.Target;
-
-/**
- * Annotates a method returning the list of objects which are part of a Component implementation.
- * When implementing complex Components, you often need to use more than one object instances.
- * Moreover, several of these instances might want to have dependencies injected, as well as lifecycle
- * callbacks invoked, like the methods annotated with {@link Init}, {@link Start}, {@link Stop},
- * {@link Destroy} annotations. In such cases you can tell the dependency manager which instances to
- * consider, by annotating a method in your Component, returning a list of objects which are part
- * of the implementation.
- * <p>
- * This annotation may be applied on a method which is part of class annotated with either a {@link Component},
- * {@link AspectService}, {@link AdapterService}, {@link FactoryConfigurationAdapterService} or
- * {@link ResourceAdapterService} annotation.
- *
- * <h3>Usage Examples</h3>
- *
- * <p> Here, the "MyComponent" component is composed of the Helper class, which is also injected with
- * service dependencies. The lifecycle callbacks are also invoked in the Helper (if the Helper defines
- * them):<p>
- * <blockquote>
- * <pre>
- *
- * class Helper {
- * LogService logService; // Injected
- * void start() {} // lifecycle callback
- * void bind(OtherService otherService) {} // injected
- * }
- *
- * @Component
- * class MyComponent {
- * // Helper which will also be injected with our service dependencies
- * private Helper helper = new Helper();
- *
- * @Composition
- * Object[] getComposition() {
- * return new Object[] { this, helper };
- * }
- *
- * @ServiceDependency
- * private LogService logService; // Helper.logService will be also be injected, if defined.
- *
- * @Start
- * void start() {} // the Helper.start() method will also be called, if defined
- *
- * @ServiceDependency
- * void bind(OtherService otherService) {} // the Helper.bind() method will also be called, if defined
- * }
- * </pre>
- * </blockquote>
- *
- * @author <a href="mailto:dev@felix.apache.org">Felix Project Team</a>
- */
-@Retention(RetentionPolicy.CLASS)
-@Target(ElementType.METHOD)
-public @interface Composition
-{
-}
diff --git a/dependencymanager/annotation/src/main/java/org/apache/felix/dm/annotation/api/ConfigurationDependency.java b/dependencymanager/annotation/src/main/java/org/apache/felix/dm/annotation/api/ConfigurationDependency.java
deleted file mode 100644
index 103f358..0000000
--- a/dependencymanager/annotation/src/main/java/org/apache/felix/dm/annotation/api/ConfigurationDependency.java
+++ /dev/null
@@ -1,125 +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.felix.dm.annotation.api;
-
-import java.lang.annotation.ElementType;
-import java.lang.annotation.Retention;
-import java.lang.annotation.RetentionPolicy;
-import java.lang.annotation.Target;
-
-
-/**
- * Annotates a method for injecting a Configuration Dependency. A configuration dependency
- * is always required, and allows you to depend on the availability of a valid configuration
- * for your component. This dependency requires the OSGi Configuration Admin Service.
- *
- * <h3>Usage Examples</h3>
- *
- * <p> In the following example, the "Printer" component depends on a configuration
- * whose PID name is "org.apache.felix.sample.Printer". This service will initialize
- * its ip/port number from the provided configuration:
- * <p>
- * <blockquote>
- * <pre>
- * package org.apache.felix.sample;
- *
- * @Component
- * public class Printer {
- * @ConfigurationDependency
- * void updated(Dictionary config) {
- * // load printer ip/port from the provided dictionary.
- * }
- * }
- * </pre>
- * </blockquote>
- *
- * <p> This other example shows how to specify a configuration dependency, as well as meta data
- * used to customize the WebConsole GUI. Using these meta data, you can specify for example the
- * default value for your configurations data, some descriptions, the cardinality of configuration
- * values, etc ...
- * <p>
- * <blockquote>
- * <pre>
- * package org.apache.felix.sample;
- *
- * @Component
- * public class Printer {
- * @ConfigurationDependency(
- * heading = "Printer Service",
- * description = "Declare here parameters used to configure the Printer service",
- * metadata = {
- * @PropertyMetaData(heading = "Ip Address",
- * description = "Enter the ip address for the Printer service",
- * defaults = { "127.0.0.1" },
- * type = String.class,
- * id = "IPADDR",
- * cardinality = 0),
- * @PropertyMetaData(heading = "Port Number",
- * description = "Enter the port number for the Printer service",
- * defaults = { "4444" },
- * type = Integer.class,
- * id = "PORTNUM",
- * cardinality = 0)
-
- * }
- * )
- * void updated(Dictionary config) {
- * // load configuration from the provided dictionary.
- * }
- * }
- * </pre>
- * </blockquote>
- *
- * @author <a href="mailto:dev@felix.apache.org">Felix Project Team</a>
- */
-@Retention(RetentionPolicy.CLASS)
-@Target(ElementType.METHOD)
-public @interface ConfigurationDependency
-{
- /**
- * Returns the pid for a given service (by default, the pid is the service class name).
- * @return the pid for a given service (default = Service class name)
- */
- String pid() default "";
-
- /**
- * Returns true if the configuration properties must be published along with the service.
- * Any additional service properties specified directly are merged with these.
- * @return true if configuration must be published along with the service, false if not.
- */
- boolean propagate() default false;
-
- /**
- * The label used to display the tab name (or section) where the properties are displayed. Example: "Printer Service".
- * @return The label used to display the tab name where the properties are displayed.
- */
- String heading() default "";
-
- /**
- * A human readable description of the PID this annotation is associated with. Example: "Configuration for the PrinterService bundle".
- * @return A human readable description of the PID this annotation is associated with.
- */
- String description() default "";
-
- /**
- * The list of properties types used to expose properties in web console.
- * @return The list of properties types used to expose properties in web console.
- */
- PropertyMetaData[] metadata() default {};
-}
diff --git a/dependencymanager/annotation/src/main/java/org/apache/felix/dm/annotation/api/Destroy.java b/dependencymanager/annotation/src/main/java/org/apache/felix/dm/annotation/api/Destroy.java
deleted file mode 100644
index 4934c89a..0000000
--- a/dependencymanager/annotation/src/main/java/org/apache/felix/dm/annotation/api/Destroy.java
+++ /dev/null
@@ -1,53 +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.felix.dm.annotation.api;
-
-import java.lang.annotation.ElementType;
-import java.lang.annotation.Retention;
-import java.lang.annotation.RetentionPolicy;
-import java.lang.annotation.Target;
-
-/**
- * Annotates a method which is invoked when the component is destroyed.
- * The method is called when the component's bundle is stopped, or when one of its
- * required dependency is lost (unless the dependency has been defined as an "instance bound"
- * dependency using the Dependency Manager API).
- * </ul>
- *
- * <h3>Usage Examples</h3>
- * <blockquote>
- * <pre>
- * @Component
- * class MyComponent {
- * @ServiceDependency
- * private LogService logService; // Required dependency over the log service.
- *
- * @Destroy
- * void destroyed() {} // called if bundle is stopped or if we have lost some required dependencies.
- * }
- * </pre>
- * </blockquote>
- *
- * @author <a href="mailto:dev@felix.apache.org">Felix Project Team</a>
- */
-@Retention(RetentionPolicy.CLASS)
-@Target(ElementType.METHOD)
-public @interface Destroy
-{
-}
diff --git a/dependencymanager/annotation/src/main/java/org/apache/felix/dm/annotation/api/FactoryConfigurationAdapterService.java b/dependencymanager/annotation/src/main/java/org/apache/felix/dm/annotation/api/FactoryConfigurationAdapterService.java
deleted file mode 100644
index 590a7d4..0000000
--- a/dependencymanager/annotation/src/main/java/org/apache/felix/dm/annotation/api/FactoryConfigurationAdapterService.java
+++ /dev/null
@@ -1,199 +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.felix.dm.annotation.api;
-
-import java.lang.annotation.ElementType;
-import java.lang.annotation.Retention;
-import java.lang.annotation.RetentionPolicy;
-import java.lang.annotation.Target;
-
-
-/**
- * Annotates a class that acts as a Factory Configuration Adapter Service. For each new <code>Config Admin</code> factory configuration matching
- * the specified factoryPid, an instance of this service will be created.
- * The adapter will be registered with the specified interface, and with the specified adapter service properties.
- * Depending on the <code>propagate</code> parameter, every public factory configuration properties
- * (which don't start with ".") will be propagated along with the adapter service properties. <p>
- *
- * Like in @{@link ConfigurationDependency}, you can optionally specify the meta types of your
- * configurations for Web Console GUI customization (configuration heading/descriptions/default values/etc ...).
- *
- * <h3>Usage Examples</h3>
- * Here, a "Dictionary" service instance is instantiated for each existing factory configuration
- * instances matching the factory pid "DictionaryServiceFactory".
- * <blockquote>
- * <pre>
- * @FactoryConfigurationAdapterService(factoryPid="DictionaryServiceFactory", updated="updated")
- * public class DictionaryImpl implements DictionaryService
- * {
- * /**
- * * The key of our config admin dictionary language.
- * */
- * final static String LANG = "lang";
- *
- * /**
- * * The key of our config admin dictionary values.
- * */
- * final static String WORDS = "words";
- *
- * /**
- * * We store all configured words in a thread-safe data structure, because ConfigAdmin
- * * may invoke our updated method at any time.
- * */
- * private CopyOnWriteArrayList<String> m_words = new CopyOnWriteArrayList<String>();
- *
- * /**
- * * Our Dictionary language.
- * */
- * private String m_lang;
- *
- * protected void updated(Dictionary<String, ?> config) {
- * m_lang = (String) config.get(LANG);
- * m_words.clear();
- * String[] words = (String[]) config.get(WORDS);
- * for (String word : words) {
- * m_words.add(word);
- * }
- * }
- * ...
- * }
- * </pre>
- * </blockquote>
- * Here, this is the same example as above, but using meta types:
- *
- * <blockquote>
- * <pre>
- * @FactoryConfigurationAdapterService(
- * factoryPid="DictionaryServiceFactory",
- * propagate=true,
- * updated="updated",
- * heading="Dictionary Services",
- * description="Declare here some Dictionary instances, allowing to instantiates some DictionaryService services for a given dictionary language",
- * metadata={
- * @PropertyMetaData(
- * heading="Dictionary Language",
- * description="Declare here the language supported by this dictionary. " +
- * "This property will be propagated with the Dictionary Service properties.",
- * defaults={"en"},
- * id=DictionaryImpl.LANG,
- * cardinality=0),
- * @PropertyMetaData(
- * heading="Dictionary words",
- * description="Declare here the list of words supported by this dictionary. This properties starts with a Dot and won't be propagated with Dictionary OSGi service properties.",
- * defaults={"hello", "world"},
- * id=DictionaryImpl.WORDS,
- * cardinality=Integer.MAX_VALUE)
- * }
- * )
- * public class DictionaryImpl implements DictionaryService
- * {
- * /**
- * * The key of our config admin dictionary language.
- * */
- * final static String LANG = "lang";
- *
- * /**
- * * The key of our config admin dictionary values.
- * */
- * final static String WORDS = "words";
- *
- * /**
- * * We store all configured words in a thread-safe data structure, because ConfigAdmin
- * * may invoke our updated method at any time.
- * */
- * private CopyOnWriteArrayList<String> m_words = new CopyOnWriteArrayList<String>();
- *
- * /**
- * * Our Dictionary language.
- * */
- * private String m_lang;
- *
- * protected void updated(Dictionary<String, ?> config) {
- * m_lang = (String) config.get(LANG);
- * m_words.clear();
- * String[] words = (String[]) config.get(WORDS);
- * for (String word : words) {
- * m_words.add(word);
- * }
- * }
- *
- * ...
- * }
- * </pre>
- * </blockquote>
- *
- * @author <a href="mailto:dev@felix.apache.org">Felix Project Team</a>
- */
-@Retention(RetentionPolicy.CLASS)
-@Target(ElementType.TYPE)
-public @interface FactoryConfigurationAdapterService
-{
- /**
- * The interface(s) to use when registering adapters. By default, directly implemented
- * interfaces will be registered in the OSGi registry.
- */
- Class<?>[] provides() default {};
-
- /**
- * Adapter Service properties. Notice that public factory configuration is also registered in service properties,
- * (only if propagate is true). Public factory configuration properties are those which don't starts with a dot (".").
- */
- Property[] properties() default {};
-
- /**
- * Returns the factory pid whose configurations will instantiate the annotated service class. (By default, the pid is the
- * service class name).
- */
- String factoryPid() default "";
-
- /**
- * The Update method to invoke (defaulting to "updated"), when a factory configuration is created or updated
- */
- String updated() default "updated";
-
- /**
- * Returns true if the configuration properties must be published along with the service.
- * Any additional service properties specified directly are merged with these.
- * @return true if configuration must be published along with the service, false if not.
- */
- boolean propagate() default false;
-
- /**
- * The label used to display the tab name (or section) where the properties are displayed. Example: "Printer Service".
- * @return The label used to display the tab name where the properties are displayed.
- */
- String heading() default "";
-
- /**
- * A human readable description of the PID this annotation is associated with. Example: "Configuration for the PrinterService bundle".
- * @return A human readable description of the PID this annotation is associated with.
- */
- String description() default "";
-
- /**
- * The list of properties types used to expose properties in web console.
- * @return The list of properties types used to expose properties in web console.
- */
- PropertyMetaData[] metadata() default {};
-
- /**
- * Sets the static method used to create the adapter instance.
- */
- String factoryMethod() default "";
-}
diff --git a/dependencymanager/annotation/src/main/java/org/apache/felix/dm/annotation/api/Init.java b/dependencymanager/annotation/src/main/java/org/apache/felix/dm/annotation/api/Init.java
deleted file mode 100644
index c18cd67..0000000
--- a/dependencymanager/annotation/src/main/java/org/apache/felix/dm/annotation/api/Init.java
+++ /dev/null
@@ -1,64 +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.felix.dm.annotation.api;
-
-import java.lang.annotation.ElementType;
-import java.lang.annotation.Retention;
-import java.lang.annotation.RetentionPolicy;
-import java.lang.annotation.Target;
-
-/**
- * Annotates a method which will be invoked when the Service is initializing.
- * All required dependencies are already injected before the annotated method is called, and
- * optional dependencies on class fields are injected with NullObjects if the optional
- * dependencies are not currently available.<p>
- *
- * If some dependencies are declared using a <b>named</b> @{@link ServiceDependency} annotation,
- * then the annotated method may optionally return a Map used to dynamically configure such
- * dependencies (Please refer to @{@link ServiceDependency#name()} attribute for more
- * information about this feature).<p>
- *
- * After the init method returns, the component is then invoked in the method annotated with
- * @{@link Start}, in order to notify that the component is about to be registered into the OSGi
- * registry (if this one provides a service). However, you can take control of when the service is registered,
- * using the @{@link LifecycleController} annotation).
- *
- * <h3>Usage Examples</h3>
- * Here, the "VideoPlayer" init method is called after the "log" dependency is injected.
- * <blockquote>
- * <pre>
- *
- * @Component
- * public class VideoPlayer {
- * @ServiceDependency
- * LogService log;
- *
- * @Init
- * void init() {} // initialize our service (the "log" dependency is already injected).
- * }
- * </pre>
- * </blockquote>
- *
- * @author <a href="mailto:dev@felix.apache.org">Felix Project Team</a>
- */
-@Retention(RetentionPolicy.CLASS)
-@Target(ElementType.METHOD)
-public @interface Init
-{
-}
diff --git a/dependencymanager/annotation/src/main/java/org/apache/felix/dm/annotation/api/Inject.java b/dependencymanager/annotation/src/main/java/org/apache/felix/dm/annotation/api/Inject.java
deleted file mode 100644
index e97c627..0000000
--- a/dependencymanager/annotation/src/main/java/org/apache/felix/dm/annotation/api/Inject.java
+++ /dev/null
@@ -1,80 +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.felix.dm.annotation.api;
-
-import java.lang.annotation.ElementType;
-import java.lang.annotation.Retention;
-import java.lang.annotation.RetentionPolicy;
-import java.lang.annotation.Target;
-
-/**
- * Inject classes in a component instance field.
- * The following injections are currently performed, depending on the type of the
- * field this annotation is applied on:
- * <ul>
- * <li>BundleContext: the bundle context of the bundle
- * <li>DependencyManager: the dependency manager instance
- * <li>Component: the component instance of the dependency manager
- * </ul>
- *
- * <p>
- * <h3>Usage Examples</h3>
- * <blockquote>
- *
- * <pre>
- * @Component
- * class X implements Z {
- * @Inject
- * BundleContext bundleContext;
- *
- * @Inject
- * Component component;
- *
- * @Inject
- * DependencyManager manager;
- *
- * OtherService otherService;
- *
- * @Init
- * void init() {
- * System.out.println("Bundle Context: " + bundleContext);
- * System.out.println("Manager: " + manager);
- *
- * // Use DM API for defining an extra service dependency
- * componnent.add(manager.createServiceDependency()
- * .setService(OtherService.class)
- * .setRequired(true)
- * .setInstanceBound(true));
- * }
- *
- * @Start
- * void start() {
- * System.out.println("OtherService: " + otherService);
- * }
- * }
- * </pre>
- * </blockquote>
- *
- * @author <a href="mailto:dev@felix.apache.org">Felix Project Team</a>
- */
-@Retention(RetentionPolicy.CLASS)
-@Target(ElementType.FIELD)
-public @interface Inject
-{
-}
diff --git a/dependencymanager/annotation/src/main/java/org/apache/felix/dm/annotation/api/LifecycleController.java b/dependencymanager/annotation/src/main/java/org/apache/felix/dm/annotation/api/LifecycleController.java
deleted file mode 100644
index afd9295..0000000
--- a/dependencymanager/annotation/src/main/java/org/apache/felix/dm/annotation/api/LifecycleController.java
+++ /dev/null
@@ -1,95 +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.felix.dm.annotation.api;
-
-import java.lang.annotation.ElementType;
-import java.lang.annotation.Retention;
-import java.lang.annotation.RetentionPolicy;
-import java.lang.annotation.Target;
-
-/**
- * Injects a <code>Runnable</code> object in a Service for starting/stopping it programatically.
- * By default, a Service is implicitly started when the service's bundle is started and when
- * all required dependencies are satisfied. However, it is sometimes required to programatically
- * take control of when the service is started or stopped. In this case, the injected <code>Runnable</code>
- * can be invoked in order to start/register (or stop/unregister) a Service at any time. When this annotation
- * is used, then the Service on which this annotation is applied is not activated by default, and you have to
- * call the injected Runnable yourself.
- * <p>
- * <h3>Usage Examples</h3>
- * <blockquote>
- *
- * <pre>
- * /**
- * * This Service will be registered programatically into the OSGi registry, using the LifecycleController annotation.
- * */
- * @Service
- * class X implements Z {
- * @LifecycleController
- * Runnable starter
- *
- * @LifecycleController(start=false)
- * Runnable stopper
- *
- * @Init
- * void init() {
- * // At this point, all required dependencies are there, but we'll activate our service in 2 seconds ...
- * Thread t = new Thread() {
- * public void run() {
- * sleep(2000);
- * // start our "Z" service (our "start" method will be called, juste before service registration
- * starter.run();
- *
- * sleep(2000);
- * // now, stop/unregister the "Z" service (we'll then be called in our stop() method
- * stopper.run();
- * }
- * };
- * t.start();
- * }
- *
- * @Start
- * public void start() {
- * // This method will be called after we invoke our starter Runnable, and our service will be
- * // published after our method returns, as in normal case.
- * }
-
- * @Stop
- * public void stop() {
- * // This method will be called after we invoke our "stop" Runnable, and our service will be
- * // unregistered before our method is invoked, as in normal case. Notice that the service won't
- * // be destroyed here, and the "starter" runnable can be re-invoked later.
- * }
- * }
- * </pre>
- * </blockquote>
- *
- * @author <a href="mailto:dev@felix.apache.org">Felix Project Team</a>
- */
-@Retention(RetentionPolicy.CLASS)
-@Target(ElementType.FIELD)
-public @interface LifecycleController
-{
- /**
- * Specifies the action to be performed when the Injected runnable is invoked. By default, the
- * Runnable will fire a Service Component activation, when invoked. If you specify this attribute
- * to false, then the Service Component will be stopped, when the runnable is invoked.
- */
- public boolean start() default true;
-}
diff --git a/dependencymanager/annotation/src/main/java/org/apache/felix/dm/annotation/api/Property.java b/dependencymanager/annotation/src/main/java/org/apache/felix/dm/annotation/api/Property.java
deleted file mode 100644
index f760ee9..0000000
--- a/dependencymanager/annotation/src/main/java/org/apache/felix/dm/annotation/api/Property.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.felix.dm.annotation.api;
-
-import java.lang.annotation.ElementType;
-import java.lang.annotation.Retention;
-import java.lang.annotation.RetentionPolicy;
-import java.lang.annotation.Target;
-
-/**
- * Annotation used to describe a property key-value(s) pair. It is used for example when
- * declaring {@link Component#properties()} attribute.<p>
- *
- * Property value(s) type is String by default, and the type is scalar if the value is single-valued,
- * or an array if the value is multi-valued.
- *
- * Eight primitive types are supported:<p>
- * <ul>
- * <li> String (default type)
- * <li> Long
- * <li> Double
- * <li> Float
- * <li> Integer
- * <li> Byte
- * <li> Boolean
- * <li> Short
- * </ul>
- *
- * You can specify the type of a property either using a combination of <code>value</code> and <code>type</code> attributes,
- * or using one of the <code>longValue/doubleValue/floatValue/intValue/byteValue/charValue/booleanValue/shortValue</code> attributes.
- *
- * Notice that you can also specify service properties dynamically by returning a Map from a method
- * annotated with {@link Start}.
- *
- * <p>
- * <h3>Usage Examples</h3>
- * <blockquote>
- *
- * <pre>
- * @Component(properties={
- * @Property(name="p1", value="v")}) // String value type (scalar)
- * @Property(name="p2", value={"s1", "s2")}) // Array of Strings
- * @Property(name="service.ranking", intValue=10) // Integer value type (scalar)
- * @Property(name="p3", intValue={1,2}) // Array of Integers
- * @Property(name="p3", value={"1"), type=Long.class}) // Long value (scalar)
- * class ServiceImpl implements Service {
- * }
- * </pre>
- * </blockquote>
- *
- * @author <a href="mailto:dev@felix.apache.org">Felix Project Team</a>
- */
-@Retention(RetentionPolicy.CLASS)
-@Target( { ElementType.ANNOTATION_TYPE })
-public @interface Property
-{
- /**
- * Returns the property name.
- * @return this property name
- */
- String name();
-
- /**
- * Returns the property value(s). The property value(s) is (are)
- * parsed using the <code>valueOf</code> method of the class specified in the #type attribute
- * (which is <code>String</code> by default). When the property value is single-value, then
- * the value type is scalar (not an array). If the property value is multi-valued, then the value type
- * is an array of the type specified in the {@link #type()} attribute (String by default).
- *
- * @return this property value(s).
- */
- String[] value() default {};
-
- /**
- * Specifies how the {@link #value()} or {@link #values()} attributes are parsed.
- * @return the property value type (String by default) used to parse {@link #value()} or {@link #values()}
- * attribtues
- */
- Class<?> type() default String.class;
-
- /**
- * A Long value or an array of Long values.
- */
- long[] longValue() default {};
-
- /**
- * A Double value or an array of Double values.
- */
- double[] doubleValue() default {};
-
- /**
- * A Float value or an array of Float values.
- */
- float[] floatValue() default {};
-
- /**
- * An Integer value or an array of Integer values.
- */
- int[] intValue() default {};
-
- /**
- * A Byte value or an array of Byte values.
- */
- byte[] byteValue() default {};
-
- /**
- * A Character value or an array of Character values.
- */
- char[] charValue() default {};
-
- /**
- * A Boolean value or an array of Boolean values.
- */
- boolean[] booleanValue() default {};
-
- /**
- * A Short value or an array of Short values.
- */
- short[] shortValue() default {};
-
- /**
- * Returns an array of property values.
- * The property value are parsed using the <code>valueOf</code> method of the class specified in the #type attribute
- * (which is <code>String</code> by default).
- *
- * @return an array of property values.
- * @deprecated use {@link #value()} attribute.
- */
- String[] values() default {};
-}
diff --git a/dependencymanager/annotation/src/main/java/org/apache/felix/dm/annotation/api/PropertyMetaData.java b/dependencymanager/annotation/src/main/java/org/apache/felix/dm/annotation/api/PropertyMetaData.java
deleted file mode 100644
index 8e7d724..0000000
--- a/dependencymanager/annotation/src/main/java/org/apache/felix/dm/annotation/api/PropertyMetaData.java
+++ /dev/null
@@ -1,121 +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.felix.dm.annotation.api;
-
-import java.lang.annotation.ElementType;
-import java.lang.annotation.Retention;
-import java.lang.annotation.RetentionPolicy;
-import java.lang.annotation.Target;
-
-
-/**
- * This annotation describes the data types of a configuration Property.
- * It can be used by other annotations which require meta type support.
- * For now, the following annotations are using <code>PropertyMetaData</code:
- * <ul>
- * <li>{@link ConfigurationDependency}: This dependency allows to define a
- * dependency over a <code>Configuration Admin</code> configuration dictionaries, whose
- * metadata can be described using <code>PropertyMetaData</code> annotation.
- * <li>{@link FactoryConfigurationAdapterService}: This service adapter allows
- * to dynamically create Services on behalf of <code>Factory Configuration Admin</code>
- * configuration dictionaries, whose metadata can be described using this <code>PropertyMetaData</code> annotation.
- * </ul>
- *
- * @author <a href="mailto:dev@felix.apache.org">Felix Project Team</a>
- */
-@Retention(RetentionPolicy.CLASS)
-@Target(ElementType.ANNOTATION_TYPE)
-public @interface PropertyMetaData
-{
- /**
- * The label used to display the property. Example: "Log Level".
- * @return The label used to display the property
- */
- String heading();
-
- /**
- * The key of a ConfigurationAdmin property. Example: "printer.logLevel"
- * @return The Configuration Admin property name
- */
- String id();
-
- /**
- * Return the property primitive type. If must be either one of the following types:<p>
- * <ul>
- * <li>String.class</li>
- * <li>Long.class</li>
- * <li>Integer.class</li>
- * <li>Character.class</li>
- * <li>Byte.class</li>
- * <li>Double.class</li>
- * <li>Float.class</li>
- * <li>Boolean.class</li>
- * </ul>
- */
- Class<?> type() default String.class;
-
- /**
- * Return a default for this property. The object must be of the appropriate type as defined by the cardinality and getType().
- * The return type is a list of String objects that can be converted to the appropriate type. The cardinality of the return
- * array must follow the absolute cardinality of this type. E.g. if the cardinality = 0, the array must contain 1 element.
- * If the cardinality is 1, it must contain 0 or 1 elements. If it is -5, it must contain from 0 to max 5 elements. Note that
- * the special case of a 0 cardinality, meaning a single value, does not allow arrays or vectors of 0 elements.
- */
- String[] defaults() default {};
-
- /**
- * Returns the property description. The description may be localized and must describe the semantics of this type and any
- * constraints. Example: "Select the log level for the Printer Service".
- * @return The localized description of the definition.
- */
- String description();
-
- /**
- * Return the cardinality of this property. The OSGi environment handles multi valued properties in arrays ([]) or in Vector objects.
- * The return value is defined as follows:<p>
- *
- * <ul>
- * <li> x = Integer.MIN_VALUE no limit, but use Vector</li>
- * <li> x < 0 -x = max occurrences, store in Vector</li>
- * <li> x > 0 x = max occurrences, store in array []</li>
- * <li> x = Integer.MAX_VALUE no limit, but use array []</li>
- * <li> x = 0 1 occurrence required</li>
- * </ul>
- */
- int cardinality() default 0;
-
- /**
- * Tells if this property is required or not.
- */
- boolean required() default true;
-
- /**
- * Return a list of valid option labels for this property. The purpose of this method is to allow menus with localized labels.
- * It is associated with the {@link #optionValues()} attribute. The labels returned here are ordered in the same way as the
- * {@link #optionValues()} attribute values.
- * @return the list of valid option labels for this property.
- */
- String[] optionLabels() default {};
-
- /**
- * Return a list of option values that this property can take. This list must be in the same sequence as the {@link #optionLabels()}
- * attribute.
- */
- String[] optionValues() default {};
-}
diff --git a/dependencymanager/annotation/src/main/java/org/apache/felix/dm/annotation/api/Registered.java b/dependencymanager/annotation/src/main/java/org/apache/felix/dm/annotation/api/Registered.java
deleted file mode 100644
index 5c34855..0000000
--- a/dependencymanager/annotation/src/main/java/org/apache/felix/dm/annotation/api/Registered.java
+++ /dev/null
@@ -1,58 +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.felix.dm.annotation.api;
-
-import java.lang.annotation.ElementType;
-import java.lang.annotation.Retention;
-import java.lang.annotation.RetentionPolicy;
-import java.lang.annotation.Target;
-
-/**
- * This annotation can be used to be notified when a component is registered. At this point, the
- * component has been registered into the OSGI registry (if it provides some services).
- * When a service is registered, the ServiceRegistration used to register the service is
- * also passed to the method (if it takes a ServiceRegistration as parameter).
- *
- * <p>
- * <h3>Usage Examples</h3>
- * <blockquote>
- *
- * <pre>
- * @Component
- * class X implements Z {
- * @Start
- * void start() {
- * // Our Z Service is about to be registered into the OSGi registry.
- * }
- *
- * @Registered
- * void registered(ServiceRegistration sr) {
- * // At this point, our service has been registered into the registry.
- * }
- * }
- * </pre>
- * </blockquote>
- *
- * @author <a href="mailto:dev@felix.apache.org">Felix Project Team</a>
- */
-@Retention(RetentionPolicy.CLASS)
-@Target(ElementType.METHOD)
-public @interface Registered
-{
-}
diff --git a/dependencymanager/annotation/src/main/java/org/apache/felix/dm/annotation/api/ResourceAdapterService.java b/dependencymanager/annotation/src/main/java/org/apache/felix/dm/annotation/api/ResourceAdapterService.java
deleted file mode 100644
index bfa388b..0000000
--- a/dependencymanager/annotation/src/main/java/org/apache/felix/dm/annotation/api/ResourceAdapterService.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.felix.dm.annotation.api;
-
-import java.lang.annotation.ElementType;
-import java.lang.annotation.Retention;
-import java.lang.annotation.RetentionPolicy;
-import java.lang.annotation.Target;
-
-/**
- * Annotates a class as a Resource adapter service. Resource adapters are things that
- * adapt a resource instead of a service, and provide an adapter service on top of this resource.
- * Resources are an abstraction that is introduced by the dependency manager, represented as a URL.
- * They can be implemented to serve resources embedded in bundles, somewhere on a file system or in
- * an http content repository server, or database.<p>
- * The adapter will be applied to any resource that matches the specified filter condition, which can
- * match some part of the resource URL (with "path", "protocol", "port", or "host" filters).
- * For each matching resource an adapter will be created based on the adapter implementation class.
- * The adapter will be registered with the specified interface and with any extra service properties
- * you supply here. Moreover, the following service properties will be propagated from the resource URL:
- *
- * <ul><li> "host": this property exposes the host part of the resource URL
- * <li>"path": the resource URL path
- * <li>"protocol": the resource URL protocol
- * <li>"port": the resource URL port
- * </ul>
- *
- * <h3>Usage Examples</h3>
- * Here, the "VideoPlayer" service provides a video service on top of any movie resources, with service
- * properties "host"/"port"/"protocol"/"path" extracted from the resource URL:
- * <blockquote>
- * <pre>
- *
- * @ResourceAdapterService(filter = "(&(path=/videos/*.mkv)(host=localhost))", propagate = true)
- * public class VideoPlayerImpl implements VideoPlayer {
- * // Injected by reflection
- * URL resource;
- *
- * void play() {} // play video referenced by this.resource
- * void stop() {} // stop playing the video
- * void transcode() {} // ...
- * }
- * </pre>
- * </blockquote>
- *
- * And here is an example of a VideoProvider, which provides some videos using a web URL.
- * Notice that Resource providers need to depend on the DependencyManager API:
- *
- * <blockquote>
- * <pre>
- * import java.net.MalformedURLException;
- * import java.net.URL;
- * import java.util.HashMap;
- * import java.util.Map;
- *
- * import org.apache.felix.dm.ResourceHandler;
- * import org.apache.felix.dm.ResourceUtil;
- * import org.apache.felix.dm.annotation.api.Component;
- * import org.apache.felix.dm.annotation.api.Init;
- * import org.apache.felix.dm.annotation.api.ServiceDependency;
- * import org.osgi.framework.BundleContext;
- * import org.osgi.framework.Filter;
- * import org.osgi.framework.InvalidSyntaxException;
- *
- * @Component
- * public class VideoProvider
- * {
- * // Injected by reflection
- * private volatile BundleContext context;
- * // List of known resource handlers
- * private Map<ResourceHandler, Filter> m_handlers = new HashMap<ResourceHandler, Filter>();
- * // List of known video resources
- * private URL[] m_videos;
- *
- * @Init
- * void init() throws MalformedURLException
- * {
- * m_videos = new URL[] {
- * new URL("http://localhost:8080/videos/video1.mkv"),
- * new URL("http://localhost:8080/videos/video2.mkv"),
- * };
- * }
- *
- * // Track resource handlers
- * @ServiceDependency(required = false)
- * public void add(Map<String, String> serviceProperties, ResourceHandler handler) throws InvalidSyntaxException
- * {
- * String filterString = serviceProperties.get("filter");
- * filterString = (filterString != null) ? filterString : "(path=*)";
- * Filter filter = context.createFilter(filterString);
- * synchronized (this)
- * {
- * m_handlers.put(handler, filter);
- * }
- * for (URL video : m_videos)
- * {
- * if (filter.match(ResourceUtil.createProperties(video)))
- * {
- * handler.added(video);
- * }
- * }
- * }
- * }
- * </pre>
- * </blockquote>
- *
- * @author <a href="mailto:dev@felix.apache.org">Felix Project Team</a>
- */
-@Retention(RetentionPolicy.CLASS)
-@Target(ElementType.TYPE)
-public @interface ResourceAdapterService
-{
- /**
- * The interface(s) to use when registering adapters
- */
- Class<?>[] provides() default {};
-
- /**
- * Additional properties to use with the adapter service registration
- */
- Property[] properties() default {};
-
- /**
- * The filter condition to use with the resource.
- */
- String filter();
-
- /**
- * <code>true</code> if properties from the resource should be propagated to the service properties.
- */
- boolean propagate() default false;
-
- /**
- * The callback method to be invoked when the Resource has changed.
- */
- String changed() default "";
-
- /**
- * Sets the static method used to create the AdapterService implementation instance.
- */
- String factoryMethod() default "";
-}
diff --git a/dependencymanager/annotation/src/main/java/org/apache/felix/dm/annotation/api/ResourceDependency.java b/dependencymanager/annotation/src/main/java/org/apache/felix/dm/annotation/api/ResourceDependency.java
deleted file mode 100644
index ebeac18..0000000
--- a/dependencymanager/annotation/src/main/java/org/apache/felix/dm/annotation/api/ResourceDependency.java
+++ /dev/null
@@ -1,155 +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.felix.dm.annotation.api;
-
-import java.lang.annotation.ElementType;
-import java.lang.annotation.Retention;
-import java.lang.annotation.RetentionPolicy;
-import java.lang.annotation.Target;
-
-/**
- * Annotates a method of field as a Resource Dependency. A resource dependency allows you to
- * depend on a resource. Resources are an abstraction that is introduced by the dependency manager, represented as a URL.
- * They can be implemented to serve resources embedded in bundles, somewhere on a file system or in
- * an http content repository server, or database. <p> A resource is a URL and you can use a filter condition based on
- * protocol, host, port, and path.
- *
- * <h3>Usage Examples</h3>
- * Here, the "VideoPlayer" component plays any provided MKV video resources
- * <blockquote>
- * <pre>
- *
- * @Component
- * public class VideoPlayer {
- * @ResourceDependency(required=false, filter="(path=/videos/*.mkv)")
- * void playResource(URL video) { ... }
- * }
- * </pre>
- * </blockquote>
- *
- * And here is an example of a VideoProvider, which provides some videos using a web URL.
- * Notice that Resource providers need to depend on the DependencyManager API:
- *
- * <blockquote>
- * <pre>
- * import java.net.MalformedURLException;
- * import java.net.URL;
- * import java.util.HashMap;
- * import java.util.Map;
- *
- * import org.apache.felix.dm.ResourceHandler;
- * import org.apache.felix.dm.ResourceUtil;
- * import org.apache.felix.dm.annotation.api.Component;
- * import org.apache.felix.dm.annotation.api.Init;
- * import org.apache.felix.dm.annotation.api.ServiceDependency;
- * import org.osgi.framework.BundleContext;
- * import org.osgi.framework.Filter;
- * import org.osgi.framework.InvalidSyntaxException;
- *
- * @Component
- * public class VideoProvider
- * {
- * // Injected by reflection
- * private volatile BundleContext context;
- * // List of known resource handlers
- * private Map<ResourceHandler, Filter> m_handlers = new HashMap<ResourceHandler, Filter>();
- * // List of known video resources
- * private URL[] m_videos;
- *
- * @Init
- * void init() throws MalformedURLException
- * {
- * m_videos = new URL[] {
- * new URL("http://localhost:8080/videos/video1.mkv"),
- * new URL("http://localhost:8080/videos/video2.mkv"),
- * };
- * }
- *
- * // Track resource handlers
- * @ServiceDependency(required = false)
- * public void add(Map<String, String> serviceProperties, ResourceHandler handler) throws InvalidSyntaxException
- * {
- * String filterString = serviceProperties.get("filter");
- * filterString = (filterString != null) ? filterString : "(path=*)";
- * Filter filter = context.createFilter(filterString);
- * synchronized (this)
- * {
- * m_handlers.put(handler, filter);
- * }
- * for (URL video : m_videos)
- * {
- * if (filter.match(ResourceUtil.createProperties(video)))
- * {
- * handler.added(video);
- * }
- * }
- * }
- * }
- * </pre>
- * </blockquote>
- *
- * @author <a href="mailto:dev@felix.apache.org">Felix Project Team</a>
- */
-@Retention(RetentionPolicy.CLASS)
-@Target({ElementType.METHOD, ElementType.FIELD})
-public @interface ResourceDependency
-{
- /**
- * Returns the callback method to be invoked when the service is available. This attribute is only meaningful when
- * the annotation is applied on a class field.
- */
- String added() default "";
-
- /**
- * Returns the callback method to be invoked when the service properties have changed.
- */
- String changed() default "";
-
- /**
- * Returns the callback method to invoke when the service is lost.
- */
- String removed() default "";
-
- /**
- * Returns whether the Service dependency is required or not.
- */
- boolean required() default true;
-
- /**
- * Returns the Service dependency OSGi filter.
- */
- String filter() default "";
-
- /**
- * Specifies if the resource URL properties must be propagated. If set to true, then the URL properties
- * ("protocol"/"host"/"port"/"path") will be propagated to the service properties of the component which
- * is using this dependency.
- */
- boolean propagate() default false;
-
- /**
- * The name used when dynamically configuring this dependency from the init method.
- * Specifying this attribute allows to dynamically configure the dependency
- * <code>filter</code> and <code>required</code> flag from the Service's init method.
- * All unnamed dependencies will be injected before the init() method; so from the init() method, you can
- * then pick up whatever information needed from already injected (unnamed) dependencies, and configure dynamically
- * your named dependencies, which will then be calculated once the init() method returns.
- */
- String name() default "";
-}
diff --git a/dependencymanager/annotation/src/main/java/org/apache/felix/dm/annotation/api/ServiceDependency.java b/dependencymanager/annotation/src/main/java/org/apache/felix/dm/annotation/api/ServiceDependency.java
deleted file mode 100644
index f935992..0000000
--- a/dependencymanager/annotation/src/main/java/org/apache/felix/dm/annotation/api/ServiceDependency.java
+++ /dev/null
@@ -1,186 +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.felix.dm.annotation.api;
-
-import java.lang.annotation.ElementType;
-import java.lang.annotation.Retention;
-import java.lang.annotation.RetentionPolicy;
-import java.lang.annotation.Target;
-
-/**
- * Annotates a method or a field for injecting a Service Dependency. When applied on a class
- * field, optional unavailable dependencies are injected with a NullObject.
- *
- * <h3>Usage Examples</h3>
- * Here, the MyComponent component is injected with a dependency over a "MyDependency" service
- *
- * <blockquote><pre>
- * @Component
- * class MyComponent {
- * @ServiceDependency(timeout=15000)
- * MyDependency dependency;
- * </pre></blockquote>
- *
- * @author <a href="mailto:dev@felix.apache.org">Felix Project Team</a>
- */
-@Retention(RetentionPolicy.CLASS)
-@Target({ElementType.METHOD, ElementType.FIELD})
-public @interface ServiceDependency
-{
- /**
- * The type if the service this dependency is applying on. By default, the method parameter
- * (or the class field) is used as the type.
- */
- Class<?> service() default Object.class;
-
- /**
- * The Service dependency OSGi filter.
- */
- String filter() default "";
-
- /**
- * The class for the default implementation, if the dependency is not available.
- */
- Class<?> defaultImpl() default Object.class;
-
- /**
- * Whether the Service dependency is required or not.
- */
- boolean required() default true;
-
- /**
- * The callback method to be invoked when the service is available. This attribute is only meaningful when
- * the annotation is applied on a class field.
- */
- String added() default "";
-
- /**
- * The callback method to be invoked when the service properties have changed.
- */
- String changed() default "";
-
- /**
- * The callback method to invoke when the service is lost.
- */
- String removed() default "";
-
- /**
- * The max time in millis to wait for the dependency availability.
- * Specifying a positive number allow to block the caller thread between service updates. Only
- * useful for required stateless dependencies that can be replaced transparently.
- * A Dynamic Proxy is used to wrap the actual service dependency (which must be an interface).
- * When the dependency goes away, an attempt is made to replace it with another one which satisfies
- * the service dependency criteria. If no service replacement is available, then any method invocation
- * (through the dynamic proxy) will block during a configurable timeout. On timeout, an unchecked
- * <code>IllegalStateException</code> exception is raised (but the service is not deactivated).<p>
- * Notice that the changed/removed callbacks are not used when the timeout parameter is > -1.
- * <p>
- *
- * -1 means no timeout at all (default). 0 means that invocation on a missing service will fail
- * immediately. A positive number represents the max timeout in millis to wait for the service availability.
- *
- * <p> Sample Code:<p>
- * <blockquote><pre>
- * @Component
- * class MyServer implements Runnable {
- * @ServiceDependency(timeout=15000)
- * MyDependency dependency;.
- *
- * @Start
- * void start() {
- * (new Thread(this)).start();
- * }
- *
- * public void run() {
- * try {
- * dependency.doWork();
- * } catch (IllegalStateException e) {
- * t.printStackTrace();
- * }
- * }
- * </pre></blockquote>
- */
- long timeout() default -1;
-
- /**
- * The name used when dynamically configuring this dependency from the init method.
- * Specifying this attribute allows to dynamically configure the dependency
- * <code>filter</code> and <code>required</code> flag from the Service's init method.
- * All unnamed dependencies will be injected before the init() method; so from the init() method, you can
- * then pick up whatever information needed from already injected (unnamed) dependencies, and configure dynamically
- * your named dependencies, which will then be calculated once the init() method returns.
- *
- * <p> Usage example of a Service whose dependency filter is configured from ConfigAdmin:
- *
- * <blockquote><pre>
- * /**
- * * A Service whose service dependency "otherService" filter is configured from ConfigAdmin
- * */
- * @Service
- * class X {
- * private Dictionary m_config;
- *
- * /**
- * * Initialize our service from config ... and store the config for later usage (from our init method)
- * */
- * @ConfigurationDependency(pid="MyPid")
- * void configure(Dictionary conf) {
- * m_config = config;
- * }
- *
- * /**
- * * All unnamed dependencies are injected: we can now configure other named
- * * dependencies, using the already injected configuration.
- * * The returned Map will be used to configure our "otherService" Dependency.
- * */
- * @Init
- * Map init() {
- * return new HashMap() {{
- * put("otherService.filter", m_config.get("filter"));
- * put("otherService.required", m_config.get("required"));
- * }};
- * }
- *
- * /**
- * * This named dependency filter/required flag will be configured by our init method (see above).
- * */
- * @ServiceDependency(name="otherService")
- * void bindOtherService(OtherService other) {
- * }
- *
- * /**
- * * All dependencies are injected and our service is now ready to be published.
- * * Notice that you can also use the publisher service attribute if you need
- * * to take control on service exposition.
- * */
- * @Start
- * void start() {
- * }
- * }
- * </pre></blockquote>
- */
- String name() default "";
-
- /**
- * Returns true if the dependency service properties must be published along with the service.
- * Any additional service properties specified directly are merged with these.
- * @return true if dependency service properties must be published along with the service, false if not.
- */
- boolean propagate() default false;
-}
diff --git a/dependencymanager/annotation/src/main/java/org/apache/felix/dm/annotation/api/Start.java b/dependencymanager/annotation/src/main/java/org/apache/felix/dm/annotation/api/Start.java
deleted file mode 100644
index da61b70..0000000
--- a/dependencymanager/annotation/src/main/java/org/apache/felix/dm/annotation/api/Start.java
+++ /dev/null
@@ -1,63 +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.felix.dm.annotation.api;
-
-import java.lang.annotation.ElementType;
-import java.lang.annotation.Retention;
-import java.lang.annotation.RetentionPolicy;
-import java.lang.annotation.Target;
-
-/**
- * Annotates a method which will be invoked when the component is started.
- * The annotated method is invoked juste before registering the service into the OSGi registry
- * (if the service provides an interface). Notice that the start method may optionally return
- * a Map which will be propagated to the provided service properties.<p>
- * Service activation/deactivation can be programatically controlled using {@link LifecycleController}.
- *
- * <p>
- * <h3>Usage Examples</h3>
- * <blockquote>
- *
- * <pre>
- * @Component(properties={@Property(name="foo", value="bar")})
- * class X implements Z {
- * @ServiceDependency
- * OtherService m_dependency;
- *
- * @Start
- * Map start() {
- * // Our Z Service is ready (all required dependencies have been satisfied), and is about to be
- * // registered into the OSGi registry. We return here an optional Map containing some extra-properties
- * // which will be appended to the properties supplied in the Component annotation.
- * return new HashMap() {{
- * put("foo2", "bar2");
- * put(Constants.SERVICE_RANKING, Integer.valueOf(10));
- * }};
- * }
- * }
- * </pre>
- * </blockquote>
- *
- * @author <a href="mailto:dev@felix.apache.org">Felix Project Team</a>
- */
-@Retention(RetentionPolicy.CLASS)
-@Target(ElementType.METHOD)
-public @interface Start
-{
-}
diff --git a/dependencymanager/annotation/src/main/java/org/apache/felix/dm/annotation/api/Stop.java b/dependencymanager/annotation/src/main/java/org/apache/felix/dm/annotation/api/Stop.java
deleted file mode 100644
index 672b7ea..0000000
--- a/dependencymanager/annotation/src/main/java/org/apache/felix/dm/annotation/api/Stop.java
+++ /dev/null
@@ -1,54 +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.felix.dm.annotation.api;
-
-import java.lang.annotation.ElementType;
-import java.lang.annotation.Retention;
-import java.lang.annotation.RetentionPolicy;
-import java.lang.annotation.Target;
-
-/**
- * Annotates a method which is invoked when the Service is being unregistered from the
- * OSGi registry.
- * The method is called when the component's bundle is stopped, or when one of its
- * required dependency is lost, or when a {@link LifecycleController} is programatically used to
- * stop a service.
- * </ul>
- *
- * <h3>Usage Examples</h3>
- * <blockquote>
- * <pre>
- * @Component
- * class MyComponent implements MyService {
- * @ServiceDependency
- * private LogService logService; // Required dependency over the log service.
- *
- * @Stop
- * void stop() {} // We are unregistering from the OSGi registry.
- * }
- * </pre>
- * </blockquote>
- *
- * @author <a href="mailto:dev@felix.apache.org">Felix Project Team</a>
- */
-@Retention(RetentionPolicy.CLASS)
-@Target(ElementType.METHOD)
-public @interface Stop
-{
-}
diff --git a/dependencymanager/annotation/src/main/java/org/apache/felix/dm/annotation/api/Unregistered.java b/dependencymanager/annotation/src/main/java/org/apache/felix/dm/annotation/api/Unregistered.java
deleted file mode 100644
index c59a435..0000000
--- a/dependencymanager/annotation/src/main/java/org/apache/felix/dm/annotation/api/Unregistered.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.felix.dm.annotation.api;
-
-import java.lang.annotation.ElementType;
-import java.lang.annotation.Retention;
-import java.lang.annotation.RetentionPolicy;
-import java.lang.annotation.Target;
-
-/**
- * This annotation can be used to be notified when a component is unregistered from the registry.
- * At this point, the component has been unregistered from the OSGI registry (if it provides some services).
- * The method must not take any parameters.
- *
- * <p>
- * <h3>Usage Examples</h3>
- * <blockquote>
- *
- * <pre>
- * @Component
- * class X implements Z {
- * @Stop
- * void stop(ServiceRegistration sr) {
- * // Our service must stop because it is about to be unregistered from the registry.
- * }
- *
- * @Unregistered
- * void unregistered() {
- * // At this point, our service has been unregistered from the OSGi registry
- * }
- * }
- * </pre>
- * </blockquote>
- *
- * @author <a href="mailto:dev@felix.apache.org">Felix Project Team</a>
- */
-@Retention(RetentionPolicy.CLASS)
-@Target(ElementType.METHOD)
-public @interface Unregistered
-{
-}
diff --git a/dependencymanager/annotation/src/main/java/org/apache/felix/dm/annotation/plugin/bnd/AnnotationCollector.java b/dependencymanager/annotation/src/main/java/org/apache/felix/dm/annotation/plugin/bnd/AnnotationCollector.java
deleted file mode 100644
index a17f3ec..0000000
--- a/dependencymanager/annotation/src/main/java/org/apache/felix/dm/annotation/plugin/bnd/AnnotationCollector.java
+++ /dev/null
@@ -1,1274 +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.felix.dm.annotation.plugin.bnd;
-
-import java.io.PrintWriter;
-import java.util.ArrayList;
-import java.util.Arrays;
-import java.util.HashSet;
-import java.util.List;
-import java.util.Set;
-
-import org.apache.felix.dm.annotation.api.AdapterService;
-import org.apache.felix.dm.annotation.api.AspectService;
-import org.apache.felix.dm.annotation.api.BundleAdapterService;
-import org.apache.felix.dm.annotation.api.BundleDependency;
-import org.apache.felix.dm.annotation.api.Component;
-import org.apache.felix.dm.annotation.api.Composition;
-import org.apache.felix.dm.annotation.api.ConfigurationDependency;
-import org.apache.felix.dm.annotation.api.Destroy;
-import org.apache.felix.dm.annotation.api.FactoryConfigurationAdapterService;
-import org.apache.felix.dm.annotation.api.Init;
-import org.apache.felix.dm.annotation.api.Inject;
-import org.apache.felix.dm.annotation.api.LifecycleController;
-import org.apache.felix.dm.annotation.api.Registered;
-import org.apache.felix.dm.annotation.api.ResourceAdapterService;
-import org.apache.felix.dm.annotation.api.ResourceDependency;
-import org.apache.felix.dm.annotation.api.ServiceDependency;
-import org.apache.felix.dm.annotation.api.Start;
-import org.apache.felix.dm.annotation.api.Stop;
-import org.apache.felix.dm.annotation.api.Unregistered;
-import org.json.JSONArray;
-import org.json.JSONException;
-import org.json.JSONObject;
-import org.osgi.framework.Bundle;
-
-import aQute.bnd.osgi.Annotation;
-import aQute.bnd.osgi.ClassDataCollector;
-import aQute.bnd.osgi.Clazz;
-import aQute.bnd.osgi.Descriptors.TypeRef;
-import aQute.bnd.osgi.Verifier;
-
-/**
- * This is the scanner which does all the annotation parsing on a given class.
- * To start the parsing, just invoke the parseClassFileWithCollector and finish methods.
- * Once parsed, the corresponding component descriptors can be built using the "writeTo" method.
- *
- * @author <a href="mailto:dev@felix.apache.org">Felix Project Team</a>
- */
-public class AnnotationCollector extends ClassDataCollector
-{
- private final static String A_INIT = Init.class.getName();
- private final static String A_START = Start.class.getName();
- private final static String A_STOP = Stop.class.getName();
- private final static String A_DESTROY = Destroy.class.getName();
- private final static String A_COMPOSITION = Composition.class.getName();
- private final static String A_LIFCLE_CTRL = LifecycleController.class.getName();
-
- private final static String A_COMPONENT = Component.class.getName();
- private final static String A_SERVICE_DEP = ServiceDependency.class.getName();
- private final static String A_CONFIGURATION_DEPENDENCY = ConfigurationDependency.class.getName();
- private final static String A_BUNDLE_DEPENDENCY = BundleDependency.class.getName();
- private final static String A_RESOURCE_DEPENDENCY = ResourceDependency.class.getName();
- private final static String A_ASPECT_SERVICE = AspectService.class.getName();
- private final static String A_ADAPTER_SERVICE = AdapterService.class.getName();
- private final static String A_BUNDLE_ADAPTER_SERVICE = BundleAdapterService.class.getName();
- private final static String A_RESOURCE_ADAPTER_SERVICE = ResourceAdapterService.class.getName();
- private final static String A_FACTORYCONFIG_ADAPTER_SERVICE = FactoryConfigurationAdapterService.class.getName();
- private final static String A_INJECT = Inject.class.getName();
- private final static String A_REGISTERED = Registered.class.getName();
- private final static String A_UNREGISTERED = Unregistered.class.getName();
-
- private Logger m_logger;
- private String m_className;
- private String[] m_interfaces;
- private boolean m_isField;
- private String m_field;
- private String m_method;
- private String m_descriptor;
- private Set<String> m_dependencyNames = new HashSet<String>();
- private List<EntryWriter> m_writers = new ArrayList<EntryWriter>(); // Last elem is either Service or AspectService
- private MetaType m_metaType;
- private String m_startMethod;
- private String m_stopMethod;
- private String m_initMethod;
- private String m_destroyMethod;
- private String m_compositionMethod;
- private String m_starter;
- private String m_stopper;
- private Set<String> m_importService = new HashSet<String>();
- private Set<String> m_exportService = new HashSet<String>();
- private String m_bundleContextField;
- private String m_dependencyManagerField;
- private String m_componentField;
- private String m_registeredMethod;
- private String m_unregisteredMethod;
-
- /**
- * This class represents a DependencyManager component descriptor entry.
- * (Service, a ServiceDependency ... see EntryType enum).
- */
-
- /**
- * Makes a new Collector for parsing a given class.
- * @param reporter the object used to report logs.
- */
- public AnnotationCollector(Logger reporter, MetaType metaType)
- {
- m_logger = reporter;
- m_metaType = metaType;
- }
-
- /**
- * Parses the name of the class.
- * @param access the class access
- * @param name the class name (package are "/" separated).
- */
- @Override
- public void classBegin(int access, TypeRef name)
- {
- m_className = name.getFQN();
- m_logger.debug("class name: %s", m_className);
- }
-
- /**
- * Parses the implemented interfaces ("/" separated).
- */
- @Override
- public void implementsInterfaces(TypeRef[] interfaces)
- {
- List<String> result = new ArrayList<String>();
- for (int i = 0; i < interfaces.length; i++)
- {
- if (!interfaces[i].getBinary().equals("scala/ScalaObject"))
- {
- result.add(interfaces[i].getFQN());
- }
- }
-
- m_interfaces = result.toArray(new String[result.size()]);
- m_logger.debug("implements: %s", Arrays.toString(m_interfaces));
- }
-
- /**
- * Parses a method. Always invoked BEFORE eventual method annotation.
- */
- @Override
- public void method(Clazz.MethodDef method)
- {
- m_logger.debug("Parsed method %s, descriptor=%s", method.getName(), method.getDescriptor());
- m_isField = false;
- m_method = method.getName();
- m_descriptor = method.getDescriptor().toString();
- }
-
- /**
- * Parses a field. Always invoked BEFORE eventual field annotation
- */
- @Override
- public void field(Clazz.FieldDef field)
- {
- m_logger.debug("Parsed field %s, descriptor=%s", field.getName(), field.getDescriptor());
- m_isField = true;
- m_field = field.getName();
- m_descriptor = field.getDescriptor().toString();
- }
-
- /**
- * An annotation has been parsed. Always invoked AFTER the "method"/"field"/"classBegin" callbacks.
- */
- @Override
- public void annotation(Annotation annotation)
- {
- m_logger.debug("Parsing annotation: %s", annotation.getName());
-
- if (annotation.getName().getFQN().equals(A_COMPONENT))
- {
- parseComponentAnnotation(annotation);
- }
- else if (annotation.getName().getFQN().equals(A_ASPECT_SERVICE))
- {
- parseAspectService(annotation);
- }
- else if (annotation.getName().getFQN().equals(A_ADAPTER_SERVICE))
- {
- parseAdapterService(annotation);
- }
- else if (annotation.getName().getFQN().equals(A_BUNDLE_ADAPTER_SERVICE))
- {
- parseBundleAdapterService(annotation);
- }
- else if (annotation.getName().getFQN().equals(A_RESOURCE_ADAPTER_SERVICE))
- {
- parseResourceAdapterService(annotation);
- }
- else if (annotation.getName().getFQN().equals(A_FACTORYCONFIG_ADAPTER_SERVICE))
- {
- parseFactoryConfigurationAdapterService(annotation);
- }
- else if (annotation.getName().getFQN().equals(A_INIT))
- {
- m_initMethod = m_method;
- }
- else if (annotation.getName().getFQN().equals(A_START))
- {
- m_startMethod = m_method;
- }
- else if (annotation.getName().getFQN().equals(A_REGISTERED))
- {
- m_registeredMethod = m_method;
- }
- else if (annotation.getName().getFQN().equals(A_STOP))
- {
- m_stopMethod = m_method;
- }
- else if (annotation.getName().getFQN().equals(A_UNREGISTERED))
- {
- m_unregisteredMethod = m_method;
- }
- else if (annotation.getName().getFQN().equals(A_DESTROY))
- {
- m_destroyMethod = m_method;
- }
- else if (annotation.getName().getFQN().equals(A_COMPOSITION))
- {
- Patterns.parseMethod(m_method, m_descriptor, Patterns.COMPOSITION);
- m_compositionMethod = m_method;
- } else if (annotation.getName().getFQN().equals(A_LIFCLE_CTRL))
- {
- parseLifecycleAnnotation(annotation);
- }
- else if (annotation.getName().getFQN().equals(A_SERVICE_DEP))
- {
- parseServiceDependencyAnnotation(annotation);
- }
- else if (annotation.getName().getFQN().equals(A_CONFIGURATION_DEPENDENCY))
- {
- parseConfigurationDependencyAnnotation(annotation);
- }
- else if (annotation.getName().getFQN().equals(A_BUNDLE_DEPENDENCY))
- {
- parseBundleDependencyAnnotation(annotation);
- }
- else if (annotation.getName().getFQN().equals(A_RESOURCE_DEPENDENCY))
- {
- parseRersourceDependencyAnnotation(annotation);
- }
- else if (annotation.getName().getFQN().equals(A_INJECT))
- {
- parseInject(annotation);
- }
- }
-
- /**
- * Finishes up the class parsing. This method must be called once the parseClassFileWithCollector method has returned.
- * @return true if some annotations have been parsed, false if not.
- */
- public boolean finish()
- {
- if (m_writers.size() == 0)
- {
- m_logger.info("No components found for class " + m_className);
- return false;
- }
-
- // We must have at least a Service annotation.
- checkServiceDeclared(EntryType.Component, EntryType.AspectService, EntryType.AdapterService,
- EntryType.BundleAdapterService,
- EntryType.ResourceAdapterService, EntryType.FactoryConfigurationAdapterService);
-
- StringBuilder sb = new StringBuilder();
- sb.append("Parsed annotation for class ");
- sb.append(m_className);
- for (int i = m_writers.size() - 1; i >= 0; i--)
- {
- sb.append("\n\t").append(m_writers.get(i).toString());
- }
- m_logger.info(sb.toString());
- return true;
- }
-
- /**
- * Writes the generated component descriptor in the given print writer.
- * The first line must be the service (@Service or AspectService).
- * @param pw the writer where the component descriptor will be written.
- */
- public void writeTo(PrintWriter pw)
- {
- // The last element our our m_writers list contains either the Service, or the AspectService descriptor.
- for (int i = m_writers.size() - 1; i >= 0; i--)
- {
- pw.println(m_writers.get(i).toString());
- }
- }
-
- /**
- * Returns list of all imported services. Imported services are deduced from every
- * @ServiceDependency annotations.
- * @return the list of imported services, or null
- */
- public Set<String> getImportService()
- {
- return m_importService;
- }
-
- /**
- * Returns list of all exported services. Imported services are deduced from every
- * annotations which provides a service (@Component, etc ...)
- * @return the list of exported services, or null
- */
- public Set<String> getExportService()
- {
- return m_exportService;
- }
-
- private void parseComponentAnnotation(Annotation annotation)
- {
- EntryWriter writer = new EntryWriter(EntryType.Component);
- m_writers.add(writer);
-
- // Register previously parsed annotations common to services (Init/Start/...)
- addCommonServiceParams(writer);
-
- // impl attribute
- writer.put(EntryParam.impl, m_className);
-
- // properties attribute
- parseProperties(annotation, EntryParam.properties, writer);
-
- // provides attribute.
- if (writer.putClassArray(annotation, EntryParam.provides, m_interfaces, m_exportService) == 0)
- {
- // no service provided: check if @Registered/@Unregistered annotation are used
- // and raise an error if true.
- checkRegisteredUnregisteredNotPresent();
- }
-
- // factorySet attribute
- String factorySetName = writer.putString(annotation, EntryParam.factorySet, null);
- if (factorySetName != null)
- {
- // When a component defines a factorySet, it means that a java.util.Set will
- // be provided into the OSGi registry, in order to let anoter component add
- // some component instance configurations into it.
- // So, we have to indicate that the Set is provided as a service, in the Export-Serviec
- // header.
- m_exportService.add("java.util.Set");
- }
-
- // factoryConfigure attribute
- writer.putString(annotation, EntryParam.factoryConfigure, null);
-
- // factoryMethod attribute
- writer.putString(annotation, EntryParam.factoryMethod, null);
- }
-
- private void addCommonServiceParams(EntryWriter writer)
- {
- if (m_initMethod != null)
- {
- writer.put(EntryParam.init, m_initMethod);
- }
-
- if (m_startMethod != null)
- {
- writer.put(EntryParam.start, m_startMethod);
- }
-
- if (m_registeredMethod != null)
- {
- writer.put(EntryParam.registered, m_registeredMethod);
- }
-
- if (m_stopMethod != null)
- {
- writer.put(EntryParam.stop, m_stopMethod);
- }
-
- if (m_unregisteredMethod != null)
- {
- writer.put(EntryParam.unregistered, m_unregisteredMethod);
- }
-
- if (m_destroyMethod != null)
- {
- writer.put(EntryParam.destroy, m_destroyMethod);
- }
-
- if (m_compositionMethod != null)
- {
- writer.put(EntryParam.composition, m_compositionMethod);
- }
-
- if (m_starter != null)
- {
- writer.put(EntryParam.starter, m_starter);
- }
-
- if (m_stopper != null)
- {
- writer.put(EntryParam.stopper, m_stopper);
- if (m_starter == null)
- {
- throw new IllegalArgumentException("Can't use a @LifecycleController annotation for stopping a service without declaring a " +
- "@LifecycleController that starts the component in class " + m_className);
- }
- }
-
- if (m_bundleContextField != null)
- {
- writer.put(EntryParam.bundleContextField, m_bundleContextField);
- }
-
- if (m_dependencyManagerField != null)
- {
- writer.put(EntryParam.dependencyManagerField, m_dependencyManagerField);
- }
-
- if (m_componentField != null)
- {
- writer.put(EntryParam.componentField, m_componentField);
- }
- }
-
- /**
- * Parses a ServiceDependency Annotation.
- * @param annotation the ServiceDependency Annotation.
- */
- private void parseServiceDependencyAnnotation(Annotation annotation)
- {
- EntryWriter writer = new EntryWriter(EntryType.ServiceDependency);
- m_writers.add(writer);
-
- // service attribute
- String service = annotation.get(EntryParam.service.toString());
- if (service != null)
- {
- service = Patterns.parseClass(service, Patterns.CLASS, 1);
- }
- else
- {
- if (m_isField)
- {
- service = Patterns.parseClass(m_descriptor, Patterns.CLASS, 1);
- }
- else
- {
- service = Patterns.parseClass(m_descriptor, Patterns.BIND_CLASS, 2);
- }
- }
- writer.put(EntryParam.service, service);
-
- // Store this service in list of imported services.
- m_importService.add(service);
-
- // autoConfig attribute
- if (m_isField)
- {
- writer.put(EntryParam.autoConfig, m_field);
- }
-
- // filter attribute
- String filter = annotation.get(EntryParam.filter.toString());
- if (filter != null)
- {
- Verifier.verifyFilter(filter, 0);
- writer.put(EntryParam.filter, filter);
- }
-
- // defaultImpl attribute
- writer.putClass(annotation, EntryParam.defaultImpl, null);
-
- // added callback
- writer.putString(annotation, EntryParam.added, (!m_isField) ? m_method : null);
-
- // timeout parameter
- writer.putString(annotation, EntryParam.timeout, null);
- Long t = (Long) annotation.get(EntryParam.timeout.toString());
- if (t != null && t.longValue() < -1)
- {
- throw new IllegalArgumentException("Invalid timeout value " + t + " in ServiceDependency annotation from class " + m_className);
- }
-
- // required attribute (not valid if parsing a temporal service dependency)
- writer.putString(annotation, EntryParam.required, null);
-
- // changed callback
- writer.putString(annotation, EntryParam.changed, null);
-
- // removed callback
- writer.putString(annotation, EntryParam.removed, null);
-
- // name attribute
- parseDependencyName(writer, annotation);
-
- // propagate attribute
- writer.putString(annotation, EntryParam.propagate, null);
- }
-
- /**
- * Parses a ConfigurationDependency annotation.
- * @param annotation the ConfigurationDependency annotation.
- */
- private void parseConfigurationDependencyAnnotation(Annotation annotation)
- {
- EntryWriter writer = new EntryWriter(EntryType.ConfigurationDependency);
- m_writers.add(writer);
-
- // pid attribute
- writer.putString(annotation, EntryParam.pid, m_className);
-
- // the method on which the annotation is applied
- writer.put(EntryParam.updated, m_method);
-
- // propagate attribute
- writer.putString(annotation, EntryParam.propagate, null);
-
- // Property Meta Types
- String pid = get(annotation, EntryParam.pid.toString(), m_className);
- parseMetaTypes(annotation, pid, false);
- }
-
- /**
- * Parses an AspectService annotation.
- * @param annotation
- */
- private void parseAspectService(Annotation annotation)
- {
- EntryWriter writer = new EntryWriter(EntryType.AspectService);
- m_writers.add(writer);
-
- // Register previously parsed Init/Start/Stop/Destroy/Composition annotations
- addCommonServiceParams(writer);
-
- // Parse service filter
- String filter = annotation.get(EntryParam.filter.toString());
- if (filter != null)
- {
- Verifier.verifyFilter(filter, 0);
- writer.put(EntryParam.filter, filter);
- }
-
- // Parse service aspect ranking
- Integer ranking = annotation.get(EntryParam.ranking.toString());
- writer.put(EntryParam.ranking, ranking.toString());
-
- // Generate Aspect Implementation
- writer.put(EntryParam.impl, m_className);
-
- // Parse Aspect properties.
- parseProperties(annotation, EntryParam.properties, writer);
-
- // Parse field/added/changed/removed attributes
- parseAspectOrAdapterCallbackMethods(annotation, writer);
-
- // Parse service interface this aspect is applying to
- Object service = annotation.get(EntryParam.service.toString());
- if (service == null)
- {
- if (m_interfaces == null)
- {
- throw new IllegalStateException("Invalid AspectService annotation: " +
- "the service attribute has not been set and the class " + m_className
- + " does not implement any interfaces");
- }
- if (m_interfaces.length != 1)
- {
- throw new IllegalStateException("Invalid AspectService annotation: " +
- "the service attribute has not been set and the class " + m_className
- + " implements more than one interface");
- }
-
- writer.put(EntryParam.service, m_interfaces[0]);
- }
- else
- {
- writer.putClass(annotation, EntryParam.service, null);
- }
-
- // Parse factoryMethod attribute
- writer.putString(annotation, EntryParam.factoryMethod, null);
- }
-
- private void parseAspectOrAdapterCallbackMethods(Annotation annotation, EntryWriter writer)
- {
- String field = annotation.get(EntryParam.field.toString());
- String added = annotation.get(EntryParam.added.toString());
- String changed = annotation.get(EntryParam.changed.toString());
- String removed = annotation.get(EntryParam.removed.toString());
- String swap = annotation.get(EntryParam.swap.toString());
-
- // "field" and "added/changed/removed/swap" attributes can't be mixed
- if (field != null && (added != null || changed != null || removed != null || swap != null))
- {
- throw new IllegalStateException("Annotation " + annotation + "can't applied on " + m_className
- + " can't mix \"field\" attribute with \"added/changed/removed\" attributes");
- }
-
- // Parse aspect impl field where to inject the original service.
- writer.putString(annotation, EntryParam.field, null);
-
- // Parse aspect impl callback methods.
- writer.putString(annotation, EntryParam.added, null);
- writer.putString(annotation, EntryParam.changed, null);
- writer.putString(annotation, EntryParam.removed, null);
- writer.putString(annotation, EntryParam.swap, null);
- }
-
- /**
- * Parses an AspectService annotation.
- * @param annotation
- */
- private void parseAdapterService(Annotation annotation)
- {
- EntryWriter writer = new EntryWriter(EntryType.AdapterService);
- m_writers.add(writer);
-
- // Register previously parsed Init/Start/Stop/Destroy/Composition annotations
- addCommonServiceParams(writer);
-
- // Generate Adapter Implementation
- writer.put(EntryParam.impl, m_className);
-
- // Parse adaptee filter
- String adapteeFilter = annotation.get(EntryParam.adapteeFilter.toString());
- if (adapteeFilter != null)
- {
- Verifier.verifyFilter(adapteeFilter, 0);
- writer.put(EntryParam.adapteeFilter, adapteeFilter);
- }
-
- // Parse the mandatory adapted service interface.
- writer.putClass(annotation, EntryParam.adapteeService, null);
-
- // Parse Adapter properties.
- parseProperties(annotation, EntryParam.properties, writer);
-
- // Parse the provided adapter service (use directly implemented interface by default).
- if (writer.putClassArray(annotation, EntryParam.provides, m_interfaces, m_exportService) == 0)
- {
- checkRegisteredUnregisteredNotPresent();
- }
-
- // Parse factoryMethod attribute
- writer.putString(annotation, EntryParam.factoryMethod, null);
-
- // Parse field/added/changed/removed attributes
- parseAspectOrAdapterCallbackMethods(annotation, writer);
- }
-
- /**
- * Parses a BundleAdapterService annotation.
- * @param annotation
- */
- private void parseBundleAdapterService(Annotation annotation)
- {
- EntryWriter writer = new EntryWriter(EntryType.BundleAdapterService);
- m_writers.add(writer);
-
- // Register previously parsed Init/Start/Stop/Destroy/Composition annotations
- addCommonServiceParams(writer);
-
- // Generate Adapter Implementation
- writer.put(EntryParam.impl, m_className);
-
- // Parse bundle filter
- String filter = annotation.get(EntryParam.filter.toString());
- if (filter != null)
- {
- Verifier.verifyFilter(filter, 0);
- writer.put(EntryParam.filter, filter);
- }
-
- // Parse stateMask attribute
- writer.putString(annotation, EntryParam.stateMask, Integer.valueOf(
- Bundle.INSTALLED | Bundle.RESOLVED | Bundle.ACTIVE).toString());
-
- // Parse Adapter properties.
- parseProperties(annotation, EntryParam.properties, writer);
-
- // Parse the optional adapter service (use directly implemented interface by default).
- if (writer.putClassArray(annotation, EntryParam.provides, m_interfaces, m_exportService) == 0)
- {
- checkRegisteredUnregisteredNotPresent();
- }
-
- // Parse propagate attribute
- writer.putString(annotation, EntryParam.propagate, Boolean.FALSE.toString());
-
- // Parse factoryMethod attribute
- writer.putString(annotation, EntryParam.factoryMethod, null);
- }
-
- /**
- * Parses a BundleAdapterService annotation.
- * @param annotation
- */
- private void parseResourceAdapterService(Annotation annotation)
- {
- EntryWriter writer = new EntryWriter(EntryType.ResourceAdapterService);
- m_writers.add(writer);
-
- // Register previously parsed Init/Start/Stop/Destroy/Composition annotations
- addCommonServiceParams(writer);
-
- // Generate Adapter Implementation
- writer.put(EntryParam.impl, m_className);
-
- // Parse resource filter
- String filter = annotation.get(EntryParam.filter.toString());
- if (filter != null)
- {
- Verifier.verifyFilter(filter, 0);
- writer.put(EntryParam.filter, filter);
- }
-
- // Parse Adapter properties.
- parseProperties(annotation, EntryParam.properties, writer);
-
- // Parse the provided adapter service (use directly implemented interface by default).
- if (writer.putClassArray(annotation, EntryParam.provides, m_interfaces, m_exportService) == 0)
- {
- checkRegisteredUnregisteredNotPresent();
- }
-
- // Parse propagate attribute
- writer.putString(annotation, EntryParam.propagate, Boolean.FALSE.toString());
-
- // Parse changed attribute
- writer.putString(annotation, EntryParam.changed, null);
- }
-
- /**
- * Parses a Factory Configuration Adapter annotation.
- * @param annotation
- */
- private void parseFactoryConfigurationAdapterService(Annotation annotation)
- {
- EntryWriter writer = new EntryWriter(EntryType.FactoryConfigurationAdapterService);
- m_writers.add(writer);
-
- // Register previously parsed Init/Start/Stop/Destroy/Composition annotations
- addCommonServiceParams(writer);
-
- // Generate Adapter Implementation
- writer.put(EntryParam.impl, m_className);
-
- // Parse factory Pid
- writer.putString(annotation, EntryParam.factoryPid, m_className);
-
- // Parse updated callback
- writer.putString(annotation, EntryParam.updated, "updated");
-
- // propagate attribute
- writer.putString(annotation, EntryParam.propagate, Boolean.FALSE.toString());
-
- // Parse the provided adapter service (use directly implemented interface by default).
- if (writer.putClassArray(annotation, EntryParam.provides, m_interfaces, m_exportService) == 0)
- {
- checkRegisteredUnregisteredNotPresent();
- }
-
- // Parse Adapter properties.
- parseProperties(annotation, EntryParam.properties, writer);
-
- // Parse optional meta types for configuration description.
- String factoryPid = get(annotation, EntryParam.factoryPid.toString(), m_className);
- parseMetaTypes(annotation, factoryPid, true);
-
- // Parse factoryMethod attribute
- writer.putString(annotation, EntryParam.factoryMethod, null);
- }
-
- private void parseBundleDependencyAnnotation(Annotation annotation)
- {
- EntryWriter writer = new EntryWriter(EntryType.BundleDependency);
- m_writers.add(writer);
-
- String filter = annotation.get(EntryParam.filter.toString());
- if (filter != null)
- {
- Verifier.verifyFilter(filter, 0);
- writer.put(EntryParam.filter, filter);
- }
-
- writer.putString(annotation, EntryParam.added, m_method);
- writer.putString(annotation, EntryParam.changed, null);
- writer.putString(annotation, EntryParam.removed, null);
- writer.putString(annotation, EntryParam.required, null);
- writer.putString(annotation, EntryParam.stateMask, null);
- writer.putString(annotation, EntryParam.propagate, null);
- parseDependencyName(writer, annotation);
- }
-
- private void parseRersourceDependencyAnnotation(Annotation annotation)
- {
- EntryWriter writer = new EntryWriter(EntryType.ResourceDependency);
- m_writers.add(writer);
-
- String filter = annotation.get(EntryParam.filter.toString());
- if (filter != null)
- {
- Verifier.verifyFilter(filter, 0);
- writer.put(EntryParam.filter, filter);
- }
-
- if (m_isField)
- {
- writer.put(EntryParam.autoConfig, m_field);
- }
-
- writer.putString(annotation, EntryParam.added, (!m_isField) ? m_method : null);
- writer.putString(annotation, EntryParam.changed, null);
- writer.putString(annotation, EntryParam.removed, null);
- writer.putString(annotation, EntryParam.required, null);
- writer.putString(annotation, EntryParam.propagate, null);
- writer.putString(annotation, EntryParam.factoryMethod, null);
- parseDependencyName(writer, annotation);
- }
-
- /**
- * Parse the name of a given dependency.
- * @param writer The writer where to write the dependency name
- * @param annotation the dependency to be parsed
- */
- private void parseDependencyName(EntryWriter writer, Annotation annotation)
- {
- String name = annotation.get(EntryParam.name.toString());
- if (name != null)
- {
- if(! m_dependencyNames.add(name))
- {
- throw new IllegalArgumentException("Duplicate dependency name " + name + " in Dependency " + annotation + " from class " + m_className);
- }
- writer.put(EntryParam.name, name);
- }
- }
-
- private void parseLifecycleAnnotation(Annotation annotation)
- {
- Patterns.parseField(m_field, m_descriptor, Patterns.RUNNABLE);
- if ("true".equals(get(annotation,EntryParam.start.name(), "true")))
- {
- if (m_starter != null) {
- throw new IllegalStateException("Lifecycle annotation already defined on field " +
- m_starter + " in class " + m_className);
- }
- m_starter = m_field;
- } else {
- if (m_stopper != null) {
- throw new IllegalStateException("Lifecycle annotation already defined on field " +
- m_stopper + " in class " + m_className);
- }
- m_stopper = m_field;
- }
- }
-
- /**
- * Parse optional meta types annotation attributes
- * @param annotation
- */
- private void parseMetaTypes(Annotation annotation, String pid, boolean factory)
- {
- if (annotation.get("metadata") != null)
- {
- String propertiesHeading = annotation.get("heading");
- String propertiesDesc = annotation.get("description");
-
- MetaType.OCD ocd = new MetaType.OCD(pid, propertiesHeading, propertiesDesc);
- for (Object p: (Object[]) annotation.get("metadata"))
- {
- Annotation property = (Annotation) p;
- String heading = property.get("heading");
- String id = property.get("id");
- String type = (String) property.get("type");
- type = (type != null) ? Patterns.parseClass(type, Patterns.CLASS, 1) : null;
- Object[] defaults = (Object[]) property.get("defaults");
- String description = property.get("description");
- Integer cardinality = property.get("cardinality");
- Boolean required = property.get("required");
-
- MetaType.AD ad = new MetaType.AD(id, type, defaults, heading, description,
- cardinality, required);
-
- Object[] optionLabels = property.get("optionLabels");
- Object[] optionValues = property.get("optionValues");
-
- if (optionLabels == null
- && optionValues != null
- ||
- optionLabels != null
- && optionValues == null
- ||
- (optionLabels != null && optionValues != null && optionLabels.length != optionValues.length))
- {
- throw new IllegalArgumentException("invalid option labels/values specified for property "
- + id +
- " in PropertyMetadata annotation from class " + m_className);
- }
-
- if (optionValues != null)
- {
- for (int i = 0; i < optionValues.length; i++)
- {
- ad.add(new MetaType.Option(optionValues[i].toString(), optionLabels[i].toString()));
- }
- }
-
- ocd.add(ad);
- }
-
- m_metaType.add(ocd);
- MetaType.Designate designate = new MetaType.Designate(pid, factory);
- m_metaType.add(designate);
- m_logger.info("Parsed MetaType Properties from class " + m_className);
- }
- }
-
- /**
- * Parses a Property annotation (which represents a list of key-value pair).
- * The properties are encoded using the following json form:
- *
- * properties ::= key-value-pair*
- * key-value-pair ::= key value
- * value ::= String | String[] | value-type
- * value-type ::= jsonObject with value-type-info
- * value-type-info ::= "type"=primitive java type
- * "value"=String|String[]
- *
- * Exemple:
- *
- * "properties" : {
- * "string-param" : "string-value",
- * "string-array-param" : ["str1", "str2],
- * "long-param" : {"type":"java.lang.Long", "value":"1"}}
- * "long-array-param" : {"type":"java.lang.Long", "value":["1"]}}
- * }
- * }
- *
- * @param annotation the annotation where the Param annotation is defined
- * @param attribute the attribute name which is of Param type
- * @param writer the object where the parsed attributes are written
- */
- private void parseProperties(Annotation annotation, EntryParam attribute, EntryWriter writer)
- {
- try
- {
- Object[] parameters = annotation.get(attribute.toString());
- if (parameters != null)
- {
- JSONObject properties = new JSONObject();
- for (Object p : parameters)
- {
- Annotation a = (Annotation) p;
- String name = (String) a.get("name");
-
- String type = a.get("type");
- Class<?> classType;
- try
- {
- classType = (type == null) ? String.class : Class.forName(Patterns.parseClass(type,
- Patterns.CLASS, 1));
- }
- catch (ClassNotFoundException e)
- {
- // Theorically impossible
- throw new IllegalArgumentException("Invalid Property type " + type
- + " from annotation " + annotation + " in class " + m_className);
- }
-
- Object[] values;
-
- if ((values = a.get("value")) != null)
- {
- values = checkPropertyType(name, classType, values);
- addProperty(properties, name, values, classType);
- }
- else if ((values = a.get("values")) != null)
- { // deprecated
- values = checkPropertyType(name, classType, values);
- addProperty(properties, name, values, classType);
- }
- else if ((values = a.get("longValue")) != null)
- {
- addProperty(properties, name, values, Long.class);
- }
- else if ((values = a.get("doubleValue")) != null)
- {
- addProperty(properties, name, values, Double.class);
- }
- else if ((values = a.get("floatValue")) != null)
- {
- addProperty(properties, name, values, Float.class);
- }
- else if ((values = a.get("intValue")) != null)
- {
- addProperty(properties, name, values, Integer.class);
- }
- else if ((values = a.get("byteValue")) != null)
- {
- addProperty(properties, name, values, Byte.class);
- }
- else if ((values = a.get("charValue")) != null)
- {
- addProperty(properties, name, values, Character.class);
- }
- else if ((values = a.get("booleanValue")) != null)
- {
- addProperty(properties, name, values, Boolean.class);
- }
- else if ((values = a.get("shortValue")) != null)
- {
- addProperty(properties, name, values, Short.class);
- }
- else
- {
- throw new IllegalArgumentException("Missing Property value from annotation "
- + annotation + " in class " + m_className);
- }
- }
- writer.putJsonObject(attribute, properties);
- }
- }
- catch (JSONException e)
- {
- throw new IllegalArgumentException("UNexpected exception while parsing Property from annotation "
- + annotation + " in class " + m_className, e);
- }
- }
-
- /**
- * Checks if a property contains values that are compatible with a give primitive type.
- *
- * @param name the property name
- * @param values the values for the property name
- * @param type the primitive type.
- * @return the same property values, possibly modified if the type is 'Character' (the strings are converted to their character integer values).
- */
- private Object[] checkPropertyType(String name, Class<?> type, Object ... values)
- {
- if (type.equals(String.class))
- {
- return values;
- } else if (type.equals(Long.class)) {
- for (Object value : values) {
- try {
- Long.valueOf(value.toString());
- } catch (NumberFormatException e) {
- throw new IllegalArgumentException("Property \"" + name + "\" in class " + m_className
- + " does not contain a valid Long value (" + value.toString() + ")");
- }
- }
- } else if (type.equals(Double.class)) {
- for (Object value : values) {
- try {
- Double.valueOf(value.toString());
- } catch (NumberFormatException e) {
- throw new IllegalArgumentException("Property \"" + name + "\" in class " + m_className
- + " does not contain a valid Double value (" + value.toString() + ")");
- }
- }
- } else if (type.equals(Float.class)) {
- for (Object value : values) {
- try {
- Float.valueOf(value.toString());
- } catch (NumberFormatException e) {
- throw new IllegalArgumentException("Property \"" + name + "\" in class " + m_className
- + " does not contain a valid Float value (" + value.toString() + ")");
- }
- }
- } else if (type.equals(Integer.class)) {
- for (Object value : values) {
- try {
- Integer.valueOf(value.toString());
- } catch (NumberFormatException e) {
- throw new IllegalArgumentException("Property \"" + name + "\" in class " + m_className
- + " does not contain a valid Integer value (" + value.toString() + ")");
- }
- }
- } else if (type.equals(Byte.class)) {
- for (Object value : values) {
- try {
- Byte.valueOf(value.toString());
- } catch (NumberFormatException e) {
- throw new IllegalArgumentException("Property \"" + name + "\" in class " + m_className
- + " does not contain a valid Byte value (" + value.toString() + ")");
- }
- }
- } else if (type.equals(Character.class)) {
- for (int i = 0; i < values.length; i++)
- {
- try
- {
- // If the string is already an integer, don't modify it
- Integer.valueOf(values[i].toString());
- }
- catch (NumberFormatException e)
- {
- // Converter the character string to its corresponding integer code.
- if (values[i].toString().length() != 1)
- {
- throw new IllegalArgumentException("Property \"" + name + "\" in class "
- + m_className + " does not contain a valid Character value (" + values[i] + ")");
- }
- try
- {
- values[i] = Integer.valueOf(values[i].toString().charAt(0));
- }
- catch (NumberFormatException e2)
- {
- throw new IllegalArgumentException("Property \"" + name + "\" in class "
- + m_className + " does not contain a valid Character value (" + values[i].toString()
- + ")");
- }
- }
- }
- } else if (type.equals(Boolean.class)) {
- for (Object value : values) {
- if (! value.toString().equalsIgnoreCase("false") && ! value.toString().equalsIgnoreCase("true")) {
- throw new IllegalArgumentException("Property \"" + name + "\" in class " + m_className
- + " does not contain a valid Boolean value (" + value.toString() + ")");
- }
- }
- } else if (type.equals(Short.class)) {
- for (Object value : values) {
- try {
- Short.valueOf(value.toString());
- } catch (NumberFormatException e) {
- throw new IllegalArgumentException("Property \"" + name + "\" in class " + m_className
- + " does not contain a valid Short value (" + value.toString() + ")");
- }
- }
- }
-
- return values;
- }
-
- /**
- * Adds a key/value(s) pair in a properties map
- * @param properties the target properties map
- * @param name the property name
- * @param value the property value(s)
- * @param type the property type
- * @throws JSONException
- */
- private void addProperty(JSONObject props, String name, Object value, Class type) throws JSONException {
- if (value.getClass().isArray())
- {
- Object[] array = (Object[]) value;
- if (array.length == 1)
- {
- value = array[0];
- }
- }
-
- if (type.equals(String.class))
- {
- props.put(name, value.getClass().isArray() ? new JSONArray(value) : value);
- }
- else
- {
- JSONObject jsonValue = new JSONObject();
- jsonValue.put("type", type.getName());
- jsonValue.put("value", value.getClass().isArray() ? new JSONArray(value) : value);
- props.put(name, jsonValue);
- }
- }
-
- /**
- * Parse Inject annotation, used to inject some special classes in some fields
- * (BundleContext/DependencyManager etc ...)
- * @param annotation the Inject annotation
- */
- private void parseInject(Annotation annotation)
- {
- if (Patterns.BUNDLE_CONTEXT.matcher(m_descriptor).matches())
- {
- m_bundleContextField = m_field;
- }
- else if (Patterns.DEPENDENCY_MANAGER.matcher(m_descriptor).matches())
- {
- m_dependencyManagerField = m_field;
- }
- else if (Patterns.COMPONENT.matcher(m_descriptor).matches())
- {
- m_componentField = m_field;
- }
- else
- {
- throw new IllegalArgumentException("@Inject annotation can't be applied on the field \"" + m_field
- + "\" in class " + m_className);
- }
- }
-
- /**
- * Checks if the class is annotated with some given annotations. Notice that the Service
- * is always parsed at end of parsing, so, we have to check the last element of our m_writers
- * List.
- * @return true if one of the provided annotations has been found from the parsed class.
- */
- private void checkServiceDeclared(EntryType... types)
- {
- boolean ok = false;
- if (m_writers.size() > 0)
- {
- for (EntryType type: types)
- {
- if (m_writers.get(m_writers.size() - 1).getEntryType() == type)
- {
- ok = true;
- break;
- }
- }
- }
-
- if (!ok)
- {
- throw new IllegalStateException(
- ": the class must be annotated with either one of the following types: "
- + Arrays.toString(types));
- }
- }
-
- /**
- * This method checks if the @Registered and/or @Unregistered annotations have been defined
- * while they should not, because the component does not provide a service.
- */
- private void checkRegisteredUnregisteredNotPresent()
- {
- if (m_registeredMethod != null)
- {
- throw new IllegalStateException("@Registered annotation can't be used on a Component " +
- " which does not provide a service (class=" + m_className + ")");
-
- }
-
- if (m_unregisteredMethod != null)
- {
- throw new IllegalStateException("@Unregistered annotation can't be used on a Component " +
- " which does not provide a service (class=" + m_className + ")");
-
- }
- }
-
- /**
- * Get an annotation attribute, and return a default value if its not present.
- * @param <T> the type of the variable which is assigned to the return value of this method.
- * @param annotation The annotation we are parsing
- * @param name the attribute name to get from the annotation
- * @param defaultValue the default value to return if the attribute is not found in the annotation
- * @return the annotation attribute value, or the defaultValue if not found
- */
- @SuppressWarnings("unchecked")
- private <T> T get(Annotation annotation, String name, T defaultValue)
- {
- T value = (T) annotation.get(name);
- return value != null ? value : defaultValue;
- }
-}
\ No newline at end of file
diff --git a/dependencymanager/annotation/src/main/java/org/apache/felix/dm/annotation/plugin/bnd/AnnotationPlugin.java b/dependencymanager/annotation/src/main/java/org/apache/felix/dm/annotation/plugin/bnd/AnnotationPlugin.java
deleted file mode 100644
index 0d09f2c..0000000
--- a/dependencymanager/annotation/src/main/java/org/apache/felix/dm/annotation/plugin/bnd/AnnotationPlugin.java
+++ /dev/null
@@ -1,179 +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.felix.dm.annotation.plugin.bnd;
-
-import java.io.PrintWriter;
-import java.io.StringWriter;
-import java.util.Iterator;
-import java.util.Map;
-import java.util.Set;
-
-import aQute.bnd.service.AnalyzerPlugin;
-import aQute.bnd.service.Plugin;
-import aQute.bnd.osgi.Analyzer;
-import aQute.bnd.osgi.Resource;
-import aQute.service.reporter.Reporter;
-
-/**
- * This class is a BND plugin. It scans the target bundle and look for DependencyManager annotations.
- * It can be directly used when using ant and can be referenced inside the ".bnd" descriptor, using
- * the "-plugin" parameter.
- *
- * @author <a href="mailto:dev@felix.apache.org">Felix Project Team</a>
- */
-public class AnnotationPlugin implements AnalyzerPlugin, Plugin
-{
- private static final String IMPORT_SERVICE = "Import-Service";
- private static final String EXPORT_SERVICE = "Export-Service";
- private BndLogger m_logger;
- private Reporter m_reporter;
- private boolean m_buildImportExportService;
-
- /**
- * This plugin is called after analysis of the JAR but before manifest
- * generation. When some DM annotations are found, the plugin will add the corresponding
- * DM component descriptors under META-INF/ directory. It will also set the
- * "DependencyManager-Component" manifest header (which references the descriptor paths).
- *
- * @param analyzer the object that is used to retrieve classes containing DM annotations.
- * @return true if the classpath has been modified so that the bundle classpath must be reanalyzed
- * @throws Exception on any errors.
- */
- public boolean analyzeJar(Analyzer analyzer) throws Exception
- {
- analyzer.setExceptions(true);
- try {
- // We'll do the actual parsing using a DescriptorGenerator object.
- DescriptorGenerator generator = new DescriptorGenerator(analyzer, m_logger);
-
- if (generator.execute())
- {
- // We have parsed some annotations: set the OSGi "DependencyManager-Component" header in the target bundle.
- analyzer.setProperty("DependencyManager-Component", generator.getDescriptorPaths());
-
- // Possibly set the Import-Service/Export-Service header
- if (m_buildImportExportService)
- {
- // Don't override Import-Service header, if it is found from the bnd directives.
- if (analyzer.getProperty(IMPORT_SERVICE) == null)
- {
- buildImportExportService(analyzer, IMPORT_SERVICE, generator.getImportService());
- }
-
- // Don't override Export-Service header, if already defined
- if (analyzer.getProperty(EXPORT_SERVICE) == null)
- {
- buildImportExportService(analyzer, EXPORT_SERVICE, generator.getExportService());
- }
- }
-
- // And insert the generated descriptors into the target bundle.
- Map<String, Resource> resources = generator.getDescriptors();
- for (Map.Entry<String, Resource> entry : resources.entrySet())
- {
- analyzer.getJar().putResource(entry.getKey(), entry.getValue());
- }
-
- // Insert the metatype resource, if any.
- Resource metaType = generator.getMetaTypeResource();
- if (metaType != null)
- {
- analyzer.getJar().putResource("OSGI-INF/metatype/metatype.xml", metaType);
- }
- }
- }
-
- catch (Throwable t)
- {
- m_logger.error(parse(t));
- }
-
- // Collect all logs and write it into the analyzer.
- m_logger.getLogs(analyzer);
-
- // When some errors are present in the analyzer logs: it seems that the Bnd ANT task
- // does not report it. So, to work around, we just log the errors ourself, and
- // we throw an Error in case some errors are detected, in order to prevent the bnd ANT
- // task from generating the target bundle.
- if (analyzer.getWarnings().size() > 0)
- {
- for (Iterator<String> e = analyzer.getWarnings().iterator(); e.hasNext();)
- {
- System.out.println(e.next());
- }
- analyzer.getWarnings().clear();
- }
-
- if (analyzer.getErrors().size() > 0)
- {
- for (Iterator<String> e = analyzer.getErrors().iterator(); e.hasNext();)
- {
- System.err.println(e.next());
- }
- analyzer.getErrors().clear();
- throw new Error("DM Annotation plugin failure");
- }
- return false;
- }
-
- private void buildImportExportService(Analyzer analyzer, String header, Set<String> services)
- {
- m_logger.info("building %s header with the following services: %s", header, services);
- if (services.size() > 0)
- {
- StringBuilder sb = new StringBuilder();
- for (String service : services)
- {
- sb.append(service);
- sb.append(",");
- }
- sb.setLength(sb.length() - 1); // skip last comma
- analyzer.setProperty(header, sb.toString());
- }
- }
-
- public void setProperties(Map<String, String> map)
- {
- String logLevel = map.get("log");
- m_logger = new BndLogger(logLevel == null ? "error" : logLevel);
- String generateImportExportService = map.get("build-import-export-service");
- if (generateImportExportService == null)
- {
- generateImportExportService = "true";
- }
- m_buildImportExportService = Boolean.parseBoolean(generateImportExportService);
- }
-
- public void setReporter(Reporter reporter)
- {
- m_reporter = reporter;
- }
-
- /**
- * Parse an exception into a string.
- * @param e The exception to parse
- * @return the parsed exception
- */
- private static String parse(Throwable e) {
- StringWriter buffer = new StringWriter();
- PrintWriter pw = new PrintWriter(buffer);
- e.printStackTrace(pw);
- return (buffer.toString());
- }
-}
diff --git a/dependencymanager/annotation/src/main/java/org/apache/felix/dm/annotation/plugin/bnd/BndLogger.java b/dependencymanager/annotation/src/main/java/org/apache/felix/dm/annotation/plugin/bnd/BndLogger.java
deleted file mode 100644
index 0a249e7..0000000
--- a/dependencymanager/annotation/src/main/java/org/apache/felix/dm/annotation/plugin/bnd/BndLogger.java
+++ /dev/null
@@ -1,83 +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.felix.dm.annotation.plugin.bnd;
-
-import aQute.bnd.osgi.Analyzer;
-import aQute.bnd.osgi.Processor;
-
-/**
- * Clas used to log messages into the bnd logger.
- *
- * @author <a href="mailto:dev@felix.apache.org">Felix Project Team</a>
- */
-public class BndLogger extends Logger
-{
- private Processor m_processor = new Processor();
-
- private final int m_level;
-
- public BndLogger(String level)
- {
- m_level = parseLogLevel(level);
- }
-
- @Override
- public void error(String msg, Object ... args)
- {
- m_processor.error(msg, args);
- }
-
- @Override
- public void error(String msg, Throwable err, Object ... args)
- {
- m_processor.error(msg, err, args);
- }
-
- @Override
- public void warn(String msg , Object ... args)
- {
- if (m_level >= WARN)
- {
- m_processor.warning(msg, args);
- }
- }
-
- @Override
- public void info(String msg, Object ... args)
- {
- if (m_level >= INFO)
- {
- m_processor.warning(msg, args);
- }
- }
-
- @Override
- public void debug(String msg, Object ... args)
- {
- if (m_level >= DEBUG)
- {
- m_processor.warning(msg, args);
- }
- }
-
- public void getLogs(Analyzer to)
- {
- to.getInfo(m_processor, "DependencyManager: ");
- }
-}
diff --git a/dependencymanager/annotation/src/main/java/org/apache/felix/dm/annotation/plugin/bnd/DescriptorGenerator.java b/dependencymanager/annotation/src/main/java/org/apache/felix/dm/annotation/plugin/bnd/DescriptorGenerator.java
deleted file mode 100644
index 846c82d..0000000
--- a/dependencymanager/annotation/src/main/java/org/apache/felix/dm/annotation/plugin/bnd/DescriptorGenerator.java
+++ /dev/null
@@ -1,218 +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.felix.dm.annotation.plugin.bnd;
-
-import java.io.ByteArrayOutputStream;
-import java.io.IOException;
-import java.io.OutputStreamWriter;
-import java.io.PrintWriter;
-import java.util.Collection;
-import java.util.HashMap;
-import java.util.HashSet;
-import java.util.Map;
-import java.util.Set;
-
-import aQute.bnd.osgi.Analyzer;
-import aQute.bnd.osgi.Clazz;
-import aQute.bnd.osgi.EmbeddedResource;
-import aQute.bnd.osgi.Resource;
-import aQute.bnd.osgi.Clazz.QUERY;
-
-/**
- * This helper parses all classes which contain DM annotations, and generates the corresponding component descriptors.
- *
- * @author <a href="mailto:dev@felix.apache.org">Felix Project Team</a>
- */
-public class DescriptorGenerator
-{
- /**
- * This is the bnd analyzer used to lookup classes containing DM annotations.
- */
- private Analyzer m_analyzer;
-
- /**
- * This is the generated Dependency Manager descriptors. The hashtable key is the path
- * to a descriptor. The value is a bnd Resource object which contains the content of a
- * descriptor.
- */
- Map<String, Resource> m_resources = new HashMap<String, Resource>();
-
- /**
- * This is the generated MetaType XML descriptor, if any Properties/Property annotations have been found.
- */
- private Resource m_metaTypeResource;
-
- /**
- * Object used to collect logs.
- */
- private final Logger m_logger;
-
- /**
- * List of imported services found from every ServiceDependency annotations.
- */
- private Set<String> m_importService = new HashSet<String>();
-
- /**
- * List of exported services found from every service providing components.
- */
- private Set<String> m_exportService = new HashSet<String>();
-
- /**
- * Creates a new descriptor generator.
- * @param analyzer The bnd analyzer used to lookup classes containing DM annotations.
- * @param debug
- */
- public DescriptorGenerator(Analyzer analyzer, Logger logger)
- {
- m_analyzer = analyzer;
- m_logger = logger;
- }
-
- /**
- * Starts the scanning.
- * @return true if some annotations were successfully parsed, false if not. corresponding generated
- * descriptors can then be retrieved by invoking the getDescriptors/getDescriptorPaths methods.
- */
- public boolean execute() throws Exception
- {
- boolean annotationsFound = false;
- Clazz clazz = null;
- // Try to locate any classes in the wildcarded universe
- // that are annotated with the DependencyManager "Service" annotations.
- Collection<Clazz> expanded = m_analyzer.getClasses("",
- // Parse everything
- QUERY.NAMED.toString(), "*");
-
- // Create the object which will collect Config Admin MetaTypes.
- MetaType metaType = new MetaType();
-
- for (Clazz c : expanded)
- {
- clazz = c;
- // Let's parse all annotations from that class !
- AnnotationCollector reader = new AnnotationCollector(m_logger, metaType);
- c.parseClassFileWithCollector(reader);
- if (reader.finish())
- {
- // And store the generated component descriptors in our resource list.
- String name = c.getFQN();
- Resource resource = createComponentResource(reader);
- m_resources.put("META-INF/dependencymanager/" + name, resource);
- annotationsFound = true;
-
- m_importService.addAll(reader.getImportService());
- m_exportService.addAll(reader.getExportService());
- }
- }
-
- // If some Meta Types have been parsed, then creates the corresponding resource file.
- if (metaType.getSize() > 0)
- {
- m_metaTypeResource = createMetaTypeResource(metaType);
- }
- return annotationsFound;
- }
-
- /**
- * Returns the path of the descriptor.
- * @return the path of the generated descriptors.
- */
- public String getDescriptorPaths()
- {
- StringBuilder descriptorPaths = new StringBuilder();
- String del = "";
- for (Map.Entry<String, Resource> entry : m_resources.entrySet())
- {
- descriptorPaths.append(del);
- descriptorPaths.append(entry.getKey());
- del = ",";
- }
- return descriptorPaths.toString();
- }
-
- /**
- * Returns the list of the generated descriptors.
- * @return the list of the generated descriptors.
- */
- public Map<String, Resource> getDescriptors()
- {
- return m_resources;
- }
-
- /**
- * Returns the MetaType resource.
- */
- public Resource getMetaTypeResource() {
- return m_metaTypeResource;
- }
-
- /**
- * Returns set of all imported services. Imported services are deduced from every
- * @ServiceDependency annotations.
- * @return the list of imported services
- */
- public Set<String> getImportService()
- {
- return m_importService;
- }
-
- /**
- * Returns set of all exported services. Imported services are deduced from every
- * annotations which provides a service (@Component, etc ...)
- * @return the list of exported services
- */
- public Set<String> getExportService()
- {
- return m_exportService;
- }
-
- /**
- * Creates a bnd resource that contains the generated dm descriptor.
- * @param collector
- * @return
- * @throws IOException
- */
- private Resource createComponentResource(AnnotationCollector collector) throws IOException
- {
- ByteArrayOutputStream out = new ByteArrayOutputStream();
- PrintWriter pw = new PrintWriter(new OutputStreamWriter(out, "UTF-8"));
- collector.writeTo(pw);
- pw.close();
- byte[] data = out.toByteArray();
- out.close();
- return new EmbeddedResource(data, 0);
- }
-
- /**
- * Creates a bnd resource that contains the generated metatype descriptor.
- * @param metaType the Object that has collected all meta type informations.
- * @return the meta type resource
- * @throws IOException on any errors
- */
- private Resource createMetaTypeResource(MetaType metaType) throws IOException
- {
- ByteArrayOutputStream out = new ByteArrayOutputStream();
- PrintWriter pw = new PrintWriter(new OutputStreamWriter(out, "UTF-8"));
- metaType.writeTo(pw);
- pw.close();
- byte[] data = out.toByteArray();
- out.close();
- return new EmbeddedResource(data, 0);
- }
-}
\ No newline at end of file
diff --git a/dependencymanager/annotation/src/main/java/org/apache/felix/dm/annotation/plugin/bnd/EntryParam.java b/dependencymanager/annotation/src/main/java/org/apache/felix/dm/annotation/plugin/bnd/EntryParam.java
deleted file mode 100644
index 6df8188..0000000
--- a/dependencymanager/annotation/src/main/java/org/apache/felix/dm/annotation/plugin/bnd/EntryParam.java
+++ /dev/null
@@ -1,66 +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.felix.dm.annotation.plugin.bnd;
-
-/**
- * The type of parameters which can be found in a component descriptor.
- *
- * @author <a href="mailto:dev@felix.apache.org">Felix Project Team</a>
- */
-public enum EntryParam
-{
- init,
- start,
- stop,
- destroy,
- impl,
- provides,
- properties,
- composition,
- service,
- filter,
- defaultImpl,
- required,
- added,
- changed,
- removed,
- swap,
- autoConfig,
- pid,
- factoryPid,
- propagate,
- updated,
- timeout,
- adapteeService,
- adapteeFilter,
- stateMask,
- ranking,
- factorySet,
- factoryConfigure,
- factoryMethod,
- field,
- name,
- starter,
- stopper,
- bundleContextField,
- dependencyManagerField,
- componentField,
- registered,
- unregistered
-}
diff --git a/dependencymanager/annotation/src/main/java/org/apache/felix/dm/annotation/plugin/bnd/EntryType.java b/dependencymanager/annotation/src/main/java/org/apache/felix/dm/annotation/plugin/bnd/EntryType.java
deleted file mode 100644
index 274505b..0000000
--- a/dependencymanager/annotation/src/main/java/org/apache/felix/dm/annotation/plugin/bnd/EntryType.java
+++ /dev/null
@@ -1,38 +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.felix.dm.annotation.plugin.bnd;
-
-/**
- * The type of each entry (lines) stored in a component descriptor.
- *
- * @author <a href="mailto:dev@felix.apache.org">Felix Project Team</a>
- */
-public enum EntryType
-{
- Component,
- AspectService,
- AdapterService,
- BundleAdapterService,
- ResourceAdapterService,
- FactoryConfigurationAdapterService,
- ServiceDependency,
- ConfigurationDependency,
- BundleDependency,
- ResourceDependency,
-}
diff --git a/dependencymanager/annotation/src/main/java/org/apache/felix/dm/annotation/plugin/bnd/EntryWriter.java b/dependencymanager/annotation/src/main/java/org/apache/felix/dm/annotation/plugin/bnd/EntryWriter.java
deleted file mode 100644
index 8731dd8..0000000
--- a/dependencymanager/annotation/src/main/java/org/apache/felix/dm/annotation/plugin/bnd/EntryWriter.java
+++ /dev/null
@@ -1,253 +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.felix.dm.annotation.plugin.bnd;
-
-import java.util.Arrays;
-import java.util.Map;
-import java.util.Set;
-import java.util.regex.Pattern;
-
-import org.json.JSONArray;
-import org.json.JSONException;
-import org.json.JSONObject;
-
-import aQute.bnd.osgi.Annotation;
-
-/**
- * This class encodes a component descriptor entry line, using json.
- *
- * @author <a href="mailto:dev@felix.apache.org">Felix Project Team</a>
- */
-public class EntryWriter
-{
- // Every descriptor entries contains a type parameter for identifying the kind of entry
- private final static String TYPE = "type";
-
- /** All parameters as stored in a json object */
- private JSONObject m_json;
-
- /** The entry type */
- private EntryType m_type;
-
- /**
- * Makes a new component descriptor entry.
- */
- public EntryWriter(EntryType type)
- {
- m_type = type;
- m_json = new JSONObject();
- try
- {
- m_json.put("type", type.toString());
- }
- catch (JSONException e)
- {
- throw new RuntimeException("could not initialize json object", e);
- }
- }
-
- /**
- * Returns this entry type.
- */
- EntryType getEntryType()
- {
- return m_type;
- }
-
- /**
- * Returns a string representation for the given component descriptor entry.
- */
- @Override
- public String toString()
- {
- return m_json.toString();
- }
-
- /**
- * Put a String parameter in this descritor entry.
- */
- public void put(EntryParam param, String value)
- {
- checkType(param.toString());
- try
- {
- m_json.put(param.toString(), value);
- }
- catch (JSONException e)
- {
- throw new IllegalArgumentException("could not add param " + param + ":" + value, e);
- }
- }
-
- /**
- * Put a String[] parameter in this descriptor entry.
- */
- public void put(EntryParam param, String[] array)
- {
- checkType(param.toString());
- try
- {
- m_json.put(param.toString(), new JSONArray(Arrays.asList(array)));
- }
- catch (JSONException e)
- {
- throw new IllegalArgumentException("could not add param " + param + ":"
- + Arrays.toString(array), e);
- }
- }
-
- /**
- * Puts a json object.
- * @throws JSONException
- */
- public void putJsonObject(EntryParam param, JSONObject jsonObject) throws JSONException
- {
- m_json.put(param.toString(), jsonObject);
- }
-
- /**
- * Get a String attribute value from an annotation and write it into this descriptor entry.
- */
- public String putString(Annotation annotation, EntryParam param, String def)
- {
- checkType(param.toString());
- Object value = annotation.get(param.toString());
- if (value == null && def != null)
- {
- value = def;
- }
- if (value != null)
- {
- put(param, value.toString());
- }
- return value == null ? null : value.toString();
- }
-
- /**
- * Get a String array attribute value from an annotation and write it into this descriptor entry.
- */
- public void putStringArray(Annotation annotation, EntryParam param, String[] def)
- {
- checkType(param.toString());
- Object value = annotation.get(param.toString());
- if (value == null && def != null)
- {
- value = def;
- }
- if (value != null)
- {
- for (Object v: ((Object[]) value))
- {
- try
- {
- m_json.append(param.toString(), v.toString());
- }
- catch (JSONException e)
- {
- throw new IllegalArgumentException("Could not add param " + param + ":"
- + value.toString(), e);
- }
- }
- }
- }
-
- /**
- * Get a class attribute value from an annotation and write it into this descriptor entry.
- */
- public void putClass(Annotation annotation, EntryParam param, Object def)
- {
- checkType(param.toString());
-
- Pattern pattern = Patterns.CLASS;
- Object value = annotation.get(param.toString());
- if (value == null && def != null)
- {
- value = def;
- pattern = null;
- }
- if (value != null)
- {
- if (pattern != null)
- {
- value = Patterns.parseClass(value.toString(), pattern, 1);
- }
- put(param, value.toString());
- }
- }
-
- /**
- * Get a class array attribute value from an annotation and write it into this descriptor entry.
- * Also collect classes found from the array into a given Set.
- * @return the class array size.
- */
- public int putClassArray(Annotation annotation, EntryParam param, Object def, Set<String> collect)
- {
- checkType(param.toString());
-
- Pattern pattern = Patterns.CLASS;
- Object value = annotation.get(param.toString());
- if (value == null && def != null)
- {
- value = def;
- pattern = null;
- }
- if (value != null)
- {
- if (!(value instanceof Object[]))
- {
- throw new IllegalArgumentException("annotation parameter " + param
- + " has not a class array type");
- }
-
- for (Object v: ((Object[]) value))
- {
- if (pattern != null)
- {
- v = Patterns.parseClass(v.toString(), pattern, 1);
- }
- try
- {
- m_json.append(param.toString(), v.toString());
- collect.add(v.toString());
- }
- catch (JSONException e)
- {
- throw new IllegalArgumentException("Could not add param " + param + ":"
- + value.toString(), e);
- }
- }
-
- return ((Object[]) value).length;
- }
-
- return 0;
- }
-
- /**
- * Check if the written key is not equals to "type" ("type" is an internal attribute we are using
- * in order to identify a kind of descriptor entry (Service, ServiceDependency, etc ...).
- */
- private void checkType(String key)
- {
- if (TYPE.equals(key))
- {
- throw new IllegalArgumentException("\"" + TYPE + "\" parameter can't be overriden");
- }
- }
-}
diff --git a/dependencymanager/annotation/src/main/java/org/apache/felix/dm/annotation/plugin/bnd/Logger.java b/dependencymanager/annotation/src/main/java/org/apache/felix/dm/annotation/plugin/bnd/Logger.java
deleted file mode 100644
index 9815e7a..0000000
--- a/dependencymanager/annotation/src/main/java/org/apache/felix/dm/annotation/plugin/bnd/Logger.java
+++ /dev/null
@@ -1,62 +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.felix.dm.annotation.plugin.bnd;
-
-/**
- * Base class for our logger. Under Maven, we log into the Maven logger. Under bnd, we log into the Bnd logger.
- *
- * @author <a href="mailto:dev@felix.apache.org">Felix Project Team</a>
- */
-public abstract class Logger
-{
- protected final static int ERROR = 1;
- protected final static int WARN = 2;
- protected final static int INFO = 3;
- protected final static int DEBUG = 4;
-
- protected int parseLogLevel(String level)
- {
- if (level == null || level.regionMatches(true, 0, "err", 0, "err".length()))
- {
- return ERROR;
- }
- else if (level.regionMatches(true, 0, "warn", 0, "warn".length()))
- {
- return WARN;
- }
- else if (level.regionMatches(true, 0, "info", 0, "info".length()))
- {
- return INFO;
- }
- else if (level.regionMatches(true, 0, "debug", 0, "debug".length()))
- {
- return DEBUG;
- }
- else
- {
- throw new IllegalArgumentException("Invalid log level value: " + level + " (valid values are \"error\", \"warn\", \"debug\")");
- }
- }
-
- public abstract void error(String msg, Object ... args);
- public abstract void error(String msg, Throwable err, Object ... args);
- public abstract void warn(String msg , Object ... args);
- public abstract void info(String msg , Object ... args);
- public abstract void debug(String msg, Object ... args);
-}
diff --git a/dependencymanager/annotation/src/main/java/org/apache/felix/dm/annotation/plugin/bnd/MetaType.java b/dependencymanager/annotation/src/main/java/org/apache/felix/dm/annotation/plugin/bnd/MetaType.java
deleted file mode 100644
index b934306..0000000
--- a/dependencymanager/annotation/src/main/java/org/apache/felix/dm/annotation/plugin/bnd/MetaType.java
+++ /dev/null
@@ -1,326 +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.felix.dm.annotation.plugin.bnd;
-
-import java.io.PrintWriter;
-import java.util.ArrayList;
-import java.util.HashMap;
-import java.util.List;
-import java.util.Map;
-
-/**
- * Helper class used to generate an XML representation of a MetaType data structure.
- *
- * @author <a href="mailto:dev@felix.apache.org">Felix Project Team</a>
- */
-public class MetaType
-{
- /**
- * The list of Object Class Definitions used to group the attributes of a given
- * set of properties.
- */
- private List<OCD> m_ocdList = new ArrayList<OCD>();
-
- /**
- * The list of Designate elements.
- */
- private List<Designate> m_designateList = new ArrayList<Designate>();
-
- /**
- * The default localization directory.
- */
- private final static String LOCALIZATION = "OSGI-INF/metatype/metatype";
-
- /**
- * Adds an Object Class Definition into this meta type.
- * @param ocd the Object Class Definition.
- */
- public void add(OCD ocd)
- {
- m_ocdList.add(ocd);
- }
-
- /**
- * Adds a Designate element, which maps a PID to an OCD.
- * @param designate the Designate element.
- */
- public void add(Designate designate)
- {
- m_designateList.add(designate);
- }
-
- /**
- * Returns the number of OCD contained in this meta type.
- * @return the number of OCD contained in this meta type.
- */
- public int getSize()
- {
- return m_ocdList.size();
- }
-
- /**
- * Generates an XML representation of this metatype.
- * @param pw a PrintWriter where the XML is written
- */
- public void writeTo(PrintWriter pw)
- {
- pw.println("<?xml version=\"1.0\" encoding=\"UTF-8\"?>");
- pw.println("<metatype:MetaData xmlns:metatype=\"http://www.osgi.org/xmlns/metatype/v1.0.0\" localization=\""
- + LOCALIZATION + "\">");
- for (OCD ocd : m_ocdList)
- {
- ocd.writeTo(pw);
- }
- for (Designate designate : m_designateList)
- {
- designate.writeTo(pw);
- }
- pw.println("</metatype:MetaData>");
- }
-
- private static void writeAttribute(String name, Object value, PrintWriter pw)
- {
- if (value != null)
- {
- pw.print(" " + name + "=" + "\"" + value.toString() + "\"");
- }
- }
-
- /**
- * An Object Class Definition, which contains a set of Attributes properies.
- */
- public static class OCD
- {
- String m_id;
- String m_name;
- String m_description;
- List<AD> m_attributes = new ArrayList<AD>();
-
- OCD(String pid, String name, String desc)
- {
- this.m_id = pid;
- this.m_name = name;
- this.m_description = desc;
- }
-
- public void add(AD ad)
- {
- m_attributes.add(ad);
- }
-
- public void writeTo(PrintWriter pw)
- {
- pw.print(" <OCD");
- writeAttribute("id", m_id, pw);
- writeAttribute("name", m_name, pw);
- writeAttribute("description", m_description, pw);
- if (m_attributes.size() == 0)
- {
- pw.println("/>");
- }
- else
- {
- pw.println(">");
- for (AD ad : m_attributes)
- {
- ad.writeTo(pw);
- }
- pw.println(" </OCD>");
- }
- }
- }
-
- /**
- * An Attribute Definition, which describes a given Properties
- */
- @SuppressWarnings("serial")
- public static class AD
- {
- String m_id;
- String m_type;
- String m_defaults;
- String m_name;
- String m_description;
- Integer m_cardinality;
- Boolean m_required;
- List<Option> m_options = new ArrayList<Option>();
-
- private final static Map<String, String> _allowedTypes = new HashMap<String, String>()
- {
- {
- put(String.class.getName(), "String");
- put(Long.class.getName(), "Long");
- put(Integer.class.getName(), "Integer");
- put(Character.class.getName(), "Char");
- put(Byte.class.getName(), "Byte");
- put(Double.class.getName(), "Double");
- put(Float.class.getName(), "Float");
- put(Boolean.class.getName(), "Boolean");
- }
- };
-
- public AD(String id, String type, Object[] defaults, String name, String desc, Integer cardinality, Boolean required)
- {
- this.m_id = id;
- this.m_type = (type == null) ? "String" : getType(type);
- this.m_name = name;
- this.m_description = desc;
- this.m_cardinality = cardinality;
- this.m_required = required;
-
- if (defaults != null)
- {
- StringBuilder sb = new StringBuilder();
- for (int i = 0; i < defaults.length; i++)
- {
- sb.append(defaults[i].toString());
- if (i < defaults.length - 1)
- {
- sb.append(",");
- }
- }
- this.m_defaults = sb.toString();
-
- // Check if the number of default values is consistent with the cardinality.
- if (cardinality != null)
- {
- int max = (cardinality.intValue() == 0) ? 1 : Math.abs(cardinality.intValue());
- if (defaults.length > max)
- {
- throw new IllegalArgumentException("number of default values ("
- + defaults.length + ") is inconsistent with cardinality ("
- + cardinality + ")");
- }
- }
- }
- }
-
- public void writeTo(PrintWriter pw)
- {
- pw.print(" <AD");
- writeAttribute("id", m_id, pw);
- writeAttribute("type", m_type, pw);
- writeAttribute("default", m_defaults, pw);
- writeAttribute("name", m_name, pw);
- writeAttribute("description", m_description, pw);
- writeAttribute("cardinality", m_cardinality, pw);
- if (m_options.size() == 0)
- {
- pw.println("/>");
- }
- else
- {
- pw.println(">");
- for (Option option : m_options)
- {
- option.writeTo(pw);
- }
- pw.println(" </AD>");
- }
- }
-
- private String getType(String t)
- {
- String result = _allowedTypes.get(t);
- if (result == null)
- {
- throw new IllegalArgumentException("Invalid Property type: " + m_type);
- }
- return result;
- }
-
- public void add(Option option)
- {
- m_options.add(option);
- }
- }
-
- /**
- * An Option datastructure, which can be associated with an Attribute.
- */
- public static class Option
- {
- String m_value;
- String m_label;
-
- Option(String value, String label)
- {
- this.m_value = value;
- this.m_label = label;
- }
-
- public void writeTo(PrintWriter pw)
- {
- pw.print(" <Option");
- writeAttribute("value", m_value, pw);
- writeAttribute("label", m_label, pw);
- pw.println("/>");
- }
- }
-
- /**
- * A Designate element, which maps a PID to a given Object Class Definition.
- */
- public static class Designate
- {
- String m_pid;
- boolean m_factory;
- OBject m_object;
-
- public Designate(String pid, boolean factory)
- {
- this.m_pid = pid;
- this.m_factory = factory;
- this.m_object = new OBject(pid);
- }
-
- public void writeTo(PrintWriter pw)
- {
- pw.print(" <Designate");
- writeAttribute("pid", m_pid, pw);
- if (m_factory)
- {
- writeAttribute("factoryPid", m_pid, pw);
- }
- pw.println(">");
- m_object.writeTo(pw);
- pw.println(" </Designate>");
- }
- }
-
- /**
- * A definition of an instance.
- */
- public static class OBject
- {
- String m_ocdref;
-
- OBject(String ocdref)
- {
- this.m_ocdref = ocdref;
- }
-
- public void writeTo(PrintWriter pw)
- {
- pw.print(" <Object");
- writeAttribute("ocdref", m_ocdref, pw);
- pw.println("/>");
- }
- }
-}
diff --git a/dependencymanager/annotation/src/main/java/org/apache/felix/dm/annotation/plugin/bnd/Patterns.java b/dependencymanager/annotation/src/main/java/org/apache/felix/dm/annotation/plugin/bnd/Patterns.java
deleted file mode 100644
index 4def6b9..0000000
--- a/dependencymanager/annotation/src/main/java/org/apache/felix/dm/annotation/plugin/bnd/Patterns.java
+++ /dev/null
@@ -1,106 +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.felix.dm.annotation.plugin.bnd;
-
-import java.util.regex.Matcher;
-import java.util.regex.Pattern;
-
-/**
- * Class containings pattern matching helper methods.
- *
- * @author <a href="mailto:dev@felix.apache.org">Felix Project Team</a>
- */
-public class Patterns
-{
- // Pattern used to check if a method is void and does not take any params
- public final static Pattern VOID = Pattern.compile("\\(\\)V");
-
- // Pattern used to check if a method returns an array of Objects
- public final static Pattern COMPOSITION = Pattern.compile("\\(\\)\\[Ljava/lang/Object;");
-
- // Pattern used to parse the class parameter from the bind methods ("bind(Type)" or "bind(Map, Type)" or "bind(BundleContext, Type)"
- public final static Pattern BIND_CLASS = Pattern.compile("\\((L[^;]+;)?L([^;]+);\\)V");
-
- // Pattern used to parse classes from class descriptors;
- public final static Pattern CLASS = Pattern.compile("L([^;]+);");
-
- // Pattern used to parse the field on which a Publisher annotation may be applied on
- public final static Pattern RUNNABLE = Pattern.compile("Ljava/lang/Runnable;");
-
- // Pattern used to parse a field whose type is BundleContext
- public final static Pattern BUNDLE_CONTEXT = Pattern.compile("Lorg/osgi/framework/BundleContext;");
-
- // Pattern used to parse a field whose type is DependencyManager
- public final static Pattern DEPENDENCY_MANAGER = Pattern.compile("Lorg.apache.felix.dm.DependencyManager;");
-
- // Pattern used to parse a field whose type is Component
- public final static Pattern COMPONENT = Pattern.compile("Lorg.apache.felix.dm.Component;");
-
- /**
- * Parses a class.
- * @param clazz the class to be parsed (the package is "/" separated).
- * @param pattern the pattern used to match the class.
- * @param group the pattern group index where the class can be retrieved.
- * @return the parsed class.
- */
- public static String parseClass(String clazz, Pattern pattern, int group)
- {
- Matcher matcher = pattern.matcher(clazz);
- if (matcher.matches())
- {
- return matcher.group(group).replace("/", ".");
- }
- else
- {
- throw new IllegalArgumentException("Invalid class descriptor: " + clazz);
- }
- }
-
- /**
- * Checks if a method descriptor matches a given pattern.
- * @param the method whose signature descriptor is checked
- * @param pattern the pattern used to check the method signature descriptor
- * @throws IllegalArgumentException if the method signature descriptor does not match the given pattern.
- */
- public static void parseMethod(String method, String descriptor, Pattern pattern)
- {
- Matcher matcher = pattern.matcher(descriptor);
- if (!matcher.matches())
- {
- throw new IllegalArgumentException("Invalid method " + method + ", wrong signature: "
- + descriptor);
- }
- }
-
- /**
- * Checks if a field descriptor matches a given pattern.
- * @param field the field whose type descriptor is checked
- * @param descriptor the field descriptor to be checked
- * @param pattern the pattern to use
- * @throws IllegalArgumentException if the method signature descriptor does not match the given pattern.
- */
- public static void parseField(String field, String descriptor, Pattern pattern) {
- Matcher matcher = pattern.matcher(descriptor);
- if (!matcher.matches())
- {
- throw new IllegalArgumentException("Invalid field " + field + ", wrong signature: "
- + descriptor);
- }
- }
-}
diff --git a/dependencymanager/annotation/src/main/java/org/apache/felix/dm/annotation/plugin/mvn/AnnotationMojo.java b/dependencymanager/annotation/src/main/java/org/apache/felix/dm/annotation/plugin/mvn/AnnotationMojo.java
deleted file mode 100644
index 79b5c65..0000000
--- a/dependencymanager/annotation/src/main/java/org/apache/felix/dm/annotation/plugin/mvn/AnnotationMojo.java
+++ /dev/null
@@ -1,292 +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.felix.dm.annotation.plugin.mvn;
-
-import java.io.BufferedInputStream;
-import java.io.BufferedOutputStream;
-import java.io.File;
-import java.io.FileOutputStream;
-import java.io.IOException;
-import java.io.InputStream;
-import java.util.Map;
-import java.util.Set;
-
-import org.apache.felix.dm.annotation.plugin.bnd.DescriptorGenerator;
-import org.apache.maven.model.Build;
-import org.apache.maven.plugin.AbstractMojo;
-import org.apache.maven.plugin.MojoExecutionException;
-import org.apache.maven.project.MavenProject;
-
-import aQute.bnd.osgi.Analyzer;
-import aQute.bnd.osgi.Jar;
-import aQute.bnd.osgi.Resource;
-
-/**
- * The <code>AnnotationMojo</code>
- * generates a Dependency Manager component descriptor file based on annotations found from java classes.
- *
- * @goal scan
- * @phase package
- * @description Build DependencyManager component descriptors from class annotations.
- * @requiresDependencyResolution compile
- * @author <a href="mailto:dev@felix.apache.org">Felix Project Team</a>
- */
-public class AnnotationMojo extends AbstractMojo
-{
- /**
- * The Maven project.
- *
- * @parameter expression="${project}"
- * @required
- * @readonly
- */
- private MavenProject m_project;
-
- /**
- * The target extension
- *
- * @parameter default-value="jar"
- * @required
- */
- private String m_artifactExtension;
-
- /**
- * If set, configures the log level.
- *
- * @parameter alias="log"
- */
- private String m_log;
-
- /**
- * If set, configures if we must auto generate Import-Service/Export-Service headers.
- *
- * @parameter alias="build-import-export-service" default-value="true"
- */
- private boolean m_buildImportExportService;
-
- /**
- * The maven project bas directory, used when generating metadata in maven project directory.
- *
- * @parameter expression="${project.basedir}"
- * @required
- * @readonly
- */
- private File m_projectBaseDir;
-
- /**
- * If set, configures the output directory where generated descriptor files are generated.
- *
- * @parameter alias="generated-output-dir"
- */
- private String m_generatedOutputDir;
-
- /**
- * "Import-Service" osgi header
- */
- private static final String IMPORT_SERVICE = "Import-Service";
-
- /**
- * "Export-Service" osgi header
- */
- private static final String EXPORT_SERVICE = "Export-Service";
-
- /**
- * Executes this mojo. We'll use the bnd library in order to scan classes
- * from our target bundle.
- */
- public void execute() throws MojoExecutionException
- {
- Analyzer analyzer = null;
- Jar jar = null;
-
- try
- {
- // Get the name of our target bundle we are parsing for annotations.
- File target = getBundleName();
- getLog().info("Generating DM component descriptors for bundle " + target);
-
- // Create a bnd analyzer and analyze our target bundle classes.
- analyzer = new Analyzer();
- analyzer.setJar(target);
- analyzer.analyze();
-
- // This helper class will parse classes using the analyzer we just created.
- DescriptorGenerator generator = new DescriptorGenerator(analyzer, new MvnLogger(getLog(), m_log));
-
- // Start scanning
- if (generator.execute())
- {
- // Some annotations have been parsed.
- // Add the list of generated component descriptors in our
- // special header.
- jar = analyzer.getJar();
- jar.getManifest().getMainAttributes()
- .putValue( "DependencyManager-Component", generator.getDescriptorPaths() );
-
- // Add generated descriptors into the target bundle (we'll use a
- // temp file).
- Map<String, Resource> resources = generator.getDescriptors();
- for (Map.Entry<String, Resource> entry : resources.entrySet())
- {
- addResource(entry.getKey(), entry.getValue().openInputStream());
- jar.putResource(entry.getKey(), entry.getValue());
- }
-
- Resource metaType = generator.getMetaTypeResource();
- if (metaType != null)
- {
- addResource("OSGI-INF/metatype/metatype.xml", metaType.openInputStream());
- jar.putResource("OSGI-INF/metatype/metatype.xml", metaType);
- }
-
- // Possibly set the Import-Service/Export-Service header
- if (m_buildImportExportService)
- {
- // Don't override Import-Service header, if it is found from
- // the bnd directives.
- if (jar.getManifest().getMainAttributes().getValue(IMPORT_SERVICE) == null)
- {
- buildImportExportService(jar, IMPORT_SERVICE, generator.getImportService());
- }
-
- // Don't override Export-Service header, if already defined
- if (jar.getManifest().getMainAttributes().getValue(EXPORT_SERVICE) == null)
- {
- buildImportExportService(jar, EXPORT_SERVICE, generator.getExportService());
- }
- }
-
- copy(jar, target);
- }
- }
-
- catch (MojoExecutionException e)
- {
- throw e;
- }
-
- catch (Throwable t)
- {
- getLog().error("Exception while scanning annotation", t);
- throw new MojoExecutionException(t.getMessage(), t.getCause());
- }
-
- finally
- {
- if (jar != null)
- {
- jar.close();
- }
- }
- }
-
- /**
- * Adds a resource file into the project base directory
- * @param key
- * @param in
- * @throws IOException
- */
- private void addResource(String key, InputStream in) throws IOException
- {
- if (m_generatedOutputDir != null) {
- File descriptorFile = new File( m_projectBaseDir + File.separator + m_generatedOutputDir, key );
- descriptorFile.getParentFile().mkdirs();
- BufferedInputStream bin = new BufferedInputStream( in );
- BufferedOutputStream out = new BufferedOutputStream( new FileOutputStream( descriptorFile ) );
- int b;
- while ( ( b = bin.read() ) != -1 )
- {
- out.write( b );
- }
- out.close();
- bin.close();
- }
- }
-
- private void buildImportExportService(Jar jar, String header, Set<String> services) throws Exception
- {
- getLog().info("building " + header + " header with the following services: " + services);
-
- if (services.size() > 0)
- {
- StringBuilder sb = new StringBuilder();
- for (String service : services)
- {
- sb.append(service);
- sb.append(",");
- }
- sb.setLength(sb.length() - 1); // skip last comma
- jar.getManifest().getMainAttributes().putValue(header, sb.toString());
- }
- }
-
- /**
- * Returns the target name of this maven project.
- *
- * @return the target name of this maven project.
- */
- private File getBundleName()
- {
- Build build = m_project.getBuild();
- return new File(build.getDirectory() + File.separator + build.getFinalName() + "."
- + m_artifactExtension);
- }
-
- /**
- * Copy the generated jar into our target bundle.
- *
- * @param jar the jar with the generated component descriptors
- * @param target our target bundle
- * @throws MojoExecutionException on any errors
- * @throws Exception on any error
- */
- private void copy(Jar jar, File target) throws MojoExecutionException, Exception
- {
- File tmp = new File(getBundleName() + ".tmp");
- try
- {
- if (tmp.exists())
- {
- if (!tmp.delete())
- {
- throw new MojoExecutionException("Could not remove " + tmp);
- }
- }
- jar.write(tmp);
- jar.close();
-
- if (target.exists() && !target.delete())
- {
- throw new MojoExecutionException("Could not remove " + target);
- }
- if (!tmp.renameTo(target))
- {
- throw new MojoExecutionException("Could not rename " + tmp + " to " + target);
- }
- }
- finally
- {
- jar.close();
- if (tmp.exists() && !tmp.delete())
- {
- throw new MojoExecutionException("Could not remove " + tmp);
- }
- }
- }
-}
diff --git a/dependencymanager/annotation/src/main/java/org/apache/felix/dm/annotation/plugin/mvn/MvnLogger.java b/dependencymanager/annotation/src/main/java/org/apache/felix/dm/annotation/plugin/mvn/MvnLogger.java
deleted file mode 100644
index 3aed298..0000000
--- a/dependencymanager/annotation/src/main/java/org/apache/felix/dm/annotation/plugin/mvn/MvnLogger.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.felix.dm.annotation.plugin.mvn;
-
-import org.apache.felix.dm.annotation.plugin.bnd.Logger;
-import org.apache.maven.plugin.logging.Log;
-
-/**
- * Maven logger.
- *
- * @author <a href="mailto:dev@felix.apache.org">Felix Project Team</a>
- */
-public class MvnLogger extends Logger
-{
- private final Log m_log;
- private final int m_level;
-
- public MvnLogger(Log log, String level)
- {
- m_log = log;
- m_level = parseLogLevel(level);
- }
-
- @Override
- public void error(String msg, Object... args)
- {
- m_log.error("DependencyManager: " + String.format(msg, args));
- }
-
- @Override
- public void error(String msg, Throwable err, Object... args)
- {
- m_log.error("DependencyManager: " + String.format(msg, args), err);
- }
-
- @Override
- public void warn(String msg, Object... args)
- {
- m_log.warn("DependencyManager: " + String.format(msg, args));
- }
-
- @Override
- public void info(String msg, Object... args)
- {
- if (m_level >= INFO)
- {
- m_log.info("DependencyManager: " + String.format(msg, args));
- }
- }
-
- @Override
- public void debug(String msg, Object... args)
- {
- if (m_level >= DEBUG)
- {
- m_log.info("DependencyManager: " + String.format(msg, args));
- }
- }
-}
diff --git a/dependencymanager/compat/DEPENDENCIES b/dependencymanager/compat/DEPENDENCIES
deleted file mode 100644
index af1991c..0000000
--- a/dependencymanager/compat/DEPENDENCIES
+++ /dev/null
@@ -1,22 +0,0 @@
-Apache Felix Dependency Manager Compatibility
-Copyright 2011-2014 The Apache Software Foundation
-
-This software was developed at the Apache Software Foundation
-(http://www.apache.org) and may have dependencies on other
-Apache software licensed under Apache License 2.0.
-
-I. Included Third-Party Software
-
-n/a
-
-II. Used Third-Party Software
-
-This product uses software developed at
-The OSGi Alliance (http://www.osgi.org/).
-Copyright (c) OSGi Alliance (2000, 2009).
-Licensed under the Apache License 2.0.
-
-III. Overall License Summary
-
-- Apache License 2.0
-
diff --git a/dependencymanager/compat/LICENSE b/dependencymanager/compat/LICENSE
deleted file mode 100644
index d645695..0000000
--- a/dependencymanager/compat/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/dependencymanager/compat/NOTICE b/dependencymanager/compat/NOTICE
deleted file mode 100644
index 8d6a8e7..0000000
--- a/dependencymanager/compat/NOTICE
+++ /dev/null
@@ -1,6 +0,0 @@
-Apache Felix Dependency Manager Compatibility
-Copyright 2011-2014 The Apache Software Foundation
-
-This product includes software developed at
-The Apache Software Foundation (http://www.apache.org/).
-Licensed under the Apache License 2.0.
diff --git a/dependencymanager/compat/changelog.txt b/dependencymanager/compat/changelog.txt
deleted file mode 100644
index 5acf33e..0000000
--- a/dependencymanager/compat/changelog.txt
+++ /dev/null
@@ -1,15 +0,0 @@
-Changes from 3.0.0 to 3.0.1
----------------------------
-
-** Bug
-
- [FELIX-3005] - Compatibility API does not add components in DependencyManager
- [FELIX-3475] - ServiceDependencyImpl does not override toString
- [FELIX-3617] - Missing toString methods in DependencyManager compat bundle
-
-** Improvement
-
-Release 3.0.0
--------------
-
-Initial version.
diff --git a/dependencymanager/compat/pom.xml b/dependencymanager/compat/pom.xml
deleted file mode 100644
index 9946f57..0000000
--- a/dependencymanager/compat/pom.xml
+++ /dev/null
@@ -1,90 +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/maven-v4_0_0.xsd">
- <modelVersion>4.0.0</modelVersion>
- <parent>
- <groupId>org.apache.felix</groupId>
- <artifactId>felix-parent</artifactId>
- <version>1.2.0</version>
- <relativePath>../../pom/pom.xml</relativePath>
- </parent>
- <properties>
- <osgi.version>4.2.0</osgi.version>
- </properties>
- <name>Apache Felix Dependency Manager Compatibility</name>
- <artifactId>org.apache.felix.dependencymanager.compat</artifactId>
- <version>3.0.2-SNAPSHOT</version>
- <packaging>bundle</packaging>
- <dependencies>
- <dependency>
- <groupId>org.osgi</groupId>
- <artifactId>org.osgi.core</artifactId>
- <version>${osgi.version}</version>
- </dependency>
- <dependency>
- <groupId>org.osgi</groupId>
- <artifactId>org.osgi.compendium</artifactId>
- <version>${osgi.version}</version>
- </dependency>
- <dependency>
- <groupId>${pom.groupId}</groupId>
- <artifactId>org.apache.felix.dependencymanager</artifactId>
- <version>3.0.0</version>
- </dependency>
- </dependencies>
- <build>
- <resources>
- <resource>
- <directory>.</directory>
- <targetPath>META-INF</targetPath>
- <includes>
- <include>LICENSE*</include>
- <include>NOTICE*</include>
- <include>DEPENDENCIES*</include>
- <include>*.txt</include>
- </includes>
- </resource>
- </resources>
- <pluginManagement>
- <plugins>
- <plugin>
- <groupId>org.apache.felix</groupId>
- <artifactId>maven-bundle-plugin</artifactId>
- <version>2.3.4</version>
- <extensions>true</extensions>
- </plugin>
- </plugins>
- </pluginManagement>
- <plugins>
- <plugin>
- <groupId>org.apache.felix</groupId>
- <artifactId>maven-bundle-plugin</artifactId>
- <configuration>
- <instructions>
- <Bundle-SymbolicName>org.apache.felix.dependencymanager.compat</Bundle-SymbolicName>
- <Bundle-Name>Apache Felix Dependency Manager Compatibility</Bundle-Name>
- <Bundle-Description>Provides compatibility with the dependency manager version 2.</Bundle-Description>
- <Bundle-Vendor>The Apache Software Foundation</Bundle-Vendor>
- <Export-Package>org.apache.felix.dependencymanager"</Export-Package>
- <Import-Package>!org.apache.felix.dependencymanager,org.apache.felix.dm;version="[3,4)",*</Import-Package>
- <Private-Package>org.apache.felix.dependencymanager.impl</Private-Package>
- </instructions>
- </configuration>
- </plugin>
- </plugins>
- </build>
-</project>
diff --git a/dependencymanager/compat/src/main/java/org/apache/felix/dependencymanager/ConfigurationDependency.java b/dependencymanager/compat/src/main/java/org/apache/felix/dependencymanager/ConfigurationDependency.java
deleted file mode 100644
index e218d68..0000000
--- a/dependencymanager/compat/src/main/java/org/apache/felix/dependencymanager/ConfigurationDependency.java
+++ /dev/null
@@ -1,67 +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.felix.dependencymanager;
-
-/**
- * Configuration dependency that can track the availability of a (valid) configuration.
- * To use it, specify a PID for the configuration. The dependency is always required,
- * because if it is not, it does not make sense to use the dependency manager. In that
- * scenario, simply register your service as a <code>ManagedService(Factory)</code> and
- * handle everything yourself. Also, only managed services are supported, not factories.
- * There are a couple of things you need to be aware of when implementing the
- * <code>updated(Dictionary)</code> method:
- * <ul>
- * <li>Make sure it throws a <code>ConfigurationException</code> when you get a
- * configuration that is invalid. In this case, the dependency will not change:
- * if it was not available, it will still not be. If it was available, it will
- * remain available and implicitly assume you keep working with your old
- * configuration.</li>
- * <li>This method will be called before all required dependencies are available.
- * Make sure you do not depend on these to parse your settings.</li>
- * </ul>
- *
- * @author <a href="mailto:dev@felix.apache.org">Felix Project Team</a>
- */
-public abstract class ConfigurationDependency implements Dependency {
- /**
- * Sets a callback which will be invoked when the configuration is available.
- * The method may take in parameter a Dictionary and may also throw a
- * ConfigurationException.
- * @param callback the callback to invoke when the configuration is available
- * @return this dependency.
- */
- public abstract ConfigurationDependency setCallback(String callback);
-
- /**
- * Sets the <code>service.pid</code> of the configuration you
- * are depending on.
- */
- public abstract ConfigurationDependency setPid(String pid);
-
- /**
- * Sets propagation of the configuration properties to the service
- * properties. Any additional service properties specified directly
- * are merged with these.
- */
- public abstract ConfigurationDependency setPropagate(boolean propagate);
-
- public abstract boolean isAvailable();
-
- public abstract boolean isRequired();
-}
diff --git a/dependencymanager/compat/src/main/java/org/apache/felix/dependencymanager/Dependency.java b/dependencymanager/compat/src/main/java/org/apache/felix/dependencymanager/Dependency.java
deleted file mode 100644
index 7970a12..0000000
--- a/dependencymanager/compat/src/main/java/org/apache/felix/dependencymanager/Dependency.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.felix.dependencymanager;
-
-/**
- * Generic dependency for a service. A dependency can be required or not.
- * A dependency will be activated by the service it belongs to. The service
- * will call the <code>start(Service service)</code> and
- * <code>stop(Service service)</code> methods.
- *
- * After it has been started, a dependency must callback
- * the associated service's <code>dependencyAvailable()</code> and
- * <code>dependencyUnavailable()</code>
- * methods. State changes of the dependency itself may only be made as long as
- * the dependency is not 'active', meaning it is associated with a running service.
- *
- * @author <a href="mailto:dev@felix.apache.org">Felix Project Team</a>
- */
-public interface Dependency {
- /**
- * Returns <code>true</code> if this a required dependency. Required dependencies
- * are dependencies that must be available before the service can be activated.
- *
- * @return <code>true</code> if the dependency is required
- */
- public boolean isRequired();
-
- /**
- * Returns <code>true</code> if the dependency is available.
- *
- * @return <code>true</code> if the dependency is available
- */
- public boolean isAvailable();
-}
diff --git a/dependencymanager/compat/src/main/java/org/apache/felix/dependencymanager/DependencyActivatorBase.java b/dependencymanager/compat/src/main/java/org/apache/felix/dependencymanager/DependencyActivatorBase.java
deleted file mode 100644
index 27f942b..0000000
--- a/dependencymanager/compat/src/main/java/org/apache/felix/dependencymanager/DependencyActivatorBase.java
+++ /dev/null
@@ -1,135 +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.felix.dependencymanager;
-
-import java.util.List;
-
-import org.apache.felix.dependencymanager.impl.ServiceImpl;
-import org.osgi.framework.BundleActivator;
-import org.osgi.framework.BundleContext;
-
-/**
- * Base bundle activator class. Subclass this activator if you want to use dependency
- * management in your bundle. There are two methods you should implement:
- * <code>init()</code> and <code>destroy()</code>. Both methods take two arguments,
- * the bundle context and the dependency manager. The dependency manager can be used
- * to define all the dependencies.
- *
- * @author <a href="mailto:dev@felix.apache.org">Felix Project Team</a>
- */
-public abstract class DependencyActivatorBase implements BundleActivator {
- private BundleContext m_context;
- private DependencyManager m_manager;
-
- /**
- * Initialize the dependency manager. Here you can add all services and their dependencies.
- * If something goes wrong and you do not want your bundle to be started, you can throw an
- * exception. This exception will be passed on to the <code>start()</code> method of the
- * bundle activator, causing the bundle not to start.
- *
- * @param context the bundle context
- * @param manager the dependency manager
- * @throws Exception if the initialization fails
- */
- public abstract void init(BundleContext context, DependencyManager manager) throws Exception;
-
- /**
- * Destroy the dependency manager. Here you can remove all services and their dependencies.
- * Actually, the base class will clean up your dependencies anyway, so most of the time you
- * don't need to do anything here.
- * If something goes wrong and you do not want your bundle to be stopped, you can throw an
- * exception. This exception will be passed on to the <code>stop()</code> method of the
- * bundle activator, causing the bundle not to stop.
- *
- * @param context the bundle context
- * @param manager the dependency manager
- * @throws Exception if the destruction fails
- */
- public abstract void destroy(BundleContext context, DependencyManager manager) throws Exception;
-
- /**
- * Start method of the bundle activator. Initializes the dependency manager
- * and calls <code>init()</code>.
- *
- * @param context the bundle context
- */
- public void start(BundleContext context) throws Exception {
- m_context = context;
- m_manager = new DependencyManager(context);
- init(m_context, m_manager);
- }
-
- /**
- * Stop method of the bundle activator. Calls the <code>destroy()</code> method
- * and cleans up all left over dependencies.
- *
- * @param context the bundle context
- */
- public void stop(BundleContext context) throws Exception {
- destroy(m_context, m_manager);
- cleanup(m_manager);
- m_manager = null;
- m_context = null;
- }
-
- /**
- * Creates a new service.
- *
- * @return the new service
- */
- public Service createService() {
- return new org.apache.felix.dependencymanager.impl.ServiceImpl(m_manager);
- }
-
- /**
- * Creates a new service dependency.
- *
- * @return the service dependency
- */
- public ServiceDependency createServiceDependency() {
- return new org.apache.felix.dependencymanager.impl.ServiceDependencyImpl(m_manager);
- }
-
- /**
- * Creates a new configuration dependency.
- *
- * @return the configuration dependency
- */
- public ConfigurationDependency createConfigurationDependency() {
- return new org.apache.felix.dependencymanager.impl.ConfigurationDependencyImpl(m_manager);
- }
-
- /**
- * Cleans up all components and their dependencies.
- *
- * @param manager the dependency manager
- */
- private void cleanup(DependencyManager manager) {
- List services = manager.getServices();
- for (int i = services.size() - 1; i >= 0; i--) {
- Service service = (Service) services.get(i);
- manager.remove(service);
- // remove any state listeners that are still registered
- if (service instanceof ServiceImpl) {
- ServiceImpl si = (ServiceImpl) service;
- si.removeStateListeners();
- }
- }
- }
-}
diff --git a/dependencymanager/compat/src/main/java/org/apache/felix/dependencymanager/DependencyManager.java b/dependencymanager/compat/src/main/java/org/apache/felix/dependencymanager/DependencyManager.java
deleted file mode 100644
index 747da1a..0000000
--- a/dependencymanager/compat/src/main/java/org/apache/felix/dependencymanager/DependencyManager.java
+++ /dev/null
@@ -1,121 +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.felix.dependencymanager;
-
-import java.util.ArrayList;
-import java.util.Collections;
-import java.util.Iterator;
-import java.util.List;
-
-import org.osgi.framework.BundleContext;
-
-/**
- * The dependency manager. Manages all services and their dependencies.
- *
- * @author <a href="mailto:dev@felix.apache.org">Felix Project Team</a>
- */
-public class DependencyManager
-{
- private org.apache.felix.dm.DependencyManager m_delegate;
-
- /**
- * Creates a new dependency manager.
- *
- * @param context the bundle context
- * @param logger
- */
- public DependencyManager(BundleContext context)
- {
- m_delegate = new org.apache.felix.dm.DependencyManager(context);
- }
-
- /**
- * Adds a new service to the dependency manager. After the service was added
- * it will be started immediately.
- *
- * @param service the service to add
- */
- public void add(Service service)
- {
- org.apache.felix.dependencymanager.impl.ServiceImpl serviceImpl = (org.apache.felix.dependencymanager.impl.ServiceImpl)service;
- ((org.apache.felix.dm.DependencyManager) m_delegate).add(serviceImpl.getDelegate());
- }
-
- /**
- * Removes a service from the dependency manager. Before the service is removed
- * it is stopped first.
- *
- * @param service the service to remove
- */
- public void remove(Service service)
- {
- org.apache.felix.dependencymanager.impl.ServiceImpl impl = (org.apache.felix.dependencymanager.impl.ServiceImpl)service;
- ((org.apache.felix.dm.DependencyManager) m_delegate).remove(impl.getDelegate());
- }
-
- /**
- * Creates a new service.
- *
- * @return the new service
- */
- public Service createService()
- {
- return new org.apache.felix.dependencymanager.impl.ServiceImpl(this);
- }
-
- /**
- * Creates a new service dependency.
- *
- * @return the service dependency
- */
- public ServiceDependency createServiceDependency()
- {
- return new org.apache.felix.dependencymanager.impl.ServiceDependencyImpl(this);
- }
-
- public ConfigurationDependency createConfigurationDependency()
- {
- return new org.apache.felix.dependencymanager.impl.ConfigurationDependencyImpl(this);
- }
-
- /**
- * Returns a list of services.
- *
- * @return a list of services
- */
- public List getServices()
- {
- List list = new ArrayList();
- List components = m_delegate.getComponents();
- Iterator it = components.iterator();
- while (it.hasNext()) {
- org.apache.felix.dm.Component c = (org.apache.felix.dm.Component) it.next();
- list.add(new org.apache.felix.dependencymanager.impl.ServiceImpl(c));
- }
- return Collections.unmodifiableList(list);
- }
-
- /**
- * Returns the dependency manager delegate (only used by backward compatibility impl)
- */
- public Object getDelegate()
- {
- return m_delegate;
- }
-}
diff --git a/dependencymanager/compat/src/main/java/org/apache/felix/dependencymanager/Service.java b/dependencymanager/compat/src/main/java/org/apache/felix/dependencymanager/Service.java
deleted file mode 100644
index e8893f1..0000000
--- a/dependencymanager/compat/src/main/java/org/apache/felix/dependencymanager/Service.java
+++ /dev/null
@@ -1,227 +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.felix.dependencymanager;
-
-import java.util.Dictionary;
-import java.util.List;
-
-import org.osgi.framework.ServiceRegistration;
-
-/**
- * Service interface.
- *
- * @author <a href="mailto:dev@felix.apache.org">Felix Project Team</a>
- */
-public interface Service {
- /**
- * Adds a new dependency to this service.
- *
- * @param dependency the dependency to add
- * @return this service
- */
- public Service add(Dependency dependency);
-
- /**
- * Removes a dependency from this service.
- *
- * @param dependency the dependency to remove
- * @return this service
- */
- public Service remove(Dependency dependency);
-
- /**
- * Sets the public interface under which this service should be registered
- * in the OSGi service registry.
- *
- * @param serviceName the name of the service interface
- * @param properties the properties for this service
- * @return this service
- */
- public Service setInterface(String serviceName, Dictionary properties);
-
- /**
- * Sets the public interfaces under which this service should be registered
- * in the OSGi service registry.
- *
- * @param serviceNames the names of the service interface
- * @param properties the properties for this service
- * @return this service
- */
- public Service setInterface(String[] serviceNames, Dictionary properties);
-
- /**
- * Sets the implementation for this service. You can actually specify
- * an instance you have instantiated manually, or a <code>Class</code>
- * that will be instantiated using its default constructor when the
- * required dependencies are resolved (effectively giving you a lazy
- * instantiation mechanism).
- *
- * There are four special methods that are called when found through
- * reflection to give you some life-cycle management options:
- * <ol>
- * <li><code>init()</code> is invoked right after the instance has been
- * created, and before any dependencies are resolved, and can be used to
- * initialize the internal state of the instance</li>
- * <li><code>start()</code> is invoked after the required dependencies
- * are resolved and injected, and before the service is registered</li>
- * <li><code>stop()</code> is invoked right after the service is
- * unregistered</li>
- * <li><code>destroy()</code> is invoked after all dependencies are
- * removed</li>
- * </ol>
- * In short, this allows you to initialize your instance before it is
- * registered, perform some post-initialization and pre-destruction code
- * as well as final cleanup. If a method is not defined, it simply is not
- * called, so you can decide which one(s) you need. If you need even more
- * fine-grained control, you can register as a service state listener too.
- *
- * @param implementation the implementation
- * @return this service
- * @see ServiceStateListener
- */
- public Service setImplementation(Object implementation);
-
- /**
- * Returns a list of dependencies.
- *
- * @return a list of dependencies
- */
- public List getDependencies();
-
- /**
- * Returns the service registration for this service. The method
- * will return <code>null</code> if no service registration is
- * available.
- *
- * @return the service registration
- */
- public ServiceRegistration getServiceRegistration();
-
- /**
- * Returns the service instance for this service. The method will
- * return <code>null</code> if no service instance is available.
- *
- * @return the service instance
- */
- public Object getService();
-
- /**
- * Returns the service properties associated with the service.
- *
- * @return the properties or <code>null</code> if there are none
- */
- public Dictionary getServiceProperties();
-
- /**
- * Sets the service properties associated with the service. If the service
- * was already registered, it will be updated.
- *
- * @param serviceProperties the properties
- */
- public void setServiceProperties(Dictionary serviceProperties);
-
- /**
- * Sets the names of the methods used as callbacks. These methods, when found, are
- * invoked as part of the life-cycle management of the service implementation. The
- * methods should not have any parameters.
- *
- * @param init the name of the init method
- * @param start the name of the start method
- * @param stop the name of the stop method
- * @param destroy the name of the destroy method
- * @return the service instance
- */
- public Service setCallbacks(String init, String start, String stop, String destroy);
-
- // listener
- /**
- * Adds a service state listener to this service.
- *
- * @param listener the state listener
- */
- public void addStateListener(ServiceStateListener listener);
-
- /**
- * Removes a service state listener from this service.
- *
- * @param listener the state listener
- */
- public void removeStateListener(ServiceStateListener listener);
-
- /**
- * Starts the service. This activates the dependency tracking mechanism
- * for this service.
- */
- public void start();
-
- /**
- * Stops the service. This deactivates the dependency tracking mechanism
- * for this service.
- */
- public void stop();
-
- /**
- * Sets the factory to use to create the implementation. You can specify
- * both the factory class and method to invoke. The method should return
- * the implementation, and can use any method to create it. Actually, this
- * can be used together with <code>setComposition</code> to create a
- * composition of instances that work together to implement a service. The
- * factory itself can also be instantiated lazily by not specifying an
- * instance, but a <code>Class</code>.
- *
- * @param factory the factory instance or class
- * @param createMethod the name of the create method
- */
- public Service setFactory(Object factory, String createMethod);
-
- /**
- * Sets the factory to use to create the implementation. You specify the
- * method to invoke. The method should return the implementation, and can
- * use any method to create it. Actually, this can be used together with
- * <code>setComposition</code> to create a composition of instances that
- * work together to implement a service.
- * <p>
- * Note that currently, there is no default for the factory, so please use
- * <code>setFactory(factory, createMethod)</code> instead.
- *
- * @param createMethod the name of the create method
- */
- public Service setFactory(String createMethod);
-
- /**
- * Sets the instance and method to invoke to get back all instances that
- * are part of a composition and need dependencies injected. All of them
- * will be searched for any of the dependencies. The method that is
- * invoked must return an <code>Object[]</code>.
- *
- * @param instance the instance that has the method
- * @param getMethod the method to invoke
- */
- public Service setComposition(Object instance, String getMethod);
-
- /**
- * Sets the method to invoke on the service implementation to get back all
- * instances that are part of a composition and need dependencies injected.
- * All of them will be searched for any of the dependencies. The method that
- * is invoked must return an <code>Object[]</code>.
- *
- * @param getMethod the method to invoke
- */
- public Service setComposition(String getMethod);
-}
diff --git a/dependencymanager/compat/src/main/java/org/apache/felix/dependencymanager/ServiceDependency.java b/dependencymanager/compat/src/main/java/org/apache/felix/dependencymanager/ServiceDependency.java
deleted file mode 100644
index aebf1bc..0000000
--- a/dependencymanager/compat/src/main/java/org/apache/felix/dependencymanager/ServiceDependency.java
+++ /dev/null
@@ -1,194 +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.felix.dependencymanager;
-
-import org.osgi.framework.ServiceReference;
-
-/**
- * Service dependency that can track an OSGi service.
- *
- * @author <a href="mailto:dev@felix.apache.org">Felix Project Team</a>
- */
-public abstract class ServiceDependency implements Dependency
-{
- /**
- * Sets the name of the service that should be tracked.
- *
- * @param serviceName the name of the service
- * @return this service dependency
- */
- public abstract ServiceDependency setService(Class serviceName);
-
- /**
- * Sets the name of the service that should be tracked. You can either specify
- * only the name, or the name and a filter. In the latter case, the filter is used
- * to track the service and should only return services of the type that was specified
- * in the name. To make sure of this, the filter is actually extended internally to
- * filter on the correct name.
- *
- * @param serviceName the name of the service
- * @param serviceFilter the filter condition
- * @return this service dependency
- */
- public abstract ServiceDependency setService(Class serviceName, String serviceFilter);
-
- /**
- * Sets the name of the service that should be tracked. You can either specify
- * only the name, or the name and a reference. In the latter case, the service reference
- * is used to track the service and should only return services of the type that was
- * specified in the name.
- *
- * @param serviceName the name of the service
- * @param serviceReference the service reference to track
- * @return this service dependency
- */
- public abstract ServiceDependency setService(Class serviceName,
- ServiceReference serviceReference);
-
- /**
- * Sets the default implementation for this service dependency. You can use this to supply
- * your own implementation that will be used instead of a Null Object when the dependency is
- * not available. This is also convenient if the service dependency is not an interface
- * (which would cause the Null Object creation to fail) but a class.
- *
- * @param implementation the instance to use or the class to instantiate if you want to lazily
- * instantiate this implementation
- * @return this service dependency
- */
- public abstract ServiceDependency setDefaultImplementation(Object implementation);
-
- /**
- * Sets the required flag which determines if this service is required or not.
- *
- * @param required the required flag
- * @return this service dependency
- */
- public abstract ServiceDependency setRequired(boolean required);
-
- /**
- * Sets auto configuration for this service. Auto configuration allows the
- * dependency to fill in any attributes in the service implementation that
- * are of the same type as this dependency. Default is on.
- *
- * @param autoConfig the value of auto config
- * @return this service dependency
- */
- public abstract ServiceDependency setAutoConfig(boolean autoConfig);
-
- /**
- * Sets auto configuration for this service. Auto configuration allows the
- * dependency to fill in the attribute in the service implementation that
- * has the same type and instance name.
- *
- * @param instanceName the name of attribute to auto config
- * @return this service dependency
- */
- public abstract ServiceDependency setAutoConfig(String instanceName);
-
- /**
- * Sets the callbacks for this service. These callbacks can be used as hooks whenever a
- * dependency is added or removed. When you specify callbacks, the default auto configuration
- * feature is automatically turned off, because we're assuming you don't need it in this
- * case. If you need both features (callbacks + autoconfig), Then, you must explicitly invoke
- * setAutoConfig(true) and setCallbacks methods.
- *
- * @param added the method to call when a service was added
- * @param removed the method to call when a service was removed
- * @return this service dependency
- */
- public ServiceDependency setCallbacks(String added, String removed)
- {
- return setCallbacks(null, added, null, removed);
- }
-
- /**
- * Sets the callbacks for this service. These callbacks can be used as hooks whenever a
- * dependency is added, changed or removed. When you specify callbacks, the default auto
- * configuration feature is automatically turned off, because we're assuming you don't
- * need it in this case. If you need both features (callbacks + autoconfig),
- * then, you must explicitly invoke setAutoConfig(true) and setCallbacks methods.
- *
- * @param added the method to call when a service was added
- * @param changed the method to call when a service was changed
- * @param removed the method to call when a service was removed
- * @return this service dependency
- */
- public ServiceDependency setCallbacks(String added, String changed, String removed)
- {
- return setCallbacks(null, added, changed, removed);
- }
-
- /**
- * Sets the callbacks for this service. These callbacks can be used as hooks whenever a
- * dependency is added or removed. They are called on the instance you provide. When you
- * specify callbacks, the default auto configuration feature is automatically turned off, because
- * we're assuming you don't need it in this case. If you need both features (callbacks + autoconfig),
- * then, you must explicitly invoke setAutoConfig(true) and setCallbacks methods.
- *
- * @param instance the instance to call the callbacks on
- * @param added the method to call when a service was added
- * @param removed the method to call when a service was removed
- * @return this service dependency
- */
- public ServiceDependency setCallbacks(Object instance, String added, String removed)
- {
- return setCallbacks(instance, added, null, removed);
- }
-
- /**
- * Sets the callbacks for this service. These callbacks can be used as hooks whenever a
- * dependency is added, changed or removed. They are called on the instance you provide. When you
- * specify callbacks, the default auto configuration feature is automatically turned off, because
- * we're assuming you don't need it in this case. If you need both features (callbacks + autoconfig),
- * then, you must explicitly invoke setAutoConfig(true) and setCallbacks methods.
- *
- * @param instance the instance to call the callbacks on
- * @param added the method to call when a service was added
- * @param changed the method to call when a service was changed
- * @param removed the method to call when a service was removed
- * @return this service dependency
- */
- public abstract ServiceDependency setCallbacks(Object instance, String added, String changed,
- String removed);
-
- /**
- * Returns <code>true>code> if auto configuration is enabled for this dependency.
- * Auto configuration means that a dependency is injected in the service instance
- * when it's available, and if it's unavailable, a "null object" will be inserted
- * instead.
- *
- * @return <code>true>code> if auto configuration is enabled for this dependency
- */
- public abstract boolean isAutoConfig();
-
- /**
- * Returns <code>true</code> if the dependency is available.
- *
- * @return <code>true</code> if the dependency is available
- */
- public abstract boolean isAvailable();
-
- /**
- * Returns <code>true</code> if this a required dependency. Required dependencies
- * are dependencies that must be available before the service can be activated.
- *
- * @return <code>true</code> if the dependency is required
- */
- public abstract boolean isRequired();
-}
diff --git a/dependencymanager/compat/src/main/java/org/apache/felix/dependencymanager/ServiceStateListener.java b/dependencymanager/compat/src/main/java/org/apache/felix/dependencymanager/ServiceStateListener.java
deleted file mode 100644
index a655633..0000000
--- a/dependencymanager/compat/src/main/java/org/apache/felix/dependencymanager/ServiceStateListener.java
+++ /dev/null
@@ -1,62 +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.felix.dependencymanager;
-
-/**
- * This interface can be used to register a service state listener. Service
- * state listeners are called whenever a service state changes. You get notified
- * when the service is starting, started, stopping and stopped. Each callback
- * includes a reference to the service in question.
- *
- * @author <a href="mailto:dev@felix.apache.org">Felix Project Team</a>
- */
-public interface ServiceStateListener {
- /**
- * Called when the service is starting. At this point, the required
- * dependencies have been injected, but the service has not been registered
- * yet.
- *
- * @param service the service
- */
- public void starting(Service service);
-
- /**
- * Called when the service is started. At this point, the service has been
- * registered.
- *
- * @param service the service
- */
- public void started(Service service);
-
- /**
- * Called when the service is stopping. At this point, the service is still
- * registered.
- *
- * @param service the service
- */
- public void stopping(Service service);
-
- /**
- * Called when the service is stopped. At this point, the service has been
- * unregistered.
- *
- * @param service the service
- */
- public void stopped(Service service);
-}
diff --git a/dependencymanager/compat/src/main/java/org/apache/felix/dependencymanager/impl/ConfigurationDependencyImpl.java b/dependencymanager/compat/src/main/java/org/apache/felix/dependencymanager/impl/ConfigurationDependencyImpl.java
deleted file mode 100644
index 54ebb83..0000000
--- a/dependencymanager/compat/src/main/java/org/apache/felix/dependencymanager/impl/ConfigurationDependencyImpl.java
+++ /dev/null
@@ -1,100 +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.felix.dependencymanager.impl;
-
-import org.apache.felix.dependencymanager.ConfigurationDependency;
-import org.apache.felix.dependencymanager.DependencyManager;
-
-/**
- * Configuration dependency that can track the availability of a (valid) configuration.
- * To use it, specify a PID for the configuration. The dependency is always required,
- * because if it is not, it does not make sense to use the dependency manager. In that
- * scenario, simply register your service as a <code>ManagedService(Factory)</code> and
- * handle everything yourself. Also, only managed services are supported, not factories.
- * There are a couple of things you need to be aware of when implementing the
- * <code>updated(Dictionary)</code> method:
- * <ul>
- * <li>Make sure it throws a <code>ConfigurationException</code> when you get a
- * configuration that is invalid. In this case, the dependency will not change:
- * if it was not available, it will still not be. If it was available, it will
- * remain available and implicitly assume you keep working with your old
- * configuration.</li>
- * <li>This method will be called before all required dependencies are available.
- * Make sure you do not depend on these to parse your settings.</li>
- * </ul>
- *
- * @author <a href="mailto:dev@felix.apache.org">Felix Project Team</a>
- */
-public class ConfigurationDependencyImpl extends ConfigurationDependency
-{
- org.apache.felix.dm.ConfigurationDependency m_delegate;
-
- public ConfigurationDependencyImpl(DependencyManager dm)
- {
- org.apache.felix.dm.DependencyManager dmDelegate = (org.apache.felix.dm.DependencyManager) dm.getDelegate();
- m_delegate = dmDelegate.createConfigurationDependency();
- }
-
- public org.apache.felix.dm.ConfigurationDependency getDelegate()
- {
- return m_delegate;
- }
-
- public ConfigurationDependency setCallback(String callback)
- {
- m_delegate.setCallback(callback);
- return this;
- }
-
- /**
- * Sets the <code>service.pid</code> of the configuration you
- * are depending on.
- */
- public ConfigurationDependency setPid(String pid)
- {
- m_delegate.setPid(pid);
- return this;
- }
-
- /**
- * Sets propagation of the configuration properties to the service
- * properties. Any additional service properties specified directly
- * are merged with these.
- */
- public ConfigurationDependency setPropagate(boolean propagate)
- {
- m_delegate.setPropagate(propagate);
- return this;
- }
-
- public boolean isAvailable()
- {
- return m_delegate.isAvailable();
- }
-
- public boolean isRequired()
- {
- return m_delegate.isRequired();
- }
-
- public String toString()
- {
- return m_delegate.toString();
- }
-}
diff --git a/dependencymanager/compat/src/main/java/org/apache/felix/dependencymanager/impl/ServiceDependencyImpl.java b/dependencymanager/compat/src/main/java/org/apache/felix/dependencymanager/impl/ServiceDependencyImpl.java
deleted file mode 100644
index 13b9c83..0000000
--- a/dependencymanager/compat/src/main/java/org/apache/felix/dependencymanager/impl/ServiceDependencyImpl.java
+++ /dev/null
@@ -1,108 +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.felix.dependencymanager.impl;
-
-import org.apache.felix.dependencymanager.DependencyManager;
-import org.apache.felix.dependencymanager.ServiceDependency;
-import org.osgi.framework.ServiceReference;
-
-public class ServiceDependencyImpl extends ServiceDependency
-{
- org.apache.felix.dm.ServiceDependency m_delegate;
-
- public ServiceDependencyImpl(DependencyManager dm)
- {
- org.apache.felix.dm.DependencyManager dmDelegate = (org.apache.felix.dm.DependencyManager) dm.getDelegate();
- m_delegate = dmDelegate.createServiceDependency();
- }
-
- public org.apache.felix.dm.ServiceDependency getDelegate()
- {
- return m_delegate;
- }
-
- public ServiceDependency setService(Class serviceName)
- {
- m_delegate.setService(serviceName);
- return this;
- }
-
- public ServiceDependency setService(Class serviceName, String serviceFilter)
- {
- m_delegate.setService(serviceName, serviceFilter);
- return this;
- }
-
- public ServiceDependency setService(Class serviceName, ServiceReference serviceReference)
- {
- m_delegate.setService(serviceName, serviceReference);
- return this;
- }
-
- public ServiceDependency setDefaultImplementation(Object implementation)
- {
- m_delegate.setDefaultImplementation(implementation);
- return this;
- }
-
- public ServiceDependency setRequired(boolean required)
- {
- m_delegate.setRequired(required);
- return this;
- }
-
- public ServiceDependency setAutoConfig(boolean autoConfig)
- {
- m_delegate.setAutoConfig(autoConfig);
- return this;
- }
-
- public ServiceDependency setAutoConfig(String instanceName)
- {
- m_delegate.setAutoConfig(instanceName);
- return this;
- }
-
- public ServiceDependency setCallbacks(Object instance, String added, String changed,
- String removed)
- {
- m_delegate.setCallbacks(instance, added, changed, removed);
- return this;
- }
-
- public boolean isAutoConfig()
- {
- return m_delegate.isAutoConfig();
- }
-
- public boolean isAvailable()
- {
- return m_delegate.isAvailable();
- }
-
- public boolean isRequired()
- {
- return m_delegate.isRequired();
- }
-
- public String toString()
- {
- return m_delegate.toString();
- }
-}
diff --git a/dependencymanager/compat/src/main/java/org/apache/felix/dependencymanager/impl/ServiceImpl.java b/dependencymanager/compat/src/main/java/org/apache/felix/dependencymanager/impl/ServiceImpl.java
deleted file mode 100644
index ecd4f42..0000000
--- a/dependencymanager/compat/src/main/java/org/apache/felix/dependencymanager/impl/ServiceImpl.java
+++ /dev/null
@@ -1,253 +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.felix.dependencymanager.impl;
-
-import java.util.ArrayList;
-import java.util.Dictionary;
-import java.util.HashMap;
-import java.util.Iterator;
-import java.util.List;
-import java.util.Map;
-
-import org.apache.felix.dependencymanager.Dependency;
-import org.apache.felix.dependencymanager.DependencyManager;
-import org.apache.felix.dependencymanager.Service;
-import org.apache.felix.dependencymanager.ServiceStateListener;
-import org.apache.felix.dm.Component;
-import org.osgi.framework.ServiceRegistration;
-
-/**
- * Service implementation.
- *
- * @author <a href="mailto:dev@felix.apache.org">Felix Project Team</a>
- */
-public class ServiceImpl implements Service
-{
- private org.apache.felix.dm.Component m_delegate;
- private Map m_stateListeners = new HashMap();
- private ArrayList m_dependencies = new ArrayList();
-
- public ServiceImpl(DependencyManager dm)
- {
- org.apache.felix.dm.DependencyManager dmDelegate = (org.apache.felix.dm.DependencyManager) dm.getDelegate();
- m_delegate = dmDelegate.createComponent();
- }
-
- public ServiceImpl(Component c) {
- m_delegate = c;
- }
-
- public Service add(Dependency dependency)
- {
- if (dependency instanceof ServiceDependencyImpl)
- {
- m_delegate.add(((org.apache.felix.dependencymanager.impl.ServiceDependencyImpl) dependency).getDelegate());
-
- }
- else if (dependency instanceof ConfigurationDependencyImpl)
- {
- m_delegate.add(((org.apache.felix.dependencymanager.impl.ConfigurationDependencyImpl) dependency).getDelegate());
- }
- else
- {
- throw new IllegalArgumentException("dependency type not supported: " + dependency);
- }
-
- synchronized (this)
- {
- m_dependencies.add(dependency);
- }
- return this;
- }
-
- public Service remove(Dependency dependency)
- {
- synchronized (this)
- {
- m_dependencies.remove(dependency);
- }
- if (dependency instanceof ServiceDependencyImpl)
- {
- m_delegate.remove(((org.apache.felix.dependencymanager.impl.ServiceDependencyImpl) dependency).getDelegate());
- }
- else if (dependency instanceof ConfigurationDependencyImpl)
- {
- m_delegate.remove(((org.apache.felix.dependencymanager.impl.ConfigurationDependencyImpl) dependency).getDelegate());
- }
- else
- {
- throw new IllegalArgumentException("dependency type not supported: " + dependency);
- }
- return this;
- }
-
- public void addStateListener(final ServiceStateListener listener)
- {
- org.apache.felix.dm.ComponentStateListener wrappedListener = new org.apache.felix.dm.ComponentStateListener()
- {
- public void started(org.apache.felix.dm.Component service)
- {
- listener.started(ServiceImpl.this);
- }
-
- public void starting(org.apache.felix.dm.Component service)
- {
- listener.starting(ServiceImpl.this);
- }
-
- public void stopped(org.apache.felix.dm.Component service)
- {
- listener.stopped(ServiceImpl.this);
- }
-
- public void stopping(org.apache.felix.dm.Component service)
- {
- listener.stopping(ServiceImpl.this);
- }
- };
- synchronized (this)
- {
- m_stateListeners.put(listener, wrappedListener);
- }
- m_delegate.addStateListener(wrappedListener);
- }
-
- public void removeStateListener(ServiceStateListener listener)
- {
- org.apache.felix.dm.ComponentStateListener wrappedListener = null;
- synchronized (m_stateListeners)
- {
- wrappedListener = (org.apache.felix.dm.ComponentStateListener) m_stateListeners.remove(listener);
- }
- if (wrappedListener != null)
- {
- m_delegate.removeStateListener(wrappedListener);
- }
- }
-
- public void removeStateListeners()
- {
- synchronized (m_stateListeners)
- {
- Iterator it = m_stateListeners.values().iterator();
- while (it.hasNext())
- {
- org.apache.felix.dm.ComponentStateListener wrappedListener =
- (org.apache.felix.dm.ComponentStateListener) it.next();
- m_delegate.removeStateListener(wrappedListener);
- }
- m_stateListeners.clear();
- }
- }
-
- public List getDependencies()
- {
- synchronized (m_dependencies)
- {
- return (List) m_dependencies.clone();
- }
- }
-
- public Object getService()
- {
- return m_delegate.getService();
- }
-
- public Dictionary getServiceProperties()
- {
- return m_delegate.getServiceProperties();
- }
-
- public ServiceRegistration getServiceRegistration()
- {
- return m_delegate.getServiceRegistration();
- }
-
- public Service setCallbacks(String init, String start, String stop, String destroy)
- {
- m_delegate.setCallbacks(init, start, stop, destroy);
- return this;
- }
-
- public Service setComposition(Object instance, String getMethod)
- {
- m_delegate.setComposition(instance, getMethod);
- return this;
- }
-
- public Service setComposition(String getMethod)
- {
- m_delegate.setComposition(getMethod);
- return this;
- }
-
- public Service setFactory(Object factory, String createMethod)
- {
- m_delegate.setFactory(factory, createMethod);
- return this;
- }
-
- public Service setFactory(String createMethod)
- {
- m_delegate.setFactory(createMethod);
- return this;
- }
-
- public Service setImplementation(Object implementation)
- {
- m_delegate.setImplementation(implementation);
- return this;
- }
-
- public Service setInterface(String serviceName, Dictionary properties)
- {
- m_delegate.setInterface(serviceName, properties);
- return this;
- }
-
- public Service setInterface(String[] serviceNames, Dictionary properties)
- {
- m_delegate.setInterface(serviceNames, properties);
- return this;
- }
-
- public void setServiceProperties(Dictionary serviceProperties)
- {
- m_delegate.setServiceProperties(serviceProperties);
- }
-
- public void start()
- {
- m_delegate.start();
- }
-
- public void stop()
- {
- m_delegate.stop();
- }
-
- public Component getDelegate() {
- return m_delegate;
- }
-
- public String toString()
- {
- return m_delegate.toString();
- }
-}
diff --git a/dependencymanager/core/DEPENDENCIES b/dependencymanager/core/DEPENDENCIES
deleted file mode 100644
index f85efb2..0000000
--- a/dependencymanager/core/DEPENDENCIES
+++ /dev/null
@@ -1,24 +0,0 @@
-Apache Felix Dependency Manager
-Copyright 2011-2014 The Apache Software Foundation
-
-This software was developed at the Apache Software Foundation
-(http://www.apache.org) and may have dependencies on other
-Apache software licensed under Apache License 2.0.
-
-I. Included Third-Party Software
-
-This product includes software developed at
-The OSGi Alliance (http://www.osgi.org/).
-Copyright (c) OSGi Alliance (2000, 2014).
-Licensed under the Apache License 2.0.
-
-II. Used Third-Party Software
-
-This product uses software developed at
-The OSGi Alliance (http://www.osgi.org/).
-Copyright (c) OSGi Alliance (2000, 2014).
-Licensed under the Apache License 2.0.
-
-III. Overall License Summary
-
-- Apache License 2.0
diff --git a/dependencymanager/core/LICENSE b/dependencymanager/core/LICENSE
deleted file mode 100644
index d645695..0000000
--- a/dependencymanager/core/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/dependencymanager/core/NOTICE b/dependencymanager/core/NOTICE
deleted file mode 100644
index 0b22b06..0000000
--- a/dependencymanager/core/NOTICE
+++ /dev/null
@@ -1,12 +0,0 @@
-Apache Felix Dependency Manager
-Copyright 2011-2014 The Apache Software Foundation
-
-
-This product includes software developed at
-The Apache Software Foundation (http://www.apache.org/).
-Licensed under the Apache License 2.0.
-
-This product includes software developed at
-The OSGi Alliance (http://www.osgi.org/).
-Copyright (c) OSGi Alliance (2000, 2014).
-Licensed under the Apache License 2.0.
diff --git a/dependencymanager/core/changelog.txt b/dependencymanager/core/changelog.txt
deleted file mode 100644
index f4b2d98..0000000
--- a/dependencymanager/core/changelog.txt
+++ /dev/null
@@ -1,65 +0,0 @@
-Release 3.2.0:
---------------
-
-FELIX-3910: Race conditions in DependencyManager
-FELIX-4334: ServiceDependency properties change callback issue
-FELIX-4285: Remove abstract modifier from DependencyActivatorBase.destroy()
-FELIX-4294: Dependency Manager Shell improvements
-FELIX-4305: DependencyMananer Adapters - service properties propagation
-FELIX-4002: ComponentStateListener.started is invoked twice when the listener is added in the start method.
-FELIX-4395: DependencyManager Configuration Dependency does not clone some class fields.
-FELIX-4014: handleAspectAwareRemoved in ServiceDependencyImpl can cause a possible deadlock
-FELIX-4097: Allow debug logging for specific instances of service dependencies to debug wiring issues.
-FELIX-4098: Aspect swap sometimes invokes the callbacks in the wrong order in a multithreaded application.
-FELIX-4099: Add support for negations in the multi property filter index.
-FELIX-4186: NPE in DependencyManager Logger
-FELIX-4226: Add option to have the dependency manager log against a single BundleContext's LogService.
-FELIX-4361: Possible ConcurrentModificationException in DependencyManager.getComponents()
-
-Release 3.1.0
--------------
-
-FELIX-303 - Support for compositions
-FELIX-1201 - Issue with DM and CM
-FELIX-1278 - DM/ AutoConfig is active event if setCallbacks method has been invoked
-FELIX-1464 - issue when using a negation in ldap service dependency filter
-FELIX-1546 - DM/Temporal Dependency/Bound Service Replacement features
-FELIX-2078 - Not all callbacks invoked when declaring a service as required and starting it after dependencies
-FELIX-2344 - DM / callback method is not invoked when an extra dependency is defined within an "init" component method.
-FELIX-2348 - DM/ ResourceAdapter NPE
-FELIX-2369 - DM/ Service start method is invoked even if an extra required dependency is unavailable
-FELIX-2816 - dependency manager calls init() twice
-FELIX-2947 - Filter indices must use service trackers that track all services and aspects.
-FELIX-2953 - Make the cache that InvocationUtil uses configurable.
-FELIX-2954 - DM/ annotated component factory does not allow to provide a component instance explicitly
-FELIX-2955 - IllegalStateException when doing a 'dm notavail' shell command.
-FELIX-2956 - DM/ json should be embedded in the annotation scanner plugin
-FELIX-2964 - DM/ NPE on some dependency manager adapters, when "auto-configuration" mode is disabled.
-FELIX-2970 - DM/ Factory Configuration Adapter Service does not copy adapter dependencies
-FELIX-2976 - InvocationUtil cache is not used properly for determining that methods do not exist in a class
-FELIX-2987 - DependencyManager ConfigurationDependency update isn't propagated to super classes
-FELIX-3008 - NPE in ServiceRegistryCache when dependency manager bundle is not started first
-FELIX-3042 - [PATCH] Add a convenience clear() method on DependencyManager
-FELIX-3057 - getServiceReferences() should not return an empty array
-FELIX-3186 - Adapter services do not get their adapted services transparently replaced when an aspect is added to them.
-FELIX-3201 - Offer more functional callback methods for services that have aspects on them.
-FELIX-3218 - ServiceTracker performance is not optimal with a service dependency that results in n-thousands of injected services.
-FELIX-3264 - Dependency manager shell should not print the state of optional dependencies when not all required ones are available
-FELIX-3292 - Allow passing of resource properties to a resource handler for use with resource adapters.
-FELIX-3337 - DependencyManager/Updated configuration dependency does not propagate to provided service properties
-FELIX-3402 - DependencyManager stop can trigger IndexOutOfBoundsException
-FELIX-3423 - AdapterImpl copies the DependencyManager.ASPECT service property when adapting an aspect.
-FELIX-3424 - Add support for changed callbacks on Aspect services.
-FELIX-3425 - Provide a filter index for adapter services.
-FELIX-3475 - DependencyManager compatibility bundle - ServiceDependencyImpl does not override toString
-FELIX-3564 - Memory leak in Filterindex / ServiceRegistryCache
-FELIX-3592 - ServiceDependencyImpl does not copy the swapped callback in it's constructor.
-FELIX-3617 - Missing toString methods in DependencyManager compat bundle
-FELIX-3682 - Dependency Manager Annotation-3.0.0 module doesn't expose OSGI meta information in MANIFEST.MF
-FELIX-3828 - Aspect and Adapter filter indices to not handle components that have been bound with multiple interfaces correctly.
-
-
-Release 3.0.0
--------------
-
-Major, backward incompatible release. Start of recorded changes.
diff --git a/dependencymanager/core/pom.xml b/dependencymanager/core/pom.xml
deleted file mode 100644
index 258b7e1..0000000
--- a/dependencymanager/core/pom.xml
+++ /dev/null
@@ -1,106 +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/maven-v4_0_0.xsd">
- <modelVersion>4.0.0</modelVersion>
- <parent>
- <groupId>org.apache.felix</groupId>
- <artifactId>felix-parent</artifactId>
- <version>1.2.0</version>
- <relativePath>../../pom/pom.xml</relativePath>
- </parent>
- <properties>
- <osgi.version>4.2.0</osgi.version>
- </properties>
- <name>Apache Felix Dependency Manager</name>
- <artifactId>org.apache.felix.dependencymanager</artifactId>
- <version>3.2.1-SNAPSHOT</version>
- <packaging>bundle</packaging>
-
- <scm>
- <connection>scm:svn:http://svn.apache.org/repos/asf/felix/trunk/dependencymanager/core</connection>
- <developerConnection>scm:svn:https://svn.apache.org/repos/asf/felix/trunk/dependencymanager/core</developerConnection>
- <url>http://svn.apache.org/repos/asf/felix/dependencymanager/core</url>
- </scm>
-
- <dependencies>
- <dependency>
- <groupId>org.osgi</groupId>
- <artifactId>org.osgi.core</artifactId>
- <version>${osgi.version}</version>
- </dependency>
- <dependency>
- <groupId>org.osgi</groupId>
- <artifactId>org.osgi.compendium</artifactId>
- <version>${osgi.version}</version>
- </dependency>
- </dependencies>
- <build>
- <resources>
- <resource>
- <directory>.</directory>
- <targetPath>META-INF</targetPath>
- <includes>
- <include>LICENSE*</include>
- <include>NOTICE*</include>
- <include>DEPENDENCIES*</include>
- <include>*.txt</include>
- </includes>
- </resource>
- </resources>
- <pluginManagement>
- <plugins>
- <plugin>
- <groupId>org.apache.felix</groupId>
- <artifactId>maven-bundle-plugin</artifactId>
- <version>2.3.4</version>
- <extensions>true</extensions>
- </plugin>
- </plugins>
- </pluginManagement>
- <plugins>
- <!-- by default the dependency manager will run on any OSGi execution environment -->
- <plugin>
- <groupId>org.apache.maven.plugins</groupId>
- <artifactId>maven-compiler-plugin</artifactId>
- <configuration>
- <target>1.3</target>
- </configuration>
- </plugin>
- <plugin>
- <groupId>org.apache.felix</groupId>
- <artifactId>maven-bundle-plugin</artifactId>
- <configuration>
- <instructions>
- <Bundle-SymbolicName>org.apache.felix.dependencymanager</Bundle-SymbolicName>
- <Bundle-Name>Apache Felix Dependency Manager</Bundle-Name>
- <Bundle-Description>Provides dynamic service and component dependency management.</Bundle-Description>
- <Bundle-Vendor>The Apache Software Foundation</Bundle-Vendor>
- <Export-Package>org.apache.felix.dm;version="3.1.0";provide:=true,org.apache.felix.dm.tracker;version="3.1.0";provide:=true</Export-Package>
- <Import-Package>*</Import-Package>
- <Private-Package>org.apache.felix.dm.impl, org.apache.felix.dm.impl.*</Private-Package>
- <!-- Uncomment this next line to include source code in the bundle.
- <Include-Resource>src/main/java</Include-Resource>
- -->
- </instructions>
- </configuration>
- </plugin>
- </plugins>
- </build>
-</project>
diff --git a/dependencymanager/core/src/main/java/org/apache/felix/dm/BundleDependency.java b/dependencymanager/core/src/main/java/org/apache/felix/dm/BundleDependency.java
deleted file mode 100644
index 90787b4..0000000
--- a/dependencymanager/core/src/main/java/org/apache/felix/dm/BundleDependency.java
+++ /dev/null
@@ -1,137 +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.felix.dm;
-
-import org.osgi.framework.Bundle;
-
-/**
- * @author <a href="mailto:dev@felix.apache.org">Felix Project Team</a>
- */
-public interface BundleDependency extends Dependency, ComponentDependencyDeclaration {
- /**
- * Sets the callbacks for this dependency. These callbacks can be used as hooks whenever a dependency is added or removed.
- * When you specify callbacks, the auto configuration feature is automatically turned off, because we're assuming you don't
- * need it in this case.
- *
- * @param added the method to call when a bundle was added
- * @param removed the method to call when a bundle was removed
- * @return the bundle dependency
- */
- public BundleDependency setCallbacks(String added, String removed);
-
- /**
- * Sets the callbacks for this dependency. These callbacks can be used as hooks whenever a dependency is added, changed or
- * removed. When you specify callbacks, the auto configuration feature is automatically turned off, because we're assuming
- * you don't need it in this case.
- *
- * @param added the method to call when a bundle was added
- * @param changed the method to call when a bundle was changed
- * @param removed the method to call when a bundle was removed
- * @return the bundle dependency
- */
- public BundleDependency setCallbacks(String added, String changed, String removed);
-
- /**
- * Sets the callbacks for this dependency. These callbacks can be used as hooks whenever a dependency is added or removed.
- * They are called on the instance you provide. When you specify callbacks, the auto configuration feature is automatically
- * turned off, because we're assuming you don't need it in this case.
- *
- * @param instance the instance to call the callbacks on
- * @param added the method to call when a bundle was added
- * @param removed the method to call when a bundle was removed
- * @return the bundle dependency
- */
- public BundleDependency setCallbacks(Object instance, String added, String removed);
-
- /**
- * Sets the callbacks for this dependency. These callbacks can be used as hooks whenever a dependency is added, changed or
- * removed. They are called on the instance you provide. When you specify callbacks, the auto configuration feature is
- * automatically turned off, because we're assuming you don't need it in this case.
- *
- * @param instance the instance to call the callbacks on
- * @param added the method to call when a bundle was added
- * @param changed the method to call when a bundle was changed
- * @param removed the method to call when a bundle was removed
- * @return the bundle dependency
- */
- public BundleDependency setCallbacks(Object instance, String added, String changed, String removed);
-
- /**
- * Enables auto configuration for this dependency. This means the component implementation (composition) will be
- * injected with this bundle dependency automatically.
- *
- * @param autoConfig <code>true</code> to enable auto configuration
- * @return the bundle dependency
- */
- public BundleDependency setAutoConfig(boolean autoConfig);
-
- /**
- * Sets the dependency to be required.
- *
- * @param required <code>true</code> if this bundle dependency is required
- * @return the bundle dependency
- */
- public BundleDependency setRequired(boolean required);
-
- /**
- * Sets the bundle to depend on directly.
- *
- * @param bundle the bundle to depend on
- * @return the bundle dependency
- */
- public BundleDependency setBundle(Bundle bundle);
-
- /**
- * Sets the filter condition to depend on. Filters are matched against the full manifest of a bundle.
- *
- * @param filter the filter condition
- * @return the bundle dependency
- * @throws IllegalArgumentException
- */
- public BundleDependency setFilter(String filter) throws IllegalArgumentException;
-
- /**
- * Sets the bundle state mask to depend on. The OSGi BundleTracker explains this mask in more detail, but
- * it is basically a mask with flags for each potential state a bundle can be in.
- *
- * @param mask the mask to use
- * @return the bundle dependency
- */
- public BundleDependency setStateMask(int mask);
-
- /**
- * Sets property propagation. If set to <code>true</code> any bundle manifest properties will be added
- * to the service properties of the component that has this dependency (if it registers as a service).
- *
- * @param propagate <code>true</code> to propagate the bundle manifest properties
- * @return the bundle dependency
- */
- public BundleDependency setPropagate(boolean propagate);
-
- /**
- * Sets the dependency to be bound to this instance. An instance bound dependency means the component is
- * kept alive even if the dependency goes away, which internally means you can keep your state until you
- * get activated again. This is mainly used when declaring additional dependencies from within the
- * <code>init</code> life cycle method of a component.
- *
- * @param isInstanceBound <code>true</code> if this dependency is instance bound
- * @return the bundle dependency
- */
- public BundleDependency setInstanceBound(boolean isInstanceBound);
-}
diff --git a/dependencymanager/core/src/main/java/org/apache/felix/dm/Component.java b/dependencymanager/core/src/main/java/org/apache/felix/dm/Component.java
deleted file mode 100644
index 50d1e28..0000000
--- a/dependencymanager/core/src/main/java/org/apache/felix/dm/Component.java
+++ /dev/null
@@ -1,318 +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.felix.dm;
-
-import java.util.Dictionary;
-import java.util.List;
-
-import org.osgi.framework.ServiceRegistration;
-
-/**
- * Component interface. Components are the main building blocks for OSGi applications.
- * They can publish themselves as a service, and they can have dependencies. These
- * dependencies will influence their life cycle as component will only be activated
- * when all required dependencies are available.
- *
- * @author <a href="mailto:dev@felix.apache.org">Felix Project Team</a>
- */
-public interface Component {
- /**
- * Adds a new dependency to this component.
- *
- * @param dependency the dependency to add
- * @return this component
- */
- public Component add(Dependency dependency);
-
- /**
- * Adds a list of new dependencies to this component.
- *
- * @param dependencies the dependencies to add
- * @return this component
- */
- public Component add(List dependencies);
-
- /**
- * Removes a dependency from this component.
- *
- * @param dependency the dependency to remove
- * @return this component
- */
- public Component remove(Dependency dependency);
-
- /**
- * Sets the public interface under which this component should be registered
- * in the OSGi service registry.
- *
- * @param serviceName the name of the service interface
- * @param properties the properties for this service
- * @return this component
- */
- public Component setInterface(String serviceName, Dictionary properties);
-
- /**
- * Sets the public interfaces under which this component should be registered
- * in the OSGi service registry.
- *
- * @param serviceNames the names of the service interface
- * @param properties the properties for these services
- * @return this component
- */
- public Component setInterface(String[] serviceNames, Dictionary properties);
-
- /**
- * Sets the implementation for this component. You can actually specify
- * an instance you have instantiated manually, or a <code>Class</code>
- * that will be instantiated using its default constructor when the
- * required dependencies are resolved, effectively giving you a lazy
- * instantiation mechanism.
- *
- * There are four special methods that are called when found through
- * reflection to give you life cycle management options:
- * <ol>
- * <li><code>init()</code> is invoked after the instance has been
- * created and dependencies have been resolved, and can be used to
- * initialize the internal state of the instance or even to add more
- * dependencies based on runtime state</li>
- * <li><code>start()</code> is invoked right before the service is
- * registered</li>
- * <li><code>stop()</code> is invoked right after the service is
- * unregistered</li>
- * <li><code>destroy()</code> is invoked after all dependencies are
- * removed</li>
- * </ol>
- * In short, this allows you to initialize your instance before it is
- * registered, perform some post-initialization and pre-destruction code
- * as well as final cleanup. If a method is not defined, it simply is not
- * called, so you can decide which one(s) you need. If you need even more
- * fine-grained control, you can register as a service state listener too.
- *
- * @param implementation the implementation
- * @return this component
- * @see ComponentStateListener
- */
- public Component setImplementation(Object implementation);
-
- /**
- * Returns a list of dependencies.
- *
- * @return a list of dependencies
- */
- public List getDependencies();
-
- /**
- * Returns the service registration for this component. The method
- * will return <code>null</code> if no service registration is
- * available, for example if this component is not registered as a
- * service at all.
- *
- * @return the service registration
- */
- public ServiceRegistration getServiceRegistration();
-
- /**
- * Returns the component instance for this component. The method will
- * return <code>null</code> if no component instance is available.
- *
- * @return the component instance
- */
- public Object getService();
-
- /**
- * Returns the service properties associated with the component.
- *
- * @return the properties or <code>null</code> if there are none
- */
- public Dictionary getServiceProperties();
-
- /**
- * Sets the service properties associated with the component. If the service
- * was already registered, it will be updated.
- *
- * @param serviceProperties the properties
- */
- public Component setServiceProperties(Dictionary serviceProperties);
-
- /**
- * Sets the names of the methods used as callbacks. These methods, when found, are
- * invoked as part of the life cycle management of the component implementation. The
- * dependency manager will look for a method of this name with the following signatures,
- * in this order:
- * <ol>
- * <li>method(Component component)</li>
- * <li>method()</li>
- * </ol>
- *
- * @param init the name of the init method
- * @param start the name of the start method
- * @param stop the name of the stop method
- * @param destroy the name of the destroy method
- * @return the component
- */
- public Component setCallbacks(String init, String start, String stop, String destroy);
- /**
- * Sets the names of the methods used as callbacks. These methods, when found, are
- * invoked on the specified instance as part of the life cycle management of the component
- * implementation.
- * <p>
- * See setCallbacks(String init, String start, String stop, String destroy) for more
- * information on the signatures. Specifying an instance means you can create a manager
- * that will be invoked whenever the life cycle of a component changes and this manager
- * can then decide how to expose this life cycle to the actual component, offering an
- * important indirection when developing your own component models.
- */
- public Component setCallbacks(Object instance, String init, String start, String stop, String destroy);
-
- // listener
- /**
- * Adds a component state listener to this component.
- *
- * @param listener the state listener
- */
- public void addStateListener(ComponentStateListener listener);
-
- /**
- * Removes a component state listener from this component.
- *
- * @param listener the state listener
- */
- public void removeStateListener(ComponentStateListener listener);
-
- /**
- * Starts the component. This activates the dependency tracking mechanism
- * for this component.
- */
- public void start();
-
- /**
- * Stops the component. This deactivates the dependency tracking mechanism
- * for this component.
- */
- public void stop();
-
- /**
- * Sets the factory to use to create the implementation. You can specify
- * both the factory class and method to invoke. The method should return
- * the implementation, and can use any method to create it. Actually, this
- * can be used together with <code>setComposition</code> to create a
- * composition of instances that work together to implement a component. The
- * factory itself can also be instantiated lazily by not specifying an
- * instance, but a <code>Class</code>.
- *
- * @param factory the factory instance or class
- * @param createMethod the name of the create method
- */
- public Component setFactory(Object factory, String createMethod);
-
- /**
- * Sets the factory to use to create the implementation. You specify the
- * method to invoke. The method should return the implementation, and can
- * use any method to create it. Actually, this can be used together with
- * <code>setComposition</code> to create a composition of instances that
- * work together to implement a component.
- * <p>
- * Note that currently, there is no default for the factory, so please use
- * <code>setFactory(factory, createMethod)</code> instead.
- *
- * @param createMethod the name of the create method
- */
- public Component setFactory(String createMethod);
-
- /**
- * Sets the instance and method to invoke to get back all instances that
- * are part of a composition and need dependencies injected. All of them
- * will be searched for any of the dependencies. The method that is
- * invoked must return an <code>Object[]</code>.
- *
- * @param instance the instance that has the method
- * @param getMethod the method to invoke
- */
- public Component setComposition(Object instance, String getMethod);
-
- /**
- * Sets the method to invoke on the service implementation to get back all
- * instances that are part of a composition and need dependencies injected.
- * All of them will be searched for any of the dependencies. The method that
- * is invoked must return an <code>Object[]</code>.
- *
- * @param getMethod the method to invoke
- */
- public Component setComposition(String getMethod);
-
- /**
- * Returns the composition instances that make up this component, or just the
- * component instance if it does not have a composition, or an empty array if
- * the component has not even been instantiated.
- */
- public Object[] getCompositionInstances();
-
- /**
- * Invokes a callback method on an array of instances. The method, whose name
- * and signatures you provide, along with the values for the parameters, is
- * invoked on all the instances where it exists.
- *
- * @see InvocationUtil#invokeCallbackMethod(Object, String, Class[][], Object[][])
- *
- * @param instances an array of instances to invoke the method on
- * @param methodName the name of the method
- * @param signatures the signatures of the method
- * @param parameters the parameter values
- */
- public void invokeCallbackMethod(Object[] instances, String methodName, Class[][] signatures, Object[][] parameters);
-
- /**
- * Returns the dependency manager associated with this component.
- */
- public DependencyManager getDependencyManager();
-
- /**
- * Configures auto configuration of injected classes in the component instance.
- * The following injections are currently performed, unless you explicitly
- * turn them off:
- * <dl>
- * <dt>BundleContext</dt><dd>the bundle context of the bundle</dd>
- * <dt>ServiceRegistration</dt><dd>the service registration used to register your service</dd>
- * <dt>DependencyManager</dt><dd>the dependency manager instance</dd>
- * <dt>Component</dt><dd>the component instance of the dependency manager</dd>
- * </dl>
- *
- * @param clazz the class (from the list above)
- * @param autoConfig <code>false</code> to turn off auto configuration
- */
- public Component setAutoConfig(Class clazz, boolean autoConfig);
-
- /**
- * Configures auto configuration of injected classes in the component instance.
- *
- * @param clazz the class (from the list above)
- * @param instanceName the name of the instance to inject the class into
- * @see setAutoConfig(Class, boolean)
- */
- public Component setAutoConfig(Class clazz, String instanceName);
-
- /**
- * Returns the status of auto configuration of the specified class.
- */
- public boolean getAutoConfig(Class clazz);
-
- /**
- * Returns the instance variable name of auto configuration of the specified class.
- */
- public String getAutoConfigInstance(Class clazz);
-}
diff --git a/dependencymanager/core/src/main/java/org/apache/felix/dm/ComponentDeclaration.java b/dependencymanager/core/src/main/java/org/apache/felix/dm/ComponentDeclaration.java
deleted file mode 100644
index 8bcf5d1..0000000
--- a/dependencymanager/core/src/main/java/org/apache/felix/dm/ComponentDeclaration.java
+++ /dev/null
@@ -1,56 +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.felix.dm;
-
-import java.util.Dictionary;
-
-import org.osgi.framework.BundleContext;
-
-/**
- * Describes a component. Component declarations form descriptions of components
- * that are managed by the dependency manager. They can be used to query their state
- * for monitoring tools. The dependency manager shell command is an example of
- * such a tool.
- *
- * @author <a href="mailto:dev@felix.apache.org">Felix Project Team</a>
- */
-public interface ComponentDeclaration {
- /** Names for the states of this component. */
- public static final String[] STATE_NAMES = { "unregistered", "registered" };
- /** State constant for an unregistered component. */
- public static final int STATE_UNREGISTERED = 0;
- /** State constant for a registered component. */
- public static final int STATE_REGISTERED = 1;
- /** Returns a list of dependencies associated with this component. */
- public ComponentDependencyDeclaration[] getComponentDependencies();
- /** Returns the description of this component (the classname or the provided service(s)) */
- public String getName();
- /** Returns the class name of the Component implementation. */
- public String getClassName();
- /** Returns the service optionally provided by this component, or null */
- public String[] getServices();
- /** Returns the service properties, or null */
- public Dictionary getServiceProperties();
- /** Returns the state of this component. */
- public int getState();
- /** Returns the instance id of this component. */
- public long getId();
- /** Returns the bundle context associated with this component. */
- public BundleContext getBundleContext();
-}
diff --git a/dependencymanager/core/src/main/java/org/apache/felix/dm/ComponentDependencyDeclaration.java b/dependencymanager/core/src/main/java/org/apache/felix/dm/ComponentDependencyDeclaration.java
deleted file mode 100644
index da6a1cf..0000000
--- a/dependencymanager/core/src/main/java/org/apache/felix/dm/ComponentDependencyDeclaration.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.felix.dm;
-
-/**
- * Describes a component dependency. They form descriptions of dependencies
- * that are managed by the dependency manager. They can be used to query their state
- * for monitoring tools. The dependency manager shell command is an example of
- * such a tool.
- *
- * @author <a href="mailto:dev@felix.apache.org">Felix Project Team</a>
- */
-public interface ComponentDependencyDeclaration {
- /** Names for the states of this dependency. */
- public static final String[] STATE_NAMES = {
- "optional unavailable",
- "optional available",
- "required unavailable",
- "required available",
- "optional (not tracking)",
- "required (not tracking)"
- };
- /** State constant for an unavailable, optional dependency. */
- public static final int STATE_UNAVAILABLE_OPTIONAL = 0;
- /** State constant for an available, optional dependency. */
- public static final int STATE_AVAILABLE_OPTIONAL = 1;
- /** State constant for an unavailable, required dependency. */
- public static final int STATE_UNAVAILABLE_REQUIRED = 2;
- /** State constant for an available, required dependency. */
- public static final int STATE_AVAILABLE_REQUIRED = 3;
- /** State constant for an optional dependency that has not been started yet. */
- public static final int STATE_OPTIONAL = 4;
- /** State constant for a required dependency that has not been started yet. */
- public static final int STATE_REQUIRED = 5;
- /** Returns the name of this dependency. */
- public String getName();
- /** Returns the name of the type of this dependency. */
- public String getType();
- /** Returns the state of this dependency. */
- public int getState();
-}
diff --git a/dependencymanager/core/src/main/java/org/apache/felix/dm/ComponentStateListener.java b/dependencymanager/core/src/main/java/org/apache/felix/dm/ComponentStateListener.java
deleted file mode 100644
index 8c397f0..0000000
--- a/dependencymanager/core/src/main/java/org/apache/felix/dm/ComponentStateListener.java
+++ /dev/null
@@ -1,62 +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.felix.dm;
-
-/**
- * This interface can be used to register a component state listener. Component
- * state listeners are called whenever a component state changes. You get notified
- * when the component is starting, started, stopping and stopped. Each callback
- * includes a reference to the component in question.
- *
- * @author <a href="mailto:dev@felix.apache.org">Felix Project Team</a>
- */
-public interface ComponentStateListener {
- /**
- * Called when the component is starting. At this point, the required
- * dependencies have been injected, but the service has not been registered
- * yet.
- *
- * @param component the component
- */
- public void starting(Component component);
-
- /**
- * Called when the component is started. At this point, the component has been
- * registered.
- *
- * @param component the component
- */
- public void started(Component component);
-
- /**
- * Called when the component is stopping. At this point, the component is still
- * registered.
- *
- * @param component the component
- */
- public void stopping(Component component);
-
- /**
- * Called when the component is stopped. At this point, the component has been
- * unregistered.
- *
- * @param component the component
- */
- public void stopped(Component component);
-}
diff --git a/dependencymanager/core/src/main/java/org/apache/felix/dm/ConfigurationDependency.java b/dependencymanager/core/src/main/java/org/apache/felix/dm/ConfigurationDependency.java
deleted file mode 100644
index 02aed1e..0000000
--- a/dependencymanager/core/src/main/java/org/apache/felix/dm/ConfigurationDependency.java
+++ /dev/null
@@ -1,96 +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.felix.dm;
-
-/**
- * Configuration dependency that can track the availability of a (valid) configuration. To use
- * it, specify a PID for the configuration. The dependency is always required, because if it is
- * not, it does not make sense to use the dependency manager. In that scenario, simply register
- * your component as a <code>ManagedService(Factory)</code> and handle everything yourself. Also,
- * only managed services are supported, not factories. There are a couple of things you need to
- * be aware of when implementing the <code>updated(Dictionary)</code> method:
- * <ul>
- * <li>Make sure it throws a <code>ConfigurationException</code> when you get a configuration
- * that is invalid. In this case, the dependency will not change: if it was not available, it
- * will still not be. If it was available, it will remain available and implicitly assume you
- * keep working with your old configuration.</li>
- * <li>This method will be called before all required dependencies are available. Make sure you
- * do not depend on these to parse your settings.</li>
- * </ul>
- *
- * @author <a href="mailto:dev@felix.apache.org">Felix Project Team</a>
- */
-public interface ConfigurationDependency extends Dependency, ComponentDependencyDeclaration {
- /**
- * Sets the name of the callback method that should be invoked when a configuration
- * is available. The contract for this method is identical to that of
- * <code>ManagedService.updated(Dictionary) throws ConfigurationException</code>.
- *
- * @param callback the name of the callback method
- */
- ConfigurationDependency setCallback(String callback);
-
- /**
- * Sets the <code>service.pid</code> of the configuration you are depending
- * on.
- */
- ConfigurationDependency setPid(String pid);
-
- /**
- * Sets propagation of the configuration properties to the service
- * properties. Any additional service properties specified directly are
- * merged with these.
- */
- ConfigurationDependency setPropagate(boolean propagate);
-
- /**
- * The label used to display the tab name (or section) where the properties
- * are displayed. Example: "Printer Service".
- *
- * @return The label used to display the tab name where the properties are
- * displayed (may be localized)
- */
- ConfigurationDependency setHeading(String heading);
-
- /**
- * A human readable description of the PID this configuration is associated
- * with. Example: "Configuration for the PrinterService bundle".
- *
- * @return A human readable description of the PID this configuration is
- * associated with (may be localized)
- */
- ConfigurationDependency setDescription(String description);
-
- /**
- * Points to the basename of the Properties file that can localize the Meta
- * Type informations. The default localization base name for the properties
- * is OSGI-INF/l10n/bundle, but can be overridden by the manifest
- * Bundle-Localization header (see core specification, in section
- * Localization on page 68). You can specify a specific localization
- * basename file using this method (e.g.
- * <code>setLocalization("person")</code> will match person_du_NL.properties
- * in the root bundle directory.
- */
- ConfigurationDependency setLocalization(String path);
-
- /**
- * Adds a MetaData regarding a given configuration property.
- */
- ConfigurationDependency add(PropertyMetaData properties);
-
- /**
- * Sets this dependency to be instance bound or not.
- *
- * @param isInstanceBound <code>true</code> if this dependency should be instance bound
- */
- ConfigurationDependency setInstanceBound(boolean isInstanceBound);
-}
diff --git a/dependencymanager/core/src/main/java/org/apache/felix/dm/Dependency.java b/dependencymanager/core/src/main/java/org/apache/felix/dm/Dependency.java
deleted file mode 100644
index 332348c..0000000
--- a/dependencymanager/core/src/main/java/org/apache/felix/dm/Dependency.java
+++ /dev/null
@@ -1,131 +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.felix.dm;
-
-import java.util.Dictionary;
-
-/**
- * Generic dependency for a component. A dependency can be required or not.
- * A dependency will be activated by the component it belongs to. The component
- * will call the <code>start(Service service)</code> and
- * <code>stop(Service service)</code> methods.
- *
- * After it has been started, a dependency must callback
- * the associated component's <code>dependencyAvailable()</code> and
- * <code>dependencyUnavailable()</code>
- * methods. State changes of the dependency itself may only be made as long as
- * the dependency is not 'active', meaning it is associated with a running component.
- *
- * @author <a href="mailto:dev@felix.apache.org">Felix Project Team</a>
- */
-public interface Dependency {
- /**
- * Returns <code>true</code> if this a required dependency. Required dependencies
- * are dependencies that must be available before the component can be activated.
- *
- * @return <code>true</code> if the dependency is required
- */
- public boolean isRequired();
-
- /**
- * Returns <code>true</code> if the dependency is available.
- *
- * @return <code>true</code> if the dependency is available
- */
- public boolean isAvailable();
-
- /**
- * As soon as the instance is created, keep it around, even if this dependency
- * goes away.
- *
- * @return <code>true</code> if the dependency is instance bound
- */
- public boolean isInstanceBound();
-
- /**
- * Returns <code>true>code> if auto configuration is enabled for this dependency.
- * Auto configuration means that a dependency is injected in the component instance
- * when it's available, and if it's unavailable, a "null object" will be inserted
- * instead.
- *
- * @return <code>true</code> if auto configuration is enabled for this dependency
- */
- public boolean isAutoConfig();
-
- /**
- * Returns the type of the instance that is injected.
- *
- * @return the type of the instance that is injected
- */
- public Class getAutoConfigType();
-
- /**
- * Returns the instance that is injected.
- *
- * @return the instance that is injected
- */
- public Object getAutoConfigInstance();
-
- /**
- * Returns the name of the member in the class of the component instance
- * to inject into. If you specify this, not all members of the right
- * type will be injected, only the member whose name matches.
- *
- * @return
- */
- public String getAutoConfigName();
-
- /**
- * Invoke the "added" callback on a required dependency.
- *
- * @param service
- */
- public void invokeAdded(DependencyService service);
-
- /**
- * Invoke the "removed" callback on a required dependency.
- *
- * @param service
- */
- public void invokeRemoved(DependencyService service);
-
- /**
- * Determines if the properties associated with this dependency should be propagated to
- * the properties of the service registered by the component they belong to.
- *
- * @see Dependency#getProperties()
- *
- * @return <code>true</code> if the properties should be propagated
- */
- public boolean isPropagated();
-
- /**
- * Returns the properties associated with this dependency.
- *
- * @see Dependency#isPropagated()
- *
- * @return the properties
- */
- public Dictionary getProperties();
-
- /**
- * Creates a copy of this dependency, cloning all declared state, but not the runtime state.
- */
- public Dependency createCopy();
-}
diff --git a/dependencymanager/core/src/main/java/org/apache/felix/dm/DependencyActivation.java b/dependencymanager/core/src/main/java/org/apache/felix/dm/DependencyActivation.java
deleted file mode 100644
index 3138c95..0000000
--- a/dependencymanager/core/src/main/java/org/apache/felix/dm/DependencyActivation.java
+++ /dev/null
@@ -1,42 +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.felix.dm;
-
-/**
- * Dependency activation interface that must be implemented by any
- * new dependency and is used by the dependency manager to start and
- * stop the dependency after it has been associated with a component.
- *
- * @author <a href="mailto:dev@felix.apache.org">Felix Project Team</a>
- */
-public interface DependencyActivation {
- /**
- * Invoked when the dependency should start.
- *
- * @param service the component this dependency belongs to
- */
- public void start(DependencyService service);
-
- /**
- * Invoked when the dependency should stop.
- *
- * @param service the component this dependency belongs to
- */
- public void stop(DependencyService service);
-}
diff --git a/dependencymanager/core/src/main/java/org/apache/felix/dm/DependencyActivatorBase.java b/dependencymanager/core/src/main/java/org/apache/felix/dm/DependencyActivatorBase.java
deleted file mode 100644
index f4ba47c..0000000
--- a/dependencymanager/core/src/main/java/org/apache/felix/dm/DependencyActivatorBase.java
+++ /dev/null
@@ -1,316 +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.felix.dm;
-
-import org.apache.felix.dm.impl.Logger;
-import org.osgi.framework.BundleActivator;
-import org.osgi.framework.BundleContext;
-
-/**
- * Base bundle activator class. Subclass this activator if you want to use dependency
- * management in your bundle. There are two methods you should implement:
- * <code>init()</code> and <code>destroy()</code>. Both methods take two arguments,
- * the bundle context and the dependency manager. The dependency manager can be used
- * to define all the dependencies.
- *
- * @author <a href="mailto:dev@felix.apache.org">Felix Project Team</a>
- */
-public abstract class DependencyActivatorBase implements BundleActivator {
- private BundleContext m_context;
- private DependencyManager m_manager;
- private Logger m_logger;
-
- /**
- * Initialize the dependency manager. Here you can add all components and their dependencies.
- * If something goes wrong and you do not want your bundle to be started, you can throw an
- * exception. This exception will be passed on to the <code>start()</code> method of the
- * bundle activator, causing the bundle not to start.
- *
- * @param context the bundle context
- * @param manager the dependency manager
- * @throws Exception if the initialization fails
- */
- public abstract void init(BundleContext context, DependencyManager manager) throws Exception;
-
- /**
- * Destroy the dependency manager. Here you can remove all components and their dependencies.
- * Actually, the base class will clean up your dependencies anyway, so most of the time you
- * don't need to do anything here.
- * <p>
- * If something goes wrong and you do not want your bundle to be stopped, you can throw an
- * exception. This exception will be passed on to the <code>stop()</code> method of the
- * bundle activator, causing the bundle not to stop.
- *
- * @param context the bundle context
- * @param manager the dependency manager
- * @throws Exception if the destruction fails
- */
- public void destroy(BundleContext context, DependencyManager manager) throws Exception { }
-
- /**
- * Start method of the bundle activator. Initializes the dependency manager
- * and calls <code>init()</code>.
- *
- * @param context the bundle context
- */
- public void start(BundleContext context) throws Exception {
- m_context = context;
- m_logger = new Logger(context);
- m_manager = new DependencyManager(context, m_logger);
- init(m_context, m_manager);
- }
-
- /**
- * Stop method of the bundle activator. Calls the <code>destroy()</code> method
- * and cleans up all left over dependencies.
- *
- * @param context the bundle context
- */
- public void stop(BundleContext context) throws Exception {
- destroy(m_context, m_manager);
- m_manager.clear();
- m_manager = null;
- m_context = null;
- }
-
- /**
- * Returns the bundle context that is associated with this bundle.
- *
- * @return the bundle context
- */
- public BundleContext getBundleContext() {
- return m_context;
- }
-
- /**
- * Returns the dependency manager that is associated with this bundle.
- *
- * @return the dependency manager
- */
- public DependencyManager getDependencyManager() {
- return m_manager;
- }
-
- /**
- * Returns the logger that is associated with this bundle. A logger instance
- * is a proxy that will log to a real OSGi logservice if available and standard
- * out if not.
- *
- * @return the logger
- */
- public Logger getLogger() {
- return m_logger;
- }
-
- /**
- * Creates a new component.
- *
- * @return the new component
- */
- public Component createComponent() {
- return m_manager.createComponent();
- }
-
- /**
- * Creates a new service dependency.
- *
- * @return the service dependency
- */
- public ServiceDependency createServiceDependency() {
- return m_manager.createServiceDependency();
- }
-
- /**
- * Creates a new temporal service dependency.
- *
- * @param timeout the max number of milliseconds to wait for a service availability.
- * @return the service dependency
- */
- public TemporalServiceDependency createTemporalServiceDependency() {
- return m_manager.createTemporalServiceDependency();
- }
-
- /**
- * Creates a new configuration dependency.
- *
- * @return the configuration dependency
- */
- public ConfigurationDependency createConfigurationDependency() {
- return m_manager.createConfigurationDependency();
- }
-
- /**
- * Creates a new configuration property metadata.
- *
- * @return the configuration property metadata
- */
- public PropertyMetaData createPropertyMetaData() {
- return m_manager.createPropertyMetaData();
- }
-
- /**
- * Creates a new bundle dependency.
- *
- * @return the bundle dependency
- */
- public BundleDependency createBundleDependency() {
- return m_manager.createBundleDependency();
- }
-
- /**
- * Creates a new resource dependency.
- *
- * @return the resource dependency
- */
- public ResourceDependency createResourceDependency() {
- return m_manager.createResourceDependency();
- }
-
- /**
- * Creates a new aspect service.
- *
- * @return the aspect service
- * @see DependencyManager#createAspectService(Class, String, int, String)
- */
- public Component createAspectService(Class serviceInterface, String serviceFilter, int ranking, String attributeName) {
- return m_manager.createAspectService(serviceInterface, serviceFilter, ranking, attributeName);
- }
-
- /**
- * Creates a new aspect service.
- *
- * @return the aspect service
- * @see DependencyManager#createAspectService(Class, String, int)
- */
- public Component createAspectService(Class serviceInterface, String serviceFilter, int ranking) {
- return m_manager.createAspectService(serviceInterface, serviceFilter, ranking);
- }
-
- /**
- * Creates a new aspect service.
- *
- * @return the aspect service
- * @see DependencyManager#createAspectService(Class, String, int, String, String, String)
- */
- public Component createAspectService(Class serviceInterface, String serviceFilter, int ranking, String add, String change, String remove) {
- return m_manager.createAspectService(serviceInterface, serviceFilter, ranking, add, change, remove);
- }
-
- /**
- * Creates a new adapter service.
- *
- * @return the adapter service
- * @see DependencyManager#createAdapterService(Class, String)
- */
- public Component createAdapterService(Class serviceInterface, String serviceFilter) {
- return m_manager.createAdapterService(serviceInterface, serviceFilter);
- }
-
- /**
- * Creates a new adapter service.
- *
- * @return the adapter service
- * @see DependencyManager#createAdapterService(Class, String, String)
- */
- public Component createAdapterService(Class serviceInterface, String serviceFilter, String autoConfig) {
- return m_manager.createAdapterService(serviceInterface, serviceFilter, autoConfig);
- }
-
- /**
- * Creates a new adapter service.
- *
- * @return the adapter service
- * @see DependencyManager#createAdapterService(Class, String, String, String, String)
- */
- public Component createAdapterService(Class serviceInterface, String serviceFilter, String add, String change, String remove) {
- return m_manager.createAdapterService(serviceInterface, serviceFilter, add, change, remove);
- }
-
- /**
- * Creates a new adapter service.
- * @return the adapter service
- * @see DependencyManager#createAdapterService(Class, String, String, String, String, String)
- */
- public Component createAdapterService(Class serviceInterface, String serviceFilter, String add, String change, String remove, String swap) {
- return m_manager.createAdapterService(serviceInterface, serviceFilter, add, change, remove, swap);
- }
-
- /**
- * Creates a new resource adapter service.
- *
- * @return the resource adapter service
- */
- public Component createResourceAdapter(String resourceFilter, boolean propagate, Object callbackInstance, String callbackChanged) {
- return m_manager.createResourceAdapterService(resourceFilter, propagate, callbackInstance, callbackChanged);
- }
-
- /**
- * Creates a new resource adapter service.
- *
- * @return the resource adapter service
- */
- public Component createResourceAdapter(String resourceFilter, boolean propagate, Object callbackInstance, String callbackSet, String callbackChanged) {
- return m_manager.createResourceAdapterService(resourceFilter, propagate, callbackInstance, callbackSet, callbackChanged);
- }
-
- /**
- * Creates a new resource adapter service.
- *
- * @return the resource adapter service
- */
- public Component createResourceAdapter(String resourceFilter, Object propagateCallbackInstance, String propagateCallbackMethod, Object callbackInstance, String callbackChanged) {
- return m_manager.createResourceAdapterService(resourceFilter, propagateCallbackInstance, propagateCallbackMethod, callbackInstance, null, callbackChanged);
- }
-
- /**
- * Creates a new resource adapter service.
- *
- * @return the resource adapter service
- */
- public Component createResourceAdapter(String resourceFilter, Object propagateCallbackInstance, String propagateCallbackMethod, Object callbackInstance, String callbackSet, String callbackChanged) {
- return m_manager.createResourceAdapterService(resourceFilter, propagateCallbackInstance, propagateCallbackMethod, callbackInstance, callbackSet, callbackChanged);
- }
-
- /**
- * Creates a new bundle adapter service.
- *
- * @return the bundle adapter service
- */
- public Component createBundleAdapterService(int bundleStateMask, String bundleFilter, boolean propagate) {
- return m_manager.createBundleAdapterService(bundleStateMask, bundleFilter, propagate);
- }
-
- /**
- * Creates a new factory configuration adapter service.
- *
- * @return the factory configuration adapter service
- */
- public Component createFactoryConfigurationAdapterService(String factoryPid, String update, boolean propagate) {
- return m_manager.createFactoryConfigurationAdapterService(factoryPid, update, propagate);
- }
-
- /**
- * Creates a new factory configuration adapter service.
- *
- * @return the factory configuration adapter service
- */
- public Component createFactoryConfigurationAdapterService(String factoryPid, String update, boolean propagate, String heading, String desc, String localization, PropertyMetaData[] propertiesMetaData) {
- return m_manager.createFactoryConfigurationAdapterService(factoryPid, update, propagate, heading, desc, localization, propertiesMetaData);
- }
-}
diff --git a/dependencymanager/core/src/main/java/org/apache/felix/dm/DependencyManager.java b/dependencymanager/core/src/main/java/org/apache/felix/dm/DependencyManager.java
deleted file mode 100644
index 3d97b42..0000000
--- a/dependencymanager/core/src/main/java/org/apache/felix/dm/DependencyManager.java
+++ /dev/null
@@ -1,625 +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.felix.dm;
-
-import java.lang.ref.WeakReference;
-import java.util.ArrayList;
-import java.util.Collections;
-import java.util.HashSet;
-import java.util.Iterator;
-import java.util.List;
-import java.util.Set;
-
-import org.apache.felix.dm.impl.AdapterServiceImpl;
-import org.apache.felix.dm.impl.AspectServiceImpl;
-import org.apache.felix.dm.impl.BundleAdapterServiceImpl;
-import org.apache.felix.dm.impl.ComponentImpl;
-import org.apache.felix.dm.impl.FactoryConfigurationAdapterServiceImpl;
-import org.apache.felix.dm.impl.Logger;
-import org.apache.felix.dm.impl.ResourceAdapterServiceImpl;
-import org.apache.felix.dm.impl.dependencies.BundleDependencyImpl;
-import org.apache.felix.dm.impl.dependencies.ConfigurationDependencyImpl;
-import org.apache.felix.dm.impl.dependencies.ResourceDependencyImpl;
-import org.apache.felix.dm.impl.dependencies.ServiceDependencyImpl;
-import org.apache.felix.dm.impl.dependencies.TemporalServiceDependencyImpl;
-import org.apache.felix.dm.impl.index.AspectFilterIndex;
-import org.apache.felix.dm.impl.index.AdapterFilterIndex;
-import org.apache.felix.dm.impl.index.ServiceRegistryCache;
-import org.apache.felix.dm.impl.index.multiproperty.MultiPropertyFilterIndex;
-import org.apache.felix.dm.impl.metatype.PropertyMetaDataImpl;
-import org.osgi.framework.Bundle;
-import org.osgi.framework.BundleContext;
-import org.osgi.framework.BundleException;
-import org.osgi.framework.FrameworkUtil;
-
-/**
- * The dependency manager manages all components and their dependencies. Using
- * this API you can declare all components and their dependencies. Under normal
- * circumstances, you get passed an instance of this class through the
- * <code>DependencyActivatorBase</code> subclass you use as your
- * <code>BundleActivator</code>, but it is also possible to create your
- * own instance.
- *
- * @author <a href="mailto:dev@felix.apache.org">Felix Project Team</a>
- */
-public class DependencyManager {
- public static final String ASPECT = "org.apache.felix.dependencymanager.aspect";
- public static final String SERVICEREGISTRY_CACHE_INDICES = "org.apache.felix.dependencymanager.filterindex";
- public static final String METHOD_CACHE_SIZE = "org.apache.felix.dependencymanager.methodcache";
- private final BundleContext m_context;
- private final Logger m_logger;
- private List m_components = Collections.synchronizedList(new ArrayList());
-
- /**
- * Creates a new dependency manager. You need to supply the
- * <code>BundleContext</code> to be used by the dependency
- * manager to register services and communicate with the
- * framework.
- *
- * @param context the bundle context
- */
- public DependencyManager(BundleContext context) {
- this(context, new Logger(context));
- }
-
- DependencyManager(BundleContext context, Logger logger) {
- m_context = createContext(context);
- m_logger = logger;
- synchronized (m_dependencyManagers) {
- m_dependencyManagers.add(new WeakReference(this));
- }
- }
-
- // service registry cache
- private static ServiceRegistryCache m_serviceRegistryCache;
- private static final Set /* WeakReference<DependencyManager> */ m_dependencyManagers = new HashSet();
- static {
- String index = System.getProperty(SERVICEREGISTRY_CACHE_INDICES);
- if (index != null) {
- Bundle bundle = FrameworkUtil.getBundle(DependencyManager.class);
- try {
- if (bundle.getState() != Bundle.ACTIVE) {
- bundle.start();
- }
- BundleContext bundleContext = bundle.getBundleContext();
-
- m_serviceRegistryCache = new ServiceRegistryCache(bundleContext);
- m_serviceRegistryCache.open(); // TODO close it somewhere
- String[] props = index.split(";");
- for (int i = 0; i < props.length; i++) {
- if (props[i].equals("*aspect*")) {
- m_serviceRegistryCache.addFilterIndex(new AspectFilterIndex());
- }
- else if (props[i].equals("*adapter*")) {
- m_serviceRegistryCache.addFilterIndex(new AdapterFilterIndex());
- }
- else {
- m_serviceRegistryCache.addFilterIndex(new MultiPropertyFilterIndex(props[i]));
- }
- }
- }
- catch (BundleException e) {
- // if we cannot start ourselves, we cannot use the indices
- // TODO we might want to warn people about this
- }
- }
- }
-
- public static List getDependencyManagers() {
- List /* DependencyManager */ result = new ArrayList();
- synchronized (m_dependencyManagers) {
- Iterator iterator = m_dependencyManagers.iterator();
- while (iterator.hasNext()) {
- WeakReference reference = (WeakReference) iterator.next();
- DependencyManager manager = (DependencyManager) reference.get();
- if (manager != null) {
- try {
- manager.getBundleContext().getBundle();
- result.add(manager);
- continue;
- }
- catch (IllegalStateException e) {
- }
- }
- iterator.remove();
- }
- }
- return result;
- }
-
- private BundleContext createContext(BundleContext context) {
- if (m_serviceRegistryCache != null) {
- return m_serviceRegistryCache.createBundleContextInterceptor(context);
- }
- else {
- return context;
- }
- }
-
- public BundleContext getBundleContext() {
- return m_context;
- }
-
- /**
- * Adds a new service to the dependency manager. After the service was added
- * it will be started immediately.
- *
- * @param service the service to add
- */
- public void add(Component service) {
- m_components.add(service);
- service.start();
- }
-
- /**
- * Removes a service from the dependency manager. Before the service is removed
- * it is stopped first.
- *
- * @param service the service to remove
- */
- public void remove(Component service) {
- service.stop();
- m_components.remove(service);
- }
-
- /**
- * Creates a new service.
- *
- * @return the new service
- */
- public Component createComponent() {
- return new ComponentImpl(m_context, this, m_logger);
- }
-
- /**
- * Creates a new service dependency.
- *
- * @return the service dependency
- */
- public ServiceDependency createServiceDependency() {
- return new ServiceDependencyImpl(m_context, m_logger);
- }
-
- /**
- * Creates a new temporal service dependency.
- *
- * @return a new temporal service dependency
- */
- public TemporalServiceDependency createTemporalServiceDependency() {
- return new TemporalServiceDependencyImpl(m_context, m_logger);
- }
-
- /**
- * Creates a new configuration dependency.
- *
- * @return the configuration dependency
- */
- public ConfigurationDependency createConfigurationDependency() {
- return new ConfigurationDependencyImpl(m_context, m_logger);
- }
-
- /**
- * Creates a new configuration property metadata.
- *
- * @return the configuration property metadata.
- */
- public PropertyMetaData createPropertyMetaData() {
- return new PropertyMetaDataImpl();
- }
-
- /**
- * Creates a new bundle dependency.
- *
- * @return a new BundleDependency instance.
- */
- public BundleDependency createBundleDependency() {
- return new BundleDependencyImpl(m_context, m_logger);
- }
-
- /**
- * Creates a new resource dependency.
- *
- * @return the resource dependency
- */
- public ResourceDependency createResourceDependency() {
- return new ResourceDependencyImpl(m_context, m_logger);
- }
-
- /**
- * Creates a new aspect. The aspect will be applied to any service that
- * matches the specified interface and filter. For each matching service
- * an aspect will be created based on the aspect implementation class.
- * The aspect will be registered with the same interface and properties
- * as the original service, plus any extra properties you supply here.
- * It will also inherit all dependencies, and if you declare the original
- * service as a member it will be injected.
- *
- * <h3>Usage Example</h3>
- *
- * <blockquote><pre>
- * manager.createAspectService(ExistingService.class, "(foo=bar)", 10, "m_service")
- * .setImplementation(ExistingServiceAspect.class)
- * );
- * </pre></blockquote>
- *
- * @param serviceInterface the service interface to apply the aspect to
- * @param serviceFilter the filter condition to use with the service interface
- * @param ranking the level used to organize the aspect chain ordering
- * @param autoConfig the aspect implementation field name where to inject original service.
- * If null, any field matching the original service will be injected.
- * @return a service that acts as a factory for generating aspects
- */
- public Component createAspectService(Class serviceInterface, String serviceFilter, int ranking, String autoConfig) {
- return new AspectServiceImpl(this, serviceInterface, serviceFilter, ranking, autoConfig, null, null, null, null);
- }
- /**
- * Creates a new aspect. The aspect will be applied to any service that
- * matches the specified interface and filter. For each matching service
- * an aspect will be created based on the aspect implementation class.
- * The aspect will be registered with the same interface and properties
- * as the original service, plus any extra properties you supply here.
- * It will also inherit all dependencies, and if you declare the original
- * service as a member it will be injected.
- *
- * <h3>Usage Example</h3>
- *
- * <blockquote><pre>
- * manager.createAspectService(ExistingService.class, "(foo=bar)", 10)
- * .setImplementation(ExistingServiceAspect.class)
- * );
- * </pre></blockquote>
- *
- * @param serviceInterface the service interface to apply the aspect to
- * @param serviceFilter the filter condition to use with the service interface
- * @param ranking the level used to organize the aspect chain ordering
- * @return a service that acts as a factory for generating aspects
- */
- public Component createAspectService(Class serviceInterface, String serviceFilter, int ranking) {
- return new AspectServiceImpl(this, serviceInterface, serviceFilter, ranking, null, null, null, null, null);
- }
- /**
- * Creates a new aspect. The aspect will be applied to any service that
- * matches the specified interface and filter. For each matching service
- * an aspect will be created based on the aspect implementation class.
- * The aspect will be registered with the same interface and properties
- * as the original service, plus any extra properties you supply here.
- * It will also inherit all dependencies, and if you declare the original
- * service as a member it will be injected.
- *
- * <h3>Usage Example</h3>
- *
- * <blockquote><pre>
- * manager.createAspectService(ExistingService.class, "(foo=bar)", 10, "add", "change", "remove")
- * .setImplementation(ExistingServiceAspect.class)
- * );
- * </pre></blockquote>
- *
- * @param serviceInterface the service interface to apply the aspect to
- * @param serviceFilter the filter condition to use with the service interface
- * @param ranking the level used to organize the aspect chain ordering
- * @param add name of the callback method to invoke on add
- * @param change name of the callback method to invoke on change
- * @param remove name of the callback method to invoke on remove
- * @return a service that acts as a factory for generating aspects
- */
- public Component createAspectService(Class serviceInterface, String serviceFilter, int ranking, String add, String change, String remove) {
- return new AspectServiceImpl(this, serviceInterface, serviceFilter, ranking, null, add, change, remove, null);
- }
-
- /**
- * Creates a new aspect. The aspect will be applied to any service that
- * matches the specified interface and filter. For each matching service
- * an aspect will be created based on the aspect implementation class.
- * The aspect will be registered with the same interface and properties
- * as the original service, plus any extra properties you supply here.
- * It will also inherit all dependencies, and if you declare the original
- * service as a member it will be injected.
- *
- * <h3>Usage Example</h3>
- *
- * <blockquote><pre>
- * manager.createAspectService(ExistingService.class, "(foo=bar)", 10, "add", "change", "remove")
- * .setImplementation(ExistingServiceAspect.class)
- * );
- * </pre></blockquote>
- *
- * @param serviceInterface the service interface to apply the aspect to
- * @param serviceFilter the filter condition to use with the service interface
- * @param ranking the level used to organize the aspect chain ordering
- * @param add name of the callback method to invoke on add
- * @param change name of the callback method to invoke on change
- * @param remove name of the callback method to invoke on remove
- * @param swap name of the callback method to invoke on swap
- * @return a service that acts as a factory for generating aspects
- */
- public Component createAspectService(Class serviceInterface, String serviceFilter, int ranking, String add, String change, String remove, String swap) {
- return new AspectServiceImpl(this, serviceInterface, serviceFilter, ranking, null, add, change, remove, swap);
- }
-
- /**
- * Creates a new adapter. The adapter will be applied to any service that
- * matches the specified interface and filter. For each matching service
- * an adapter will be created based on the adapter implementation class.
- * The adapter will be registered with the specified interface and existing properties
- * from the original service plus any extra properties you supply here.
- * It will also inherit all dependencies, and if you declare the original
- * service as a member it will be injected.
- *
- * <h3>Usage Example</h3>
- *
- * <blockquote><pre>
- * manager.createAdapterService(AdapteeService.class, "(foo=bar)")
- * .setInterface(AdapterService.class, new Hashtable() {{ put("extra", "property"); }})
- * .setImplementation(AdapterImpl.class);
- * </pre></blockquote>
- *
- * @param serviceInterface the service interface to apply the adapter to
- * @param serviceFilter the filter condition to use with the service interface
- * @return a service that acts as a factory for generating adapters
- */
- public Component createAdapterService(Class serviceInterface, String serviceFilter) {
- return new AdapterServiceImpl(this, serviceInterface, serviceFilter, null, null, null, null);
- }
- /**
- * Creates a new adapter. The adapter will be applied to any service that
- * matches the specified interface and filter. For each matching service
- * an adapter will be created based on the adapter implementation class.
- * The adapter will be registered with the specified interface and existing properties
- * from the original service plus any extra properties you supply here.
- * It will also inherit all dependencies, and if you declare the original
- * service as a member it will be injected.
- *
- * <h3>Usage Example</h3>
- *
- * <blockquote><pre>
- * manager.createAdapterService(AdapteeService.class, "(foo=bar)", "m_service")
- * .setInterface(AdapterService.class, new Hashtable() {{ put("extra", "property"); }})
- * .setImplementation(AdapterImpl.class);
- * </pre></blockquote>
- *
- * @param serviceInterface the service interface to apply the adapter to
- * @param serviceFilter the filter condition to use with the service interface
- * @param autoConfig the name of the member to inject the service into
- * @return a service that acts as a factory for generating adapters
- */
- public Component createAdapterService(Class serviceInterface, String serviceFilter, String autoConfig) {
- return new AdapterServiceImpl(this, serviceInterface, serviceFilter, autoConfig, null, null, null);
- }
- /**
- * Creates a new adapter. The adapter will be applied to any service that
- * matches the specified interface and filter. For each matching service
- * an adapter will be created based on the adapter implementation class.
- * The adapter will be registered with the specified interface and existing properties
- * from the original service plus any extra properties you supply here.
- * It will also inherit all dependencies, and if you declare the original
- * service as a member it will be injected.
- *
- * <h3>Usage Example</h3>
- *
- * <blockquote><pre>
- * manager.createAdapterService(AdapteeService.class, "(foo=bar)", "add", "change", "remove")
- * .setInterface(AdapterService.class, new Hashtable() {{ put("extra", "property"); }})
- * .setImplementation(AdapterImpl.class);
- * </pre></blockquote>
- *
- * @param serviceInterface the service interface to apply the adapter to
- * @param serviceFilter the filter condition to use with the service interface
- * @param add name of the callback method to invoke on add
- * @param change name of the callback method to invoke on change
- * @param remove name of the callback method to invoke on remove
- * @param swap name of the callback method to invoke on swap
- * @return a service that acts as a factory for generating adapters
- */
- public Component createAdapterService(Class serviceInterface, String serviceFilter, String add, String change, String remove, String swap) {
- return new AdapterServiceImpl(this, serviceInterface, serviceFilter, null, add, change, remove, swap);
- }
-
- /** @see DependencyManager#createAdapterService(Class, String, String, String, String, String) */
- public Component createAdapterService(Class serviceInterface, String serviceFilter, String add, String change, String remove) {
- return new AdapterServiceImpl(this, serviceInterface, serviceFilter, null, add, change, remove);
- }
-
- /**
- * Creates a new resource adapter. The adapter will be applied to any resource that
- * matches the specified filter condition. For each matching resource
- * an adapter will be created based on the adapter implementation class.
- * The adapter will be registered with the specified interface and existing properties
- * from the original resource plus any extra properties you supply here.
- * It will also inherit all dependencies, and if you declare the original
- * service as a member it will be injected.
- *
- * <h3>Usage Example</h3>
- *
- * <blockquote><pre>
- * manager.createResourceAdapterService("(&(path=/test)(repository=TestRepository))", true)
- * // The interface to use when registering adapter
- * .setInterface(AdapterService.class.getName(), new Hashtable() {{ put("foo", "bar"); }})
- * // the implementation of the adapter
- * .setImplementation(AdapterServiceImpl.class);
- * </pre></blockquote>
- *
- * @param resourceFilter the filter condition to use with the resource
- * @param resourcePropertiesFilter the filter condition on the resource properties to use with the resource
- * @param propagate <code>true</code> if properties from the resource should be propagated to the service
- * @param callbackInstance instance to invoke the callback on
- * @param callbackChanged the name of the callback method
- * @return a service that acts as a factory for generating resource adapters
- * @see Resource
- */
- public Component createResourceAdapterService(String resourceFilter, boolean propagate, Object callbackInstance, String callbackChanged) {
- return new ResourceAdapterServiceImpl(this, resourceFilter, propagate, callbackInstance, null, callbackChanged);
- }
-
- /** @see DependencyManager#createResourceAdapterService(String, boolean, Object, String) */
- public Component createResourceAdapterService(String resourceFilter, boolean propagate, Object callbackInstance, String callbackSet, String callbackChanged) {
- return new ResourceAdapterServiceImpl(this, resourceFilter, propagate, callbackInstance, callbackSet, callbackChanged);
- }
-
- /** @see DependencyManager#createResourceAdapterService(String, boolean, Object, String) */
- public Component createResourceAdapterService(String resourceFilter, Object propagateCallbackInstance, String propagateCallbackMethod, Object callbackInstance, String callbackChanged) {
- return new ResourceAdapterServiceImpl(this, resourceFilter, propagateCallbackInstance, propagateCallbackMethod, callbackInstance, null, callbackChanged);
- }
-
- /** @see DependencyManager#createResourceAdapterService(String, boolean, Object, String) */
- public Component createResourceAdapterService(String resourceFilter, Object propagateCallbackInstance, String propagateCallbackMethod, Object callbackInstance, String callbackSet, String callbackChanged) {
- return new ResourceAdapterServiceImpl(this, resourceFilter, propagateCallbackInstance, propagateCallbackMethod, callbackInstance, callbackSet, callbackChanged);
- }
-
- /**
- * Creates a new bundle adapter. The adapter will be applied to any bundle that
- * matches the specified bundle state mask and filter condition. For each matching
- * bundle an adapter will be created based on the adapter implementation class.
- * The adapter will be registered with the specified interface
- *
- * TODO and existing properties from the original resource plus any extra properties you supply here.
- * It will also inherit all dependencies, and if you declare the original
- * service as a member it will be injected.
- *
- * <h3>Usage Example</h3>
- *
- * <blockquote><pre>
- * manager.createBundleAdapterService(Bundle.INSTALLED | Bundle.RESOLVED | Bundle.ACTIVE,
- * "(Bundle-SymbolicName=org.apache.felix.dependencymanager)",
- * true)
- * // The interface to use when registering adapter
- * .setInterface(AdapterService.class.getName(), new Hashtable() {{ put("foo", "bar"); }})
- * // the implementation of the adapter
- * .setImplementation(AdapterServiceImpl.class);
- * </pre></blockquote>
- *
- * @param bundleStateMask the bundle state mask to apply
- * @param bundleFilter the filter to apply to the bundle manifest
- * @param propagate <code>true</code> if properties from the bundle should be propagated to the service
- * @return a service that acts as a factory for generating bundle adapters
- */
- public Component createBundleAdapterService(int bundleStateMask, String bundleFilter, boolean propagate) {
- return new BundleAdapterServiceImpl(this, bundleStateMask, bundleFilter, propagate);
- }
-
- /**
- * Creates a new Managed Service Factory Configuration Adapter. For each new Config Admin factory configuration matching
- * the factoryPid, an adapter will be created based on the adapter implementation class.
- * The adapter will be registered with the specified interface, and with the specified adapter service properties.
- * Depending on the <code>propagate</code> parameter, every public factory configuration properties
- * (which don't start with ".") will be propagated along with the adapter service properties.
- * It will also inherit all dependencies.
- *
- * <h3>Usage Example</h3>
- *
- * <blockquote><pre>
- * manager.createFactoryConfigurationAdapterService("MyFactoryPid", "update", true)
- * // The interface to use when registering adapter
- * .setInterface(AdapterService.class.getName(), new Hashtable() {{ put("foo", "bar"); }})
- * // the implementation of the adapter
- * .setImplementation(AdapterServiceImpl.class);
- * </pre></blockquote>
- *
- * @param factoryPid the pid matching the factory configuration
- * @param update the adapter method name that will be notified when the factory configuration is created/updated.
- * @param propagate true if public factory configuration should be propagated to the adapter service properties
- * @return a service that acts as a factory for generating the managed service factory configuration adapter
- */
- public Component createFactoryConfigurationAdapterService(String factoryPid, String update, boolean propagate) {
- return new FactoryConfigurationAdapterServiceImpl(this, factoryPid, update, propagate);
- }
-
- /**
- * Creates a new Managed Service Factory Configuration Adapter with meta type support. For each new Config Admin
- * factory configuration matching the factoryPid, an adapter will be created based on the adapter implementation
- * class. The adapter will be registered with the specified interface, and with the specified adapter service
- * properties. Depending on the <code>propagate</code> parameter, every public factory configuration properties
- * (which don't start with ".") will be propagated along with the adapter service properties.
- * It will also inherit all dependencies.
- *
- * <h3>Usage Example</h3>
- *
- * <blockquote><pre>
- * PropertyMetaData[] propertiesMetaData = new PropertyMetaData[] {
- * manager.createPropertyMetaData()
- * .setCardinality(Integer.MAX_VALUE)
- * .setType(String.class)
- * .setHeading("English words")
- * .setDescription("Declare here some valid english words")
- * .setDefaults(new String[] {"hello", "world"})
- * .setId("words")
- * };
- *
- * manager.add(createFactoryConfigurationAdapterService("FactoryPid",
- * "updated",
- * true, // propagate CM settings
- * "EnglishDictionary",
- * "English dictionary configuration properties",
- * null,
- * propertiesMetaData)
- * .setImplementation(Adapter.class));
- * </pre></blockquote>
- *
- * @param factoryPid the pid matching the factory configuration
- * @param update the adapter method name that will be notified when the factory configuration is created/updated.
- * @param propagate true if public factory configuration should be propagated to the adapter service properties
- * @param heading The label used to display the tab name (or section) where the properties are displayed.
- * Example: "Printer Service"
- * @param desc A human readable description of the factory PID this configuration is associated with.
- * Example: "Configuration for the PrinterService bundle"
- * @param localization Points to the basename of the Properties file that can localize the Meta Type informations.
- * The default localization base name for the properties is OSGI-INF/l10n/bundle, but can
- * be overridden by the manifest Bundle-Localization header (see core specification, in section Localization
- * on page 68). You can specify a specific localization basename file using this parameter
- * (e.g. <code>"person"</code> will match person_du_NL.properties in the root bundle directory).
- * @param propertiesMetaData Array of MetaData regarding configuration properties
- * @return a service that acts as a factory for generating the managed service factory configuration adapter
- */
- public Component createFactoryConfigurationAdapterService(String factoryPid, String update, boolean propagate, String heading, String desc, String localization, PropertyMetaData[] propertiesMetaData) {
- return new FactoryConfigurationAdapterServiceImpl(this, factoryPid, update, propagate, m_context, m_logger, heading, desc, localization, propertiesMetaData);
- }
-
- /**
- * Returns a list of services.
- *
- * @return a list of services
- */
- public List getComponents() {
- synchronized (m_components) {
- List copyComponents = new ArrayList(m_components.size());
- for (int i = 0; i < m_components.size(); i++) {
- copyComponents.add(m_components.get(i));
- }
- return copyComponents;
- }
- }
-
- /**
- * Removes all components and their dependencies.
- */
- public void clear() {
- Component[] components;
- synchronized (m_components) {
- components = (Component[]) m_components.toArray(new Component[m_components.size()]);
- }
- for (int i = components.length - 1; i >= 0; i--) {
- Component component = (Component) components[i];
- remove(component);
- // remove any state listeners that are still registered
- if (component instanceof ComponentImpl) {
- ComponentImpl si = (ComponentImpl) component;
- si.removeStateListeners();
- }
- }
- }
-}
diff --git a/dependencymanager/core/src/main/java/org/apache/felix/dm/DependencyService.java b/dependencymanager/core/src/main/java/org/apache/felix/dm/DependencyService.java
deleted file mode 100644
index 6fe87d8..0000000
--- a/dependencymanager/core/src/main/java/org/apache/felix/dm/DependencyService.java
+++ /dev/null
@@ -1,113 +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.felix.dm;
-
-import org.osgi.framework.BundleContext;
-
-/**
- * Interface to the component, so dependencies can interact with it.
- *
- * @author <a href="mailto:dev@felix.apache.org">Felix Project Team</a>
- */
-public interface DependencyService {
- /**
- * Will be called when the dependency becomes available.
- *
- * @param dependency the dependency
- */
- public void dependencyAvailable(Dependency dependency);
-
- /**
- * Will be called when the dependency becomes unavailable .
- *
- * @param dependency the dependency
- */
- public void dependencyUnavailable(Dependency dependency);
-
- /**
- * Will be called when the dependency changes.
- *
- * @param dependency the dependency
- */
- public void dependencyChanged(Dependency dependency);
-
- /**
- * Returns the component instance.
- *
- * @return component instance
- */
- public Object getService(); // is also defined on the Service interface
-
- /**
- * Initializes the component. Instantiates it and injects the default injectables such
- * as {@link BundleContext} and {@link DependencyManager}.
- */
- public void initService(); // was an implementation method TODO we use it in ConfDepImpl but should not (probably)
-
- /**
- * Returns <code>true</code> if this component is registered. In other words, all
- * its required dependencies are available.
- *
- * @return <code>true</code> if the component is registered
- */
- public boolean isRegistered(); // impl method
-
- /**
- * Returns a list of all instances that are part of the composition for this component.
- *
- * @return an array of instances
- */
- public Object[] getCompositionInstances(); // impl method
-
- /**
- * Returns <code>true</code> if this component is instantiated.
- *
- * @return <code>true</code> if this component is instantiated
- */
- public boolean isInstantiated();
-
- /**
- * Can be called by the dependency whenever it wants to invoke callback methods.
- */
- public void invokeCallbackMethod(Object[] instances, String methodName, Class[][] signatures, Object[][] parameters);
-
- /**
- * Returns the component interface.
- *
- * @return the component interface
- */
- public Component getServiceInterface();
-
- /**
- * Injects the dependency into autoconfig class field (if any) of the dependency service.
- * @param dependency
- */
- public void autoConfig(final Dependency dependency);
-
- /**
- * Propagates the dependency properties to the ones provided by the dependency service.
- * No effet if the dependency is not configured with the setPropagate method.
- *
- * @param dependency the dependency whose properties will be propagated to the service properties of this dependency service.
- *
- * @see ServiceDependency#setPropagate(boolean)
- * @see ServiceDependency#setPropagate(String)
- */
- public void propagate(final Dependency dependency);
-}
diff --git a/dependencymanager/core/src/main/java/org/apache/felix/dm/FilterIndex.java b/dependencymanager/core/src/main/java/org/apache/felix/dm/FilterIndex.java
deleted file mode 100644
index df648e9..0000000
--- a/dependencymanager/core/src/main/java/org/apache/felix/dm/FilterIndex.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.felix.dm;
-
-import java.util.List;
-
-import org.osgi.framework.BundleContext;
-import org.osgi.framework.ServiceEvent;
-import org.osgi.framework.ServiceListener;
-
-/**
- * A filter index is an interface you can implement to create your own, optimized index for specific filter expressions.
- *
- * @author <a href="mailto:dev@felix.apache.org">Felix Project Team</a>
- */
-public interface FilterIndex {
- /** Opens this filter index. */
- public void open(BundleContext context);
- /** Closes this filter index. */
- public void close();
- /** Determines if the combination of class and filter is applicable for this filter index. */
- public boolean isApplicable(String clazz, String filter);
- /** Returns all service references that match the specified class and filter. */
- public List /* <ServiceReference> */ getAllServiceReferences(String clazz, String filter);
- /** Invoked whenever a service event occurs. */
- public void serviceChanged(ServiceEvent event);
- /** Adds a service listener to this filter index. */
- public void addServiceListener(ServiceListener listener, String filter);
- /** Removes a service listener from this filter index. If the listener is not present in the filter index, this method does nothing. */
- public void removeServiceListener(ServiceListener listener);
-}
diff --git a/dependencymanager/core/src/main/java/org/apache/felix/dm/InvocationUtil.java b/dependencymanager/core/src/main/java/org/apache/felix/dm/InvocationUtil.java
deleted file mode 100644
index 46ddf60..0000000
--- a/dependencymanager/core/src/main/java/org/apache/felix/dm/InvocationUtil.java
+++ /dev/null
@@ -1,204 +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.felix.dm;
-
-import java.lang.reflect.InvocationTargetException;
-import java.lang.reflect.Method;
-import java.lang.reflect.Modifier;
-import java.lang.reflect.Proxy;
-import java.util.Arrays;
-import java.util.LinkedHashMap;
-import java.util.Map;
-
-/**
- * Utility methods for invoking callbacks. Lookups of callbacks are accellerated by using a LRU cache.
- *
- * @author <a href="mailto:dev@felix.apache.org">Felix Project Team</a>
- */
-public class InvocationUtil {
- private static final Map /* <Key, Method> */ m_methodCache;
- static {
- int size = 2048;
- try {
- String value = System.getProperty(DependencyManager.METHOD_CACHE_SIZE);
- if (value != null) {
- size = Integer.parseInt(value);
- }
- }
- catch (Exception e) {}
- m_methodCache = new LRUMap(Math.max(size, 64));
- }
-
- /**
- * Invokes a callback method on an instance. The code will search for a callback method with
- * the supplied name and any of the supplied signatures in order, invoking the first one it finds.
- *
- * @param instance the instance to invoke the method on
- * @param methodName the name of the method
- * @param signatures the ordered list of signatures to look for
- * @param parameters the parameter values to use for each potential signature
- * @return whatever the method returns
- * @throws NoSuchMethodException when no method could be found
- * @throws IllegalArgumentException when illegal values for this methods arguments are supplied
- * @throws IllegalAccessException when the method cannot be accessed
- * @throws InvocationTargetException when the method that was invoked throws an exception
- */
- public static Object invokeCallbackMethod(Object instance, String methodName, Class[][] signatures, Object[][] parameters) throws NoSuchMethodException, IllegalArgumentException, IllegalAccessException, InvocationTargetException {
- Class currentClazz = instance.getClass();
- while (currentClazz != null && currentClazz != Object.class) {
- try {
- return invokeMethod(instance, currentClazz, methodName, signatures, parameters, false);
- }
- catch (NoSuchMethodException nsme) {
- // ignore
- }
- currentClazz = currentClazz.getSuperclass();
- }
- throw new NoSuchMethodException(methodName);
- }
-
- /**
- * Invoke a method on an instance.
- *
- * @param object the instance to invoke the method on
- * @param clazz the class of the instance
- * @param name the name of the method
- * @param signatures the signatures to look for in order
- * @param parameters the parameter values for the signatures
- * @param isSuper <code>true</code> if this is a superclass and we should therefore not look for private methods
- * @return whatever the method returns
- * @throws NoSuchMethodException when no method could be found
- * @throws IllegalArgumentException when illegal values for this methods arguments are supplied
- * @throws IllegalAccessException when the method cannot be accessed
- * @throws InvocationTargetException when the method that was invoked throws an exception
- */
- public static Object invokeMethod(Object object, Class clazz, String name, Class[][] signatures, Object[][] parameters, boolean isSuper) throws NoSuchMethodException, InvocationTargetException, IllegalArgumentException, IllegalAccessException {
- if (object == null) {
- throw new IllegalArgumentException("Instance cannot be null");
- }
- if (clazz == null) {
- throw new IllegalArgumentException("Class cannot be null");
- }
-
- // if we're talking to a proxy here, dig one level deeper to expose the
- // underlying invocation handler (we do the same for injecting instances)
- if (Proxy.isProxyClass(clazz)) {
- object = Proxy.getInvocationHandler(object);
- clazz = object.getClass();
- }
-
- Method m = null;
- for (int i = 0; i < signatures.length; i++) {
- Class[] signature = signatures[i];
- m = getDeclaredMethod(clazz, name, signature, isSuper);
- if (m != null) {
- return m.invoke(object, parameters[i]);
- }
- }
- throw new NoSuchMethodException(name);
- }
-
- private static Method getDeclaredMethod(Class clazz, String name, Class[] signature, boolean isSuper) {
- // first check our cache
- Key key = new Key(clazz, name, signature);
- Method m = null;
- synchronized (m_methodCache) {
- m = (Method) m_methodCache.get(key);
- if (m != null) {
- return m;
- }
- else if (m_methodCache.containsKey(key)) {
- // the key is in our cache, it just happens to have a null value
- return null;
- }
- }
- // then do a lookup
- try {
- m = clazz.getDeclaredMethod(name, signature);
- if (!(isSuper && Modifier.isPrivate(m.getModifiers()))) {
- m.setAccessible(true);
- }
- }
- catch (NoSuchMethodException e) {
- // ignore
- }
- synchronized (m_methodCache) {
- m_methodCache.put(key, m);
- }
- return m;
- }
-
- public static class Key {
- private final Class m_clazz;
- private final String m_name;
- private final Class[] m_signature;
-
- public Key(Class clazz, String name, Class[] signature) {
- m_clazz = clazz;
- m_name = name;
- m_signature = signature;
- }
-
- public int hashCode() {
- final int prime = 31;
- int result = 1;
- result = prime * result + ((m_clazz == null) ? 0 : m_clazz.hashCode());
- result = prime * result + ((m_name == null) ? 0 : m_name.hashCode());
- result = prime * result + Arrays.hashCode(m_signature);
- return result;
- }
-
- public boolean equals(Object obj) {
- if (this == obj)
- return true;
- if (obj == null)
- return false;
- if (getClass() != obj.getClass())
- return false;
- Key other = (Key) obj;
- if (m_clazz == null) {
- if (other.m_clazz != null)
- return false;
- }
- else if (!m_clazz.equals(other.m_clazz))
- return false;
- if (m_name == null) {
- if (other.m_name != null)
- return false;
- }
- else if (!m_name.equals(other.m_name))
- return false;
- if (!Arrays.equals(m_signature, other.m_signature))
- return false;
- return true;
- }
- }
-
- public static class LRUMap extends LinkedHashMap {
- private final int m_size;
-
- public LRUMap(int size) {
- m_size = size;
- }
-
- protected boolean removeEldestEntry(java.util.Map.Entry eldest) {
- return size() > m_size;
- }
- }
-}
diff --git a/dependencymanager/core/src/main/java/org/apache/felix/dm/PropertyMetaData.java b/dependencymanager/core/src/main/java/org/apache/felix/dm/PropertyMetaData.java
deleted file mode 100644
index 902f293..0000000
--- a/dependencymanager/core/src/main/java/org/apache/felix/dm/PropertyMetaData.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.felix.dm;
-
-/**
- * This interface defines meta data regarding a given configuration property.
- *
- * @author <a href="mailto:dev@felix.apache.org">Felix Project Team</a>
- */
-public interface PropertyMetaData {
- /**
- * The label used to display the property. Example: "Log Level".
- *
- * @return The label used to display the property (may be localized)
- */
- public PropertyMetaData setHeading(String heading);
-
- /**
- * The key of a ConfigurationAdmin property. Example: "printer.logLevel"
- *
- * @return The Configuration Admin property name
- */
- public PropertyMetaData setId(String id);
-
- /**
- * Returns the property primitive type. If must be either one of the following types:<p>
- * <ul>
- * <li>String.class</li>
- * <li>Long.class</li>
- * <li>Integer.class</li>
- * <li>Character.class</li>
- * <li>Byte.class</li>
- * <li>Double.class</li>
- * <li>Float.class</li>
- * <li>Boolean.class</li>
- * </ul>
- */
- public PropertyMetaData setType(Class type);
-
- /**
- * Returns a default for this property. The object must be of the appropriate type as defined by the cardinality and getType().
- * The return type is a list of String objects that can be converted to the appropriate type. The cardinality of the return
- * array must follow the absolute cardinality of this type. E.g. if the cardinality = 0, the array must contain 1 element.
- * If the cardinality is 1, it must contain 0 or 1 elements. If it is -5, it must contain from 0 to max 5 elements. Note that
- * the special case of a 0 cardinality, meaning a single value, does not allow arrays or vectors of 0 elements.
- */
- public PropertyMetaData setDefaults(String[] defaults);
-
- /**
- * Returns the property description. The description may be localized and must describe the semantics of this type and any
- * constraints. Example: "Select the log level for the Printer Service".
- *
- * @return a localizable description of the property.
- */
- public PropertyMetaData setDescription(String description);
-
- /**
- * Return the cardinality of this property. The OSGi environment handles multi valued properties in arrays ([]) or in Vector objects.
- * The return value is defined as follows:<p>
- *
- * <ul>
- * <li> x = Integer.MIN_VALUE no limit, but use Vector</li>
- * <li> x < 0 -x = max occurrences, store in Vector</li>
- * <li> x > 0 x = max occurrences, store in array []</li>
- * <li> x = Integer.MAX_VALUE no limit, but use array []</li>
- * <li> x = 0 1 occurrence required</li>
- * </ul>
- */
- public PropertyMetaData setCardinality(int cardinality);
-
- /**
- * Tells if this property is required or not.
- */
- public PropertyMetaData setRequired(boolean required);
-
- /**
- * Return a list of valid options for this property (the labels may be localized).
- *
- * @return the list of valid options for this property.
- */
- public PropertyMetaData addOption(String optionLabel, String optionValue);
-}
\ No newline at end of file
diff --git a/dependencymanager/core/src/main/java/org/apache/felix/dm/ResourceDependency.java b/dependencymanager/core/src/main/java/org/apache/felix/dm/ResourceDependency.java
deleted file mode 100644
index b837262..0000000
--- a/dependencymanager/core/src/main/java/org/apache/felix/dm/ResourceDependency.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.felix.dm;
-
-import java.net.URL;
-
-/**
- * A resource dependency is a dependency on a resource. A resource in this context is an object that is
- * identified by a URL. Resources should somehow be provided by an external component, the resource
- * provider. These dependencies then react on them becoming available or not. Use cases for such dependencies
- * are resources that are embedded in bundles, in a workspace or some remote or local repository, etc.
- *
- * @author <a href="mailto:dev@felix.apache.org">Felix Project Team</a>
- */
-public interface ResourceDependency extends Dependency, ComponentDependencyDeclaration, ResourceHandler {
- /**
- * Sets the callbacks for this service. These callbacks can be used as hooks whenever a
- * dependency is added or removed. When you specify callbacks, the auto configuration
- * feature is automatically turned off, because we're assuming you don't need it in this
- * case.
- *
- * @param added the method to call when a service was added
- * @param removed the method to call when a service was removed
- * @return this service dependency
- */
- public ResourceDependency setCallbacks(String added, String removed);
-
- /**
- * Sets the callbacks for this service. These callbacks can be used as hooks whenever a
- * dependency is added, changed or removed. When you specify callbacks, the auto
- * configuration feature is automatically turned off, because we're assuming you don't
- * need it in this case.
- *
- * @param added the method to call when a service was added
- * @param changed the method to call when a service was changed
- * @param removed the method to call when a service was removed
- * @return this service dependency
- */
- public ResourceDependency setCallbacks(String added, String changed, String removed);
-
- /**
- * Sets the callbacks for this service. These callbacks can be used as hooks whenever a
- * dependency is added or removed. They are called on the instance you provide. When you
- * specify callbacks, the auto configuration feature is automatically turned off, because
- * we're assuming you don't need it in this case.
- *
- * @param instance the instance to call the callbacks on
- * @param added the method to call when a service was added
- * @param removed the method to call when a service was removed
- * @return this service dependency
- */
- public ResourceDependency setCallbacks(Object instance, String added, String removed);
-
- /**
- * Sets the callbacks for this service. These callbacks can be used as hooks whenever a
- * dependency is added, changed or removed. They are called on the instance you provide. When you
- * specify callbacks, the auto configuration feature is automatically turned off, because
- * we're assuming you don't need it in this case.
- *
- * @param instance the instance to call the callbacks on
- * @param added the method to call when a service was added
- * @param changed the method to call when a service was changed
- * @param removed the method to call when a service was removed
- * @return this service dependency
- */
- public ResourceDependency setCallbacks(Object instance, String added, String changed, String removed);
-
- /**
- * Sets auto configuration for this service. Auto configuration allows the
- * dependency to fill in any attributes in the service implementation that
- * are of the same type as this dependency. Default is on.
- *
- * @param autoConfig the value of auto config
- * @return this service dependency
- */
- public ResourceDependency setAutoConfig(boolean autoConfig);
-
- /**
- * Sets auto configuration for this service. Auto configuration allows the
- * dependency to fill in the attribute in the service implementation that
- * has the same type and instance name.
- *
- * @param instanceName the name of attribute to auto config
- * @return this service dependency
- */
- public ResourceDependency setAutoConfig(String instanceName);
-
- /**
- * Sets the resource for this dependency.
- *
- * @param resource the URL of the resource
- */
- public ResourceDependency setResource(URL resource);
-
- /**
- * Determines if this is a required dependency or not.
- *
- * @param required <code>true</code> if the dependency is required
- */
- public ResourceDependency setRequired(boolean required);
-
- /**
- * Sets the filter condition for this resource dependency.
- *
- * @param resourceFilter the filter condition
- */
- public ResourceDependency setFilter(String resourceFilter);
-
- /** @see ResourceDependency#setPropagate(Object, String) */
- public ResourceDependency setPropagate(boolean propagate);
-
- /**
- * Sets an Object instance and a callback method used to propagate some properties to the provided service properties.
- * The method will be invoked on the specified object instance and must have one of the following signatures:<p>
- * <ul><li>Dictionary callback(ServiceReference, Object service)
- * <li>Dictionary callback(ServiceReference)
- * </ul>
- * @param instance the Object instance which is used to retrieve propagated service properties
- * @param method the method to invoke for retrieving the properties to be propagated to the service properties.
- * @return this service dependency.
- */
- public ResourceDependency setPropagate(Object instance, String method);
-
- /**
- * Sets this dependency to be instance bound or not.
- *
- * @param isInstanceBound <code>true</code> if this dependency should be instance bound
- */
- public ResourceDependency setInstanceBound(boolean isInstanceBound);
-}
diff --git a/dependencymanager/core/src/main/java/org/apache/felix/dm/ResourceHandler.java b/dependencymanager/core/src/main/java/org/apache/felix/dm/ResourceHandler.java
deleted file mode 100644
index 2414027..0000000
--- a/dependencymanager/core/src/main/java/org/apache/felix/dm/ResourceHandler.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.felix.dm;
-
-import java.net.URL;
-import java.util.Dictionary;
-
-/**
- * Service interface for anybody wanting to be notified of changes to resources.
- *
- * @author <a href="mailto:dev@felix.apache.org">Felix Project Team</a>
- */
-public interface ResourceHandler {
- /** Name of the property that's used to describe the filter condition for a resource. */
- public static final String FILTER = "filter";
- /** Exact URL that this handler is looking for. Can be used instead of a filter to be very explicit about the resource you're looking for. */
- public static final String URL = "url";
- /** The host part of the URL. */
- public static final String HOST = "host";
- /** The path part of the URL. */
- public static final String PATH = "path";
- /** The protocol part of the URL. */
- public static final String PROTOCOL = "protocol";
- /** The port part of the URL. */
- public static final String PORT = "port";
-
- /**
- * @deprecated Please use {@link #added(URL, Dictionary)} instead. When both are specified,
- * the new method takes precedence and the deprecated one is not invoked.
- */
- public void added(URL resource);
-
- /**
- * Invoked whenever a new resource is added.
- */
- public void added(URL resource, Dictionary resourceProperties);
-
- /**
- * @deprecated Please use {@link #changed(URL, Dictionary)} instead. When both are specified,
- * the new method takes precedence and the deprecated one is not invoked.
- */
- public void changed(URL resource);
-
- /**
- * Invoked whenever an existing resource changes.
- */
- public void changed(URL resource, Dictionary resourceProperties);
-
- /**
- * @deprecated Please use {@link #removed(URL, Dictionary)} instead. When both are specified,
- * the new method takes precedence and the deprecated one is not invoked.
- */
- public void removed(URL resource);
-
- /**
- * Invoked whenever an existing resource is removed.
- */
- public void removed(URL resource, Dictionary resourceProperties);
-}
diff --git a/dependencymanager/core/src/main/java/org/apache/felix/dm/ResourceUtil.java b/dependencymanager/core/src/main/java/org/apache/felix/dm/ResourceUtil.java
deleted file mode 100644
index 88d9c88..0000000
--- a/dependencymanager/core/src/main/java/org/apache/felix/dm/ResourceUtil.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.felix.dm;
-
-import java.net.URL;
-import java.util.Dictionary;
-import java.util.Properties;
-
-/**
- * Utility class for resource handling.
- *
- * @author <a href="mailto:dev@felix.apache.org">Felix Project Team</a>
- */
-public class ResourceUtil {
- /**
- * Creates a set of properties for a resource based on its URL.
- *
- * @param url the URL
- * @return a set of properties
- */
- public static Dictionary createProperties(URL url) {
- Properties props = new Properties();
- props.setProperty(ResourceHandler.PROTOCOL, url.getProtocol());
- props.setProperty(ResourceHandler.HOST, url.getHost());
- props.setProperty(ResourceHandler.PORT, Integer.toString(url.getPort()));
- props.setProperty(ResourceHandler.PATH, url.getPath());
- return props;
- }
-}
diff --git a/dependencymanager/core/src/main/java/org/apache/felix/dm/ServiceDependency.java b/dependencymanager/core/src/main/java/org/apache/felix/dm/ServiceDependency.java
deleted file mode 100644
index dde8953..0000000
--- a/dependencymanager/core/src/main/java/org/apache/felix/dm/ServiceDependency.java
+++ /dev/null
@@ -1,224 +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.felix.dm;
-
-import org.osgi.framework.ServiceReference;
-
-/**
- * Service dependency that can track an OSGi service.
- *
- * @author <a href="mailto:dev@felix.apache.org">Felix Project Team</a>
- */
-public interface ServiceDependency extends Dependency, ComponentDependencyDeclaration {
- /**
- * Sets the name of the service that should be tracked.
- *
- * @param serviceName the name of the service
- * @return this service dependency
- */
- public ServiceDependency setService(Class serviceName);
-
- /**
- * Sets the name of the service that should be tracked. You can either specify
- * only the name, or the name and a filter. In the latter case, the filter is used
- * to track the service and should only return services of the type that was specified
- * in the name. To make sure of this, the filter is actually extended internally to
- * filter on the correct name.
- *
- * @param serviceName the name of the service
- * @param serviceFilter the filter condition
- * @return this service dependency
- */
- public ServiceDependency setService(Class serviceName, String serviceFilter);
-
- /**
- * Sets the filter for the services that should be tracked. Any service object
- * matching the filter will be returned, without any additional filter on the
- * class.
- *
- * @param serviceFilter the filter condition
- * @return this service dependency
- */
- public ServiceDependency setService(String serviceFilter);
-
- /**
- * Sets the name of the service that should be tracked. You can either specify
- * only the name, or the name and a reference. In the latter case, the service reference
- * is used to track the service and should only return services of the type that was
- * specified in the name.
- *
- * @param serviceName the name of the service
- * @param serviceReference the service reference to track
- * @return this service dependency
- */
- public ServiceDependency setService(Class serviceName, ServiceReference serviceReference);
-
- /**
- * Sets the default implementation for this service dependency. You can use this to supply
- * your own implementation that will be used instead of a Null Object when the dependency is
- * not available. This is also convenient if the service dependency is not an interface
- * (which would cause the Null Object creation to fail) but a class.
- *
- * @param implementation the instance to use or the class to instantiate if you want to lazily
- * instantiate this implementation
- * @return this service dependency
- */
- public ServiceDependency setDefaultImplementation(Object implementation);
-
- /**
- * Sets the required flag which determines if this service is required or not.
- *
- * @param required the required flag
- * @return this service dependency
- */
- public ServiceDependency setRequired(boolean required);
-
- /**
- * Sets auto configuration for this service. Auto configuration allows the
- * dependency to fill in any attributes in the service implementation that
- * are of the same type as this dependency. Default is on.
- *
- * @param autoConfig the value of auto config
- * @return this service dependency
- */
- public ServiceDependency setAutoConfig(boolean autoConfig);
-
- /**
- * Sets auto configuration for this service. Auto configuration allows the
- * dependency to fill in the attribute in the service implementation that
- * has the same type and instance name.
- *
- * @param instanceName the name of attribute to auto config
- * @return this service dependency
- */
- public ServiceDependency setAutoConfig(String instanceName);
-
- /**
- * Sets the callbacks for this service. These callbacks can be used as hooks whenever a
- * dependency is added or removed. When you specify callbacks, the auto configuration
- * feature is automatically turned off, because we're assuming you don't need it in this
- * case.
- *
- * @param added the method to call when a service was added
- * @param removed the method to call when a service was removed
- * @return this service dependency
- */
- public ServiceDependency setCallbacks(String added, String removed);
-
- /**
- * Sets the callbacks for this service. These callbacks can be used as hooks whenever a
- * dependency is added, changed or removed. When you specify callbacks, the auto
- * configuration feature is automatically turned off, because we're assuming you don't
- * need it in this case.
- *
- * @param added the method to call when a service was added
- * @param changed the method to call when a service was changed
- * @param removed the method to call when a service was removed
- * @return this service dependency
- */
- public ServiceDependency setCallbacks(String added, String changed, String removed);
-
- /**
- * Sets the callbacks for this service. These callbacks can be used as hooks whenever a
- * dependency is added, changed or removed. When you specify callbacks, the auto
- * configuration feature is automatically turned off, because we're assuming you don't
- * need it in this case.
- * @param added the method to call when a service was added
- * @param changed the method to call when a service was changed
- * @param removed the method to call when a service was removed
- * @param swapped the method to call when the service was swapped due to addition or
- * removal of an aspect
- * @return this service dependency
- */
- public ServiceDependency setCallbacks(String added, String changed, String removed, String swapped);
-
- /**
- * Sets the callbacks for this service. These callbacks can be used as hooks whenever a
- * dependency is added or removed. They are called on the instance you provide. When you
- * specify callbacks, the auto configuration feature is automatically turned off, because
- * we're assuming you don't need it in this case.
- *
- * @param instance the instance to call the callbacks on
- * @param added the method to call when a service was added
- * @param removed the method to call when a service was removed
- * @return this service dependency
- */
- public ServiceDependency setCallbacks(Object instance, String added, String removed);
-
- /**
- * Sets the callbacks for this service. These callbacks can be used as hooks whenever a
- * dependency is added, changed or removed. They are called on the instance you provide. When you
- * specify callbacks, the auto configuration feature is automatically turned off, because
- * we're assuming you don't need it in this case.
- *
- * @param instance the instance to call the callbacks on
- * @param added the method to call when a service was added
- * @param changed the method to call when a service was changed
- * @param removed the method to call when a service was removed
- * @return this service dependency
- */
- public ServiceDependency setCallbacks(Object instance, String added, String changed, String removed);
-
- /**
- * Sets the callbacks for this service. These callbacks can be used as hooks whenever a
- * dependency is added, changed or removed. When you specify callbacks, the auto
- * configuration feature is automatically turned off, because we're assuming you don't
- * need it in this case.
- * @param instance the instance to call the callbacks on
- * @param added the method to call when a service was added
- * @param changed the method to call when a service was changed
- * @param removed the method to call when a service was removed
- * @param swapped the method to call when the service was swapped due to addition or
- * removal of an aspect
- * @return this service dependency
- */
- public ServiceDependency setCallbacks(Object instance, String added, String changed, String removed, String swapped);
-
- /**
- * Sets propagation of the service dependency properties to the provided service properties. Any additional
- * service properties specified directly are merged with these.
- */
- public ServiceDependency setPropagate(boolean propagate);
-
- /**
- * Sets an Object instance and a callback method used to propagate some properties to the provided service properties.
- * The method will be invoked on the specified object instance and must have one of the following signatures:<p>
- * <ul><li>Dictionary callback(ServiceReference, Object service)
- * <li>Dictionary callback(ServiceReference)
- * </ul>
- * @param instance the Object instance which is used to retrieve propagated service properties
- * @param method the method to invoke for retrieving the properties to be propagated to the service properties.
- * @return this service dependency.
- */
- public ServiceDependency setPropagate(Object instance, String method);
-
- /**
- * Sets this dependency to be instance bound or not.
- *
- * @param isInstanceBound <code>true</code> if this dependency should be instance bound
- */
- public ServiceDependency setInstanceBound(boolean isInstanceBound);
-
- /**
- * Enabled debug logging for this dependency instance. The logging is prefixed with the given identifier.
- * @param identifier
- * @return this service dependency.
- */
- public ServiceDependency setDebug(String identifier);
-}
diff --git a/dependencymanager/core/src/main/java/org/apache/felix/dm/ServiceUtil.java b/dependencymanager/core/src/main/java/org/apache/felix/dm/ServiceUtil.java
deleted file mode 100644
index f257bfe..0000000
--- a/dependencymanager/core/src/main/java/org/apache/felix/dm/ServiceUtil.java
+++ /dev/null
@@ -1,175 +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.felix.dm;
-
-import java.util.List;
-
-import org.osgi.framework.Bundle;
-import org.osgi.framework.Constants;
-import org.osgi.framework.ServiceReference;
-
-/**
- * OSGi service utilities.
- *
- * @author <a href="mailto:dev@felix.apache.org">Felix Project Team</a>
- */
-public class ServiceUtil {
- /**
- * Returns the service ranking of a service, based on its service reference. If
- * the service has a property specifying its ranking, that will be returned. If
- * not, the default ranking of zero will be returned.
- *
- * @param ref the service reference to determine the ranking for
- * @return the ranking
- */
- public static int getRanking(ServiceReference ref) {
- return getRankingAsInteger(ref).intValue();
- }
-
- /**
- * Returns the service ranking of a service, based on its service reference. If
- * the service has a property specifying its ranking, that will be returned. If
- * not, the default ranking of zero will be returned.
- *
- * @param ref the service reference to determine the ranking for
- * @return the ranking
- */
- public static Integer getRankingAsInteger(ServiceReference ref) {
- Integer rank = (Integer) ref.getProperty(Constants.SERVICE_RANKING);
- if (rank != null) {
- return rank;
- }
- return new Integer(0);
- }
-
- /**
- * Returns the service ID of a service, based on its service reference. This
- * method is aware of service aspects as defined by the dependency manager and
- * will return the ID of the orginal service if you give it an aspect.
- *
- * @param ref the service reference to determine the service ID of
- * @return the service ID
- */
- public static long getServiceId(ServiceReference ref) {
- return getServiceIdAsLong(ref).longValue();
- }
-
- /**
- * Returns the service ID of a service, based on its service reference. This
- * method is aware of service aspects as defined by the dependency manager and
- * will return the ID of the orginal service if you give it an aspect.
- *
- * @param ref the service reference to determine the service ID of
- * @return the service ID
- */
- public static Long getServiceIdAsLong(ServiceReference ref) {
- return getServiceIdObject(ref);
- }
-
- public static Long getServiceIdObject(ServiceReference ref) {
- Long aid = (Long) ref.getProperty(DependencyManager.ASPECT);
- if (aid != null) {
- return aid;
- }
- Long sid = (Long) ref.getProperty(Constants.SERVICE_ID);
- if (sid != null) {
- return sid;
- }
- throw new IllegalArgumentException("Invalid service reference, no service ID found");
- }
-
- /**
- * Determines if the service is an aspect as defined by the dependency manager.
- * Aspects are defined by a property and this method will check for its presence.
- *
- * @param ref the service reference
- * @return <code>true</code> if it's an aspect, <code>false</code> otherwise
- */
- public static boolean isAspect(ServiceReference ref) {
- Long aid = (Long) ref.getProperty(DependencyManager.ASPECT);
- return (aid != null);
- }
-
- /**
- * Converts a service reference to a string, listing both the bundle it was
- * registered from and all properties.
- *
- * @param ref the service reference
- * @return a string representation of the service
- */
- public static String toString(ServiceReference ref) {
- if (ref == null) {
- return "ServiceReference[null]";
- }
- else {
- StringBuffer buf = new StringBuffer();
- Bundle bundle = ref.getBundle();
- if (bundle != null) {
- buf.append("ServiceReference[");
- buf.append(bundle.getBundleId());
- buf.append("]{");
- }
- else {
- buf.append("ServiceReference[unregistered]{");
- }
- buf.append(propertiesToString(ref, null));
- buf.append("}");
- return buf.toString();
- }
- }
-
- /**
- * Converts the properties of a service reference to a string.
- *
- * @param ref the service reference
- * @param exclude a list of properties to exclude, or <code>null</code> to show everything
- * @return a string representation of the service properties
- */
- public static String propertiesToString(ServiceReference ref, List /* <String> */ exclude) {
- StringBuffer buf = new StringBuffer();
- String[] keys = ref.getPropertyKeys();
- for (int i = 0; i < keys.length; i++) {
- if (i > 0) {
- buf.append(',');
- }
- buf.append(keys[i]);
- buf.append('=');
- Object val = ref.getProperty(keys[i]);
- if (exclude == null || !exclude.contains(val)) {
- if (val instanceof String[]) {
- String[] valArray = (String[]) val;
- StringBuffer valBuf = new StringBuffer();
- valBuf.append('{');
- for (int j = 0; j < valArray.length; j++) {
- if (valBuf.length() > 1) {
- valBuf.append(',');
- }
- valBuf.append(valArray[j].toString());
- }
- valBuf.append('}');
- buf.append(valBuf);
- }
- else {
- buf.append(val.toString());
- }
- }
- }
- return buf.toString();
- }
-}
diff --git a/dependencymanager/core/src/main/java/org/apache/felix/dm/TemporalServiceDependency.java b/dependencymanager/core/src/main/java/org/apache/felix/dm/TemporalServiceDependency.java
deleted file mode 100644
index 0e0310f..0000000
--- a/dependencymanager/core/src/main/java/org/apache/felix/dm/TemporalServiceDependency.java
+++ /dev/null
@@ -1,74 +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.felix.dm;
-
-/**
- * A Temporal Service dependency that can block the caller thread between service updates. Only useful for required stateless
- * dependencies that can be replaced transparently. A Dynamic Proxy is used to wrap the actual service dependency. When the
- * dependency goes away, an attempt is made to replace it with another one which satisfies the service dependency criteria. If
- * no service replacement is available, then any method invocation (through the dynamic proxy) will block during a configurable
- * timeout. On timeout, an unchecked <code>IllegalStateException</code> exception is raised (but the service is not
- * deactivated).
- * <p>
- * <b>This class only supports required dependencies, and temporal dependencies must be accessed outside the Activator (OSGi)
- * thread, because method invocations may block the caller thread when dependencies are not satisfied. </b>
- * <p>
- * Sample Code:
- * <p>
- * <blockquote>
- *
- * <pre>
- * import org.apache.felix.dependencymanager.*;
- *
- * public class Activator extends DependencyActivatorBase {
- * public void init(BundleContext ctx, DependencyManager dm) throws Exception {
- * dm.add(createService()
- * .setImplementation(MyServer.class)
- * .add(createTemporalServiceDependency()
- * .setTimeout(15000)
- * .setService(MyDependency.class)));
- * }
- *
- * public void destroy(BundleContext ctx, DependencyManager dm) throws Exception {
- * }
- * }
- *
- * class MyServer implements Runnable {
- * MyDependency _dependency; // Auto-Injected by reflection.
- * void start() {
- * (new Thread(this)).start();
- * }
- *
- * public void run() {
- * try {
- * _dependency.doWork();
- * } catch (IllegalStateException e) {
- * t.printStackTrace();
- * }
- * }
- * </pre>
- *
- * </blockquote>
- *
- * @author <a href="mailto:dev@felix.apache.org">Felix Project Team</a>
- */
-public interface TemporalServiceDependency extends ServiceDependency {
- /**
- * Sets the timeout for this temporal dependency. Specifying a timeout value of zero means that there is no timeout period,
- * and an invocation on a missing service will fail immediately.
- *
- * @param timeout the dependency timeout value greater or equals to 0
- * @throws IllegalArgumentException if the timeout is negative
- * @return this temporal dependency
- */
- TemporalServiceDependency setTimeout(long timeout);
-}
diff --git a/dependencymanager/core/src/main/java/org/apache/felix/dm/impl/AbstractDecorator.java b/dependencymanager/core/src/main/java/org/apache/felix/dm/impl/AbstractDecorator.java
deleted file mode 100644
index 794ecef..0000000
--- a/dependencymanager/core/src/main/java/org/apache/felix/dm/impl/AbstractDecorator.java
+++ /dev/null
@@ -1,284 +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.felix.dm.impl;
-
-import java.net.URL;
-import java.util.Dictionary;
-import java.util.HashMap;
-import java.util.List;
-import java.util.Map;
-
-import org.apache.felix.dm.Component;
-import org.apache.felix.dm.ComponentStateListener;
-import org.apache.felix.dm.Dependency;
-import org.apache.felix.dm.DependencyManager;
-import org.osgi.framework.Bundle;
-import org.osgi.framework.BundleContext;
-import org.osgi.framework.ServiceReference;
-import org.osgi.framework.ServiceRegistration;
-import org.osgi.service.cm.ConfigurationException;
-
-/**
- * @author <a href="mailto:dev@felix.apache.org">Felix Project Team</a>
- */
-public abstract class AbstractDecorator {
- protected volatile DependencyManager m_manager;
- private final Map m_services = new HashMap();
-
- public abstract Component createService(Object[] properties);
-
- /**
- * Catches our DependencyManager handle from our component init method.
- */
- public void init(Component c) {
- m_manager = c.getDependencyManager();
- }
-
- /**
- * Extra method, which may be used by sub-classes, when adaptee has changed.
- * For now, it's only used by the FactoryConfigurationAdapterImpl class,
- * but it might also make sense to use this for Resource Adapters ...
- */
- public void updateService(Object[] properties) {
- throw new NoSuchMethodError("Method updateService not implemented");
- }
-
- /**
- * Set some service properties to all already instantiated services.
- */
- public void setServiceProperties(Dictionary serviceProperties) {
- Object[] components;
- synchronized (m_services) {
- components = m_services.values().toArray();
- }
- for (int i = 0; i < components.length; i++) {
- ((Component) components[i]).setServiceProperties(serviceProperties);
- }
- }
-
- /**
- * Remove a StateListener from all already instantiated services.
- */
- public void addStateListener(ComponentStateListener listener) {
- Object[] components;
- synchronized (m_services) {
- components = m_services.values().toArray();
- }
- for (int i = 0; i < components.length; i++) {
- ((Component) components[i]).addStateListener(listener);
- }
- }
-
- /**
- * Remove a StateListener from all already instantiated services.
- */
- public void removeStateListener(ComponentStateListener listener) {
- Object[] components;
- synchronized (m_services) {
- components = m_services.values().toArray();
- }
- for (int i = 0; i < components.length; i++) {
- ((Component) components[i]).removeStateListener(listener);
- }
- }
-
- /**
- * Add a Dependency to all already instantiated services.
- */
- public void addDependency(Dependency d) {
- Object[] components;
- synchronized (m_services) {
- components = m_services.values().toArray();
- }
- for (int i = 0; i < components.length; i++) {
- ((Component) components[i]).add(d);
- }
- }
-
- /**
- * Add a Dependency to all already instantiated services.
- */
- public void addDependencies(List dependencies) {
- Object[] components;
- synchronized (m_services) {
- components = m_services.values().toArray();
- }
- for (int i = 0; i < components.length; i++) {
- ((Component) components[i]).add(dependencies);
- }
- }
-
- /**
- * Remove a Dependency from all instantiated services.
- */
- public void removeDependency(Dependency d) {
- Object[] components;
- synchronized (m_services) {
- components = m_services.values().toArray();
- }
- for (int i = 0; i < components.length; i++) {
- ((Component) components[i]).remove(d);
- }
- }
-
- // callbacks for FactoryConfigurationAdapterImpl
- public void updated(String pid, Dictionary properties) throws ConfigurationException {
- try {
- Component service;
- synchronized (m_services) {
- service = (Component) m_services.get(pid);
- }
- if (service == null) {
- service = createService(new Object[] { properties });
- synchronized (m_services) {
- m_services.put(pid, service);
- }
- m_manager.add(service);
- }
- else {
- updateService(new Object[] { properties, service });
- }
- }
- catch (Throwable t) {
- if (t instanceof ConfigurationException) {
- throw (ConfigurationException) t;
- }
- else if (t.getCause() instanceof ConfigurationException) {
- throw (ConfigurationException) t.getCause();
- }
- else {
- throw new ConfigurationException(null, "Could not create service for ManagedServiceFactory Pid " + pid, t);
- }
- }
- }
-
- public void deleted(String pid) {
- Component service = null;
- synchronized (m_services) {
- service = (Component) m_services.remove(pid);
- }
- if (service != null) {
- m_manager.remove(service);
- }
- }
-
- // callbacks for resources
- public void added(URL resource) {
- Component newService = createService(new Object[] { resource });
- synchronized (m_services) {
- m_services.put(resource, newService);
- }
- m_manager.add(newService);
- }
-
- public void removed(URL resource) {
- Component newService;
- synchronized (m_services) {
- newService = (Component) m_services.remove(resource);
- }
- if (newService == null) {
- throw new IllegalStateException("Service should not be null here.");
- }
- m_manager.remove(newService);
- }
-
- // callbacks for services
- public void added(ServiceReference ref, Object service) {
- Component newService = createService(new Object[] { ref, service });
- synchronized (m_services) {
- m_services.put(ref, newService);
- }
- m_manager.add(newService);
- }
-
- public void removed(ServiceReference ref, Object service) {
- Component newService;
- synchronized (m_services) {
- newService = (Component) m_services.remove(ref);
- }
- if (newService == null) {
- throw new IllegalStateException("Service should not be null here.");
- }
- m_manager.remove(newService);
- }
-
- public void swapped(ServiceReference oldRef, Object oldService, ServiceReference newRef, Object newService) {
- synchronized (m_services) {
- Component service = (Component) m_services.remove(oldRef);
- if (service == null) {
- throw new IllegalStateException("Service should not be null here.");
- }
- m_services.put(newRef, service);
- }
- }
-
- // callbacks for bundles
- public void added(Bundle bundle) {
- Component newService = createService(new Object[] { bundle });
- synchronized (m_services) {
- m_services.put(bundle, newService);
- }
- m_manager.add(newService);
- }
-
- public void removed(Bundle bundle) {
- Component newService;
- synchronized (m_services) {
- newService = (Component) m_services.remove(bundle);
- }
- if (newService == null) {
- throw new IllegalStateException("Service should not be null here.");
- }
- m_manager.remove(newService);
- }
-
- public void stop() {
- Object[] components;
- synchronized (m_services) {
- components = m_services.values().toArray();
- m_services.clear();
- }
- for (int i = 0; i < components.length; i++) {
- m_manager.remove((Component) components[i]);
- }
- }
-
- public void configureAutoConfigState(Component target, Component source) {
- configureAutoConfigState(target, source, BundleContext.class);
- configureAutoConfigState(target, source, ServiceRegistration.class);
- configureAutoConfigState(target, source, DependencyManager.class);
- configureAutoConfigState(target, source, Component.class);
- }
-
- public Map getServices() {
- synchronized (m_services) {
- return new HashMap(m_services);
- }
- }
-
- private void configureAutoConfigState(Component target, Component source, Class clazz) {
- String name = source.getAutoConfigInstance(clazz);
- if (name != null) {
- target.setAutoConfig(clazz, name);
- }
- else {
- target.setAutoConfig(clazz, source.getAutoConfig(clazz));
- }
- }
-}
diff --git a/dependencymanager/core/src/main/java/org/apache/felix/dm/impl/AdapterServiceImpl.java b/dependencymanager/core/src/main/java/org/apache/felix/dm/impl/AdapterServiceImpl.java
deleted file mode 100644
index f568598..0000000
--- a/dependencymanager/core/src/main/java/org/apache/felix/dm/impl/AdapterServiceImpl.java
+++ /dev/null
@@ -1,162 +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.felix.dm.impl;
-import java.util.Dictionary;
-import java.util.Enumeration;
-import java.util.Hashtable;
-import java.util.List;
-import java.util.Properties;
-
-import org.apache.felix.dm.Component;
-import org.apache.felix.dm.ComponentStateListener;
-import org.apache.felix.dm.Dependency;
-import org.apache.felix.dm.DependencyManager;
-import org.apache.felix.dm.ServiceDependency;
-import org.osgi.framework.Constants;
-import org.osgi.framework.ServiceReference;
-
-/**
- * Adapter Service implementation. This class extends the FilterService in order to catch
- * some Service methods for configuring actual adapter service implementation.
- *
- * @author <a href="mailto:dev@felix.apache.org">Felix Project Team</a>
- */
-public class AdapterServiceImpl extends FilterService {
- /**
- * Creates a new Adapter Service implementation.
- *
- * @param dm the dependency manager used to create our internal adapter service
- * @param adapteeInterface the service interface to apply the adapter to
- * @param adapteeFilter the filter condition to use with the service interface
- * @param add
- * @param change
- * @param remove
- */
- public AdapterServiceImpl(DependencyManager dm, Class adapteeInterface, String adapteeFilter, String autoConfig, String add, String change, String remove, String swap) {
- super(dm.createComponent()); // This service will be filtered by our super class, allowing us to take control.
- m_component.setImplementation(new AdapterImpl(adapteeInterface, adapteeFilter, autoConfig, add, change, remove, swap))
- .add(dm.createServiceDependency()
- .setService(adapteeInterface, adapteeFilter)
- .setAutoConfig(false)
- .setCallbacks("added", null, "removed", "swapped"))
- .setCallbacks("init", null, "stop", null);
- }
-
- public AdapterServiceImpl(DependencyManager dm, Class adapteeInterface, String adapteeFilter, String autoConfig, String add, String change, String remove) {
- super(dm.createComponent()); // This service will be filtered by our super class, allowing us to take control.
- m_component.setImplementation(new AdapterImpl(adapteeInterface, adapteeFilter, autoConfig, add, change, remove, null))
- .add(dm.createServiceDependency()
- .setService(adapteeInterface, adapteeFilter)
- .setAutoConfig(false)
- .setCallbacks("added", null, "removed", "swapped"))
- .setCallbacks("init", null, "stop", null);
- }
-
- public class AdapterImpl extends AbstractDecorator {
- private final Class m_adapteeInterface;
- private final String m_adapteeFilter;
- private final String m_add;
- private final String m_change;
- private final String m_remove;
- private final String m_swap;
- private final String m_autoConfig;
-
- public AdapterImpl(Class adapteeInterface, String adapteeFilter, String autoConfig, String add, String change, String remove, String swap) {
- m_adapteeInterface = adapteeInterface;
- m_adapteeFilter = adapteeFilter;
- m_autoConfig = autoConfig;
- m_add = add;
- m_change = change;
- m_swap = swap;
- m_remove = remove;
- }
-
- public Component createService(Object[] properties) {
- ServiceReference ref = (ServiceReference) properties[0];
- Object aspect = ref.getProperty(DependencyManager.ASPECT);
- String serviceIdToTrack = (aspect != null) ? aspect.toString() : ref.getProperty(Constants.SERVICE_ID).toString();
- List dependencies = m_component.getDependencies();
- dependencies.remove(0);
- ServiceDependency dependency = m_manager.createServiceDependency()
- // create a dependency on both the service id we're adapting and possible aspects for this given service id
- .setService(m_adapteeInterface, "(|(" + Constants.SERVICE_ID + "=" + serviceIdToTrack
- + ")(" + DependencyManager.ASPECT + "=" + serviceIdToTrack + "))")
- .setRequired(true);
- if (m_autoConfig != null) {
- dependency.setAutoConfig(m_autoConfig);
- }
- if (m_add != null || m_change != null || m_remove != null || m_swap != null) {
- dependency.setCallbacks(m_add, m_change, m_remove, m_swap);
- }
- dependency.setPropagate(this, "propagateAdapteeProperties");
-
-// dependency.setDebug("AdapterDependency#" + m_adapteeInterface.getSimpleName());
-
- Component service = m_manager.createComponent()
- .setInterface(m_serviceInterfaces, getServiceProperties(ref))
- .setImplementation(m_serviceImpl)
- .setFactory(m_factory, m_factoryCreateMethod) // if not set, no effect
- .setComposition(m_compositionInstance, m_compositionMethod) // if not set, no effect
- .setCallbacks(m_callbackObject, m_init, m_start, m_stop, m_destroy) // if not set, no effect
- .add(dependency);
-
- configureAutoConfigState(service, m_component);
-
- for (int i = 0; i < dependencies.size(); i++) {
- service.add(((Dependency) dependencies.get(i)).createCopy());
- }
-
- for (int i = 0; i < m_stateListeners.size(); i ++) {
- service.addStateListener((ComponentStateListener) m_stateListeners.get(i));
- }
- return service;
- }
-
- public String toString() {
- return "Adapter for " + m_adapteeInterface + ((m_adapteeFilter != null) ? " with filter " + m_adapteeFilter : "");
- }
-
- public Dictionary getServiceProperties(ServiceReference ref) {
- Dictionary props = new Hashtable();
- if (m_serviceProperties != null) {
- Enumeration e = m_serviceProperties.keys();
- while (e.hasMoreElements()) {
- Object key = e.nextElement();
- props.put(key, m_serviceProperties.get(key));
- }
- }
- return props;
- }
-
- public Dictionary propagateAdapteeProperties(ServiceReference ref) {
- Dictionary props = new Hashtable();
- String[] keys = ref.getPropertyKeys();
- for (int i = 0; i < keys.length; i++) {
- String key = keys[i];
- if (key.equals(DependencyManager.ASPECT) || key.equals(Constants.SERVICE_ID) || key.equals(Constants.SERVICE_RANKING) || key.equals(Constants.OBJECTCLASS)) {
- // do not copy these either
- }
- else {
- props.put(key, ref.getProperty(key));
- }
- }
- return props;
- }
- }
-}
diff --git a/dependencymanager/core/src/main/java/org/apache/felix/dm/impl/AspectServiceImpl.java b/dependencymanager/core/src/main/java/org/apache/felix/dm/impl/AspectServiceImpl.java
deleted file mode 100644
index 871691b..0000000
--- a/dependencymanager/core/src/main/java/org/apache/felix/dm/impl/AspectServiceImpl.java
+++ /dev/null
@@ -1,253 +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.felix.dm.impl;
-
-import java.util.ArrayList;
-import java.util.Dictionary;
-import java.util.Enumeration;
-import java.util.HashMap;
-import java.util.Iterator;
-import java.util.List;
-import java.util.Map;
-import java.util.Properties;
-import java.util.Set;
-
-import org.apache.felix.dm.Component;
-import org.apache.felix.dm.ComponentStateListener;
-import org.apache.felix.dm.Dependency;
-import org.apache.felix.dm.DependencyManager;
-import org.apache.felix.dm.DependencyService;
-import org.apache.felix.dm.ServiceDependency;
-import org.apache.felix.dm.impl.dependencies.ServiceDependencyImpl;
-import org.osgi.framework.Constants;
-import org.osgi.framework.ServiceReference;
-
-/**
- * Aspect Service implementation. This class extends the FilterService in order to catch
- * some Service methods for configuring actual aspect service implementation.
- *
- * @author <a href="mailto:dev@felix.apache.org">Felix Project Team</a>
- */
-public class AspectServiceImpl extends FilterService {
- private final String m_add;
- private final String m_change;
- private final String m_remove;
- private final String m_swap;
- private final String m_aspectFilter;
- private final int m_ranking; // the aspect ranking
-
- public AspectServiceImpl(DependencyManager dm, Class aspectInterface, String aspectFilter, int ranking, String autoConfig, String add, String change, String remove, String swap)
- {
- super(dm.createComponent()); // This service will be filtered by our super class, allowing us to take control.
- m_ranking = ranking;
- m_add = add;
- m_change = change;
- m_remove = remove;
- m_swap = swap;
- m_aspectFilter = aspectFilter;
- m_component.setImplementation(new AspectImpl(aspectInterface, autoConfig))
- .add(dm.createServiceDependency()
- .setService(aspectInterface, createDependencyFilterForAspect(aspectFilter))
- .setAutoConfig(false)
- .setCallbacks("added", "removed"))
- .setCallbacks("init", null, "stop", null);
- }
-
- private String createDependencyFilterForAspect(String filter) {
- // we only want to match services which are not themselves aspects
- if (filter == null || filter.length() == 0) {
- return "(!(" + DependencyManager.ASPECT + "=*))";
- }
- else {
- return "(&(!(" + DependencyManager.ASPECT + "=*))" + filter + ")";
- }
- }
-
- private Properties getServiceProperties(ServiceReference ref) {
- Properties props = new Properties();
- String[] keys = ref.getPropertyKeys();
- for (int i = 0; i < keys.length; i++) {
- String key = keys[i];
- if (key.equals(Constants.SERVICE_ID) || key.equals(Constants.SERVICE_RANKING) || key.equals(DependencyManager.ASPECT) || key.equals(Constants.OBJECTCLASS)) {
- // do not copy these
- }
- else {
- props.put(key, ref.getProperty(key));
- }
- }
- if (m_serviceProperties != null) {
- Enumeration e = m_serviceProperties.keys();
- while (e.hasMoreElements()) {
- Object key = e.nextElement();
- props.put(key, m_serviceProperties.get(key));
- }
- }
- // finally add our aspect property
- props.put(DependencyManager.ASPECT, ref.getProperty(Constants.SERVICE_ID));
- // and the ranking
- props.put(Constants.SERVICE_RANKING, Integer.valueOf(m_ranking));
- return props;
- }
-
- /**
- * This class is the Aspect Implementation. It will create the actual Aspect Service, and
- * will use the Aspect Service parameters provided by our enclosing class.
- */
- class AspectImpl extends AbstractDecorator {
- private final String m_autoConfig; // the aspect impl field name where to inject decorated service
- private final Class m_aspectInterface; // the service decorated by this aspect
-
- public AspectImpl(Class aspectInterface, String autoConfig) {
- m_aspectInterface = aspectInterface;
- m_autoConfig = autoConfig;
- }
-
- /**
- * Creates an aspect implementation component for a new original service.
- * @param param First entry contains the ref to the original service
- */
- public Component createService(Object[] params) {
- // Get the new original service reference.
- ServiceReference ref = (ServiceReference) params[0];
- List dependencies = m_component.getDependencies();
- // remove our internal dependency, replace it with one that points to the specific service that just was passed in.
- dependencies.remove(0);
- Properties serviceProperties = getServiceProperties(ref);
- String[] serviceInterfaces = getServiceInterfaces();
-
- ServiceDependency aspectDependency = (ServiceDependencyImpl)
- m_manager.createServiceDependency().setService(m_aspectInterface, createAspectFilter(ref)).setRequired(true);
-
-// aspectDependency.setDebug("AspectDependency#" +
-// (m_serviceImpl instanceof Class ? (((Class) m_serviceImpl).getSimpleName()) : m_serviceImpl));
-
- aspectDependency.setCallbacks(new CallbackProxy(aspectDependency, ref),
- m_add != null ? "addAspect" : null,
- "changeAspect", // We have to propagate in case aspect does not have a change callback
- m_remove != null ? "removeAspect" : null,
- m_swap != null ? "swapAspect" : null);
-
- if (m_autoConfig != null) {
- aspectDependency.setAutoConfig(m_autoConfig);
- } else if (m_add == null && m_change == null && m_remove == null && m_swap == null) {
- // Since we have set callbacks, we must reactivate setAutoConfig because user has not specified any callbacks.
- aspectDependency.setAutoConfig(true);
- }
-
- Component service = m_manager.createComponent()
- .setInterface(serviceInterfaces, serviceProperties)
- .setImplementation(m_serviceImpl)
- .setFactory(m_factory, m_factoryCreateMethod) // if not set, no effect
- .setComposition(m_compositionInstance, m_compositionMethod) // if not set, no effect
- .setCallbacks(m_callbackObject, m_init, m_start, m_stop, m_destroy) // if not set, no effect
- .add(aspectDependency);
-
- configureAutoConfigState(service, m_component);
-
- for (int i = 0; i < dependencies.size(); i++) {
- service.add(((Dependency) dependencies.get(i)).createCopy());
- }
-
- for (int i = 0; i < m_stateListeners.size(); i++) {
- service.addStateListener((ComponentStateListener) m_stateListeners.get(i));
- }
- return service;
- }
-
- /**
- * Modify some specific aspect service properties.
- */
- public void setServiceProperties(Dictionary props) {
- Map services = super.getServices();
- Iterator it = services.entrySet().iterator();
- while (it.hasNext()) {
- Map.Entry entry = (Map.Entry) it.next();
- ServiceReference originalServiceRef = (ServiceReference) entry.getKey();
- Component c = (Component) entry.getValue();
- // m_serviceProperties is already set to the new service properties; and the getServiceProperties will
- // merge m_serviceProperties with the original service properties.
- Dictionary newProps = getServiceProperties(originalServiceRef);
- c.setServiceProperties(newProps);
- }
- }
-
- private String[] getServiceInterfaces() {
- List serviceNames = new ArrayList();
- // Of course, we provide the aspect interface.
- serviceNames.add(m_aspectInterface.getName());
- // But also append additional aspect implementation interfaces.
- if (m_serviceInterfaces != null) {
- for (int i = 0; i < m_serviceInterfaces.length; i ++) {
- if (!m_serviceInterfaces[i].equals(m_aspectInterface.getName())) {
- serviceNames.add(m_serviceInterfaces[i]);
- }
- }
- }
- return (String[]) serviceNames.toArray(new String[serviceNames.size()]);
- }
-
- private String createAspectFilter(ServiceReference ref) {
- Long sid = (Long) ref.getProperty(Constants.SERVICE_ID);
- return "(&(|(!(" + Constants.SERVICE_RANKING + "=*))(" + Constants.SERVICE_RANKING + "<=" + (m_ranking - 1) + "))(|(" + Constants.SERVICE_ID + "=" + sid + ")(" + DependencyManager.ASPECT + "=" + sid + ")))";
- }
-
- public String toString() {
- return "Aspect for " + m_aspectInterface + ((m_aspectFilter != null) ? " with filter " + m_aspectFilter : "");
- }
- }
-
- class CallbackProxy {
- private final ServiceDependencyImpl m_aspectDependency;
- private final ServiceReference m_originalServiceRef;
-
- CallbackProxy(ServiceDependency aspectDependency, ServiceReference originalServiceRef) {
- m_aspectDependency = (ServiceDependencyImpl) aspectDependency;
- m_originalServiceRef = originalServiceRef;
- }
-
- private void addAspect(Component c, ServiceReference ref, Object service) {
- // Just forward "add" service dependency callback.
- m_aspectDependency.invoke(c.getCompositionInstances(), (DependencyService) c, ref, service, m_add);
- }
-
- private void changeAspect(Component c, ServiceReference ref, Object service) {
- // Invoke "change" service dependency callback
- if (m_change != null) {
- m_aspectDependency.invoke(c.getCompositionInstances(), (DependencyService) c, ref, service, m_change);
- }
- // Propagate change to immediate higher aspect, or to client using our aspect.
- // We always propagate our own properties, and the ones from the original service, but we don't inherit
- // from lower ranked aspect service properties.
- Dictionary props = getServiceProperties(m_originalServiceRef);
- c.setServiceProperties(props);
- }
-
- private void removeAspect(Component c, ServiceReference ref, Object service) {
- // Just forward "remove" service dependency callback.
- m_aspectDependency.invoke(c.getCompositionInstances(), (DependencyService) c, ref, service, m_remove);
- }
-
- private void swapAspect(Component c, ServiceReference prevRef, Object prev, ServiceReference currRef,
- Object curr) {
- // Just forward "swap" service dependency callback.
- m_aspectDependency.invokeSwappedCallback(c.getCompositionInstances(), (DependencyService) c, prevRef, prev,
- currRef, curr, m_swap);
- }
- }
-}
diff --git a/dependencymanager/core/src/main/java/org/apache/felix/dm/impl/BundleAdapterServiceImpl.java b/dependencymanager/core/src/main/java/org/apache/felix/dm/impl/BundleAdapterServiceImpl.java
deleted file mode 100644
index 76390a0..0000000
--- a/dependencymanager/core/src/main/java/org/apache/felix/dm/impl/BundleAdapterServiceImpl.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.felix.dm.impl;
-
-import java.util.Enumeration;
-import java.util.List;
-import java.util.Properties;
-
-import org.apache.felix.dm.Component;
-import org.apache.felix.dm.ComponentStateListener;
-import org.apache.felix.dm.Dependency;
-import org.apache.felix.dm.DependencyManager;
-import org.osgi.framework.Bundle;
-
-/**
- * Bundle Adapter Service implementation. This class extends the FilterService in order to catch
- * some Service methods for configuring actual adapter service implementation.
- *
- * @author <a href="mailto:dev@felix.apache.org">Felix Project Team</a>
- */
-public class BundleAdapterServiceImpl extends FilterService
-{
- /**
- * Creates a new Bundle Adapter Service implementation.
- */
- public BundleAdapterServiceImpl(DependencyManager dm, int bundleStateMask, String bundleFilter, boolean propagate)
- {
- super(dm.createComponent()); // This service will be filtered by our super class, allowing us to take control.
- m_component.setImplementation(new BundleAdapterImpl(bundleStateMask, bundleFilter, propagate))
- .add(dm.createBundleDependency()
- .setFilter(bundleFilter)
- .setStateMask(bundleStateMask)
- .setCallbacks("added", "removed"))
- .setCallbacks("init", null, "stop", null);
- }
-
- public class BundleAdapterImpl extends AbstractDecorator {
- private final boolean m_propagate;
- private final int m_bundleStateMask;
- private final String m_bundleFilter;
-
- public BundleAdapterImpl(int bundleStateMask, String bundleFilter, boolean propagate) {
- m_bundleStateMask = bundleStateMask;
- m_bundleFilter = bundleFilter;
- m_propagate = propagate;
- }
-
- public Component createService(Object[] properties) {
- Bundle bundle = (Bundle) properties[0];
- Properties props = new Properties();
- if (m_serviceProperties != null) {
- Enumeration e = m_serviceProperties.keys();
- while (e.hasMoreElements()) {
- Object key = e.nextElement();
- props.put(key, m_serviceProperties.get(key));
- }
- }
- List dependencies = m_component.getDependencies();
- // the first dependency is always the dependency on the bundle, which
- // will be replaced with a more specific dependency below
- dependencies.remove(0);
- Component service = m_manager.createComponent()
- .setInterface(m_serviceInterfaces, props)
- .setImplementation(m_serviceImpl)
- .setFactory(m_factory, m_factoryCreateMethod) // if not set, no effect
- .setComposition(m_compositionInstance, m_compositionMethod) // if not set, no effect
- .setCallbacks(m_callbackObject, m_init, m_start, m_stop, m_destroy) // if not set, no effect
- .add(m_manager.createBundleDependency()
- .setBundle(bundle)
- .setStateMask(m_bundleStateMask)
- .setPropagate(m_propagate)
- .setCallbacks(null, "changed", null)
- .setAutoConfig(true)
- .setRequired(true));
-
- for (int i = 0; i < dependencies.size(); i++) {
- service.add(((Dependency) dependencies.get(i)).createCopy());
- }
-
- for (int i = 0; i < m_stateListeners.size(); i ++) {
- service.addStateListener((ComponentStateListener) m_stateListeners.get(i));
- }
- configureAutoConfigState(service, m_component);
- return service;
- }
- }
-}
diff --git a/dependencymanager/core/src/main/java/org/apache/felix/dm/impl/ComponentImpl.java b/dependencymanager/core/src/main/java/org/apache/felix/dm/impl/ComponentImpl.java
deleted file mode 100644
index 3f05e5d..0000000
--- a/dependencymanager/core/src/main/java/org/apache/felix/dm/impl/ComponentImpl.java
+++ /dev/null
@@ -1,1315 +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.felix.dm.impl;
-
-import java.lang.reflect.Constructor;
-import java.lang.reflect.Field;
-import java.lang.reflect.InvocationTargetException;
-import java.lang.reflect.Method;
-import java.lang.reflect.Proxy;
-import java.util.ArrayList;
-import java.util.Arrays;
-import java.util.Dictionary;
-import java.util.Enumeration;
-import java.util.HashMap;
-import java.util.Hashtable;
-import java.util.Iterator;
-import java.util.List;
-import java.util.Map;
-import java.util.Properties;
-
-import org.apache.felix.dm.Component;
-import org.apache.felix.dm.ComponentDeclaration;
-import org.apache.felix.dm.ComponentDependencyDeclaration;
-import org.apache.felix.dm.ComponentStateListener;
-import org.apache.felix.dm.Dependency;
-import org.apache.felix.dm.DependencyActivation;
-import org.apache.felix.dm.DependencyManager;
-import org.apache.felix.dm.DependencyService;
-import org.apache.felix.dm.InvocationUtil;
-import org.osgi.framework.BundleContext;
-import org.osgi.framework.ServiceRegistration;
-
-/**
- * Component implementation.
- *
- * @author <a href="mailto:dev@felix.apache.org">Felix Project Team</a>
- */
-public class ComponentImpl implements Component, DependencyService, ComponentDeclaration, Comparable {
- private static final Class[] VOID = new Class[] {};
- private static final ServiceRegistration NULL_REGISTRATION;
- private static final ComponentStateListener[] SERVICE_STATE_LISTENER_TYPE = new ComponentStateListener[] {};
- private static long HIGHEST_ID = 0;
-
- private final Object SYNC = new Object();
- private final BundleContext m_context;
- private final DependencyManager m_manager;
- private final long m_id;
-
- // configuration (static)
- private String m_callbackInit;
- private String m_callbackStart;
- private String m_callbackStop;
- private String m_callbackDestroy;
- private volatile Object m_serviceName;
- private volatile Object m_implementation;
- private volatile Object m_callbackInstance;
-
- // configuration (dynamic, but does not affect state)
- private volatile Dictionary m_serviceProperties;
-
- // configuration (dynamic, and affects state)
- private final ArrayList m_dependencies = new ArrayList();
-
- // runtime state (calculated from dependencies)
- private State m_state;
-
- // runtime state (changes because of state changes)
- private volatile Object m_serviceInstance;
- private volatile ServiceRegistration m_registration;
- private volatile boolean m_isBound;
- private volatile boolean m_isInstantiated;
-
- // service state listeners
- private final List m_stateListeners = new ArrayList();
-
- // work queue
- private final SerialExecutor m_executor;
-
- // instance factory
- private volatile Object m_instanceFactory;
- private volatile String m_instanceFactoryCreateMethod;
-
- // composition manager
- private volatile Object m_compositionManager;
- private volatile String m_compositionManagerGetMethod;
- private volatile Object m_compositionManagerInstance;
-
- // internal logging
- private final Logger m_logger;
-
- private final Map m_autoConfig = new HashMap();
- private final Map m_autoConfigInstance = new HashMap();
-
- private boolean m_isStarted = false;
-
- // Used to track what state listener callback we have already called
- private int m_stateListener = LISTENER_IDLE;
-
- // We have not yet called any state listener callbacks
- private final static int LISTENER_IDLE = 0;
-
- // We have already called the "starting" state listener callback.
- private final static int LISTENER_STARTING = 1;
-
- // We have already called the "started" state listener callback.
- private final static int LISTENER_STARTED = 2;
-
- // We have already called the "stopping" state listener callback.
- private final static int LISTENER_STOPPING = 3;
-
- // We have already called the "stopped" state listener callback.
- private final static int LISTENER_STOPPED = 4;
-
- public ComponentImpl(BundleContext context, DependencyManager manager, Logger logger) {
- m_executor = new SerialExecutor(logger);
- synchronized (VOID) {
- m_id = HIGHEST_ID++;
- }
- m_logger = logger;
- m_state = new State((List) m_dependencies.clone(), false, false, false);
- m_context = context;
- m_manager = manager;
- m_callbackInit = "init";
- m_callbackStart = "start";
- m_callbackStop = "stop";
- m_callbackDestroy = "destroy";
- m_implementation = null;
- m_autoConfig.put(BundleContext.class, Boolean.TRUE);
- m_autoConfig.put(ServiceRegistration.class, Boolean.TRUE);
- m_autoConfig.put(DependencyManager.class, Boolean.TRUE);
- m_autoConfig.put(Component.class, Boolean.TRUE);
- }
-
- private void calculateStateChanges() {
- // see if any of the things we did caused a further change of state
- State oldState, newState;
- synchronized (m_dependencies) {
- oldState = m_state;
- newState = new State((List) m_dependencies.clone(), !oldState.isInactive(), m_isInstantiated, m_isBound);
- m_state = newState;
- }
- calculateStateChanges(oldState, newState);
- }
-
- private void calculateStateChanges(final State oldState, final State newState) {
- if (oldState.isInactive() && (newState.isTrackingOptional())) {
- m_executor.enqueue(new Runnable() {
- public void run() {
- activateService(newState);
- }});
- }
- if (oldState.isInactive() && (newState.isWaitingForRequired())) {
- m_executor.enqueue(new Runnable() {
- public void run() {
- startTrackingRequired(newState);
- }});
- }
- if (oldState.isWaitingForRequired() && newState.isTrackingOptional()) {
- m_executor.enqueue(new Runnable() {
- public void run() {
- activateService(newState);
- }});
- }
- if ((oldState.isWaitingForRequired()) && newState.isInactive()) {
- m_executor.enqueue(new Runnable() {
- public void run() {
- stopTrackingRequired(oldState);
- }});
- }
- if (oldState.isTrackingOptional() && newState.isWaitingForRequiredInstantiated()) {
- m_executor.enqueue(new Runnable() {
- public void run() {
- // TODO as far as I can see there is nothing left to do here
- // unbindService(newState);
- }});
- }
- if (oldState.isTrackingOptional() && newState.isWaitingForRequired()) {
- m_executor.enqueue(new Runnable() {
- public void run() {
- deactivateService(oldState);
- }});
- }
- if (oldState.isTrackingOptional() && newState.isBound()) {
- m_executor.enqueue(new Runnable() {
- public void run() {
- bindService(newState);
- }});
- }
- if (oldState.isTrackingOptional() && newState.isInactive()) {
- m_executor.enqueue(new Runnable() {
- public void run() {
- deactivateService(oldState);
- stopTrackingRequired(oldState);
- }});
- }
- if (oldState.isWaitingForRequiredInstantiated() && newState.isWaitingForRequired()) {
- m_executor.enqueue(new Runnable() {
- public void run() {
- deactivateService(oldState);
- }});
- }
- if (oldState.isWaitingForRequiredInstantiated() && newState.isInactive()) {
- m_executor.enqueue(new Runnable() {
- public void run() {
- deactivateService(oldState);
- stopTrackingRequired(oldState);
- }});
- }
- if (oldState.isWaitingForRequiredInstantiated() && newState.isBound()) {
- m_executor.enqueue(new Runnable() {
- public void run() {
- bindService(newState);
- }});
- }
- if (oldState.isBound() && newState.isWaitingForRequiredInstantiated()) {
- m_executor.enqueue(new Runnable() {
- public void run() {
- unbindService(oldState);
- }});
- }
- if (oldState.isBound() && newState.isWaitingForRequired()) {
- m_executor.enqueue(new Runnable() {
- public void run() {
- unbindService(oldState);
- deactivateService(oldState);
- }});
- }
- if (oldState.isBound() && newState.isInactive()) {
- m_executor.enqueue(new Runnable() {
- public void run() {
- unbindService(oldState);
- deactivateService(oldState);
- stopTrackingRequired(oldState);
- }});
- }
- m_executor.execute();
- }
-
- // TODO fix code duplication between add(Dependency) and add(List)
- public Component add(final Dependency dependency) {
- State oldState, newState;
- synchronized (m_dependencies) {
- oldState = m_state;
- m_dependencies.add(dependency);
- }
-
- // if we're inactive, don't do anything, otherwise we might want to start
- // the dependency
- if (!oldState.isInactive()) {
- // if the dependency is required, it should be started regardless of the state
- // we're in
- if (dependency.isRequired()) {
- ((DependencyActivation) dependency).start(this);
- }
- else {
- // if the dependency is optional, it should only be started if we're in
- // bound state
- if (oldState.isBound()) {
- ((DependencyActivation) dependency).start(this);
- }
- }
- }
-
- synchronized (m_dependencies) {
- oldState = m_state;
- // starting the dependency above might have triggered another state change, so
- // we have to fetch the current state again
- newState = new State((List) m_dependencies.clone(), !oldState.isInactive(), m_isInstantiated, m_isBound);
- m_state = newState;
- }
- calculateStateChanges(oldState, newState);
- return this;
- }
-
- public Component add(List dependencies) {
- State oldState, newState;
- synchronized (m_dependencies) {
- oldState = m_state;
- for (int i = 0; i < dependencies.size(); i++) {
- m_dependencies.add(dependencies.get(i));
- }
- }
-
- // if we're inactive, don't do anything, otherwise we might want to start
- // the dependencies
- if (!oldState.isInactive()) {
- for (int i = 0; i < dependencies.size(); i++) {
- Dependency dependency = (Dependency) dependencies.get(i);
- // if the dependency is required, it should be started regardless of the state
- // we're in
- if (dependency.isRequired()) {
- ((DependencyActivation) dependency).start(this);
- }
- else {
- // if the dependency is optional, it should only be started if we're in
- // bound state
- if (oldState.isBound()) {
- ((DependencyActivation) dependency).start(this);
- }
- }
- }
- }
-
- synchronized (m_dependencies) {
- oldState = m_state;
- // starting the dependency above might have triggered another state change, so
- // we have to fetch the current state again
- newState = new State((List) m_dependencies.clone(), !oldState.isInactive(), m_isInstantiated, m_isBound);
- m_state = newState;
- }
- calculateStateChanges(oldState, newState);
- return this;
- }
-
- public Component remove(Dependency dependency) {
- State oldState, newState;
- synchronized (m_dependencies) {
- oldState = m_state;
- m_dependencies.remove(dependency);
- }
- if (oldState.isAllRequiredAvailable() || ((oldState.isWaitingForRequired() || oldState.isWaitingForRequiredInstantiated()) && dependency.isRequired())) {
- ((DependencyActivation) dependency).stop(this);
- }
- synchronized (m_dependencies) {
- // starting the dependency above might have triggered another state change, so
- // we have to fetch the current state again
- oldState = m_state;
- newState = new State((List) m_dependencies.clone(), !oldState.isInactive(), m_isInstantiated, m_isBound);
- m_state = newState;
- }
- calculateStateChanges(oldState, newState);
- return this;
- }
-
- public List getDependencies() {
- synchronized (m_dependencies) {
- return (List) m_dependencies.clone();
- }
- }
-
- public ServiceRegistration getServiceRegistration() {
- return m_registration;
- }
-
- public Object getService() {
- return m_serviceInstance;
- }
-
- public Component getServiceInterface() {
- return this;
- }
-
- public void dependencyAvailable(final Dependency dependency) {
- State oldState, newState;
- synchronized (m_dependencies) {
- oldState = m_state;
- newState = new State((List) m_dependencies.clone(), !oldState.isInactive(), m_isInstantiated, m_isBound);
- m_state = newState;
- }
- if (newState.isAllRequiredAvailable() || newState.isWaitingForRequiredInstantiated()) {
- updateInstance(dependency);
- }
- calculateStateChanges(oldState, newState);
- }
-
- public void dependencyChanged(final Dependency dependency) {
- State state;
- synchronized (m_dependencies) {
- state = m_state;
- }
- if (state.isAllRequiredAvailable()) {
- updateInstance(dependency);
- }
- }
-
- public void autoConfig(final Dependency dependency) {
- State state;
- synchronized (m_dependencies) {
- state = m_state;
- }
- if (state.isAllRequiredAvailable() && dependency.isAutoConfig()) {
- configureImplementation(dependency.getAutoConfigType(), dependency.getAutoConfigInstance(), dependency.getAutoConfigName());
- }
- }
-
- public void propagate(final Dependency dependency) {
- State state;
- synchronized (m_dependencies) {
- state = m_state;
- }
- if (state.isAllRequiredAvailable() && dependency.isPropagated() && m_registration != null) {
- m_registration.setProperties(calculateServiceProperties());
- }
- }
-
- public void dependencyUnavailable(final Dependency dependency) {
- State oldState, newState;
- synchronized (m_dependencies) {
- oldState = m_state;
- newState = new State((List) m_dependencies.clone(), !oldState.isInactive(), m_isInstantiated, m_isBound);
- m_state = newState;
- }
- if (newState.isAllRequiredAvailable()) {
- updateInstance(dependency);
- }
- calculateStateChanges(oldState, newState);
- }
-
- public void start() {
- boolean needsStarting = false;
- synchronized (this) {
- if (!m_isStarted) {
- m_isStarted = true;
- needsStarting = true;
- }
- }
- if (needsStarting) {
- State oldState, newState;
- synchronized (m_dependencies) {
- oldState = m_state;
- newState = new State((List) m_dependencies.clone(), true, m_isInstantiated, m_isBound);
- m_state = newState;
- }
- calculateStateChanges(oldState, newState);
- }
- }
-
- public void stop() {
- boolean needsStopping = false;
- synchronized (this) {
- if (m_isStarted) {
- m_isStarted = false;
- needsStopping = true;
- }
- }
- if (needsStopping) {
- State oldState, newState;
- synchronized (m_dependencies) {
- oldState = m_state;
- newState = new State((List) m_dependencies.clone(), false, m_isInstantiated, m_isBound);
- m_state = newState;
- }
- calculateStateChanges(oldState, newState);
- }
- }
-
- public synchronized Component setInterface(String serviceName, Dictionary properties) {
- ensureNotActive();
- m_serviceName = serviceName;
- m_serviceProperties = properties;
- return this;
- }
-
- public synchronized Component setInterface(String[] serviceName, Dictionary properties) {
- ensureNotActive();
- m_serviceName = serviceName;
- m_serviceProperties = properties;
- return this;
- }
-
- public synchronized Component setCallbacks(String init, String start, String stop, String destroy) {
- ensureNotActive();
- m_callbackInit = init;
- m_callbackStart = start;
- m_callbackStop = stop;
- m_callbackDestroy = destroy;
- return this;
- }
-
- public synchronized Component setCallbacks(Object instance, String init, String start, String stop, String destroy) {
- ensureNotActive();
- m_callbackInstance = instance;
- m_callbackInit = init;
- m_callbackStart = start;
- m_callbackStop = stop;
- m_callbackDestroy = destroy;
- return this;
- }
-
- public synchronized Component setImplementation(Object implementation) {
- ensureNotActive();
- m_implementation = implementation;
- return this;
- }
-
- public synchronized Component setFactory(Object factory, String createMethod) {
- ensureNotActive();
- m_instanceFactory = factory;
- m_instanceFactoryCreateMethod = createMethod;
- return this;
- }
-
- public synchronized Component setFactory(String createMethod) {
- return setFactory(null, createMethod);
- }
-
- public synchronized Component setComposition(Object instance, String getMethod) {
- ensureNotActive();
- m_compositionManager = instance;
- m_compositionManagerGetMethod = getMethod;
- return this;
- }
-
- public synchronized Component setComposition(String getMethod) {
- return setComposition(null, getMethod);
- }
-
- public String toString() {
- return this.getClass().getSimpleName() + "[" + m_serviceName + " " + m_implementation + "]";
- }
-
- public synchronized Dictionary getServiceProperties() {
- if (m_serviceProperties != null) {
- return (Dictionary) ((Hashtable) m_serviceProperties).clone();
- }
- return null;
- }
-
- public Component setServiceProperties(Dictionary serviceProperties) {
- boolean needsProperties = false;
- Dictionary properties = null;
- synchronized (this) {
- m_serviceProperties = serviceProperties;
- if ((m_registration != null) && (m_serviceName != null)) {
- properties = calculateServiceProperties();
- needsProperties = true;
- }
- }
- if (needsProperties) {
- m_registration.setProperties(properties);
- }
- return this;
- }
-
- // service state listener methods
- public void addStateListener(final ComponentStateListener listener) {
- m_executor.execute(new Runnable() {
- public void run() { // executed immediately if we are already being executed from the executor
- synchronized (m_stateListeners) {
- m_stateListeners.add(listener);
- }
- switch (m_stateListener) {
- case LISTENER_STARTING:
- // this new listener missed the starting cb
- listener.starting(ComponentImpl.this);
- break;
- case LISTENER_STARTED:
- // this new listener missed the starting/started cb
- listener.starting(ComponentImpl.this);
- listener.started(ComponentImpl.this);
- break;
- case LISTENER_STOPPING:
- // this new listener missed the starting/started/stopping cb
- listener.starting(ComponentImpl.this);
- listener.started(ComponentImpl.this);
- listener.stopping(ComponentImpl.this);
- break;
- case LISTENER_STOPPED:
- // no need to call missed listener callbacks
- break;
- }
- }
- });
- }
-
- public void removeStateListener(final ComponentStateListener listener) {
- m_executor.execute(new Runnable() {
- public void run() { // executed immediately if we are already being executed from the executor
- switch (m_stateListener) {
- case LISTENER_STARTING:
- // The listener has been previously called in starting cb;
- // so we should call the listener started cb, before unregistering it.
- listener.started(ComponentImpl.this);
- break;
-
- case LISTENER_STOPPING:
- // The listener has been previously called in stopping cb;
- // so we should call the listener stopped cb, before unregistering it.
- listener.stopped(ComponentImpl.this);
- break;
- }
- synchronized (m_stateListeners) {
- m_stateListeners.remove(listener);
- }
- }
- });
- m_executor.execute();
- }
-
- public void removeStateListeners() {
- synchronized (m_stateListeners) {
- m_stateListeners.clear();
- }
- }
-
- private void stateListenersStarting() {
- // called from our serial executor
- m_stateListener = LISTENER_STARTING;
- ComponentStateListener[] list = getListeners();
- for (int i = 0; i < list.length; i++) {
- try {
- list[i].starting(this);
- }
- catch (Throwable t) {
- m_logger.log(Logger.LOG_ERROR, "Error invoking listener starting method.", t);
- }
- }
- }
-
- private void stateListenersStarted() {
- // called from our serial executor
- m_stateListener = LISTENER_STARTED;
- ComponentStateListener[] list = getListeners();
- for (int i = 0; i < list.length; i++) {
- try {
- list[i].started(this);
- }
- catch (Throwable t) {
- m_logger.log(Logger.LOG_ERROR, "Error invoking listener started method.", t);
- }
- }
- }
-
- private void stateListenersStopping() {
- // called from our serial executor
- m_stateListener = LISTENER_STOPPING;
- ComponentStateListener[] list = getListeners();
- for (int i = 0; i < list.length; i++) {
- try {
- list[i].stopping(this);
- }
- catch (Throwable t) {
- m_logger.log(Logger.LOG_ERROR, "Error invoking listener stopping method.", t);
- }
- }
- }
-
- private void stateListenersStopped() {
- // called from our serial executor
- m_stateListener = LISTENER_STOPPED;
- ComponentStateListener[] list = getListeners();
- for (int i = 0; i < list.length; i++) {
- try {
- list[i].stopped(this);
- }
- catch (Throwable t) {
- m_logger.log(Logger.LOG_ERROR, "Error invoking listener stopped method.", t);
- }
- }
- }
-
- private ComponentStateListener[] getListeners() {
- synchronized (m_stateListeners) {
- return (ComponentStateListener[]) m_stateListeners.toArray(SERVICE_STATE_LISTENER_TYPE);
- }
- }
-
- private void activateService(State state) {
- String init;
- synchronized (this) {
- init = m_callbackInit;
- }
- // service activation logic, first we initialize the service instance itself
- // meaning it is created if necessary and the bundle context is set
- initService();
- // now is the time to configure the service, meaning all required
- // dependencies will be set and any callbacks called
- configureService(state);
- // flag that our instance has been created
- m_isInstantiated = true;
- // then we invoke the init callback so the service can further initialize
- // itself
- invoke(init);
- // see if any of this caused further state changes
- calculateStateChanges();
- }
-
- private void bindService(State state) {
- String start;
- synchronized (this) {
- start = m_callbackStart;
- }
-
- // configure service with extra-dependencies which might have been added from init() method.
- configureServiceWithExtraDependencies(state);
- // inform the state listeners we're starting
- stateListenersStarting();
- // invoke the start callback, since we're now ready to be used
- invoke(start);
- // start tracking optional services
- startTrackingOptional(state);
- // register the service in the framework's service registry
- registerService();
- // inform the state listeners we've started
- stateListenersStarted();
- }
-
- private void configureServiceWithExtraDependencies(State state) {
- Iterator i = state.getDependencies().iterator();
- while (i.hasNext()) {
- Dependency dependency = (Dependency) i.next();
- if (dependency.isAutoConfig() && dependency.isInstanceBound()) {
- configureImplementation(dependency.getAutoConfigType(), dependency.getAutoConfigInstance(), dependency.getAutoConfigName());
- }
- }
- }
-
- private void unbindService(State state) {
- String stop;
- synchronized (this) {
- stop = m_callbackStop;
- }
- // service deactivation logic, first inform the state listeners
- // we're stopping
- stateListenersStopping();
- // then, unregister the service from the framework
- unregisterService();
- // stop tracking optional services
- stopTrackingOptional(state);
- // invoke the stop callback
- invoke(stop);
- // inform the state listeners we've stopped
- stateListenersStopped();
- }
-
- private void deactivateService(State state) {
- String destroy;
- synchronized (this) {
- destroy = m_callbackDestroy;
- }
- // flag that our instance was destroyed
- m_isInstantiated = false;
- // invoke the destroy callback
- invoke(destroy);
- // destroy the service instance
- destroyService(state);
- }
-
- private void invoke(String name) {
- if (name != null) {
- // if a callback instance was specified, look for the method there, if not,
- // ask the service for its composition instances
- Object[] instances = m_callbackInstance != null ? new Object[] { m_callbackInstance } : getCompositionInstances();
- invokeCallbackMethod(instances, name,
- new Class[][] {{ Component.class }, {}},
- new Object[][] {{ this }, {}});
- }
- }
-
- public void invokeCallbackMethod(Object[] instances, String methodName, Class[][] signatures, Object[][] parameters) {
- for (int i = 0; i < instances.length; i++) {
- try {
- InvocationUtil.invokeCallbackMethod(instances[i], methodName, signatures, parameters);
- }
- catch (NoSuchMethodException e) {
- // if the method does not exist, ignore it
- }
- catch (InvocationTargetException e) {
- // the method itself threw an exception, log that
- m_logger.log(Logger.LOG_WARNING, "Invocation of '" + methodName + "' failed.", e.getCause());
- }
- catch (Exception e) {
- m_logger.log(Logger.LOG_WARNING, "Could not invoke '" + methodName + "'.", e);
- }
- }
- }
-
- private void startTrackingOptional(State state) {
- Iterator i = state.getDependencies().iterator();
- while (i.hasNext()) {
- Dependency dependency = (Dependency) i.next();
- if (!dependency.isRequired()) {
- ((DependencyActivation) dependency).start(this);
- }
- }
- }
-
- private void stopTrackingOptional(State state) {
- Iterator i = state.getDependencies().iterator();
- while (i.hasNext()) {
- Dependency dependency = (Dependency) i.next();
- if (!dependency.isRequired()) {
- ((DependencyActivation) dependency).stop(this);
- }
- }
- }
-
- private void startTrackingRequired(State state) {
- Iterator i = state.getDependencies().iterator();
- while (i.hasNext()) {
- Dependency dependency = (Dependency) i.next();
- if (dependency.isRequired()) {
- ((DependencyActivation) dependency).start(this);
- }
- }
- }
-
- private void stopTrackingRequired(State state) {
- Iterator i = state.getDependencies().iterator();
- while (i.hasNext()) {
- Dependency dependency = (Dependency) i.next();
- if (dependency.isRequired()) {
- ((DependencyActivation) dependency).stop(this);
- }
- }
- }
-
- private Object createInstance(Class clazz) throws SecurityException, NoSuchMethodException, InstantiationException, IllegalAccessException, IllegalArgumentException, InvocationTargetException {
- Constructor constructor = clazz.getConstructor(VOID);
- constructor.setAccessible(true);
- return constructor.newInstance(null);
- }
-
- public void initService() {
- if (m_serviceInstance == null) {
- if (m_implementation instanceof Class) {
- // instantiate
- try {
- m_serviceInstance = createInstance((Class) m_implementation);
- }
- catch (Exception e) {
- m_logger.log(Logger.LOG_ERROR, "Could not create service instance of class " + m_implementation + ".", e);
- }
- }
- else {
- if (m_instanceFactoryCreateMethod != null) {
- Object factory = null;
- if (m_instanceFactory != null) {
- if (m_instanceFactory instanceof Class) {
- try {
- factory = createInstance((Class) m_instanceFactory);
- }
- catch (Exception e) {
- m_logger.log(Logger.LOG_ERROR, "Could not create factory instance of class " + m_instanceFactory + ".", e);
- }
- }
- else {
- factory = m_instanceFactory;
- }
- }
- else {
- // TODO review if we want to try to default to something if not specified
- // for now the JavaDoc of setFactory(method) reflects the fact that we need
- // to review it
- }
- if (factory == null) {
- m_logger.log(Logger.LOG_ERROR, "Factory cannot be null.");
- }
- else {
- try {
- m_serviceInstance = InvocationUtil.invokeMethod(factory, factory.getClass(), m_instanceFactoryCreateMethod, new Class[][] {{}}, new Object[][] {{}}, false);
- }
- catch (Exception e) {
- m_logger.log(Logger.LOG_ERROR, "Could not create service instance using factory " + factory + " method " + m_instanceFactoryCreateMethod + ".", e);
- }
- }
- }
- if (m_serviceInstance == null) {
- if (m_implementation == null) {
- m_logger.log(Logger.LOG_ERROR, "Implementation cannot be null.");
- }
- m_serviceInstance = m_implementation;
- }
- }
- // configure the bundle context
- if (((Boolean) m_autoConfig.get(BundleContext.class)).booleanValue()) {
- configureImplementation(BundleContext.class, m_context, (String) m_autoConfigInstance.get(BundleContext.class));
- }
- if (((Boolean) m_autoConfig.get(ServiceRegistration.class)).booleanValue()) {
- configureImplementation(ServiceRegistration.class, NULL_REGISTRATION, (String) m_autoConfigInstance.get(ServiceRegistration.class));
- }
- if (((Boolean) m_autoConfig.get(DependencyManager.class)).booleanValue()) {
- configureImplementation(DependencyManager.class, m_manager, (String) m_autoConfigInstance.get(DependencyManager.class));
- }
- if (((Boolean) m_autoConfig.get(Component.class)).booleanValue()) {
- configureImplementation(Component.class, this, (String) m_autoConfigInstance.get(Component.class));
- }
- }
- }
-
- public synchronized Component setAutoConfig(Class clazz, boolean autoConfig) {
- m_autoConfig.put(clazz, Boolean.valueOf(autoConfig));
- return this;
- }
-
- public synchronized Component setAutoConfig(Class clazz, String instanceName) {
- m_autoConfig.put(clazz, Boolean.valueOf(instanceName != null));
- m_autoConfigInstance.put(clazz, instanceName);
- return this;
- }
-
- public boolean getAutoConfig(Class clazz) {
- Boolean result = (Boolean) m_autoConfig.get(clazz);
- return (result != null && result.booleanValue());
- }
-
- public String getAutoConfigInstance(Class clazz) {
- return (String) m_autoConfigInstance.get(clazz);
- }
-
- private void configureService(State state) {
- // configure all services (the optional dependencies might be configured
- // as null objects but that's what we want at this point)
- configureServices(state);
- }
-
- private void destroyService(State state) {
- unconfigureServices(state);
- m_serviceInstance = null;
- }
-
- private void registerService() {
- if (m_serviceName != null) {
- ServiceRegistrationImpl wrapper = new ServiceRegistrationImpl();
- m_registration = wrapper;
- if (((Boolean) m_autoConfig.get(ServiceRegistration.class)).booleanValue()) {
- configureImplementation(ServiceRegistration.class, m_registration, (String) m_autoConfigInstance.get(ServiceRegistration.class));
- }
-
- // service name can either be a string or an array of strings
- ServiceRegistration registration;
-
- // determine service properties
- Dictionary properties = calculateServiceProperties();
-
- // register the service
- try {
- if (m_serviceName instanceof String) {
- registration = m_context.registerService((String) m_serviceName, m_serviceInstance, properties);
- }
- else {
- registration = m_context.registerService((String[]) m_serviceName, m_serviceInstance, properties);
- }
- wrapper.setServiceRegistration(registration);
- }
- catch (IllegalArgumentException iae) {
- m_logger.log(Logger.LOG_ERROR, "Could not register service " + m_serviceInstance, iae);
- // set the registration to an illegal state object, which will make all invocations on this
- // wrapper fail with an ISE (which also occurs when the SR becomes invalid)
- wrapper.setIllegalState();
- }
- }
- m_isBound = true;
- }
-
- private Dictionary calculateServiceProperties() {
- Dictionary properties = new Properties();
- addTo(properties, m_serviceProperties);
- for (int i = 0; i < m_dependencies.size(); i++) {
- Dependency d = (Dependency) m_dependencies.get(i);
- if (d.isPropagated() && d.isAvailable()) {
- Dictionary dict = d.getProperties();
- addTo(properties, dict);
- }
- }
- if (properties.size() == 0) {
- properties = null;
- }
- return properties;
- }
-
- private void addTo(Dictionary properties, Dictionary additional) {
- if (properties == null) {
- throw new IllegalArgumentException("Dictionary to add to cannot be null.");
- }
- if (additional != null) {
- Enumeration e = additional.keys();
- while (e.hasMoreElements()) {
- Object key = e.nextElement();
- properties.put(key, additional.get(key));
- }
- }
- }
-
- private void unregisterService() {
- m_isBound = false;
- if (m_serviceName != null) {
- m_registration.unregister();
- configureImplementation(ServiceRegistration.class, NULL_REGISTRATION);
- m_registration = null;
- }
- }
-
- private void updateInstance(Dependency dependency) {
- if (dependency.isAutoConfig()) {
- configureImplementation(dependency.getAutoConfigType(), dependency.getAutoConfigInstance(), dependency.getAutoConfigName());
- }
- if (dependency.isPropagated() && m_registration != null) {
- m_registration.setProperties(calculateServiceProperties());
- }
- }
-
- /**
- * Configure a field in the service implementation. The service implementation
- * is searched for fields that have the same type as the class that was specified
- * and for each of these fields, the specified instance is filled in.
- *
- * @param clazz the class to search for
- * @param instance the instance to fill in
- * @param instanceName the name of the instance to fill in, or <code>null</code> if not used
- */
- private void configureImplementation(Class clazz, Object instance, String instanceName) {
- Object[] instances = getCompositionInstances();
- if (instances != null) {
- for (int i = 0; i < instances.length; i++) {
- Object serviceInstance = instances[i];
- Class serviceClazz = serviceInstance.getClass();
- if (Proxy.isProxyClass(serviceClazz)) {
- serviceInstance = Proxy.getInvocationHandler(serviceInstance);
- serviceClazz = serviceInstance.getClass();
- }
- while (serviceClazz != null) {
- Field[] fields = serviceClazz.getDeclaredFields();
- for (int j = 0; j < fields.length; j++) {
- Field field = fields[j];
- Class type = field.getType();
- if ((instanceName == null && type.equals(clazz))
- || (instanceName != null && field.getName().equals(instanceName) && type.isAssignableFrom(clazz))) {
- try {
- field.setAccessible(true);
- // synchronized makes sure the field is actually written to immediately
- synchronized (SYNC) {
- field.set(serviceInstance, instance);
- }
- }
- catch (Exception e) {
- m_logger.log(Logger.LOG_ERROR, "Could not set field " + field, e);
- return;
- }
- }
- }
- serviceClazz = serviceClazz.getSuperclass();
- }
- }
- }
- }
-
- public Object[] getCompositionInstances() {
- Object[] instances = null;
- if (m_compositionManagerGetMethod != null) {
- if (m_compositionManager != null) {
- m_compositionManagerInstance = m_compositionManager;
- }
- else {
- m_compositionManagerInstance = m_serviceInstance;
- }
- if (m_compositionManagerInstance != null) {
- try {
- instances = (Object[]) InvocationUtil.invokeMethod(m_compositionManagerInstance, m_compositionManagerInstance.getClass(), m_compositionManagerGetMethod, new Class[][] {{}}, new Object[][] {{}}, false);
- }
- catch (Exception e) {
- m_logger.log(Logger.LOG_ERROR, "Could not obtain instances from the composition manager.", e);
- instances = m_serviceInstance == null ? new Object[] {} : new Object[] { m_serviceInstance };
- }
- }
- }
- else {
- instances = m_serviceInstance == null ? new Object[] {} : new Object[] { m_serviceInstance };
- }
- return instances;
- }
-
- private void configureImplementation(Class clazz, Object instance) {
- configureImplementation(clazz, instance, null);
- }
-
- private void configureServices(State state) {
- Iterator i = state.getDependencies().iterator();
- while (i.hasNext()) {
- Dependency dependency = (Dependency) i.next();
- if (dependency.isAutoConfig()) {
- configureImplementation(dependency.getAutoConfigType(), dependency.getAutoConfigInstance(), dependency.getAutoConfigName());
- }
- if (dependency.isRequired()) {
- dependency.invokeAdded(this);
- }
- }
- }
-
- private void unconfigureServices(State state) {
- Iterator i = state.getDependencies().iterator();
- while (i.hasNext()) {
- Dependency dependency = (Dependency) i.next();
- if (dependency.isRequired()) {
- dependency.invokeRemoved(this);
- }
- }
- }
-
- protected void ensureNotActive() {
- State state;
- synchronized (m_dependencies) {
- state = m_state;
- }
- if (!state.isInactive()) {
- throw new IllegalStateException("Cannot modify state while active.");
- }
- }
-
- public boolean isRegistered() {
- State state;
- synchronized (m_dependencies) {
- state = m_state;
- }
- return (state.isAllRequiredAvailable());
- }
-
- public boolean isInstantiated() {
- State state;
- synchronized (m_dependencies) {
- state = m_state;
- }
- return (state.isTrackingOptional() || state.isBound() || state.isWaitingForRequiredInstantiated());
- }
-
- // ServiceComponent interface
-
- static class SCDImpl implements ComponentDependencyDeclaration {
- private final String m_name;
- private final int m_state;
- private final String m_type;
-
- public SCDImpl(String name, int state, String type) {
- m_name = name;
- m_state = state;
- m_type = type;
- }
-
- public String getName() {
- return m_name;
- }
-
- public int getState() {
- return m_state;
- }
-
- public String getType() {
- return m_type;
- }
- }
-
- public ComponentDependencyDeclaration[] getComponentDependencies() {
- List deps = getDependencies();
- if (deps != null) {
- ComponentDependencyDeclaration[] result = new ComponentDependencyDeclaration[deps.size()];
- for (int i = 0; i < result.length; i++) {
- Dependency dep = (Dependency) deps.get(i);
- if (dep instanceof ComponentDependencyDeclaration) {
- result[i] = (ComponentDependencyDeclaration) dep;
- }
- else {
- result[i] = new SCDImpl(dep.toString(), (dep.isAvailable() ? 1 : 0) + (dep.isRequired() ? 2 : 0), dep.getClass().getName());
- }
- }
- return result;
- }
- return null;
- }
-
- public String getName() {
- StringBuffer sb = new StringBuffer();
- Object serviceName = m_serviceName;
- if (serviceName instanceof String[]) {
- String[] names = (String[]) serviceName;
- for (int i = 0; i < names.length; i++) {
- if (i > 0) {
- sb.append(", ");
- }
- sb.append(names[i]);
- }
- appendProperties(sb);
- } else if (serviceName instanceof String) {
- sb.append(serviceName.toString());
- appendProperties(sb);
- } else {
- Object implementation = m_implementation;
- if (implementation != null) {
- if (implementation instanceof Class) {
- sb.append(((Class) implementation).getName());
- } else {
- // If the implementation instance does not override "toString", just display
- // the class name, else display the component using its toString method
- try {
- Method m = implementation.getClass().getMethod("toString", new Class[0]);
- if (m.getDeclaringClass().equals(Object.class)) {
- sb.append(implementation.getClass().getName());
- } else {
- sb.append(implementation.toString());
- }
- } catch (java.lang.NoSuchMethodException e) {
- // Just display the class name
- sb.append(implementation.getClass().getName());
- }
- }
- } else {
- sb.append(super.toString());
- }
- }
- return sb.toString();
- }
-
- public String getClassName() {
- Object serviceInstance = m_serviceInstance;
- if (serviceInstance != null) {
- return serviceInstance.getClass().getName();
- }
-
- Object implementation = m_implementation;
- if (implementation != null) {
- if (implementation instanceof Class) {
- return ((Class) implementation).getName();
- }
- return implementation.getClass().getName();
- }
-
- Object instanceFactory = m_instanceFactory;
- if (instanceFactory != null) {
- return instanceFactory.getClass().getName();
- } else {
- // Unexpected ...
- return getClass().getName();
- }
- }
-
- private void appendProperties(StringBuffer result) {
- Dictionary properties = calculateServiceProperties();
- if (properties != null) {
- result.append("(");
- Enumeration enumeration = properties.keys();
- while (enumeration.hasMoreElements()) {
- Object key = enumeration.nextElement();
- result.append(key.toString());
- result.append('=');
- Object value = properties.get(key);
- if (value instanceof String[]) {
- String[] values = (String[]) value;
- result.append('{');
- for (int i = 0; i < values.length; i++) {
- if (i > 0) {
- result.append(',');
- }
- result.append(values[i].toString());
- }
- result.append('}');
- }
- else {
- result.append(value.toString());
- }
- if (enumeration.hasMoreElements()) {
- result.append(',');
- }
- }
- result.append(")");
- }
- }
-
- public int getState() {
- return (isRegistered() ? 1 : 0);
- }
-
- public long getId() {
- return m_id;
- }
-
- public synchronized String[] getServices() {
- if (m_serviceName instanceof String[]) {
- return (String[]) m_serviceName;
- } else if (m_serviceName instanceof String) {
- return new String[] { (String) m_serviceName };
- } else {
- return null;
- }
- }
-
- public DependencyManager getDependencyManager() {
- return m_manager;
- }
-
- static {
- NULL_REGISTRATION = (ServiceRegistration) Proxy.newProxyInstance(ComponentImpl.class.getClassLoader(), new Class[] {ServiceRegistration.class}, new DefaultNullObject());
- }
-
- public BundleContext getBundleContext() {
- return m_context;
- }
-
- public int compareTo(Object object) {
- if (object instanceof ComponentImpl) {
- ComponentImpl other = (ComponentImpl) object;
- long id1 = this.getBundleContext().getBundle().getBundleId();
- long id2 = ((ComponentImpl) other).getBundleContext().getBundle().getBundleId();
- if (id1 == id2) {
- return (int)(this.m_id - other.m_id);
- }
- return (int)(id1 - id2);
- }
- return -1;
- }
-}
diff --git a/dependencymanager/core/src/main/java/org/apache/felix/dm/impl/DefaultNullObject.java b/dependencymanager/core/src/main/java/org/apache/felix/dm/impl/DefaultNullObject.java
deleted file mode 100644
index f981610..0000000
--- a/dependencymanager/core/src/main/java/org/apache/felix/dm/impl/DefaultNullObject.java
+++ /dev/null
@@ -1,71 +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.felix.dm.impl;
-
-import java.lang.reflect.InvocationHandler;
-import java.lang.reflect.Method;
-
-
-/**
- * Default null object implementation. Uses a dynamic proxy. Null objects are used
- * as placeholders for services that are not available.
- *
- * @author <a href="mailto:dev@felix.apache.org">Felix Project Team</a>
- */
-public final class DefaultNullObject implements InvocationHandler {
- private static final Boolean DEFAULT_BOOLEAN = Boolean.FALSE;
- private static final Byte DEFAULT_BYTE = new Byte((byte) 0);
- private static final Short DEFAULT_SHORT = new Short((short) 0);
- private static final Integer DEFAULT_INT = new Integer(0);
- private static final Long DEFAULT_LONG = new Long(0);
- private static final Float DEFAULT_FLOAT = new Float(0.0f);
- private static final Double DEFAULT_DOUBLE = new Double(0.0);
-
- /**
- * Invokes a method on this null object. The method will return a default
- * value without doing anything.
- */
- public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
- Class returnType = method.getReturnType();
- if (returnType.equals(Boolean.class) || returnType.equals(Boolean.TYPE)) {
- return DEFAULT_BOOLEAN;
- }
- else if (returnType.equals(Byte.class) || returnType.equals(Byte.TYPE)) {
- return DEFAULT_BYTE;
- }
- else if (returnType.equals(Short.class) || returnType.equals(Short.TYPE)) {
- return DEFAULT_SHORT;
- }
- else if (returnType.equals(Integer.class) || returnType.equals(Integer.TYPE)) {
- return DEFAULT_INT;
- }
- else if (returnType.equals(Long.class) || returnType.equals(Long.TYPE)) {
- return DEFAULT_LONG;
- }
- else if (returnType.equals(Float.class) || returnType.equals(Float.TYPE)) {
- return DEFAULT_FLOAT;
- }
- else if (returnType.equals(Double.class) || returnType.equals(Double.TYPE)) {
- return DEFAULT_DOUBLE;
- }
- else {
- return null;
- }
- }
-}
\ No newline at end of file
diff --git a/dependencymanager/core/src/main/java/org/apache/felix/dm/impl/FactoryConfigurationAdapterServiceImpl.java b/dependencymanager/core/src/main/java/org/apache/felix/dm/impl/FactoryConfigurationAdapterServiceImpl.java
deleted file mode 100644
index 350f189..0000000
--- a/dependencymanager/core/src/main/java/org/apache/felix/dm/impl/FactoryConfigurationAdapterServiceImpl.java
+++ /dev/null
@@ -1,296 +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.felix.dm.impl;
-
-import java.lang.reflect.Constructor;
-import java.lang.reflect.InvocationTargetException;
-import java.util.Dictionary;
-import java.util.Enumeration;
-import java.util.Hashtable;
-import java.util.List;
-
-import org.apache.felix.dm.Component;
-import org.apache.felix.dm.ComponentStateListener;
-import org.apache.felix.dm.Dependency;
-import org.apache.felix.dm.DependencyManager;
-import org.apache.felix.dm.InvocationUtil;
-import org.apache.felix.dm.PropertyMetaData;
-import org.apache.felix.dm.impl.metatype.MetaTypeProviderImpl;
-import org.osgi.framework.BundleContext;
-import org.osgi.framework.Constants;
-import org.osgi.service.cm.ManagedServiceFactory;
-import org.osgi.service.metatype.MetaTypeProvider;
-import org.osgi.service.metatype.ObjectClassDefinition;
-
-/**
- * Factory configuration adapter service implementation. This class extends the FilterService in order to catch
- * some Service methods for configuring actual adapter service implementation.
- *
- * @author <a href="mailto:dev@felix.apache.org">Felix Project Team</a>
- */
-public class FactoryConfigurationAdapterServiceImpl extends FilterService {
- // Our Managed Service Factory PID
- protected final String m_factoryPid;
-
- public FactoryConfigurationAdapterServiceImpl(DependencyManager dm, String factoryPid, String update, boolean propagate) {
- super(dm.createComponent()); // This service will be filtered by our super class, allowing us to take control.
- m_factoryPid = factoryPid;
-
- Hashtable props = new Hashtable();
- props.put(Constants.SERVICE_PID, factoryPid);
- m_component
- .setInterface(ManagedServiceFactory.class.getName(), props)
- .setImplementation(new AdapterImpl(update, propagate))
- .setCallbacks("init", null, "stop", null);
- }
-
- public FactoryConfigurationAdapterServiceImpl(DependencyManager dm, String factoryPid, String update, boolean propagate,
- BundleContext bctx, Logger logger, String heading, String description, String localization, PropertyMetaData[] properyMetaData) {
- super(dm.createComponent()); // This service will be filtered by our super class, allowing us to take control.
- m_factoryPid = factoryPid;
- Hashtable props = new Hashtable();
- props.put(Constants.SERVICE_PID, factoryPid);
- m_component
- .setInterface(ManagedServiceFactory.class.getName(), props)
- .setImplementation(new MetaTypeAdapterImpl(update, propagate,
- bctx, logger, heading, description,
- localization, properyMetaData))
- .setCallbacks("init", null, "stop", null);
- }
-
- public String getName() {
- return "Adapter for factory pid " + m_factoryPid;
- }
-
- /**
- * Creates, updates, or removes a service, when a ConfigAdmin factory configuration is created/updated or deleted.
- */
- public class AdapterImpl extends AbstractDecorator implements ManagedServiceFactory {
- // The adapter "update" method used to provide the configuration
- protected final String m_update;
-
- // Tells if the CM config must be propagated along with the adapter service properties
- protected final boolean m_propagate;
-
- /**
- * Creates a new CM factory configuration adapter.
- *
- * @param factoryPid
- * @param updateMethod
- * @param adapterInterface
- * @param adapterImplementation
- * @param adapterProperties
- * @param propagate
- */
- public AdapterImpl(String updateMethod, boolean propagate) {
- m_update = updateMethod;
- m_propagate = propagate;
- }
-
- /**
- * Returns the managed service factory name.
- */
- public String getName() {
- return m_factoryPid;
- }
-
- /**
- * Method called from our superclass, when we need to create a service.
- */
- public Component createService(Object[] properties) {
- Dictionary settings = (Dictionary) properties[0];
- Component newService = m_manager.createComponent();
- Object impl = null;
-
- try {
- if (m_serviceImpl != null) {
- impl = (m_serviceImpl instanceof Class) ? ((Class) m_serviceImpl).newInstance() : m_serviceImpl;
- }
- else {
- impl = instantiateFromFactory(m_factory, m_factoryCreateMethod);
- }
- InvocationUtil.invokeCallbackMethod(impl, m_update,
- new Class[][] {{ Dictionary.class }, {}},
- new Object[][] {{ settings }, {}});
- }
-
- catch (Throwable t) {
- handleException(t);
- }
-
- // Merge adapter service properties, with CM settings
- Dictionary serviceProperties = getServiceProperties(settings);
- newService.setInterface(m_serviceInterfaces, serviceProperties);
- newService.setImplementation(impl);
- newService.setComposition(m_compositionInstance, m_compositionMethod); // if not set, no effect
- newService.setCallbacks(m_callbackObject, m_init, m_start, m_stop, m_destroy); // if not set, no effect
- configureAutoConfigState(newService, m_component);
-
- List dependencies = m_component.getDependencies();
- for (int i = 0; i < dependencies.size(); i++) {
- newService.add(((Dependency) dependencies.get(i)).createCopy());
- }
-
- for (int i = 0; i < m_stateListeners.size(); i ++) {
- newService.addStateListener((ComponentStateListener) m_stateListeners.get(i));
- }
-
- return newService;
- }
-
- /**
- * Method called from our superclass, when we need to update a Service, because
- * the configuration has changed.
- */
- public void updateService(Object[] properties) {
- Dictionary cmSettings = (Dictionary) properties[0];
- Component service = (Component) properties[1];
- Object impl = service.getService();
-
- try {
- InvocationUtil.invokeCallbackMethod(impl, m_update,
- new Class[][] {{ Dictionary.class }, {}},
- new Object[][] {{ cmSettings }, {}});
- if (m_serviceInterfaces != null && m_propagate == true) {
- Dictionary serviceProperties = getServiceProperties(cmSettings);
- service.setServiceProperties(serviceProperties);
- }
- }
-
- catch (Throwable t) {
- handleException(t);
- }
- }
-
- /**
- * Merge CM factory configuration setting with the adapter service properties. The private CM factory configuration
- * settings are ignored. A CM factory configuration property is private if its name starts with a dot (".").
- *
- * @param adapterProperties
- * @param settings
- * @return
- */
- private Dictionary getServiceProperties(Dictionary settings) {
- Dictionary props = new Hashtable();
-
- // Add adapter Service Properties
- if (m_serviceProperties != null) {
- Enumeration keys = m_serviceProperties.keys();
- while (keys.hasMoreElements()) {
- Object key = keys.nextElement();
- Object val = m_serviceProperties.get(key);
- props.put(key, val);
- }
- }
-
- if (m_propagate) {
- // Add CM setting into adapter service properties.
- // (CM setting will override existing adapter service properties).
- Enumeration keys = settings.keys();
- while (keys.hasMoreElements()) {
- Object key = keys.nextElement();
- if (! key.toString().startsWith(".")) {
- // public properties are propagated
- Object val = settings.get(key);
- props.put(key, val);
- }
- }
- }
-
-
- return props;
- }
-
- private Object instantiateFromFactory(Object mFactory, String mFactoryCreateMethod) {
- Object factory = null;
- if (m_factory instanceof Class) {
- try {
- factory = createInstance((Class) m_factory);
- }
- catch (Throwable t) {
- handleException(t);
- }
- }
- else {
- factory = m_factory;
- }
-
- try {
- return InvocationUtil.invokeMethod(factory, factory.getClass(), m_factoryCreateMethod, new Class[][] { {} }, new Object[][] { {} }, false);
- }
- catch (Throwable t) {
- handleException(t);
- return null;
- }
- }
-
- private Object createInstance(Class clazz) throws SecurityException, NoSuchMethodException, InstantiationException, IllegalAccessException {
- Constructor constructor = clazz.getConstructor(new Class[] {});
- constructor.setAccessible(true);
- return clazz.newInstance();
- }
-
- private void handleException(Throwable t) {
- if (t instanceof InvocationTargetException) {
- // Our super class will check if the target exception is itself a ConfigurationException.
- // In this case, it will simply re-thrown.
- throw new RuntimeException(((InvocationTargetException) t).getTargetException());
- }
- else if (t instanceof RuntimeException) {
- throw (RuntimeException) t;
- }
- else {
- throw new RuntimeException(t);
- }
- }
- }
-
-
- /**
- * Extends AdapterImpl for MetaType support.
- */
- class MetaTypeAdapterImpl extends AdapterImpl implements MetaTypeProvider {
- // Our MetaType Provider for describing our properties metadata
- private final MetaTypeProviderImpl m_metaType;
-
- public MetaTypeAdapterImpl(String updateMethod, boolean propagate,
- BundleContext bctx, Logger logger, String heading,
- String description, String localization,
- PropertyMetaData[] properyMetaData) {
- super(updateMethod, propagate);
- m_metaType = new MetaTypeProviderImpl(m_factoryPid, bctx, logger, null, this);
- m_metaType.setName(heading);
- m_metaType.setDescription(description);
- if (localization != null) {
- m_metaType.setLocalization(localization);
- }
- for (int i = 0; i < properyMetaData.length; i++) {
- m_metaType.add(properyMetaData[i]);
- }
- }
-
- public String[] getLocales() {
- return m_metaType.getLocales();
- }
-
- public ObjectClassDefinition getObjectClassDefinition(String id, String locale) {
- return m_metaType.getObjectClassDefinition(id, locale);
- }
- }
-}
diff --git a/dependencymanager/core/src/main/java/org/apache/felix/dm/impl/FilterService.java b/dependencymanager/core/src/main/java/org/apache/felix/dm/impl/FilterService.java
deleted file mode 100644
index 38e7760..0000000
--- a/dependencymanager/core/src/main/java/org/apache/felix/dm/impl/FilterService.java
+++ /dev/null
@@ -1,288 +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.felix.dm.impl;
-
-import java.util.ArrayList;
-import java.util.Dictionary;
-import java.util.Iterator;
-import java.util.List;
-
-import org.apache.felix.dm.Component;
-import org.apache.felix.dm.ComponentDeclaration;
-import org.apache.felix.dm.ComponentDependencyDeclaration;
-import org.apache.felix.dm.ComponentStateListener;
-import org.apache.felix.dm.Dependency;
-import org.apache.felix.dm.DependencyManager;
-import org.osgi.framework.BundleContext;
-import org.osgi.framework.ServiceRegistration;
-
-/**
- * This class allows to filter a Component interface. All Aspect/Adapters extend this class
- * in order to add functionality to the default Component implementation.
- *
- * @author <a href="mailto:dev@felix.apache.org">Felix Project Team</a>
- */
-public class FilterService implements Component, ComponentDeclaration {
- protected ComponentImpl m_component;
- protected List m_stateListeners = new ArrayList();
- protected String m_init = "init";
- protected String m_start = "start";
- protected String m_stop = "stop";
- protected String m_destroy = "destroy";
- protected Object m_callbackObject;
- protected Object m_compositionInstance;
- protected String m_compositionMethod;
- protected String[] m_serviceInterfaces;
- protected Object m_serviceImpl;
- protected Object m_factory;
- protected String m_factoryCreateMethod;
- protected Dictionary m_serviceProperties;
-
- public FilterService(Component service) {
- m_component = (ComponentImpl) service;
- }
-
- public Component add(Dependency dependency) {
- m_component.add(dependency);
- // Add the dependency (if optional) to all already instantiated services.
- // If the dependency is required, our internal service will be stopped/restarted, so in this case
- // we have nothing to do.
- if (! dependency.isRequired()) {
- AbstractDecorator ad = (AbstractDecorator) m_component.getService();
- if (ad != null)
- {
- ad.addDependency(dependency);
- }
- }
- return this;
- }
-
- public Component add(List dependencies) {
- m_component.add(dependencies);
- // Add the dependencies to all already instantiated services.
- // If one dependency from the list is required, we have nothing to do, since our internal
- // service will be stopped/restarted.
- Iterator it = dependencies.iterator();
- while (it.hasNext()) {
- if (((Dependency) it.next()).isRequired()) {
- return this;
- }
- }
- // Ok, the list contains no required dependencies: add optionals dependencies in already instantiated
- // services.
- AbstractDecorator ad = (AbstractDecorator) m_component.getService();
- if (ad != null) {
- ad.addDependencies(dependencies);
- }
- return this;
- }
-
- public void addStateListener(ComponentStateListener listener) {
- synchronized (this) {
- m_stateListeners.add(listener);
- }
- // Add the listener to all already instantiated services.
- AbstractDecorator ad = (AbstractDecorator) m_component.getService();
- if (ad != null) {
- ad.addStateListener(listener);
- }
- }
-
- public List getDependencies() {
- return m_component.getDependencies();
- }
-
- public Object getService() {
- return m_component.getService();
- }
-
- public String getClassName() {
- return m_component.getClassName();
- }
-
- public synchronized Dictionary getServiceProperties() {
- return m_serviceProperties;
- }
-
- public ServiceRegistration getServiceRegistration() {
- return m_component.getServiceRegistration();
- }
-
- public Component remove(Dependency dependency) {
- m_component.remove(dependency);
- // Remove the dependency (if optional) from all already instantiated services.
- // If the dependency is required, our internal service will be stopped, so in this case
- // we have nothing to do.
- if (!dependency.isRequired())
- {
- AbstractDecorator ad = (AbstractDecorator) m_component.getService();
- if (ad != null)
- {
- ad.removeDependency(dependency);
- }
- }
- return this;
- }
-
- public void removeStateListener(ComponentStateListener listener) {
- synchronized (this) {
- m_stateListeners.remove(listener);
- }
- // Remove the listener from all already instantiated services.
- AbstractDecorator ad = (AbstractDecorator) m_component.getService();
- if (ad != null) {
- ad.removeStateListener(listener);
- }
- }
-
- public synchronized Component setCallbacks(Object instance, String init, String start, String stop, String destroy) {
- m_component.ensureNotActive();
- m_callbackObject = instance;
- m_init = init;
- m_start = start;
- m_stop = stop;
- m_destroy = destroy;
- return this;
- }
-
- public Component setCallbacks(String init, String start, String stop, String destroy) {
- setCallbacks(null, init, start, stop, destroy);
- return this;
- }
-
- public synchronized Component setComposition(Object instance, String getMethod) {
- m_component.ensureNotActive();
- m_compositionInstance = instance;
- m_compositionMethod = getMethod;
- return this;
- }
-
- public synchronized Component setComposition(String getMethod) {
- m_component.ensureNotActive();
- m_compositionMethod = getMethod;
- return this;
- }
-
- public synchronized Component setFactory(Object factory, String createMethod) {
- m_component.ensureNotActive();
- m_factory = factory;
- m_factoryCreateMethod = createMethod;
- return this;
- }
-
- public Component setFactory(String createMethod) {
- return setFactory(null, createMethod);
- }
-
- public synchronized Component setImplementation(Object implementation) {
- m_component.ensureNotActive();
- m_serviceImpl = implementation;
- return this;
- }
-
- public Component setInterface(String serviceName, Dictionary properties) {
- return setInterface(new String[] { serviceName }, properties);
- }
-
- public synchronized Component setInterface(String[] serviceInterfaces, Dictionary properties) {
- m_component.ensureNotActive();
- if (serviceInterfaces != null) {
- m_serviceInterfaces = new String[serviceInterfaces.length];
- System.arraycopy(serviceInterfaces, 0, m_serviceInterfaces, 0, serviceInterfaces.length);
- m_serviceProperties = properties;
- }
- return this;
- }
-
- public Component setServiceProperties(Dictionary serviceProperties) {
- synchronized (this) {
- m_serviceProperties = serviceProperties;
- }
- // Set the properties to all already instantiated services.
- if (serviceProperties != null) {
- AbstractDecorator ad = (AbstractDecorator) m_component.getService();
- if (ad != null) {
- ad.setServiceProperties(serviceProperties);
- }
- }
- return this;
- }
-
- public void start() {
- m_component.start();
- }
-
- public void stop() {
- m_component.stop();
- }
-
- public void invokeCallbackMethod(Object[] instances, String methodName, Class[][] signatures, Object[][] parameters) {
- m_component.invokeCallbackMethod(instances, methodName, signatures, parameters);
- }
-
- public Object[] getCompositionInstances() {
- return m_component.getCompositionInstances();
- }
-
- public DependencyManager getDependencyManager() {
- return m_component.getDependencyManager();
- }
-
- public Component setAutoConfig(Class clazz, boolean autoConfig) {
- m_component.setAutoConfig(clazz, autoConfig);
- return this;
- }
-
- public Component setAutoConfig(Class clazz, String instanceName) {
- m_component.setAutoConfig(clazz, instanceName);
- return this;
- }
-
- public boolean getAutoConfig(Class clazz) {
- return m_component.getAutoConfig(clazz);
- }
-
- public String getAutoConfigInstance(Class clazz) {
- return m_component.getAutoConfigInstance(clazz);
- }
-
- public ComponentDependencyDeclaration[] getComponentDependencies() {
- return m_component.getComponentDependencies();
- }
-
- public String getName() {
- return m_component.getName();
- }
-
- public int getState() {
- return m_component.getState();
- }
-
- public long getId() {
- return m_component.getId();
- }
-
- public String[] getServices() {
- return m_component.getServices();
- }
-
- public BundleContext getBundleContext() {
- return m_component.getBundleContext();
- };
-}
\ No newline at end of file
diff --git a/dependencymanager/core/src/main/java/org/apache/felix/dm/impl/Logger.java b/dependencymanager/core/src/main/java/org/apache/felix/dm/impl/Logger.java
deleted file mode 100644
index eb7e146..0000000
--- a/dependencymanager/core/src/main/java/org/apache/felix/dm/impl/Logger.java
+++ /dev/null
@@ -1,235 +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.felix.dm.impl;
-
-import java.lang.reflect.InvocationTargetException;
-import java.lang.reflect.Method;
-
-import org.apache.felix.dm.DependencyManager;
-import org.osgi.framework.BundleContext;
-import org.osgi.framework.BundleException;
-import org.osgi.framework.FrameworkUtil;
-import org.osgi.framework.InvalidSyntaxException;
-import org.osgi.framework.ServiceEvent;
-import org.osgi.framework.ServiceListener;
-import org.osgi.framework.ServiceReference;
-
-/**
- * This class mimics the standard OSGi <tt>LogService</tt> interface. An
- * instance of this class is used by the dependency manager for all logging.
- * By default this class logs messages to standard out. The log level can be set to
- * control the amount of logging performed, where a higher number results in
- * more logging. A log level of zero turns off logging completely.
- *
- * The log levels match those specified in the OSGi Log Service.
- * This class also tracks log services and will use the highest ranking
- * log service, if present, as a back end instead of printing to standard
- * out. The class uses reflection to invoking the log service's method to
- * avoid a dependency on the log interface, which is also why it does not
- * actually implement <code>LogService</code>. This class is in many ways
- * similar to the one used in the system bundle for that same purpose.
- *
- * @author <a href="mailto:dev@felix.apache.org">Felix Project Team</a>
- */
-public class Logger implements ServiceListener {
- private static final String LOG_SINGLE_CONTEXT = "org.apache.felix.dependencymanager.singleContextLog";
- public static final int LOG_ERROR = 1;
- public static final int LOG_WARNING = 2;
- public static final int LOG_INFO = 3;
- public static final int LOG_DEBUG = 4;
-
- private final BundleContext m_context;
-
- private final static int LOGGER_OBJECT_IDX = 0;
- private final static int LOGGER_METHOD_IDX = 1;
- private ServiceReference m_logRef = null;
- private Object[] m_logger = null;
-
- public Logger(BundleContext context) {
- if ("true".equals(System.getProperty(LOG_SINGLE_CONTEXT))) {
- m_context = FrameworkUtil.getBundle(DependencyManager.class).getBundleContext();
- } else {
- m_context = context;
- }
- startListeningForLogService();
- }
-
- public final void log(int level, String msg) {
- _log(null, level, msg, null);
- }
-
- public final void log(int level, String msg, Throwable throwable) {
- _log(null, level, msg, throwable);
- }
-
- public final void log(ServiceReference sr, int level, String msg) {
- _log(sr, level, msg, null);
- }
-
- public final void log(ServiceReference sr, int level, String msg, Throwable throwable) {
- _log(sr, level, msg, throwable);
- }
-
- protected void doLog(ServiceReference sr, int level, String msg, Throwable throwable) {
- String s = (sr == null) ? null : "SvcRef " + sr;
- s = (s == null) ? msg : s + " " + msg;
- s = (throwable == null) ? s : s + " (" + throwable + ")";
- switch (level) {
- case LOG_DEBUG:
- System.out.println("DEBUG: " + s);
- break;
- case LOG_ERROR:
- System.out.println("ERROR: " + s);
- if (throwable != null) {
- if ((throwable instanceof BundleException) && (((BundleException) throwable).getNestedException() != null)) {
- throwable = ((BundleException) throwable).getNestedException();
- }
- throwable.printStackTrace();
- }
- break;
- case LOG_INFO:
- System.out.println("INFO: " + s);
- break;
- case LOG_WARNING:
- System.out.println("WARNING: " + s);
- break;
- default:
- System.out.println("UNKNOWN[" + level + "]: " + s);
- }
- }
-
- private void _log(ServiceReference sr, int level, String msg, Throwable throwable) {
- // Save our own copy just in case it changes. We could try to do
- // more conservative locking here, but let's be optimistic.
- Object[] logger = m_logger;
- // Use the log service if available.
- if (logger != null) {
- _logReflectively(logger, sr, level, msg, throwable);
- }
- // Otherwise, default logging action.
- else {
- doLog(sr, level, msg, throwable);
- }
- }
-
- private void _logReflectively(Object[] logger, ServiceReference sr, int level, String msg, Throwable throwable) {
- if (logger != null) {
- Object[] params = { sr, new Integer(level), msg, throwable };
- try {
- ((Method) logger[LOGGER_METHOD_IDX]).invoke(logger[LOGGER_OBJECT_IDX], params);
- }
- catch (InvocationTargetException ex) {
- System.err.println("Logger: " + ex);
- }
- catch (IllegalAccessException ex) {
- System.err.println("Logger: " + ex);
- }
- }
- }
-
- /**
- * This method is called when the bundle context is set;
- * it simply adds a service listener so that the bundle can track
- * log services to be used as the back end of the logging mechanism. It also
- * attempts to get an existing log service, if present, but in general
- * there will never be a log service present since the system bundle is
- * started before every other bundle.
- */
- private synchronized void startListeningForLogService() {
- try {
- // add a service listener for log services, carefully avoiding any code dependency on it
- m_context.addServiceListener(this, "(objectClass=org.osgi.service.log.LogService)");
- }
- catch (InvalidSyntaxException ex) {
- // this will never happen since the filter is hard coded
- }
- // try to get an existing log service
- m_logRef = m_context.getServiceReference("org.osgi.service.log.LogService");
- // get the service object if available and set it in the logger
- if (m_logRef != null) {
- setLogger(m_context.getService(m_logRef));
- }
- }
-
- /**
- * This method implements the callback for the ServiceListener interface.
- * It is public as a byproduct of implementing the interface and should
- * not be called directly. This method tracks run-time changes to log
- * service availability. If the log service being used by the framework's
- * logging mechanism goes away, then this will try to find an alternative.
- * If a higher ranking log service is registered, then this will switch
- * to the higher ranking log service.
- */
- public final synchronized void serviceChanged(ServiceEvent event) {
- // if no logger is in use, then grab this one
- if ((event.getType() == ServiceEvent.REGISTERED) && (m_logRef == null)) {
- m_logRef = event.getServiceReference();
- // get the service object and set it in the logger
- setLogger(m_context.getService(m_logRef));
- }
- // if a logger is in use, but this one has a higher ranking, then swap
- // it for the existing logger
- else if ((event.getType() == ServiceEvent.REGISTERED) && (m_logRef != null)) {
- ServiceReference ref = m_context.getServiceReference("org.osgi.service.log.LogService");
- if (!ref.equals(m_logRef)) {
- m_context.ungetService(m_logRef);
- m_logRef = ref;
- setLogger(m_context.getService(m_logRef));
- }
- }
- // if the current logger is going away, release it and try to
- // find another one
- else if ((event.getType() == ServiceEvent.UNREGISTERING) && m_logRef != null && m_logRef.equals(event.getServiceReference())) {
- // Unget the service object.
- m_context.ungetService(m_logRef);
- // Try to get an existing log service.
- m_logRef = m_context.getServiceReference("org.osgi.service.log.LogService");
- // get the service object if available and set it in the logger
- if (m_logRef != null) {
- setLogger(m_context.getService(m_logRef));
- }
- else {
- setLogger(null);
- }
- }
- }
-
- /**
- * This method sets the new log service object. It also caches the method to
- * invoke. The service object and method are stored in array to optimistically
- * eliminate the need to locking when logging.
- */
- private void setLogger(Object logObj) {
- if (logObj == null) {
- m_logger = null;
- }
- else {
- Class[] formalParams = { ServiceReference.class, Integer.TYPE, String.class, Throwable.class };
- try {
- Method logMethod = logObj.getClass().getMethod("log", formalParams);
- logMethod.setAccessible(true);
- m_logger = new Object[] { logObj, logMethod };
- }
- catch (NoSuchMethodException ex) {
- System.err.println("Logger: " + ex);
- m_logger = null;
- }
- }
- }
-}
\ No newline at end of file
diff --git a/dependencymanager/core/src/main/java/org/apache/felix/dm/impl/ResourceAdapterServiceImpl.java b/dependencymanager/core/src/main/java/org/apache/felix/dm/impl/ResourceAdapterServiceImpl.java
deleted file mode 100644
index b513924..0000000
--- a/dependencymanager/core/src/main/java/org/apache/felix/dm/impl/ResourceAdapterServiceImpl.java
+++ /dev/null
@@ -1,143 +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.felix.dm.impl;
-
-import java.net.URL;
-import java.util.Enumeration;
-import java.util.List;
-import java.util.Properties;
-
-import org.apache.felix.dm.Component;
-import org.apache.felix.dm.ComponentStateListener;
-import org.apache.felix.dm.Dependency;
-import org.apache.felix.dm.DependencyManager;
-import org.apache.felix.dm.ResourceDependency;
-
-/**
- * Resource adapter service implementation. This class extends the FilterService in order to catch
- * some Service methods for configuring actual resource adapter service implementation.
- *
- * @author <a href="mailto:dev@felix.apache.org">Felix Project Team</a>
- */
-public class ResourceAdapterServiceImpl extends FilterService {
- private Object m_callbackInstance = null;
- private String m_callbackChanged = "changed";
- private String m_callbackAdded = "setResource";
- private final String m_resourceFilter;
-
- /**
- * Creates a new Resource Adapter Service implementation.
- * @param dm the dependency manager used to create our internal adapter service
- */
- public ResourceAdapterServiceImpl(DependencyManager dm, String resourceFilter, boolean propagate, Object callbackInstance, String callbackSet, String callbackChanged) {
- super(dm.createComponent()); // This service will be filtered by our super class, allowing us to take control.
- m_callbackInstance = callbackInstance;
- m_callbackAdded = callbackSet;
- m_callbackChanged = callbackChanged;
- m_resourceFilter = resourceFilter;
- m_component.setImplementation(new ResourceAdapterImpl(propagate))
- .add(dm.createResourceDependency()
- .setFilter(resourceFilter)
- .setAutoConfig(false)
- .setCallbacks("added", "removed"))
- .setCallbacks("init", null, "stop", null);
- }
-
- public ResourceAdapterServiceImpl(DependencyManager dm, String resourceFilter, Object propagateCallbackInstance, String propagateCallbackMethod, Object callbackInstance, String callbackSet, String callbackChanged) {
- super(dm.createComponent()); // This service will be filtered by our super class, allowing us to take control.
- m_callbackInstance = callbackInstance;
- m_callbackAdded = callbackSet;
- m_callbackChanged = callbackChanged;
- m_resourceFilter = resourceFilter;
- m_component.setImplementation(new ResourceAdapterImpl(propagateCallbackInstance, propagateCallbackMethod))
- .add(dm.createResourceDependency()
- .setFilter(resourceFilter)
- .setAutoConfig(false)
- .setCallbacks("added", "removed"))
- .setCallbacks("init", null, "stop", null);
- }
-
- public String getName() {
- return "Resource Adapter" + ((m_resourceFilter != null) ? " with filter " + m_resourceFilter : "");
- }
-
- public class ResourceAdapterImpl extends AbstractDecorator {
- private final boolean m_propagate;
- private final Object m_propagateCallbackInstance;
- private final String m_propagateCallbackMethod;
-
- public ResourceAdapterImpl(boolean propagate) {
- this(propagate, null, null);
- }
-
- public ResourceAdapterImpl(Object propagateCallbackInstance, String propagateCallbackMethod) {
- this(true, propagateCallbackInstance, propagateCallbackMethod);
- }
-
- private ResourceAdapterImpl(boolean propagate, Object propagateCallbackInstance, String propagateCallbackMethod) {
- m_propagate = propagate;
- m_propagateCallbackInstance = propagateCallbackInstance;
- m_propagateCallbackMethod = propagateCallbackMethod;
- }
-
- public Component createService(Object[] properties) {
- URL resource = (URL) properties[0];
- Properties props = new Properties();
- if (m_serviceProperties != null) {
- Enumeration e = m_serviceProperties.keys();
- while (e.hasMoreElements()) {
- Object key = e.nextElement();
- props.put(key, m_serviceProperties.get(key));
- }
- }
- List dependencies = m_component.getDependencies();
- // the first dependency is always the dependency on the resource, which
- // will be replaced with a more specific dependency below
- dependencies.remove(0);
- ResourceDependency resourceDependency = m_manager.createResourceDependency()
- .setResource(resource)
- .setCallbacks(m_callbackInstance, m_callbackAdded, m_callbackChanged, null)
- .setAutoConfig(m_callbackAdded == null)
- .setRequired(true);
- if (m_propagateCallbackInstance != null && m_propagateCallbackMethod != null) {
- resourceDependency.setPropagate(m_propagateCallbackInstance, m_propagateCallbackMethod);
- } else {
- resourceDependency.setPropagate(m_propagate);
- }
- Component service = m_manager.createComponent()
- .setInterface(m_serviceInterfaces, props)
- .setImplementation(m_serviceImpl)
- .setFactory(m_factory, m_factoryCreateMethod) // if not set, no effect
- .setComposition(m_compositionInstance, m_compositionMethod) // if not set, no effect
- .setCallbacks(m_callbackObject, m_init, m_start, m_stop, m_destroy) // if not set, no effect
- .add(resourceDependency);
-
- configureAutoConfigState(service, m_component);
-
- for (int i = 0; i < dependencies.size(); i++) {
- service.add(((Dependency) dependencies.get(i)).createCopy());
- }
-
- for (int i = 0; i < m_stateListeners.size(); i ++) {
- service.addStateListener((ComponentStateListener) m_stateListeners.get(i));
- }
- return service;
- }
- }
-}
diff --git a/dependencymanager/core/src/main/java/org/apache/felix/dm/impl/SerialExecutor.java b/dependencymanager/core/src/main/java/org/apache/felix/dm/impl/SerialExecutor.java
deleted file mode 100644
index ea6fe3a..0000000
--- a/dependencymanager/core/src/main/java/org/apache/felix/dm/impl/SerialExecutor.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.felix.dm.impl;
-
-import java.util.concurrent.ConcurrentLinkedQueue;
-import java.util.concurrent.Executor;
-import java.util.concurrent.atomic.AtomicReference;
-
-import org.osgi.service.log.LogService;
-
-/**
- * Allows you to enqueue tasks from multiple threads and then execute
- * them on one thread sequentially. It assumes more than one thread will
- * try to execute the tasks and it will make an effort to pick the first
- * task that comes along whilst making sure subsequent tasks return
- * without waiting. <p>
- *
- * This class is lock free and ensures "safe object publication" between scheduling threads and
- * actual executing thread: if one thread T1 schedules a task, but another thread T2 actually
- * executes it, then all the objects from the T1 thread will be "safely published" to the executing T2 thread.
- * Safe publication is ensured because we are using a ConcurrentLinkedQueue.
- * (see [1], chapter 3.5.3 (Safe publication idioms).
- *
- * [1] Java Concurrency In Practice, Addison Wesley
- *
- * @author <a href="mailto:dev@felix.apache.org">Felix Project Team</a>
- */
-public class SerialExecutor implements Executor {
- /**
- * All tasks scheduled are stored there and only one thread may run them.
- **/
- protected final ConcurrentLinkedQueue m_tasks = new ConcurrentLinkedQueue();
-
- /**
- * Thread currently executing the task queue.
- **/
- protected final AtomicReference m_runningThread = new AtomicReference();
-
- /**
- * Logger used when a task execution throws an exception
- **/
- private final Logger m_logger;
-
- /**
- * Makes a new SerialExecutor
- * @param logger used when a task execution throws an exception. Can be null if no exception should be logger.
- */
- public SerialExecutor(Logger logger) {
- m_logger = logger;
- }
-
- /**
- * Enqueues a task for later execution. You must call {@link #execute()} in order
- * to trigger the task execution, which may or may not be executed by
- * your current thread.
- */
- public void enqueue(Runnable task) {
- m_tasks.add(task); // No need to synchronize, m_tasks is a concurrent linked queue.
- }
-
- /**
- * Executes any pending tasks, enqueued using the {@link SerialExecutor#schedule(Runnable)} method.
- * This method is thread safe, so multiple threads can try to execute the pending
- * tasks, but only the first will be used to actually do so. Other threads will return immediately.
- */
- public void execute() {
- Thread currentThread = Thread.currentThread();
- if (m_runningThread.compareAndSet(null, currentThread)) {
- runTasks(currentThread);
- }
- }
-
- /**
- * Schedules a task for execution, and then attempts to execute it. This method is thread safe, so
- * multiple threads can try to execute a task but only the first will be executed, other threads will
- * return immediately, and the first thread will execute the tasks scheduled by the other threads.<p>
- * <p>
- * This method is reentrant: if the current thread is currently being executed by this executor, then
- * the task passed to this method will be executed immediately, from the current invoking thread
- * (inline execution).
- */
- public void execute(Runnable task) {
- Thread currentThread = Thread.currentThread();
- if (m_runningThread.get() == currentThread) {
- runTask(task);
- } else {
- enqueue(task);
- execute();
- }
- }
-
- /**
- * Run all pending tasks
- * @param currentRunninghread the current executing thread
- */
- private void runTasks(Thread currentRunninghread) {
- do {
- try {
- Runnable task;
- ConcurrentLinkedQueue tasks = m_tasks;
-
- while ((task = (Runnable) tasks.poll()) != null) {
- runTask(task);
- }
- }
- finally {
- m_runningThread.set(null);
- }
- }
- // We must test again if some tasks have been scheduled after our "while" loop above, but before the
- // m_runningThread reference has been reset to null.
- while (!m_tasks.isEmpty() && m_runningThread.compareAndSet(null, currentRunninghread));
- }
-
- /**
- * Run a given task.
- * @param task the task to execute.
- */
- void runTask(Runnable command) {
- try {
- command.run();
- }
- catch (Throwable t) {
- if (m_logger != null) {
- m_logger.log(LogService.LOG_ERROR, "Error processing tasks", t);
- } else {
- t.printStackTrace();
- }
- }
- }
-
- public String toString() {
- return "[Executor: queue size: " + m_tasks.size() + "]";
- }
-}
diff --git a/dependencymanager/core/src/main/java/org/apache/felix/dm/impl/ServiceRegistrationImpl.java b/dependencymanager/core/src/main/java/org/apache/felix/dm/impl/ServiceRegistrationImpl.java
deleted file mode 100644
index a3a45d7..0000000
--- a/dependencymanager/core/src/main/java/org/apache/felix/dm/impl/ServiceRegistrationImpl.java
+++ /dev/null
@@ -1,98 +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.felix.dm.impl;
-
-import java.util.Dictionary;
-
-import org.osgi.framework.ServiceReference;
-import org.osgi.framework.ServiceRegistration;
-
-/**
- * A wrapper around a service registration that blocks until the
- * service registration is available.
- *
- * @author <a href="mailto:dev@felix.apache.org">Felix Project Team</a>
- */
-public final class ServiceRegistrationImpl implements ServiceRegistration {
- public static final ServiceRegistrationImpl ILLEGAL_STATE = new ServiceRegistrationImpl();
- private volatile ServiceRegistration m_registration;
-
- public ServiceRegistrationImpl() {
- m_registration = null;
- }
-
- public ServiceReference getReference() {
- return ensureRegistration().getReference();
- }
-
- public void setProperties(Dictionary dictionary) {
- ensureRegistration().setProperties(dictionary);
- }
-
- public void unregister() {
- ensureRegistration().unregister();
- }
-
- public boolean equals(Object obj) {
- return ensureRegistration().equals(obj);
- }
-
- public int hashCode() {
- return ensureRegistration().hashCode();
- }
-
- public String toString() {
- return ensureRegistration().toString();
- }
-
- private synchronized ServiceRegistration ensureRegistration() {
- while (m_registration == null) {
- try {
- wait();
- }
- catch (InterruptedException ie) {
- // we were interrupted so hopefully we will now have a
- // service registration ready; if not we wait again
- }
- }
- // check if we're in an illegal state and throw an exception
- if (ILLEGAL_STATE == m_registration) {
- throw new IllegalStateException("Service is not registered.");
- }
- return m_registration;
- }
-
- /**
- * Sets the service registration and notifies all waiting parties.
- */
- void setServiceRegistration(ServiceRegistration registration) {
- synchronized (this) {
- m_registration = registration;
- notifyAll();
- }
- }
-
- /**
- * Sets this wrapper to an illegal state, which will cause all threads
- * that are waiting for this service registration to fail.
- */
- void setIllegalState() {
- setServiceRegistration(ServiceRegistrationImpl.ILLEGAL_STATE);
- }
-}
diff --git a/dependencymanager/core/src/main/java/org/apache/felix/dm/impl/State.java b/dependencymanager/core/src/main/java/org/apache/felix/dm/impl/State.java
deleted file mode 100644
index 9094a8b..0000000
--- a/dependencymanager/core/src/main/java/org/apache/felix/dm/impl/State.java
+++ /dev/null
@@ -1,133 +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.felix.dm.impl;
-
-import java.util.List;
-
-import org.apache.felix.dm.Dependency;
-
-/**
- * Encapsulates the current state of the dependencies of a service. A state is
- * basically an immutable value object.
- *
- * @author <a href="mailto:dev@felix.apache.org">Felix Project Team</a>
- */
-public final class State {
- private static final String[] STATES = { "?", "inactive", "waiting for required", "tracking optional", "bound", "waiting for required (instantiated)" };
- private static final int INACTIVE = 1;
- private static final int WAITING_FOR_REQUIRED = 2;
- private static final int TRACKING_OPTIONAL = 3;
- private static final int BOUND = 4;
- private static final int WAITING_FOR_REQUIRED_INSTANTIATED = 5;
- private final List m_deps;
- private final int m_state;
- private String m_stringValue;
-
- /**
- * Creates a new state instance.
- *
- * @param deps the dependencies that determine the state
- * @param isActive <code>true</code> if the service is active (started)
- */
- public State(List deps, boolean isActive, boolean isInstantiated, boolean isBound /* unused? */) {
- m_deps = deps;
- // only bother calculating dependencies if we're active
- if (isActive) {
- boolean allRequiredAvailable = true;
- boolean keepInstanceAround = isInstantiated;
- for (int i = 0; i < deps.size(); i++) {
- Dependency dep = (Dependency) deps.get(i);
- if (dep.isRequired()) {
- if (!dep.isAvailable()) {
- allRequiredAvailable = false;
- if (!dep.isInstanceBound()) {
- keepInstanceAround = false;
- }
- }
- }
- }
- if (allRequiredAvailable) {
- if (isInstantiated) {
- m_state = BOUND;
- }
- else {
- m_state = TRACKING_OPTIONAL;
- }
- }
- else {
- if (keepInstanceAround) {
- m_state = WAITING_FOR_REQUIRED_INSTANTIATED;
- }
- else {
- m_state = WAITING_FOR_REQUIRED;
- }
- }
- }
- else {
- m_state = INACTIVE;
- }
- }
-
- public boolean isInactive() {
- return m_state == INACTIVE;
- }
-
- public boolean isWaitingForRequired() {
- return m_state == WAITING_FOR_REQUIRED;
- }
-
- public boolean isTrackingOptional() {
- return m_state == TRACKING_OPTIONAL;
- }
-
- public boolean isBound() {
- return m_state == BOUND;
- }
-
- public boolean isAllRequiredAvailable() {
- return isTrackingOptional() || isBound();
- }
-
- public boolean isWaitingForRequiredInstantiated() {
- return m_state == WAITING_FOR_REQUIRED_INSTANTIATED;
- }
-
- public List getDependencies() {
- return m_deps;
- }
-
- public synchronized String toString() {
- if (m_stringValue == null) {
- // we only need to determine this once, but we do it lazily
- StringBuffer buf = new StringBuffer();
- buf.append("State[" + STATES[m_state]);
- List deps = m_deps;
- for (int i = 0; i < deps.size(); i++) {
- if (i == 0) {
- buf.append("|");
- }
- Dependency dep = (Dependency) deps.get(i);
- buf.append("(" + (dep.isRequired() ? "Req " : " ") + (dep.isAvailable() ? "Avl " : " ") + (dep.isInstanceBound() ? "InB " : " ") + (dep.isPropagated() ? "Prp " : " ") + dep + ")");
- }
- buf.append("]");
- m_stringValue = buf.toString();
- }
- return m_stringValue;
- }
-}
diff --git a/dependencymanager/core/src/main/java/org/apache/felix/dm/impl/dependencies/BundleDependencyImpl.java b/dependencymanager/core/src/main/java/org/apache/felix/dm/impl/dependencies/BundleDependencyImpl.java
deleted file mode 100644
index b8b82c6..0000000
--- a/dependencymanager/core/src/main/java/org/apache/felix/dm/impl/dependencies/BundleDependencyImpl.java
+++ /dev/null
@@ -1,501 +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.felix.dm.impl.dependencies;
-
-import java.lang.reflect.InvocationTargetException;
-import java.lang.reflect.Proxy;
-import java.util.ArrayList;
-import java.util.Dictionary;
-import java.util.List;
-
-import org.apache.felix.dm.BundleDependency;
-import org.apache.felix.dm.ComponentDependencyDeclaration;
-import org.apache.felix.dm.Dependency;
-import org.apache.felix.dm.DependencyService;
-import org.apache.felix.dm.InvocationUtil;
-import org.apache.felix.dm.impl.DefaultNullObject;
-import org.apache.felix.dm.impl.Logger;
-import org.apache.felix.dm.tracker.BundleTracker;
-import org.apache.felix.dm.tracker.BundleTrackerCustomizer;
-import org.osgi.framework.Bundle;
-import org.osgi.framework.BundleContext;
-import org.osgi.framework.BundleEvent;
-import org.osgi.framework.Filter;
-import org.osgi.framework.InvalidSyntaxException;
-import org.osgi.service.log.LogService;
-
-/**
- * @author <a href="mailto:dev@felix.apache.org">Felix Project Team</a>
- */
-public class BundleDependencyImpl extends DependencyBase implements BundleDependency, BundleTrackerCustomizer, ComponentDependencyDeclaration {
- private final BundleContext m_context;
- private BundleTracker m_tracker;
- private int m_stateMask = Bundle.INSTALLED | Bundle.RESOLVED | Bundle.ACTIVE;
- private List m_services = new ArrayList();
- private boolean m_isAvailable;
- private Object m_callbackInstance;
- private String m_callbackAdded;
- private String m_callbackChanged;
- private String m_callbackRemoved;
- private boolean m_autoConfig;
- private Bundle m_bundleInstance;
- private Filter m_filter;
- private long m_bundleId = -1;
- private String m_autoConfigInstance;
- private Object m_nullObject;
- private boolean m_autoConfigInvoked;
- private boolean m_propagate;
- private Object m_propagateCallbackInstance;
- private String m_propagateCallbackMethod;
-
- public BundleDependencyImpl(BundleContext context, Logger logger) {
- super(logger);
- m_context = context;
- m_autoConfig = true;
- }
-
- public BundleDependencyImpl(BundleDependencyImpl prototype) {
- super(prototype);
- m_context = prototype.m_context;
- m_autoConfig = prototype.m_autoConfig;
- m_stateMask = prototype.m_stateMask;
- m_nullObject = prototype.m_nullObject;
- m_bundleInstance = prototype.m_bundleInstance;
- m_filter = prototype.m_filter;
- m_bundleId = prototype.m_bundleId;
- m_propagate = prototype.m_propagate;
- m_callbackInstance = prototype.m_callbackInstance;
- m_callbackAdded = prototype.m_callbackAdded;
- m_callbackChanged = prototype.m_callbackChanged;
- m_callbackRemoved = prototype.m_callbackRemoved;
- m_autoConfigInstance = prototype.m_autoConfigInstance;
- }
-
- public Dependency createCopy() {
- return new BundleDependencyImpl(this);
- }
-
- public BundleDependency setInstanceBound(boolean isInstanceBound) {
- setIsInstanceBound(isInstanceBound);
- return this;
- }
-
- public synchronized boolean isAvailable() {
- return m_isAvailable;
- }
-
- public void start(DependencyService service) {
- boolean needsStarting = false;
- synchronized (this) {
- m_services.add(service);
- if (!m_isStarted) {
- m_tracker = new BundleTracker(m_context, m_stateMask, this);
- m_isStarted = true;
- needsStarting = true;
- }
- }
- if (needsStarting) {
- m_tracker.open();
- }
- }
-
- public void stop(DependencyService service) {
- boolean needsStopping = false;
- synchronized (this) {
- if (m_services.size() == 1 && m_services.contains(service)) {
- m_isStarted = false;
- needsStopping = true;
- }
- }
- if (needsStopping) {
- m_tracker.close();
- m_tracker = null;
- m_services.remove(service);
- }
- }
-
- public String getName() {
- StringBuilder sb = new StringBuilder();
- if ((m_stateMask & Bundle.ACTIVE) != 0) {
- sb.append("active ");
- }
- if ((m_stateMask & Bundle.INSTALLED) != 0) {
- sb.append("installed ");
- }
- if ((m_stateMask & Bundle.RESOLVED) != 0) {
- sb.append("resolved ");
- }
- if (m_filter != null) {
- sb.append(m_filter.toString());
- }
- if (m_bundleId != -1) {
- sb.append("bundle.id=" + m_bundleId);
- }
- return sb.toString();
- }
-
- public String getType() {
- return "bundle";
- }
-
- public Object addingBundle(Bundle bundle, BundleEvent event) {
- // if we don't like a bundle, we could reject it here by returning null
- long bundleId = bundle.getBundleId();
- if (m_bundleId >= 0 && m_bundleId != bundleId) {
- return null;
- }
- Filter filter = m_filter;
- if (filter != null) {
- Dictionary headers = bundle.getHeaders();
- if (!m_filter.match(headers)) {
- return null;
- }
- }
- return bundle;
- }
-
- public void addedBundle(Bundle bundle, BundleEvent event, Object object) {
- boolean makeAvailable = makeAvailable();
- Object[] services = m_services.toArray();
- for (int i = 0; i < services.length; i++) {
- DependencyService ds = (DependencyService) services[i];
- if (makeAvailable) {
- ds.dependencyAvailable(this);
- if (!isRequired()) {
- invokeAdded(ds, bundle);
- }
- }
- else {
- ds.dependencyChanged(this);
- invokeAdded(ds, bundle);
- }
- }
- }
-
- public void modifiedBundle(Bundle bundle, BundleEvent event, Object object) {
- Object[] services = m_services.toArray();
- for (int i = 0; i < services.length; i++) {
- DependencyService ds = (DependencyService) services[i];
- ds.dependencyChanged(this);
- if (ds.isInstantiated()) {
- invokeChanged(ds, bundle);
- }
- }
- }
-
- public void removedBundle(Bundle bundle, BundleEvent event, Object object) {
- boolean makeUnavailable = makeUnavailable();
- Object[] services = m_services.toArray();
- for (int i = 0; i < services.length; i++) {
- DependencyService ds = (DependencyService) services[i];
- if (makeUnavailable) {
- ds.dependencyUnavailable(this);
- if (!isRequired()) {
- invokeRemoved(ds, bundle);
- }
- }
- else {
- ds.dependencyChanged(this);
- invokeRemoved(ds, bundle);
- }
- }
- }
-
- private synchronized boolean makeAvailable() {
- if (!isAvailable()) {
- m_isAvailable = true;
- return true;
- }
- return false;
- }
-
- private synchronized boolean makeUnavailable() {
- if ((isAvailable()) && (m_tracker.getTrackingCount() == 0)) {
- m_isAvailable = false;
- return true;
- }
- return false;
- }
-
- public void invokeAdded(DependencyService dependencyService, Bundle service) {
- invoke(dependencyService, service, m_callbackAdded);
- }
-
- public void invokeChanged(DependencyService dependencyService, Bundle service) {
- invoke(dependencyService, service, m_callbackChanged);
- }
-
- public void invokeRemoved(DependencyService dependencyService, Bundle service) {
- invoke(dependencyService, service, m_callbackRemoved);
- }
-
- public void invoke(DependencyService dependencyService, Bundle service, String name) {
- if (name != null) {
- dependencyService.invokeCallbackMethod(getCallbackInstances(dependencyService), name,
- new Class[][] {{Bundle.class}, {Object.class}, {}},
- new Object[][] {{service}, {service}, {}}
- );
- }
- }
-
- private synchronized Object[] getCallbackInstances(DependencyService dependencyService) {
- if (m_callbackInstance == null) {
- return dependencyService.getCompositionInstances();
- }
- else {
- return new Object[] { m_callbackInstance };
- }
- }
-
- /**
- * Sets the callbacks for this service. These callbacks can be used as hooks whenever a
- * dependency is added or removed. When you specify callbacks, the auto configuration
- * feature is automatically turned off, because we're assuming you don't need it in this
- * case.
- *
- * @param added the method to call when a service was added
- * @param removed the method to call when a service was removed
- * @return this service dependency
- */
- public synchronized BundleDependency setCallbacks(String added, String removed) {
- return setCallbacks(null, added, null, removed);
- }
-
- /**
- * Sets the callbacks for this service. These callbacks can be used as hooks whenever a
- * dependency is added, changed or removed. When you specify callbacks, the auto
- * configuration feature is automatically turned off, because we're assuming you don't
- * need it in this case.
- *
- * @param added the method to call when a service was added
- * @param changed the method to call when a service was changed
- * @param removed the method to call when a service was removed
- * @return this service dependency
- */
- public synchronized BundleDependency setCallbacks(String added, String changed, String removed) {
- return setCallbacks(null, added, changed, removed);
- }
-
- /**
- * Sets the callbacks for this service. These callbacks can be used as hooks whenever a
- * dependency is added or removed. They are called on the instance you provide. When you
- * specify callbacks, the auto configuration feature is automatically turned off, because
- * we're assuming you don't need it in this case.
- *
- * @param instance the instance to call the callbacks on
- * @param added the method to call when a service was added
- * @param removed the method to call when a service was removed
- * @return this service dependency
- */
- public synchronized BundleDependency setCallbacks(Object instance, String added, String removed) {
- return setCallbacks(instance, added, null, removed);
- }
-
- /**
- * Sets the callbacks for this service. These callbacks can be used as hooks whenever a
- * dependency is added, changed or removed. They are called on the instance you provide. When you
- * specify callbacks, the auto configuration feature is automatically turned off, because
- * we're assuming you don't need it in this case.
- *
- * @param instance the instance to call the callbacks on
- * @param added the method to call when a service was added
- * @param changed the method to call when a service was changed
- * @param removed the method to call when a service was removed
- * @return this service dependency
- */
- public synchronized BundleDependency setCallbacks(Object instance, String added, String changed, String removed) {
- ensureNotActive();
- // if at least one valid callback is specified, we turn off auto configuration
- if ((added != null || removed != null || changed != null) && ! m_autoConfigInvoked) {
- setAutoConfig(false);
- }
- m_callbackInstance = instance;
- m_callbackAdded = added;
- m_callbackChanged = changed;
- m_callbackRemoved = removed;
- return this;
- }
-
- private void ensureNotActive() {
- if (m_tracker != null) {
- throw new IllegalStateException("Cannot modify state while active.");
- }
- }
- public synchronized BundleDependency setAutoConfig(boolean autoConfig) {
- ensureNotActive();
- m_autoConfig = autoConfig;
- m_autoConfigInvoked = true;
- return this;
- }
-
- public synchronized BundleDependency setAutoConfig(String instanceName) {
- ensureNotActive();
- m_autoConfig = (instanceName != null);
- m_autoConfigInstance = instanceName;
- m_autoConfigInvoked = true;
- return this;
- }
-
- public synchronized BundleDependency setRequired(boolean required) {
- ensureNotActive();
- setIsRequired(required);
- return this;
- }
-
- public BundleDependency setBundle(Bundle bundle) {
- m_bundleId = bundle.getBundleId();
- return this;
- }
-
- public BundleDependency setFilter(String filter) throws IllegalArgumentException {
- if (filter != null) {
- try {
- m_filter = m_context.createFilter(filter);
- }
- catch (InvalidSyntaxException e) {
- throw new IllegalArgumentException(e.getMessage());
- }
- }
- return this;
- }
-
- public BundleDependency setStateMask(int mask) {
- m_stateMask = mask;
- return this;
- }
-
- public synchronized boolean isAutoConfig() {
- return m_autoConfig;
- }
-
- public Bundle getBundle() {
- Bundle[] bundles = m_tracker.getBundles();
- if (bundles != null && bundles.length > 0) {
- return bundles[0];
- }
- return null;
- }
-
- public Object getAutoConfigInstance() {
- return lookupBundle();
- }
-
- public Bundle lookupBundle() {
- Bundle service = null;
- if (m_isStarted) {
- service = getBundle();
- }
- else {
- Bundle[] bundles = m_context.getBundles();
- for (int i = 0; i < bundles.length; i++) {
- if ((bundles[i].getState() & m_stateMask) > 0) {
- Filter filter = m_filter;
- if (filter == null) {
- service = bundles[i];
- break;
- }
- else if (filter.match(bundles[i].getHeaders())) {
- service = bundles[i];
- break;
- }
- }
- }
- }
- if (service == null && isAutoConfig()) {
- // TODO does it make sense to add support for custom bundle impls?
-// service = getDefaultImplementation();
- if (service == null) {
- service = getNullObject();
- }
- }
- return service;
- }
-
- private Bundle getNullObject() {
- if (m_nullObject == null) {
- try {
- m_nullObject = Proxy.newProxyInstance(getClass().getClassLoader(), new Class[] { Bundle.class }, new DefaultNullObject());
- }
- catch (Exception e) {
- m_logger.log(Logger.LOG_ERROR, "Could not create null object for Bundle.", e);
- }
- }
- return (Bundle) m_nullObject;
- }
-
- public String getAutoConfigName() {
- return m_autoConfigInstance;
- }
-
- public Class getAutoConfigType() {
- return Bundle.class;
- }
-
- public void invokeAdded(DependencyService service) {
- // we remember these for future reference, needed for required service callbacks
- m_bundleInstance = lookupBundle();
- invokeAdded(service, m_bundleInstance);
- }
-
- public void invokeRemoved(DependencyService service) {
- invokeRemoved(service, m_bundleInstance);
- m_bundleInstance = null;
- }
-
- public BundleDependency setPropagate(boolean propagate) {
- ensureNotActive();
- m_propagate = propagate;
- return this;
- }
-
- public BundleDependency setPropagate(Object instance, String method) {
- setPropagate(instance != null && method != null);
- m_propagateCallbackInstance = instance;
- m_propagateCallbackMethod = method;
- return this;
- }
-
- public Dictionary getProperties() {
- Bundle bundle = lookupBundle();
- if (bundle != null) {
- if (m_propagateCallbackInstance != null && m_propagateCallbackMethod != null) {
- try {
- return (Dictionary) InvocationUtil.invokeCallbackMethod(m_propagateCallbackInstance, m_propagateCallbackMethod, new Class[][] {{ Bundle.class }}, new Object[][] {{ bundle }});
- }
- catch (InvocationTargetException e) {
- m_logger.log(LogService.LOG_WARNING, "Exception while invoking callback method", e.getCause());
- }
- catch (Exception e) {
- m_logger.log(LogService.LOG_WARNING, "Exception while trying to invoke callback method", e);
- }
- throw new IllegalStateException("Could not invoke callback");
- }
- else {
- return bundle.getHeaders();
- }
- }
- else {
- throw new IllegalStateException("cannot find bundle");
- }
- }
-
- public boolean isPropagated() {
- return m_propagate;
- }
-}
diff --git a/dependencymanager/core/src/main/java/org/apache/felix/dm/impl/dependencies/ConfigurationDependencyImpl.java b/dependencymanager/core/src/main/java/org/apache/felix/dm/impl/dependencies/ConfigurationDependencyImpl.java
deleted file mode 100644
index b7a1473..0000000
--- a/dependencymanager/core/src/main/java/org/apache/felix/dm/impl/dependencies/ConfigurationDependencyImpl.java
+++ /dev/null
@@ -1,404 +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.felix.dm.impl.dependencies;
-
-import java.lang.reflect.InvocationTargetException;
-import java.util.ArrayList;
-import java.util.Dictionary;
-import java.util.HashSet;
-import java.util.List;
-import java.util.Properties;
-import java.util.Set;
-
-import org.apache.felix.dm.ComponentDependencyDeclaration;
-import org.apache.felix.dm.ConfigurationDependency;
-import org.apache.felix.dm.Dependency;
-import org.apache.felix.dm.DependencyActivation;
-import org.apache.felix.dm.DependencyService;
-import org.apache.felix.dm.InvocationUtil;
-import org.apache.felix.dm.PropertyMetaData;
-import org.apache.felix.dm.impl.Logger;
-import org.apache.felix.dm.impl.metatype.MetaTypeProviderImpl;
-import org.osgi.framework.BundleContext;
-import org.osgi.framework.Constants;
-import org.osgi.framework.ServiceRegistration;
-import org.osgi.service.cm.ConfigurationException;
-import org.osgi.service.cm.ManagedService;
-import org.osgi.service.log.LogService;
-
-/**
- * Configuration dependency that can track the availability of a (valid) configuration.
- * To use it, specify a PID for the configuration. The dependency is always required,
- * because if it is not, it does not make sense to use the dependency manager. In that
- * scenario, simply register your service as a <code>ManagedService(Factory)</code> and
- * handle everything yourself. Also, only managed services are supported, not factories.
- * There are a couple of things you need to be aware of when implementing the
- * <code>updated(Dictionary)</code> method:
- * <ul>
- * <li>Make sure it throws a <code>ConfigurationException</code> when you get a
- * configuration that is invalid. In this case, the dependency will not change:
- * if it was not available, it will still not be. If it was available, it will
- * remain available and implicitly assume you keep working with your old
- * configuration.</li>
- * <li>This method will be called before all required dependencies are available.
- * Make sure you do not depend on these to parse your settings.</li>
- * </ul>
- *
- * @author <a href="mailto:dev@felix.apache.org">Felix Project Team</a>
- */
-public class ConfigurationDependencyImpl extends DependencyBase implements ConfigurationDependency, ManagedService, ComponentDependencyDeclaration, DependencyActivation {
- private BundleContext m_context;
- private String m_pid;
- private ServiceRegistration m_registration;
- protected List m_services = new ArrayList();
- private Dictionary m_settings;
- private String m_callback;
- private final Set m_updateInvokedCache = new HashSet();
- private MetaTypeProviderImpl m_metaType;
- private boolean m_propagate;
- private Object m_propagateCallbackInstance;
- private String m_propagateCallbackMethod;
-
- public ConfigurationDependencyImpl(BundleContext context, Logger logger) {
- super(logger);
- m_context = context;
- }
-
- public ConfigurationDependencyImpl(ConfigurationDependencyImpl prototype) {
- super(prototype);
- m_context = prototype.m_context;
- m_pid = prototype.m_pid;
- m_propagate = prototype.m_propagate;
- m_callback = prototype.m_callback;
- m_metaType = prototype.m_metaType;
- m_propagateCallbackInstance = prototype.m_propagateCallbackInstance;
- m_propagateCallbackMethod = prototype.m_propagateCallbackMethod;
- }
-
- public Dependency createCopy() {
- return new ConfigurationDependencyImpl(this);
- }
-
- public synchronized boolean isAvailable() {
- return m_settings != null;
- }
-
- /**
- * Will always return <code>true</code> as optional configuration dependencies
- * do not make sense. You might as well just implement <code>ManagedService</code>
- * yourself in those cases.
- */
- public boolean isRequired() {
- return true;
- }
-
- /**
- * Returns <code>true</code> when configuration properties should be propagated
- * as service properties.
- */
- public boolean isPropagated() {
- return m_propagate;
- }
-
- public ConfigurationDependency setInstanceBound(boolean isInstanceBound) {
- setIsInstanceBound(isInstanceBound);
- return this;
- }
-
-
- public Dictionary getConfiguration() {
- return m_settings;
- }
-
- public void start(DependencyService service) {
- boolean needsStarting = false;
- synchronized (this) {
- m_services.add(service);
- if (!m_isStarted) {
- m_isStarted = true;
- needsStarting = true;
- }
- }
- if (needsStarting) {
- Properties props = new Properties();
- props.put(Constants.SERVICE_PID, m_pid);
- ManagedService ms = this;
- if (m_metaType != null) {
- ms = m_metaType;
- }
- m_registration = m_context.registerService(ManagedService.class.getName(), ms, props);
- }
- }
-
- public void stop(DependencyService service) {
- boolean needsStopping = false;
- synchronized (this) {
- if (m_services.size() == 1 && m_services.contains(service)) {
- m_isStarted = false;
- needsStopping = true;
- }
- }
- if (needsStopping) {
- m_registration.unregister();
- m_registration = null;
- m_services.remove(service);
- }
- }
-
- public ConfigurationDependency setCallback(String callback) {
- m_callback = callback;
- return this;
- }
-
- public void updated(Dictionary settings) throws ConfigurationException {
- synchronized (m_updateInvokedCache) {
- m_updateInvokedCache.clear();
- }
- Dictionary oldSettings = null;
- synchronized (this) {
- oldSettings = m_settings;
- }
-
- if (oldSettings == null && settings == null) {
- // CM has started but our configuration is not still present in the CM database: ignore
- return;
- }
-
- Object[] services = m_services.toArray();
- for (int i = 0; i < services.length; i++) {
- DependencyService ds = (DependencyService) services[i];
- // if non-null settings come in, we have to instantiate the service and
- // apply these settings
- ds.initService();
- Object service = ds.getService();
-
- if (service != null) {
- invokeUpdate(ds, service, settings);
- }
- else {
- m_logger.log(Logger.LOG_ERROR, "Service " + ds + " with configuration dependency " + this + " could not be instantiated.");
- return;
- }
- }
-
- synchronized (this) {
- m_settings = settings;
- }
-
- for (int i = 0; i < services.length; i++) {
- DependencyService ds = (DependencyService) services[i];
- // If these settings did not cause a configuration exception, we determine if they have
- // caused the dependency state to change
- if ((oldSettings == null) && (settings != null)) {
- ds.dependencyAvailable(this);
- }
- if ((oldSettings != null) && (settings == null)) {
- ds.dependencyUnavailable(this);
- }
- if ((oldSettings != null) && (settings != null)) {
- ds.dependencyChanged(this);
- }
- }
- }
-
- public void invokeUpdate(DependencyService ds, Object service, Dictionary settings) throws ConfigurationException {
- boolean wasAdded;
- synchronized (m_updateInvokedCache) {
- wasAdded = m_updateInvokedCache.add(ds);
- }
- if (wasAdded) {
- String callback = (m_callback == null) ? "updated" : m_callback;
- try {
- // if exception is thrown here, what does that mean for the
- // state of this dependency? how smart do we want to be??
- // it's okay like this, if the new settings contain errors, we
- // remain in the state we were, assuming that any error causes
- // the "old" configuration to stay in effect.
- // CM will log any thrown exceptions.
- InvocationUtil.invokeCallbackMethod(service, callback, new Class[][] {{ Dictionary.class }}, new Object[][] {{ settings }});
- }
- catch (InvocationTargetException e) {
- // The component has thrown an exception during it's callback invocation.
- if (e.getTargetException() instanceof ConfigurationException) {
- // the callback threw an OSGi ConfigurationException: just re-throw it.
- throw (ConfigurationException) e.getTargetException();
- }
- else {
- // wrap the callback exception into a ConfigurationException.
- throw new ConfigurationException(null, "Service " + ds + " with " + this.toString() + " could not be updated", e.getTargetException());
- }
- }
- catch (NoSuchMethodException e) {
- // if the method does not exist, ignore it
- }
- catch (Throwable t) {
- // wrap any other exception as a ConfigurationException.
- throw new ConfigurationException(null, "Service " + ds + " with " + this.toString() + " could not be updated", t);
- }
- }
- }
-
- /**
- * Sets the <code>service.pid</code> of the configuration you
- * are depending on.
- */
- public ConfigurationDependency setPid(String pid) {
- ensureNotActive();
- m_pid = pid;
- return this;
- }
-
- /**
- * Sets propagation of the configuration properties to the service
- * properties. Any additional service properties specified directly
- * are merged with these.
- */
- public ConfigurationDependency setPropagate(boolean propagate) {
- ensureNotActive();
- m_propagate = propagate;
- return this;
- }
-
- private void ensureNotActive() {
- if (m_services != null && m_services.size() > 0) {
- throw new IllegalStateException("Cannot modify state while active.");
- }
- }
-
- public String toString() {
- return "ConfigurationDependency[" + m_pid + "]";
- }
-
- public String getName() {
- return m_pid;
- }
-
- public String getType() {
- return "configuration";
- }
-
- public Object getAutoConfigInstance() {
- return getConfiguration();
- }
-
- public String getAutoConfigName() {
- // TODO Auto-generated method stub
- return null;
- }
-
- public Class getAutoConfigType() {
- return Dictionary.class;
- }
-
- public void invokeAdded(DependencyService service) {
- try {
- invokeUpdate(service, service.getService(), getConfiguration());
- }
- catch (ConfigurationException e) {
- // if this happens, it's definitely an inconsistency, since we
- // asked the instance the same question before (if this is a
- // valid configuration) and then it was
- e.printStackTrace();
- }
- }
-
- public void invokeRemoved(DependencyService service) {
- synchronized (m_updateInvokedCache) {
- m_updateInvokedCache.remove(service);
- }
- }
-
- public boolean isAutoConfig() {
- // TODO Auto-generated method stub
- return false;
- }
-
- public ConfigurationDependency setPropagate(Object instance, String method) {
- setPropagate(instance != null && method != null);
- m_propagateCallbackInstance = instance;
- m_propagateCallbackMethod = method;
- return this;
- }
-
- public Dictionary getProperties() {
- Dictionary config = getConfiguration();
- if (config != null) {
- if (m_propagateCallbackInstance != null && m_propagateCallbackMethod != null) {
- try {
- return (Dictionary) InvocationUtil.invokeCallbackMethod(m_propagateCallbackInstance, m_propagateCallbackMethod, new Class[][] {{ Dictionary.class }, {}}, new Object[][] {{ config }, {}});
- }
- catch (InvocationTargetException e) {
- m_logger.log(LogService.LOG_WARNING, "Exception while invoking callback method", e.getCause());
- }
- catch (Exception e) {
- m_logger.log(LogService.LOG_WARNING, "Exception while trying to invoke callback method", e);
- }
- throw new IllegalStateException("Could not invoke callback");
- }
- else {
- return config;
- }
- }
- else {
- throw new IllegalStateException("cannot find configuration");
- }
- }
-
- public BundleContext getBundleContext() {
- return m_context;
- }
-
- public Logger getLogger() {
- return m_logger;
- }
-
- public ConfigurationDependency add(PropertyMetaData properties)
- {
- createMetaTypeImpl();
- m_metaType.add(properties);
- return this;
- }
-
- public ConfigurationDependency setDescription(String description)
- {
- createMetaTypeImpl();
- m_metaType.setDescription(description);
- return this;
- }
-
- public ConfigurationDependency setHeading(String heading)
- {
- createMetaTypeImpl();
- m_metaType.setName(heading);
- return this;
- }
-
- public ConfigurationDependency setLocalization(String path)
- {
- createMetaTypeImpl();
- m_metaType.setLocalization(path);
- return this;
- }
-
- private synchronized void createMetaTypeImpl() {
- if (m_metaType == null) {
- m_metaType = new MetaTypeProviderImpl(getName(), getBundleContext(), getLogger(), this, null);
- }
- }
-}
diff --git a/dependencymanager/core/src/main/java/org/apache/felix/dm/impl/dependencies/DependencyBase.java b/dependencymanager/core/src/main/java/org/apache/felix/dm/impl/dependencies/DependencyBase.java
deleted file mode 100644
index b952f4f..0000000
--- a/dependencymanager/core/src/main/java/org/apache/felix/dm/impl/dependencies/DependencyBase.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.felix.dm.impl.dependencies;
-
-import org.apache.felix.dm.ComponentDependencyDeclaration;
-import org.apache.felix.dm.Dependency;
-import org.apache.felix.dm.DependencyActivation;
-import org.apache.felix.dm.impl.Logger;
-
-/**
- * @author <a href="mailto:dev@felix.apache.org">Felix Project Team</a>
- */
-public abstract class DependencyBase implements Dependency, DependencyActivation {
- private boolean m_isRequired;
- private volatile boolean m_isInstanceBound;
- protected final Logger m_logger;
- protected volatile boolean m_isStarted;
-
- public DependencyBase(Logger logger) {
- m_logger = logger;
- }
-
- public DependencyBase(DependencyBase prototype) {
- m_logger = prototype.m_logger;
- m_isRequired = prototype.isRequired();
- m_isInstanceBound = prototype.m_isInstanceBound;
- }
-
- public synchronized boolean isRequired() {
- return m_isRequired;
- }
-
- protected synchronized void setIsRequired(boolean isRequired) {
- m_isRequired = isRequired;
- }
-
- public final boolean isInstanceBound() {
- return m_isInstanceBound;
- }
-
- public final void setIsInstanceBound(boolean isInstanceBound) {
- m_isInstanceBound = isInstanceBound;
- }
-
- public int getState() {
- if (m_isStarted) {
- return (isAvailable() ? 1 : 0) + (isRequired() ? 2 : 0);
- }
- else {
- return isRequired() ? ComponentDependencyDeclaration.STATE_REQUIRED : ComponentDependencyDeclaration.STATE_OPTIONAL;
- }
- }
-
-}
diff --git a/dependencymanager/core/src/main/java/org/apache/felix/dm/impl/dependencies/ResourceDependencyImpl.java b/dependencymanager/core/src/main/java/org/apache/felix/dm/impl/dependencies/ResourceDependencyImpl.java
deleted file mode 100644
index e2bca98..0000000
--- a/dependencymanager/core/src/main/java/org/apache/felix/dm/impl/dependencies/ResourceDependencyImpl.java
+++ /dev/null
@@ -1,535 +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.felix.dm.impl.dependencies;
-
-import java.lang.reflect.InvocationTargetException;
-import java.net.URL;
-import java.util.ArrayList;
-import java.util.Dictionary;
-import java.util.Enumeration;
-import java.util.List;
-import java.util.Properties;
-
-import org.apache.felix.dm.Component;
-import org.apache.felix.dm.ComponentDependencyDeclaration;
-import org.apache.felix.dm.Dependency;
-import org.apache.felix.dm.DependencyActivation;
-import org.apache.felix.dm.DependencyService;
-import org.apache.felix.dm.InvocationUtil;
-import org.apache.felix.dm.ResourceDependency;
-import org.apache.felix.dm.ResourceHandler;
-import org.apache.felix.dm.impl.Logger;
-import org.osgi.framework.BundleContext;
-import org.osgi.framework.ServiceRegistration;
-import org.osgi.service.log.LogService;
-
-/**
- * @author <a href="mailto:dev@felix.apache.org">Felix Project Team</a>
- */
-public class ResourceDependencyImpl extends DependencyBase implements ResourceDependency, ResourceHandler, DependencyActivation, ComponentDependencyDeclaration {
- private volatile BundleContext m_context;
- private volatile ServiceRegistration m_registration;
- private Object m_callbackInstance;
- private String m_callbackAdded;
- private String m_callbackChanged;
- private String m_callbackRemoved;
- private boolean m_autoConfig;
- private String m_autoConfigInstance;
- protected List m_services = new ArrayList();
- private String m_resourceFilter;
- private URL m_trackedResource;
- private List m_resources = new ArrayList();
- private List m_resourceProperties = new ArrayList();
- private URL m_resourceInstance;
- private Dictionary m_resourcePropertiesInstance;
- private boolean m_propagate;
- private Object m_propagateCallbackInstance;
- private String m_propagateCallbackMethod;
-
- public ResourceDependencyImpl(BundleContext context, Logger logger) {
- super(logger);
- m_context = context;
- m_autoConfig = true;
- }
-
- public ResourceDependencyImpl(ResourceDependencyImpl prototype) {
- super(prototype);
- m_context = prototype.m_context;
- m_autoConfig = prototype.m_autoConfig;
- m_callbackInstance = prototype.m_callbackInstance;
- m_callbackAdded = prototype.m_callbackAdded;
- m_callbackChanged = prototype.m_callbackChanged;
- m_callbackRemoved = prototype.m_callbackRemoved;
- m_autoConfigInstance = prototype.m_autoConfigInstance;
- m_resourceFilter = prototype.m_resourceFilter;
- m_trackedResource = prototype.m_trackedResource;
- m_propagate = prototype.m_propagate;
- }
-
- public Dependency createCopy() {
- return new ResourceDependencyImpl(this);
- }
-
- public synchronized boolean isAvailable() {
- return m_resources.size() > 0;
- }
-
- public void start(DependencyService service) {
- boolean needsStarting = false;
- synchronized (this) {
- m_services.add(service);
- if (!m_isStarted) {
- m_isStarted = true;
- needsStarting = true;
- }
- }
- if (needsStarting) {
- Dictionary props = null;
- if (m_trackedResource != null) {
- props = new Properties();
- props.put(ResourceHandler.URL, m_trackedResource);
- }
- else {
- if (m_resourceFilter != null) {
- props = new Properties();
- props.put(ResourceHandler.FILTER, m_resourceFilter);
- }
- }
- m_registration = m_context.registerService(ResourceHandler.class.getName(), this, props);
- }
- }
-
- public void stop(DependencyService service) {
- boolean needsStopping = false;
- synchronized (this) {
- if (m_services.size() == 1 && m_services.contains(service)) {
- m_isStarted = false;
- needsStopping = true;
- m_services.remove(service);
- }
- }
- if (needsStopping) {
- m_registration.unregister();
- m_registration = null;
- }
- }
-
- public void added(URL resource) {
- handleResourceAdded(resource, null);
- }
-
- public void added(URL resource, Dictionary resourceProperties) {
- handleResourceAdded(resource, resourceProperties);
- }
-
- private void handleResourceAdded(URL resource, Dictionary resourceProperties) {
- if (m_trackedResource == null || m_trackedResource.equals(resource)) {
- long counter;
- Object[] services;
- synchronized (this) {
- m_resources.add(resource);
- m_resourceProperties.add(resourceProperties);
- counter = m_resources.size();
- services = m_services.toArray();
- }
- for (int i = 0; i < services.length; i++) {
- DependencyService ds = (DependencyService) services[i];
- if (counter == 1) {
- ds.dependencyAvailable(this);
- if (!isRequired()) {
- invokeAdded(ds, resource, resourceProperties);
- }
- }
- else {
- ds.dependencyChanged(this);
- invokeAdded(ds, resource, resourceProperties);
- }
- }
- }
- }
-
- public void changed(URL resource) {
- handleResourceChanged(resource, null);
- }
-
- public void changed(URL resource, Dictionary resourceProperties) {
- handleResourceChanged(resource, resourceProperties);
- }
-
- private void handleResourceChanged(URL resource, Dictionary resourceProperties) {
- if (m_trackedResource == null || m_trackedResource.equals(resource)) {
- Object[] services;
- synchronized (this) {
- // change the resource properties for the resource
- m_resourceProperties.set(m_resources.indexOf(resource), resourceProperties);
- services = m_services.toArray();
- }
- for (int i = 0; i < services.length; i++) {
- DependencyService ds = (DependencyService) services[i];
- invokeChanged(ds, resource, resourceProperties);
- }
- }
- }
-
- public void removed(URL resource) {
- handleResourceRemoved(resource, null);
- }
-
- public void removed(URL resource, Dictionary resourceProperties) {
- handleResourceRemoved(resource, resourceProperties);
- }
-
- public void handleResourceRemoved(URL resource, Dictionary resourceProperties) {
- if (m_trackedResource == null || m_trackedResource.equals(resource)) {
- long counter;
- Object[] services;
- synchronized (this) {
- if (m_resources.indexOf(resource) == -1) {
- m_logger.log(Logger.LOG_WARNING, "handleResourceRemoved called for unknown resource: " + resource);
- return;
- }
- m_resourceProperties.remove(m_resources.indexOf(resource));
- m_resources.remove(resource);
- counter = m_resources.size();
- services = m_services.toArray();
- }
- for (int i = 0; i < services.length; i++) {
- DependencyService ds = (DependencyService) services[i];
- if (counter == 0) {
- ds.dependencyUnavailable(this);
- if (!isRequired()) {
- invokeRemoved(ds, resource, resourceProperties);
- }
- }
- else {
- ds.dependencyChanged(this);
- invokeRemoved(ds, resource, resourceProperties);
- }
- }
- }
- }
-
- public void invokeAdded(DependencyService ds, URL serviceInstance, Dictionary resourceProperties) {
- invoke(ds, serviceInstance, resourceProperties, m_callbackAdded);
- }
-
- public void invokeChanged(DependencyService ds, URL serviceInstance, Dictionary resourceProperties) {
- invoke(ds, serviceInstance, resourceProperties, m_callbackChanged);
- }
-
- public void invokeRemoved(DependencyService ds, URL serviceInstance, Dictionary resourceProperties) {
- invoke(ds, serviceInstance, resourceProperties, m_callbackRemoved);
- }
-
- private void invoke(DependencyService ds, URL serviceInstance, Dictionary resourceProperties, String name) {
- if (name != null) {
- ds.invokeCallbackMethod(getCallbackInstances(ds), name,
- new Class[][] {
- { Component.class, URL.class, Dictionary.class },
- { Component.class, URL.class },
- { Component.class },
- { URL.class, Dictionary.class },
- { URL.class },
- { Object.class },
- {}},
- new Object[][] {
- { ds.getServiceInterface(), serviceInstance, resourceProperties },
- { ds.getServiceInterface(), serviceInstance },
- { ds.getServiceInterface() },
- { serviceInstance, resourceProperties },
- { serviceInstance },
- { serviceInstance },
- {}}
- );
- }
- }
-
- /**
- * Sets the callbacks for this service. These callbacks can be used as hooks whenever a
- * dependency is added or removed. When you specify callbacks, the auto configuration
- * feature is automatically turned off, because we're assuming you don't need it in this
- * case.
- *
- * @param added the method to call when a service was added
- * @param removed the method to call when a service was removed
- * @return this service dependency
- */
- public synchronized ResourceDependency setCallbacks(String added, String removed) {
- return setCallbacks(null, added, null, removed);
- }
-
- /**
- * Sets the callbacks for this service. These callbacks can be used as hooks whenever a
- * dependency is added, changed or removed. When you specify callbacks, the auto
- * configuration feature is automatically turned off, because we're assuming you don't
- * need it in this case.
- *
- * @param added the method to call when a service was added
- * @param changed the method to call when a service was changed
- * @param removed the method to call when a service was removed
- * @return this service dependency
- */
- public synchronized ResourceDependency setCallbacks(String added, String changed, String removed) {
- return setCallbacks(null, added, changed, removed);
- }
-
- /**
- * Sets the callbacks for this service. These callbacks can be used as hooks whenever a
- * dependency is added or removed. They are called on the instance you provide. When you
- * specify callbacks, the auto configuration feature is automatically turned off, because
- * we're assuming you don't need it in this case.
- *
- * @param instance the instance to call the callbacks on
- * @param added the method to call when a service was added
- * @param removed the method to call when a service was removed
- * @return this service dependency
- */
- public synchronized ResourceDependency setCallbacks(Object instance, String added, String removed) {
- return setCallbacks(instance, added, null, removed);
- }
-
- /**
- * Sets the callbacks for this service. These callbacks can be used as hooks whenever a
- * dependency is added, changed or removed. They are called on the instance you provide. When you
- * specify callbacks, the auto configuration feature is automatically turned off, because
- * we're assuming you don't need it in this case.
- *
- * @param instance the instance to call the callbacks on
- * @param added the method to call when a service was added
- * @param changed the method to call when a service was changed
- * @param removed the method to call when a service was removed
- * @return this service dependency
- */
- public synchronized ResourceDependency setCallbacks(Object instance, String added, String changed, String removed) {
- ensureNotActive();
- // if at least one valid callback is specified, we turn off auto configuration
- if (added != null || removed != null || changed != null) {
- setAutoConfig(false);
- }
- m_callbackInstance = instance;
- m_callbackAdded = added;
- m_callbackChanged = changed;
- m_callbackRemoved = removed;
- return this;
- }
-
- private void ensureNotActive() {
- if (m_registration != null) {
- throw new IllegalStateException("Cannot modify state while active.");
- }
- }
-
- /**
- * Sets auto configuration for this service. Auto configuration allows the
- * dependency to fill in any attributes in the service implementation that
- * are of the same type as this dependency. Default is on.
- *
- * @param autoConfig the value of auto config
- * @return this service dependency
- */
- public synchronized ResourceDependency setAutoConfig(boolean autoConfig) {
- ensureNotActive();
- m_autoConfig = autoConfig;
- return this;
- }
-
- /**
- * Sets auto configuration for this service. Auto configuration allows the
- * dependency to fill in the attribute in the service implementation that
- * has the same type and instance name.
- *
- * @param instanceName the name of attribute to auto config
- * @return this service dependency
- */
- public synchronized ResourceDependency setAutoConfig(String instanceName) {
- ensureNotActive();
- m_autoConfig = (instanceName != null);
- m_autoConfigInstance = instanceName;
- return this;
- }
-
- private synchronized Object[] getCallbackInstances(DependencyService ds) {
- if (m_callbackInstance == null) {
- return ds.getCompositionInstances();
- }
- else {
- return new Object[] { m_callbackInstance };
- }
- }
-
- public ResourceDependency setResource(URL resource) {
- m_trackedResource = resource;
- return this;
- }
-
- public synchronized ResourceDependency setRequired(boolean required) {
- ensureNotActive();
- setIsRequired(required);
- return this;
- }
-
- public ResourceDependency setFilter(String resourceFilter) {
- ensureNotActive();
- m_resourceFilter = resourceFilter;
- return this;
- }
-
- public ResourceDependency setFilter(String resourceFilter, String resourcePropertiesFilter) {
- ensureNotActive();
- m_resourceFilter = resourceFilter;
- return this;
- }
-
- public void setResourcePropertiesConfigurationMember() {
-
- }
-
- public synchronized boolean isAutoConfig() {
- return m_autoConfig;
- }
-
- public URL getResource() {
- return lookupResource();
- }
-
- private URL lookupResource() {
- try {
- return (URL) m_resources.get(0);
- }
- catch (IndexOutOfBoundsException e) {
- return null;
- }
- }
-
- private Dictionary lookupResourceProperties() {
- try {
- return (Dictionary) m_resourceProperties.get(0);
- }
- catch (IndexOutOfBoundsException e) {
- return null;
- }
- }
-
- public Object getAutoConfigInstance() {
- return lookupResource();
- }
-
- public String getAutoConfigName() {
- return m_autoConfigInstance;
- }
-
- public Class getAutoConfigType() {
- return URL.class;
- }
-
- public void invokeAdded(DependencyService service) {
- // we remember these for future reference, needed for required callbacks
- m_resourceInstance = lookupResource();
- m_resourcePropertiesInstance = lookupResourceProperties();
- invokeAdded(service, m_resourceInstance, m_resourcePropertiesInstance);
- }
-
- public void invokeRemoved(DependencyService service) {
- invokeRemoved(service, m_resourceInstance, m_resourcePropertiesInstance);
- m_resourceInstance = null;
- m_resourcePropertiesInstance = null;
- }
-
- public ResourceDependency setPropagate(boolean propagate) {
- ensureNotActive();
- m_propagate = propagate;
- return this;
- }
-
- public ResourceDependency setPropagate(Object instance, String method) {
- setPropagate(instance != null && method != null);
- m_propagateCallbackInstance = instance;
- m_propagateCallbackMethod = method;
- return this;
- }
-
- public Dictionary getProperties() {
- URL resource = lookupResource();
- Dictionary resourceProperties = lookupResourceProperties();
- if (resource != null) {
- if (m_propagateCallbackInstance != null && m_propagateCallbackMethod != null) {
- try {
- return (Dictionary) InvocationUtil.invokeCallbackMethod(m_propagateCallbackInstance, m_propagateCallbackMethod, new Class[][] {{ URL.class }}, new Object[][] {{ resource }});
- }
- catch (InvocationTargetException e) {
- m_logger.log(LogService.LOG_WARNING, "Exception while invoking callback method", e.getCause());
- }
- catch (Exception e) {
- m_logger.log(LogService.LOG_WARNING, "Exception while trying to invoke callback method", e);
- }
- throw new IllegalStateException("Could not invoke callback");
- }
- else {
- Properties props = new Properties();
- props.setProperty(ResourceHandler.HOST, resource.getHost());
- props.setProperty(ResourceHandler.PATH, resource.getPath());
- props.setProperty(ResourceHandler.PROTOCOL, resource.getProtocol());
- props.setProperty(ResourceHandler.PORT, Integer.toString(resource.getPort()));
- // add the custom resource properties
- if (resourceProperties != null) {
- Enumeration properyKeysEnum = resourceProperties.keys();
- while (properyKeysEnum.hasMoreElements()) {
- String key = (String) properyKeysEnum.nextElement();
- if (!key.equals(ResourceHandler.HOST) &&
- !key.equals(ResourceHandler.PATH) &&
- !key.equals(ResourceHandler.PROTOCOL) &&
- !key.equals(ResourceHandler.PORT)) {
- props.setProperty(key, resourceProperties.get(key).toString());
- } else {
- m_logger.log(LogService.LOG_WARNING, "Custom resource property is overlapping with the default resource property for key: " + key);
- }
- }
- }
- return props;
- }
- }
- else {
- throw new IllegalStateException("cannot find resource");
- }
- }
-
- public boolean isPropagated() {
- return m_propagate;
- }
-
- public ResourceDependency setInstanceBound(boolean isInstanceBound) {
- setIsInstanceBound(isInstanceBound);
- return this;
- }
-
- public String getName() {
- StringBuilder sb = new StringBuilder();
- if (m_resourceFilter != null) {
- sb.append(m_resourceFilter);
- }
- if (m_trackedResource != null) {
- sb.append(m_trackedResource.toString());
- }
- return sb.toString();
- }
-
- public String getType() {
- return "resource";
- }
-}
diff --git a/dependencymanager/core/src/main/java/org/apache/felix/dm/impl/dependencies/ServiceDependencyImpl.java b/dependencymanager/core/src/main/java/org/apache/felix/dm/impl/dependencies/ServiceDependencyImpl.java
deleted file mode 100644
index d74d938..0000000
--- a/dependencymanager/core/src/main/java/org/apache/felix/dm/impl/dependencies/ServiceDependencyImpl.java
+++ /dev/null
@@ -1,1505 +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.felix.dm.impl.dependencies;
-
-import java.lang.reflect.InvocationTargetException;
-import java.lang.reflect.Proxy;
-import java.util.AbstractMap;
-import java.util.ArrayList;
-import java.util.Arrays;
-import java.util.Comparator;
-import java.util.Dictionary;
-import java.util.HashMap;
-import java.util.HashSet;
-import java.util.Iterator;
-import java.util.List;
-import java.util.Map;
-import java.util.Map.Entry;
-import java.util.Properties;
-import java.util.Set;
-
-import org.apache.felix.dm.Component;
-import org.apache.felix.dm.ComponentDependencyDeclaration;
-import org.apache.felix.dm.Dependency;
-import org.apache.felix.dm.DependencyService;
-import org.apache.felix.dm.InvocationUtil;
-import org.apache.felix.dm.ServiceDependency;
-import org.apache.felix.dm.ServiceUtil;
-import org.apache.felix.dm.impl.SerialExecutor;
-import org.apache.felix.dm.impl.DefaultNullObject;
-import org.apache.felix.dm.impl.Logger;
-import org.apache.felix.dm.tracker.ServiceTracker;
-import org.apache.felix.dm.tracker.ServiceTrackerCustomizer;
-import org.osgi.framework.BundleContext;
-import org.osgi.framework.Constants;
-import org.osgi.framework.InvalidSyntaxException;
-import org.osgi.framework.ServiceReference;
-import org.osgi.service.log.LogService;
-
-/**
- * Service dependency that can track an OSGi service.
- *
- * @author <a href="mailto:dev@felix.apache.org">Felix Project Team</a>
- */
-public class ServiceDependencyImpl extends DependencyBase implements ServiceDependency, ServiceTrackerCustomizer,
- ComponentDependencyDeclaration {
- protected final List m_services = new ArrayList();
- protected volatile ServiceTracker m_tracker;
- protected final BundleContext m_context;
- protected volatile Class m_trackedServiceName;
- private volatile Object m_nullObject;
- private volatile String m_trackedServiceFilter;
- private volatile String m_trackedServiceFilterUnmodified;
- private volatile ServiceReference m_trackedServiceReference;
- private volatile Object m_callbackInstance;
- private volatile String m_callbackAdded;
- private volatile String m_callbackChanged;
- private volatile String m_callbackRemoved;
- private volatile String m_callbackSwapped;
- private boolean m_autoConfig;
- private volatile String m_autoConfigInstance;
- private boolean m_autoConfigInvoked;
- private volatile Object m_defaultImplementation;
- private volatile Object m_defaultImplementationInstance;
- private boolean m_isAvailable;
- private volatile boolean m_propagate;
- private volatile Object m_propagateCallbackInstance;
- private volatile String m_propagateCallbackMethod;
- private final Map m_sr = new HashMap(); /* <DependencyService, Set<Tuple<ServiceReference, Object>> */
- private final Map m_componentByRank = new HashMap(); /* <Component, Map<Long, Map<Integer, Tuple>>> */
- private volatile boolean m_debug = false;
- private volatile String m_debugKey = null;
-
- /**
- * Executor used to ensure proper synchronization without holding locks.
- */
- private final SerialExecutor m_serial;
-
- // ----------------------- Inner classes --------------------------------------------------------------
-
- private static final Comparator COMPARATOR = new Comparator() {
- public int getRank(ServiceReference ref) {
- Object ranking = ref.getProperty(Constants.SERVICE_RANKING);
- if (ranking != null && (ranking instanceof Integer)) {
- return ((Integer) ranking).intValue();
- }
- return 0;
- }
-
- public int compare(Object a, Object b) {
- ServiceReference ra = (ServiceReference) a, rb = (ServiceReference) b;
- int ranka = getRank(ra);
- int rankb = getRank(rb);
- if (ranka < rankb) {
- return -1;
- } else if (ranka > rankb) {
- return 1;
- }
- return 0;
- }
- };
-
- private static final class Tuple /* <ServiceReference, Object> */{
- private final ServiceReference m_serviceReference;
- private final Object m_service;
-
- public Tuple(ServiceReference first, Object last) {
- m_serviceReference = first;
- m_service = last;
- }
-
- public ServiceReference getServiceReference() {
- return m_serviceReference;
- }
-
- public Object getService() {
- return m_service;
- }
-
- public boolean equals(Object obj) {
- return ((Tuple) obj).getServiceReference().equals(getServiceReference());
- }
-
- public int hashCode() {
- return m_serviceReference.hashCode();
- }
-
- public String toString() {
- return "{" + m_serviceReference.getProperty(Constants.SERVICE_ID) + "=" + m_service + "}";
- }
- }
-
- /**
- * Entry to wrap service properties behind a Map.
- */
- private static final class ServicePropertiesMapEntry implements Map.Entry {
- private final String m_key;
- private Object m_value;
-
- public ServicePropertiesMapEntry(String key, Object value) {
- m_key = key;
- m_value = value;
- }
-
- public Object getKey() {
- return m_key;
- }
-
- public Object getValue() {
- return m_value;
- }
-
- public String toString() {
- return m_key + "=" + m_value;
- }
-
- public Object setValue(Object value) {
- Object oldValue = m_value;
- m_value = value;
- return oldValue;
- }
-
- public boolean equals(Object o) {
- if (!(o instanceof Map.Entry)) {
- return false;
- }
- Map.Entry e = (Map.Entry) o;
- return eq(m_key, e.getKey()) && eq(m_value, e.getValue());
- }
-
- public int hashCode() {
- return ((m_key == null) ? 0 : m_key.hashCode()) ^ ((m_value == null) ? 0 : m_value.hashCode());
- }
-
- private static final boolean eq(Object o1, Object o2) {
- return (o1 == null ? o2 == null : o1.equals(o2));
- }
- }
-
- /**
- * Wraps service properties behind a Map.
- */
- private final static class ServicePropertiesMap extends AbstractMap {
- private final ServiceReference m_ref;
-
- public ServicePropertiesMap(ServiceReference ref) {
- m_ref = ref;
- }
-
- public Object get(Object key) {
- return m_ref.getProperty(key.toString());
- }
-
- public int size() {
- return m_ref.getPropertyKeys().length;
- }
-
- public Set entrySet() {
- Set set = new HashSet();
- String[] keys = m_ref.getPropertyKeys();
- for (int i = 0; i < keys.length; i++) {
- set.add(new ServicePropertiesMapEntry(keys[i], m_ref.getProperty(keys[i])));
- }
- return set;
- }
- }
-
- // ----------------------- Public methods -----------------------------------------------------------
-
- /**
- * Creates a new service dependency.
- *
- * @param context the bundle context
- * @param logger the logger
- */
- public ServiceDependencyImpl(BundleContext context, Logger logger) {
- super(logger);
- m_context = context;
- m_autoConfig = true;
- m_serial = new SerialExecutor(logger);
- }
-
- /** Copying constructor that clones an existing instance. */
- public ServiceDependencyImpl(ServiceDependencyImpl prototype) {
- super(prototype);
- m_serial = new SerialExecutor(m_logger);
- synchronized (prototype) {
- m_context = prototype.m_context;
- m_autoConfig = prototype.m_autoConfig;
- m_trackedServiceName = prototype.m_trackedServiceName;
- m_nullObject = prototype.m_nullObject;
- m_trackedServiceFilter = prototype.m_trackedServiceFilter;
- m_trackedServiceFilterUnmodified = prototype.m_trackedServiceFilterUnmodified;
- m_trackedServiceReference = prototype.m_trackedServiceReference;
- m_callbackInstance = prototype.m_callbackInstance;
- m_callbackAdded = prototype.m_callbackAdded;
- m_callbackChanged = prototype.m_callbackChanged;
- m_callbackRemoved = prototype.m_callbackRemoved;
- m_callbackSwapped = prototype.m_callbackSwapped;
- m_autoConfigInstance = prototype.m_autoConfigInstance;
- m_defaultImplementation = prototype.m_defaultImplementation;
- }
- }
-
- //@Override
- public ServiceDependency setDebug(String identifier) {
- this.m_debug = true;
- this.m_debugKey = identifier;
- return this;
- }
-
- //@Override
- public Dependency createCopy() {
- return new ServiceDependencyImpl(this);
- }
-
- //@Override
- public synchronized boolean isAutoConfig() {
- return m_autoConfig;
- }
-
- //@Override
- public synchronized boolean isAvailable() {
- return m_isAvailable;
- }
-
- //@Override
- public void start(final DependencyService service) {
- m_serial.execute(new Runnable() {
- public void run() {
- // this code is executed exclusively and without holding any locks
- doStart(service);
- }
- });
- }
-
- //@Override
- public void stop(final DependencyService service) {
- m_serial.execute(new Runnable() {
- public void run() {
- // this code is executed exclusively and without holding any locks
- doStop(service);
- }
- });
- }
-
- //@Override
- public Object addingService(ServiceReference ref) {
- Object service = m_context.getService(ref);
- // first check to make sure the service is actually an instance of our service
- if (!m_trackedServiceName.isInstance(service)) {
- return null;
- }
- return service;
- }
-
- //@Override
- public void addedService(final ServiceReference ref, final Object service) {
- m_serial.execute(new Runnable() {
- public void run() {
- // this code is executed exclusively and without holding any locks
- doAddedService(ref, service);
- }
- });
- }
-
- //@Override
- public void modifiedService(final ServiceReference ref, final Object service) {
- m_serial.execute(new Runnable() {
- public void run() {
- // this code is executed exclusively and without holding any locks
- doModifiedService(ref, service);
- }
- });
- }
-
- //@Override
- public void removedService(final ServiceReference ref, final Object service) {
- m_serial.execute(new Runnable() {
- public void run() {
- // this code is executed exclusively and without holding any locks
- doRemovedService(ref, service);
- }
- });
- }
-
- //@Override
- public void invokeAdded(final DependencyService service) {
- m_serial.execute(new Runnable() {
- public void run() {
- // this code is executed exclusively and without holding any locks
- doInvokeAdded(service);
- }
- });
- }
-
- //@Override
- public void invokeRemoved(final DependencyService service) {
- m_serial.execute(new Runnable() {
- public void run() {
- // this code is executed exclusively and without holding any locks
- doInvokeRemoved(service);
- }
- });
- }
-
- //@Override
- public synchronized String toString() {
- return "ServiceDependency[" + m_trackedServiceName + " " + m_trackedServiceFilterUnmodified + "]";
- }
-
- //@Override
- public String getAutoConfigName() {
- return m_autoConfigInstance;
- }
-
- //@Override
- public Object getAutoConfigInstance() {
- return lookupService();
- }
-
- //@Override
- public Class getAutoConfigType() {
- return getInterface();
- }
-
- //@Override
- public String getName() {
- StringBuilder sb = new StringBuilder();
- if (m_trackedServiceName != null) {
- sb.append(m_trackedServiceName.getName());
- if (m_trackedServiceFilterUnmodified != null) {
- sb.append(' ');
- sb.append(m_trackedServiceFilterUnmodified);
- }
- }
- if (m_trackedServiceReference != null) {
- sb.append("{service.id=" + m_trackedServiceReference.getProperty(Constants.SERVICE_ID) + "}");
- }
- return sb.toString();
- }
-
- //@Override
- public String getType() {
- return "service";
- }
-
- //@Override
- public Dictionary getProperties() {
- ServiceReference reference = lookupServiceReference();
- Object service = lookupService();
- if (reference != null) {
- if (m_propagateCallbackInstance != null && m_propagateCallbackMethod != null) {
- try {
- return (Dictionary) InvocationUtil.invokeCallbackMethod(m_propagateCallbackInstance, m_propagateCallbackMethod,
- new Class[][]{{ServiceReference.class, Object.class}, {ServiceReference.class}}, new Object[][]{
- {reference, service}, {reference}});
- } catch (InvocationTargetException e) {
- m_logger.log(LogService.LOG_WARNING, "Exception while invoking callback method", e.getCause());
- } catch (Exception e) {
- m_logger.log(LogService.LOG_WARNING, "Exception while trying to invoke callback method", e);
- }
- throw new IllegalStateException("Could not invoke callback");
- } else {
- Properties props = new Properties();
- String[] keys = reference.getPropertyKeys();
- for (int i = 0; i < keys.length; i++) {
- if (!(keys[i].equals(Constants.SERVICE_ID) || keys[i].equals(Constants.SERVICE_PID))) {
- props.put(keys[i], reference.getProperty(keys[i]));
- }
- }
- return props;
- }
- } else {
- throw new IllegalStateException("cannot find service reference");
- }
- }
-
- //@Override
- public boolean isPropagated() {
- return m_propagate;
- }
-
- // ----- CREATION
-
- /**
- * Sets the name of the service that should be tracked.
- *
- * @param serviceName the name of the service
- * @return this service dependency
- */
- //@Override
- public synchronized ServiceDependency setService(Class serviceName) {
- setService(serviceName, null, null);
- return this;
- }
-
- /**
- * Sets the name of the service that should be tracked. You can either specify
- * only the name, only the filter, or the name and a filter.
- * <p>
- * If you specify name and filter, the filter is used
- * to track the service and should only return services of the type that was specified
- * in the name. To make sure of this, the filter is actually extended internally to
- * filter on the correct name.
- * <p>
- * If you specify only the filter, the name is assumed to be a service of type
- * <code>Object</code> which means that, when auto configuration is on, instances
- * of that service will be injected in any field of type <code>Object</code>.
- *
- * @param serviceName the name of the service
- * @param serviceFilter the filter condition
- * @return this service dependency
- */
- //@Override
- public synchronized ServiceDependency setService(Class serviceName, String serviceFilter) {
- setService(serviceName, null, serviceFilter);
- return this;
- }
-
- /**
- * Sets the name of the service that should be tracked. The name is assumed to be
- * a service of type <code>Object</code> which means that, when auto configuration
- * is on, instances of that service will be injected in any field of type
- * <code>Object</code>.
- *
- * @param serviceFilter the filter condition
- * @return this service dependency
- */
- //@Override
- public synchronized ServiceDependency setService(String serviceFilter) {
- if (serviceFilter == null) {
- throw new IllegalArgumentException("Service filter cannot be null.");
- }
- setService(null, null, serviceFilter);
- return this;
- }
-
- /**
- * Sets the name of the service that should be tracked. By specifying the service
- * reference of the service you want to track, you can directly track a single
- * service. The name you use must match the type of service referred to by the
- * service reference and it is up to you to make sure that is the case.
- *
- * @param serviceName the name of the service
- * @param serviceReference the service reference to track
- * @return this service dependency
- */
- //@Override
- public synchronized ServiceDependency setService(Class serviceName, ServiceReference serviceReference) {
- setService(serviceName, serviceReference, null);
- return this;
- }
-
- /**
- * Sets the default implementation for this service dependency. You can use this to supply
- * your own implementation that will be used instead of a Null Object when the dependency is
- * not available. This is also convenient if the service dependency is not an interface
- * (which would cause the Null Object creation to fail) but a class.
- *
- * @param implementation the instance to use or the class to instantiate if you want to lazily
- * instantiate this implementation
- * @return this service dependency
- */
- //@Override
- public synchronized ServiceDependency setDefaultImplementation(Object implementation) {
- ensureNotActive();
- m_defaultImplementation = implementation;
- return this;
- }
-
- /**
- * Sets the required flag which determines if this service is required or not.
- *
- * @param required the required flag
- * @return this service dependency
- */
- //@Override
- public synchronized ServiceDependency setRequired(boolean required) {
- ensureNotActive();
- setIsRequired(required);
- return this;
- }
-
- //@Override
- public ServiceDependency setInstanceBound(boolean isInstanceBound) {
- setIsInstanceBound(isInstanceBound);
- return this;
- }
-
- /**
- * Sets auto configuration for this service. Auto configuration allows the
- * dependency to fill in any attributes in the service implementation that
- * are of the same type as this dependency. Default is on.
- *
- * @param autoConfig the value of auto config
- * @return this service dependency
- */
- //@Override
- public synchronized ServiceDependency setAutoConfig(boolean autoConfig) {
- ensureNotActive();
- m_autoConfig = autoConfig;
- m_autoConfigInvoked = true;
- return this;
- }
-
- /**
- * Sets auto configuration for this service. Auto configuration allows the
- * dependency to fill in the attribute in the service implementation that
- * has the same type and instance name.
- *
- * @param instanceName the name of attribute to auto config
- * @return this service dependency
- */
- //@Override
- public synchronized ServiceDependency setAutoConfig(String instanceName) {
- ensureNotActive();
- m_autoConfig = (instanceName != null);
- m_autoConfigInstance = instanceName;
- m_autoConfigInvoked = true;
- return this;
- }
-
- /**
- * Sets the callbacks for this service. These callbacks can be used as hooks whenever a
- * dependency is added or removed. When you specify callbacks, the auto configuration
- * feature is automatically turned off, because we're assuming you don't need it in this
- * case.
- *
- * @param added the method to call when a service was added
- * @param removed the method to call when a service was removed
- * @return this service dependency
- */
- //@Override
- public synchronized ServiceDependency setCallbacks(String added, String removed) {
- return setCallbacks((Object) null, added, null, removed);
- }
-
- /**
- * Sets the callbacks for this service. These callbacks can be used as hooks whenever a
- * dependency is added, changed or removed. When you specify callbacks, the auto
- * configuration feature is automatically turned off, because we're assuming you don't
- * need it in this case.
- *
- * @param added the method to call when a service was added
- * @param changed the method to call when a service was changed
- * @param removed the method to call when a service was removed
- * @return this service dependency
- */
- //@Override
- public synchronized ServiceDependency setCallbacks(String added, String changed, String removed) {
- return setCallbacks((Object) null, added, changed, removed);
- }
-
- /**
- * Sets the callbacks for this service. These callbacks can be used as hooks whenever a
- * dependency is added, changed or removed. When you specify callbacks, the auto
- * configuration feature is automatically turned off, because we're assuming you don't
- * need it in this case.
- * @param added the method to call when a service was added
- * @param changed the method to call when a service was changed
- * @param removed the method to call when a service was removed
- * @param swapped the method to call when the service was swapped due to addition or
- * removal of an aspect
- * @return this service dependency
- */
- //@Override
- public synchronized ServiceDependency setCallbacks(String added, String changed, String removed, String swapped) {
- return setCallbacks((Object) null, added, changed, removed, swapped);
- }
-
- /**
- * Sets the callbacks for this service. These callbacks can be used as hooks whenever a
- * dependency is added or removed. They are called on the instance you provide. When you
- * specify callbacks, the auto configuration feature is automatically turned off, because
- * we're assuming you don't need it in this case.
- *
- * @param instance the instance to call the callbacks on
- * @param added the method to call when a service was added
- * @param removed the method to call when a service was removed
- * @return this service dependency
- */
- //@Override
- public synchronized ServiceDependency setCallbacks(Object instance, String added, String removed) {
- return setCallbacks(instance, added, (String) null, removed);
- }
-
- /**
- * Sets the callbacks for this service. These callbacks can be used as hooks whenever a
- * dependency is added, changed or removed. They are called on the instance you provide. When you
- * specify callbacks, the auto configuration feature is automatically turned off, because
- * we're assuming you don't need it in this case.
- *
- * @param instance the instance to call the callbacks on
- * @param added the method to call when a service was added
- * @param changed the method to call when a service was changed
- * @param removed the method to call when a service was removed
- * @return this service dependency
- */
- //@Override
- public synchronized ServiceDependency setCallbacks(Object instance, String added, String changed, String removed) {
- return setCallbacks(instance, added, changed, removed, null);
- }
-
- /**
- * Sets the callbacks for this service. These callbacks can be used as hooks whenever a
- * dependency is added, changed or removed. When you specify callbacks, the auto
- * configuration feature is automatically turned off, because we're assuming you don't
- * need it in this case.
- * @param instance the instance to call the callbacks on
- * @param added the method to call when a service was added
- * @param changed the method to call when a service was changed
- * @param removed the method to call when a service was removed
- * @param swapped the method to call when the service was swapped due to addition or
- * removal of an aspect
- * @return this service dependency
- */
- //@Override
- public synchronized ServiceDependency setCallbacks(Object instance, String added, String changed, String removed, String swapped) {
- ensureNotActive();
- // if at least one valid callback is specified, we turn off auto configuration, unless
- // someone already explicitly invoked autoConfig
- if ((added != null || removed != null || changed != null || swapped != null) && !m_autoConfigInvoked) {
- setAutoConfig(false);
- }
- m_callbackInstance = instance;
- m_callbackAdded = added;
- m_callbackChanged = changed;
- m_callbackRemoved = removed;
- m_callbackSwapped = swapped;
- return this;
- }
-
- //@Override
- public ServiceDependency setPropagate(boolean propagate) {
- ensureNotActive();
- m_propagate = propagate;
- return this;
- }
-
- //@Override
- public ServiceDependency setPropagate(Object instance, String method) {
- setPropagate(instance != null && method != null);
- m_propagateCallbackInstance = instance;
- m_propagateCallbackMethod = method;
- return this;
- }
-
- public void invoke(Object[] callbackInstances, DependencyService dependencyService, ServiceReference reference, Object service, String name) {
- if (m_debug) {
- m_logger.log(Logger.LOG_DEBUG, "[" + m_debugKey + "] invoke: " + name);
- }
- if (name != null) {
- dependencyService.invokeCallbackMethod(callbackInstances, name, new Class[][]{
- {Component.class, ServiceReference.class, m_trackedServiceName},
- {Component.class, ServiceReference.class, Object.class}, {Component.class, ServiceReference.class},
- {Component.class, m_trackedServiceName}, {Component.class, Object.class}, {Component.class},
- {Component.class, Map.class, m_trackedServiceName}, {ServiceReference.class, m_trackedServiceName},
- {ServiceReference.class, Object.class}, {ServiceReference.class}, {m_trackedServiceName}, {Object.class}, {},
- {Map.class, m_trackedServiceName}}, new Object[][]{{dependencyService, reference, service},
- {dependencyService, reference, service}, {dependencyService, reference}, {dependencyService, service},
- {dependencyService, service}, {dependencyService}, {dependencyService, new ServicePropertiesMap(reference), service},
- {reference, service}, {reference, service}, {reference}, {service}, {service}, {},
- {new ServicePropertiesMap(reference), service}});
- }
- }
-
- public void invokeSwappedCallback(Object[] callbackInstances, DependencyService component, ServiceReference previousReference, Object previous,
- ServiceReference currentServiceReference, Object current, String swapCallback) {
- // sanity check on the service references
- Integer oldRank = (Integer) previousReference.getProperty(Constants.SERVICE_RANKING);
- Integer newRank = (Integer) currentServiceReference.getProperty(Constants.SERVICE_RANKING);
-
- if (oldRank != null && newRank != null && oldRank.equals(newRank)) {
- throw new IllegalStateException("Attempt to swap a service for a service with the same rank! previousReference: "
- + previousReference + ", currentReference: " + currentServiceReference);
- }
-
- component.invokeCallbackMethod(callbackInstances, swapCallback, new Class[][]{
- {m_trackedServiceName, m_trackedServiceName}, {Object.class, Object.class},
- {ServiceReference.class, m_trackedServiceName, ServiceReference.class, m_trackedServiceName},
- {ServiceReference.class, Object.class, ServiceReference.class, Object.class},
- {Component.class, m_trackedServiceName, m_trackedServiceName}, {Component.class, Object.class, Object.class},
- {Component.class, ServiceReference.class, m_trackedServiceName, ServiceReference.class, m_trackedServiceName},
- {Component.class, ServiceReference.class, Object.class, ServiceReference.class, Object.class}}, new Object[][]{
- {previous, current}, {previous, current}, {previousReference, previous, currentServiceReference, current},
- {previousReference, previous, currentServiceReference, current}, {component, previous, current},
- {component, previous, current}, {component, previousReference, previous, currentServiceReference, current},
- {component, previousReference, previous, currentServiceReference, current}});
- }
-
- // --------------------------------------- Protected methods -------------------------------------------------------------------
-
- protected synchronized boolean makeAvailable() {
- if (!isAvailable()) {
- m_isAvailable = true;
- return true;
- }
- return false;
- }
-
- protected synchronized Object getService() {
- Object service = null;
- if (m_isStarted) {
- service = m_tracker.getService();
- }
- if (service == null && isAutoConfig()) {
- service = getDefaultImplementation();
- if (service == null) {
- service = getNullObject();
- }
- }
- return service;
- }
-
- // --------------------------------------- Private methods --------------------------------------------
-
- private void doStart(DependencyService service) {
- boolean needsStarting = false;
- synchronized (this) {
- m_services.add(service);
- if (!m_isStarted) {
- if (m_trackedServiceName != null) {
- if (m_trackedServiceFilter != null) {
- try {
- m_tracker = new ServiceTracker(m_context, m_context.createFilter(m_trackedServiceFilter), this);
- } catch (InvalidSyntaxException e) {
- throw new IllegalStateException("Invalid filter definition for dependency: " + m_trackedServiceFilter);
- }
- } else if (m_trackedServiceReference != null) {
- m_tracker = new ServiceTracker(m_context, m_trackedServiceReference, this);
- } else {
- m_tracker = new ServiceTracker(m_context, m_trackedServiceName.getName(), this);
- }
- } else {
- throw new IllegalStateException("Could not create tracker for dependency, no service name specified.");
- }
- m_isStarted = true;
- needsStarting = true;
- }
- }
- if (needsStarting) {
- // when the swapped callback is set, also track the aspects
- boolean trackAllServices = false;
- boolean trackAllAspects = false;
- if (m_callbackSwapped != null) {
- trackAllAspects = true;
- }
- m_tracker.open(trackAllServices, trackAllAspects);
- }
- }
-
- private void doStop(DependencyService service) {
- boolean needsStopping = false;
- synchronized (this) {
- if (m_services.size() == 1 && m_services.contains(service)) {
- m_isStarted = false;
- needsStopping = true;
- }
- }
- if (needsStopping) {
- m_tracker.close();
- m_tracker = null;
- }
- //moved this down
- synchronized (this) {
- m_services.remove(service);
- }
- }
-
- private void doAddedService(ServiceReference ref, Object service) {
- if (m_debug) {
- m_logger.log(Logger.LOG_DEBUG, "[" + m_debugKey + "] addedservice: " + ref);
- }
- boolean makeAvailable = makeAvailable();
-
- Object[] services;
- synchronized (this) {
- services = m_services.toArray();
- }
- for (int i = 0; i < services.length; i++) {
- DependencyService ds = (DependencyService) services[i];
- if (makeAvailable) {
- if (ds.isInstantiated() && isInstanceBound() && isRequired()) {
- if (m_debug) {
- m_logger.log(Logger.LOG_DEBUG, "[" + m_debugKey + "] invoke added: " + ref);
- }
- invokeAdded(ds, ref, service);
- }
- // The dependency callback will be deferred until all required dependency are available.
- if (m_debug) {
- m_logger.log(Logger.LOG_DEBUG, "[" + m_debugKey + "] dependency available: " + ref);
- }
- ds.dependencyAvailable(this); //**
- if (!isRequired()) {
- // For optional dependency, we always invoke callback, because at this point, we know
- // that the service has been started, and the service start method has been called.
- // (See the ServiceImpl.bindService method, which will activate optional dependencies using
- // startTrackingOptional() method).
- if (m_debug) {
- m_logger.log(Logger.LOG_DEBUG, "[" + m_debugKey + "] invoke added: " + ref);
- }
- invokeAdded(ds, ref, service);
- }
- } else {
- if (m_debug) {
- m_logger.log(Logger.LOG_DEBUG, "[" + m_debugKey + "] dependency added (was available): " + ref);
- }
- // First, inject the added service in autoconfig field, if any.
- ds.autoConfig(this);
-
- // At this point, either the dependency is optional (meaning that the service has been started,
- // because if not, then our dependency would not be active); or the dependency is required,
- // meaning that either the service is not yet started, or already started.
- // In all cases, we have to inject the required dependency.
- // we only try to invoke the method here if we are really already instantiated
- if (ds.isInstantiated() && ds.getCompositionInstances().length > 0) {
- if (m_debug) {
- m_logger.log(Logger.LOG_DEBUG, "[" + m_debugKey + "] invoke added: " + ref);
- }
- if (invokeAdded(ds, ref, service)) {
- // Propagate (if needed) all "setPropagate" dependencies to the dependency service.
- ds.propagate(this);
- }
- }
- }
- }
- }
-
- private void doModifiedService(ServiceReference ref, Object service) {
- Object[] services;
- synchronized (this) {
- services = m_services.toArray();
- }
- for (int i = 0; i < services.length; i++) {
- DependencyService ds = (DependencyService) services[i];
- ds.autoConfig(this);
- if (ds.isInstantiated()) {
- if (invokeChanged(ds, ref, service)) {
- // The "change" or "swap" callback has been invoked (if not it means that the modified service
- // is for a lower ranked aspect to which we are not interested in).
- // Now, propagate (if needed) changed properties to dependency service properties.
- ds.propagate(this);
- }
- }
- }
- }
-
- private void doRemovedService(ServiceReference ref, Object service) {
- if (m_debug) {
- m_logger.log(Logger.LOG_DEBUG, "[" + m_debugKey + "] removedService: " + ref + ", rank: " + ref.getProperty("service.ranking"));
- }
- boolean makeUnavailable = makeUnavailable();
- if (m_debug) {
- m_logger.log(Logger.LOG_DEBUG, "[" + m_debugKey + "] make unavailable: " + makeUnavailable);
- }
- Object[] services;
- synchronized (this) {
- services = m_services.toArray();
- }
-
- for (int i = 0; i < services.length; i++) {
- DependencyService ds = (DependencyService) services[i];
- if (makeUnavailable) {
- ds.dependencyUnavailable(this);
- // when the dependency is optional or the dependency is instance bound and the component is instantiated (and the dependency is required)
- // then remove is invoked. In other cases the removed has been when the component was unconfigured.
- if (!isRequired() || (ds.isInstantiated() && isInstanceBound())) {
- invokeRemoved(ds, ref, service);
- }
- } else {
- // Some dependencies are still available: first inject the remaining highest ranked dependency
- // in component class field, if the dependency is configured in autoconfig mode.
- ds.autoConfig(this);
- // Next, invoke "removed" callback. If the dependency is aspect aware, we only invoke removed cb
- // if the removed service is the highest ranked service. Note that if the cb is not called, we don't
- // propagate the remaining dependency properties.
- if (invokeRemoved(ds, ref, service)) {
- // Finally, since we have lost one dependency, we have to possibly propagate the highest ranked
- // dependency available.
- ds.propagate(this);
- }
- }
- }
- // unget what we got in addingService (see ServiceTracker 701.4.1)
- m_context.ungetService(ref);
-
- }
-
- private void doInvokeAdded(DependencyService service) {
- if (m_debug) {
- m_logger.log(Logger.LOG_DEBUG, "[" + m_debugKey + "] invoke added due to configure. (component is activated)");
- }
- ServiceReference[] refs = m_tracker.getServiceReferences();
- if (refs != null) {
- for (int i = 0; i < refs.length; i++) {
- ServiceReference sr = refs[i];
- Object svc = m_context.getService(sr);
- invokeAdded(service, sr, svc);
- }
- }
- }
-
- private void doInvokeRemoved(DependencyService service) {
- if (m_debug) {
- m_logger.log(Logger.LOG_DEBUG, "[" + m_debugKey + "] invoke removed due to unconfigure. (component is destroyed)");
- }
- Set references = null;
- Object[] tupleArray = null;
- synchronized (m_sr) {
- references = (Set) m_sr.get(service);
- // is this null check necessary ??
- if (references != null) {
- tupleArray = references.toArray(new Tuple[references.size()]);
- }
- }
-
- Tuple[] refs = (Tuple[]) (tupleArray != null ? tupleArray : new Tuple[0]);
-
- for (int i = 0; i < refs.length; i++) {
- ServiceReference sr = refs[i].getServiceReference();
- Object svc = refs[i].getService();
- invokeRemoved(service, sr, svc);
- }
- }
-
- private Object lookupService() {
- Object service = null;
- if (m_isStarted) {
- service = getService();
- } else {
- ServiceReference[] refs = null;
- ServiceReference ref = null;
- if (m_trackedServiceName != null) {
- if (m_trackedServiceFilter != null) {
- try {
- refs = m_context.getServiceReferences(m_trackedServiceName.getName(), m_trackedServiceFilter);
- if (refs != null) {
- Arrays.sort(refs, COMPARATOR);
- ref = refs[0];
- }
- } catch (InvalidSyntaxException e) {
- throw new IllegalStateException("Invalid filter definition for dependency.");
- }
- } else if (m_trackedServiceReference != null) {
- ref = m_trackedServiceReference;
- } else {
- ref = m_context.getServiceReference(m_trackedServiceName.getName());
- }
- if (ref != null) {
- service = m_context.getService(ref);
- }
- } else {
- throw new IllegalStateException("Could not lookup dependency, no service name specified.");
- }
- }
- if (service == null && isAutoConfig()) {
- service = getDefaultImplementation();
- if (service == null) {
- service = getNullObject();
- }
- }
- return service;
- }
-
- private ServiceReference lookupServiceReference() {
- // TODO lots of duplication in lookupService()
- ServiceReference service = null;
- if (m_isStarted) {
- service = m_tracker.getServiceReference();
- } else {
- ServiceReference[] refs = null;
- ServiceReference ref = null;
- if (m_trackedServiceName != null) {
- if (m_trackedServiceFilter != null) {
- try {
- refs = m_context.getServiceReferences(m_trackedServiceName.getName(), m_trackedServiceFilter);
- if (refs != null) {
- Arrays.sort(refs, COMPARATOR);
- ref = refs[0];
- }
- } catch (InvalidSyntaxException e) {
- throw new IllegalStateException("Invalid filter definition for dependency.");
- }
- } else if (m_trackedServiceReference != null) {
- ref = m_trackedServiceReference;
- } else {
- ref = m_context.getServiceReference(m_trackedServiceName.getName());
- }
- if (ref != null) {
- service = ref;
- }
- } else {
- throw new IllegalStateException("Could not lookup dependency, no service name specified.");
- }
- }
- return service;
- }
-
- private synchronized Class getInterface() {
- return m_trackedServiceName;
- }
-
- private Object getNullObject() {
- if (m_nullObject == null) {
- Class trackedServiceName;
- synchronized (this) {
- trackedServiceName = m_trackedServiceName;
- }
- try {
- m_nullObject = Proxy.newProxyInstance(trackedServiceName.getClassLoader(), new Class[]{trackedServiceName},
- new DefaultNullObject());
- } catch (Exception e) {
- m_logger.log(Logger.LOG_ERROR, "Could not create null object for " + trackedServiceName + ".", e);
- }
- }
- return m_nullObject;
- }
-
- private Object getDefaultImplementation() {
- if (m_defaultImplementation != null) {
- if (m_defaultImplementation instanceof Class) {
- try {
- m_defaultImplementationInstance = ((Class) m_defaultImplementation).newInstance();
- } catch (Exception e) {
- m_logger.log(Logger.LOG_ERROR, "Could not create default implementation instance of class " + m_defaultImplementation
- + ".", e);
- }
- } else {
- m_defaultImplementationInstance = m_defaultImplementation;
- }
- }
- return m_defaultImplementationInstance;
- }
-
- /**
- * Invoke added or swap callback.
- * @return true if one of the swap/added callbacks has been invoked, false if not, meaning that the added dependency is not the highest ranked one.
- */
- private boolean invokeAdded(DependencyService dependencyService, ServiceReference reference, Object service) {
- // We are already serialized.
- if (m_debug) {
- m_logger.log(Logger.LOG_DEBUG, "[" + m_debugKey + "] invoke added");
- }
- boolean added = false;
- synchronized (m_sr) {
- Set set = (Set) m_sr.get(dependencyService);
- if (set == null) {
- set = new HashSet();
- m_sr.put(dependencyService, set);
- }
- added = set.add(new Tuple(reference, service));
- }
- if (added) {
- // when a changed callback is specified we might not call the added callback just yet
- if (m_callbackSwapped != null) {
- return handleAspectAwareAdded(dependencyService, reference, service);
- } else {
- invoke(dependencyService, reference, service, m_callbackAdded);
- return true;
- }
- }
- return false;
- }
-
- private boolean invokeChanged(DependencyService dependencyService, ServiceReference reference, Object service) {
- if (m_callbackSwapped != null) {
- if (m_debug) {
- m_logger.log(Logger.LOG_DEBUG, "[" + m_debugKey + "] handleAspectAwareChanged on " + service);
- }
- return handleAspectAwareChanged(dependencyService, reference, service);
- }
- invoke(dependencyService, reference, service, m_callbackChanged);
- return true;
- }
-
- /*
- * Invoke the removed or the swap callback.
- * @return true if the swap or the removed callback has been called, false if not.
- */
- private boolean invokeRemoved(DependencyService dependencyService, ServiceReference reference, Object service) {
- if (m_debug) {
- m_logger.log(Logger.LOG_DEBUG, "[" + m_debugKey + "] invoke removed");
- }
- boolean removed = false;
- synchronized (m_sr) {
- Set set = (Set) m_sr.get(dependencyService);
- removed = (set != null && set.remove(new Tuple(reference, service)));
- }
- if (m_debug) {
- m_logger.log(Logger.LOG_DEBUG, "[" + m_debugKey + "] removed: " + removed);
- }
- if (removed) {
- if (m_callbackSwapped != null) {
- return handleAspectAwareRemoved(dependencyService, reference, service);
- } else {
- invoke(dependencyService, reference, service, m_callbackRemoved);
- return true;
- }
- }
- return false;
- }
-
- private void invoke(DependencyService dependencyService, ServiceReference reference, Object service, String name) {
- invoke(getCallbackInstances(dependencyService), dependencyService, reference, service, name);
- }
-
- /**
- * Invoke added or swap callback for aspect aware service dependency.
- * @return true if one of the swap/added callbacks has been invoked, false if not, meaning that the added dependency is not the highest ranked one.
- */
- private boolean handleAspectAwareAdded(final DependencyService dependencyService, final ServiceReference reference, final Object service) {
- // At this point, we are already serialized: no need to synchronized.
- if (m_debug) {
- m_logger.log(Logger.LOG_DEBUG, "[" + m_debugKey + "] aspectawareadded: " + reference.getProperty("service.ranking"));
- }
- if (componentIsDependencyManagerFactory(dependencyService)) {
- // component is either aspect or adapter factory instance, these must be ignored.
- return false;
- }
- boolean invokeAdded = false;
- boolean invokeSwapped = false;
- Integer ranking = ServiceUtil.getRankingAsInteger(reference);
- Tuple newHighestRankedService = null;
- Tuple prevHighestRankedService = null;
- Map rankings = null;
-
- Long originalServiceId = ServiceUtil.getServiceIdAsLong(reference);
- Map componentMap = (Map) m_componentByRank.get(dependencyService); /* <Long, Map<Integer, Tuple>> */
- if (componentMap == null) {
- // create new componentMap
- componentMap = new HashMap(); /* <Long, Map<Integer, Tuple>> */
- m_componentByRank.put(dependencyService, componentMap);
- }
- rankings = (Map) componentMap.get(originalServiceId); /* <Integer, Tuple> */
- if (rankings == null) {
- // new component added
- rankings = new HashMap(); /* <Integer, Tuple> */
- componentMap.put(originalServiceId, rankings);
- rankings.put(ranking, new Tuple(reference, service));
- invokeAdded = true;
- }
-
- if (!invokeAdded) {
- // current highest ranked
- prevHighestRankedService = (Tuple) getHighestRankedService(dependencyService, originalServiceId).getValue();
- newHighestRankedService = swapHighestRankedService(dependencyService, originalServiceId, reference, service, ranking);
- if (m_debug) {
- m_logger.log(Logger.LOG_DEBUG, "[" + m_debugKey + "] prevhigh: " + prevHighestRankedService.getServiceReference().getProperty("service.ranking") + ", new high: " +
- newHighestRankedService.getServiceReference().getProperty("service.ranking"));
- }
- if (!prevHighestRankedService.getServiceReference().equals(newHighestRankedService.getServiceReference())) {
- // new highest ranked service
- if (m_debug) {
- m_logger.log(Logger.LOG_DEBUG, "[" + m_debugKey + "] New highest ranked to swap to");
- }
- invokeSwapped = true;
- } else {
- if (m_debug) {
- m_logger.log(Logger.LOG_DEBUG, "[" + m_debugKey + "] Ignoring lower ranked or irrelevant swap");
- }
- }
- }
- if (m_debug) {
- m_logger.log(Logger.LOG_DEBUG, "[" + m_debugKey + "] " + m_componentByRank.toString());
- }
-
- // up until this point should be synchronized on m_componentsByRank to keep integrity of the administration and consequences
- // then the do phase comes, here we want to guarantee the effects of this operation are done like they were synchronized, however
- // synchronization on m_componentsByRank to too course grained here, so we'd like to switch to synchronization on the
- // original service id, therefore we're using our own guarded block to ensure the correct order.
-
- if (invokeAdded) {
- if (m_debug) {
- m_logger.log(Logger.LOG_DEBUG, "[" + m_debugKey + "] invoke added: " + reference.getProperty("service.ranking"));
- }
- // We can safely invoke callback since we are already serialized.
- invoke(dependencyService, reference, service, m_callbackAdded);
- return true;
- } else if (invokeSwapped) {
- if (m_debug) {
- m_logger.log(Logger.LOG_DEBUG, "[" + m_debugKey + "] invoke swapped: " + newHighestRankedService.getServiceReference().getProperty("service.ranking") + " replacing " +
- prevHighestRankedService.getServiceReference().getProperty("service.ranking"));
- }
- // We can safely invoke callback since we are already serialized.
- invokeSwappedCallback(dependencyService, prevHighestRankedService.getServiceReference(), prevHighestRankedService.getService(),
- newHighestRankedService.getServiceReference(), newHighestRankedService.getService());
- return true;
- }
- return false;
- }
-
- private boolean componentIsDependencyManagerFactory(DependencyService dependencyService) {
- Object component = dependencyService.getService();
- if (component != null) {
- String className = component.getClass().getName();
- return className.startsWith("org.apache.felix.dm")
- && !className.startsWith("org.apache.felix.dm.impl.AdapterServiceImpl$AdapterImpl")
- && !className.startsWith("org.apache.felix.dm.test");
- }
- return false;
- }
-
- private Tuple swapHighestRankedService(DependencyService dependencyService, Long serviceId, ServiceReference newReference,
- Object newService, Integer newRanking) {
- // does a component with a higher ranking exist
- synchronized (m_componentByRank) {
- Map componentMap = (Map) m_componentByRank.get(dependencyService); /* <Long, Map<Integer, Tuple>> */
- Map rankings = (Map) componentMap.get(serviceId); /* <Integer, Tuple> */
- rankings.put(newRanking, new Tuple(newReference, newService));
- Entry highestEntry = getHighestRankedService(dependencyService, serviceId); /* <Integer, Tuple> */
- return (Tuple) highestEntry.getValue();
- }
- }
-
- private Entry getHighestRankedService(DependencyService dependencyService, Long serviceId) { /* <Integer, Tuple> */
- Entry highestEntry = null; /* <Integer, Tuple> */
- Map componentMap = (Map) m_componentByRank.get(dependencyService); /* <Long, Map<Integer, Tuple>> */
- Map rankings = (Map) componentMap.get(serviceId); /* <Integer, Tuple> */
- if (rankings != null) {
- for (Iterator entryIterator = rankings.entrySet().iterator(); entryIterator.hasNext();) { /* <Integer, Tuple> */
- Entry mapEntry = (Entry) entryIterator.next();
- if (highestEntry == null) {
- highestEntry = mapEntry;
- } else {
- if (((Integer) mapEntry.getKey()).intValue() > ((Integer) highestEntry.getKey()).intValue()) {
- highestEntry = mapEntry;
- }
- }
- }
- }
- return highestEntry;
- }
-
- private boolean isLastService(DependencyService dependencyService, ServiceReference reference, Object object, Long serviceId) {
- // get the collection of rankings
- Map componentMap = (Map) m_componentByRank.get(dependencyService); /* <Long, Map<Integer, Tuple>> */
-
- Map rankings = null; /* <Integer, Tuple> */
- if (componentMap != null) {
- rankings = (Map) componentMap.get(serviceId);
- }
- // if there is only one element left in the collection of rankings
- // and this last element has the same ranking as the supplied service (in other words, it is the same)
- // then this is the last service
- // NOTE: it is possible that there is only one element, but that it's not equal to the supplied service,
- // because an aspect on top of the original service is being removed (but the original service is still
- // there). That in turn triggers:
- // 1) a call to added(original-service)
- // 2) that causes a swap
- // 3) a call to removed(aspect-service) <-- that's what we're talking about
- if (m_debug) {
- m_logger.log(Logger.LOG_DEBUG, "[" + m_debugKey + "] last service: " + m_componentByRank.toString());
- }
- return (componentMap != null && rankings != null && rankings.size() == 1 && ((Entry) rankings.entrySet().iterator().next())
- .getKey().equals(ServiceUtil.getRankingAsInteger(reference)));
- }
-
- private boolean handleAspectAwareChanged(DependencyService dependencyService, ServiceReference reference, Object service) {
- if (m_debug) {
- m_logger.log(Logger.LOG_DEBUG, "[" + m_debugKey + "] aspectawareChanged: service.ranking=" + reference.getProperty("service.ranking"));
- }
- if (componentIsDependencyManagerFactory(dependencyService)) {
- // component is either aspect or adapter factory instance, these must be ignored.
- return false;
- }
- boolean invokeChanged = false;
-
- // Determine current highest ranked service: we'll take into account the change event only if it
- // comes from the highest ranked service.
- Long serviceId = ServiceUtil.getServiceIdAsLong(reference);
- Map componentMap = (Map) m_componentByRank.get(dependencyService); /* <Long, Map<Integer, Tuple>> */
- if (componentMap != null) {
- Map rankings = (Map) componentMap.get(serviceId); /* <Integer, Tuple> */
- if (rankings != null) {
- Entry highestEntry = getHighestRankedService(dependencyService, serviceId); /* <Integer, Tuple> */
- if (m_debug) {
- m_logger.log(Logger.LOG_DEBUG, "[" + m_debugKey + "] highest service ref:" + highestEntry);
- }
- if (highestEntry == null) {
- invokeChanged = true;
- } else {
- Tuple tuple = (Tuple) highestEntry.getValue();
- if (reference.equals(tuple.getServiceReference())) {
- // The changed service is the highest ranked service: we can handle the modification event.
- invokeChanged = true;
- }
- }
- }
- }
-
- if (m_debug) {
- m_logger.log(Logger.LOG_DEBUG, "[" + m_debugKey + "] invokeChanged=" + invokeChanged);
- }
-
- if (invokeChanged) {
- if (m_debug) {
- m_logger.log(Logger.LOG_DEBUG, "[" + m_debugKey + "] invoke changed: ref ranking=" + reference.getProperty("service.ranking"));
- }
- invoke(dependencyService, reference, service, m_callbackChanged);
- return true;
- }
- return false;
- }
-
- /*
- * handles aspect aware removed service.
- * @return true if the swap or the removed callback has been called, false if not.
- */
- private boolean handleAspectAwareRemoved(DependencyService dependencyService, ServiceReference reference, Object service) {
- if (m_debug) {
- m_logger.log(Logger.LOG_DEBUG, "[" + m_debugKey + "] aspectawareremoved: " + reference.getProperty("service.ranking"));
- }
- if (componentIsDependencyManagerFactory(dependencyService)) {
- // component is either aspect or adapter factory instance, these must be ignored.
- return false;
- }
- // we might need to swap here too!
- boolean invokeRemoved = false;
- Long serviceId = ServiceUtil.getServiceIdAsLong(reference);
- Tuple prevHighestRankedService = null;
- Tuple newHighestRankedService = null;
- boolean invokeSwapped = false;
- Map rankings = null;
- Long originalServiceId = ServiceUtil.getServiceIdAsLong(reference);
-
- if (isLastService(dependencyService, reference, service, serviceId)) {
- invokeRemoved = true;
- } else {
- // not the last service, but should we swap?
- prevHighestRankedService = (Tuple) getHighestRankedService(dependencyService, originalServiceId).getValue();
- if (prevHighestRankedService.getServiceReference().equals(reference)) {
- // swapping out
- if (m_debug) {
- m_logger.log(Logger.LOG_DEBUG, "[" + m_debugKey + "] Swap out on remove!");
- }
- invokeSwapped = true;
- }
- }
- if (m_debug) {
- m_logger.log(Logger.LOG_DEBUG, "[" + m_debugKey + "] is last service: " + invokeRemoved);
- }
- // cleanup
- Map componentMap = (Map) m_componentByRank.get(dependencyService); /* <Long, Map<Integer, Tuple>> */
- if (componentMap != null) {
- rankings = (Map) componentMap.get(originalServiceId); /* <Integer, Tuple> */
- List rankingsToRemove = new ArrayList();
- for (Iterator entryIterator = rankings.entrySet().iterator(); entryIterator.hasNext();) {
- Entry mapEntry = (Entry) entryIterator.next();
- if (((Tuple) mapEntry.getValue()).getServiceReference().equals(reference)) {
- // remove the reference
- // rankings.remove(mapEntry.getKey());
- rankingsToRemove.add(mapEntry.getKey());
- }
- }
- for (Iterator rankingIterator = rankingsToRemove.iterator(); rankingIterator.hasNext();) {
- rankings.remove(rankingIterator.next());
- }
- if (rankings.size() == 0) {
- componentMap.remove(originalServiceId);
- }
- if (componentMap.size() == 0) {
- m_componentByRank.remove(dependencyService);
- }
- }
- // determine current highest ranked service
- if (invokeSwapped) {
- newHighestRankedService = (Tuple) getHighestRankedService(dependencyService, originalServiceId).getValue();
- }
- if (invokeRemoved) {
- // handle invoke outside the sync block since we won't know what will happen there
- if (m_debug) {
- m_logger.log(Logger.LOG_DEBUG, "[" + m_debugKey + "] invoke removed: " + reference.getProperty("service.ranking"));
- }
- // We can safely invoke callback, since we are already serialized
- invoke(dependencyService, reference, service, m_callbackRemoved);
- return true;
- } else if (invokeSwapped) {
- if (m_debug) {
- m_logger.log(Logger.LOG_DEBUG, "[" + m_debugKey + "] invoke swapped: " + newHighestRankedService.getServiceReference().getProperty("service.ranking") + " replacing " +
- prevHighestRankedService.getServiceReference().getProperty("service.ranking"));
- }
- // We can safely invoke callback, since we are already serialized
- invokeSwappedCallback(dependencyService, prevHighestRankedService.getServiceReference(), prevHighestRankedService.getService(),
- newHighestRankedService.getServiceReference(), newHighestRankedService.getService());
- return true;
- }
-
- return false;
- }
-
- private void invokeSwappedCallback(DependencyService component, ServiceReference previousReference, Object previous,
- ServiceReference currentServiceReference, Object current) {
- invokeSwappedCallback(getCallbackInstances(component), component, previousReference, previous, currentServiceReference, current, m_callbackSwapped);
- }
-
- private synchronized boolean makeUnavailable() {
- // TODO should we check also m_isStarted ?
- if ((isAvailable()) && (m_isStarted == false || !m_tracker.hasReference())) {
- m_isAvailable = false;
- return true;
- }
- return false;
- }
-
- private synchronized Object[] getCallbackInstances(DependencyService dependencyService) {
- if (m_callbackInstance == null) {
- return dependencyService.getCompositionInstances();
- } else {
- return new Object[]{m_callbackInstance};
- }
- }
-
- // ----- CREATION
-
- /** Internal method to set the name, service reference and/or filter. */
- private void setService(Class serviceName, ServiceReference serviceReference, String serviceFilter) {
- ensureNotActive();
- if (serviceName == null) {
- m_trackedServiceName = Object.class;
- } else {
- m_trackedServiceName = serviceName;
- }
- if (serviceFilter != null) {
- m_trackedServiceFilterUnmodified = serviceFilter;
- if (serviceName == null) {
- m_trackedServiceFilter = serviceFilter;
- } else {
- m_trackedServiceFilter = "(&(" + Constants.OBJECTCLASS + "=" + serviceName.getName() + ")" + serviceFilter + ")";
- }
- } else {
- m_trackedServiceFilterUnmodified = null;
- m_trackedServiceFilter = null;
- }
- if (serviceReference != null) {
- m_trackedServiceReference = serviceReference;
- if (serviceFilter != null) {
- throw new IllegalArgumentException("Cannot specify both a filter and a service reference.");
- }
- } else {
- m_trackedServiceReference = null;
- }
- }
-
- private void ensureNotActive() {
- if (m_tracker != null) {
- throw new IllegalStateException("Cannot modify state while active.");
- }
- }
-}
diff --git a/dependencymanager/core/src/main/java/org/apache/felix/dm/impl/dependencies/TemporalServiceDependencyImpl.java b/dependencymanager/core/src/main/java/org/apache/felix/dm/impl/dependencies/TemporalServiceDependencyImpl.java
deleted file mode 100644
index 73518b2..0000000
--- a/dependencymanager/core/src/main/java/org/apache/felix/dm/impl/dependencies/TemporalServiceDependencyImpl.java
+++ /dev/null
@@ -1,190 +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.felix.dm.impl.dependencies;
-
-import java.lang.reflect.InvocationHandler;
-import java.lang.reflect.Method;
-import java.lang.reflect.Proxy;
-
-import org.apache.felix.dm.DependencyActivatorBase;
-import org.apache.felix.dm.DependencyService;
-import org.apache.felix.dm.ServiceDependency;
-import org.apache.felix.dm.TemporalServiceDependency;
-import org.apache.felix.dm.impl.Logger;
-import org.osgi.framework.Bundle;
-import org.osgi.framework.BundleContext;
-import org.osgi.framework.ServiceReference;
-
-/**
- * Temporal Service dependency implementation, used to hide temporary service dependency "outage".
- * Only works with a required dependency.
- *
- * @author <a href="mailto:dev@felix.apache.org">Felix Project Team</a>
- */
-public class TemporalServiceDependencyImpl extends ServiceDependencyImpl implements TemporalServiceDependency, InvocationHandler {
- // Max millis to wait for service availability.
- private long m_timeout = 30000;
-
- // Dependency service currently used (with highest rank or highest service id).
- private volatile Object m_cachedService;
-
- // Framework bundle (we use it to detect if the framework is stopping)
- private final Bundle m_frameworkBundle;
-
- // The service proxy, which blocks when service is not available.
- private Object m_serviceInstance;
-
- /**
- * Creates a new Temporal Service Dependency.
- *
- * @param context The bundle context of the bundle which is instantiating this dependency object
- * @param logger the logger our Internal logger for logging events.
- * @see DependencyActivatorBase#createTemporalServiceDependency()
- */
- public TemporalServiceDependencyImpl(BundleContext context, Logger logger) {
- super(context, logger);
- super.setRequired(true);
- m_frameworkBundle = context.getBundle(0);
- }
-
- /**
- * Sets the timeout for this temporal dependency. Specifying a timeout value of zero means that there is no timeout period,
- * and an invocation on a missing service will fail immediately.
- *
- * @param timeout the dependency timeout value greater or equals to 0
- * @throws IllegalArgumentException if the timeout is negative
- * @return this temporal dependency
- */
- public synchronized TemporalServiceDependency setTimeout(long timeout) {
- if (timeout < 0) {
- throw new IllegalArgumentException("Invalid timeout value: " + timeout);
- }
- m_timeout = timeout;
- return this;
- }
-
- /**
- * Sets the required flag which determines if this service is required or not. This method
- * just override the superclass method in order to check if the required flag is true
- * (optional dependency is not supported by this class).
- *
- * @param required the required flag, which must be set to true
- * @return this service dependency
- * @throws IllegalArgumentException if the "required" parameter is not true.
- */
- //@Override
- public ServiceDependency setRequired(boolean required) {
- if (! required) {
- throw new IllegalArgumentException("A Temporal Service dependency can't be optional");
- }
- super.setRequired(required);
- return this;
- }
-
- /**
- * The ServiceTracker calls us here in order to inform about a service arrival.
- */
- //@Override
- public synchronized void addedService(ServiceReference ref, Object service) {
- // Update our service cache, using the tracker. We do this because the
- // just added service might not be the service with the highest rank ...
- m_cachedService = m_tracker.getService();
- boolean makeAvailable = makeAvailable();
- if (makeAvailable) {
- m_serviceInstance = Proxy.newProxyInstance(m_trackedServiceName.getClassLoader(), new Class[] { m_trackedServiceName }, this);
- }
- Object[] services = m_services.toArray();
- for (int i = 0; i < services.length; i++) {
- DependencyService ds = (DependencyService) services[i];
- if (makeAvailable) {
- ds.dependencyAvailable(this);
- }
- }
- if (!makeAvailable) {
- notifyAll();
- }
- }
-
- /**
- * The ServiceTracker calls us here when a tracked service properties are modified.
- */
- //@Override
- public void modifiedService(ServiceReference ref, Object service) {
- // We don't care.
- }
-
- /**
- * The ServiceTracker calls us here when a tracked service is lost.
- */
- //@Override
- public synchronized void removedService(ServiceReference ref, Object service) {
- // If we detect that the fwk is stopping, we behave as our superclass. That is:
- // the lost dependency has to trigger our service deactivation, since the fwk is stopping
- // and the lost dependency won't come up anymore.
- if (m_frameworkBundle.getState() == Bundle.STOPPING) {
- // Important: Notice that calling "super.removedService() might invoke our service "stop"
- // callback, which in turn might invoke the just removed service dependency. In this case,
- // our "invoke" method won't use the tracker to get the service dependency (because at this point,
- // the tracker has withdrawn its reference to the lost service). So, you will see that the "invoke"
- // method will use the "m_cachedService" instead ...
- super.removedService(ref, service);
- } else {
- // Unget what we got in addingService (see ServiceTracker 701.4.1)
- m_context.ungetService(ref);
- // Now, ask the service tracker if there is another available service (with a lower rank).
- // If no more service dependencies are available, the tracker will then return null;
- // and our invoke method will block the service method invocation, until another service
- // becomes available.
- m_cachedService = m_tracker.getService();
- }
- }
-
- /**
- * @returns our dependency instance. Unlike in ServiceDependency, we always returns our proxy.
- */
- //@Override
- protected synchronized Object getService() {
- return m_serviceInstance;
- }
-
- //@Override
- public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
- Object service = m_cachedService;
- if (service == null) {
- synchronized (this) {
- long start = System.currentTimeMillis();
- long waitTime = m_timeout;
- while (service == null) {
- if (waitTime <= 0) {
- throw new IllegalStateException("Service unavailable: " + m_trackedServiceName.getName());
- }
- try {
- wait(waitTime);
- }
- catch (InterruptedException e) {
- throw new IllegalStateException("Service unavailable: " + m_trackedServiceName.getName());
- }
- waitTime = m_timeout - (System.currentTimeMillis() - start);
- service = m_cachedService;
- }
-
- }
- }
- try {
- return method.invoke(service, args);
- }
- catch (IllegalAccessException iae) {
- method.setAccessible(true);
- return method.invoke(service, args);
- }
- }
-}
diff --git a/dependencymanager/core/src/main/java/org/apache/felix/dm/impl/index/AbstractFactoryFilterIndex.java b/dependencymanager/core/src/main/java/org/apache/felix/dm/impl/index/AbstractFactoryFilterIndex.java
deleted file mode 100644
index 95df931..0000000
--- a/dependencymanager/core/src/main/java/org/apache/felix/dm/impl/index/AbstractFactoryFilterIndex.java
+++ /dev/null
@@ -1,95 +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.felix.dm.impl.index;
-
-import java.util.Arrays;
-import java.util.HashMap;
-import java.util.Map;
-import java.util.Set;
-import java.util.TreeSet;
-
-import org.apache.felix.dm.ServiceUtil;
-import org.osgi.framework.Constants;
-import org.osgi.framework.ServiceReference;
-
-/**
- * @author <a href="mailto:dev@felix.apache.org">Felix Project Team</a>
- */
-public abstract class AbstractFactoryFilterIndex {
-
- protected final Map /* <Long, SortedSet<ServiceReference>> */ m_sidToServiceReferencesMap = new HashMap();
- protected final Map /* <ServiceListener, String> */ m_listenerToFilterMap = new HashMap();
-
- public void addedService(ServiceReference reference, Object service) {
- add(reference);
- }
-
- public void modifiedService(ServiceReference reference, Object service) {
- modify(reference);
- }
-
- public void removedService(ServiceReference reference, Object service) {
- remove(reference);
- }
-
- public void add(ServiceReference reference) {
- Long sid = ServiceUtil.getServiceIdObject(reference);
- synchronized (m_sidToServiceReferencesMap) {
- Set list = (Set) m_sidToServiceReferencesMap.get(sid);
- if (list == null) {
- list = new TreeSet();
- m_sidToServiceReferencesMap.put(sid, list);
- }
- list.add(reference);
- }
- }
-
- public void modify(ServiceReference reference) {
- remove(reference);
- add(reference);
- }
-
- public void remove(ServiceReference reference) {
- Long sid = ServiceUtil.getServiceIdObject(reference);
- synchronized (m_sidToServiceReferencesMap) {
- Set list = (Set) m_sidToServiceReferencesMap.get(sid);
- if (list != null) {
- list.remove(reference);
- }
- }
- }
-
- protected boolean referenceMatchesObjectClass(ServiceReference ref, String objectClass) {
- boolean matches = false;
- Object value = ref.getProperty(Constants.OBJECTCLASS);
- matches = Arrays.asList((String[])value).contains(objectClass);
- return matches;
- }
-
- /** Structure to hold internal filter data. */
- protected static class FilterData {
- public long serviceId;
- public String objectClass;
- public int ranking;
-
- public String toString() {
- return "FilterData [serviceId=" + serviceId + "]";
- }
- }
-}
diff --git a/dependencymanager/core/src/main/java/org/apache/felix/dm/impl/index/AdapterFilterIndex.java b/dependencymanager/core/src/main/java/org/apache/felix/dm/impl/index/AdapterFilterIndex.java
deleted file mode 100644
index 470e6ca..0000000
--- a/dependencymanager/core/src/main/java/org/apache/felix/dm/impl/index/AdapterFilterIndex.java
+++ /dev/null
@@ -1,223 +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.felix.dm.impl.index;
-
-import java.util.ArrayList;
-import java.util.HashMap;
-import java.util.Iterator;
-import java.util.List;
-import java.util.Map;
-import java.util.SortedSet;
-import java.util.regex.Matcher;
-import java.util.regex.Pattern;
-
-import org.apache.felix.dm.DependencyManager;
-import org.apache.felix.dm.FilterIndex;
-import org.apache.felix.dm.ServiceUtil;
-import org.apache.felix.dm.tracker.ServiceTracker;
-import org.apache.felix.dm.tracker.ServiceTrackerCustomizer;
-import org.osgi.framework.BundleContext;
-import org.osgi.framework.Constants;
-import org.osgi.framework.InvalidSyntaxException;
-import org.osgi.framework.ServiceEvent;
-import org.osgi.framework.ServiceListener;
-import org.osgi.framework.ServiceReference;
-
-/**
- * @author <a href="mailto:dev@felix.apache.org">Felix Project Team</a>
- */
-public class AdapterFilterIndex extends AbstractFactoryFilterIndex implements FilterIndex, ServiceTrackerCustomizer {
- // (&(objectClass=foo.Bar)(|(service.id=18233)(org.apache.felix.dependencymanager.aspect=18233)))
- private static final String FILTER_REGEXP = "\\(&\\(" + Constants.OBJECTCLASS + "=([a-zA-Z\\.\\$0-9]*)\\)\\(\\|\\("
- + Constants.SERVICE_ID + "=([0-9]*)\\)\\("
- + DependencyManager.ASPECT + "=([0-9]*)\\)\\)\\)";
- private static final Pattern PATTERN = Pattern.compile(FILTER_REGEXP);
- private final Object m_lock = new Object();
- private ServiceTracker m_tracker;
- private BundleContext m_context;
- private final Map /* <String, List<ServiceListener>> */ m_sidToListenersMap = new HashMap();
- protected final Map /* <ServiceListener, String> */ m_listenerToObjectClassMap = new HashMap();
-
- public void open(BundleContext context) {
- synchronized (m_lock) {
- if (m_context != null) {
- throw new IllegalStateException("Filter already open.");
- }
- try {
- m_tracker = new ServiceTracker(context, context.createFilter("(" + Constants.OBJECTCLASS + "=*)"), this);
- }
- catch (InvalidSyntaxException e) {
- throw new Error();
- }
- m_context = context;
- }
- m_tracker.open(true, true);
- }
-
- public void close() {
- ServiceTracker tracker;
- synchronized (m_lock) {
- if (m_context == null) {
- throw new IllegalStateException("Filter already closed.");
- }
- tracker = m_tracker;
- m_tracker = null;
- m_context = null;
- }
- tracker.close();
- }
-
- public boolean isApplicable(String clazz, String filter) {
- return getFilterData(clazz, filter) != null;
- }
-
- /** Returns a value object with the relevant filter data, or <code>null</code> if this filter was not valid. */
- private FilterData getFilterData(String clazz, String filter) {
- // something like:
- // (&(objectClass=foo.Bar)(|(service.id=18233)(org.apache.felix.dependencymanager.aspect=18233)))
- FilterData resultData = null;
- if (filter != null) {
- Matcher matcher = PATTERN.matcher(filter);
- if (matcher.matches()) {
- String sid = matcher.group(2);
- String sid2 = matcher.group(3);
- if (sid.equals(sid2)) {
- resultData = new FilterData();
- resultData.serviceId = Long.parseLong(sid);
- }
- }
- }
- return resultData;
- }
-
- public List getAllServiceReferences(String clazz, String filter) {
- List /* <ServiceReference> */result = new ArrayList();
- Matcher matcher = PATTERN.matcher(filter);
- if (matcher.matches()) {
- FilterData data = getFilterData(clazz, filter);
- if (data != null) {
- SortedSet /* <ServiceReference> */list = null;
- synchronized (m_sidToServiceReferencesMap) {
- list = (SortedSet) m_sidToServiceReferencesMap.get(Long.valueOf(data.serviceId));
- if (list != null) {
- Iterator iterator = list.iterator();
- while (iterator.hasNext()) {
- ServiceReference ref = (ServiceReference) iterator.next();
- String objectClass = matcher.group(1);
- if (referenceMatchesObjectClass(ref, objectClass)) {
- result.add(ref);
- }
- }
- }
- }
- }
- }
- return result;
- }
-
- public void serviceChanged(ServiceEvent event) {
- ServiceReference reference = event.getServiceReference();
- Long sid = ServiceUtil.getServiceIdObject(reference);
- List /* <ServiceListener> */ notificationList = new ArrayList();
- synchronized (m_sidToListenersMap) {
- List /* <ServiceListener> */ list = (ArrayList) m_sidToListenersMap.get(sid);
- if (list != null) {
- Iterator iterator = list.iterator();
- while (iterator.hasNext()) {
- ServiceListener listener = (ServiceListener) iterator.next();
- String objectClass = (String) m_listenerToObjectClassMap.get(listener);
- if (referenceMatchesObjectClass(reference, objectClass)) {
- notificationList.add(listener);
- }
- }
- }
- }
- // notify
- Iterator iterator = notificationList.iterator();
- while (iterator.hasNext()) {
- ServiceListener listener = (ServiceListener) iterator.next();
- listener.serviceChanged(event);
- }
- }
-
- public void addServiceListener(ServiceListener listener, String filter) {
- FilterData data = getFilterData(null, filter);
- if (data != null) {
- Long sidObject = Long.valueOf(data.serviceId);
- synchronized (m_sidToListenersMap) {
- List /* <ServiceListener> */ listeners = (List) m_sidToListenersMap.get(sidObject);
- if (listeners == null) {
- listeners = new ArrayList();
- m_sidToListenersMap.put(sidObject, listeners);
- }
- listeners.add(listener);
- m_listenerToFilterMap.put(listener, filter);
- Matcher matcher = PATTERN.matcher(filter);
- if (matcher.matches()) {
- String objectClass = matcher.group(1);
- m_listenerToObjectClassMap.put(listener, objectClass);
- } else {
- throw new IllegalArgumentException("Filter string does not match index pattern");
- }
-
- }
- }
- }
-
- public void removeServiceListener(ServiceListener listener) {
- synchronized (m_sidToListenersMap) {
- m_listenerToObjectClassMap.remove(listener);
- String filter = (String) m_listenerToFilterMap.remove(listener);
- if (filter != null) {
- // the listener does exist
- FilterData data = getFilterData(null, filter);
- if (data != null) {
- Long sidObject = Long.valueOf(data.serviceId);
- List /* ServiceListener */ listeners = (List) m_sidToListenersMap.get(sidObject);
- if (listeners != null) {
- listeners.remove(listener);
- }
- }
- }
- }
- }
-
- public Object addingService(ServiceReference reference) {
- BundleContext context;
- synchronized (m_lock) {
- context = m_context;
- }
- if (context != null) {
- return context.getService(reference);
- }
- else {
- throw new IllegalStateException("No valid bundle context.");
- }
- }
-
- public String toString() {
- StringBuffer sb = new StringBuffer();
- sb.append("AdapterFilterIndex[");
- sb.append("S2L: " + m_sidToListenersMap.size());
- sb.append(", S2SR: " + m_sidToServiceReferencesMap.size());
- sb.append(", L2F: " + m_listenerToFilterMap.size());
- sb.append("]");
- return sb.toString();
- }
-}
diff --git a/dependencymanager/core/src/main/java/org/apache/felix/dm/impl/index/AspectFilterIndex.java b/dependencymanager/core/src/main/java/org/apache/felix/dm/impl/index/AspectFilterIndex.java
deleted file mode 100644
index f2e0aca..0000000
--- a/dependencymanager/core/src/main/java/org/apache/felix/dm/impl/index/AspectFilterIndex.java
+++ /dev/null
@@ -1,266 +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.felix.dm.impl.index;
-
-import java.util.ArrayList;
-import java.util.Collection;
-import java.util.HashMap;
-import java.util.Iterator;
-import java.util.List;
-import java.util.Map;
-import java.util.Map.Entry;
-import java.util.SortedMap;
-import java.util.SortedSet;
-import java.util.TreeMap;
-
-import org.apache.felix.dm.DependencyManager;
-import org.apache.felix.dm.FilterIndex;
-import org.apache.felix.dm.ServiceUtil;
-import org.apache.felix.dm.tracker.ServiceTracker;
-import org.apache.felix.dm.tracker.ServiceTrackerCustomizer;
-import org.osgi.framework.BundleContext;
-import org.osgi.framework.Constants;
-import org.osgi.framework.InvalidSyntaxException;
-import org.osgi.framework.ServiceEvent;
-import org.osgi.framework.ServiceListener;
-import org.osgi.framework.ServiceReference;
-
-/**
- * @author <a href="mailto:dev@felix.apache.org">Felix Project Team</a>
- */
-public class AspectFilterIndex extends AbstractFactoryFilterIndex implements FilterIndex, ServiceTrackerCustomizer {
- // (&(objectClass=foo.Bar)(|(!(service.ranking=*))(service.ranking<=99))(|(service.id=4451)(org.apache.felix.dependencymanager.aspect=4451)))
- private static final String FILTER_START = "(&(" + Constants.OBJECTCLASS + "=";
- private static final String FILTER_SUBSTRING_0 = ")(&(|(!(" + Constants.SERVICE_RANKING + "=*))(" + Constants.SERVICE_RANKING + "<=";
- private static final String FILTER_SUBSTRING_1 = "))(|(" + Constants.SERVICE_ID + "=";
- private static final String FILTER_SUBSTRING_2 = ")(" + DependencyManager.ASPECT + "=";
- private static final String FILTER_END = "))))";
- private final Object m_lock = new Object();
- private ServiceTracker m_tracker;
- private BundleContext m_context;
-
- private final Map /* <Long, Map<String, SortedMap<Integer, Collection<ServiceListener>>> */ m_sidToObjectClassToRankingToListenersMap = new HashMap();
-
- public void open(BundleContext context) {
- synchronized (m_lock) {
- if (m_context != null) {
- throw new IllegalStateException("Filter already open.");
- }
- try {
- m_tracker = new ServiceTracker(context, context.createFilter("(" + Constants.OBJECTCLASS + "=*)"), this);
- }
- catch (InvalidSyntaxException e) {
- throw new Error();
- }
- m_context = context;
- }
- m_tracker.open(true, true);
- }
-
- public void close() {
- ServiceTracker tracker;
- synchronized (m_lock) {
- if (m_context == null) {
- throw new IllegalStateException("Filter already closed.");
- }
- tracker = m_tracker;
- m_tracker = null;
- m_context = null;
- }
- tracker.close();
- }
-
- public boolean isApplicable(String clazz, String filter) {
- return getFilterData(clazz, filter) != null;
- }
-
- /** Returns a value object with the relevant filter data, or <code>null</code> if this filter was not valid. */
- private FilterData getFilterData(String clazz, String filter) {
- // something like:
- // (&(objectClass=foo.Bar)(&(|(!(service.ranking=*))(service.ranking<=9))(|(service.id=37)(org.apache.felix.dependencymanager.aspect=37))))
- if ((filter != null)
- && (filter.startsWith(FILTER_START)) // (&(objectClass=
- && (filter.endsWith(FILTER_END)) // ))))
- ) {
- int i0 = filter.indexOf(FILTER_SUBSTRING_0);
- if (i0 == -1) {
- return null;
- }
- int i1 = filter.indexOf(FILTER_SUBSTRING_1);
- if (i1 == -1 || i1 <= i0) {
- return null;
- }
- int i2 = filter.indexOf(FILTER_SUBSTRING_2);
- if (i2 == -1 || i2 <= i1) {
- return null;
- }
- long sid = Long.parseLong(filter.substring(i1 + FILTER_SUBSTRING_1.length(), i2));
- long sid2 = Long.parseLong(filter.substring(i2 + FILTER_SUBSTRING_2.length(), filter.length() - FILTER_END.length()));
- if (sid != sid2) {
- return null;
- }
- FilterData result = new FilterData();
- result.objectClass = filter.substring(FILTER_START.length(), i0);
- result.serviceId = sid;
- result.ranking = Integer.parseInt(filter.substring(i0 + FILTER_SUBSTRING_0.length(), i1));
- return result;
- }
- return null;
- }
-
- public List getAllServiceReferences(String clazz, String filter) {
- List /* <ServiceReference> */ result = new ArrayList();
- FilterData data = getFilterData(clazz, filter);
- if (data != null) {
- SortedSet /* <ServiceReference> */ list = null;
- synchronized (m_sidToServiceReferencesMap) {
- list = (SortedSet) m_sidToServiceReferencesMap.get(Long.valueOf(data.serviceId));
- if (list != null) {
- Iterator iterator = list.iterator();
- while (iterator.hasNext()) {
- ServiceReference reference = (ServiceReference) iterator.next();
- if (referenceMatchesObjectClass(reference, data.objectClass) && ServiceUtil.getRanking(reference) <= data.ranking) {
- result.add(reference);
- }
- }
- }
- }
- }
- return result;
- }
-
- public void serviceChanged(ServiceEvent event) {
- List list = new ArrayList();
- ServiceReference reference = event.getServiceReference();
- Long sidObject = ServiceUtil.getServiceIdObject(reference);
- int ranking = ServiceUtil.getRanking(reference);
- String[] objectClasses = (String[]) reference.getProperty(Constants.OBJECTCLASS);
-
- synchronized (m_sidToObjectClassToRankingToListenersMap) {
- for (int i = 0; i < objectClasses.length; i++) {
- // handle each of the object classes separately since aspects only work on one object class at a time
- String objectClass = objectClasses[i];
- Map /* <String, Map<Integer, Collection<ServiceListener>>> */ objectClassToRankingToListenersMap = (SortedMap) m_sidToObjectClassToRankingToListenersMap.get(sidObject);
- if (objectClassToRankingToListenersMap != null) {
- SortedMap /* Integer, ServiceListener> */ rankingToListenersMap = (SortedMap) objectClassToRankingToListenersMap.get(objectClass);
- if (rankingToListenersMap != null) {
- Iterator iterator = rankingToListenersMap.entrySet().iterator();
- while (iterator.hasNext()) {
- Entry entry = (Entry) iterator.next();
- if (ranking <= ((Integer) entry.getKey()).intValue()) {
- list.addAll((Collection)entry.getValue());
- }
- }
- }
- }
- }
- }
- Iterator iterator = list.iterator();
- while (iterator.hasNext()) {
- ServiceListener listener = (ServiceListener) iterator.next();
- listener.serviceChanged(event);
- }
- }
-
- public void addServiceListener(ServiceListener listener, String filter) {
- FilterData data = getFilterData(null, filter);
- if (data != null) {
- Long sidObject = Long.valueOf(data.serviceId);
- synchronized (m_sidToObjectClassToRankingToListenersMap) {
- Map /* <String, Map<Integer, Collection<ServiceListener>>> */ objectClassToRankingToListenersMap = (SortedMap) m_sidToObjectClassToRankingToListenersMap.get(sidObject);
- if (objectClassToRankingToListenersMap == null) {
- objectClassToRankingToListenersMap = new TreeMap();
- m_sidToObjectClassToRankingToListenersMap.put(sidObject, objectClassToRankingToListenersMap);
- }
-
- SortedMap /* Integer, ServiceListener> */ rankingToListenersMap = (SortedMap) objectClassToRankingToListenersMap.get(data.objectClass);
- if (rankingToListenersMap == null) {
- rankingToListenersMap = new TreeMap();
- objectClassToRankingToListenersMap.put(data.objectClass, rankingToListenersMap);
- }
-
- Collection listeners = (Collection) rankingToListenersMap.get(Integer.valueOf(data.ranking));
- if (listeners == null) {
- listeners = new ArrayList();
- rankingToListenersMap.put(Integer.valueOf(data.ranking), listeners);
- }
-
- listeners.add(listener);
- m_listenerToFilterMap.put(listener, filter);
- }
- }
- }
-
- public void removeServiceListener(ServiceListener listener) {
- synchronized (m_sidToObjectClassToRankingToListenersMap) {
- String filter = (String) m_listenerToFilterMap.remove(listener);
- if (filter != null) {
- // the listener does exist
- FilterData data = getFilterData(null, filter);
- if (data != null) {
- // this index is applicable
- Long sidObject = Long.valueOf(data.serviceId);
- Map /* <String, Map<Integer, Collection<ServiceListener>>> */ objectClassToRankingToListenersMap = (SortedMap) m_sidToObjectClassToRankingToListenersMap.get(sidObject);
- if (objectClassToRankingToListenersMap != null) {
- SortedMap /* Integer, ServiceListener> */ rankingToListenersMap = (SortedMap) objectClassToRankingToListenersMap.get(data.objectClass);
- if (rankingToListenersMap != null) {
- Collection listeners = (Collection) rankingToListenersMap.get(Integer.valueOf(data.ranking));
- if (listeners != null) {
- listeners.remove(listener);
- }
- // cleanup
- if (listeners.isEmpty()) {
- rankingToListenersMap.remove(Integer.valueOf(data.ranking));
- }
- if (rankingToListenersMap.isEmpty()) {
- objectClassToRankingToListenersMap.remove(data.objectClass);
- }
- if (objectClassToRankingToListenersMap.isEmpty()) {
- m_sidToObjectClassToRankingToListenersMap.remove(sidObject);
- }
- }
- }
- }
- }
- }
- }
-
- public Object addingService(ServiceReference reference) {
- BundleContext context;
- synchronized (m_lock) {
- context = m_context;
- }
- if (context != null) {
- return context.getService(reference);
- }
- else {
- throw new IllegalStateException("No valid bundle context.");
- }
- }
-
- public String toString() {
- StringBuffer sb = new StringBuffer();
- sb.append("AspectFilterIndex[");
- sb.append("S2R2L: " + m_sidToObjectClassToRankingToListenersMap.size());
- sb.append(", S2SR: " + m_sidToServiceReferencesMap.size());
- sb.append(", L2F: " + m_listenerToFilterMap.size());
- sb.append("]");
- return sb.toString();
- }
-}
diff --git a/dependencymanager/core/src/main/java/org/apache/felix/dm/impl/index/BundleContextInterceptor.java b/dependencymanager/core/src/main/java/org/apache/felix/dm/impl/index/BundleContextInterceptor.java
deleted file mode 100644
index 9224898..0000000
--- a/dependencymanager/core/src/main/java/org/apache/felix/dm/impl/index/BundleContextInterceptor.java
+++ /dev/null
@@ -1,163 +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.felix.dm.impl.index;
-
-import java.util.Arrays;
-import java.util.Iterator;
-import java.util.List;
-
-import org.apache.felix.dm.FilterIndex;
-import org.apache.felix.dm.impl.Logger;
-import org.osgi.framework.BundleContext;
-import org.osgi.framework.Constants;
-import org.osgi.framework.InvalidSyntaxException;
-import org.osgi.framework.ServiceEvent;
-import org.osgi.framework.ServiceListener;
-import org.osgi.framework.ServiceReference;
-
-/**
- * @author <a href="mailto:dev@felix.apache.org">Felix Project Team</a>
- */
-public class BundleContextInterceptor extends BundleContextInterceptorBase {
- protected static final String INDEX_LOG_TRESHOLD = "org.apache.felix.dm.index.log.treshold";
- private final ServiceRegistryCache m_cache;
- private final boolean m_perfmon = System.getProperty(INDEX_LOG_TRESHOLD) != null;
- private Logger m_logger;
- private long m_treshold;
-
- public BundleContextInterceptor(ServiceRegistryCache cache, BundleContext context) {
- super(context);
- m_cache = cache;
- if (m_perfmon) {
- m_treshold = Long.parseLong(System.getProperty(INDEX_LOG_TRESHOLD));
- m_logger = new Logger(context);
- }
- }
-
- public void addServiceListener(ServiceListener listener, String filter) throws InvalidSyntaxException {
- FilterIndex filterIndex = m_cache.hasFilterIndexFor(null, filter);
- if (filterIndex != null) {
- filterIndex.addServiceListener(listener, filter);
- }
- else {
-// System.out.println("BCI:Listener " + listener.getClass().getName() + " filter " + filter);
- m_context.addServiceListener(listener, filter);
- }
- }
-
- public void addServiceListener(ServiceListener listener) {
- FilterIndex filterIndex = m_cache.hasFilterIndexFor(null, null);
- if (filterIndex != null) {
- filterIndex.addServiceListener(listener, null);
- }
- else {
-// System.out.println("BCI:Listener " + listener.getClass().getName() + " without filter");
- m_context.addServiceListener(listener);
- }
- }
-
- public void removeServiceListener(ServiceListener listener) {
- // remove servicelistener. although it would be prettier to find the correct filterindex first it's
- // probaby faster to do a brute force removal.
- Iterator filterIndexIterator = m_cache.getFilterIndices().iterator();
- while (filterIndexIterator.hasNext()) {
- ((FilterIndex) filterIndexIterator.next()).removeServiceListener(listener);
- }
- m_context.removeServiceListener(listener);
- }
-
- public ServiceReference[] getServiceReferences(String clazz, String filter) throws InvalidSyntaxException {
- long start = 0L;
- if (m_perfmon) {
- start = System.currentTimeMillis();
- }
- // first we ask the cache if there is an index for our request (class and filter combination)
- FilterIndex filterIndex = m_cache.hasFilterIndexFor(clazz, filter);
- if (filterIndex != null) {
- List /* <ServiceReference> */ result = filterIndex.getAllServiceReferences(clazz, filter);
- Iterator iterator = result.iterator();
- while (iterator.hasNext()) {
- ServiceReference reference = (ServiceReference) iterator.next();
- String[] list = (String[]) reference.getProperty(Constants.OBJECTCLASS);
- for (int i = 0; i < list.length; i++) {
- if (!reference.isAssignableTo(m_context.getBundle(), list[i])) {
- iterator.remove();
- break;
- }
- }
- }
- if (m_perfmon) {
- long duration = System.currentTimeMillis() - start;
- if (duration > m_treshold) {
- m_logger.log(org.apache.felix.dm.impl.Logger.LOG_DEBUG, "Indexed filter exceeds lookup time treshold (" + duration + "ms.): " + clazz + " " + filter);
- }
- }
- if (result == null || result.size() == 0) {
- return null;
- }
- return (ServiceReference[]) result.toArray(new ServiceReference[result.size()]);
- }
- else {
- // if they don't know, we ask the real bundle context instead
- ServiceReference[] serviceReferences = m_context.getServiceReferences(clazz, filter);
- if (m_perfmon) {
- long duration = System.currentTimeMillis() - start;
- if (duration > m_treshold) {
- m_logger.log(org.apache.felix.dm.impl.Logger.LOG_DEBUG, "Unindexed filter exceeds lookup time treshold (" + duration + "ms.): " + clazz + " " + filter);
- }
- }
- return serviceReferences;
- }
- }
-
- public ServiceReference[] getAllServiceReferences(String clazz, String filter) throws InvalidSyntaxException {
- // first we ask the cache if there is an index for our request (class and filter combination)
- FilterIndex filterIndex = m_cache.hasFilterIndexFor(clazz, filter);
- if (filterIndex != null) {
- List /* <ServiceReference> */ result = filterIndex.getAllServiceReferences(clazz, filter);
- if (result == null || result.size() == 0) {
- return null;
- }
- return (ServiceReference[]) result.toArray(new ServiceReference[result.size()]);
- }
- else {
- // if they don't know, we ask the real bundle context instead
- return m_context.getAllServiceReferences(clazz, filter);
- }
- }
-
- public ServiceReference getServiceReference(String clazz) {
- ServiceReference[] references;
- try {
- references = getServiceReferences(clazz, null);
- if (references == null || references.length == 0) {
- return null;
- }
- Arrays.sort(references);
- return references[references.length - 1];
- }
- catch (InvalidSyntaxException e) {
- throw new Error("Invalid filter syntax thrown for null filter.", e);
- }
- }
-
- public void serviceChanged(ServiceEvent event) {
- m_cache.serviceChangedForFilterIndices(event);
- }
-}
diff --git a/dependencymanager/core/src/main/java/org/apache/felix/dm/impl/index/BundleContextInterceptorBase.java b/dependencymanager/core/src/main/java/org/apache/felix/dm/impl/index/BundleContextInterceptorBase.java
deleted file mode 100644
index 6bb237d..0000000
--- a/dependencymanager/core/src/main/java/org/apache/felix/dm/impl/index/BundleContextInterceptorBase.java
+++ /dev/null
@@ -1,163 +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.felix.dm.impl.index;
-
-import java.io.File;
-import java.io.InputStream;
-import java.util.Dictionary;
-import java.util.HashMap;
-import java.util.Map;
-import java.util.Map.Entry;
-
-import org.osgi.framework.Bundle;
-import org.osgi.framework.BundleContext;
-import org.osgi.framework.BundleException;
-import org.osgi.framework.BundleListener;
-import org.osgi.framework.Filter;
-import org.osgi.framework.FrameworkListener;
-import org.osgi.framework.InvalidSyntaxException;
-import org.osgi.framework.ServiceListener;
-import org.osgi.framework.ServiceReference;
-import org.osgi.framework.ServiceRegistration;
-
-/**
- * Base class for bundle context interceptors that keep track of service listeners and delegate incoming changes to them.
- *
- * @author <a href="mailto:dev@felix.apache.org">Felix Project Team</a>
- */
-public abstract class BundleContextInterceptorBase implements BundleContext, ServiceListener {
- protected final BundleContext m_context;
- /** Keeps track of all service listeners and their optional filters. */
- private final Map /* <ServiceListener, String> */m_serviceListenerFilterMap = new HashMap();
- private long m_currentVersion = 0;
- private long m_entryVersion = -1;
- private Entry[] m_serviceListenerFilterMapEntries;
-
- public BundleContextInterceptorBase(BundleContext context) {
- m_context = context;
- }
-
- public String getProperty(String key) {
- return m_context.getProperty(key);
- }
-
- public Bundle getBundle() {
- return m_context.getBundle();
- }
-
- public Bundle installBundle(String location) throws BundleException {
- return m_context.installBundle(location);
- }
-
- public Bundle installBundle(String location, InputStream input) throws BundleException {
- return m_context.installBundle(location, input);
- }
-
- public Bundle getBundle(long id) {
- return m_context.getBundle(id);
- }
-
- public Bundle[] getBundles() {
- return m_context.getBundles();
- }
-
- public void addServiceListener(ServiceListener listener, String filter) throws InvalidSyntaxException {
- synchronized (m_serviceListenerFilterMap) {
- m_serviceListenerFilterMap.put(listener, filter);
- m_currentVersion++;
- }
- }
-
- public void addServiceListener(ServiceListener listener) {
- synchronized (m_serviceListenerFilterMap) {
- m_serviceListenerFilterMap.put(listener, null);
- m_currentVersion++;
- }
- }
-
- public void removeServiceListener(ServiceListener listener) {
- synchronized (m_serviceListenerFilterMap) {
- m_serviceListenerFilterMap.remove(listener);
- m_currentVersion++;
- }
- }
-
- public void addBundleListener(BundleListener listener) {
- m_context.addBundleListener(listener);
- }
-
- public void removeBundleListener(BundleListener listener) {
- m_context.removeBundleListener(listener);
- }
-
- public void addFrameworkListener(FrameworkListener listener) {
- m_context.addFrameworkListener(listener);
- }
-
- public void removeFrameworkListener(FrameworkListener listener) {
- m_context.removeFrameworkListener(listener);
- }
-
- public ServiceRegistration registerService(String[] clazzes, Object service, Dictionary properties) {
- return m_context.registerService(clazzes, service, properties);
- }
-
- public ServiceRegistration registerService(String clazz, Object service, Dictionary properties) {
- return m_context.registerService(clazz, service, properties);
- }
-
- public ServiceReference[] getServiceReferences(String clazz, String filter) throws InvalidSyntaxException {
- return m_context.getServiceReferences(clazz, filter);
- }
-
- public ServiceReference[] getAllServiceReferences(String clazz, String filter) throws InvalidSyntaxException {
- return m_context.getAllServiceReferences(clazz, filter);
- }
-
- public ServiceReference getServiceReference(String clazz) {
- return m_context.getServiceReference(clazz);
- }
-
- public Object getService(ServiceReference reference) {
- return m_context.getService(reference);
- }
-
- public boolean ungetService(ServiceReference reference) {
- return m_context.ungetService(reference);
- }
-
- public File getDataFile(String filename) {
- return m_context.getDataFile(filename);
- }
-
- public Filter createFilter(String filter) throws InvalidSyntaxException {
- return m_context.createFilter(filter);
- }
-
- protected Entry[] synchronizeCollection() {
- // lazy copy on write: we make a new copy only if writes have changed the collection
- synchronized (m_serviceListenerFilterMap) {
- if (m_currentVersion != m_entryVersion) {
- m_serviceListenerFilterMapEntries = (Entry[]) m_serviceListenerFilterMap.entrySet().toArray(new Entry[m_serviceListenerFilterMap.size()]);
- m_entryVersion = m_currentVersion;
- }
- }
- return m_serviceListenerFilterMapEntries;
- }
-}
diff --git a/dependencymanager/core/src/main/java/org/apache/felix/dm/impl/index/FilterIndexBundleContext.java b/dependencymanager/core/src/main/java/org/apache/felix/dm/impl/index/FilterIndexBundleContext.java
deleted file mode 100644
index afaee86..0000000
--- a/dependencymanager/core/src/main/java/org/apache/felix/dm/impl/index/FilterIndexBundleContext.java
+++ /dev/null
@@ -1,64 +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.felix.dm.impl.index;
-
-import java.util.Map.Entry;
-
-import org.osgi.framework.BundleContext;
-import org.osgi.framework.InvalidSyntaxException;
-import org.osgi.framework.ServiceEvent;
-import org.osgi.framework.ServiceListener;
-
-/**
- * @author <a href="mailto:dev@felix.apache.org">Felix Project Team</a>
- */
-public class FilterIndexBundleContext extends BundleContextInterceptorBase {
- public FilterIndexBundleContext(BundleContext context) {
- super(context);
- }
-
- public void serviceChanged(ServiceEvent event) {
- Entry[] entries = synchronizeCollection();
- for (int i = 0; i < entries.length; i++) {
- Entry serviceListenerFilterEntry = entries[i];
- ServiceListener serviceListener = (ServiceListener) serviceListenerFilterEntry.getKey();
- String filter = (String) serviceListenerFilterEntry.getValue();
- if (filter == null) {
- serviceListener.serviceChanged(event);
- }
- else {
- // call service changed on the listener if the filter matches the event
- // TODO review if we can be smarter here
- try {
- if ("(objectClass=*)".equals(filter)) {
- serviceListener.serviceChanged(event);
- }
- else {
- if (m_context.createFilter(filter).match(event.getServiceReference())) {
- serviceListener.serviceChanged(event);
- }
- }
- }
- catch (InvalidSyntaxException e) {
- e.printStackTrace();
- }
- }
- }
- }
-}
diff --git a/dependencymanager/core/src/main/java/org/apache/felix/dm/impl/index/ServiceRegistryCache.java b/dependencymanager/core/src/main/java/org/apache/felix/dm/impl/index/ServiceRegistryCache.java
deleted file mode 100644
index f97637c..0000000
--- a/dependencymanager/core/src/main/java/org/apache/felix/dm/impl/index/ServiceRegistryCache.java
+++ /dev/null
@@ -1,177 +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.felix.dm.impl.index;
-
-import java.util.ArrayList;
-import java.util.HashMap;
-import java.util.Iterator;
-import java.util.List;
-import java.util.Map;
-import java.util.concurrent.CopyOnWriteArrayList;
-
-import org.apache.felix.dm.FilterIndex;
-import org.apache.felix.dm.impl.Logger;
-import org.osgi.framework.BundleContext;
-import org.osgi.framework.ServiceEvent;
-import org.osgi.framework.ServiceListener;
-import org.osgi.framework.ServiceRegistration;
-
-/**
- * @author <a href="mailto:dev@felix.apache.org">Felix Project Team</a>
- */
-public class ServiceRegistryCache implements ServiceListener/*, CommandProvider*/ {
- private final List /* <FilterIndex> */ m_filterIndexList = new CopyOnWriteArrayList();
- private final BundleContext m_context;
- private final FilterIndexBundleContext m_filterIndexBundleContext;
- private final Map /* <BundleContext, BundleContextInterceptor> */ m_bundleContextInterceptorMap = new HashMap();
- private long m_currentVersion = 0;
- private long m_arrayVersion = -1;
- private BundleContextInterceptor[] m_interceptors = null;
- private ServiceRegistration m_registration;
-
- public ServiceRegistryCache(BundleContext context) {
- m_context = context;
- m_filterIndexBundleContext = new FilterIndexBundleContext(m_context);
- }
-
- public void open() {
- m_context.addServiceListener(this);
-// m_registration = m_context.registerService(CommandProvider.class.getName(), this, null);
- }
-
- public void close() {
-// m_registration.unregister();
- m_context.removeServiceListener(this);
- }
-
- public void addFilterIndex(FilterIndex index) {
- m_filterIndexList.add(index);
- index.open(m_filterIndexBundleContext);
- }
-
- public void removeFilterIndex(FilterIndex index) {
- index.close();
- m_filterIndexList.remove(index);
- }
-
- public void serviceChanged(ServiceEvent event) {
- // any incoming event is first dispatched to the list of filter indices
- m_filterIndexBundleContext.serviceChanged(event);
- // and then all the other listeners can access it
- synchronized (m_bundleContextInterceptorMap) {
- if (m_currentVersion != m_arrayVersion) {
- // if our copy is out of date, we make a new one
- m_interceptors = (BundleContextInterceptor[]) m_bundleContextInterceptorMap.values().toArray(new BundleContextInterceptor[m_bundleContextInterceptorMap.size()]);
- m_arrayVersion = m_currentVersion;
- }
- }
-
- serviceChangedForFilterIndices(event);
- }
-
- /** Creates an interceptor for a bundle context that uses our cache. */
- public BundleContext createBundleContextInterceptor(BundleContext context) {
- synchronized (m_bundleContextInterceptorMap) {
- BundleContextInterceptor bundleContextInterceptor = (BundleContextInterceptor) m_bundleContextInterceptorMap.get(context);
- if (bundleContextInterceptor == null) {
- bundleContextInterceptor = new BundleContextInterceptor(this, context);
- m_bundleContextInterceptorMap.put(context, bundleContextInterceptor);
- m_currentVersion++;
- // TODO figure out a good way to clean up bundle contexts that are no longer valid so they can be garbage collected
- }
- return bundleContextInterceptor;
- }
- }
-
- public FilterIndex hasFilterIndexFor(String clazz, String filter) {
- Iterator iterator = m_filterIndexList.iterator();
- while (iterator.hasNext()) {
- FilterIndex filterIndex = (FilterIndex) iterator.next();
- if (filterIndex.isApplicable(clazz, filter)) {
- return filterIndex;
- }
- }
- return null;
- }
-
- public void serviceChangedForFilterIndices(ServiceEvent event) {
- Iterator iterator = m_filterIndexList.iterator();
- while (iterator.hasNext()) {
- FilterIndex filterIndex = (FilterIndex) iterator.next();
- filterIndex.serviceChanged(event);
- }
- }
-
-// public void _sc(CommandInterpreter ci) {
-// ci.println(toString());
-// }
-//
-// public void _fi(CommandInterpreter ci) {
-// String arg = ci.nextArgument();
-// if (arg != null) {
-// int x = Integer.parseInt(arg);
-// FilterIndex filterIndex = (FilterIndex) m_filterIndexList.get(x);
-// String a1 = ci.nextArgument();
-// String a2 = null;
-// if (a1 != null) {
-// if ("-".equals(a1)) {
-// a1 = null;
-// }
-// a2 = ci.nextArgument();
-// }
-// if (filterIndex.isApplicable(a1, a2)) {
-// List /* <ServiceReference> */ references = filterIndex.getAllServiceReferences(a1, a2);
-// ci.println("Found " + references.size() + " references:");
-// for (int i = 0; i < references.size(); i++) {
-// ci.println("" + i + " - " + references.get(i));
-// }
-// }
-// else {
-// ci.println("Filter not applicable.");
-// }
-// }
-// else {
-// ci.println("FilterIndices:");
-// Iterator iterator = m_filterIndexList.iterator();
-// int index = 0;
-// while (iterator.hasNext()) {
-// FilterIndex filterIndex = (FilterIndex) iterator.next();
-// ci.println("" + index + " " + filterIndex);
-// index++;
-// }
-// }
-// }
-//
-// public String getHelp() {
-// return "I'm not going to help you!";
-// }
-
- public String toString() {
- StringBuffer sb = new StringBuffer();
- sb.append("ServiceRegistryCache[");
- sb.append("FilterIndices: " + m_filterIndexList.size());
- sb.append(", BundleContexts intercepted: " + m_bundleContextInterceptorMap.size());
- sb.append("]");
- return sb.toString();
- }
-
- public List getFilterIndices() {
- return m_filterIndexList;
- }
-}
diff --git a/dependencymanager/core/src/main/java/org/apache/felix/dm/impl/index/multiproperty/Filter.java b/dependencymanager/core/src/main/java/org/apache/felix/dm/impl/index/multiproperty/Filter.java
deleted file mode 100644
index 66f4731..0000000
--- a/dependencymanager/core/src/main/java/org/apache/felix/dm/impl/index/multiproperty/Filter.java
+++ /dev/null
@@ -1,149 +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.felix.dm.impl.index.multiproperty;
-
-import java.util.HashMap;
-import java.util.Iterator;
-import java.util.Map;
-import java.util.Set;
-import java.util.StringTokenizer;
-import java.util.TreeSet;
-
-/**
- * @author <a href="mailto:dev@felix.apache.org">Felix Project Team</a>
- */
-public class Filter {
-
- private boolean m_valid = true;
- private Map /* <String, Property> */ m_properties = new HashMap();
- private Set /* <String> */ m_propertyKeys = new TreeSet(String.CASE_INSENSITIVE_ORDER);
-
- private Filter() {
-
- }
-
- // Sample valid filter string (&(objectClass=OBJECTCLASS)(&(model=MODEL)(concept=CONCEPT)(role=ROLE)(!(context=*))))
- public static Filter parse(String filterString) {
- Filter filter = new Filter();
- StringTokenizer tokenizer = new StringTokenizer(filterString, "(&|=)", true);
-
- String token = null;
- String prevToken = null;
- String key = null;
- StringBuilder valueBuilder = new StringBuilder();
- boolean negate = false;
-
- while (tokenizer.hasMoreTokens()) {
- prevToken = token;
- token = tokenizer.nextToken();
- if (token.equals("|")) {
- // we're not into OR's
- filter.m_valid = false;
- break;
- }
- if (token.equals("!")) {
- negate = true;
- } else if (token.equals("=")) {
- key = prevToken.toLowerCase();
- } else if (key != null) {
- if (!token.equals(")")) {
- valueBuilder.append(token); // might be superseded by a &
- }
- if (token.equals(")")) {
- // set complete
- if (filter.m_properties.containsKey(key)) {
- // set current property to multivalue
- Property property = (Property) filter.m_properties.get(key);
- property.addValue(valueBuilder.toString(), negate);
- } else {
- Property property = new Property(negate, key, valueBuilder.toString());
- filter.m_properties.put(key, property);
- filter.m_propertyKeys.add(key);
- }
- negate = false;
- key = null;
- valueBuilder = new StringBuilder();
- }
- }
- }
- return filter;
- }
-
- public boolean containsProperty(String propertyKey) {
- return m_properties.containsKey(propertyKey);
- }
-
- public Set /* <String> */ getPropertyKeys() {
- return m_properties.keySet();
- }
-
- public Property getProperty(String key) {
- return (Property) m_properties.get(key);
- }
-
- public boolean isValid() {
- if (!m_valid) {
- return m_valid;
- } else {
- // also check the properties
- Iterator propertiesIterator = m_properties.values().iterator();
- while (propertiesIterator.hasNext()) {
- Property property = (Property) propertiesIterator.next();
- if (!property.isValid()) {
- return false;
- }
- }
- }
- return true;
- }
-
- public static void main(String args[]) {
- Filter parser = Filter.parse("(&(objectClass=OBJECTCLASS)(&(a=x)(a=n)(a=y)(b=y)(c=z)))");
- System.out.println("key: " + parser.createKey());
- }
-
- protected String createKey() {
- StringBuilder builder = new StringBuilder();
- Iterator keys = m_propertyKeys.iterator();
-
- while (keys.hasNext()) {
- String key = (String) keys.next();
- Property prop = (Property) m_properties.get(key);
- if (!prop.isWildcard()) {
- Iterator values = prop.getValues().iterator();
- while (values.hasNext()) {
- String value = (String) values.next();
- builder.append(key);
- builder.append("=");
- builder.append(value);
- if (keys.hasNext() || values.hasNext()) {
- builder.append(";");
- }
- }
- }
- }
- // strip the final ';' in case the last key was a wildcard property
- if (builder.charAt(builder.length() - 1) == ';') {
- return builder.toString().substring(0, builder.length() - 1);
- } else {
- return builder.toString();
- }
- }
-
-}
diff --git a/dependencymanager/core/src/main/java/org/apache/felix/dm/impl/index/multiproperty/MultiPropertyFilterIndex.java b/dependencymanager/core/src/main/java/org/apache/felix/dm/impl/index/multiproperty/MultiPropertyFilterIndex.java
deleted file mode 100644
index 513be72..0000000
--- a/dependencymanager/core/src/main/java/org/apache/felix/dm/impl/index/multiproperty/MultiPropertyFilterIndex.java
+++ /dev/null
@@ -1,486 +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.felix.dm.impl.index.multiproperty;
-
-import java.util.ArrayList;
-import java.util.Arrays;
-import java.util.Collection;
-import java.util.HashMap;
-import java.util.Iterator;
-import java.util.LinkedHashMap;
-import java.util.List;
-import java.util.Map;
-import java.util.Set;
-import java.util.TreeSet;
-import java.util.concurrent.CopyOnWriteArrayList;
-
-import org.apache.felix.dm.FilterIndex;
-import org.apache.felix.dm.tracker.ServiceTracker;
-import org.apache.felix.dm.tracker.ServiceTrackerCustomizer;
-import org.osgi.framework.BundleContext;
-import org.osgi.framework.Constants;
-import org.osgi.framework.InvalidSyntaxException;
-import org.osgi.framework.ServiceEvent;
-import org.osgi.framework.ServiceListener;
-import org.osgi.framework.ServiceReference;
-
-/**
- * @author <a href="mailto:dev@felix.apache.org">Felix Project Team</a>
- */
-public class MultiPropertyFilterIndex implements FilterIndex, ServiceTrackerCustomizer {
-
- private final Object m_lock = new Object();
- private ServiceTracker m_tracker;
- private BundleContext m_context;
- private Map /* <String, Property> */ m_configProperties = new LinkedHashMap();
- private List /* <String> */ m_negatePropertyKeys = new ArrayList();
- private final Map /* <String, List<ServiceReference>> */ m_keyToServiceReferencesMap = new HashMap();
- private final Map /* <String, List<ServiceListener>> */ m_keyToListenersMap = new HashMap();
- private final Map /* <ServiceListener, String> */ m_listenerToFilterMap = new HashMap();
-
- public MultiPropertyFilterIndex(String configString) {
- parseConfig(configString);
- }
-
- public boolean isApplicable(String clazz, String filterString) {
- Filter filter = createFilter(clazz, filterString);
-
- if (!filter.isValid()) {
- return false;
- }
- // compare property keys to the ones in the configuration
- Set /* <String> */ filterPropertyKeys = filter.getPropertyKeys();
- if (m_configProperties.size() != filterPropertyKeys.size()) {
- return false;
- }
- Iterator filterPropertyKeysIterator = filterPropertyKeys.iterator();
- while (filterPropertyKeysIterator.hasNext()) {
- String filterPropertyKey = (String) filterPropertyKeysIterator.next();
- if (!m_configProperties.containsKey(filterPropertyKey)) {
- return false;
- } else if (((Property)m_configProperties.get(filterPropertyKey)).isNegate() != filter.getProperty(filterPropertyKey).isNegate()) {
- // negation should be equal
- return false;
- } else if (!filter.getProperty(filterPropertyKey).isNegate() && filter.getProperty(filterPropertyKey).getValue().equals("*")) {
- // no wildcards without negation allowed
- return false;
- }
- }
- // our properties match so we're applicable
- return true;
- }
-
- public boolean isApplicable(ServiceReference ref) {
- String[] propertyKeys = ref.getPropertyKeys();
- TreeSet referenceProperties = new TreeSet(String.CASE_INSENSITIVE_ORDER);
- for (int i = 0; i < propertyKeys.length; i++) {
- referenceProperties.add(propertyKeys[i]);
- }
- Iterator iterator = m_configProperties.keySet().iterator();
- while (iterator.hasNext()) {
- String item = (String) iterator.next();
- Property configProperty = (Property) m_configProperties.get(item);
- if (!configProperty.isNegate() && !(referenceProperties.contains(item))) {
- return false;
- } else if (configProperty.isNegate() && referenceProperties.contains(item)) {
- return false;
- }
- }
- return true;
- }
-
- private void parseConfig(String configString) {
- String[] propertyConfigs = configString.split(",");
- for (int i = 0; i < propertyConfigs.length; i++) {
- String propertyConfig = propertyConfigs[i];
- Property property = new Property();
- String key;
- String value = null;
- if (propertyConfig.startsWith("!")) {
- property.setNegate(true);
- key = propertyConfig.substring(1);
- } else {
- key = propertyConfig;
- }
- if (key.endsWith("*")) {
- key = key.substring(0, key.indexOf("*"));
- value = "*";
- }
- property.setKey(key.toLowerCase());
- property.addValue(value, property.isNegate());
- m_configProperties.put(key.toLowerCase(), property);
- if (property.isNegate()) {
- m_negatePropertyKeys.add(key);
- }
- }
- }
-
- protected Collection /* <Property> */ getProperties() {
- return m_configProperties.values();
- }
-
- protected String createKeyFromFilter(String clazz, String filterString) {
- return createFilter(clazz, filterString).createKey();
- }
-
- private Filter createFilter(String clazz, String filterString) {
- String filterStringWithObjectClass = filterString;
- if (clazz != null) {
- if (filterString != null) {
- if (!filterStringWithObjectClass.startsWith("(&(objectClass=")) {
- filterStringWithObjectClass = "(&(objectClass=" + clazz + ")" + filterString + ")";
- }
- } else {
- filterStringWithObjectClass = "(objectClass=" + clazz + ")";
- }
- }
- Filter filter = Filter.parse(filterStringWithObjectClass);
- return filter;
- }
-
- protected List createKeys(ServiceReference reference) {
- List /* <String> */ results = new ArrayList();
- List sets = new ArrayList();
- String[] keys = reference.getPropertyKeys();
- Arrays.sort(keys, String.CASE_INSENSITIVE_ORDER);
- for (int i = 0; i < keys.length; i++) {
- List set = new ArrayList();
- String key = keys[i].toLowerCase();
- if (m_configProperties.containsKey(key)) {
- Object valueObject = reference.getProperty(key);
- if (valueObject instanceof String[]) {
- set.addAll(getPermutations(key, (String[]) valueObject));
- } else {
- set.add(toKey(key, valueObject));
- }
- sets.add(set);
- }
- }
-
- List reversedSets = new ArrayList();
- int size = sets.size();
- for (int i = size - 1; i > -1; i--) {
- reversedSets.add(sets.get(i));
- }
- List products = carthesianProduct(0, reversedSets);
- // convert sets into strings
- for (int i = 0; i < products.size(); i++) {
- List set = (List) products.get(i);
- StringBuilder b = new StringBuilder();
- for (int j = 0; j < set.size(); j++) {
- String item = (String) set.get(j);
- b.append(item);
- if (j < set.size() - 1) {
- b.append(";");
- }
- }
- results.add(b.toString());
- }
-
- return results;
- }
-
- /**
- * Note that we calculate the carthesian product for multi value properties. Use filters on these sparingly since memory
- * consumption can get really high when multiple properties have a lot of values.
- *
- * @param index
- * @param sets
- * @return
- */
- private List carthesianProduct(int index, List sets) {
- List result = new ArrayList();
- if (index == sets.size()) {
- result.add(new ArrayList());
- } else {
- List set = (List) sets.get(index);
- for (int i = 0; i < set.size(); i++) {
- Object object = set.get(i);
- List pSets = carthesianProduct(index + 1, sets);
- for (int j = 0; j < pSets.size(); j++) {
- List pSet = (List) pSets.get(j);
- pSet.add(object);
- result.add(pSet);
- }
- }
- }
- return result;
- }
-
- List getPermutations(String key, String[] values) {
- List results = new ArrayList();
- Arrays.sort(values, String.CASE_INSENSITIVE_ORDER);
- for (int v = 0; v < values.length; v++) {
- String processValue = values[v];
- List /* <String> */ items = new ArrayList();
- items.add(processValue);
- // per value get combinations
- List /* <String> */ subItems = new ArrayList(items);
- for (int w = v; w < values.length; w++) {
- // make a copy of the current list
- subItems = new ArrayList(subItems);
- if (w != v) {
- String value = values[w];
- subItems.add(value);
- }
- results.add(toKey(key, subItems));
- }
- }
- return results;
- }
-
- protected String toKey(String key, List values) {
- StringBuilder builder = new StringBuilder();
- for (int i = 0; i < values.size(); i++) {
- builder.append(toKey(key, (String) values.get(i)));
- if (i < values.size() - 1) {
- builder.append(";");
- }
- }
- return builder.toString();
- }
-
- protected String toKey(String key, Object value) {
- StringBuilder builder = new StringBuilder();
- builder.append(key);
- builder.append("=");
- builder.append(value.toString());
- return builder.toString();
- }
-
- public Object addingService(ServiceReference reference) {
- BundleContext context;
- synchronized (m_lock) {
- context = m_context;
- }
- if (context != null) {
- return context.getService(reference);
- }
- else {
- throw new IllegalStateException("No valid bundle context.");
- }
- }
-
- public void addedService(ServiceReference reference, Object service) {
- if (isApplicable(reference) && shouldBeIndexed(reference)) {
- handleServiceAdd(reference);
- }
- }
-
- public void modifiedService(ServiceReference reference, Object service) {
- if (isApplicable(reference)) {
- handleServicePropertiesChange(reference);
- }
- }
-
- public void removedService(ServiceReference reference, Object service) {
- if (isApplicable(reference) && shouldBeIndexed(reference)) {
- handleServiceRemove(reference);
- }
- }
-
- protected void handleServiceAdd(ServiceReference reference) {
- List /* <String> */ keys = createKeys(reference);
- synchronized (m_keyToServiceReferencesMap) {
- for (int i = 0; i < keys.size(); i++) {
- List /* <ServiceReference> */ references = (List) m_keyToServiceReferencesMap.get(keys.get(i));
- if (references == null) {
- references = new ArrayList();
- m_keyToServiceReferencesMap.put(keys.get(i), references);
- }
- references.add(reference);
- }
- }
- }
-
- protected void handleServicePropertiesChange(ServiceReference reference) {
-
- synchronized (m_keyToServiceReferencesMap) {
- // TODO this is a quite expensive linear scan over the existing collection
- // because we first need to remove any existing references and they can be
- // all over the place :)
- Iterator iterator = m_keyToServiceReferencesMap.values().iterator();
- while (iterator.hasNext()) {
- List /* <ServiceReference> */ list = (List) iterator.next();
- if (list != null) {
- Iterator i2 = list.iterator();
- while (i2.hasNext()) {
- ServiceReference ref = (ServiceReference) i2.next();
- if (ref.equals(reference)) {
- i2.remove();
- }
- }
- }
- }
- // only re-add the reference when it is still applicable for this filter index
- if (shouldBeIndexed(reference)) {
- List /* <String> */ keys = createKeys(reference);
- for (int i = 0; i < keys.size(); i++) {
- List /* <ServiceReference> */ references = (List) m_keyToServiceReferencesMap.get(keys.get(i));
- if (references == null) {
- references = new ArrayList();
- m_keyToServiceReferencesMap.put(keys.get(i), references);
- }
- references.add(reference);
- }
- }
- }
- }
-
- protected void handleServiceRemove(ServiceReference reference) {
- List /* <String> */ keys = createKeys(reference);
- synchronized (m_keyToServiceReferencesMap) {
- for (int i = 0; i < keys.size(); i++) {
- List /* <ServiceReference> */ references = (List) m_keyToServiceReferencesMap.get(keys.get(i));
- if (references != null) {
- references.remove(reference);
- if (references.isEmpty()) {
- m_keyToServiceReferencesMap.remove(keys.get(i));
- }
- }
- }
- }
- }
-
- protected boolean shouldBeIndexed(ServiceReference reference) {
- // is already applicable, so we should only check whether there's a negate field in the filter which has a value in the reference
- Iterator negatePropertyKeyIterator = m_negatePropertyKeys.iterator();
- while (negatePropertyKeyIterator.hasNext()) {
- String negatePropertyKey = (String) negatePropertyKeyIterator.next();
- if (reference.getProperty(negatePropertyKey) != null) {
- return false;
- }
- }
- return true;
- }
-
- public void open(BundleContext context) {
- synchronized (m_lock) {
- if (m_context != null) {
- throw new IllegalStateException("Filter already open.");
- }
- try {
- m_tracker = new ServiceTracker(context, context.createFilter("(" + Constants.OBJECTCLASS + "=*)"), this);
- }
- catch (InvalidSyntaxException e) {
- throw new Error();
- }
- m_context = context;
- }
- m_tracker.open(true, true);
- }
-
- public void close() {
- ServiceTracker tracker;
- synchronized (m_lock) {
- if (m_context == null) {
- throw new IllegalStateException("Filter already closed.");
- }
- tracker = m_tracker;
- m_tracker = null;
- m_context = null;
- }
- tracker.close();
- }
-
- public List /* <ServiceReference> */ getAllServiceReferences(String clazz, String filter) {
- List /* <ServiceReference> */ result = new ArrayList();
- String key = createKeyFromFilter(clazz, filter);
- ServiceReference reference;
- synchronized (m_keyToServiceReferencesMap) {
- List references = (List) m_keyToServiceReferencesMap.get(key);
- if (references != null) {
- result.addAll(references);
- }
- }
- return result;
- }
-
- public void serviceChanged(ServiceEvent event) {
- if (isApplicable(event.getServiceReference())) {
- List /* <String> */ keys = createKeys(event.getServiceReference());
- List list = new ArrayList();
- synchronized (m_keyToListenersMap) {
- for (int i = 0; i < keys.size(); i++) {
- String key = (String) keys.get(i);
- List listeners = (List) m_keyToListenersMap.get(key);
- if (listeners != null) {
- list.addAll(listeners);
- }
- }
- }
- if (list != null) {
- Iterator iterator = list.iterator();
- while (iterator.hasNext()) {
- ServiceListener listener = (ServiceListener) iterator.next();
- listener.serviceChanged(event);
- }
- }
- }
- }
-
- public void addServiceListener(ServiceListener listener, String filter) {
- String key = createKeyFromFilter(null, filter);
- synchronized (m_keyToListenersMap) {
- List /* <ServiceListener> */ listeners = (List) m_keyToListenersMap.get(key);
- if (listeners == null) {
- listeners = new CopyOnWriteArrayList();
- m_keyToListenersMap.put(key, listeners);
- }
- listeners.add(listener);
- m_listenerToFilterMap.put(listener, filter);
- }
- }
-
- public void removeServiceListener(ServiceListener listener) {
- synchronized (m_keyToListenersMap) {
- String filter = (String) m_listenerToFilterMap.remove(listener);
- if (filter != null) {
- // the listener does exist
- String key = createKeyFromFilter(null, filter);
-
- boolean result = filter != null;
- if (result) {
- List /* <ServiceListener> */ listeners = (List) m_keyToListenersMap.get(key);
- if (listeners != null) {
- listeners.remove(listener);
- if (listeners.isEmpty()) {
- m_keyToListenersMap.remove(key);
- }
- }
- // TODO actually, if listeners == null that would be strange....
- }
- }
- }
- }
-
- protected Collection getServiceListeners() {
- return m_listenerToFilterMap.keySet();
- }
-
- public String toString() {
- StringBuffer sb = new StringBuffer();
- sb.append(" dMultiPropertyExactFilter[");
- sb.append("K2L: " + m_keyToListenersMap.size());
- sb.append(", K2SR: " + m_keyToServiceReferencesMap.size());
- sb.append(", L2F: " + m_listenerToFilterMap.size());
- sb.append("]");
- return sb.toString();
- }
-}
diff --git a/dependencymanager/core/src/main/java/org/apache/felix/dm/impl/index/multiproperty/Property.java b/dependencymanager/core/src/main/java/org/apache/felix/dm/impl/index/multiproperty/Property.java
deleted file mode 100644
index 4e7c683..0000000
--- a/dependencymanager/core/src/main/java/org/apache/felix/dm/impl/index/multiproperty/Property.java
+++ /dev/null
@@ -1,102 +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.felix.dm.impl.index.multiproperty;
-
-import java.util.Set;
-import java.util.TreeSet;
-
-/**
- * @author <a href="mailto:dev@felix.apache.org">Felix Project Team</a>
- */
-import java.util.Set;
-import java.util.TreeSet;
-
-public class Property {
- boolean m_negate;
- boolean m_valid = true;
- String m_key;
- String m_value;
- Set m_values = new TreeSet(String.CASE_INSENSITIVE_ORDER);
-
- public Property() {
- }
-
- public Property(boolean negate, String key, String value) {
- super();
- this.m_negate = negate;
- this.m_key = key.toLowerCase();
- this.m_values.add(value);
- this.m_value = value;
- }
-
- public void setNegate(boolean negate) {
- this.m_negate = negate;
- }
-
- public void setKey(String key) {
- this.m_key = key.toLowerCase();
- }
-
- public void addValue(String value, boolean negate) {
- if (this.m_negate != negate) {
- // multiproperty with different negations, causes invalid configuration.
- m_valid = false;
- }
- if (this.m_value == null) {
- // value has not bee set yet
- this.m_value = value;
- }
- if (value != null) {
- m_values.add(value);
- }
- }
-
- public boolean isNegate() {
- return m_negate;
- }
-
- public String getKey() {
- return m_key;
- }
-
- public String getValue() {
- return m_value;
- }
-
- public Set getValues() {
- return m_values;
- }
-
- public boolean isWildcard() {
- return "*".equals(m_value);
- }
-
- public boolean isMultiValue() {
- return m_values.size() > 1;
- }
-
- public String toString() {
- return "Property [negate=" + m_negate + ", key=" + m_key + ", values="
- + m_values + "]";
- }
-
- public boolean isValid() {
- return m_valid;
- }
-}
\ No newline at end of file
diff --git a/dependencymanager/core/src/main/java/org/apache/felix/dm/impl/metatype/AttributeDefinitionImpl.java b/dependencymanager/core/src/main/java/org/apache/felix/dm/impl/metatype/AttributeDefinitionImpl.java
deleted file mode 100644
index 3a72c95..0000000
--- a/dependencymanager/core/src/main/java/org/apache/felix/dm/impl/metatype/AttributeDefinitionImpl.java
+++ /dev/null
@@ -1,76 +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.felix.dm.impl.metatype;
-
-import org.osgi.service.metatype.AttributeDefinition;
-
-/**
- * @author <a href="mailto:dev@felix.apache.org">Felix Project Team</a>
- */
-public class AttributeDefinitionImpl implements AttributeDefinition {
- private PropertyMetaDataImpl m_propertyMetaData;
- private Resource m_resource;
-
- public AttributeDefinitionImpl(PropertyMetaDataImpl propertyMetaData, Resource resource) {
- m_propertyMetaData = propertyMetaData;
- m_resource = resource;
- }
-
- public int getCardinality() {
- return m_propertyMetaData.getCardinality();
- }
-
- public String[] getDefaultValue() {
- return m_propertyMetaData.getDefaults();
- }
-
- public String getDescription() {
- return m_resource.localize(m_propertyMetaData.getDescription());
- }
-
- public String getID() {
- return m_propertyMetaData.getId();
- }
-
- public String getName() {
- return m_resource.localize(m_propertyMetaData.getHeading());
- }
-
- public String[] getOptionLabels() {
- String[] labels = m_propertyMetaData.getOptionLabels();
- if (labels != null) {
- for (int i = 0; i < labels.length; i++) {
- labels[i] = m_resource.localize(labels[i]);
- }
- }
- return labels;
- }
-
- public String[] getOptionValues() {
- return m_propertyMetaData.getOptionValues();
- }
-
- public int getType() {
- return m_propertyMetaData.getType();
- }
-
- public String validate(String value) {
- return null;
- }
-}
diff --git a/dependencymanager/core/src/main/java/org/apache/felix/dm/impl/metatype/MetaTypeProviderImpl.java b/dependencymanager/core/src/main/java/org/apache/felix/dm/impl/metatype/MetaTypeProviderImpl.java
deleted file mode 100644
index a3704a2..0000000
--- a/dependencymanager/core/src/main/java/org/apache/felix/dm/impl/metatype/MetaTypeProviderImpl.java
+++ /dev/null
@@ -1,258 +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.felix.dm.impl.metatype;
-
-import java.io.IOException;
-import java.io.InputStream;
-import java.net.URL;
-import java.util.ArrayList;
-import java.util.Dictionary;
-import java.util.Enumeration;
-import java.util.HashMap;
-import java.util.List;
-import java.util.Locale;
-import java.util.Map;
-import java.util.Properties;
-import java.util.StringTokenizer;
-import java.util.TreeSet;
-
-import org.apache.felix.dm.PropertyMetaData;
-import org.apache.felix.dm.impl.Logger;
-import org.osgi.framework.BundleContext;
-import org.osgi.framework.Constants;
-import org.osgi.service.cm.ConfigurationException;
-import org.osgi.service.cm.ManagedService;
-import org.osgi.service.cm.ManagedServiceFactory;
-import org.osgi.service.log.LogService;
-import org.osgi.service.metatype.MetaTypeProvider;
-import org.osgi.service.metatype.ObjectClassDefinition;
-
-/**
- * When a ConfigurationDepdendency is configured with properties metadata, we provide
- * a specific ManagedService which also implements the MetaTypeProvider interface. This interface
- * allows the MetaTypeService to retrieve our properties metadata, which will then be handled by webconsole.
- *
- * @author <a href="mailto:dev@felix.apache.org">Felix Project Team</a>
- */
-public class MetaTypeProviderImpl implements MetaTypeProvider, ManagedService, ManagedServiceFactory {
- private ManagedService m_managedServiceDelegate;
- private ManagedServiceFactory m_managedServiceFactoryDelegate;
- private List m_propertiesMetaData = new ArrayList();
- private String m_description;
- private String m_heading;
- private String m_localization;
- private Map m_localesProperties = new HashMap();
- private Logger m_logger;
- private BundleContext m_bctx;
- private String m_pid;
-
- public MetaTypeProviderImpl(String pid, BundleContext ctx, Logger logger, ManagedService msDelegate, ManagedServiceFactory msfDelegate) {
- m_pid = pid;
- m_bctx = ctx;
- m_logger = logger;
- m_managedServiceDelegate = msDelegate;
- m_managedServiceFactoryDelegate = msfDelegate;
- // Set the default localization file base name (see core specification, in section Localization on page 68).
- // By default, this file can be stored in OSGI-INF/l10n/bundle.properties (and corresponding localized version
- // in OSGI-INF/l10n/bundle_en_GB_welsh.properties, OSGI-INF/l10n/bundle_en_GB.properties, etc ...
- // This default localization property file name can be overriden using the PropertyMetaData.setLocalization method.
- m_localization = (String) m_bctx.getBundle().getHeaders().get(Constants.BUNDLE_LOCALIZATION);
- if (m_localization == null) {
- m_localization = Constants.BUNDLE_LOCALIZATION_DEFAULT_BASENAME;
- }
- }
-
- /**
- * Registers the metatype information of a given configuration property
- * @param property
- */
- public void add(PropertyMetaData property) {
- m_propertiesMetaData.add(property);
- }
-
- /**
- * A human readable description of the PID this annotation is associated with. Example: "Configuration for the PrinterService bundle".
- * @return A human readable description of the PID this annotation is associated with (may be localized)
- */
- public void setDescription(String description) {
- m_description = description;
- }
-
- /**
- * The label used to display the tab name (or section) where the properties are displayed. Example: "Printer Service".
- * @return The label used to display the tab name where the properties are displayed (may be localized)
- */
- public void setName(String heading) {
- m_heading = heading;
- }
-
- /**
- * Points to the basename of the Properties file that can localize the Meta Type informations.
- * By default, (e.g. <code>setLocalization("person")</code> would match person_du_NL.properties in the root bundle directory.
- * The default localization base name for the properties is OSGI-INF/l10n/bundle, but can
- * be overridden by the manifest Bundle-Localization header (see core specification, in section Localization on page 68).
- */
- public void setLocalization(String path) {
- if (path.endsWith(".properties")) {
- throw new IllegalArgumentException(
- "path must point to the base name of the propertie file, "
- + "excluding local suffixes. For example: "
- + "foo/bar/person is valid and matches the property file \"foo/bar/person_bundle_en_GB_welsh.properties\"");
- }
- m_localization = path.startsWith("/") ? path.substring(1) : path;
- }
-
- // --------------- MetaTypeProvider interface -------------------------------------------------
-
- /**
- * Returns all the Locales our bundle is containing. For instance, if our bundle contains the following localization files:
- * OSGI-INF/l10n/bundle_en_GB_welsh.properties and OSGI-INF/l10n/bundle_en_GB.properties, then this method will return
- * "en_GB", "en_GB_welsh" ...
- * @return the list of Locale supported by our bundle.
- */
- public String[] getLocales() {
- int lastSlash = m_localization.lastIndexOf("/");
- String path = (lastSlash == -1) ? "/" : ("/" + m_localization.substring(0, lastSlash - 1));
- String base = (lastSlash == -1) ? m_localization : m_localization.substring(lastSlash + 1);
- Enumeration e = m_bctx.getBundle().findEntries(path,
- base + "*.properties", false);
- if (e == null) {
- return null;
- }
-
- TreeSet set = new TreeSet();
- while (e.hasMoreElements()) {
- // We have found a locale property file in the form of "path/file[_language[_ country[_variation]].properties"
- // And now, we have to get the "language[_country[_variation]]" part ...
- URL url = (URL) e.nextElement();
- String name = url.getPath();
- name = name.substring(name.lastIndexOf("/") + 1);
- int underscore = name.indexOf("_");
- if (underscore != -1) {
- name = name.substring(underscore + 1, name.length() - ".properties".length());
- }
- if (name.length() > 0) {
- set.add(name);
- }
- }
-
- String[] locales = (String[]) set.toArray(new String[set.size()]);
- return locales.length == 0 ? null : locales;
- }
-
- /**
- * Returns the ObjectClassDefinition for a given Pid/Locale.
- */
- public ObjectClassDefinition getObjectClassDefinition(String id, String locale) {
- try {
- // Check if the id matches our PID
- if (!id.equals(m_pid)) {
- m_logger.log(LogService.LOG_ERROR, "id " + id + " does not match pid " + m_pid);
- return null;
- }
-
- Properties localeProperties = getLocaleProperties(locale);
- return new ObjectClassDefinitionImpl(m_pid, m_heading,
- m_description, m_propertiesMetaData, new Resource(localeProperties));
- }
-
- catch (Throwable t) {
- m_logger.log(
- Logger.LOG_ERROR,
- "Unexpected exception while geting ObjectClassDefinition for " + id + " (locale="
- + locale + ")", t);
- return null;
- }
- }
-
- /**
- * We also implements the ManagedService and we just delegates the configuration handling to
- * our associated ConfigurationDependency.
- */
- public void updated(Dictionary properties) throws ConfigurationException {
- m_managedServiceDelegate.updated(properties);
- }
-
- /**
- * Gets the properties for a given Locale.
- * @param locale
- * @return
- * @throws IOException
- */
- private synchronized Properties getLocaleProperties(String locale) throws IOException {
- locale = locale == null ? Locale.getDefault().toString() : locale;
- Properties properties = (Properties) m_localesProperties.get(locale);
- if (properties == null) {
- properties = new Properties();
- URL url = m_bctx.getBundle().getEntry(m_localization + ".properties");
- if (url != null) {
- loadLocale(properties, url);
- }
-
- String path = m_localization;
- StringTokenizer tok = new StringTokenizer(locale, "_");
- while (tok.hasMoreTokens()) {
- path += "_" + tok.nextToken();
- url = m_bctx.getBundle().getEntry(path + ".properties");
- if (url != null) {
- properties = new Properties(properties);
- loadLocale(properties, url);
- }
- }
- m_localesProperties.put(locale, properties);
- }
- return properties;
- }
-
- /**
- * Loads a Locale Properties file.
- * @param properties
- * @param url
- * @throws IOException
- */
- private void loadLocale(Properties properties, URL url) throws IOException {
- InputStream in = null;
- try {
- in = url.openStream();
- properties.load(in);
- }
- finally {
- if (in != null) {
- try {
- in.close();
- }
- catch (IOException ignored) {
- }
- }
- }
- }
-
- // ManagedServiceFactory implementation
- public void deleted(String pid) {
- m_managedServiceFactoryDelegate.deleted(pid);
- }
-
- public String getName() {
- return m_pid;
- }
-
- public void updated(String pid, Dictionary properties) throws ConfigurationException {
- m_managedServiceFactoryDelegate.updated(pid, properties);
- }
-}
diff --git a/dependencymanager/core/src/main/java/org/apache/felix/dm/impl/metatype/ObjectClassDefinitionImpl.java b/dependencymanager/core/src/main/java/org/apache/felix/dm/impl/metatype/ObjectClassDefinitionImpl.java
deleted file mode 100644
index a5f66bf..0000000
--- a/dependencymanager/core/src/main/java/org/apache/felix/dm/impl/metatype/ObjectClassDefinitionImpl.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.felix.dm.impl.metatype;
-
-import java.io.IOException;
-import java.io.InputStream;
-import java.util.ArrayList;
-import java.util.List;
-
-import org.osgi.service.metatype.AttributeDefinition;
-import org.osgi.service.metatype.ObjectClassDefinition;
-
-/**
- * ObjectClassDefinition implementation.
- *
- * @author <a href="mailto:dev@felix.apache.org">Felix Project Team</a>
- */
-public class ObjectClassDefinitionImpl implements ObjectClassDefinition {
- // Our OCD name (may be localized)
- private String m_name;
-
- // Our OCD description (may be localized)
- private String m_description;
-
- // Our OCD id
- private String m_id;
-
- // The list of Properties MetaData objects (from DependencyManager API)
- private List m_propertiesMetaData;
-
- // The localized resource that can be used when localizing some parameters
- private Resource m_resource;
-
- public ObjectClassDefinitionImpl(String id, String name, String description, List propertiesMetaData, Resource resource) {
- m_id = id;
- m_name = name;
- m_description = description;
- m_propertiesMetaData = propertiesMetaData;
- m_resource = resource;
- }
-
- // --------------------- ObjectClassDefinition ----------------------------------------
-
- public AttributeDefinition[] getAttributeDefinitions(int filter) {
- List attrs = new ArrayList();
- for (int i = 0; i < m_propertiesMetaData.size(); i++) {
- PropertyMetaDataImpl metaData = (PropertyMetaDataImpl) m_propertiesMetaData.get(i);
- switch (filter) {
- case ObjectClassDefinition.ALL:
- attrs.add(new AttributeDefinitionImpl(metaData, m_resource));
- break;
- case ObjectClassDefinition.OPTIONAL:
- if (!metaData.isRequired()) {
- attrs.add(new AttributeDefinitionImpl(metaData, m_resource));
- }
- break;
- case ObjectClassDefinition.REQUIRED:
- if (metaData.isRequired()) {
- attrs.add(new AttributeDefinitionImpl(metaData, m_resource));
- }
- break;
- }
- }
-
- AttributeDefinition[] array = new AttributeDefinitionImpl[attrs.size()];
- return (AttributeDefinition[]) attrs.toArray(array);
- }
-
- public String getDescription() {
- return m_resource.localize(m_description);
- }
-
- public String getID() {
- return m_id;
- }
-
- public InputStream getIcon(int size) throws IOException {
- // TODO Auto-generated method stub
- return null;
- }
-
- public String getName() {
- return m_resource.localize(m_name);
- }
-}
diff --git a/dependencymanager/core/src/main/java/org/apache/felix/dm/impl/metatype/PropertyMetaDataImpl.java b/dependencymanager/core/src/main/java/org/apache/felix/dm/impl/metatype/PropertyMetaDataImpl.java
deleted file mode 100644
index 50ba1bc..0000000
--- a/dependencymanager/core/src/main/java/org/apache/felix/dm/impl/metatype/PropertyMetaDataImpl.java
+++ /dev/null
@@ -1,204 +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.felix.dm.impl.metatype;
-
-import java.util.ArrayList;
-import java.util.HashMap;
-import java.util.List;
-import java.util.Map;
-
-import org.apache.felix.dm.PropertyMetaData;
-import org.osgi.service.metatype.AttributeDefinition;
-
-/**
- * DependencyManager PropertyMetaData Implementation. This class describes meta informations regarding
- * one given configuration property.
- *
- * @author <a href="mailto:dev@felix.apache.org">Felix Project Team</a>
- */
-public class PropertyMetaDataImpl implements PropertyMetaData {
- /**
- * List of option labels (may be localized)
- */
- List m_optionsLabels = new ArrayList();
-
- /**
- * List of option values
- */
- List m_optionsValues = new ArrayList();
-
- /**
- * Property cardinality.
- * @see {@link AttributeDefinition#getCardinality()}
- */
- private int m_cardinality;
-
- /**
- * Valid default property values
- */
- private String[] m_defaults;
-
- /**
- * Property description.
- */
- private String m_description;
-
- /**
- * Property title.
- */
- private String m_heading;
-
- /**
- * Property unique Id
- */
- private String m_id;
-
- /**
- * Required flag.
- */
- private boolean m_required;
-
- /**
- * Property Type.
- * @see {@link AttributeDefinition#getType()}
- */
- private int m_type = AttributeDefinition.STRING;
-
- /**
- * Mapping between java types and valid MetaType types.
- * @see {@link AttributeDefinition#getType()}
- */
- private final static Map m_typeMapping = new HashMap() {{
- put(Boolean.class, new Integer(AttributeDefinition.BOOLEAN));
- put(Byte.class, new Integer(AttributeDefinition.BYTE));
- put(Character.class, new Integer(AttributeDefinition.CHARACTER));
- put(Double.class, new Integer(AttributeDefinition.FLOAT));
- put(Integer.class, new Integer(AttributeDefinition.INTEGER));
- put(Long.class, new Integer(AttributeDefinition.LONG));
- put(Short.class, new Integer(AttributeDefinition.SHORT));
- put(String.class, new Integer(AttributeDefinition.STRING));
- }};
-
- public PropertyMetaData addOption(String optionLabel, String optionValue) {
- m_optionsLabels.add(optionLabel);
- m_optionsValues.add(optionValue);
- return this;
- }
-
- public PropertyMetaData setCardinality(int cardinality) {
- m_cardinality = cardinality;
- return this;
- }
-
- public PropertyMetaData setDefaults(String[] defaults) {
- m_defaults = defaults;
- return this;
- }
-
- public PropertyMetaData setDescription(String description) {
- m_description = description;
- return this;
- }
-
- public PropertyMetaData setHeading(String heading) {
- m_heading = heading;
- return this;
- }
-
- public PropertyMetaData setId(String id) {
- m_id = id;
- return this;
- }
-
- public PropertyMetaData setRequired(boolean required) {
- m_required = required;
- return this;
- }
-
- public PropertyMetaData setType(Class classType) {
- Integer type = (Integer) m_typeMapping.get(classType);
- if (type == null) {
- throw new IllegalArgumentException("Invalid type: " + classType + ". Valid types are "
- + m_typeMapping.keySet());
- }
- m_type = type.intValue();
- return this;
- }
-
- public String[] getOptionLabels() {
- String[] optionLabels = new String[m_optionsLabels.size()];
- return (String[]) m_optionsLabels.toArray(optionLabels);
- }
-
- public String[] getOptionValues() {
- String[] optionValues = new String[m_optionsValues.size()];
- return (String[]) m_optionsValues.toArray(optionValues);
- }
-
- public int getCardinality() {
- return m_cardinality;
- }
-
- public String[] getDefaults() {
- return m_defaults;
- }
-
- public String getDescription() {
- return m_description;
- }
-
- public String getHeading() {
- return m_heading;
- }
-
- public String getId() {
- return m_id;
- }
-
- public boolean isRequired() {
- return m_required;
- }
-
- public int getType() {
- return m_type;
- }
-
- public String toString() {
- StringBuffer sb = new StringBuffer();
- sb.append("cardinality=").append(m_cardinality);
- sb.append("; defaults=");
- for (int i = 0; i < m_defaults.length; i ++) {
- sb.append(m_defaults[i]).append(" ");
- }
- sb.append("; description=").append(m_description);
- sb.append("; heading=").append(m_heading);
- sb.append("; id=").append(m_id);
- sb.append("; required=").append(m_required);
- sb.append("; type=").append(getType());
- sb.append("; optionLabels=");
- for (int i = 0; i < m_optionsLabels.size(); i ++) {
- sb.append(m_optionsLabels.get(i)).append(" ");
- }
- sb.append("; optionValues=");
- for (int i = 0; i < m_optionsValues.size(); i ++) {
- sb.append(m_optionsValues.get(i)).append(" ");
- }
- return sb.toString();
- }
-}
diff --git a/dependencymanager/core/src/main/java/org/apache/felix/dm/impl/metatype/Resource.java b/dependencymanager/core/src/main/java/org/apache/felix/dm/impl/metatype/Resource.java
deleted file mode 100644
index c588a0c..0000000
--- a/dependencymanager/core/src/main/java/org/apache/felix/dm/impl/metatype/Resource.java
+++ /dev/null
@@ -1,42 +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.felix.dm.impl.metatype;
-
-import java.util.Properties;
-
-/**
- * Helper class used to localize a given Property Meta Data.
- *
- * @author <a href="mailto:dev@felix.apache.org">Felix Project Team</a>
- */
-public class Resource {
- private Properties m_properties;
-
- public Resource(Properties properties) {
- m_properties = properties;
- }
-
- public String localize(String param) {
- if (m_properties != null && param != null && param.startsWith("%")) {
- param = param.substring(1);
- return m_properties.getProperty(param);
- }
- return param;
- }
-}
diff --git a/dependencymanager/core/src/main/java/org/apache/felix/dm/tracker/AbstractTracked.java b/dependencymanager/core/src/main/java/org/apache/felix/dm/tracker/AbstractTracked.java
deleted file mode 100644
index 2f9d3e1..0000000
--- a/dependencymanager/core/src/main/java/org/apache/felix/dm/tracker/AbstractTracked.java
+++ /dev/null
@@ -1,460 +0,0 @@
-package org.apache.felix.dm.tracker;
-/*
- * Copyright (c) OSGi Alliance (2007, 2008). All Rights Reserved.
- *
- * 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.
- */
-
-import java.util.ArrayList;
-import java.util.LinkedHashMap;
-import java.util.LinkedList;
-import java.util.List;
-
-/**
- * Abstract class to track items. If a Tracker is reused (closed then reopened),
- * then a new AbstractTracked object is used. This class acts a map of tracked
- * item -> customized object. Subclasses of this class will act as the listener
- * object for the tracker. This class is used to synchronize access to the
- * tracked items. This is not a public class. It is only for use by the
- * implementation of the Tracker class.
- *
- * @ThreadSafe
- * @version $Revision: 5871 $
- * @since 1.4
- */
-abstract class AbstractTracked {
- /* set this to true to compile in debug messages */
- private static final boolean DEBUG = false;
-
- /**
- * Ordered Map of tracked items to customized objects. An ordered map is used to
- * provide a predictable order in the getTracked() method.
- *
- * @GuardedBy this
- */
- private LinkedHashMap tracked;
-
- /**
- * Modification count. This field is initialized to zero and incremented by
- * modified.
- *
- * @GuardedBy this
- */
- private int trackingCount;
-
- /**
- * List of items in the process of being added. This is used to deal with
- * nesting of events. Since events may be synchronously delivered, events
- * can be nested. For example, when processing the adding of a service and
- * the customizer causes the service to be unregistered, notification to the
- * nested call to untrack that the service was unregistered can be made to
- * the track method.
- *
- * Since the ArrayList implementation is not synchronized, all access to
- * this list must be protected by the same synchronized object for
- * thread-safety.
- *
- * @GuardedBy this
- */
- private final List adding;
-
- /**
- * true if the tracked object is closed.
- *
- * This field is volatile because it is set by one thread and read by
- * another.
- */
- volatile boolean closed;
-
- /**
- * Initial list of items for the tracker. This is used to correctly process
- * the initial items which could be modified before they are tracked. This
- * is necessary since the initial set of tracked items are not "announced"
- * by events and therefore the event which makes the item untracked could be
- * delivered before we track the item.
- *
- * An item must not be in both the initial and adding lists at the same
- * time. An item must be moved from the initial list to the adding list
- * "atomically" before we begin tracking it.
- *
- * Since the LinkedList implementation is not synchronized, all access to
- * this list must be protected by the same synchronized object for
- * thread-safety.
- *
- * @GuardedBy this
- */
- private final LinkedList initial;
-
- /**
- * AbstractTracked constructor.
- */
- AbstractTracked() {
- this.tracked = new LinkedHashMap();
- trackingCount = 0;
- adding = new ArrayList(6);
- initial = new LinkedList();
- closed = false;
- }
-
- void setTracked(LinkedHashMap map) {
- this.tracked = map;
- }
-
- /**
- * Set initial list of items into tracker before events begin to be
- * received.
- *
- * This method must be called from Tracker's open method while synchronized
- * on this object in the same synchronized block as the add listener call.
- *
- * @param list The initial list of items to be tracked. <code>null</code>
- * entries in the list are ignored.
- * @GuardedBy this
- */
- void setInitial(Object[] list) {
- if (list == null) {
- return;
- }
- int size = list.length;
- for (int i = 0; i < size; i++) {
- Object item = list[i];
- if (item == null) {
- continue;
- }
- if (DEBUG) {
- System.out.println("AbstractTracked.setInitial: " + item); //$NON-NLS-1$
- }
- initial.add(item);
- }
- }
-
- /**
- * Track the initial list of items. This is called after events can begin to
- * be received.
- *
- * This method must be called from Tracker's open method while not
- * synchronized on this object after the add listener call.
- *
- */
- void trackInitial() {
- while (true) {
- Object item;
- synchronized (this) {
- if (closed || (initial.size() == 0)) {
- /*
- * if there are no more initial items
- */
- return; /* we are done */
- }
- /*
- * move the first item from the initial list to the adding list
- * within this synchronized block.
- */
- item = initial.removeFirst();
- if (tracked.get(item) != null) {
- /* if we are already tracking this item */
- if (DEBUG) {
- System.out
- .println("AbstractTracked.trackInitial[already tracked]: " + item); //$NON-NLS-1$
- }
- continue; /* skip this item */
- }
- if (adding.contains(item)) {
- /*
- * if this item is already in the process of being added.
- */
- if (DEBUG) {
- System.out
- .println("AbstractTracked.trackInitial[already adding]: " + item); //$NON-NLS-1$
- }
- continue; /* skip this item */
- }
- adding.add(item);
- }
- if (DEBUG) {
- System.out.println("AbstractTracked.trackInitial: " + item); //$NON-NLS-1$
- }
- trackAdding(item, null); /*
- * Begin tracking it. We call trackAdding
- * since we have already put the item in the
- * adding list.
- */
- }
- }
-
- /**
- * Called by the owning Tracker object when it is closed.
- */
- void close() {
- closed = true;
- }
-
- /**
- * Begin to track an item.
- *
- * @param item Item to be tracked.
- * @param related Action related object.
- */
- void track(final Object item, final Object related) {
- final Object object;
- synchronized (this) {
- if (closed) {
- return;
- }
- object = tracked.get(item);
- if (object == null) { /* we are not tracking the item */
- if (adding.contains(item)) {
- /* if this item is already in the process of being added. */
- if (DEBUG) {
- System.out
- .println("AbstractTracked.track[already adding]: " + item); //$NON-NLS-1$
- }
- return;
- }
- adding.add(item); /* mark this item is being added */
- }
- else { /* we are currently tracking this item */
- if (DEBUG) {
- System.out
- .println("AbstractTracked.track[modified]: " + item); //$NON-NLS-1$
- }
- modified(); /* increment modification count */
- }
- }
-
- if (object == null) { /* we are not tracking the item */
- trackAdding(item, related);
- }
- else {
- /* Call customizer outside of synchronized region */
- customizerModified(item, related, object);
- /*
- * If the customizer throws an unchecked exception, it is safe to
- * let it propagate
- */
- }
- }
-
- /**
- * Common logic to add an item to the tracker used by track and
- * trackInitial. The specified item must have been placed in the adding list
- * before calling this method.
- *
- * @param item Item to be tracked.
- * @param related Action related object.
- */
- private void trackAdding(final Object item, final Object related) {
- if (DEBUG) {
- System.out.println("AbstractTracked.trackAdding: " + item); //$NON-NLS-1$
- }
- Object object = null;
- boolean becameUntracked = false;
- /* Call customizer outside of synchronized region */
- try {
- object = customizerAdding(item, related);
- /*
- * If the customizer throws an unchecked exception, it will
- * propagate after the finally
- */
- }
- finally {
- boolean needToCallback = false;
- synchronized (this) {
- if (adding.remove(item) && !closed) {
- /*
- * if the item was not untracked during the customizer
- * callback
- */
- if (object != null) {
- tracked.put(item, object);
- modified(); /* increment modification count */
- notifyAll(); /* notify any waiters */
- needToCallback = true; /* marrs: invoke added callback */
- }
- }
- else {
- becameUntracked = true;
- }
- }
- if (needToCallback) {
- customizerAdded(item, related, object);
- }
- }
- /*
- * The item became untracked during the customizer callback.
- */
- if (becameUntracked && (object != null)) {
- if (DEBUG) {
- System.out
- .println("AbstractTracked.trackAdding[removed]: " + item); //$NON-NLS-1$
- }
- /* Call customizer outside of synchronized region */
- customizerRemoved(item, related, object);
- /*
- * If the customizer throws an unchecked exception, it is safe to
- * let it propagate
- */
- }
- }
-
- /**
- * Discontinue tracking the item.
- *
- * @param item Item to be untracked.
- * @param related Action related object.
- */
- void untrack(final Object item, final Object related) {
- final Object object;
- synchronized (this) {
- if (initial.remove(item)) { /*
- * if this item is already in the list
- * of initial references to process
- */
- if (DEBUG) {
- System.out
- .println("AbstractTracked.untrack[removed from initial]: " + item); //$NON-NLS-1$
- }
- return; /*
- * we have removed it from the list and it will not be
- * processed
- */
- }
-
- if (adding.remove(item)) { /*
- * if the item is in the process of
- * being added
- */
- if (DEBUG) {
- System.out
- .println("AbstractTracked.untrack[being added]: " + item); //$NON-NLS-1$
- }
- return; /*
- * in case the item is untracked while in the process of
- * adding
- */
- }
- object = tracked.remove(item); /*
- * must remove from tracker before
- * calling customizer callback
- */
- if (object == null) { /* are we actually tracking the item */
- return;
- }
- modified(); /* increment modification count */
- }
- if (DEBUG) {
- System.out.println("AbstractTracked.untrack[removed]: " + item); //$NON-NLS-1$
- }
- /* Call customizer outside of synchronized region */
- customizerRemoved(item, related, object);
- /*
- * If the customizer throws an unchecked exception, it is safe to let it
- * propagate
- */
- }
-
- /**
- * Returns the number of tracked items.
- *
- * @return The number of tracked items.
- *
- * @GuardedBy this
- */
- int size() {
- return tracked.size();
- }
-
- /**
- * Return the customized object for the specified item
- *
- * @param item The item to lookup in the map
- * @return The customized object for the specified item.
- *
- * @GuardedBy this
- */
- Object getCustomizedObject(final Object item) {
- return tracked.get(item);
- }
-
- /**
- * Return the list of tracked items.
- *
- * @param list An array to contain the tracked items.
- * @return The specified list if it is large enough to hold the tracked
- * items or a new array large enough to hold the tracked items.
- * @GuardedBy this
- */
- Object[] getTracked(final Object[] list) {
- return tracked.keySet().toArray(list);
- }
-
- /**
- * Increment the modification count. If this method is overridden, the
- * overriding method MUST call this method to increment the tracking count.
- *
- * @GuardedBy this
- */
- void modified() {
- trackingCount++;
- }
-
- /**
- * Returns the tracking count for this <code>ServiceTracker</code> object.
- *
- * The tracking count is initialized to 0 when this object is opened. Every
- * time an item is added, modified or removed from this object the tracking
- * count is incremented.
- *
- * @GuardedBy this
- * @return The tracking count for this object.
- */
- int getTrackingCount() {
- return trackingCount;
- }
-
- /**
- * Call the specific customizer adding method. This method must not be
- * called while synchronized on this object.
- *
- * @param item Item to be tracked.
- * @param related Action related object.
- * @return Customized object for the tracked item or <code>null</code> if
- * the item is not to be tracked.
- */
- abstract Object customizerAdding(final Object item, final Object related);
-
- /** marrs: Call the specific customizer added method. */
- abstract void customizerAdded(final Object item, final Object related, final Object object);
-
- /**
- * Call the specific customizer modified method. This method must not be
- * called while synchronized on this object.
- *
- * @param item Tracked item.
- * @param related Action related object.
- * @param object Customized object for the tracked item.
- */
- abstract void customizerModified(final Object item, final Object related,
- final Object object);
-
- /**
- * Call the specific customizer removed method. This method must not be
- * called while synchronized on this object.
- *
- * @param item Tracked item.
- * @param related Action related object.
- * @param object Customized object for the tracked item.
- */
- abstract void customizerRemoved(final Object item, final Object related,
- final Object object);
-}
diff --git a/dependencymanager/core/src/main/java/org/apache/felix/dm/tracker/BundleTracker.java b/dependencymanager/core/src/main/java/org/apache/felix/dm/tracker/BundleTracker.java
deleted file mode 100644
index 9343375..0000000
--- a/dependencymanager/core/src/main/java/org/apache/felix/dm/tracker/BundleTracker.java
+++ /dev/null
@@ -1,478 +0,0 @@
-package org.apache.felix.dm.tracker;
-/*
- * Copyright (c) OSGi Alliance (2007, 2008). All Rights Reserved.
- *
- * 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.
- */
-
-import org.osgi.framework.Bundle;
-import org.osgi.framework.BundleContext;
-import org.osgi.framework.BundleEvent;
-import org.osgi.framework.SynchronousBundleListener;
-
-/**
- * The <code>BundleTracker</code> class simplifies tracking bundles much like
- * the <code>ServiceTracker</code> simplifies tracking services.
- * <p>
- * A <code>BundleTracker</code> is constructed with state criteria and a
- * <code>BundleTrackerCustomizer</code> object. A <code>BundleTracker</code> can
- * use the <code>BundleTrackerCustomizer</code> to select which bundles are
- * tracked and to create a customized object to be tracked with the bundle. The
- * <code>BundleTracker</code> can then be opened to begin tracking all bundles
- * whose state matches the specified state criteria.
- * <p>
- * The <code>getBundles</code> method can be called to get the
- * <code>Bundle</code> objects of the bundles being tracked. The
- * <code>getObject</code> method can be called to get the customized object for
- * a tracked bundle.
- * <p>
- * The <code>BundleTracker</code> class is thread-safe. It does not call a
- * <code>BundleTrackerCustomizer</code> while holding any locks.
- * <code>BundleTrackerCustomizer</code> implementations must also be
- * thread-safe.
- *
- * @ThreadSafe
- * @version $Revision: 5894 $
- * @since 1.4
- */
-public class BundleTracker implements BundleTrackerCustomizer {
- /* set this to true to compile in debug messages */
- static final boolean DEBUG = false;
-
- /**
- * The Bundle Context used by this <code>BundleTracker</code>.
- */
- protected final BundleContext context;
-
- /**
- * The <code>BundleTrackerCustomizer</code> object for this tracker.
- */
- final BundleTrackerCustomizer customizer;
-
- /**
- * Tracked bundles: <code>Bundle</code> object -> customized Object and
- * <code>BundleListener</code> object
- */
- private volatile Tracked tracked;
-
- /**
- * Accessor method for the current Tracked object. This method is only
- * intended to be used by the unsynchronized methods which do not modify the
- * tracked field.
- *
- * @return The current Tracked object.
- */
- private Tracked tracked() {
- return tracked;
- }
-
- /**
- * State mask for bundles being tracked. This field contains the ORed values
- * of the bundle states being tracked.
- */
- final int mask;
-
- /**
- * Create a <code>BundleTracker</code> for bundles whose state is present in
- * the specified state mask.
- *
- * <p>
- * Bundles whose state is present on the specified state mask will be
- * tracked by this <code>BundleTracker</code>.
- *
- * @param context The <code>BundleContext</code> against which the tracking
- * is done.
- * @param stateMask The bit mask of the <code>OR</code>ing of the bundle
- * states to be tracked.
- * @param customizer The customizer object to call when bundles are added,
- * modified, or removed in this <code>BundleTracker</code>. If
- * customizer is <code>null</code>, then this
- * <code>BundleTracker</code> will be used as the
- * <code>BundleTrackerCustomizer</code> and this
- * <code>BundleTracker</code> will call the
- * <code>BundleTrackerCustomizer</code> methods on itself.
- * @see Bundle#getState()
- */
- public BundleTracker(BundleContext context, int stateMask,
- BundleTrackerCustomizer customizer) {
- this.context = context;
- this.mask = stateMask;
- this.customizer = (customizer == null) ? this : customizer;
- }
-
- /**
- * Open this <code>BundleTracker</code> and begin tracking bundles.
- *
- * <p>
- * Bundle which match the state criteria specified when this
- * <code>BundleTracker</code> was created are now tracked by this
- * <code>BundleTracker</code>.
- *
- * @throws java.lang.IllegalStateException If the <code>BundleContext</code>
- * with which this <code>BundleTracker</code> was created is no
- * longer valid.
- * @throws java.lang.SecurityException If the caller and this class do not
- * have the appropriate
- * <code>AdminPermission[context bundle,LISTENER]</code>, and the
- * Java Runtime Environment supports permissions.
- */
- public void open() {
- final Tracked t;
- synchronized (this) {
- if (tracked != null) {
- return;
- }
- if (DEBUG) {
- System.out.println("BundleTracker.open"); //$NON-NLS-1$
- }
- t = new Tracked();
- synchronized (t) {
- context.addBundleListener(t);
- Bundle[] bundles = context.getBundles();
- if (bundles != null) {
- int length = bundles.length;
- for (int i = 0; i < length; i++) {
- int state = bundles[i].getState();
- if ((state & mask) == 0) {
- /* null out bundles whose states are not interesting */
- bundles[i] = null;
- }
- }
- /* set tracked with the initial bundles */
- t.setInitial(bundles);
- }
- }
- tracked = t;
- }
- /* Call tracked outside of synchronized region */
- t.trackInitial(); /* process the initial references */
- }
-
- /**
- * Close this <code>BundleTracker</code>.
- *
- * <p>
- * This method should be called when this <code>BundleTracker</code> should
- * end the tracking of bundles.
- *
- * <p>
- * This implementation calls {@link #getBundles()} to get the list of
- * tracked bundles to remove.
- */
- public void close() {
- final Bundle[] bundles;
- final Tracked outgoing;
- synchronized (this) {
- outgoing = tracked;
- if (outgoing == null) {
- return;
- }
- if (DEBUG) {
- System.out.println("BundleTracker.close"); //$NON-NLS-1$
- }
- outgoing.close();
- bundles = getBundles();
- tracked = null;
- try {
- context.removeBundleListener(outgoing);
- }
- catch (IllegalStateException e) {
- /* In case the context was stopped. */
- }
- }
- if (bundles != null) {
- for (int i = 0; i < bundles.length; i++) {
- outgoing.untrack(bundles[i], null);
- }
- }
- }
-
- /**
- * Default implementation of the
- * <code>BundleTrackerCustomizer.addingBundle</code> method.
- *
- * <p>
- * This method is only called when this <code>BundleTracker</code> has been
- * constructed with a <code>null BundleTrackerCustomizer</code> argument.
- *
- * <p>
- * This implementation simply returns the specified <code>Bundle</code>.
- *
- * <p>
- * This method can be overridden in a subclass to customize the object to be
- * tracked for the bundle being added.
- *
- * @param bundle The <code>Bundle</code> being added to this
- * <code>BundleTracker</code> object.
- * @param event The bundle event which caused this customizer method to be
- * called or <code>null</code> if there is no bundle event associated
- * with the call to this method.
- * @return The specified bundle.
- * @see BundleTrackerCustomizer#addingBundle(Bundle, BundleEvent)
- */
- public Object addingBundle(Bundle bundle, BundleEvent event) {
- return bundle;
- }
-
- public void addedBundle(Bundle bundle, BundleEvent event, Object object) {
- /* do nothing */
- }
-
- /**
- * Default implementation of the
- * <code>BundleTrackerCustomizer.modifiedBundle</code> method.
- *
- * <p>
- * This method is only called when this <code>BundleTracker</code> has been
- * constructed with a <code>null BundleTrackerCustomizer</code> argument.
- *
- * <p>
- * This implementation does nothing.
- *
- * @param bundle The <code>Bundle</code> whose state has been modified.
- * @param event The bundle event which caused this customizer method to be
- * called or <code>null</code> if there is no bundle event associated
- * with the call to this method.
- * @param object The customized object for the specified Bundle.
- * @see BundleTrackerCustomizer#modifiedBundle(Bundle, BundleEvent, Object)
- */
- public void modifiedBundle(Bundle bundle, BundleEvent event, Object object) {
- /* do nothing */
- }
-
- /**
- * Default implementation of the
- * <code>BundleTrackerCustomizer.removedBundle</code> method.
- *
- * <p>
- * This method is only called when this <code>BundleTracker</code> has been
- * constructed with a <code>null BundleTrackerCustomizer</code> argument.
- *
- * <p>
- * This implementation does nothing.
- *
- * @param bundle The <code>Bundle</code> being removed.
- * @param event The bundle event which caused this customizer method to be
- * called or <code>null</code> if there is no bundle event associated
- * with the call to this method.
- * @param object The customized object for the specified bundle.
- * @see BundleTrackerCustomizer#removedBundle(Bundle, BundleEvent, Object)
- */
- public void removedBundle(Bundle bundle, BundleEvent event, Object object) {
- /* do nothing */
- }
-
- /**
- * Return an array of <code>Bundle</code>s for all bundles being tracked by
- * this <code>BundleTracker</code>.
- *
- * @return An array of <code>Bundle</code>s or <code>null</code> if no
- * bundles are being tracked.
- */
- public Bundle[] getBundles() {
- final Tracked t = tracked();
- if (t == null) { /* if BundleTracker is not open */
- return null;
- }
- synchronized (t) {
- int length = t.size();
- if (length == 0) {
- return null;
- }
- return (Bundle[]) t.getTracked(new Bundle[length]);
- }
- }
-
- /**
- * Returns the customized object for the specified <code>Bundle</code> if
- * the specified bundle is being tracked by this <code>BundleTracker</code>.
- *
- * @param bundle The <code>Bundle</code> being tracked.
- * @return The customized object for the specified <code>Bundle</code> or
- * <code>null</code> if the specified <code>Bundle</code> is not
- * being tracked.
- */
- public Object getObject(Bundle bundle) {
- final Tracked t = tracked();
- if (t == null) { /* if BundleTracker is not open */
- return null;
- }
- synchronized (t) {
- return t.getCustomizedObject(bundle);
- }
- }
-
- /**
- * Remove a bundle from this <code>BundleTracker</code>.
- *
- * The specified bundle will be removed from this <code>BundleTracker</code>
- * . If the specified bundle was being tracked then the
- * <code>BundleTrackerCustomizer.removedBundle</code> method will be called
- * for that bundle.
- *
- * @param bundle The <code>Bundle</code> to be removed.
- */
- public void remove(Bundle bundle) {
- final Tracked t = tracked();
- if (t == null) { /* if BundleTracker is not open */
- return;
- }
- t.untrack(bundle, null);
- }
-
- /**
- * Return the number of bundles being tracked by this
- * <code>BundleTracker</code>.
- *
- * @return The number of bundles being tracked.
- */
- public int size() {
- final Tracked t = tracked();
- if (t == null) { /* if BundleTracker is not open */
- return 0;
- }
- synchronized (t) {
- return t.size();
- }
- }
-
- /**
- * Returns the tracking count for this <code>BundleTracker</code>.
- *
- * The tracking count is initialized to 0 when this
- * <code>BundleTracker</code> is opened. Every time a bundle is added,
- * modified or removed from this <code>BundleTracker</code> the tracking
- * count is incremented.
- *
- * <p>
- * The tracking count can be used to determine if this
- * <code>BundleTracker</code> has added, modified or removed a bundle by
- * comparing a tracking count value previously collected with the current
- * tracking count value. If the value has not changed, then no bundle has
- * been added, modified or removed from this <code>BundleTracker</code>
- * since the previous tracking count was collected.
- *
- * @return The tracking count for this <code>BundleTracker</code> or -1 if
- * this <code>BundleTracker</code> is not open.
- */
- public int getTrackingCount() {
- final Tracked t = tracked();
- if (t == null) { /* if BundleTracker is not open */
- return -1;
- }
- synchronized (t) {
- return t.getTrackingCount();
- }
- }
-
- /**
- * Inner class which subclasses AbstractTracked. This class is the
- * <code>SynchronousBundleListener</code> object for the tracker.
- *
- * @ThreadSafe
- * @since 1.4
- */
- class Tracked extends AbstractTracked implements SynchronousBundleListener {
- /**
- * Tracked constructor.
- */
- Tracked() {
- super();
- }
-
- /**
- * <code>BundleListener</code> method for the <code>BundleTracker</code>
- * class. This method must NOT be synchronized to avoid deadlock
- * potential.
- *
- * @param event <code>BundleEvent</code> object from the framework.
- */
- public void bundleChanged(final BundleEvent event) {
- /*
- * Check if we had a delayed call (which could happen when we
- * close).
- */
- if (closed) {
- return;
- }
- final Bundle bundle = event.getBundle();
- final int state = bundle.getState();
- if (DEBUG) {
- System.out
- .println("BundleTracker.Tracked.bundleChanged[" + state + "]: " + bundle); //$NON-NLS-1$ //$NON-NLS-2$
- }
-
- if ((state & mask) != 0) {
- track(bundle, event);
- /*
- * If the customizer throws an unchecked exception, it is safe
- * to let it propagate
- */
- }
- else {
- untrack(bundle, event);
- /*
- * If the customizer throws an unchecked exception, it is safe
- * to let it propagate
- */
- }
- }
-
- /**
- * Call the specific customizer adding method. This method must not be
- * called while synchronized on this object.
- *
- * @param item Item to be tracked.
- * @param related Action related object.
- * @return Customized object for the tracked item or <code>null</code>
- * if the item is not to be tracked.
- */
- Object customizerAdding(final Object item,
- final Object related) {
- return customizer
- .addingBundle((Bundle) item, (BundleEvent) related);
- }
-
- void customizerAdded(final Object item, final Object related, final Object object) {
- customizer.addedBundle((Bundle) item, (BundleEvent) related, object);
- }
-
- /**
- * Call the specific customizer modified method. This method must not be
- * called while synchronized on this object.
- *
- * @param item Tracked item.
- * @param related Action related object.
- * @param object Customized object for the tracked item.
- */
- void customizerModified(final Object item,
- final Object related, final Object object) {
- customizer.modifiedBundle((Bundle) item, (BundleEvent) related,
- object);
- }
-
- /**
- * Call the specific customizer removed method. This method must not be
- * called while synchronized on this object.
- *
- * @param item Tracked item.
- * @param related Action related object.
- * @param object Customized object for the tracked item.
- */
- void customizerRemoved(final Object item,
- final Object related, final Object object) {
- customizer.removedBundle((Bundle) item, (BundleEvent) related,
- object);
- }
- }
-}
diff --git a/dependencymanager/core/src/main/java/org/apache/felix/dm/tracker/BundleTrackerCustomizer.java b/dependencymanager/core/src/main/java/org/apache/felix/dm/tracker/BundleTrackerCustomizer.java
deleted file mode 100644
index 0fd340e..0000000
--- a/dependencymanager/core/src/main/java/org/apache/felix/dm/tracker/BundleTrackerCustomizer.java
+++ /dev/null
@@ -1,106 +0,0 @@
-package org.apache.felix.dm.tracker;
-/*
- * Copyright (c) OSGi Alliance (2007, 2008). All Rights Reserved.
- *
- * 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.
- */
-
-import org.osgi.framework.Bundle;
-import org.osgi.framework.BundleEvent;
-
-/**
- * The <code>BundleTrackerCustomizer</code> interface allows a
- * <code>BundleTracker</code> to customize the <code>Bundle</code>s that are
- * tracked. A <code>BundleTrackerCustomizer</code> is called when a bundle is
- * being added to a <code>BundleTracker</code>. The
- * <code>BundleTrackerCustomizer</code> can then return an object for the
- * tracked bundle. A <code>BundleTrackerCustomizer</code> is also called when a
- * tracked bundle is modified or has been removed from a
- * <code>BundleTracker</code>.
- *
- * <p>
- * The methods in this interface may be called as the result of a
- * <code>BundleEvent</code> being received by a <code>BundleTracker</code>.
- * Since <code>BundleEvent</code>s are received synchronously by the
- * <code>BundleTracker</code>, it is highly recommended that implementations of
- * these methods do not alter bundle states while being synchronized on any
- * object.
- *
- * <p>
- * The <code>BundleTracker</code> class is thread-safe. It does not call a
- * <code>BundleTrackerCustomizer</code> while holding any locks.
- * <code>BundleTrackerCustomizer</code> implementations must also be
- * thread-safe.
- *
- * @ThreadSafe
- * @version $Revision: 5874 $
- * @since 1.4
- */
-public interface BundleTrackerCustomizer {
- /**
- * A bundle is being added to the <code>BundleTracker</code>.
- *
- * <p>
- * This method is called before a bundle which matched the search parameters
- * of the <code>BundleTracker</code> is added to the
- * <code>BundleTracker</code>. This method should return the object to be
- * tracked for the specified <code>Bundle</code>. The returned object is
- * stored in the <code>BundleTracker</code> and is available from the
- * {@link BundleTracker#getObject(Bundle) getObject} method.
- *
- * @param bundle The <code>Bundle</code> being added to the
- * <code>BundleTracker</code>.
- * @param event The bundle event which caused this customizer method to be
- * called or <code>null</code> if there is no bundle event associated
- * with the call to this method.
- * @return The object to be tracked for the specified <code>Bundle</code>
- * object or <code>null</code> if the specified <code>Bundle</code>
- * object should not be tracked.
- */
- public Object addingBundle(Bundle bundle, BundleEvent event);
-
- /** marrs: A bundle has been added to the BundleTracker. */
- public void addedBundle(Bundle bundle, BundleEvent event, Object object);
-
- /**
- * A bundle tracked by the <code>BundleTracker</code> has been modified.
- *
- * <p>
- * This method is called when a bundle being tracked by the
- * <code>BundleTracker</code> has had its state modified.
- *
- * @param bundle The <code>Bundle</code> whose state has been modified.
- * @param event The bundle event which caused this customizer method to be
- * called or <code>null</code> if there is no bundle event associated
- * with the call to this method.
- * @param object The tracked object for the specified bundle.
- */
- public void modifiedBundle(Bundle bundle, BundleEvent event,
- Object object);
-
- /**
- * A bundle tracked by the <code>BundleTracker</code> has been removed.
- *
- * <p>
- * This method is called after a bundle is no longer being tracked by the
- * <code>BundleTracker</code>.
- *
- * @param bundle The <code>Bundle</code> that has been removed.
- * @param event The bundle event which caused this customizer method to be
- * called or <code>null</code> if there is no bundle event associated
- * with the call to this method.
- * @param object The tracked object for the specified bundle.
- */
- public void removedBundle(Bundle bundle, BundleEvent event,
- Object object);
-}
diff --git a/dependencymanager/core/src/main/java/org/apache/felix/dm/tracker/ServiceTracker.java b/dependencymanager/core/src/main/java/org/apache/felix/dm/tracker/ServiceTracker.java
deleted file mode 100644
index 01102c6..0000000
--- a/dependencymanager/core/src/main/java/org/apache/felix/dm/tracker/ServiceTracker.java
+++ /dev/null
@@ -1,1428 +0,0 @@
-package org.apache.felix.dm.tracker;
-/*
- * Copyright (c) OSGi Alliance (2000, 2009). All Rights Reserved.
- *
- * 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.
- */
-
-import java.security.AccessController;
-import java.security.PrivilegedAction;
-import java.util.ArrayList;
-import java.util.HashMap;
-import java.util.Iterator;
-import java.util.LinkedHashMap;
-import java.util.List;
-import java.util.Map;
-import java.util.Map.Entry;
-import java.util.TreeSet;
-
-import org.apache.felix.dm.DependencyManager;
-import org.apache.felix.dm.ServiceUtil;
-import org.osgi.framework.AllServiceListener;
-import org.osgi.framework.BundleContext;
-import org.osgi.framework.Constants;
-import org.osgi.framework.Filter;
-import org.osgi.framework.InvalidSyntaxException;
-import org.osgi.framework.ServiceEvent;
-import org.osgi.framework.ServiceListener;
-import org.osgi.framework.ServiceReference;
-import org.osgi.framework.Version;
-
-/**
- * The <code>ServiceTracker</code> class simplifies using services from the
- * Framework's service registry.
- * <p>
- * A <code>ServiceTracker</code> object is constructed with search criteria and
- * a <code>ServiceTrackerCustomizer</code> object. A <code>ServiceTracker</code>
- * can use a <code>ServiceTrackerCustomizer</code> to customize the service
- * objects to be tracked. The <code>ServiceTracker</code> can then be opened to
- * begin tracking all services in the Framework's service registry that match
- * the specified search criteria. The <code>ServiceTracker</code> correctly
- * handles all of the details of listening to <code>ServiceEvent</code>s and
- * getting and ungetting services.
- * <p>
- * The <code>getServiceReferences</code> method can be called to get references
- * to the services being tracked. The <code>getService</code> and
- * <code>getServices</code> methods can be called to get the service objects for
- * the tracked service.
- * <p>
- * The <code>ServiceTracker</code> class is thread-safe. It does not call a
- * <code>ServiceTrackerCustomizer</code> while holding any locks.
- * <code>ServiceTrackerCustomizer</code> implementations must also be
- * thread-safe.
- *
- * @ThreadSafe
- * @version $Revision: 6386 $
- */
-public class ServiceTracker implements ServiceTrackerCustomizer {
- /* set this to true to compile in debug messages */
- static final boolean DEBUG = false;
- /**
- * The Bundle Context used by this <code>ServiceTracker</code>.
- */
- protected final BundleContext context;
- /**
- * The Filter used by this <code>ServiceTracker</code> which specifies the
- * search criteria for the services to track.
- *
- * @since 1.1
- */
- protected final Filter filter;
- /**
- * The <code>ServiceTrackerCustomizer</code> for this tracker.
- */
- final ServiceTrackerCustomizer customizer;
- /**
- * Filter string for use when adding the ServiceListener. If this field is
- * set, then certain optimizations can be taken since we don't have a user
- * supplied filter.
- */
- final String listenerFilter;
- /**
- * Class name to be tracked. If this field is set, then we are tracking by
- * class name.
- */
- private final String trackClass;
- /**
- * Reference to be tracked. If this field is set, then we are tracking a
- * single ServiceReference.
- */
- private final ServiceReference trackReference;
- /**
- * Tracked services: <code>ServiceReference</code> -> customized Object and
- * <code>ServiceListener</code> object
- */
- private volatile Tracked tracked;
-
- /**
- * Accessor method for the current Tracked object. This method is only
- * intended to be used by the unsynchronized methods which do not modify the
- * tracked field.
- *
- * @return The current Tracked object.
- */
- private Tracked tracked() {
- return tracked;
- }
-
- /**
- * Cached ServiceReference for getServiceReference.
- *
- * This field is volatile since it is accessed by multiple threads.
- */
- private volatile ServiceReference cachedReference;
- /**
- * Cached service object for getService.
- *
- * This field is volatile since it is accessed by multiple threads.
- */
- private volatile Object cachedService;
-
- /**
- * org.osgi.framework package version which introduced
- * {@link ServiceEvent#MODIFIED_ENDMATCH}
- */
- private static final Version endMatchVersion = new Version(1, 5, 0);
-
- /**
- * Flag that gets set when opening the tracker, determines if the tracker should
- * track all aspects or just the highest ranked ones.
- */
- public boolean m_trackAllAspects;
-
- /**
- * Create a <code>ServiceTracker</code> on the specified
- * <code>ServiceReference</code>.
- *
- * <p>
- * The service referenced by the specified <code>ServiceReference</code>
- * will be tracked by this <code>ServiceTracker</code>.
- *
- * @param context The <code>BundleContext</code> against which the tracking
- * is done.
- * @param reference The <code>ServiceReference</code> for the service to be
- * tracked.
- * @param customizer The customizer object to call when services are added,
- * modified, or removed in this <code>ServiceTracker</code>. If
- * customizer is <code>null</code>, then this
- * <code>ServiceTracker</code> will be used as the
- * <code>ServiceTrackerCustomizer</code> and this
- * <code>ServiceTracker</code> will call the
- * <code>ServiceTrackerCustomizer</code> methods on itself.
- */
- public ServiceTracker(final BundleContext context,
- final ServiceReference reference,
- final ServiceTrackerCustomizer customizer) {
- this.context = context;
- this.trackReference = reference;
- this.trackClass = null;
- this.customizer = (customizer == null) ? this : customizer;
- this.listenerFilter = "(" + Constants.SERVICE_ID + "="
- + reference.getProperty(Constants.SERVICE_ID).toString() + ")";
- try {
- this.filter = context.createFilter(listenerFilter);
- }
- catch (InvalidSyntaxException e) {
- /*
- * we could only get this exception if the ServiceReference was
- * invalid
- */
- IllegalArgumentException iae = new IllegalArgumentException(
- "unexpected InvalidSyntaxException: " + e.getMessage());
- iae.initCause(e);
- throw iae;
- }
- }
-
- /**
- * Create a <code>ServiceTracker</code> on the specified class name.
- *
- * <p>
- * Services registered under the specified class name will be tracked by
- * this <code>ServiceTracker</code>.
- *
- * @param context The <code>BundleContext</code> against which the tracking
- * is done.
- * @param clazz The class name of the services to be tracked.
- * @param customizer The customizer object to call when services are added,
- * modified, or removed in this <code>ServiceTracker</code>. If
- * customizer is <code>null</code>, then this
- * <code>ServiceTracker</code> will be used as the
- * <code>ServiceTrackerCustomizer</code> and this
- * <code>ServiceTracker</code> will call the
- * <code>ServiceTrackerCustomizer</code> methods on itself.
- */
- public ServiceTracker(final BundleContext context, final String clazz,
- final ServiceTrackerCustomizer customizer) {
- this.context = context;
- this.trackReference = null;
- this.trackClass = clazz;
- this.customizer = (customizer == null) ? this : customizer;
- // we call clazz.toString to verify clazz is non-null!
- this.listenerFilter = "(" + Constants.OBJECTCLASS + "="
- + clazz.toString() + ")";
- try {
- this.filter = context.createFilter(listenerFilter);
- }
- catch (InvalidSyntaxException e) {
- /*
- * we could only get this exception if the clazz argument was
- * malformed
- */
- IllegalArgumentException iae = new IllegalArgumentException(
- "unexpected InvalidSyntaxException: " + e.getMessage());
- iae.initCause(e);
- throw iae;
- }
- }
-
- /**
- * Create a <code>ServiceTracker</code> on the specified <code>Filter</code>
- * object.
- *
- * <p>
- * Services which match the specified <code>Filter</code> object will be
- * tracked by this <code>ServiceTracker</code>.
- *
- * @param context The <code>BundleContext</code> against which the tracking
- * is done.
- * @param filter The <code>Filter</code> to select the services to be
- * tracked.
- * @param customizer The customizer object to call when services are added,
- * modified, or removed in this <code>ServiceTracker</code>. If
- * customizer is null, then this <code>ServiceTracker</code> will be
- * used as the <code>ServiceTrackerCustomizer</code> and this
- * <code>ServiceTracker</code> will call the
- * <code>ServiceTrackerCustomizer</code> methods on itself.
- * @since 1.1
- */
- public ServiceTracker(final BundleContext context, final Filter filter,
- final ServiceTrackerCustomizer customizer) {
- this.context = context;
- this.trackReference = null;
- this.trackClass = null;
- final Version frameworkVersion = (Version) AccessController
- .doPrivileged(new PrivilegedAction() {
- public Object run() {
- String version = context
- .getProperty(Constants.FRAMEWORK_VERSION);
- return (version == null) ? Version.emptyVersion
- : new Version(version);
- }
- });
- final boolean endMatchSupported = (frameworkVersion
- .compareTo(endMatchVersion) >= 0);
- this.listenerFilter = endMatchSupported ? filter.toString() : null;
- this.filter = filter;
- this.customizer = (customizer == null) ? this : customizer;
- if ((context == null) || (filter == null)) {
- /*
- * we throw a NPE here to be consistent with the other constructors
- */
- throw new NullPointerException();
- }
- }
-
- /**
- * Open this <code>ServiceTracker</code> and begin tracking services.
- *
- * <p>
- * This implementation calls <code>open(false)</code>.
- *
- * @throws java.lang.IllegalStateException If the <code>BundleContext</code>
- * with which this <code>ServiceTracker</code> was created is no
- * longer valid.
- * @see #open(boolean)
- */
- public void open() {
- open(false);
- }
-
- /**
- * Open this <code>ServiceTracker</code> and begin tracking services.
- *
- * <p>
- * Services which match the search criteria specified when this
- * <code>ServiceTracker</code> was created are now tracked by this
- * <code>ServiceTracker</code>.
- *
- * @param trackAllServices If <code>true</code>, then this
- * <code>ServiceTracker</code> will track all matching services
- * regardless of class loader accessibility. If <code>false</code>,
- * then this <code>ServiceTracker</code> will only track matching
- * services which are class loader accessible to the bundle whose
- * <code>BundleContext</code> is used by this
- * <code>ServiceTracker</code>.
- * @throws java.lang.IllegalStateException If the <code>BundleContext</code>
- * with which this <code>ServiceTracker</code> was created is no
- * longer valid.
- * @since 1.3
- */
- public void open(boolean trackAllServices) {
- open(trackAllServices, false);
- }
-
- /**
- * Open this <code>ServiceTracker</code> and begin tracking services.
- *
- * <p>
- * Services which match the search criteria specified when this
- * <code>ServiceTracker</code> was created are now tracked by this
- * <code>ServiceTracker</code>.
- *
- * @param trackAllServices If <code>true</code>, then this
- * <code>ServiceTracker</code> will track all matching services
- * regardless of class loader accessibility. If <code>false</code>,
- * then this <code>ServiceTracker</code> will only track matching
- * services which are class loader accessible to the bundle whose
- * <code>BundleContext</code> is used by this
- * <code>ServiceTracker</code>.
- * @param trackAllAspects If <code>true</code> then this
- * <code>ServiceTracker</code> will track all aspects regardless
- * of their rank. If <code>false</code> only the highest ranked
- * aspects (or the original service if there are no aspects) will
- * be tracked. The latter is the default.
- * @throws java.lang.IllegalStateException If the <code>BundleContext</code>
- * with which this <code>ServiceTracker</code> was created is no
- * longer valid.
- */
- public void open(boolean trackAllServices, boolean trackAllAspects) {
- final Tracked t;
- synchronized (this) {
- if (tracked != null) {
- return;
- }
- if (DEBUG) {
- System.out.println("ServiceTracker.open: " + filter);
- }
- m_trackAllAspects = trackAllAspects;
- t = trackAllServices ? new AllTracked() : new Tracked();
- synchronized (t) {
- try {
- context.addServiceListener(t, listenerFilter);
- ServiceReference[] references = null;
- if (trackClass != null) {
- references = getInitialReferences(trackAllServices,
- trackClass, null);
- }
- else {
- if (trackReference != null) {
- if (trackReference.getBundle() != null) {
- references = new ServiceReference[] {trackReference};
- }
- }
- else { /* user supplied filter */
- references = getInitialReferences(trackAllServices,
- null,
- (listenerFilter != null) ? listenerFilter
- : filter.toString());
- }
- }
- /* set tracked with the initial references */
- t.setInitial(references);
- }
- catch (InvalidSyntaxException e) {
- throw new RuntimeException(
- "unexpected InvalidSyntaxException: "
- + e.getMessage(), e);
- }
- }
- tracked = t;
- }
- /* Call tracked outside of synchronized region */
- t.trackInitial(); /* process the initial references */
- }
-
- /**
- * Returns the list of initial <code>ServiceReference</code>s that will be
- * tracked by this <code>ServiceTracker</code>.
- *
- * @param trackAllServices If <code>true</code>, use
- * <code>getAllServiceReferences</code>.
- * @param className The class name with which the service was registered, or
- * <code>null</code> for all services.
- * @param filterString The filter criteria or <code>null</code> for all
- * services.
- * @return The list of initial <code>ServiceReference</code>s.
- * @throws InvalidSyntaxException If the specified filterString has an
- * invalid syntax.
- */
- private ServiceReference[] getInitialReferences(boolean trackAllServices,
- String className, String filterString)
- throws InvalidSyntaxException {
- if (trackAllServices) {
- return context.getAllServiceReferences(className, filterString);
- }
- return context.getServiceReferences(className, filterString);
- }
-
- /**
- * Close this <code>ServiceTracker</code>.
- *
- * <p>
- * This method should be called when this <code>ServiceTracker</code> should
- * end the tracking of services.
- *
- * <p>
- * This implementation calls {@link #getServiceReferences()} to get the list
- * of tracked services to remove.
- */
- public void close() {
- final Tracked outgoing;
- final ServiceReference[] references;
- synchronized (this) {
- outgoing = tracked;
- if (outgoing == null) {
- return;
- }
- if (DEBUG) {
- System.out.println("ServiceTracker.close: " + filter);
- }
- outgoing.close();
- references = getServiceReferences();
- tracked = null;
- try {
- context.removeServiceListener(outgoing);
- }
- catch (IllegalStateException e) {
- /* In case the context was stopped. */
- }
- }
- modified(); /* clear the cache */
- synchronized (outgoing) {
- outgoing.notifyAll(); /* wake up any waiters */
- }
- if (references != null) {
- for (int i = 0; i < references.length; i++) {
- outgoing.untrack(references[i], null);
- }
- }
- if (DEBUG) {
- if ((cachedReference == null) && (cachedService == null)) {
- System.out
- .println("ServiceTracker.close[cached cleared]: "
- + filter);
- }
- }
- }
-
- /**
- * Default implementation of the
- * <code>ServiceTrackerCustomizer.addingService</code> method.
- *
- * <p>
- * This method is only called when this <code>ServiceTracker</code> has been
- * constructed with a <code>null ServiceTrackerCustomizer</code> argument.
- *
- * <p>
- * This implementation returns the result of calling <code>getService</code>
- * on the <code>BundleContext</code> with which this
- * <code>ServiceTracker</code> was created passing the specified
- * <code>ServiceReference</code>.
- * <p>
- * This method can be overridden in a subclass to customize the service
- * object to be tracked for the service being added. In that case, take care
- * not to rely on the default implementation of
- * {@link #removedService(ServiceReference, Object) removedService} to unget
- * the service.
- *
- * @param reference The reference to the service being added to this
- * <code>ServiceTracker</code>.
- * @return The service object to be tracked for the service added to this
- * <code>ServiceTracker</code>.
- * @see ServiceTrackerCustomizer#addingService(ServiceReference)
- */
- public Object addingService(ServiceReference reference) {
- return context.getService(reference);
- }
-
- public void addedService(ServiceReference reference, Object service) {
- /* do nothing */
- }
-
- /**
- * Default implementation of the
- * <code>ServiceTrackerCustomizer.modifiedService</code> method.
- *
- * <p>
- * This method is only called when this <code>ServiceTracker</code> has been
- * constructed with a <code>null ServiceTrackerCustomizer</code> argument.
- *
- * <p>
- * This implementation does nothing.
- *
- * @param reference The reference to modified service.
- * @param service The service object for the modified service.
- * @see ServiceTrackerCustomizer#modifiedService(ServiceReference, Object)
- */
- public void modifiedService(ServiceReference reference, Object service) {
- /* do nothing */
- }
-
- /**
- * Default implementation of the
- * <code>ServiceTrackerCustomizer.removedService</code> method.
- *
- * <p>
- * This method is only called when this <code>ServiceTracker</code> has been
- * constructed with a <code>null ServiceTrackerCustomizer</code> argument.
- *
- * <p>
- * This implementation calls <code>ungetService</code>, on the
- * <code>BundleContext</code> with which this <code>ServiceTracker</code>
- * was created, passing the specified <code>ServiceReference</code>.
- * <p>
- * This method can be overridden in a subclass. If the default
- * implementation of {@link #addingService(ServiceReference) addingService}
- * method was used, this method must unget the service.
- *
- * @param reference The reference to removed service.
- * @param service The service object for the removed service.
- * @see ServiceTrackerCustomizer#removedService(ServiceReference, Object)
- */
- public void removedService(ServiceReference reference, Object service) {
- context.ungetService(reference);
- }
-
- /**
- * Wait for at least one service to be tracked by this
- * <code>ServiceTracker</code>. This method will also return when this
- * <code>ServiceTracker</code> is closed.
- *
- * <p>
- * It is strongly recommended that <code>waitForService</code> is not used
- * during the calling of the <code>BundleActivator</code> methods.
- * <code>BundleActivator</code> methods are expected to complete in a short
- * period of time.
- *
- * <p>
- * This implementation calls {@link #getService()} to determine if a service
- * is being tracked.
- *
- * @param timeout The time interval in milliseconds to wait. If zero, the
- * method will wait indefinitely.
- * @return Returns the result of {@link #getService()}.
- * @throws InterruptedException If another thread has interrupted the
- * current thread.
- * @throws IllegalArgumentException If the value of timeout is negative.
- */
- public Object waitForService(long timeout) throws InterruptedException {
- if (timeout < 0) {
- throw new IllegalArgumentException("timeout value is negative");
- }
- Object object = getService();
- while (object == null) {
- final Tracked t = tracked();
- if (t == null) { /* if ServiceTracker is not open */
- return null;
- }
- synchronized (t) {
- if (t.size() == 0) {
- t.wait(timeout);
- }
- }
- object = getService();
- if (timeout > 0) {
- return object;
- }
- }
- return object;
- }
-
- /**
- * Return an array of <code>ServiceReference</code>s for all services being
- * tracked by this <code>ServiceTracker</code>.
- *
- * @return Array of <code>ServiceReference</code>s or <code>null</code> if
- * no services are being tracked.
- */
- public ServiceReference[] getServiceReferences() {
- final Tracked t = tracked();
- if (t == null) { /* if ServiceTracker is not open */
- return null;
- }
- synchronized (t) {
- int length = t.size();
- if (length == 0) {
- return null;
- }
- return (ServiceReference[]) t
- .getTracked(new ServiceReference[length]);
- }
- }
-
- /**
- * Returns a boolean indicating whether this <code>ServiceTracker</code> is tracking any services.
- *
- * @return true if services are being tracked, false if no services are being tracked.
- */
- public boolean hasReference() {
- if (cachedReference != null) {
- return true;
- }
- final Tracked t = tracked();
- if (t == null) { /* if ServiceTracker is not open */
- return false;
- }
- synchronized (t) {
- int length = t.size();
- return length > 0;
- }
- }
-
- /**
- * Returns a <code>ServiceReference</code> for one of the services being
- * tracked by this <code>ServiceTracker</code>.
- *
- * <p>
- * If multiple services are being tracked, the service with the highest
- * ranking (as specified in its <code>service.ranking</code> property) is
- * returned. If there is a tie in ranking, the service with the lowest
- * service ID (as specified in its <code>service.id</code> property); that
- * is, the service that was registered first is returned. This is the same
- * algorithm used by <code>BundleContext.getServiceReference</code>.
- *
- * <p>
- * This implementation calls {@link #getServiceReferences()} to get the list
- * of references for the tracked services.
- *
- * @return A <code>ServiceReference</code> or <code>null</code> if no
- * services are being tracked.
- * @since 1.1
- */
- public ServiceReference getServiceReference() {
- ServiceReference reference = cachedReference;
- if (reference != null) {
- if (DEBUG) {
- System.out
- .println("ServiceTracker.getServiceReference[cached]: "
- + filter);
- }
- return reference;
- }
- if (DEBUG) {
- System.out.println("ServiceTracker.getServiceReference: " + filter);
- }
- ServiceReference[] references = getServiceReferences();
- int length = (references == null) ? 0 : references.length;
- if (length == 0) { /* if no service is being tracked */
- return null;
- }
- int index = 0;
- if (length > 1) { /* if more than one service, select highest ranking */
- int rankings[] = new int[length];
- int count = 0;
- int maxRanking = Integer.MIN_VALUE;
- for (int i = 0; i < length; i++) {
- Object property = references[i]
- .getProperty(Constants.SERVICE_RANKING);
- int ranking = (property instanceof Integer) ? ((Integer) property)
- .intValue()
- : 0;
- rankings[i] = ranking;
- if (ranking > maxRanking) {
- index = i;
- maxRanking = ranking;
- count = 1;
- }
- else {
- if (ranking == maxRanking) {
- count++;
- }
- }
- }
- if (count > 1) { /* if still more than one service, select lowest id */
- long minId = Long.MAX_VALUE;
- for (int i = 0; i < length; i++) {
- if (rankings[i] == maxRanking) {
- long id = ((Long) (references[i]
- .getProperty(Constants.SERVICE_ID)))
- .longValue();
- if (id < minId) {
- index = i;
- minId = id;
- }
- }
- }
- }
- }
- return cachedReference = references[index];
- }
-
- /**
- * Returns the service object for the specified
- * <code>ServiceReference</code> if the specified referenced service is
- * being tracked by this <code>ServiceTracker</code>.
- *
- * @param reference The reference to the desired service.
- * @return A service object or <code>null</code> if the service referenced
- * by the specified <code>ServiceReference</code> is not being
- * tracked.
- */
- public Object getService(ServiceReference reference) {
- final Tracked t = tracked();
- if (t == null) { /* if ServiceTracker is not open */
- return null;
- }
- synchronized (t) {
- return t.getCustomizedObject(reference);
- }
- }
-
- /**
- * Return an array of service objects for all services being tracked by this
- * <code>ServiceTracker</code>.
- *
- * <p>
- * This implementation calls {@link #getServiceReferences()} to get the list
- * of references for the tracked services and then calls
- * {@link #getService(ServiceReference)} for each reference to get the
- * tracked service object.
- *
- * @return An array of service objects or <code>null</code> if no services
- * are being tracked.
- */
- public Object[] getServices() {
- final Tracked t = tracked();
- if (t == null) { /* if ServiceTracker is not open */
- return null;
- }
- synchronized (t) {
- ServiceReference[] references = getServiceReferences();
- int length = (references == null) ? 0 : references.length;
- if (length == 0) {
- return null;
- }
- Object[] objects = new Object[length];
- for (int i = 0; i < length; i++) {
- objects[i] = getService(references[i]);
- }
- return objects;
- }
- }
-
- /**
- * Returns a service object for one of the services being tracked by this
- * <code>ServiceTracker</code>.
- *
- * <p>
- * If any services are being tracked, this implementation returns the result
- * of calling <code>getService(getServiceReference())</code>.
- *
- * @return A service object or <code>null</code> if no services are being
- * tracked.
- */
- public Object getService() {
- Object service = cachedService;
- if (service != null) {
- if (DEBUG) {
- System.out
- .println("ServiceTracker.getService[cached]: "
- + filter);
- }
- return service;
- }
- if (DEBUG) {
- System.out.println("ServiceTracker.getService: " + filter);
- }
- ServiceReference reference = getServiceReference();
- if (reference == null) {
- return null;
- }
- return cachedService = getService(reference);
- }
-
- /**
- * Remove a service from this <code>ServiceTracker</code>.
- *
- * The specified service will be removed from this
- * <code>ServiceTracker</code>. If the specified service was being tracked
- * then the <code>ServiceTrackerCustomizer.removedService</code> method will
- * be called for that service.
- *
- * @param reference The reference to the service to be removed.
- */
- public void remove(ServiceReference reference) {
- final Tracked t = tracked();
- if (t == null) { /* if ServiceTracker is not open */
- return;
- }
- t.untrack(reference, null);
- }
-
- /**
- * Return the number of services being tracked by this
- * <code>ServiceTracker</code>.
- *
- * @return The number of services being tracked.
- */
- public int size() {
- final Tracked t = tracked();
- if (t == null) { /* if ServiceTracker is not open */
- return 0;
- }
- synchronized (t) {
- return t.size();
- }
- }
-
- /**
- * Returns the tracking count for this <code>ServiceTracker</code>.
- *
- * The tracking count is initialized to 0 when this
- * <code>ServiceTracker</code> is opened. Every time a service is added,
- * modified or removed from this <code>ServiceTracker</code>, the tracking
- * count is incremented.
- *
- * <p>
- * The tracking count can be used to determine if this
- * <code>ServiceTracker</code> has added, modified or removed a service by
- * comparing a tracking count value previously collected with the current
- * tracking count value. If the value has not changed, then no service has
- * been added, modified or removed from this <code>ServiceTracker</code>
- * since the previous tracking count was collected.
- *
- * @since 1.2
- * @return The tracking count for this <code>ServiceTracker</code> or -1 if
- * this <code>ServiceTracker</code> is not open.
- */
- public int getTrackingCount() {
- final Tracked t = tracked();
- if (t == null) { /* if ServiceTracker is not open */
- return -1;
- }
- synchronized (t) {
- return t.getTrackingCount();
- }
- }
-
- /**
- * Called by the Tracked object whenever the set of tracked services is
- * modified. Clears the cache.
- */
- /*
- * This method must not be synchronized since it is called by Tracked while
- * Tracked is synchronized. We don't want synchronization interactions
- * between the listener thread and the user thread.
- */
- void modified() {
- cachedReference = null; /* clear cached value */
- cachedService = null; /* clear cached value */
- if (DEBUG) {
- System.out.println("ServiceTracker.modified: " + filter);
- }
- }
-
- /**
- * Inner class which subclasses AbstractTracked. This class is the
- * <code>ServiceListener</code> object for the tracker.
- *
- * @ThreadSafe
- */
- class Tracked extends AbstractTracked implements ServiceListener {
- /**
- * A list of services that are currently hidden because there is an aspect available with a higher ranking.
- * @GuardedBy this
- */
- private final List m_hidden = new ArrayList();
-
- /**
- * Returns the highest hidden aspect for the specified service ID.
- *
- * @param serviceId the service ID
- * @return a service reference, or <code>null</code> if there was no such service
- */
- private ServiceReference highestHidden(long serviceId) {
- ServiceReference result = null;
- int max = Integer.MIN_VALUE;
- synchronized (this) {
- for (int i = 0; i < m_hidden.size(); i++) {
- ServiceReference ref = (ServiceReference) m_hidden.get(i);
- Long sid = (Long) ref.getProperty(Constants.SERVICE_ID);
- Long aid = (Long) ref.getProperty(DependencyManager.ASPECT);
- if ((aid != null && aid.longValue() == serviceId)
- || (aid == null && sid != null && sid.longValue() == serviceId)) {
- Integer ranking = (Integer) ref.getProperty(Constants.SERVICE_RANKING);
- int r = 0;
- if (ranking != null) {
- r = ranking.intValue();
- }
- if (r > max) {
- max = r;
- result = ref;
- }
- }
- }
- }
- return result;
- }
-
- /**
- * Returns the highest tracked service for the specified service ID.
- *
- * @param serviceId the service ID
- * @return a service reference, or <code>null</code> if there was no such service
- */
- private ServiceReference highestTracked(long serviceId) {
- ServiceReference result = null;
- int max = Integer.MIN_VALUE;
-
- synchronized (this) {
- int length = size();
- if (length == 0) {
- return null;
- }
- Object[] trackedServices = getTracked(new ServiceReference[length]);
- for (int i = 0; i < trackedServices.length; i++) {
- ServiceReference ref = (ServiceReference) trackedServices[i];
- Long sid = (Long) ref.getProperty(Constants.SERVICE_ID);
- Long aid = (Long) ref.getProperty(DependencyManager.ASPECT);
- if ((aid != null && aid.longValue() == serviceId)
- || (aid == null && sid != null && sid.longValue() == serviceId)) {
- Integer ranking = (Integer) ref.getProperty(Constants.SERVICE_RANKING);
- int r = 0;
- if (ranking != null) {
- r = ranking.intValue();
- }
- if (r > max) {
- max = r;
- result = ref;
- }
- }
- }
- return result;
- }
- }
-
- private final HashMap m_highestTrackedCache = new HashMap();
-
- private ServiceReference highestTrackedCache(long serviceId) {
- Long sid = Long.valueOf(serviceId);
- synchronized (this) {
- TreeSet services = (TreeSet) m_highestTrackedCache.get(sid);
- if (services != null && services.size() > 0) {
- ServiceReference result = (ServiceReference) services.last();
- return result;
- }
- }
- return null;
- }
-
- private void addHighestTrackedCache(ServiceReference reference) {
- Long serviceId = ServiceUtil.getServiceIdObject(reference);
- synchronized (this) {
- TreeSet services = (TreeSet) m_highestTrackedCache.get(serviceId);
- if (services == null) {
- services = new TreeSet();
- m_highestTrackedCache.put(serviceId, services);
- }
- services.add(reference);
- }
- }
-
- private void removeHighestTrackedCache(ServiceReference reference) {
- Long serviceId = ServiceUtil.getServiceIdObject(reference);
- synchronized (this) {
- TreeSet services = (TreeSet) m_highestTrackedCache.get(serviceId);
- if (services != null) {
- services.remove(reference);
- }
- }
- }
-
- private void clearHighestTrackedCache() {
- synchronized (this) {
- m_highestTrackedCache.clear();
- }
- }
-
- private final HashMap m_highestHiddenCache = new HashMap();
-
- private ServiceReference highestHiddenCache(long serviceId) {
- Long sid = Long.valueOf(serviceId);
- synchronized (this) {
- TreeSet services = (TreeSet) m_highestHiddenCache.get(sid);
- if (services != null && services.size() > 0) {
- ServiceReference result = (ServiceReference) services.last();
- return result;
- }
- }
- return null;
- }
-
- private void addHighestHiddenCache(ServiceReference reference) {
- Long serviceId = ServiceUtil.getServiceIdObject(reference);
- synchronized (this) {
- TreeSet services = (TreeSet) m_highestHiddenCache.get(serviceId);
- if (services == null) {
- services = new TreeSet();
- m_highestHiddenCache.put(serviceId, services);
- }
- services.add(reference);
- }
- }
-
- private void removeHighestHiddenCache(ServiceReference reference) {
- Long serviceId = ServiceUtil.getServiceIdObject(reference);
- synchronized (this) {
- TreeSet services = (TreeSet) m_highestHiddenCache.get(serviceId);
- if (services != null) {
- services.remove(reference);
- }
- }
- }
-
- /**
- * Hide a service reference, placing it in the list of hidden services.
- *
- * @param ref the service reference to add to the hidden list
- */
- private void hide(ServiceReference ref) {
- addHighestHiddenCache(ref);
- }
-
- /**
- * Unhide a service reference, removing it from the list of hidden services.
- *
- * @param ref the service reference to remove from the hidden list
- */
- private void unhide(ServiceReference ref) {
- removeHighestHiddenCache(ref);
- }
-
- /**
- * Tracked constructor.
- */
- Tracked() {
- super();
- setTracked(new HashMapCache());
- }
-
- void setInitial(Object[] list) {
- if (list == null) {
- return;
- }
- if (m_trackAllAspects) {
- // not hiding aspects
- super.setInitial(list);
- } else {
- Map highestRankedServiceMap = new HashMap(); // <Long, RankedService>
- for (int i = 0; i < list.length; i++) {
- ServiceReference sr = (ServiceReference) list[i];
- if (sr != null) {
- Long serviceId = ServiceUtil.getServiceIdAsLong(sr);
- int ranking = ServiceUtil.getRanking(sr);
-
- RankedService rs = (RankedService) highestRankedServiceMap.get(serviceId);
- if (rs == null) {
- // the service did not exist yet in our map
- highestRankedServiceMap.put(serviceId, new RankedService(ranking, sr));
- }
- else if (ranking > rs.getRanking()) {
- // the service replaces a lower ranked one
- hide(rs.getServiceReference());
- rs.update(ranking, sr);
- }
- else {
- // the service does NOT replace a lower ranked one
- hide(sr);
- }
- }
- }
- if (highestRankedServiceMap.size() > 0) {
- Object[] result = new Object[highestRankedServiceMap.size()];
- int index = 0;
- for(Iterator it = highestRankedServiceMap.entrySet().iterator(); it.hasNext(); ) {
- Entry entry = (Entry) it.next();
- result[index] = ((RankedService)entry.getValue()).getServiceReference();
- index++;
- }
- super.setInitial(result);
- }
- }
- }
-
- /**
- * <code>ServiceListener</code> method for the
- * <code>ServiceTracker</code> class. This method must NOT be
- * synchronized to avoid deadlock potential.
- *
- * @param event <code>ServiceEvent</code> object from the framework.
- */
- public void serviceChanged(final ServiceEvent event) {
- if (m_trackAllAspects) {
- serviceChangedIncludeAspects(event);
- }
- else {
- serviceChangedHideAspects(event);
- }
- }
-
- public void serviceChangedIncludeAspects(final ServiceEvent event) {
- /*
- * Check if we had a delayed call (which could happen when we
- * close).
- */
- if (closed) {
- return;
- }
- final ServiceReference reference = event.getServiceReference();
- if (DEBUG) {
- System.out
- .println("ServiceTracker.Tracked.serviceChanged["
- + event.getType() + "]: " + reference);
- }
-
- switch (event.getType()) {
- case ServiceEvent.REGISTERED :
- case ServiceEvent.MODIFIED :
- if (listenerFilter != null) { // service listener added with
- // filter
- track(reference, event);
- /*
- * If the customizer throws an unchecked exception, it
- * is safe to let it propagate
- */
- }
- else { // service listener added without filter
- if (filter.match(reference)) {
- track(reference, event);
- /*
- * If the customizer throws an unchecked exception,
- * it is safe to let it propagate
- */
- }
- else {
- untrack(reference, event);
- /*
- * If the customizer throws an unchecked exception,
- * it is safe to let it propagate
- */
- }
- }
- break;
- case 8 /* ServiceEvent.MODIFIED_ENDMATCH */ :
- case ServiceEvent.UNREGISTERING :
- untrack(reference, event);
- /*
- * If the customizer throws an unchecked exception, it is
- * safe to let it propagate
- */
- break;
- }
- }
-
- public void serviceChangedHideAspects(final ServiceEvent event) {
- /*
- * Check if we had a delayed call (which could happen when we
- * close).
- */
- if (closed) {
- return;
- }
- final ServiceReference reference = event.getServiceReference();
- if (DEBUG) {
- System.out
- .println("ServiceTracker.Tracked.serviceChanged["
- + event.getType() + "]: " + reference);
- }
-
- long sid = ServiceUtil.getServiceId(reference);
- switch (event.getType()) {
- case ServiceEvent.REGISTERED :
- case ServiceEvent.MODIFIED :
- ServiceReference higher = null;
- ServiceReference lower = null;
- ServiceReference sr = highestTrackedCache(sid);
- if (sr != null) {
- int ranking = ServiceUtil.getRanking(reference);
- int trackedRanking = ServiceUtil.getRanking(sr);
- if (ranking > trackedRanking) {
- // found a higher ranked one!
- if (DEBUG) {
- System.out.println("ServiceTracker.Tracked.serviceChanged[" + event.getType() + "]: Found a higher ranked aspect: " + ServiceUtil.toString(reference) + " vs " + ServiceUtil.toString(sr));
- }
- higher = sr;
- }
- else if (ranking < trackedRanking) {
- // found lower ranked one!
- if (DEBUG) {
- System.out.println("ServiceTracker.Tracked.serviceChanged[" + event.getType() + "]: Found a lower ranked aspect: " + ServiceUtil.toString(reference) + " vs " + ServiceUtil.toString(sr));
- }
- lower = sr;
- }
- }
-
- if (listenerFilter != null) { // service listener added with filter
- if (lower != null) {
- hide(reference);
- }
- else {
- try {
- track(reference, event);
- }
- finally {
- if (higher != null) {
- try {
- untrack(higher, null);
- }
- finally {
- hide(higher);
- }
- }
- }
- }
- /*
- * If the customizer throws an unchecked exception, it
- * is safe to let it propagate
- */
- }
- else { // service listener added without filter
- if (filter.match(reference)) {
- if (lower != null) {
- hide(reference);
- }
- else {
- try {
- track(reference, event);
- }
- finally {
- if (higher != null) {
- try {
- untrack(higher, null);
- }
- finally {
- hide(higher);
- }
- }
- }
- }
- /*
- * If the customizer throws an unchecked exception,
- * it is safe to let it propagate
- */
- }
- else {
- ServiceReference ht = highestTrackedCache(sid);
- if (reference.equals(ht)) {
- try {
- ServiceReference hh = highestHiddenCache(sid);
- if (hh != null) {
- unhide(hh);
- track(hh, null);
- }
- }
- finally {
- untrack(reference, event);
- }
- }
- else {
- unhide(reference);
- }
- /*
- * If the customizer throws an unchecked exception,
- * it is safe to let it propagate
- */
- }
- }
- break;
- case 8 /* ServiceEvent.MODIFIED_ENDMATCH */ :
- case ServiceEvent.UNREGISTERING :
- ServiceReference ht = highestTrackedCache(sid);
- if (reference.equals(ht)) {
- try {
- ServiceReference hh = highestHiddenCache(sid);
- if (hh != null) {
- unhide(hh);
- track(hh, null);
- }
- }
- finally {
- untrack(reference, event);
- }
- }
- else {
- unhide(reference);
- }
- /*
- * If the customizer throws an unchecked exception, it is
- * safe to let it propagate
- */
- break;
- }
- }
-
- /**
- * Increment the tracking count and tell the tracker there was a
- * modification.
- *
- * @GuardedBy this
- */
- void modified() {
- super.modified(); /* increment the modification count */
- ServiceTracker.this.modified();
- }
-
- /**
- * Call the specific customizer adding method. This method must not be
- * called while synchronized on this object.
- *
- * @param item Item to be tracked.
- * @param related Action related object.
- * @return Customized object for the tracked item or <code>null</code>
- * if the item is not to be tracked.
- */
- Object customizerAdding(final Object item,
- final Object related) {
- return customizer.addingService((ServiceReference) item);
- }
-
- void customizerAdded(final Object item, final Object related, final Object object) {
- customizer.addedService((ServiceReference) item, object);
- }
-
- /**
- * Call the specific customizer modified method. This method must not be
- * called while synchronized on this object.
- *
- * @param item Tracked item.
- * @param related Action related object.
- * @param object Customized object for the tracked item.
- */
- void customizerModified(final Object item,
- final Object related, final Object object) {
- customizer.modifiedService((ServiceReference) item, object);
- }
-
- /**
- * Call the specific customizer removed method. This method must not be
- * called while synchronized on this object.
- *
- * @param item Tracked item.
- * @param related Action related object.
- * @param object Customized object for the tracked item.
- */
- void customizerRemoved(final Object item,
- final Object related, final Object object) {
- customizer.removedService((ServiceReference) item, object);
- }
-
- class HashMapCache extends LinkedHashMap {
- public Object put(Object key, Object value) {
- addHighestTrackedCache((ServiceReference) key);
- return super.put(key, value);
- }
-
- public void putAll(Map m) {
- Iterator i = m.keySet().iterator();
- while (i.hasNext()) {
- addHighestTrackedCache((ServiceReference) i.next());
- }
- super.putAll(m);
- }
-
- public Object remove(Object key) {
- removeHighestTrackedCache((ServiceReference) key);
- return super.remove(key);
- }
-
- public void clear() {
- clearHighestTrackedCache();
- super.clear();
- }
- }
- }
-
- /**
- * Subclass of Tracked which implements the AllServiceListener interface.
- * This class is used by the ServiceTracker if open is called with true.
- *
- * @since 1.3
- * @ThreadSafe
- */
- class AllTracked extends Tracked implements AllServiceListener {
- /**
- * AllTracked constructor.
- */
- AllTracked() {
- super();
- setTracked(new HashMapCache());
- }
- }
-
- /**
- * Holds a ranking and a service reference that can be updated if necessary.
- */
- private static final class RankedService {
- private int m_ranking;
- private ServiceReference m_serviceReference;
-
- public RankedService(int ranking, ServiceReference serviceReference) {
- m_ranking = ranking;
- m_serviceReference = serviceReference;
- }
-
- public void update(int ranking, ServiceReference serviceReference) {
- m_ranking = ranking;
- m_serviceReference = serviceReference;
- }
-
- public int getRanking() {
- return m_ranking;
- }
-
- public ServiceReference getServiceReference() {
- return m_serviceReference;
- }
- }
-}
diff --git a/dependencymanager/core/src/main/java/org/apache/felix/dm/tracker/ServiceTrackerCustomizer.java b/dependencymanager/core/src/main/java/org/apache/felix/dm/tracker/ServiceTrackerCustomizer.java
deleted file mode 100644
index 857e34a..0000000
--- a/dependencymanager/core/src/main/java/org/apache/felix/dm/tracker/ServiceTrackerCustomizer.java
+++ /dev/null
@@ -1,96 +0,0 @@
-package org.apache.felix.dm.tracker;
-/*
- * Copyright (c) OSGi Alliance (2000, 2008). All Rights Reserved.
- *
- * 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.
- */
-
-import org.osgi.framework.ServiceReference;
-
-/**
- * The <code>ServiceTrackerCustomizer</code> interface allows a
- * <code>ServiceTracker</code> to customize the service objects that are
- * tracked. A <code>ServiceTrackerCustomizer</code> is called when a service is
- * being added to a <code>ServiceTracker</code>. The
- * <code>ServiceTrackerCustomizer</code> can then return an object for the
- * tracked service. A <code>ServiceTrackerCustomizer</code> is also called when
- * a tracked service is modified or has been removed from a
- * <code>ServiceTracker</code>.
- *
- * <p>
- * The methods in this interface may be called as the result of a
- * <code>ServiceEvent</code> being received by a <code>ServiceTracker</code>.
- * Since <code>ServiceEvent</code>s are synchronously delivered by the
- * Framework, it is highly recommended that implementations of these methods do
- * not register (<code>BundleContext.registerService</code>), modify (
- * <code>ServiceRegistration.setProperties</code>) or unregister (
- * <code>ServiceRegistration.unregister</code>) a service while being
- * synchronized on any object.
- *
- * <p>
- * The <code>ServiceTracker</code> class is thread-safe. It does not call a
- * <code>ServiceTrackerCustomizer</code> while holding any locks.
- * <code>ServiceTrackerCustomizer</code> implementations must also be
- * thread-safe.
- *
- * @ThreadSafe
- * @version $Revision: 5874 $
- */
-public interface ServiceTrackerCustomizer {
- /**
- * A service is being added to the <code>ServiceTracker</code>.
- *
- * <p>
- * This method is called before a service which matched the search
- * parameters of the <code>ServiceTracker</code> is added to the
- * <code>ServiceTracker</code>. This method should return the service object
- * to be tracked for the specified <code>ServiceReference</code>. The
- * returned service object is stored in the <code>ServiceTracker</code> and
- * is available from the <code>getService</code> and
- * <code>getServices</code> methods.
- *
- * @param reference The reference to the service being added to the
- * <code>ServiceTracker</code>.
- * @return The service object to be tracked for the specified referenced
- * service or <code>null</code> if the specified referenced service
- * should not be tracked.
- */
- public Object addingService(ServiceReference reference);
-
- /** marrs: A service has been added to the ServiceTracker. */
- public void addedService(ServiceReference reference, Object service);
-
- /**
- * A service tracked by the <code>ServiceTracker</code> has been modified.
- *
- * <p>
- * This method is called when a service being tracked by the
- * <code>ServiceTracker</code> has had it properties modified.
- *
- * @param reference The reference to the service that has been modified.
- * @param service The service object for the specified referenced service.
- */
- public void modifiedService(ServiceReference reference, Object service);
-
- /**
- * A service tracked by the <code>ServiceTracker</code> has been removed.
- *
- * <p>
- * This method is called after a service is no longer being tracked by the
- * <code>ServiceTracker</code>.
- *
- * @param reference The reference to the service that has been removed.
- * @param service The service object for the specified referenced service.
- */
- public void removedService(ServiceReference reference, Object service);
-}
diff --git a/dependencymanager/pom.xml b/dependencymanager/pom.xml
deleted file mode 100644
index 446d8ca..0000000
--- a/dependencymanager/pom.xml
+++ /dev/null
@@ -1,61 +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/maven-v4_0_0.xsd">
- <modelVersion>4.0.0</modelVersion>
- <packaging>pom</packaging>
- <parent>
- <groupId>org.apache.felix</groupId>
- <artifactId>felix-parent</artifactId>
- <version>1.2.0</version>
- <relativePath>../pom/pom.xml</relativePath>
- </parent>
- <name>Apache Felix Dependency Manager Projects</name>
- <artifactId>dependencymanager-reactor</artifactId>
- <version>3.0.0-SNAPSHOT</version>
- <licenses>
- <license>
- <name>Apache License, Version 2.0</name>
- <url>http://www.apache.org/licenses/LICENSE-2.0.txt</url>
- <distribution>repo</distribution>
- </license>
- </licenses>
- <modules>
- <module>core</module>
- <module>shell</module>
- <module>compat</module>
- <module>annotation</module>
- <module>runtime</module>
- <module>samples</module>
- <module>samples.annotation</module>
- <module>test</module>
- </modules>
- <repositories>
- <repository>
- <id>maven2-repository.dev.java.net</id>
- <name>Java.net Maven 2 Repository</name>
- <url>http://download.java.net/maven/2</url>
- </repository>
- </repositories>
- <scm>
- <connection>scm:svn:http://svn.apache.org/repos/asf/felix/trunk/dependencymanager/</connection>
- <developerConnection>scm:svn:https://svn.apache.org/repos/asf/felix/trunk/dependencymanager/</developerConnection>
- <url>http://svn.apache.org/viewvc/felix/trunk/dependencymanager/</url>
- </scm>
-</project>
diff --git a/dependencymanager/runtime/DEPENDENCIES b/dependencymanager/runtime/DEPENDENCIES
deleted file mode 100644
index d8a62db..0000000
--- a/dependencymanager/runtime/DEPENDENCIES
+++ /dev/null
@@ -1,24 +0,0 @@
-Apache Felix Dependency Manager Runtime
-Copyright 2011-2014 The Apache Software Foundation
-
-This software was developed at the Apache Software Foundation
-(http://www.apache.org) and may have dependencies on other
-Apache software licensed under Apache License 2.0.
-
-I. Included Third-Party Software
-
-This product includes software from http://www.json.org.
-Copyright (c) 2002 JSON.org
-Licensed under the JSON License
-
-II. Used Third-Party Software
-
-This product uses software developed at
-The OSGi Alliance (http://www.osgi.org/).
-Copyright (c) OSGi Alliance (2000, 2014).
-Licensed under the Apache License 2.0.
-
-III. Overall License Summary
-
-- Apache License 2.0
-- JSON License
diff --git a/dependencymanager/runtime/LICENSE b/dependencymanager/runtime/LICENSE
deleted file mode 100644
index d645695..0000000
--- a/dependencymanager/runtime/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/dependencymanager/runtime/LICENSE.json b/dependencymanager/runtime/LICENSE.json
deleted file mode 100644
index 68d19c8..0000000
--- a/dependencymanager/runtime/LICENSE.json
+++ /dev/null
@@ -1,21 +0,0 @@
-Copyright (c) 2002 JSON.org
-
-Permission is hereby granted, free of charge, to any person obtaining a copy
-of this software and associated documentation files (the "Software"), to deal
-in the Software without restriction, including without limitation the rights
-to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
-copies of the Software, and to permit persons to whom the Software is
-furnished to do so, subject to the following conditions:
-
-The above copyright notice and this permission notice shall be included in
-all copies or substantial portions of the Software.
-
-The Software shall be used for Good, not Evil.
-
-THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
-IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
-FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
-AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
-LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
-OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
-SOFTWARE.
\ No newline at end of file
diff --git a/dependencymanager/runtime/NOTICE b/dependencymanager/runtime/NOTICE
deleted file mode 100644
index a988034..0000000
--- a/dependencymanager/runtime/NOTICE
+++ /dev/null
@@ -1,10 +0,0 @@
-Apache Felix Dependency Manager Runtime
-Copyright 2011-2014 The Apache Software Foundation
-
-This product includes software developed at
-The Apache Software Foundation (http://www.apache.org/).
-Licensed under the Apache License 2.0.
-
-This product includes software from http://www.json.org.
-Copyright (c) 2002 JSON.org
-Licensed under the JSON License
diff --git a/dependencymanager/runtime/doc/changelog.txt b/dependencymanager/runtime/doc/changelog.txt
deleted file mode 100644
index 3e87fea..0000000
--- a/dependencymanager/runtime/doc/changelog.txt
+++ /dev/null
@@ -1,29 +0,0 @@
-Release 3.2.0
--------------
-
-** Bug
- * [FELIX-4050] Named dependencies are not injected if new dependencies are added at init phase.
- * [FELIX-4233] Race condition in dependency manager runtime SerialExecutor.
-
-** Improvement
- * [FELIX-3869] - Fragment support for DependencyManager-Component
- * [FELIX-4357] - Support types beside String/String[] in @Property annotation.
-
-Release 3.1.0
--------------
-
-** Bug
-
-** Improvement
- * Removed root changelog.txt
- * [FELIX-2954] - annotated component factory does not allow to provide a component instance explicitly
- * [FELIX-2966] - Annotations should automatically generate Import-Service/Export-Service headers
- * [FELIX-2965] - Annotations should allow to enable or disable auto-configuration mode.
- * [FELIX-3866] - Added support for swap attribute in AspectService and AdpaterService annotations.
-
-Initial Release 3.0.0
----------------------
-
-** Bug
-
-** Improvement
diff --git a/dependencymanager/runtime/findbugs.xml b/dependencymanager/runtime/findbugs.xml
deleted file mode 100644
index 10368c3..0000000
--- a/dependencymanager/runtime/findbugs.xml
+++ /dev/null
@@ -1,13 +0,0 @@
-<FindBugsFilter>
- <!--
- The m_logService field of the Log" class is injected by the Activator.
- -->
- <Match>
- <Class name="org.apache.felix.dm.runtime.Log" />
- <Bug pattern="UWF_UNWRITTEN_FIELD" />
- </Match>
- <Match>
- <Class name="org.apache.felix.dm.runtime.Log" />
- <Bug pattern="NP_UNWRITTEN_FIELD" />
- </Match>
-</FindBugsFilter>
diff --git a/dependencymanager/runtime/pom.xml b/dependencymanager/runtime/pom.xml
deleted file mode 100644
index fffe677..0000000
--- a/dependencymanager/runtime/pom.xml
+++ /dev/null
@@ -1,113 +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/maven-v4_0_0.xsd">
- <modelVersion>4.0.0</modelVersion>
- <parent>
- <groupId>org.apache.felix</groupId>
- <artifactId>felix-parent</artifactId>
- <version>1.2.0</version>
- <relativePath>../../pom/pom.xml</relativePath>
- </parent>
- <properties>
- <osgi.version>4.2.0</osgi.version>
- </properties>
- <name>Apache Felix Dependency Manager Runtime</name>
- <artifactId>org.apache.felix.dependencymanager.runtime</artifactId>
- <version>3.2.1-SNAPSHOT</version>
- <packaging>bundle</packaging>
-
- <scm>
- <connection>scm:svn:http://svn.apache.org/repos/asf/felix/trunk/dependencymanager/runtime</connection>
- <developerConnection>scm:svn:https://svn.apache.org/repos/asf/felix/trunk/dependencymanager/runtime</developerConnection>
- <url>http://svn.apache.org/repos/asf/felix/dependencymanager/runtime</url>
- </scm>
-
- <dependencies>
- <dependency>
- <groupId>org.osgi</groupId>
- <artifactId>org.osgi.core</artifactId>
- <version>${osgi.version}</version>
- </dependency>
- <dependency>
- <groupId>org.osgi</groupId>
- <artifactId>org.osgi.compendium</artifactId>
- <version>${osgi.version}</version>
- </dependency>
- <dependency>
- <groupId>${pom.groupId}</groupId>
- <artifactId>org.apache.felix.dependencymanager</artifactId>
- <version>3.2.1-SNAPSHOT</version>
- </dependency>
- <dependency>
- <groupId>org.json</groupId>
- <artifactId>json</artifactId>
- <scope>provided</scope>
- <version>20070829</version>
- </dependency>
- </dependencies>
- <build>
- <resources>
- <resource>
- <directory>.</directory>
- <targetPath>META-INF</targetPath>
- <includes>
- <include>LICENSE*</include>
- <include>NOTICE*</include>
- <include>DEPENDENCIES*</include>
- <include>*.txt</include>
- </includes>
- </resource>
- </resources>
- <pluginManagement>
- <plugins>
- <plugin>
- <groupId>org.apache.felix</groupId>
- <artifactId>maven-bundle-plugin</artifactId>
- <version>2.3.4</version>
- <extensions>true</extensions>
- </plugin>
- </plugins>
- </pluginManagement>
- <plugins>
- <plugin>
- <groupId>org.apache.maven.plugins</groupId>
- <artifactId>maven-compiler-plugin</artifactId>
- <configuration>
- <source>1.5</source>
- <target>1.5</target>
- </configuration>
- </plugin>
- <plugin>
- <groupId>org.apache.felix</groupId>
- <artifactId>maven-bundle-plugin</artifactId>
- <configuration>
- <instructions>
- <Bundle-SymbolicName>org.apache.felix.dependencymanager.runtime</Bundle-SymbolicName>
- <Bundle-Name>Apache Felix Dependency Manager Runtime</Bundle-Name>
- <Bundle-Description>Loads component descriptors from active bundles.</Bundle-Description>
- <Bundle-Vendor>The Apache Software Foundation</Bundle-Vendor>
- <Private-Package>org.apache.felix.dm.runtime</Private-Package>
- <Import-Package>*</Import-Package>
- <Export-Package />
- <Embed-Dependency>json;inline=org/json/**</Embed-Dependency>
- <Bundle-Activator>org.apache.felix.dm.runtime.Activator</Bundle-Activator>
- </instructions>
- </configuration>
- </plugin>
- </plugins>
- </build>
-</project>
diff --git a/dependencymanager/runtime/src/main/java/org/apache/felix/dm/runtime/AbstractBuilder.java b/dependencymanager/runtime/src/main/java/org/apache/felix/dm/runtime/AbstractBuilder.java
deleted file mode 100644
index 9fbb616..0000000
--- a/dependencymanager/runtime/src/main/java/org/apache/felix/dm/runtime/AbstractBuilder.java
+++ /dev/null
@@ -1,194 +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.felix.dm.runtime;
-
-import java.lang.reflect.InvocationTargetException;
-import java.util.List;
-
-import org.apache.felix.dm.Component;
-import org.apache.felix.dm.ComponentStateListener;
-import org.apache.felix.dm.Dependency;
-import org.apache.felix.dm.DependencyManager;
-import org.osgi.framework.Bundle;
-import org.osgi.framework.BundleContext;
-import org.osgi.framework.ServiceRegistration;
-
-/**
- * Base class for all kind of DM component builders (for Component, Aspect, Adapters ...).
- *
- * @author <a href="mailto:dev@felix.apache.org">Felix Project Team</a>
- */
-public abstract class AbstractBuilder
-{
- /**
- * Returns the service component type.
- */
- abstract String getType();
-
- /**
- * Builds the service component.
- * @param serviceMetaData the service component metadata parsed from the descriptor file.
- * @param serviceDependencies the service component dependencies metadata parsed from the descriptor file.
- */
- abstract void build(MetaData serviceMetaData, List<MetaData> serviceDependencies, Bundle b,
- DependencyManager dm)
- throws Exception;
-
- /**
- * Sets common Service parameters, if provided from our Component descriptor
- */
- protected void setCommonServiceParams(Component c, MetaData srvMeta)
- throws Exception
- {
- // Set auto configured component fields.
- DependencyManager dm = c.getDependencyManager();
- boolean autoConfigureComponents =
- "true".equals(dm.getBundleContext().getProperty(Activator.CONF_ENABLE_AUTOCONFIG));
-
- if (!autoConfigureComponents)
- {
- c.setAutoConfig(BundleContext.class, Boolean.FALSE);
- c.setAutoConfig(ServiceRegistration.class, Boolean.FALSE);
- c.setAutoConfig(DependencyManager.class, Boolean.FALSE);
- c.setAutoConfig(Component.class, Boolean.FALSE);
- }
-
- // See if BundleContext must be auto configured.
- String bundleContextField = srvMeta.getString(Params.bundleContextField, null);
- if (bundleContextField != null)
- {
- c.setAutoConfig(BundleContext.class, bundleContextField);
- }
-
- // See if DependencyManager must be auto configured.
- String dependencyManagerField = srvMeta.getString(Params.dependencyManagerField, null);
- if (dependencyManagerField != null)
- {
- c.setAutoConfig(DependencyManager.class, dependencyManagerField);
- }
-
- // See if Component must be auto configured.
- String componentField = srvMeta.getString(Params.componentField, null);
- if (componentField != null)
- {
- c.setAutoConfig(Component.class, componentField);
- }
-
- // Now, if the component has a @Started annotation, then add our component state listener,
- // which will callback the corresponding annotated method, once the component is started.
- String registered = srvMeta.getString(Params.registered, null);
- String unregistered = srvMeta.getString(Params.unregistered, null);
-
- if (registered != null || unregistered != null)
- {
- c.addStateListener(new RegistrationListener(registered, unregistered));
- }
- }
-
- /**
- * Registers all unnamed dependencies into a given service. Named dependencies are
- * handled differently, and are managed by the ServiceLifecycleHandler class.
- * @throws Exception
- */
- protected static void addUnamedDependencies(Bundle b, DependencyManager dm, Component s,
- MetaData srvMeta, List<MetaData> depsMeta)
- throws Exception
- {
- for (MetaData dependency : depsMeta)
- {
- String name = dependency.getString(Params.name, null);
- if (name == null) {
- DependencyBuilder depBuilder = new DependencyBuilder(dependency);
- Log.instance().info("adding dependency %s into service %s",
- dependency, srvMeta);
- Dependency d = depBuilder.build(b, dm, false);
- s.add(d);
- }
- }
- }
-
- static class RegistrationListener implements ComponentStateListener
- {
- private final String m_registered;
- private String m_unregistered;
-
- RegistrationListener(String registered, String unregistered)
- {
- m_registered = registered;
- m_unregistered = unregistered;
- }
-
- public void starting(Component c)
- {
- // No need to invoke any callback here, since it is the ServiceLifecycleHandler
- // that will invoke the method annotated with @Start
- }
-
- public void started(Component c)
- {
- if (m_registered != null)
- {
- // The component has registered a service: notify all component instances
- Object[] componentInstances = c.getCompositionInstances();
- for (Object instance : componentInstances)
- {
- try
- {
- Class[][] signatures = new Class[][] { { ServiceRegistration.class }, {} };
- Object[][] params = new Object[][] { { c.getServiceRegistration() }, {} };
- InvocationUtil.invokeCallbackMethod(instance, m_registered, signatures, params);
- }
- catch (Throwable t)
- {
- Log.instance().error("Exception caught while invoking method %s on component %s",
- t,
- m_registered,
- instance);
- }
- }
- }
- }
-
- public void stopping(Component c)
- {
- // No need to invoke any callback here, since it is the ServiceLifecycleHandler
- // that will invoke the method annotated with @Stop
- }
-
- public void stopped(Component c)
- {
- if (m_unregistered != null)
- {
- Object instance = c.getService();
- try
- {
- InvocationUtil
- .invokeCallbackMethod(instance,
- m_unregistered,
- new Class[][] {{}},
- new Object[][] {{}});
- }
- catch (Throwable t)
- {
- Log.instance().error("Exception caught while invoking method %s on component %s", t, m_registered, instance);
- }
- }
- }
- }
-}
diff --git a/dependencymanager/runtime/src/main/java/org/apache/felix/dm/runtime/Activator.java b/dependencymanager/runtime/src/main/java/org/apache/felix/dm/runtime/Activator.java
deleted file mode 100644
index 18a3499..0000000
--- a/dependencymanager/runtime/src/main/java/org/apache/felix/dm/runtime/Activator.java
+++ /dev/null
@@ -1,111 +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.felix.dm.runtime;
-
-import java.util.HashMap;
-import java.util.Map;
-
-import org.apache.felix.dm.Component;
-import org.apache.felix.dm.DependencyActivatorBase;
-import org.apache.felix.dm.DependencyManager;
-import org.apache.felix.dm.ServiceDependency;
-import org.osgi.framework.Bundle;
-import org.osgi.framework.BundleContext;
-import org.osgi.service.log.LogService;
-import org.osgi.service.packageadmin.PackageAdmin;
-
-/*
- * This is the Activator for our DependencyManager Component Runtime.
- * Here, we'll track started/stopped bundles which have some DependencyManager
- * descriptors (META-INF/dependencymanager/*.dm). Such descriptors are generated
- * by the Bnd plugin which parses DependencyManager annotations at compile time.
- *
- * @author <a href="mailto:dev@felix.apache.org">Felix Project Team</a>
- */
-public class Activator extends DependencyActivatorBase
-{
- /**
- * Name of bundle context property telling if log service is required or not.
- * (default = false)
- */
- final static String CONF_LOG = "dm.runtime.log";
-
- /**
- * Name of bundle context property telling if PackageAdmin service is required or not.
- * (default = false)
- */
- private final static String CONF_PACKAGE_ADMIN = "dm.runtime.packageAdmin";
-
- /**
- * Name of bundle context property telling if Components must be auto configured
- * with BundleContext/ServiceRegistration etc .. (default = false)
- */
- final static String CONF_ENABLE_AUTOCONFIG = "dm.runtime.autoconfig";
-
- /**
- * Initialize our DependencyManager Runtime service.
- *
- * We depend on the OSGi LogService, and we track all started bundles which do have a
- * "DependencyManager-Component" Manifest header.
- * If the "dm.runtime.log=true" or "dm.runtime.packageAdmin=true" parameter is configured in the Felix config.properties
- * then we'll use a required/temporal service dependency over the respective service.
- * These temporal dependencies avoid us to be restarted if the respective service is temporarily
- * unavailable (that is: when the service is updating).
- * if the "dm.runtime.log" or "dm.runtime.packageAdmin" is not configured or it it is set to false, then we'll use
- * an optional dependency over the respective service, in order to use a NullObject in case
- * the service is not available.
- */
- @Override
- public void init(BundleContext context, DependencyManager dm) throws Exception
- {
- Component component = createComponent()
- .setImplementation( DependencyManagerRuntime.class )
- .setComposition( "getComposition" )
- .add(createBundleDependency()
- .setRequired( false )
- .setAutoConfig( false )
- .setStateMask( Bundle.ACTIVE )
- .setFilter( "(DependencyManager-Component=*)" )
- .setCallbacks( "bundleStarted", "bundleStopped" ) );
-
- Map<String, Class<?>> services = new HashMap<String, Class<?>>( 2 );
- services.put( CONF_LOG, LogService.class );
- services.put( CONF_PACKAGE_ADMIN, PackageAdmin.class );
- for (Map.Entry<String, Class<?>> entry : services.entrySet())
- {
- String serviceProperty = entry.getKey();
- Class<?> service = entry.getValue();
- boolean serviceActive = "true".equalsIgnoreCase(context.getProperty(serviceProperty));
- ServiceDependency serviceDep =
- serviceActive ? createTemporalServiceDependency()
- : createServiceDependency().setRequired(false);
- serviceDep.setService(service).setAutoConfig(true);
- component.add(serviceDep);
- }
- dm.add( component );
- }
-
- /**
- * Our bundle is stopping: shutdown our Dependency Manager Runtime service.
- */
- @Override
- public void destroy(BundleContext context, DependencyManager dm) throws Exception
- {
- }
-}
diff --git a/dependencymanager/runtime/src/main/java/org/apache/felix/dm/runtime/AdapterServiceBuilder.java b/dependencymanager/runtime/src/main/java/org/apache/felix/dm/runtime/AdapterServiceBuilder.java
deleted file mode 100644
index e869e12..0000000
--- a/dependencymanager/runtime/src/main/java/org/apache/felix/dm/runtime/AdapterServiceBuilder.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.felix.dm.runtime;
-
-import java.util.Dictionary;
-import java.util.List;
-
-import org.apache.felix.dm.Component;
-import org.apache.felix.dm.DependencyManager;
-import org.osgi.framework.Bundle;
-
-/**
- * Builded called when the JSON parser find an adapter service descriptor.
- *
- * @author <a href="mailto:dev@felix.apache.org">Felix Project Team</a>
- */
-public class AdapterServiceBuilder extends AbstractBuilder
-{
- /** The type attribute specified in the JSON descriptor */
- private final static String TYPE = "AdapterService";
-
- @Override
- public String getType()
- {
- return TYPE;
- }
-
- @Override
- public void build(MetaData srvMeta, List<MetaData> depsMeta, Bundle b, DependencyManager dm)
- throws Exception
- {
- Class<?> adapterImplClass = b.loadClass(srvMeta.getString(Params.impl));
- String[] provides = srvMeta.getStrings(Params.provides, null);
- Dictionary<String, Object> adapterProperties = srvMeta.getDictionary(Params.properties, null);
- Class<?> adapteeService = b.loadClass(srvMeta.getString(Params.adapteeService));
- String adapteeFilter = srvMeta.getString(Params.adapteeFilter, null);
- String field = srvMeta.getString(Params.field, null);
- String added = srvMeta.getString(Params.added, null);
- String changed = srvMeta.getString(Params.changed, null);
- String removed = srvMeta.getString(Params.removed, null);
- String swap = srvMeta.getString(Params.swap, null);
-
- if (field != null && (added != null || changed != null || removed != null || swap != null))
- {
- throw new IllegalArgumentException("autoconfig field " + field + " can't be defined with both added/changed/removed/swap calllbacks");
- }
-
- Component c;
-
- if (field != null)
- {
- c = dm.createAdapterService(adapteeService, adapteeFilter, field);
- }
- else
- {
- if (added != null || changed != null || removed != null || swap != null)
- {
- c = dm.createAdapterService(adapteeService, adapteeFilter, added, changed, removed, swap);
-
- }
- else
- {
- c = dm.createAdapterService(adapteeService, adapteeFilter);
- }
- }
-
- setCommonServiceParams(c, srvMeta);
- c.setInterface(provides, adapterProperties);
-
- String factoryMethod = srvMeta.getString(Params.factoryMethod, null);
- if (factoryMethod == null)
- {
- c.setImplementation(adapterImplClass);
- }
- else
- {
- c.setFactory(adapterImplClass, factoryMethod);
- }
- c.setComposition(srvMeta.getString(Params.composition, null));
- ServiceLifecycleHandler lfcleHandler = new ServiceLifecycleHandler(c, b, dm, srvMeta, depsMeta);
- // The dependencies will be plugged by our lifecycle handler.
- c.setCallbacks(lfcleHandler, "init", "start", "stop", "destroy");
- // Adds dependencies (except named dependencies, which are managed by the lifecycle handler).
- addUnamedDependencies(b, dm, c, srvMeta, depsMeta);
- dm.add(c);
- }
-}
diff --git a/dependencymanager/runtime/src/main/java/org/apache/felix/dm/runtime/AspectServiceBuilder.java b/dependencymanager/runtime/src/main/java/org/apache/felix/dm/runtime/AspectServiceBuilder.java
deleted file mode 100644
index 46273ef..0000000
--- a/dependencymanager/runtime/src/main/java/org/apache/felix/dm/runtime/AspectServiceBuilder.java
+++ /dev/null
@@ -1,110 +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.felix.dm.runtime;
-
-import java.util.Dictionary;
-import java.util.List;
-
-import org.apache.felix.dm.Component;
-import org.apache.felix.dm.DependencyManager;
-import org.osgi.framework.Bundle;
-
-/**
- * Class used to build an aspect service using metadata found from DependencyManager runtime
- * meta-inf descriptor.
- *
- * @author <a href="mailto:dev@felix.apache.org">Felix Project Team</a>
- */
-public class AspectServiceBuilder extends AbstractBuilder
-{
- private final static String TYPE = "AspectService";
-
- @Override
- public String getType()
- {
- return TYPE;
- }
-
- @Override
- public void build(MetaData srvMeta, List<MetaData> depsMeta, Bundle b, DependencyManager dm)
- throws Exception
- {
- Log.instance().info("AspectServiceBuilder: building aspect service: %s with dependencies %s",
- srvMeta,
- depsMeta);
-
- Class<?> serviceInterface = b.loadClass(srvMeta.getString(Params.service));
- String serviceFilter = srvMeta.getString(Params.filter, null);
- Dictionary<String, Object> aspectProperties = srvMeta.getDictionary(Params.properties, null);
- int ranking = srvMeta.getInt(Params.ranking, 1);
- String implClassName = srvMeta.getString(Params.impl);
- Object implClass = b.loadClass(implClassName);
- String field = srvMeta.getString(Params.field, null);
- String added = srvMeta.getString(Params.added, null);
- String changed = srvMeta.getString(Params.changed, null);
- String removed = srvMeta.getString(Params.removed, null);
- String swap = srvMeta.getString(Params.swap, null);
-
- if (field != null && (added != null || changed != null || removed != null || swap != null))
- {
- throw new IllegalArgumentException("autoconfig field " + field + " can't be defined with both added/changed/removed/swap calllbacks");
- }
-
- Component c;
- if (field != null)
- {
- c = dm.createAspectService(serviceInterface, serviceFilter, ranking, field)
- .setServiceProperties(aspectProperties);
- }
- else
- {
- if (added != null || changed != null || removed != null || swap != null)
- {
- c = dm.createAspectService(serviceInterface, serviceFilter, ranking, added, changed, removed, swap)
- .setServiceProperties(aspectProperties);
- }
- else
- {
- c = dm.createAspectService(serviceInterface, serviceFilter, ranking)
- .setServiceProperties(aspectProperties);
- }
-
- }
-
- setCommonServiceParams(c, srvMeta);
- String factoryMethod = srvMeta.getString(Params.factoryMethod, null);
- if (factoryMethod == null)
- {
- c.setImplementation(implClass);
- }
- else
- {
- c.setFactory(implClass, factoryMethod);
- }
-
- c.setComposition(srvMeta.getString(Params.composition, null));
- ServiceLifecycleHandler lfcleHandler = new ServiceLifecycleHandler(c, b, dm, srvMeta, depsMeta);
- // The dependencies will be plugged by our lifecycle handler.
- c.setCallbacks(lfcleHandler, "init", "start", "stop", "destroy");
- // Adds dependencies (except named dependencies, which are managed by the lifecycle
- // handler).
- addUnamedDependencies(b, dm, c, srvMeta, depsMeta);
- dm.add(c);
- }
-}
diff --git a/dependencymanager/runtime/src/main/java/org/apache/felix/dm/runtime/BundleAdapterServiceBuilder.java b/dependencymanager/runtime/src/main/java/org/apache/felix/dm/runtime/BundleAdapterServiceBuilder.java
deleted file mode 100644
index 94f8e62..0000000
--- a/dependencymanager/runtime/src/main/java/org/apache/felix/dm/runtime/BundleAdapterServiceBuilder.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.felix.dm.runtime;
-
-import java.util.Dictionary;
-import java.util.List;
-
-import org.apache.felix.dm.Component;
-import org.apache.felix.dm.DependencyManager;
-import org.osgi.framework.Bundle;
-
-/**
- * Class used to build a bundle adapter service using metadata found from DependencyManager runtime
- * meta-inf descriptor.
- *
- * @author <a href="mailto:dev@felix.apache.org">Felix Project Team</a>
- */
-public class BundleAdapterServiceBuilder extends AbstractBuilder
-{
- private final static String TYPE = "BundleAdapterService";
-
- @Override
- public String getType()
- {
- return TYPE;
- }
-
- @Override
- public void build(MetaData srvMeta, List<MetaData> depsMeta, Bundle b, DependencyManager dm)
- throws Exception
- {
- int stateMask = srvMeta.getInt(Params.stateMask, Bundle.INSTALLED | Bundle.RESOLVED | Bundle.ACTIVE);
- String filter = srvMeta.getString(Params.filter, null);
- Class<?> adapterImplClass = b.loadClass(srvMeta.getString(Params.impl));
- String[] provides = srvMeta.getStrings(Params.provides, null);
- Dictionary<String, Object> properties = srvMeta.getDictionary(Params.properties, null);
- boolean propagate = "true".equals(srvMeta.getString(Params.propagate, "false"));
- Component c = dm.createBundleAdapterService(stateMask, filter, propagate);
- c.setInterface(provides, properties);
- String factoryMethod = srvMeta.getString(Params.factoryMethod, null);
- if (factoryMethod == null)
- {
- c.setImplementation(adapterImplClass);
- }
- else
- {
- c.setFactory(adapterImplClass, factoryMethod);
- }
-
- setCommonServiceParams(c, srvMeta);
- c.setComposition(srvMeta.getString(Params.composition, null));
- ServiceLifecycleHandler lfcleHandler = new ServiceLifecycleHandler(c, b, dm, srvMeta, depsMeta);
- // The dependencies will be plugged by our lifecycle handler.
- c.setCallbacks(lfcleHandler, "init", "start", "stop", "destroy");
- // Adds dependencies (except named dependencies, which are managed by the lifecycle handler).
- addUnamedDependencies(b, dm, c, srvMeta, depsMeta);
- dm.add(c);
- }
-}
diff --git a/dependencymanager/runtime/src/main/java/org/apache/felix/dm/runtime/ComponentBuilder.java b/dependencymanager/runtime/src/main/java/org/apache/felix/dm/runtime/ComponentBuilder.java
deleted file mode 100644
index aa0d60f..0000000
--- a/dependencymanager/runtime/src/main/java/org/apache/felix/dm/runtime/ComponentBuilder.java
+++ /dev/null
@@ -1,111 +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.felix.dm.runtime;
-
-import java.util.Dictionary;
-import java.util.Hashtable;
-import java.util.List;
-import java.util.Set;
-
-import org.apache.felix.dm.Component;
-import org.apache.felix.dm.DependencyManager;
-import org.osgi.framework.Bundle;
-import org.osgi.framework.BundleContext;
-import org.osgi.framework.ServiceRegistration;
-
-/**
- * Builds a DependencyManager Component.
- *
- * @author <a href="mailto:dev@felix.apache.org">Felix Project Team</a>
- */
-public class ComponentBuilder extends AbstractBuilder
-{
- private final static String TYPE = "Component";
- private final static String DM_FACTORY_NAME = "dm.factory.name";
-
- @Override
- public String getType()
- {
- return TYPE;
- }
-
- @Override
- public void build(MetaData srvMeta, List<MetaData> depsMeta, Bundle b, DependencyManager dm)
- throws Exception
- {
- Component c = dm.createComponent();
- String factory = srvMeta.getString(Params.factorySet, null);
-
- // Setup Component auto config fields
- setCommonServiceParams(c, srvMeta);
-
- // Check if we must provide a Component factory set.
- if (factory == null)
- {
- Log.instance().info("ComponentBuilder: building service %s with dependencies %s",
- srvMeta,
- depsMeta);
-
- String impl = srvMeta.getString(Params.impl);
- String composition = srvMeta.getString(Params.composition, null);
- String factoryMethod = srvMeta.getString(Params.factoryMethod, null);
- if (factoryMethod == null)
- {
- c.setImplementation(b.loadClass(impl));
- }
- else
- {
- c.setFactory(b.loadClass(impl), factoryMethod);
- }
- c.setComposition(composition);
-
- // Adds dependencies (except named dependencies, which are managed by the lifecycle
- // handler).
- addUnamedDependencies(b, dm, c, srvMeta, depsMeta);
- // Creates a ServiceHandler, which will filter all service lifecycle callbacks.
- ServiceLifecycleHandler lfcleHandler =
- new ServiceLifecycleHandler(c, b, dm, srvMeta, depsMeta);
- c.setCallbacks(lfcleHandler, "init", "start", "stop", "destroy");
-
- // Set the provided services
- Dictionary<String, Object> properties = srvMeta.getDictionary(Params.properties, null);
- String[] services = srvMeta.getStrings(Params.provides, null);
- c.setInterface(services, properties);
- }
- else
- {
- Log.instance()
- .info("ComponentBuilder: providing factory set for service %s with dependencies %s",
- srvMeta,
- depsMeta);
-
- // We don't instantiate the service, but instead we provide a Set in the registry.
- // This Set will act as a factory and another component may registers some
- // service configurations into it in order to fire some service instantiations.
- FactorySet factorySet = new FactorySet(b, srvMeta, depsMeta);
- c.setImplementation(factorySet);
- c.setCallbacks(null, "start", "stop", null);
- Hashtable<String, String> props = new Hashtable<String, String>();
- props.put(DM_FACTORY_NAME, factory);
- c.setInterface(Set.class.getName(), props);
- }
-
- dm.add(c);
- }
-}
diff --git a/dependencymanager/runtime/src/main/java/org/apache/felix/dm/runtime/DependencyBuilder.java b/dependencymanager/runtime/src/main/java/org/apache/felix/dm/runtime/DependencyBuilder.java
deleted file mode 100644
index 9b8b42d..0000000
--- a/dependencymanager/runtime/src/main/java/org/apache/felix/dm/runtime/DependencyBuilder.java
+++ /dev/null
@@ -1,255 +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.felix.dm.runtime;
-
-import org.apache.felix.dm.BundleDependency;
-import org.apache.felix.dm.ConfigurationDependency;
-import org.apache.felix.dm.Dependency;
-import org.apache.felix.dm.DependencyManager;
-import org.apache.felix.dm.ResourceDependency;
-import org.apache.felix.dm.ServiceDependency;
-import org.apache.felix.dm.TemporalServiceDependency;
-import org.osgi.framework.Bundle;
-
-/**
- * Class used to build a concrete dependency from meta data.
- *
- * @author <a href="mailto:dev@felix.apache.org">Felix Project Team</a>
- */
-public class DependencyBuilder
-{
- public enum DependencyType
- {
- ServiceDependency,
- TemporalServiceDependency,
- ConfigurationDependency,
- BundleDependency,
- ResourceDependency
- }
-
- private MetaData m_metaData;
-
- public DependencyBuilder(MetaData dependencyMetaData)
- {
- m_metaData = dependencyMetaData;
- }
-
- public Dependency build(Bundle b, DependencyManager dm)
- throws Exception
- {
- return build(b, dm, false);
- }
-
- public Dependency build(Bundle b, DependencyManager dm, boolean instanceBound)
- throws Exception
- {
- Dependency dp = null;
- DependencyType type;
-
- try
- {
- type = DependencyType.valueOf(m_metaData.getString(Params.type));
- }
- catch (IllegalArgumentException e)
- {
- throw new IllegalArgumentException("no \"type\" parameter found from metaData: " + m_metaData);
- }
-
- switch (type)
- {
- case ServiceDependency:
- dp = createServiceDependency(b, dm, instanceBound);
- break;
-
- case ConfigurationDependency:
- dp = createConfigurationDependency(dm, instanceBound);
- break;
-
- case BundleDependency:
- dp = createBundleDependency(dm, instanceBound);
- break;
-
- case ResourceDependency:
- dp = createResourceDependency(dm, instanceBound);
- break;
-
- default:
- throw new IllegalArgumentException("Can't build service dependency: " + type);
- }
- return dp;
- }
-
- private Dependency createServiceDependency(Bundle b, DependencyManager dm, boolean instanceBound)
- throws ClassNotFoundException
- {
- String service = m_metaData.getString(Params.service);
- Class<?> serviceClass = b.loadClass(service);
- String serviceFilter = m_metaData.getString(Params.filter, null);
- String defaultServiceImpl = m_metaData.getString(Params.defaultImpl, null);
- Class<?> defaultServiceImplClass =
- (defaultServiceImpl != null) ? b.loadClass(defaultServiceImpl) : null;
- String added = m_metaData.getString(Params.added, null);
- long timeout = m_metaData.getLong(Params.timeout, -1L);
- String changed = timeout != -1 ? null : m_metaData.getString(Params.changed, null);
- String removed = timeout != -1 ? null : m_metaData.getString(Params.removed, null);
- String autoConfigField = m_metaData.getString(Params.autoConfig, null);
- boolean required = "true".equals(m_metaData.getString(Params.required, "true"));
- boolean propagate = "true".equals(m_metaData.getString(Params.propagate, "false"));
-
- Dependency dp = createServiceDependency(dm, serviceClass,
- serviceFilter, defaultServiceImplClass, added, changed,
- removed, autoConfigField, timeout, required, instanceBound, propagate);
- return dp;
- }
-
- private Dependency createServiceDependency(DependencyManager dm, Class<?> serviceClass,
- String serviceFilter, Class<?> defaultServiceImplClass, String added,
- String changed, String removed, String autoConfigField, long timeout, boolean required,
- boolean instanceBound, boolean propagate)
- {
- ServiceDependency sd = timeout != -1 ? dm.createTemporalServiceDependency()
- : dm.createServiceDependency();
- sd.setService(serviceClass, serviceFilter);
- if (defaultServiceImplClass != null)
- {
- sd.setDefaultImplementation(defaultServiceImplClass);
- }
- sd.setCallbacks(added, changed, removed);
- if (autoConfigField != null)
- {
- sd.setAutoConfig(autoConfigField);
- }
- if (timeout != -1)
- {
- ((TemporalServiceDependency) sd).setTimeout(timeout);
- // Set required flag (always true for a temporal dependency)
- sd.setRequired(true);
- }
- else
- {
- // for ServiceDependency, get required flag.
- sd.setRequired(required);
- }
-
- sd.setInstanceBound(instanceBound);
- sd.setPropagate(propagate);
- return sd;
- }
-
- private Dependency createConfigurationDependency(DependencyManager dm, boolean instanceBound)
- {
- String pid = m_metaData.getString(Params.pid);
- boolean propagate = "true".equals(m_metaData.getString(Params.propagate, "false"));
- String callback = m_metaData.getString(Params.updated, "updated");
- Dependency dp = createConfigurationDependency(dm, pid, callback, propagate, instanceBound);
- return dp;
- }
-
- private Dependency createConfigurationDependency(DependencyManager dm, String pid, String callback,
- boolean propagate, boolean instanceBound)
- {
- if (pid == null)
- {
- throw new IllegalArgumentException(
- "pid attribute not provided in ConfigurationDependency declaration");
- }
- ConfigurationDependency cd = dm.createConfigurationDependency();
- cd.setPid(pid);
- cd.setCallback(callback);
- cd.setPropagate(propagate);
- cd.setInstanceBound(instanceBound);
- return cd;
- }
-
- /**
- * Creates a BundleDependency that we parsed from a component descriptor entry.
- * @param b
- * @param dm
- * @param parser
- * @return
- */
- private Dependency createBundleDependency(DependencyManager dm, boolean instanceBound)
- {
- String added = m_metaData.getString(Params.added, null);
- String changed = m_metaData.getString(Params.changed, null);
- String removed = m_metaData.getString(Params.removed, null);
- boolean required = "true".equals(m_metaData.getString(Params.required, "true"));
- String filter = m_metaData.getString(Params.filter, null);
- int stateMask = m_metaData.getInt(Params.stateMask, -1);
- boolean propagate = "true".equals(m_metaData.getString(Params.propagate, "false"));
-
- Dependency dp = createBundleDependency(dm, added, changed, removed, required, propagate, filter,
- stateMask, instanceBound);
- return dp;
- }
-
- private Dependency createBundleDependency(DependencyManager dm, String added, String changed,
- String removed, boolean required, boolean propagate, String filter, int stateMask, boolean instanceBound)
- {
- BundleDependency bd = dm.createBundleDependency();
- bd.setCallbacks(added, changed, removed);
- bd.setRequired(required);
- bd.setPropagate(propagate);
- if (filter != null)
- {
- bd.setFilter(filter);
- }
- if (stateMask != -1)
- {
- bd.setStateMask(stateMask);
- }
- bd.setInstanceBound(instanceBound);
- return bd;
- }
-
- private Dependency createResourceDependency(DependencyManager dm, boolean instanceBound)
- {
- String added = m_metaData.getString(Params.added, null);
- String changed = m_metaData.getString(Params.changed, null);
- String removed = m_metaData.getString(Params.removed, null);
- String filter = m_metaData.getString(Params.filter, null);
- boolean required = "true".equals(m_metaData.getString(Params.required, "true"));
- boolean propagate = "true".equals(m_metaData.getString(Params.propagate, "false"));
- String autoConfigField = m_metaData.getString(Params.autoConfig, null);
-
- Dependency dp = createResourceDependency(dm, added, changed, removed, required, filter,
- propagate, autoConfigField, instanceBound);
- return dp;
- }
-
- private Dependency createResourceDependency(DependencyManager dm, String added,
- String changed, String removed, boolean required, String filter, boolean propagate,
- String autoConfigField, boolean instanceBound)
- {
- ResourceDependency rd = dm.createResourceDependency();
- rd.setCallbacks(added, changed, removed);
- rd.setRequired(required);
- if (filter != null)
- {
- rd.setFilter(filter);
- }
- if (autoConfigField != null)
- {
- rd.setAutoConfig(autoConfigField);
- }
- rd.setPropagate(propagate);
- rd.setInstanceBound(instanceBound);
- return rd;
- }
-}
diff --git a/dependencymanager/runtime/src/main/java/org/apache/felix/dm/runtime/DependencyManagerRuntime.java b/dependencymanager/runtime/src/main/java/org/apache/felix/dm/runtime/DependencyManagerRuntime.java
deleted file mode 100644
index f107497..0000000
--- a/dependencymanager/runtime/src/main/java/org/apache/felix/dm/runtime/DependencyManagerRuntime.java
+++ /dev/null
@@ -1,216 +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.felix.dm.runtime;
-
-import java.io.BufferedReader;
-import java.io.IOException;
-import java.io.InputStreamReader;
-import java.net.URL;
-import java.util.ArrayList;
-import java.util.List;
-import java.util.concurrent.ConcurrentHashMap;
-
-import org.apache.felix.dm.Component;
-import org.apache.felix.dm.DependencyManager;
-import org.osgi.framework.Bundle;
-import org.osgi.service.packageadmin.PackageAdmin;
-
-/**
- * This class parses service descriptors generated by the annotation bnd processor.
- * The descriptors are located under META-INF/dependencymanager directory. Such files are actually
- * referenced by a specific "DependendencyManager-Component" manifest header.
- *
- * @author <a href="mailto:dev@felix.apache.org">Felix Project Team</a>
- */
-public class DependencyManagerRuntime
-{
- private ConcurrentHashMap<Bundle, DependencyManager> m_managers =
- new ConcurrentHashMap<Bundle, DependencyManager>();
- private DescriptorParser m_parser;
- private PackageAdmin m_packageAdmin; // Possibly a NullObject
-
- /**
- * Our constructor. We'll initialize here our DM component builders.
- */
- public DependencyManagerRuntime()
- {
- // Instantiates our descriptor parser, and register our service builders into it.
- m_parser = new DescriptorParser();
- m_parser.addBuilder(new ComponentBuilder());
- m_parser.addBuilder(new AspectServiceBuilder());
- m_parser.addBuilder(new AdapterServiceBuilder());
- m_parser.addBuilder(new BundleAdapterServiceBuilder());
- m_parser.addBuilder(new FactoryConfigurationAdapterServiceBuilder());
- m_parser.addBuilder(new ResourceAdapterServiceBuilder());
- }
-
- /**
- * Return our Object Composition (the Activator will inject dependencies into it)
- */
- protected Object[] getComposition()
- {
- return new Object[] { this, Log.instance() };
- }
-
- /**
- * Starts our Service (at this point, we have been injected with our bundle context, as well
- * as with our log service. We'll listen to bundle start/stop events (we implement the
- * SynchronousBundleListener interface).
- */
- protected void start()
- {
- Log.instance().info("Starting Dependency Manager annotation runtime");
- }
-
- /**
- * Stops our service. We'll stop all activated DependencyManager services.
- */
- @SuppressWarnings("unchecked")
- protected void stop()
- {
- Log.instance().info("Runtime: stopping services");
- for (DependencyManager dm : m_managers.values())
- {
- List<Component> services = new ArrayList<Component>(dm.getComponents());
- for (Component service : services)
- {
- dm.remove(service);
- }
- }
-
- m_managers.clear();
- }
-
- /**
- * Load the DM descriptors from the started bundle. We also check possible fragments
- * attached to the bundle, which might also contain some DM descriptors.
- * @param bundle the started bundle which contains a DependencyManager-Component header
- */
- protected void bundleStarted(Bundle bundle)
- {
- Log.instance().info("Scanning started bundle %s", bundle.getSymbolicName());
- List<URL> descriptorURLs = new ArrayList<URL>();
- collectDescriptors(bundle, descriptorURLs);
- Bundle[] fragments = m_packageAdmin.getFragments(bundle);
- if (fragments != null)
- {
- for (Bundle fragment : fragments)
- {
- collectDescriptors(fragment, descriptorURLs);
- }
- }
- for (URL descriptorURL : descriptorURLs)
- {
- loadDescriptor(bundle, descriptorURL);
- }
- }
-
- /**
- * Unregisters all services for a stopping bundle.
- * @param b
- */
- @SuppressWarnings("unchecked")
- protected void bundleStopped(Bundle b)
- {
- Log.instance().info("Runtime: Removing services from stopping bundle: %s", b.getSymbolicName());
- DependencyManager dm = m_managers.remove(b);
- if (dm != null)
- {
- List<Component> services = new ArrayList<Component>(dm.getComponents());
- for (Component service : services)
- {
- Log.instance().info("Runtime: Removing service: %s", service);
- dm.remove(service);
- }
- }
- }
-
- /**
- * Collect all descriptors found from a given bundle, including its possible attached fragments.
- * @param bundle a started bundle containing some DM descriptors
- * @param out the list of descriptors' URLS found from the started bundle, as well as from possibly
- * attached fragments.
- */
- private void collectDescriptors(Bundle bundle, List<URL> out) {
- String descriptorPaths = (String) bundle.getHeaders().get("DependencyManager-Component");
- if (descriptorPaths == null)
- {
- return;
- }
-
- for (String descriptorPath : descriptorPaths.split(","))
- {
- URL descriptorURL = bundle.getEntry(descriptorPath);
- if (descriptorURL == null)
- {
- Log.instance()
- .error("Runtime: " + "DependencyManager component descriptor not found: %s",
- descriptorPath);
- continue;
- }
- out.add(descriptorURL);
- }
- }
-
- /**
- * Load a DependencyManager component descriptor from a given bundle.
- * @param b
- * @param descriptorURL
- */
- private void loadDescriptor(Bundle b, URL descriptorURL)
- {
- Log.instance().debug("Parsing descriptor %s from bundle %s", descriptorURL, b.getSymbolicName());
-
- BufferedReader in = null;
- try
- {
- in = new BufferedReader(new InputStreamReader(descriptorURL.openStream()));
- DependencyManager dm = m_managers.get(b);
- if (dm == null)
- {
- dm = new DependencyManager(b.getBundleContext());
- m_managers.put(b, dm);
- }
-
- m_parser.parse(in, b, dm);
- }
-
- catch (Throwable t)
- {
- Log.instance().error("Runtime: Error while parsing descriptor %s from bundle %s",
- t,
- descriptorURL,
- b.getSymbolicName());
- }
-
- finally
- {
- if (in != null)
- {
- try
- {
- in.close();
- }
- catch (IOException ignored)
- {
- }
- }
- }
- }
-}
\ No newline at end of file
diff --git a/dependencymanager/runtime/src/main/java/org/apache/felix/dm/runtime/DescriptorParser.java b/dependencymanager/runtime/src/main/java/org/apache/felix/dm/runtime/DescriptorParser.java
deleted file mode 100644
index 2c162b1..0000000
--- a/dependencymanager/runtime/src/main/java/org/apache/felix/dm/runtime/DescriptorParser.java
+++ /dev/null
@@ -1,83 +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.felix.dm.runtime;
-
-import java.io.BufferedReader;
-import java.util.ArrayList;
-import java.util.HashMap;
-import java.util.List;
-import java.util.Map;
-
-import org.apache.felix.dm.DependencyManager;
-import org.json.JSONObject;
-import org.osgi.framework.Bundle;
-
-/**
- * This class parses files generated in META-INF/*.dm by the DependencyManager bnd plugin.
- * Each descriptor contains a JSON definition of a Service, along with its corresponding
- * dependencies.
- *
- * @author <a href="mailto:dev@felix.apache.org">Felix Project Team</a>
- */
-public class DescriptorParser
-{
- private Map<String, AbstractBuilder> m_builders = new HashMap<String, AbstractBuilder>();
-
- public void addBuilder(AbstractBuilder sb)
- {
- m_builders.put(sb.getType(), sb);
- }
-
- public void parse(BufferedReader reader, Bundle b, DependencyManager dm) throws Exception
- {
- String line;
-
- // The first line is a Service Component (a Service, an Aspect Service, etc ...)
- line = reader.readLine();
- Log.instance().debug("DescriptorParser: parsing service %s", line);
- JSONObject json = new JSONObject(line);
- JSONMetaData serviceMetaData = new JSONMetaData(json);
-
- String type = (String) json.get("type");
- if (type == null)
- {
- throw new IllegalArgumentException("Invalid descriptor"
- + ": no \"type\" parameter found in first line");
- }
-
- AbstractBuilder builder = m_builders.get(type);
- if (builder == null)
- {
- throw new IllegalArgumentException("Invalid descriptor"
- + ": invalid \"type\" parameter found in first line");
- }
-
- // Parse the rest of the lines (dependencies)
- List<MetaData> serviceDependencies = new ArrayList<MetaData>();
- while ((line = reader.readLine()) != null)
- {
- Log.instance().debug("Parsing dependency %s", line);
- JSONObject dep = new JSONObject(line);
- serviceDependencies.add(new JSONMetaData(dep));
- }
-
- // and Invoke the builder
- builder.build(serviceMetaData, serviceDependencies, b, dm);
- }
-}
diff --git a/dependencymanager/runtime/src/main/java/org/apache/felix/dm/runtime/FactoryConfigurationAdapterServiceBuilder.java b/dependencymanager/runtime/src/main/java/org/apache/felix/dm/runtime/FactoryConfigurationAdapterServiceBuilder.java
deleted file mode 100644
index 0f4eb09..0000000
--- a/dependencymanager/runtime/src/main/java/org/apache/felix/dm/runtime/FactoryConfigurationAdapterServiceBuilder.java
+++ /dev/null
@@ -1,74 +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.felix.dm.runtime;
-
-import java.util.Dictionary;
-import java.util.List;
-
-import org.apache.felix.dm.Component;
-import org.apache.felix.dm.DependencyManager;
-import org.osgi.framework.Bundle;
-
-/**
- * Class used to build a factory configuration adapter service using metadata found from DependencyManager runtime
- * meta-inf descriptor.
- *
- * @author <a href="mailto:dev@felix.apache.org">Felix Project Team</a>
- */
-public class FactoryConfigurationAdapterServiceBuilder extends AbstractBuilder
-{
- private final static String TYPE = "FactoryConfigurationAdapterService";
-
- @Override
- public String getType()
- {
- return TYPE;
- }
-
- @Override
- public void build(MetaData srvMeta, List<MetaData> depsMeta, Bundle b, DependencyManager dm)
- throws Exception
- {
- Class<?> implClass = b.loadClass(srvMeta.getString(Params.impl));
- String factoryPid = srvMeta.getString(Params.factoryPid);
- String updated = srvMeta.getString(Params.updated);
- String[] provides = srvMeta.getStrings(Params.provides, null);
- Dictionary<String, Object> properties = srvMeta.getDictionary(Params.properties, null);
- boolean propagate = "true".equals(srvMeta.getString(Params.propagate, "false"));
- Component c = dm.createFactoryConfigurationAdapterService(factoryPid, updated, propagate);
- c.setInterface(provides, properties);
- String factoryMethod = srvMeta.getString(Params.factoryMethod, null);
- if (factoryMethod == null)
- {
- c.setImplementation(implClass);
- }
- else
- {
- c.setFactory(implClass, factoryMethod);
- }
- setCommonServiceParams(c, srvMeta);
- c.setComposition(srvMeta.getString(Params.composition, null));
- ServiceLifecycleHandler lfcleHandler = new ServiceLifecycleHandler(c, b, dm, srvMeta, depsMeta);
- // The dependencies will be plugged by our lifecycle handler.
- c.setCallbacks(lfcleHandler, "init", "start", "stop", "destroy");
- // Adds dependencies (except named dependencies, which are managed by the lifecycle handler).
- addUnamedDependencies(b, dm, c, srvMeta, depsMeta);
- dm.add(c);
- }
-}
diff --git a/dependencymanager/runtime/src/main/java/org/apache/felix/dm/runtime/FactorySet.java b/dependencymanager/runtime/src/main/java/org/apache/felix/dm/runtime/FactorySet.java
deleted file mode 100644
index 8241b6d..0000000
--- a/dependencymanager/runtime/src/main/java/org/apache/felix/dm/runtime/FactorySet.java
+++ /dev/null
@@ -1,539 +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.felix.dm.runtime;
-
-import java.lang.reflect.Method;
-import java.util.AbstractSet;
-import java.util.Dictionary;
-import java.util.Enumeration;
-import java.util.Hashtable;
-import java.util.Iterator;
-import java.util.List;
-import java.util.concurrent.ConcurrentHashMap;
-
-import org.apache.felix.dm.Component;
-import org.apache.felix.dm.Dependency;
-import org.apache.felix.dm.DependencyManager;
-import org.osgi.framework.Bundle;
-
-/**
- * This class implements a <code>java.util.Set</code> which acts as a service factory.
- * When a <code>Service</annotation> contains a <code>factory</code> attribute, this class is provided
- * into the OSGi registry with a <code>dm.factory.name</code> service property. So, another factory component
- * may be injected with this Set. And each time a Dictionary configuration is registered in the Set,
- * then a new Service instance will be instantiated, and will be provided with the Dictionary passed to the
- * Service instance.
- *
- * @author <a href="mailto:dev@felix.apache.org">Felix Project Team</a>
- */
-@SuppressWarnings( { "unchecked" })
-public class FactorySet extends AbstractSet<Dictionary>
-{
- /**
- * The actual Service instance that is allocated for each dictionaries added in this Set.
- */
- private Object m_impl;
-
- /**
- * The Service provided in the OSGi registry.
- */
- private final String[] m_provide;
-
- /**
- * The properties to be provided by the Service.
- */
- private final Dictionary m_serviceProperties;
-
- /**
- * The configure Service callback used to pass configuration added in this Set.
- */
- private final String m_configure;
-
- /**
- * The map between our Dictionaries and corresponding Service instances.
- */
- private final ConcurrentHashMap<ServiceKey, Object> m_services = new ConcurrentHashMap<ServiceKey, Object>();
-
- /**
- * The list of Dependencies which are applied in the Service.
- */
- private MetaData m_srvMeta;
-
- /**
- * The list of Dependencies which are applied in the Service.
- */
- private List<MetaData> m_depsMeta;
-
- /**
- * The DependencyManager which is used to create Service instances.
- */
- private DependencyManager m_dm;
-
- /**
- * This class is used to serialize concurrent method calls, and allow to leave our methods unsynchronized.
- * This is required because some of our methods may invoke some Service callbacks, which must be called outside
- * synchronized block (in order to avoid potential dead locks).
- */
- private SerialExecutor m_serialExecutor = new SerialExecutor();
-
- /**
- * Flag used to check if our service is Active.
- */
- private volatile boolean m_active;
-
- /**
- * The bundle containing the Service annotated with the factory attribute.
- */
- private Bundle m_bundle;
-
- /**
- * Flag used to check if a service is being created
- */
- private final static Object SERVICE_CREATING = new Object();
-
- /**
- * When a Dictionary is registered in a factory Set, we use this special
- * property key, whose value may provide the instance to use when
- * creating a service.
- */
- private final static String DM_FACTORY_INSTANCE = "dm.factory.instance";
-
- /**
- * This class wraps <tt>Dictionary</tt>, allowing to store the dictionary into a Map, using
- * reference-equality in place of object-equality when getting the Dictionary from the Map.
- */
- private static class ServiceKey
- {
- private Dictionary m_dictionary;
-
- public ServiceKey(Dictionary dictionary)
- {
- m_dictionary = dictionary;
- }
-
- Dictionary getDictionary()
- {
- return m_dictionary;
- }
-
- @Override
- public boolean equals(Object that)
- {
- return that instanceof ServiceKey ? (((ServiceKey) that).getDictionary() == m_dictionary)
- : false;
- }
-
- @Override
- public int hashCode()
- {
- return System.identityHashCode(m_dictionary);
- }
-
- @Override
- public String toString()
- {
- return Dictionary.class.getName() + "@" + System.identityHashCode(m_dictionary);
- }
- }
-
- /**
- * Sole constructor.
- * @param b the bundle containing the Service annotated with the factory attribute
- * @param impl The Service implementation class
- * @param serviceProperties The Service properties
- * @param provides The Services provided by this Service
- * @param factoryConfigure The configure callback invoked in order to pass configurations added in this Set.
- */
- public FactorySet(Bundle b, MetaData srvMeta, List<MetaData> depsMeta)
- {
- m_serviceProperties = srvMeta.getDictionary(Params.properties, null);
- m_provide = srvMeta.getStrings(Params.provides, null);
- m_configure = srvMeta.getString(Params.factoryConfigure, null);
- m_bundle = b;
- m_srvMeta = srvMeta;
- m_depsMeta = depsMeta;
- }
-
- /**
- * Our Service is starting.
- */
- public void start(Component c)
- {
- m_active = true;
- m_dm = c.getDependencyManager();
- }
-
- /**
- * Our Service is stopping: we have to remove all Service instances that we have created.
- */
- public void stop()
- {
- try
- {
- clear();
- }
- finally
- {
- m_active = false;
- }
- }
-
- /**
- * Create or Update a Service.
- */
- @Override
- @SuppressWarnings("synthetic-access")
- public boolean add(final Dictionary configuration)
- {
- // Check parameter validity
- if (configuration == null)
- {
- throw new NullPointerException("configuration parameter can't be null");
- }
-
- // Check if our service is running.
- checkServiceAvailable();
-
- // Check if service is being created
- ServiceKey serviceKey = new ServiceKey(configuration);
- boolean creating = false;
- synchronized (this)
- {
- if (!m_services.containsKey(serviceKey))
- {
- m_services.put(serviceKey, SERVICE_CREATING);
- creating = true;
- }
- // Create or Update the Service.
- m_serialExecutor.enqueue(new Runnable()
- {
- public void run()
- {
- doAdd(configuration);
- }
- });
- }
-
- m_serialExecutor.execute();
- return creating;
- }
-
- /**
- * Another Service wants to remove an existing Service.
- * This method is not synchronized but uses a SerialExecutor for serializing concurrent method call.
- * (This avoid potential dead locks, especially when Service callback methods are invoked).
- */
- @Override
- @SuppressWarnings("synthetic-access")
- public boolean remove(final Object configuration)
- {
- // Check parameter validity.
- if (configuration == null)
- {
- throw new NullPointerException("configuration parameter can't be null");
- }
- if (!(configuration instanceof Dictionary))
- {
- throw new IllegalArgumentException("configuration must be an instance of a Dictionary");
- }
-
- // Check if our service is active.
- checkServiceAvailable();
-
- // Check if service is created (or creating)
- boolean found = m_services.containsKey(new ServiceKey((Dictionary) configuration));
- if (found)
- {
- // Create or Update the Service.
- m_serialExecutor.enqueue(new Runnable()
- {
- public void run()
- {
- doRemove((Dictionary) configuration);
- }
- });
- m_serialExecutor.execute();
- }
- return found;
- }
-
- /**
- * Another Service wants to remove all existing Services.
- * This method is not synchronized but uses a SerialExecutor for serializing concurrent method call.
- * (This avoid potential dead locks, especially when Service callback methods are invoked).
- */
- @Override
- @SuppressWarnings("synthetic-access")
- public void clear()
- {
- if (!m_active)
- {
- return;
- }
-
- // Create or Update the Service.
- m_serialExecutor.enqueue(new Runnable()
- {
- public void run()
- {
- doClear();
- }
- });
- m_serialExecutor.execute();
- }
-
- /**
- * returns the list of active Service instances configurations.
- */
- @Override
- public Iterator<Dictionary> iterator()
- {
- throw new UnsupportedOperationException(
- "iterator method is not supported by DependencyManager Set's service factories");
- }
-
- @Override
- public String toString()
- {
- return FactorySet.class.getName() + "(" + m_services.size() + " active instances)";
- }
-
- /**
- * Returns the number of active Service instances.
- */
- @Override
- public int size()
- {
- if (!m_active)
- {
- return 0;
- }
- return m_services.size();
- }
-
- /**
- * Checks if our Service is available (we are not stopped").
- */
- private void checkServiceAvailable()
- {
- if (!m_active)
- {
- throw new IllegalStateException("Service not available");
- }
- }
-
- /**
- * Add or create a new Service instance, given its configuration. This method is invoked by the
- * SerialExecutor, hence it's thread safe and we'll invoke Service's callbacks without being
- * synchronized (hence this will avoid potential dead locks).
- */
- private void doAdd(Dictionary configuration)
- {
- // Check if the service exists.
- ServiceKey serviceKey = new ServiceKey(configuration);
- Object service = m_services.get(serviceKey);
- if (service == null || service == SERVICE_CREATING)
- {
- try
- {
- // Create the Service / impl, unless it is explicitly provided from the
- // configuration (using the specific key "dm.factory.instance").
- Component s = m_dm.createComponent();
- Class implClass = m_bundle.loadClass(m_srvMeta.getString(Params.impl));
- Object impl = configuration.get(DM_FACTORY_INSTANCE);
- if (impl == null)
- {
- String factoryMethod = m_srvMeta.getString(Params.factoryMethod, null);
- if (factoryMethod == null)
- {
- m_impl = implClass.newInstance();
- }
- else
- {
- Method m = implClass.getDeclaredMethod(factoryMethod);
- m.setAccessible(true);
- m_impl = m.invoke(null);
- }
- }
- else
- {
- m_impl = impl;
- }
-
- // Invoke "configure" callback
- if (m_configure != null)
- {
- invokeConfigure(m_impl, m_configure, configuration);
- }
-
- // Create Service
- s.setImplementation(m_impl);
- if (m_provide != null)
- {
- // Merge service properties with the configuration provided by the factory.
- Dictionary serviceProperties = mergeSettings(m_serviceProperties, configuration);
- s.setInterface(m_provide, serviceProperties);
- }
-
- s.setComposition(m_srvMeta.getString(Params.composition, null));
- ServiceLifecycleHandler lfcleHandler = new ServiceLifecycleHandler(s, m_bundle, m_dm,
- m_srvMeta, m_depsMeta);
- // The dependencies will be plugged by our lifecycle handler.
- s.setCallbacks(lfcleHandler, "init", "start", "stop", "destroy");
-
- // Adds dependencies (except named dependencies, which are managed by the lifecycle handler).
- for (MetaData dependency: m_depsMeta)
- {
- String name = dependency.getString(Params.name, null);
- if (name == null)
- {
- DependencyBuilder depBuilder = new DependencyBuilder(dependency);
- Log.instance().info("ServiceLifecycleHandler.init: adding dependency %s into service %s",
- dependency, m_srvMeta);
- Dependency d = depBuilder.build(m_bundle, m_dm, false);
- s.add(d);
- }
- }
-
- // Register the Service instance, and keep track of it.
- Log.instance().info("ServiceFactory: created service %s", m_srvMeta);
- m_dm.add(s);
- m_services.put(serviceKey, s);
- }
- catch (Throwable t)
- {
- // Make sure the SERVICE_CREATING flag is also removed
- m_services.remove(serviceKey);
- Log.instance().error("ServiceFactory: could not instantiate service %s",
- t, m_srvMeta);
- }
- }
- else
- {
- // Reconfigure an already existing Service.
- if (m_configure != null)
- {
- Log.instance().info("ServiceFactory: updating service %s", m_impl);
- invokeConfigure(m_impl, m_configure, configuration);
- }
-
- // Update service properties
- if (m_provide != null)
- {
- Dictionary settings = mergeSettings(m_serviceProperties, configuration);
- ((Component) service).setServiceProperties(settings);
- }
- }
- }
-
- private void doRemove(Dictionary configuraton)
- {
- Log.instance().info("ServiceFactory: removing service %s", m_srvMeta);
- ServiceKey serviceKey = new ServiceKey(configuraton);
- Object service = m_services.remove(serviceKey);
- if (service != null && service != SERVICE_CREATING)
- {
- m_dm.remove((Component) service);
- }
- }
-
- private void doClear()
- {
- try
- {
- for (Object service: m_services.values())
- {
- if (service instanceof Component)
- {
- m_dm.remove((Component) service);
- }
- }
- }
- finally
- {
- m_services.clear();
- }
- }
-
- /**
- * Merge factory configuration settings with the service properties. The private factory configuration
- * settings are ignored. A factory configuration property is private if its name starts with a dot (".").
- *
- * @param serviceProperties
- * @param factoryConfiguration
- * @return
- */
- private Dictionary mergeSettings(Dictionary serviceProperties, Dictionary factoryConfiguration)
- {
- Dictionary props = new Hashtable();
-
- if (serviceProperties != null)
- {
- Enumeration keys = serviceProperties.keys();
- while (keys.hasMoreElements())
- {
- Object key = keys.nextElement();
- Object val = serviceProperties.get(key);
- props.put(key, val);
- }
- }
-
- Enumeration keys = factoryConfiguration.keys();
- while (keys.hasMoreElements())
- {
- Object key = keys.nextElement();
- if (!key.toString().startsWith("."))
- {
- // public properties are propagated
- Object val = factoryConfiguration.get(key);
- props.put(key, val);
- }
- }
- return props;
- }
-
- /**
- * Invokes the configure callback method on the service instance implemenatation.
- * @param impl
- * @param configure
- * @param config
- */
- private void invokeConfigure(Object impl, String configure, Dictionary config)
- {
- try
- {
- InvocationUtil.invokeCallbackMethod(impl, configure,
- new Class[][] { { Dictionary.class } },
- new Object[][] { { config } });
- }
-
- catch (Throwable t)
- {
- if (t instanceof RuntimeException)
- {
- throw (RuntimeException) t;
- }
- else
- {
- throw new RuntimeException("Could not invoke method " + configure
- + " on object " + impl, t);
- }
- }
- }
-}
diff --git a/dependencymanager/runtime/src/main/java/org/apache/felix/dm/runtime/InvocationUtil.java b/dependencymanager/runtime/src/main/java/org/apache/felix/dm/runtime/InvocationUtil.java
deleted file mode 100644
index fb4456b..0000000
--- a/dependencymanager/runtime/src/main/java/org/apache/felix/dm/runtime/InvocationUtil.java
+++ /dev/null
@@ -1,111 +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.felix.dm.runtime;
-
-import java.lang.reflect.InvocationTargetException;
-import java.lang.reflect.Method;
-import java.lang.reflect.Modifier;
-import java.lang.reflect.Proxy;
-import java.security.AccessController;
-import java.security.PrivilegedAction;
-
-/**
- * Java reflexion utility methods.
- *
- * @author <a href="mailto:dev@felix.apache.org">Felix Project Team</a>
- */
-public class InvocationUtil
-{
- public static Object invokeCallbackMethod(Object instance,
- String methodName,
- Class<?>[][] signatures,
- Object[][] parameters)
- throws NoSuchMethodException, IllegalArgumentException, IllegalAccessException,
- InvocationTargetException
- {
- Class<?> currentClazz = instance.getClass();
- while (currentClazz != null)
- {
- try
- {
- return invokeMethod(instance, currentClazz, methodName, signatures, parameters, false);
- }
- catch (NoSuchMethodException nsme)
- {
- // ignore
- }
- currentClazz = currentClazz.getSuperclass();
- }
- throw new NoSuchMethodException(methodName);
- }
-
- public static Object invokeMethod(Object object,
- Class<?> clazz,
- String name,
- Class<?>[][] signatures,
- Object[][] parameters,
- boolean isSuper)
- throws NoSuchMethodException, InvocationTargetException, IllegalArgumentException,
- IllegalAccessException
- {
- if (object == null)
- {
- throw new IllegalArgumentException("Instance cannot be null");
- }
- if (clazz == null)
- {
- throw new IllegalArgumentException("Class cannot be null");
- }
-
- // If we're talking to a proxy here, dig one level deeper to expose the
- // underlying invocation handler ...
-
- if (Proxy.isProxyClass(clazz))
- {
- object = Proxy.getInvocationHandler(object);
- clazz = object.getClass();
- }
-
- for (int i = 0; i < signatures.length; i++)
- {
- Class<?>[] signature = signatures[i];
- try
- {
- final Method m = clazz.getDeclaredMethod(name, signature);
- if (!(isSuper && Modifier.isPrivate(m.getModifiers())))
- {
- AccessController.doPrivileged(new PrivilegedAction<Object>()
- {
- public Object run()
- {
- m.setAccessible(true);
- return null;
- }
- });
- return m.invoke(object, parameters[i]);
- }
- }
- catch (NoSuchMethodException e)
- {
- // ignore this and keep looking
- }
- }
- throw new NoSuchMethodException(name);
- }
-}
diff --git a/dependencymanager/runtime/src/main/java/org/apache/felix/dm/runtime/JSONMetaData.java b/dependencymanager/runtime/src/main/java/org/apache/felix/dm/runtime/JSONMetaData.java
deleted file mode 100644
index 2310721..0000000
--- a/dependencymanager/runtime/src/main/java/org/apache/felix/dm/runtime/JSONMetaData.java
+++ /dev/null
@@ -1,481 +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.felix.dm.runtime;
-
-import java.lang.reflect.Array;
-import java.util.Dictionary;
-import java.util.HashMap;
-import java.util.Hashtable;
-import java.util.Iterator;
-
-import org.json.JSONArray;
-import org.json.JSONException;
-import org.json.JSONObject;
-
-/**
- * Thsi class represents the parsed data found from meta-inf dependencymanager descriptors.
- *
- * @author <a href="mailto:dev@felix.apache.org">Felix Project Team</a>
- */
-public class JSONMetaData implements MetaData, Cloneable
-{
- /**
- * The parsed Dependency or Service metadata. The map value is either a String, a String[],
- * or a Dictionary, whose values are String or String[].
- */
- private HashMap<String, Object> m_metadata = new HashMap<String, Object>();
-
- /**
- * Decodes Json metadata for either a Service or a Dependency descriptor entry.
- * The JSON object has the following form:
- *
- * entry ::= String | String[] | dictionary
- * dictionary ::= key-value-pair*
- * key-value-pair ::= key value
- * value ::= String | String[] | value-type
- * value-type ::= jsonObject with value-type-info
- * value-type-info ::= "type"=primitive java type
- * "value"=String|String[]
- *
- * Exemple:
- *
- * {"string-param" : "string-value",
- * "string-array-param" : ["string1", "string2"],
- * "properties" : {
- * "string-param" : "string-value",
- * "string-array-param" : ["str1", "str2],
- * "long-param" : {"type":"java.lang.Long", "value":"1"}}
- * "long-array-param" : {"type":"java.lang.Long", "value":["1"]}}
- * }
- * }
- *
- * @param jso the JSON object that corresponds to a dependency manager descriptor entry line.
- * @throws JSONException
- */
- @SuppressWarnings("unchecked")
- public JSONMetaData(JSONObject jso) throws JSONException
- {
- // Decode json object into our internal map.
- Iterator<String> it = jso.keys();
- while (it.hasNext())
- {
- String key = it.next();
- Object value = jso.get(key);
- if (value instanceof String)
- {
- m_metadata.put(key, value);
- }
- else if (value instanceof JSONArray)
- {
- m_metadata.put(key, decodeStringArray((JSONArray) value));
- }
- else if (value instanceof JSONObject)
- {
- m_metadata.put(key, parseProperties((JSONObject) value));
- }
- }
- }
-
- private Hashtable<String, Object> parseProperties(JSONObject properties) throws JSONException {
- Hashtable<String, Object> parsedProps = new Hashtable<String, Object>();
- Iterator<String> it = properties.keys();
- while (it.hasNext())
- {
- String key = it.next();
- Object value = properties.get(key);
- if (value instanceof String)
- {
- // This property type is a simple string
- parsedProps.put(key, value);
- }
- else if (value instanceof JSONArray)
- {
- // This property type is a simple string array
- parsedProps.put(key, decodeStringArray((JSONArray) value));
- }
- else if (value instanceof JSONObject)
- {
- // This property type is a typed value, encoded as a JSONObject with two keys: "type"/"value"
- JSONObject json = ((JSONObject) value);
- String type = json.getString("type");
- Object typeValue = json.get("value");
-
- if (type == null)
- {
- throw new JSONException("missing type attribute in json metadata for key " + key);
- }
- if (typeValue == null)
- {
- throw new JSONException("missing type value attribute in json metadata for key " + key);
- }
-
- Class<?> typeClass;
- try
- {
- typeClass = Class.forName(type);
- }
- catch (ClassNotFoundException e)
- {
- throw new JSONException("invalid type attribute (" + type + ") in json metadata for key "
- + key);
- }
-
- if (typeValue instanceof JSONArray)
- {
- parsedProps.put(key, toPrimitiveTypeArray(typeClass, (JSONArray) typeValue));
- }
- else
- {
- parsedProps.put(key, toPrimitiveType(typeClass, typeValue.toString()));
- }
- }
- }
- return parsedProps;
- }
-
- private Object toPrimitiveType(Class<?> type, String value) throws JSONException {
- if (type.equals(String.class))
- {
- return value;
- }
- else if (type.equals(Long.class))
- {
- return Long.parseLong(value);
- }
- else if (type.equals(Double.class))
- {
- return Double.valueOf(value);
- }
- else if (type.equals(Float.class))
- {
- return Float.valueOf(value);
- }
- else if (type.equals(Integer.class))
- {
- return Integer.valueOf(value);
- }
- else if (type.equals(Byte.class))
- {
- return Byte.valueOf(value);
- }
- else if (type.equals(Character.class))
- {
- return Character.valueOf((char) Integer.parseInt(value));
- }
- else if (type.equals(Boolean.class))
- {
- return Boolean.valueOf(value);
- }
- else if (type.equals(Short.class))
- {
- return Short.valueOf(value);
- }
- else
- {
- throw new JSONException("invalid type (" + type + ") attribute in json metadata");
- }
- }
-
- private Object toPrimitiveTypeArray(Class<?> type, JSONArray array) throws JSONException {
- int len = array.length();
- Object result = Array.newInstance(type, len);
-
- if (type.equals(String.class))
- {
- for (int i = 0; i < len; i ++) {
- Array.set(result, i, array.getString(i));
- }
- }
- else if (type.equals(Long.class))
- {
- for (int i = 0; i < len; i ++) {
- Array.set(result, i, Long.valueOf(array.getString(i)));
- }
- }
- else if (type.equals(Double.class))
- {
- for (int i = 0; i < len; i ++) {
- Array.set(result, i, Double.valueOf(array.getString(i)));
- }
- }
- else if (type.equals(Float.class))
- {
- for (int i = 0; i < len; i ++) {
- Array.set(result, i, Float.valueOf(array.getString(i)));
- }
- }
- else if (type.equals(Integer.class))
- {
- for (int i = 0; i < len; i ++) {
- Array.set(result, i, Integer.valueOf(array.getString(i)));
- }
- }
- else if (type.equals(Byte.class))
- {
- for (int i = 0; i < len; i ++) {
- Array.set(result, i, Byte.valueOf(array.getString(i)));
- }
- }
- else if (type.equals(Character.class))
- {
- for (int i = 0; i < len; i ++) {
- Array.set(result, i, Character.valueOf((char) Integer.parseInt(array.getString(i))));
- }
- }
- else if (type.equals(Boolean.class))
- {
- for (int i = 0; i < len; i ++) {
- Array.set(result, i, Boolean.valueOf(array.getString(i)));
- }
- }
- else if (type.equals(Short.class))
- {
- for (int i = 0; i < len; i ++) {
- Array.set(result, i, Short.valueOf(array.getString(i)));
- }
- }
- else
- {
- throw new JSONException("invalid type (" + type + ") attribute in json metadata");
- }
- return result;
- }
-
- /**
- * Close this class instance to another one.
- */
- @SuppressWarnings("unchecked")
- @Override
- public Object clone() throws CloneNotSupportedException
- {
- JSONMetaData clone = (JSONMetaData) super.clone();
- clone.m_metadata = (HashMap<String, Object>) m_metadata.clone();
- return clone;
- }
-
- public String getString(Params key)
- {
- Object value = m_metadata.get(key.toString());
- if (value == null)
- {
- throw new IllegalArgumentException("Parameter " + key + " not found");
- }
- return value.toString();
- }
-
- public String getString(Params key, String def)
- {
- try
- {
- return getString(key);
- }
- catch (IllegalArgumentException e)
- {
- return def;
- }
- }
-
- public int getInt(Params key)
- {
- Object value = m_metadata.get(key.toString());
- if (value != null)
- {
- try
- {
- if (value instanceof Integer) {
- return ((Integer) value).intValue();
- }
- return Integer.parseInt(value.toString());
- }
- catch (NumberFormatException e)
- {
- throw new IllegalArgumentException("parameter " + key
- + " is not an int value: "
- + value);
- }
- }
- else
- {
- throw new IllegalArgumentException("missing " + key
- + " parameter from annotation");
- }
- }
-
- public int getInt(Params key, int def)
- {
- Object value = m_metadata.get(key.toString());
- if (value != null)
- {
- try
- {
- if (value instanceof Integer) {
- return ((Integer) value).intValue();
- }
- return Integer.parseInt(value.toString());
- }
- catch (NumberFormatException e)
- {
- throw new IllegalArgumentException("parameter " + key
- + " is not an int value: "
- + value);
- }
- }
- else
- {
- return def;
- }
- }
-
- public long getLong(Params key)
- {
- Object value = m_metadata.get(key.toString());
- if (value != null)
- {
- try
- {
- if (value instanceof Long) {
- return ((Long) value).longValue();
- }
- return Long.parseLong(value.toString());
- }
- catch (NumberFormatException e)
- {
- throw new IllegalArgumentException("parameter " + key
- + " is not a long value: "
- + value);
- }
- }
- else
- {
- throw new IllegalArgumentException("missing " + key
- + " parameter from annotation");
- }
- }
-
- public long getLong(Params key, long def)
- {
- Object value = m_metadata.get(key.toString());
- if (value != null)
- {
- try
- {
- if (value instanceof Long) {
- return (Long) value;
- }
- return Long.parseLong(value.toString());
- }
- catch (NumberFormatException e)
- {
- throw new IllegalArgumentException("parameter " + key
- + " is not a long value: "
- + value);
- }
- }
- else
- {
- return def;
- }
- }
-
- public String[] getStrings(Params key)
- {
- Object array = m_metadata.get(key.toString());
- if (array == null)
- {
- throw new IllegalArgumentException("Parameter " + key + " not found");
- }
-
- if (!(array instanceof String[]))
- {
- throw new IllegalArgumentException("Parameter " + key + " is not a String[] (" + array.getClass()
- + ")");
- }
- return (String[]) array;
- }
-
- public String[] getStrings(Params key, String[] def)
- {
- try
- {
- return getStrings(key);
- }
- catch (IllegalArgumentException t)
- {
- return def;
- }
- }
-
- @SuppressWarnings("unchecked")
- public Dictionary<String, Object> getDictionary(Params key,
- Dictionary<String, Object> def)
- {
- Object dictionary = m_metadata.get(key.toString());
- if (dictionary == null)
- {
- return def;
- }
-
- if (!(dictionary instanceof Dictionary<?, ?>))
- {
- throw new IllegalArgumentException("Parameter " + key + " is not a Dictionary ("
- + dictionary.getClass() + ")");
- }
-
- return (Dictionary<String, Object>) dictionary;
- }
-
- @Override
- public String toString()
- {
- return m_metadata.toString();
- }
-
- public void setDictionary(Params key, Dictionary<String, Object> dictionary)
- {
- m_metadata.put(key.toString(), dictionary);
- }
-
- public void setString(Params key, String value)
- {
- m_metadata.put(key.toString(), value);
- }
-
- public void setStrings(Params key, String[] values)
- {
- m_metadata.put(key.toString(), values);
- }
-
- /**
- * Decodes a JSONArray into a String array (all JSON array values are supposed to be strings).
- */
- private String[] decodeStringArray(JSONArray array) throws JSONException
- {
- String[] arr = new String[array.length()];
- for (int i = 0; i < array.length(); i++)
- {
- Object value = array.get(i);
- if (!(value instanceof String))
- {
- throw new IllegalArgumentException("JSON array is not an array of Strings: " + array);
- }
- arr[i] = value.toString();
- }
- return arr;
- }
-}
diff --git a/dependencymanager/runtime/src/main/java/org/apache/felix/dm/runtime/Log.java b/dependencymanager/runtime/src/main/java/org/apache/felix/dm/runtime/Log.java
deleted file mode 100644
index f23ba0e..0000000
--- a/dependencymanager/runtime/src/main/java/org/apache/felix/dm/runtime/Log.java
+++ /dev/null
@@ -1,80 +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.felix.dm.runtime;
-
-import org.osgi.service.log.LogService;
-
-/**
- * This class logs some formattable strings into the OSGi Log Service.
- *
- * @author <a href="mailto:dev@felix.apache.org">Felix Project Team</a>
- */
-public class Log
-{
- /** The wrap log service which is actually used (Injected by Activator) */
- private volatile LogService m_logService;
-
- /** Our sole instance */
- private static Log m_instance = new Log();
-
- public static Log instance()
- {
- return m_instance;
- }
-
- public void error(String format, Object ... args)
- {
- m_logService.log(LogService.LOG_ERROR, String.format(format, args));
- }
-
- public void error(String format, Throwable t, Object ... args)
- {
- m_logService.log(LogService.LOG_ERROR, String.format(format, args), t);
- }
-
- public void warn(String format, Object ... args)
- {
- m_logService.log(LogService.LOG_WARNING, String.format(format, args));
- }
-
- public void warn(String format, Throwable t, Object ... args)
- {
- m_logService.log(LogService.LOG_WARNING, String.format(format, args), t);
- }
-
- public void info(String format, Object ... args)
- {
- m_logService.log(LogService.LOG_INFO, String.format(format, args));
- }
-
- public void info(String format, Throwable t, Object ... args)
- {
- m_logService.log(LogService.LOG_INFO, String.format(format, args), t);
- }
-
- public void debug(String format, Object ... args)
- {
- m_logService.log(LogService.LOG_DEBUG, String.format(format, args));
- }
-
- public void debug(String format, Throwable t, Object ... args)
- {
- m_logService.log(LogService.LOG_DEBUG, String.format(format, args), t);
- }
-}
diff --git a/dependencymanager/runtime/src/main/java/org/apache/felix/dm/runtime/MetaData.java b/dependencymanager/runtime/src/main/java/org/apache/felix/dm/runtime/MetaData.java
deleted file mode 100644
index 435f958..0000000
--- a/dependencymanager/runtime/src/main/java/org/apache/felix/dm/runtime/MetaData.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.felix.dm.runtime;
-
-import java.util.Dictionary;
-
-/**
- * This class represents the meta data parsed from a descriptor entry (json) line.
- *
- * @author <a href="mailto:dev@felix.apache.org">Felix Project Team</a>
- */
-public interface MetaData extends Cloneable
-{
- /**
- * Returns a String descriptor entry parameter value.
- */
- String getString(Params key);
-
- /**
- * Returns a String descriptor entry parameter value.
- */
- String getString(Params key, String def);
-
- /**
- * Returns a String descriptor entry parameter value.
- */
- int getInt(Params key);
-
- /**
- * Returns a String descriptor entry parameter value.
- */
- int getInt(Params key, int def);
-
- /**
- * Returns a String descriptor entry parameter value.
- */
- long getLong(Params key);
-
- /**
- * Returns a String descriptor entry parameter value.
- */
- long getLong(Params key, long def);
-
- /**
- * Returns a String array descriptor entry parameter value.
- */
- String[] getStrings(Params key);
-
- /**
- * Returns a String array descriptor entry parameter value.
- */
- String[] getStrings(Params key, String[] def);
-
- /**
- * Returns a descriptor entry value which is a complex value.
- */
- Dictionary<String, Object> getDictionary(Params key, Dictionary<String, Object> def);
-
- /**
- * Modifies a key Sring value
- */
- void setString(Params key, String value);
-
- /**
- * Modifies a String[] value.
- */
- void setStrings(Params key, String[] values);
-
- /**
- * Modifies a String[] value.
- */
- void setDictionary(Params key, Dictionary<String, Object> dictionary);
-
- /**
- * Clone this MetaData object.
- */
- Object clone() throws CloneNotSupportedException;
-}
diff --git a/dependencymanager/runtime/src/main/java/org/apache/felix/dm/runtime/Params.java b/dependencymanager/runtime/src/main/java/org/apache/felix/dm/runtime/Params.java
deleted file mode 100644
index 7dbc25c..0000000
--- a/dependencymanager/runtime/src/main/java/org/apache/felix/dm/runtime/Params.java
+++ /dev/null
@@ -1,67 +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.felix.dm.runtime;
-
-/**
- * List of descriptor parameters.
- *
- * @author <a href="mailto:dev@felix.apache.org">Felix Project Team</a>
- */
-public enum Params
-{
- type,
- init,
- start,
- stop,
- destroy,
- impl,
- provides,
- properties,
- composition,
- service,
- filter,
- defaultImpl,
- required,
- added,
- changed,
- removed,
- swap,
- autoConfig,
- pid,
- propagate,
- updated,
- timeout,
- adapteeService,
- adapteeFilter,
- stateMask,
- ranking,
- factoryPid,
- factorySet,
- factoryConfigure,
- factoryMethod,
- name,
- field,
- starter,
- stopper,
- bundleContextField,
- dependencyManagerField,
- componentField,
- registered,
- unregistered
-}
diff --git a/dependencymanager/runtime/src/main/java/org/apache/felix/dm/runtime/ResourceAdapterServiceBuilder.java b/dependencymanager/runtime/src/main/java/org/apache/felix/dm/runtime/ResourceAdapterServiceBuilder.java
deleted file mode 100644
index 7174396..0000000
--- a/dependencymanager/runtime/src/main/java/org/apache/felix/dm/runtime/ResourceAdapterServiceBuilder.java
+++ /dev/null
@@ -1,74 +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.felix.dm.runtime;
-
-import java.util.Dictionary;
-import java.util.List;
-
-import org.apache.felix.dm.Component;
-import org.apache.felix.dm.DependencyManager;
-import org.osgi.framework.Bundle;
-
-/**
- * Class used to build a resource adapter service using metadata found from DependencyManager runtime
- * meta-inf descriptor.
- *
- * @author <a href="mailto:dev@felix.apache.org">Felix Project Team</a>
- */
-public class ResourceAdapterServiceBuilder extends AbstractBuilder
-{
- private final static String TYPE = "ResourceAdapterService";
-
- @Override
- public String getType()
- {
- return TYPE;
- }
-
- @Override
- public void build(MetaData srvMeta, List<MetaData> depsMeta, Bundle b, DependencyManager dm)
- throws Exception
- {
- String filter = srvMeta.getString(Params.filter, null);
- Class<?> implClass = b.loadClass(srvMeta.getString(Params.impl));
- String[] provides = srvMeta.getStrings(Params.provides, null);
- Dictionary<String, Object> properties = srvMeta.getDictionary(Params.properties, null);
- boolean propagate = "true".equals(srvMeta.getString(Params.propagate, "false"));
- String changed = srvMeta.getString(Params.changed, null /* no change callback if not specified explicitly */);
- Component c = dm.createResourceAdapterService(filter, propagate, null, changed);
- c.setInterface(provides, properties);
- String factoryMethod = srvMeta.getString(Params.factoryMethod, null);
- if (factoryMethod == null)
- {
- c.setImplementation(implClass);
- }
- else
- {
- c.setFactory(implClass, factoryMethod);
- }
- setCommonServiceParams(c, srvMeta);
- c.setComposition(srvMeta.getString(Params.composition, null));
- ServiceLifecycleHandler lfcleHandler = new ServiceLifecycleHandler(c, b, dm, srvMeta, depsMeta);
- // The dependencies will be plugged by our lifecycle handler.
- c.setCallbacks(lfcleHandler, "init", "start", "stop", "destroy");
- // Adds dependencies (except named dependencies, which are managed by the lifecycle handler).
- addUnamedDependencies(b, dm, c, srvMeta, depsMeta);
- dm.add(c);
- }
-}
diff --git a/dependencymanager/runtime/src/main/java/org/apache/felix/dm/runtime/SerialExecutor.java b/dependencymanager/runtime/src/main/java/org/apache/felix/dm/runtime/SerialExecutor.java
deleted file mode 100644
index 041e7f3..0000000
--- a/dependencymanager/runtime/src/main/java/org/apache/felix/dm/runtime/SerialExecutor.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.felix.dm.runtime;
-
-import java.util.LinkedList;
-import java.util.NoSuchElementException;
-
-/**
- * Allows you to enqueue tasks from multiple threads and then execute
- * them on one thread sequentially. It assumes more than one thread will
- * try to execute the tasks and it will make an effort to pick the first
- * task that comes along whilst making sure subsequent tasks return
- * without waiting.
- *
- * @author <a href="mailto:dev@felix.apache.org">Felix Project Team</a>
- */
-public final class SerialExecutor {
- private static final Runnable DUMMY_RUNNABLE = new Runnable() { public void run() {}; };
- private final LinkedList m_workQueue = new LinkedList();
- private Runnable m_active;
-
- /**
- * Enqueue a new task for later execution. This method is
- * thread-safe, so multiple threads can contribute tasks.
- *
- * @param runnable the runnable containing the actual task
- */
- public synchronized void enqueue(final Runnable runnable) {
- m_workQueue.addLast(new Runnable() {
- public void run() {
- try {
- runnable.run();
- }
- finally {
- scheduleNext();
- }
- }
- });
- }
-
- /**
- * Execute any pending tasks. This method is thread safe,
- * so multiple threads can try to execute the pending
- * tasks, but only the first will be used to actually do
- * so. Other threads will return immediately.
- */
- public void execute() {
- Runnable active;
- synchronized (this) {
- active = m_active;
- // for now just put some non-null value in there so we can never
- // get a race condition when two threads enter this section after
- // one another (causing sheduleNext() to be invoked twice below)
- m_active = DUMMY_RUNNABLE;
- }
- if (active == null) {
- scheduleNext();
- }
- }
-
- private void scheduleNext() {
- Runnable active;
- synchronized (this) {
- try {
- m_active = (Runnable) m_workQueue.removeFirst();
- }
- catch (NoSuchElementException e) {
- m_active = null;
- }
- active = m_active;
- }
- if (active != null) {
- active.run();
- }
- }
-}
diff --git a/dependencymanager/runtime/src/main/java/org/apache/felix/dm/runtime/ServiceLifecycleHandler.java b/dependencymanager/runtime/src/main/java/org/apache/felix/dm/runtime/ServiceLifecycleHandler.java
deleted file mode 100644
index a41358e..0000000
--- a/dependencymanager/runtime/src/main/java/org/apache/felix/dm/runtime/ServiceLifecycleHandler.java
+++ /dev/null
@@ -1,471 +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.felix.dm.runtime;
-
-import java.lang.reflect.Field;
-import java.lang.reflect.InvocationTargetException;
-import java.lang.reflect.Proxy;
-import java.util.ArrayList;
-import java.util.Dictionary;
-import java.util.Enumeration;
-import java.util.HashMap;
-import java.util.Hashtable;
-import java.util.Iterator;
-import java.util.List;
-import java.util.Map;
-import java.util.concurrent.atomic.AtomicBoolean;
-
-import org.apache.felix.dm.Component;
-import org.apache.felix.dm.Dependency;
-import org.apache.felix.dm.DependencyManager;
-import org.osgi.framework.Bundle;
-
-/**
- * Allow Services to configure dynamically their dependency filters from their init() method.
- * Basically, this class acts as a service implementation lifecycle handler. When we detect that the Service is
- * called in its init() method, and if init() returns a Map, then the Map is assumed to contain
- * dependency filters, which will be applied to all named dependencies. The Map optionally returned by
- * Service's init method may contain the following keys:
- * <ul>
- * <li>name.filter: the value must be a valid OSGi filter, and the "name" prefix must match a ServiceDependency
- * name attribute</li>
- * <li>name.required: the value is a boolean ("true"|"false") and the "name" prefix must match a
- * ServiceDependency name attribute</li>
- * </ul>
- *
- * <p>Dependencies which provide a name attribute will be activated after the init method returns. Other
- * dependencies are injected before the init method.
- *
- * <p>Example of a Service whose dependency filter is configured from ConfigAdmin:
- *
- * <blockquote><pre>
- * /**
- * * A Service whose service dependency filter/require attribute may be configured from ConfigAdmin
- * */
- * @Service
- * class X {
- * private Dictionary m_config;
- *
- * @ConfigurationDependency(pid="MyPid")
- * void configure(Dictionary conf) {
- * // Initialize our service from config ...
- *
- * // And store the config for later usage (from our init method)
- * m_config = config;
- * }
- *
- * @ServiceDependency(name="dependency1")
- * void bindOtherService(OtherService other) {
- * // the filter and required flag will be configured from our init method.
- * }
- *
- * // The returned Map will be used to configure our "dependency1" Dependency.
- * @Init
- * Map init() {
- * return new HashMap() {{
- * put("dependency1.filter", m_config.get("filter"));
- * put("dependency1.required", m_config.get("required"));
- * }};
- * }
- * }
- * </pre></blockquote>
- *
- * @author <a href="mailto:dev@felix.apache.org">Felix Project Team</a>
- */
-public class ServiceLifecycleHandler
-{
- private final String m_init;
- private final String m_start;
- private final String m_stop;
- private final String m_destroy;
- private final MetaData m_srvMeta;
- private final List<MetaData> m_depsMeta;
- private final List<Dependency> m_namedDeps = new ArrayList<Dependency>();
- private final Bundle m_bundle;
- private volatile ToggleServiceDependency m_toggle;
- private final static Object SYNC = new Object();
-
- /**
- * Makes a new ServiceLifecycleHandler object. This objects allows to decorate the "init" service callback, in
- * order to see if "init" callback returns a dependency customization map.
- *
- * @param srv The Service for the annotated class
- * @param srvBundle the Service bundle
- * @param dm The DependencyManager that was used to create the service
- * @param srvMeta The Service MetaData
- * @param depMeta The Dependencies MetaData
- */
- public ServiceLifecycleHandler(Component srv, Bundle srvBundle, DependencyManager dm,
- MetaData srvMeta, List<MetaData> depMeta)
- {
- m_srvMeta = srvMeta;
- m_init = srvMeta.getString(Params.init, null);
- m_start = srvMeta.getString(Params.start, null);
- m_stop = srvMeta.getString(Params.stop, null);
- m_destroy = srvMeta.getString(Params.destroy, null);
- m_bundle = srvBundle;
- m_depsMeta = depMeta;
- }
-
- /**
- * Handles an "init" lifecycle service callback. We just catch the "init" method, and callback
- * the actual Service' init method, to see if a dependency customization map is returned.
- * We also check if a Lifecycle Controller is used. In this case, we add a hidden custom dependency,
- * allowing to take control of when the component is actually started/stopped.
- * We also handle an edge case described in FELIX-4050, where component state calculation
- * may mess up if some dependencies are added using the API from the init method.
- *
- * @param c The Annotated Component
- */
- @SuppressWarnings({ "unchecked", "rawtypes" })
- public void init(Component c)
- throws Exception
- {
- Object serviceInstance = c.getService();
- DependencyManager dm = c.getDependencyManager();
-
- // Check if a lifecycle controller is defined for this service. If true, then
- // We'll use the ToggleServiceDependency in order to manually activate/deactivate
- // the component ...
- String starter = m_srvMeta.getString(Params.starter, null);
- String stopper = m_srvMeta.getString(Params.stopper, null);
-
- if (starter != null)
- {
- // We'll inject two runnables: one that will start or service, when invoked, and the other
- // that will stop our service, when invoked. We'll use a shared atomic boolean in order to
- // synchronize both runnables.
- Log.instance().debug("Setting up a lifecycle controller for service %s", serviceInstance);
- String componentName = serviceInstance.getClass().getName();
- // Create a toggle service, used to start/stop our service.
- m_toggle = new ToggleServiceDependency();
- AtomicBoolean startFlag = new AtomicBoolean(false);
- // Add the toggle to the service (we'll remove it from our destroy emthod).
- c.add(m_toggle);
- // Inject the runnable that will start our service, when invoked.
- setField(serviceInstance, starter, Runnable.class, new ComponentStarter(componentName, m_toggle, startFlag));
- if (stopper != null) {
- // Inject the runnable that will stop our service, when invoked.
- setField(serviceInstance, stopper, Runnable.class, new ComponentStopper(componentName, m_toggle, startFlag));
- }
- }
-
- // Before invoking an optional init method, we have to handle an edge case (FELIX-4050), where
- // init may add dependencies using the API and also return a map for configuring some
- // named dependencies. We have to add a hidden toggle dependency in the component, which we'll
- // active *after* the init method is called, and possibly *after* named dependencies are configured.
-
- ToggleServiceDependency initToggle = null;
- if (m_init != null)
- {
- initToggle = new ToggleServiceDependency();
- c.add(initToggle);
- }
-
- // Invoke component and all composites init methods, and for each one, check if a dependency
- // customization map is returned by the method. This map will be used to configure
- // some dependency filters (or required flag).
-
- Map<String, String> customization = new HashMap<String, String>();
- Object[] composites = c.getCompositionInstances();
- for (Object composite: composites)
- {
- Object o = invokeMethod(composite, m_init, dm, c);
- if (o != null && Map.class.isAssignableFrom(o.getClass()))
- {
- customization.putAll((Map) o);
- }
- }
-
- Log.instance().debug("ServiceLifecycleHandler.init: invoked init method from service %s " +
- ", returned map: %s", serviceInstance, customization);
-
- // Apply name dependency filters possibly returned by the init() method.
-
- for (MetaData dependency: m_depsMeta)
- {
- // Check if this dependency has a name, and if we find the name from the
- // customization map, then apply filters and required flag from the map into it.
-
- String name = dependency.getString(Params.name, null);
- if (name != null)
- {
- String filter = customization.get(name + ".filter");
- String required = customization.get(name + ".required");
-
- if (filter != null || required != null)
- {
- dependency = (MetaData) dependency.clone();
- if (filter != null)
- {
- dependency.setString(Params.filter, filter);
- }
- if (required != null)
- {
- dependency.setString(Params.required, required);
- }
- }
-
- DependencyBuilder depBuilder = new DependencyBuilder(dependency);
- Log.instance().info("ServiceLifecycleHandler.init: adding dependency %s into service %s",
- dependency, m_srvMeta);
- Dependency d = depBuilder.build(m_bundle, dm, true);
- m_namedDeps.add(d);
- }
- }
-
- // Add all extra dependencies in one shot, in order to calculate state changes for all dependencies at a time.
- if (m_namedDeps.size() > 0)
- {
- Log.instance().info("ServiceLifecycleHandler.init: adding extra/named dependencies %s",
- m_namedDeps);
- c.add(m_namedDeps);
- }
-
- // init method fully handled, and all possible named dependencies have been configured. Now, activate the
- // hidden toggle, and then remove it from the component, because we don't need it anymore.
- if (initToggle != null)
- {
- initToggle.setAvailable(true);
- c.remove(initToggle);
- }
- }
-
- /**
- * Handles the Service's start lifecycle callback. We just invoke the service "start" service callback on
- * the service instance, as well as on all eventual service composites.
- * We take care to check if a start callback returns a Map, which is meant to contain
- * some additional properties which must be appended to existing service properties.
- * Such extra properties takes precedence over existing service properties.
- */
- @SuppressWarnings({ "unchecked", "rawtypes" })
- public void start(Component service)
- throws IllegalArgumentException, IllegalAccessException, InvocationTargetException
- {
- // Check if some extra service properties are returned by start method.
-
- DependencyManager dm = service.getDependencyManager();
- Map<String, String> extraProperties = new HashMap<String, String>();
- Object[] composites = service.getCompositionInstances();
- for (Object composite: composites)
- {
- Object o = invokeMethod(composite, m_start, dm, service);
- if (o != null && Map.class.isAssignableFrom(o.getClass()))
- {
- extraProperties.putAll((Map) o);
- }
- }
-
- if (extraProperties.size() > 0)
- {
- // Store extra properties returned by start callbacks into existing service properties
- Dictionary existingProperties = service.getServiceProperties();
- if (existingProperties != null)
- {
- Hashtable props = new Hashtable();
- Enumeration e = existingProperties.keys();
- while (e.hasMoreElements())
- {
- Object key = e.nextElement();
- props.put(key, existingProperties.get(key));
- }
- props.putAll(extraProperties);
- service.setServiceProperties(props);
- }
- else
- {
- service.setServiceProperties(new Hashtable(extraProperties));
- }
- }
-
- // Remove "instance bound" flag from all dependencies, because we want to be deactivated
- // once we lose one of our named dependencies (which are instance bound dependencies).
-
- Iterator it = m_namedDeps.iterator();
- while (it.hasNext())
- {
- Dependency d = (Dependency) it.next();
- try
- {
- InvocationUtil.invokeCallbackMethod(d, "setInstanceBound",
- new Class[][] { { Boolean.TYPE }, {} },
- new Object[][] { { Boolean.FALSE }, {} });
- }
- catch (NoSuchMethodException e)
- {
- Log.instance().error("Lifecycle handler could not reset instanceBound of dependency: %s", e, d);
- }
- }
- }
-
- /**
- * Handles the Service's stop lifecycle callback. We just invoke the service "stop" callback on
- * the service instance, as well as on all eventual service composites.
- */
- public void stop(Component service)
- throws IllegalArgumentException, IllegalAccessException, InvocationTargetException
- {
- callbackComposites(service, m_stop);
- }
-
- /**
- * Handles the Service's destroy lifecycle callback. We just invoke the service "destroy" callback on
- * the service instance, as well as on all eventual service composites.
- */
- public void destroy(Component service)
- throws IllegalArgumentException, IllegalAccessException, InvocationTargetException
- {
- // Clear named dependencies eventuall returned by our service init callback.
- m_namedDeps.clear();
- if (m_toggle != null)
- {
- // If we created a toggle for our service, just remove it from the service.
- service.remove(m_toggle);
- m_toggle = null;
- }
- callbackComposites(service, m_destroy);
- }
-
- /**
- * Invoke a callback on all Service compositions.
- */
- private void callbackComposites(Component service, String callback)
- throws IllegalArgumentException, IllegalAccessException, InvocationTargetException
- {
- Object[] composites = service.getCompositionInstances();
- for (Object composite: composites)
- {
- invokeMethod(composite, callback, service.getDependencyManager(), service);
- }
- }
-
- /**
- * Invoke a callback on an Object instance.
- */
- private Object invokeMethod(Object serviceInstance, String method, DependencyManager dm, Component c)
- throws IllegalArgumentException, IllegalAccessException, InvocationTargetException
- {
- if (method != null)
- {
- try
- {
- return InvocationUtil.invokeCallbackMethod(serviceInstance, method,
- new Class[][] { { Component.class }, {} },
- new Object[][] { { c }, {} }
- );
- }
-
- catch (NoSuchMethodException e)
- {
- // ignore this
- }
-
- // Other exception will be thrown up to the ServiceImpl.invokeCallbackMethod(), which is
- // currently invoking our method. So, no need to log something here, since the invokeCallbackMethod
- // method is already logging any thrown exception.
- }
- return null;
- }
-
- /**
- * Sets a field of an object by reflexion.
- */
- private void setField(Object instance, String fieldName, Class<?> fieldClass, Object fieldValue)
- {
- Object serviceInstance = instance;
- Class<?> serviceClazz = serviceInstance.getClass();
- if (Proxy.isProxyClass(serviceClazz))
- {
- serviceInstance = Proxy.getInvocationHandler(serviceInstance);
- serviceClazz = serviceInstance.getClass();
- }
- while (serviceClazz != null)
- {
- Field[] fields = serviceClazz.getDeclaredFields();
- for (int j = 0; j < fields.length; j++)
- {
- Field field = fields[j];
- Class<?> type = field.getType();
- if (field.getName().equals(fieldName) && type.isAssignableFrom(fieldClass))
- {
- try
- {
- field.setAccessible(true);
- // synchronized makes sure the field is actually written to immediately
- synchronized (SYNC)
- {
- field.set(serviceInstance, fieldValue);
- }
- }
- catch (Throwable e)
- {
- throw new RuntimeException("Could not set field " + field, e);
- }
- }
- }
- serviceClazz = serviceClazz.getSuperclass();
- }
- }
-
- private static class ComponentStarter implements Runnable {
- private final String m_componentName;
- private final ToggleServiceDependency m_toggle;
- private final AtomicBoolean m_startFlag;
-
- public ComponentStarter(String name, ToggleServiceDependency toggle, AtomicBoolean startFlag)
- {
- m_componentName = name;
- m_toggle = toggle;
- m_startFlag = startFlag;
- }
-
- @SuppressWarnings("synthetic-access")
- public void run()
- {
- if (m_startFlag.compareAndSet(false, true)) {
- Log.instance().debug("Lifecycle controller is activating the component %s",
- m_componentName);
- m_toggle.setAvailable(true);
- }
- }
- }
-
- private static class ComponentStopper implements Runnable {
- private final Object m_componentName;
- private final ToggleServiceDependency m_toggle;
- private final AtomicBoolean m_startFlag;
-
- public ComponentStopper(String componentName, ToggleServiceDependency toggle, AtomicBoolean startFlag)
- {
- m_componentName = componentName;
- m_toggle = toggle;
- m_startFlag = startFlag;
- }
-
- @SuppressWarnings("synthetic-access")
- public void run()
- {
- if (m_startFlag.compareAndSet(true, false)) {
- Log.instance().debug("Lifecycle controller is deactivating the component %s",
- m_componentName);
- m_toggle.setAvailable(false);
- }
- }
- }
-}
diff --git a/dependencymanager/runtime/src/main/java/org/apache/felix/dm/runtime/ToggleServiceDependency.java b/dependencymanager/runtime/src/main/java/org/apache/felix/dm/runtime/ToggleServiceDependency.java
deleted file mode 100644
index b2505f9..0000000
--- a/dependencymanager/runtime/src/main/java/org/apache/felix/dm/runtime/ToggleServiceDependency.java
+++ /dev/null
@@ -1,176 +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.felix.dm.runtime;
-
-import java.util.ArrayList;
-import java.util.Dictionary;
-import java.util.List;
-
-import org.apache.felix.dm.Dependency;
-import org.apache.felix.dm.DependencyActivation;
-import org.apache.felix.dm.DependencyService;
-
-/**
- * This is a custom DependencyManager Dependency, allowing to take control of when the dependency
- * is available or not. It's used in the context of the LifecycleController class, in order to
- * activate/deactivate a Component on demand.
- *
- * @author <a href="mailto:dev@felix.apache.org">Felix Project Team</a>
- */
-public class ToggleServiceDependency implements Dependency, DependencyActivation
-{
- private final List<Object> m_services = new ArrayList<Object>();
- private volatile boolean m_isAvailable;
- private volatile boolean m_stopped;
-
- public ToggleServiceDependency()
- {
- }
-
- public ToggleServiceDependency(boolean isAvailable)
- {
- m_isAvailable = isAvailable;
- }
-
- public void setAvailable(boolean isAvailable)
- {
- synchronized (this)
- {
- if (m_stopped)
- {
- return;
- }
- boolean changed = m_isAvailable != isAvailable;
- m_isAvailable = isAvailable;
-
- if (! changed) {
- return;
- }
- }
-
- // invoked on every change
- if (m_isAvailable)
- {
- Object[] services = m_services.toArray();
- for (int i = 0; i < services.length; i++)
- {
- DependencyService ds = (DependencyService) services[i];
- ds.dependencyAvailable(this);
- if (!isRequired())
- {
- invokeAdded(ds);
- }
- }
- }
- else
- {
- Object[] services = m_services.toArray();
- for (int i = 0; i < services.length; i++)
- {
- DependencyService ds = (DependencyService) services[i];
- ds.dependencyUnavailable(this);
- if (!isRequired())
- {
- invokeRemoved(ds);
- }
- }
- }
- }
-
- public Dependency createCopy()
- {
- return new ToggleServiceDependency(m_isAvailable);
- }
-
- public Object getAutoConfigInstance()
- {
- return "" + m_isAvailable;
- }
-
- public String getAutoConfigName()
- {
- return null;
- }
-
- public Class<?> getAutoConfigType()
- {
- return String.class;
- }
-
- @SuppressWarnings("unchecked")
- public Dictionary getProperties()
- {
- return null;
- }
-
- public void invokeAdded(DependencyService service)
- {
- }
-
- public void invokeRemoved(DependencyService service)
- {
- }
-
- public void invoke(DependencyService dependencyService, String name)
- {
- }
-
- public boolean isAutoConfig()
- {
- return false;
- }
-
- public boolean isAvailable()
- {
- return m_isAvailable;
- }
-
- public boolean isInstanceBound()
- {
- return true;
- }
-
- public boolean isPropagated()
- {
- return false;
- }
-
- public boolean isRequired()
- {
- return true;
- }
-
- public void start(DependencyService service)
- {
- synchronized (this)
- {
- m_services.add(service);
- m_stopped = false;
- }
- }
-
- public void stop(DependencyService service)
- {
- synchronized (this)
- {
- m_services.remove(service);
- m_stopped = true;
- }
- }
-}
diff --git a/dependencymanager/samples.annotation/LICENSE b/dependencymanager/samples.annotation/LICENSE
deleted file mode 100644
index d645695..0000000
--- a/dependencymanager/samples.annotation/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/dependencymanager/samples.annotation/NOTICE b/dependencymanager/samples.annotation/NOTICE
deleted file mode 100644
index cfc3633..0000000
--- a/dependencymanager/samples.annotation/NOTICE
+++ /dev/null
@@ -1,26 +0,0 @@
-Apache Felix Dependency Manager
-Copyright 2009 The Apache Software Foundation
-
-
-I. Included Software
-
-This product includes software developed at
-The Apache Software Foundation (http://www.apache.org/).
-Licensed under the Apache License 2.0.
-
-This product includes software developed at
-The OSGi Alliance (http://www.osgi.org/).
-Copyright (c) OSGi Alliance (2000, 2007).
-Licensed under the Apache License 2.0.
-
-
-II. Used Software
-
-This product uses software developed at
-The OSGi Alliance (http://www.osgi.org/).
-Copyright (c) OSGi Alliance (2000, 2007).
-Licensed under the Apache License 2.0.
-
-
-III. License Summary
-- Apache License 2.0
diff --git a/dependencymanager/samples.annotation/README b/dependencymanager/samples.annotation/README
deleted file mode 100644
index 000d7e7..0000000
--- a/dependencymanager/samples.annotation/README
+++ /dev/null
@@ -1,209 +0,0 @@
-This sample illustrates the usage of the new DependencyManager annotations.
-
-Sample description:
-==================
-
-This sample shows a basic "SpellChecker" application which provides a Felix "spellcheck" GOGO shell
-command. The GOGO "spellcheck" command accepts a string as parameter, which is checked for proper
-existence. The SpellChecker class has a required/multiple (1..N) dependency over every available
-"DictionaryService" services, which are internally used by the SpellChecker command, when checking
-word existence.
-
-A DictionaryService is defined using a FactoryConfigurationAdapterService annotation, allowing to
-instantiate many "DictionaryService" instances from webconsole. This annotation actually registers a
-ManagedServiceFactory into the Registry, and you can specify some meta type informations in the
-annotation, allowing to configure the DictionaryService words and language from WebConsole. Each
-time you instantiate a factory configuration whose factory pid equals "DictionaryImplFactoryPid",
-in the webconsole "Dictionary Services" configuration section, then a corresponding "DictionaryImpl"
-component is instantiated and is then injected into the SpellChecker service. So, before testing,
-you first have to go to webconsole Configuration panel, and specify some dictionaries (see the
-"Dictionary Services" section). Then, go to the felix GOGO shell, and you will then see the
-"spellcheck" command (when typing "help").
-
-Notice that in the sample, you will also find a DictionaryAspect Service (DictionaryAspect.java),
-which decorates the EnglishDictionary service, by adding some additional words to it.
-
-How to test:
-===========
-
-1) Install the following bundles (with same or higher version):
-
- org.apache.felix.configadmin-1.2.8.jar
- org.apache.felix.metatype-1.0.4.jar
- org.apache.felix.http.jetty-2.2.0.jar
- org.apache.felix.webconsole-3.1.8.jar
- org.apache.felix.shell-1.4.2.jar
- org.apache.felix.dependencymanager-3.0.0.jar
- org.apache.felix.dependencymanager.shell-3.0.0.jar
- org.apache.felix.dependencymanager.runtime-3.0.0.jar
- org.apache.felix.log-1.0.1.jar (optional)
-
-2) compile dependency manager sample.annotation from trunk:
-
- svn checkout http://svn.apache.org/repos/asf/felix/trunk/dependencymanager dependencymanager
- cd dependencymanager/sample.annotation
- mvn clean install
-
-Then install ./target/org.apache.felix.dependencymanager.samples.annotation-3.0.0-SNAPSHOT.jar into
-felix.
-
-3) Start felix
-
-At this point, you should have the following running bundles:
-
-g! lb
-START LEVEL 1
- ID|State |Level|Name
- 0|Active | 0|System Bundle (3.2.1)
- 1|Active | 1|Apache Felix Bundle Repository (1.6.2)
- 2|Active | 1|Apache Felix Configuration Admin Service (1.2.8)
- 3|Active | 1|Apache Felix Dependency Manager (3.0.0)
- 4|Active | 1|Apache Felix Dependency Manager Runtime (3.0.0)
- 5|Active | 1|Apache Felix Dependency Manager Annotation Sample (3.0.0.SNAPSHOT)
- 6|Active | 1|Apache Felix Dependency Manager Shell (3.0.0)
- 7|Active | 1|Apache Felix Gogo Command (0.8.0)
- 8|Active | 1|Apache Felix Gogo Runtime (0.8.0)
- 9|Active | 1|Apache Felix Gogo Shell (0.8.0)
- 10|Active | 1|Apache Felix Http Jetty (2.2.0)
- 11|Active | 1|Apache Felix Log Service (1.0.1)
- 12|Active | 1|Apache Felix Metatype Service (1.0.4)
- 13|Active | 1|Apache Felix Shell Service (1.4.2)
- 14|Active | 1|Apache Felix Web Management Console (3.1.8)
-
-4) Inspect Dependency Manager components from gogo shell:
-
-type "dm 5" for browsing the components for the bundle id 5
-
-[5] org.apache.felix.dependencymanager.samples.annotation
- org.osgi.service.cm.ManagedServiceFactory(service.pid=DictionaryImplFactoryPid) registered
- org.osgi.service.log.LogService service optional available
- org.apache.felix.dm.samples.annotation.SpellChecker(osgi.command.function={spellcheck},osgi.command.scope=dmsample.annotation) unregistered
- org.apache.felix.dm.samples.annotation.DictionaryService service required unavailable
- org.osgi.service.log.LogService service optional unavailable
- org.apache.felix.dm.impl.AspectServiceImpl$AspectImpl@4d76b4 unregistered
- org.apache.felix.dm.samples.annotation.DictionaryService (&(!(org.apache.felix.dependencymanager.aspect=*))(lang=en)) service optional unavailable
- DictionaryAspectPID configuration required unavailable
- org.osgi.service.log.LogService service optional unavailable
-
-Here, the bundle [5] corresponds to our annotation.sample bundle. In this bundle, we have three
-components:
-
-* org.osgi.service.cm.ManagedServiceFactory: this is the service DM has internally registered in
- order to be able to instantiate some of our "DictionaryImpl" component instances from config
- admin (using the factory pid "DictionaryImplFactoryPid"). See DictionaryImpl.java and especially
- the @FactoryConfigurationAdapterService annotation. The component depends on the log service
- because our "DictionaryImpl" component also depends on the log service. The ManagedServiceFactory
- is actually depending on all dependencies defined in our "DictionaryImpl" component, and those
- dependencies will be applied on each instantiated DictionaryImpl component instances.
-
-* org.apache.felix.dm.samples.annotation.SpellChecker: This is our "SpellChecker" component exposing
- two services properties: "osgi.command.function" (the gogo shell method name), and
- "osgi.command.scope" (the gogo command scope).
- It also has two dependencies: "org.apache.felix.dm.samples.annotation.DictionaryService", and
- "org.osgi.service.log.LogService".
-
-* org.apache.felix.dm.impl.AspectServiceImpl$AspectImpl: this is also an internal service registered
- by dependency manager, in order to instantiate our "DictionaryAspect" interceptor service. See
- DictionaryAspect.java. The aspect impl depends on the three dependencies (which are initially
- defined in DictionaryAspect.java):
-
- - org.apache.felix.dm.samples.annotation.DictionaryService: this is the service our DictionaryAspect
- is intercepting. The AspectServiceImpl$AspectImpl will create a DictionaryAspect instance for
- every DictionaryService found from the OSGi registry (that is, for every DictionaryService you
- create from web console "Dictionary Services" configuraton section).
-
- - DictionaryAspectPID configuration: this is the config pid our DictionaryAspect is depending on (see
- @ConfigurationDependency in DictionaryAspect.java).
-
- - org.osgi.service.log.LogService: the DictionaryAspect is optionally depending on the log service
- (a null object is used if there is no one).
-
-So, when a DictionaryService will come up, the AspectServiceImpl component will instantiate a
-corresponding "DictionaryAspect" instance, with all the dependencies defined in DictionaryAspect.
-
-5) Create a DictionaryService from web console:
-
-Go to web console: in the Configuration panel, edit the "Dictionary Services" Configuration, and add
-some dictionaries. By default, an English dictionary is displayed. Just click on "save", *then click
-on your refresh web browser*: you will see a new dictionary service instance. At this point, a
-"DictionaryImpl" component instance will be create (with the service property "lang=en"), and the
-SpellCheck component will be injected with it (the DictionaryImpl implements
-DictionaryService). Then you should see the "spellcheck" command, when typing "help" on the gogo
-shell.
-
-6) test the spellchecker under gogo shell:
-
-Just type "spellcheck hello", and the command should reply a fantastic message, like "word hello is
-correct".
-
-7) Inspect again DependencyManager components from the shell:
-
-Type again "dm 5", for browsing the components coming from our bundle id 5:
-
-[5] org.apache.felix.dependencymanager.samples.annotation
- org.osgi.service.cm.ManagedServiceFactory(service.pid=DictionaryImplFactoryPid) registered
- org.osgi.service.log.LogService service optional available
- org.apache.felix.dm.samples.annotation.SpellChecker(osgi.command.function={spellcheck},osgi.command.scope=dmsample.annotation) registered
- org.apache.felix.dm.samples.annotation.DictionaryService service required available
- org.osgi.service.log.LogService service optional available
- org.apache.felix.dm.impl.AspectServiceImpl$AspectImpl@128edf2 unregistered
- org.apache.felix.dm.samples.annotation.DictionaryService (&(!(org.apache.felix.dependencymanager.aspect=*))(lang=en)) service optional unavailable
- DictionaryAspectPID configuration required unavailable
- org.osgi.service.log.LogService service optional unavailable
- org.apache.felix.dm.samples.annotation.DictionaryService(service.pid=DictionaryImplFactoryPid.e01b70ff-d2b5-4305-9e86-84c68a2fddbb,service.factoryPid=DictionaryImplFactoryPid,lang=en) registered
- org.osgi.service.log.LogService service optional available
-
-Here, you can see the following:
-
-* the org.osgi.service.cm.ManagedServiceFactory with factory pid "DictionaryImplFactoryPid" is now
- registered, because we have created a dictionary from config admin (in the Dictionary Services"
- webconsole configuration section).
-
-* the SpellChecker is now "registered" because it has been injected with the DictionaryImpl we have
- created from webconsole.
-
-* the AspectServiceImpl$AspectImpl is not yet registered because we still have to instantiate a
- configuration from webconsole for the "DictionaryAspectPID" PID: this configuration is required to
- instance our DictionaryAspect component (see the @ConfigurationDependency annotation in
- DictionaryAspect.java).
-
-* One instance of the DictionaryService component is now registered (this instance corresponds to
- what we just configured from webconsole, in the "Dictionary Services" section).
-
-8) Finally, activate the "Aspect Dictionary" component:
-
-To do so, you can click on the "Aspect Dictionary" button, from web console Configuration section,
-in order to decorate the english dictionary with some custom words. By default, the "aspect" word is
-pre configured, but you can click on the "+" button in order to add more words. Then click on
-Save. At this point, the English DictionaryService will be decorated with the aspect service. So,
-now, if you type "spellcheck aspect", then the message: "word aspect is correct" should be
-displayed. What is going on is that the original DictionaryService will be replaced by the
-DictionaryAspect, using a higher service.ranking (ranking 10, see DictionaryAspect.java). So the
-spell checker will be transparently re-injected with the DictionayAspect, which is from his side
-depending on the originial DictionaryService.
-
-So, if you type "dm 5", you will know see two DictionaryService instances:
-
- org.apache.felix.dm.samples.annotation.DictionaryService(service.pid=DictionaryImplFactoryPid.8390ad56-b2de-4414-9123-29c65c42e5b9,service.factoryPid=DictionaryImplFactoryPid,lang=en) registered
- org.osgi.service.log.LogService service optional available
-
- org.apache.felix.dm.samples.annotation.DictionaryService(service.pid=DictionaryImplFactoryPid.8390ad56-b2de-4414-9123-29c65c42e5b9,service.ranking=10,service.factoryPid=DictionaryImplFactoryPid,org.apache.felix.dependencymanager.aspect=57,lang=en) registered
- org.apache.felix.dm.samples.annotation.DictionaryService (&(|(!(service.ranking=*))(service.ranking<=9))(|(service.id=57)(org.apache.felix.dependencymanager.aspect=57))) service required available
- DictionaryAspectPID configuration required available
- org.osgi.service.log.LogService service optional available
-
-The first one is the original DictionaryService we have created using the factory pid
-"DictionaryImplFactoryPid" from web console. By default, the ranking of this service is 0.
-
-Next, you see the new DictionaryService which corresponds to our DictionaryAspect service. It has
-the following properties:
-
-* it has inherited from all service properties found from the original intercepted DictionarService.
-* it has a higher service ranking than the original one (see service.ranking=10). This ranking is
- actually defined in DictionaryAspect.java, in the @Aspect annotation.
-* it has a dependency over the original DictionaryService (using an appropriate filter).
-* it also inherits from all dependencies originally defined in the DictionaryImpl component
-
-
-
-
diff --git a/dependencymanager/samples.annotation/directives.bnd b/dependencymanager/samples.annotation/directives.bnd
deleted file mode 100644
index dc246ef..0000000
--- a/dependencymanager/samples.annotation/directives.bnd
+++ /dev/null
@@ -1,5 +0,0 @@
-Bundle-Name: Apache Felix Dependency Manager Annotation Sample
-Bundle-SymbolicName: org.apache.felix.dependencymanager.samples.annotation
-Import-Package: *
-Private-Package: org.apache.felix.dm.samples.annotation
--plugin org.apache.felix.dm.annotation.plugin.bnd.AnnotationPlugin;log=warn
diff --git a/dependencymanager/samples.annotation/pom.xml b/dependencymanager/samples.annotation/pom.xml
deleted file mode 100644
index babe3c7..0000000
--- a/dependencymanager/samples.annotation/pom.xml
+++ /dev/null
@@ -1,81 +0,0 @@
-<?xml version="1.0"?>
-<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.felix</groupId>
- <artifactId>felix-parent</artifactId>
- <version>1.2.0</version>
- <relativePath>../../pom/pom.xml</relativePath>
- </parent>
- <properties>
- <osgi.version>4.2.0</osgi.version>
- </properties>
- <name>Apache Felix Dependency Manager Annotation Samples</name>
- <artifactId>org.apache.felix.dependencymanager.samples.annotation</artifactId>
- <version>3.2.1-SNAPSHOT</version>
- <packaging>bundle</packaging>
- <dependencies>
- <dependency>
- <groupId>org.osgi</groupId>
- <artifactId>org.osgi.core</artifactId>
- <version>${osgi.version}</version>
- </dependency>
- <dependency>
- <groupId>org.osgi</groupId>
- <artifactId>org.osgi.compendium</artifactId>
- <version>${osgi.version}</version>
- </dependency>
- <dependency>
- <groupId>${project.groupId}</groupId>
- <artifactId>org.apache.felix.dependencymanager.annotation</artifactId>
- <version>3.2.0</version>
- </dependency>
- <dependency>
- <groupId>${project.groupId}</groupId>
- <artifactId>org.apache.felix.gogo.runtime</artifactId>
- <version>0.6.0</version>
- </dependency>
- </dependencies>
- <build>
- <plugins>
- <plugin>
- <groupId>org.apache.maven.plugins</groupId>
- <artifactId>maven-compiler-plugin</artifactId>
- <configuration>
- <source>1.5</source>
- <target>1.5</target>
- </configuration>
- </plugin>
- <plugin>
- <groupId>org.apache.felix</groupId>
- <artifactId>maven-bundle-plugin</artifactId>
- <version>2.3.7</version>
- <extensions>true</extensions>
- <configuration>
- <instructions>
- <Bundle-Name>Apache Felix Dependency Manager Annotation Sample</Bundle-Name>
- <Bundle-SymbolicName>org.apache.felix.dependencymanager.samples.annotation</Bundle-SymbolicName>
- <Import-Package>org.apache.felix.service.command;status=provisional,*</Import-Package>
- <Private-Package>org.apache.felix.dm.samples.annotation</Private-Package>
- </instructions>
- </configuration>
- </plugin>
- <plugin>
- <groupId>org.apache.felix</groupId>
- <artifactId>org.apache.felix.dependencymanager.annotation</artifactId>
- <version>3.2.0</version>
- <executions>
- <execution>
- <goals>
- <goal>scan</goal>
- </goals>
- <configuration>
- <log>debug</log>
- <!-- generated-output-dir>.</generated-output-dir>-->
- </configuration>
- </execution>
- </executions>
- </plugin>
- </plugins>
- </build>
-</project>
diff --git a/dependencymanager/samples.annotation/src/main/java/org/apache/felix/dm/samples/annotation/DictionaryAspect.java b/dependencymanager/samples.annotation/src/main/java/org/apache/felix/dm/samples/annotation/DictionaryAspect.java
deleted file mode 100644
index 76914f0..0000000
--- a/dependencymanager/samples.annotation/src/main/java/org/apache/felix/dm/samples/annotation/DictionaryAspect.java
+++ /dev/null
@@ -1,106 +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.felix.dm.samples.annotation;
-
-import java.util.Dictionary;
-import java.util.concurrent.CopyOnWriteArrayList;
-
-import org.apache.felix.dm.annotation.api.AspectService;
-import org.apache.felix.dm.annotation.api.PropertyMetaData;
-import org.apache.felix.dm.annotation.api.ConfigurationDependency;
-import org.apache.felix.dm.annotation.api.ServiceDependency;
-import org.apache.felix.dm.annotation.api.Start;
-import org.osgi.service.log.LogService;
-
-/**
- * This aspect applies to the English DictionaryService, and allows to decorate it with some
- * custom English words, which are configurable from WebConsole.
- */
-@AspectService(ranking = 10, filter = "(lang=en)")
-public class DictionaryAspect implements DictionaryService
-{
- /**
- * This is the service this aspect is applying to.
- */
- private volatile DictionaryService m_originalDictionary;
-
- /**
- * We store all configured words in a thread-safe data structure, because ConfigAdmin may
- * invoke our updated method at any time.
- */
- private CopyOnWriteArrayList<String> m_words = new CopyOnWriteArrayList<String>();
-
- /**
- * We'll use the OSGi log service for logging. If no log service is available, then we'll
- * use a NullObject.
- */
- @ServiceDependency(required = false)
- private LogService m_log;
-
- /**
- * Defines a configuration dependency for retrieving our english custom words (by default,
- * our PID is our full class name).
- */
- @ConfigurationDependency(
- pid="DictionaryAspectPID",
- propagate = false,
- heading = "Aspect Dictionary",
- description = "Declare here some additional english words",
- metadata = {
- @PropertyMetaData(heading = "Dictionary aspect words",
- description = "Declare here the list of english words to be added into the default english dictionary",
- defaults = { "aspect" },
- id = "words",
- cardinality = Integer.MAX_VALUE)
- }
- )
- protected void updated(Dictionary<String, ?> config)
- {
- m_words.clear();
- String[] words = (String[]) config.get("words");
- for (String word : words)
- {
- m_words.add(word);
- }
- }
-
- /**
- * Our Aspect Service is starting and is about to be registered in the OSGi regsitry.
- */
- @Start
- protected void start()
- {
- m_log.log(LogService.LOG_INFO, "Starting aspect Dictionary with words: " + m_words
- + "; original dictionary service=" + m_originalDictionary);
- }
-
- /**
- * Checks if a word is found from our custom word list. if not, delegate to the decorated
- * dictionary.
- */
- public boolean checkWord(String word)
- {
- m_log.log(LogService.LOG_INFO, "DictionaryAspect: checking word " + word
- + " (original dictionary=" + m_originalDictionary + ")");
- if (m_words.contains(word))
- {
- return true;
- }
- return m_originalDictionary.checkWord(word);
- }
-
- public String toString()
- {
- return "DictionaryAspect: words=" + m_words + "; original dictionary="
- + m_originalDictionary;
- }
-}
diff --git a/dependencymanager/samples.annotation/src/main/java/org/apache/felix/dm/samples/annotation/DictionaryImpl.java b/dependencymanager/samples.annotation/src/main/java/org/apache/felix/dm/samples/annotation/DictionaryImpl.java
deleted file mode 100644
index 313241f..0000000
--- a/dependencymanager/samples.annotation/src/main/java/org/apache/felix/dm/samples/annotation/DictionaryImpl.java
+++ /dev/null
@@ -1,122 +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.felix.dm.samples.annotation;
-
-import java.util.Dictionary;
-import java.util.concurrent.CopyOnWriteArrayList;
-
-import org.apache.felix.dm.annotation.api.PropertyMetaData;
-import org.apache.felix.dm.annotation.api.FactoryConfigurationAdapterService;
-import org.apache.felix.dm.annotation.api.ServiceDependency;
-import org.apache.felix.dm.annotation.api.Start;
-import org.osgi.service.log.LogService;
-
-/**
- * A Dictionary Service. This service uses a FactoryConfigurationAdapterService annotation,
- * allowing to instantiate this service from webconsole. This annotation will actually register
- * a ManagedServiceFactory in the registry, and also supports meta types for configuring this
- * service from WebConsole.
- *
- * You must configure at least one Dictionary from web console, since the SpellCheck won't start if no Dictionary
- * Service is available.
- */
-@FactoryConfigurationAdapterService(
- factoryPid="DictionaryImplFactoryPid",
- propagate=true,
- updated="updated",
- heading="Dictionary Services",
- description="Declare here some Dictionary instances, allowing to instantiates some DictionaryService services for a given dictionary language",
- metadata={
- @PropertyMetaData(
- heading="Dictionary Language",
- description="Declare here the language supported by this dictionary. " +
- "This property will be propagated with the Dictionary Service properties.",
- defaults={"en"},
- id="lang",
- cardinality=0),
- @PropertyMetaData(
- heading="Dictionary words",
- description="Declare here the list of words supported by this dictionary. This properties starts with a Dot and won't be propagated with Dictionary OSGi service properties.",
- defaults={"hello", "world"},
- id=DictionaryImpl.WORDS,
- cardinality=Integer.MAX_VALUE)
- }
-)
-public class DictionaryImpl implements DictionaryService
-{
- /**
- * The key of our config admin dictionary values. This key stats with a "." (dot), meaning
- * that this property won't be propagated along with our OSGi service properties.
- */
- final static String WORDS = ".words";
-
- /**
- * We store all configured words in a thread-safe data structure, because ConfigAdmin
- * may invoke our updated method at any time.
- */
- private CopyOnWriteArrayList<String> m_words = new CopyOnWriteArrayList<String>();
-
- /**
- * We'll use the OSGi log service for logging. If no log service is available, then we'll use a NullObject.
- */
- @ServiceDependency(required = false)
- private LogService m_log;
-
- /**
- * Our Dictionary language.
- */
- private String m_lang;
-
- /**
- * Our service will be initialized from ConfigAdmin.
- * @param config The configuration where we'll lookup our words list (key=".words").
- */
- protected void updated(Dictionary<String, ?> config) {
- m_lang = (String) config.get("lang");
- m_words.clear();
- String[] words = (String[]) config.get(WORDS);
- for (String word : words) {
- m_words.add(word);
- }
- }
-
- /**
- * A new Dictionary Service is starting (because a new factory configuration has been created
- * from webconsole).
- */
- @Start
- protected void start()
- {
- m_log.log(LogService.LOG_INFO, "Starting Dictionary Service with language: " + m_lang);
- }
-
- /**
- * Check if a word exists if the list of words we have been configured from ConfigAdmin/WebConsole.
- */
- public boolean checkWord(String word)
- {
- return m_words.contains(word);
- }
-
- @Override
- public String toString()
- {
- return "Dictionary: language=" + m_lang + ", words=" + m_words;
- }
-}
diff --git a/dependencymanager/samples.annotation/src/main/java/org/apache/felix/dm/samples/annotation/DictionaryService.java b/dependencymanager/samples.annotation/src/main/java/org/apache/felix/dm/samples/annotation/DictionaryService.java
deleted file mode 100644
index da34e5e..0000000
--- a/dependencymanager/samples.annotation/src/main/java/org/apache/felix/dm/samples/annotation/DictionaryService.java
+++ /dev/null
@@ -1,36 +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.felix.dm.samples.annotation;
-
-/**
- * A simple service interface that defines a dictionary service. A dictionary
- * service simply verifies the existence of a word.
- *
- * @author <a href="mailto:dev@felix.apache.org">Felix Project Team</a>
- */
-public interface DictionaryService
-{
- /**
- * Check for the existence of a word.
- *
- * @param word the word to be checked.
- * @return true if the word is in the dictionary, false otherwise.
- */
- public boolean checkWord(String word);
-}
diff --git a/dependencymanager/samples.annotation/src/main/java/org/apache/felix/dm/samples/annotation/SpellChecker.java b/dependencymanager/samples.annotation/src/main/java/org/apache/felix/dm/samples/annotation/SpellChecker.java
deleted file mode 100644
index 6ebc74b..0000000
--- a/dependencymanager/samples.annotation/src/main/java/org/apache/felix/dm/samples/annotation/SpellChecker.java
+++ /dev/null
@@ -1,108 +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.felix.dm.samples.annotation;
-
-import java.util.concurrent.CopyOnWriteArrayList;
-
-import org.apache.felix.dm.annotation.api.Property;
-import org.apache.felix.dm.annotation.api.Component;
-import org.apache.felix.dm.annotation.api.ServiceDependency;
-import org.apache.felix.dm.annotation.api.Start;
-import org.apache.felix.dm.annotation.api.Stop;
-import org.apache.felix.service.command.CommandProcessor;
-import org.apache.felix.service.command.Descriptor;
-import org.osgi.service.log.LogService;
-
-/**
- * Felix "spellcheck" Gogo Shell Command. This command allows to check if some given words are valid or not.
- * This command will be activated only if (at least) one DictionaryService has been injected.
- * To create a Dictionary Service, you have to go the the web console and define a "Dictionary Services" factory
- * configuration instance, which will fire an instantiation of the corresponding dictionary service.
- */
-@Component(provides={SpellChecker.class},
- properties={@Property(name=CommandProcessor.COMMAND_SCOPE, value="dmsample.annotation"),
- @Property(name=CommandProcessor.COMMAND_FUNCTION, values={"spellcheck"})})
-public class SpellChecker
-{
- /**
- * We'll use the OSGi log service for logging. If no log service is available, then we'll use a NullObject.
- */
- @ServiceDependency(required = false)
- private LogService m_log;
-
- /**
- * We'll store all Dictionaries is a CopyOnWrite list, in order to avoid method synchronization.
- */
- private CopyOnWriteArrayList<DictionaryService> m_dictionaries = new CopyOnWriteArrayList<DictionaryService>();
-
- /**
- * Inject a dictionary into this service.
- * @param serviceProperties the dictionary OSGi service properties
- * @param dictionary the new dictionary
- */
- @ServiceDependency(removed = "removeDictionary")
- protected void addDictionary(DictionaryService dictionary)
- {
- m_dictionaries.add(dictionary);
- }
-
- /**
- * Lifecycle method callback, used to check if our service has been activated.
- */
- @Start
- protected void start() {
- m_log.log(LogService.LOG_WARNING, "Spell Checker started");
- }
-
- /**
- * Lifecycle method callback, used to check if our service has been activated.
- */
- @Stop
- protected void stop() {
- m_log.log(LogService.LOG_WARNING, "Spell Checker stopped");
- }
-
- /**
- * Remove a dictionary from our service.
- * @param dictionary
- */
- protected void removeDictionary(DictionaryService dictionary)
- {
- m_dictionaries.remove(dictionary);
- }
-
- // --- Gogo Shell command
-
- @Descriptor("checks if word is found from an available dictionary")
- public void spellcheck(@Descriptor("the word to check")String word)
- {
- m_log.log(LogService.LOG_INFO, "Checking spelling of word \"" + word
- + "\" using the following dictionaries: " + m_dictionaries);
-
- for (DictionaryService dictionary : m_dictionaries)
- {
- if (dictionary.checkWord(word))
- {
- System.out.println("word " + word + " is correct");
- return;
- }
- }
- System.err.println("word " + word + " is incorrect");
- }
-}
diff --git a/dependencymanager/samples/pom.xml b/dependencymanager/samples/pom.xml
deleted file mode 100644
index 44370b8..0000000
--- a/dependencymanager/samples/pom.xml
+++ /dev/null
@@ -1,63 +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/maven-v4_0_0.xsd">
- <modelVersion>4.0.0</modelVersion>
- <parent>
- <groupId>org.apache.felix</groupId>
- <artifactId>felix-parent</artifactId>
- <version>1.2.0</version>
- <relativePath>../../pom/pom.xml</relativePath>
- </parent>
- <properties>
- <osgi.version>4.2.0</osgi.version>
- </properties>
- <name>Apache Felix Dependency Manager Samples</name>
- <artifactId>org.apache.felix.dependencymanager.samples</artifactId>
- <version>3.2.1-SNAPSHOT</version>
- <dependencies>
- <dependency>
- <groupId>org.osgi</groupId>
- <artifactId>org.osgi.core</artifactId>
- <version>${osgi.version}</version>
- </dependency>
- <dependency>
- <groupId>org.osgi</groupId>
- <artifactId>org.osgi.compendium</artifactId>
- <version>${osgi.version}</version>
- </dependency>
- <dependency>
- <groupId>${pom.groupId}</groupId>
- <artifactId>org.apache.felix.dependencymanager</artifactId>
- <version>3.2.0</version>
- <scope>provided</scope>
- </dependency>
- </dependencies>
- <build>
- <plugins>
- <plugin>
- <artifactId>maven-compiler-plugin</artifactId>
- <configuration>
- <source>1.5</source>
- <target>1.5</target>
- <useDefaultManifestFile>false</useDefaultManifestFile>
- <compilerArgument>-g</compilerArgument>
- <compilerVersion>1.5</compilerVersion>
- </configuration>
- </plugin>
- </plugins>
- </build>
-</project>
diff --git a/dependencymanager/samples/src/main/java/samples/dependonconfiguration/Activator.java b/dependencymanager/samples/src/main/java/samples/dependonconfiguration/Activator.java
deleted file mode 100644
index fda9b3a..0000000
--- a/dependencymanager/samples/src/main/java/samples/dependonconfiguration/Activator.java
+++ /dev/null
@@ -1,26 +0,0 @@
-package samples.dependonconfiguration;
-
-import org.apache.felix.dm.DependencyActivatorBase;
-import org.apache.felix.dm.DependencyManager;
-import org.osgi.framework.BundleContext;
-
-public class Activator extends DependencyActivatorBase {
- public void init(BundleContext context, DependencyManager manager) throws Exception {
- manager.add(createComponent()
- .setImplementation(Task.class)
- .add(createConfigurationDependency()
- .setPid("config.pid")
- // The following is optional and allows to display our configuration from webconsole
- .setHeading("Task Configuration")
- .setDescription("Configuration for the Task Service")
- .add(createPropertyMetaData()
- .setCardinality(0)
- .setType(String.class)
- .setHeading("Task Interval")
- .setDescription("Declare here the interval used to trigger the Task")
- .setDefaults(new String[] {"10"})
- .setId("interval"))));
- }
-
- public void destroy(BundleContext context, DependencyManager manager) throws Exception {}
-}
diff --git a/dependencymanager/samples/src/main/java/samples/dependonconfiguration/Task.java b/dependencymanager/samples/src/main/java/samples/dependonconfiguration/Task.java
deleted file mode 100644
index d4fdb82..0000000
--- a/dependencymanager/samples/src/main/java/samples/dependonconfiguration/Task.java
+++ /dev/null
@@ -1,28 +0,0 @@
-package samples.dependonconfiguration;
-
-import java.util.Dictionary;
-
-import org.osgi.service.cm.ConfigurationException;
-import org.osgi.service.cm.ManagedService;
-
-public class Task implements ManagedService {
- private String m_interval;
-
- public void updated(Dictionary properties) throws ConfigurationException {
- if (properties != null) {
- m_interval = (String) properties.get("interval");
- if (m_interval == null) {
- throw new ConfigurationException("interval", "must be specified");
- }
- System.out.println("Task.updated: properties=" + properties);
- }
- }
-
- public void start() {
- System.out.println("Task.start");
- }
-
- public void execute() {
- System.out.println("Scheduling task with interval " + m_interval);
- }
-}
diff --git a/dependencymanager/samples/src/main/java/samples/dependonservice/Activator.java b/dependencymanager/samples/src/main/java/samples/dependonservice/Activator.java
deleted file mode 100644
index 235df30..0000000
--- a/dependencymanager/samples/src/main/java/samples/dependonservice/Activator.java
+++ /dev/null
@@ -1,24 +0,0 @@
-package samples.dependonservice;
-
-import org.apache.felix.dm.DependencyActivatorBase;
-import org.apache.felix.dm.DependencyManager;
-import org.osgi.framework.BundleContext;
-import org.osgi.service.log.LogService;
-
-public class Activator extends DependencyActivatorBase {
- public void init(BundleContext context, DependencyManager manager) throws Exception {
- manager.add(createComponent()
- .setImplementation(DataGenerator.class)
- .add(createServiceDependency()
- .setService(Store.class)
- .setRequired(true)
- )
- .add(createServiceDependency()
- .setService(LogService.class)
- .setRequired(false)
- )
- );
- }
-
- public void destroy(BundleContext context, DependencyManager manager) throws Exception {}
-}
diff --git a/dependencymanager/samples/src/main/java/samples/dependonservice/DataGenerator.java b/dependencymanager/samples/src/main/java/samples/dependonservice/DataGenerator.java
deleted file mode 100644
index f24ef43..0000000
--- a/dependencymanager/samples/src/main/java/samples/dependonservice/DataGenerator.java
+++ /dev/null
@@ -1,15 +0,0 @@
-package samples.dependonservice;
-
-import org.osgi.service.log.LogService;
-
-public class DataGenerator {
- private volatile Store m_store;
- private volatile LogService m_log;
-
- public void generate() {
- for (int i = 0; i < 10; i++) {
- m_store.put("#" + i, "value_" + i);
- }
- m_log.log(LogService.LOG_INFO, "Data generated.");
- }
-}
diff --git a/dependencymanager/samples/src/main/java/samples/dependonservice/Store.java b/dependencymanager/samples/src/main/java/samples/dependonservice/Store.java
deleted file mode 100644
index 8d111cf..0000000
--- a/dependencymanager/samples/src/main/java/samples/dependonservice/Store.java
+++ /dev/null
@@ -1,6 +0,0 @@
-package samples.dependonservice;
-
-public interface Store {
- public void put(String key, Object value);
- public Object get(String key);
-}
diff --git a/dependencymanager/samples/src/main/java/samples/registerservice/Activator.java b/dependencymanager/samples/src/main/java/samples/registerservice/Activator.java
deleted file mode 100644
index 15e89ac..0000000
--- a/dependencymanager/samples/src/main/java/samples/registerservice/Activator.java
+++ /dev/null
@@ -1,16 +0,0 @@
-package samples.registerservice;
-
-import org.apache.felix.dm.DependencyActivatorBase;
-import org.apache.felix.dm.DependencyManager;
-import org.osgi.framework.BundleContext;
-
-public class Activator extends DependencyActivatorBase {
- public void init(BundleContext context, DependencyManager manager) throws Exception {
- manager.add(createComponent()
- .setInterface(Store.class.getName(), null)
- .setImplementation(MemoryStore.class)
- );
- }
-
- public void destroy(BundleContext context, DependencyManager manager) throws Exception {}
-}
diff --git a/dependencymanager/samples/src/main/java/samples/registerservice/MemoryStore.java b/dependencymanager/samples/src/main/java/samples/registerservice/MemoryStore.java
deleted file mode 100644
index 5b44151..0000000
--- a/dependencymanager/samples/src/main/java/samples/registerservice/MemoryStore.java
+++ /dev/null
@@ -1,16 +0,0 @@
-package samples.registerservice;
-
-import java.util.HashMap;
-import java.util.Map;
-
-public class MemoryStore implements Store {
- private Map m_map = new HashMap();
-
- public Object get(String key) {
- return m_map.get(key);
- }
-
- public void put(String key, Object value) {
- m_map.put(key, value);
- }
-}
diff --git a/dependencymanager/samples/src/main/java/samples/registerservice/Store.java b/dependencymanager/samples/src/main/java/samples/registerservice/Store.java
deleted file mode 100644
index 90dcf5b..0000000
--- a/dependencymanager/samples/src/main/java/samples/registerservice/Store.java
+++ /dev/null
@@ -1,6 +0,0 @@
-package samples.registerservice;
-
-public interface Store {
- public void put(String key, Object value);
- public Object get(String key);
-}
diff --git a/dependencymanager/samples/src/main/java/samples/trackingserviceswithcallbacks/Activator.java b/dependencymanager/samples/src/main/java/samples/trackingserviceswithcallbacks/Activator.java
deleted file mode 100644
index b3ee19c..0000000
--- a/dependencymanager/samples/src/main/java/samples/trackingserviceswithcallbacks/Activator.java
+++ /dev/null
@@ -1,20 +0,0 @@
-package samples.trackingserviceswithcallbacks;
-
-import org.apache.felix.dm.DependencyActivatorBase;
-import org.apache.felix.dm.DependencyManager;
-import org.osgi.framework.BundleContext;
-
-public class Activator extends DependencyActivatorBase {
- public void init(BundleContext context, DependencyManager manager) throws Exception {
- manager.add(createComponent()
- .setImplementation(DocumentTranslator.class)
- .add(createServiceDependency()
- .setService(Translator.class)
- .setRequired(false)
- .setCallbacks("added", "removed")
- )
- );
- }
-
- public void destroy(BundleContext context, DependencyManager manager) throws Exception {}
-}
diff --git a/dependencymanager/samples/src/main/java/samples/trackingserviceswithcallbacks/DocumentTranslator.java b/dependencymanager/samples/src/main/java/samples/trackingserviceswithcallbacks/DocumentTranslator.java
deleted file mode 100644
index 41848eb..0000000
--- a/dependencymanager/samples/src/main/java/samples/trackingserviceswithcallbacks/DocumentTranslator.java
+++ /dev/null
@@ -1,27 +0,0 @@
-package samples.trackingserviceswithcallbacks;
-
-import java.util.ArrayList;
-import java.util.List;
-
-import javax.swing.text.Document;
-
-public class DocumentTranslator {
- private List<Translator> m_translators = new ArrayList<Translator>();
-
- public void added(Translator translator) {
- m_translators.add(translator);
- }
-
- public void removed(Translator translator) {
- m_translators.remove(translator);
- }
-
- public Document translate(Document document, String from, String to) {
- for (Translator translator : m_translators) {
- if (translator.canTranslate(from, to)) {
- return translator.translate(document, from, to);
- }
- }
- return null;
- }
-}
diff --git a/dependencymanager/samples/src/main/java/samples/trackingserviceswithcallbacks/Translator.java b/dependencymanager/samples/src/main/java/samples/trackingserviceswithcallbacks/Translator.java
deleted file mode 100644
index de7ac30..0000000
--- a/dependencymanager/samples/src/main/java/samples/trackingserviceswithcallbacks/Translator.java
+++ /dev/null
@@ -1,8 +0,0 @@
-package samples.trackingserviceswithcallbacks;
-
-import javax.swing.text.Document;
-
-public interface Translator {
- public boolean canTranslate(String from, String to);
- public Document translate(Document document, String from, String to);
-}
diff --git a/dependencymanager/shell/DEPENDENCIES b/dependencymanager/shell/DEPENDENCIES
deleted file mode 100644
index b0aa7d7..0000000
--- a/dependencymanager/shell/DEPENDENCIES
+++ /dev/null
@@ -1,22 +0,0 @@
-Apache Felix Dependency Manager Shell
-Copyright 2011-2014 The Apache Software Foundation
-
-This software was developed at the Apache Software Foundation
-(http://www.apache.org) and may have dependencies on other
-Apache software licensed under Apache License 2.0.
-
-I. Included Third-Party Software
-
-n/a
-
-II. Used Third-Party Software
-
-This product uses software developed at
-The OSGi Alliance (http://www.osgi.org/).
-Copyright (c) OSGi Alliance (2000, 2009).
-Licensed under the Apache License 2.0.
-
-III. Overall License Summary
-
-- Apache License 2.0
-
diff --git a/dependencymanager/shell/LICENSE b/dependencymanager/shell/LICENSE
deleted file mode 100644
index d645695..0000000
--- a/dependencymanager/shell/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/dependencymanager/shell/NOTICE b/dependencymanager/shell/NOTICE
deleted file mode 100644
index e156c9d..0000000
--- a/dependencymanager/shell/NOTICE
+++ /dev/null
@@ -1,7 +0,0 @@
-Apache Felix Dependency Manager Shell
-Copyright 2011-2014 The Apache Software Foundation
-
-
-This product includes software developed at
-The Apache Software Foundation (http://www.apache.org/).
-Licensed under the Apache License 2.0.
diff --git a/dependencymanager/shell/changelog.txt b/dependencymanager/shell/changelog.txt
deleted file mode 100644
index 01f1db3..0000000
--- a/dependencymanager/shell/changelog.txt
+++ /dev/null
@@ -1,10 +0,0 @@
-Release 3.2.0
--------------
-
-FELIX-4294 - Dependency Manager Shell improvements
-FELIX-4352 - Extend shell command to give better insight in where the problem is
-
-Release 3.0.0
--------------
-
-Major, backward incompatible release. Start of recorded changes.
diff --git a/dependencymanager/shell/pom.xml b/dependencymanager/shell/pom.xml
deleted file mode 100644
index ab0437d..0000000
--- a/dependencymanager/shell/pom.xml
+++ /dev/null
@@ -1,120 +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/maven-v4_0_0.xsd">
- <modelVersion>4.0.0</modelVersion>
- <parent>
- <groupId>org.apache.felix</groupId>
- <artifactId>felix-parent</artifactId>
- <version>1.2.0</version>
- <relativePath>../../pom/pom.xml</relativePath>
- </parent>
- <properties>
- <osgi.version>4.2.0</osgi.version>
- </properties>
- <name>Apache Felix Dependency Manager Shell</name>
- <artifactId>org.apache.felix.dependencymanager.shell</artifactId>
- <version>3.2.1-SNAPSHOT</version>
- <packaging>bundle</packaging>
-
- <scm>
- <connection>scm:svn:http://svn.apache.org/repos/asf/felix/trunk/dependencymanager/shell</connection>
- <developerConnection>scm:svn:https://svn.apache.org/repos/asf/felix/trunk/dependencymanager/shell</developerConnection>
- <url>http://svn.apache.org/repos/asf/felix/dependencymanager/shell</url>
- </scm>
-
- <dependencies>
- <dependency>
- <groupId>${pom.groupId}</groupId>
- <artifactId>org.apache.felix.dependencymanager</artifactId>
- <version>3.2.1-SNAPSHOT</version>
- </dependency>
- <dependency>
- <groupId>org.osgi</groupId>
- <artifactId>org.osgi.core</artifactId>
- <version>${osgi.version}</version>
- </dependency>
- <dependency>
- <groupId>org.osgi</groupId>
- <artifactId>org.osgi.compendium</artifactId>
- <version>${osgi.version}</version>
- </dependency>
- <dependency>
- <groupId>${pom.groupId}</groupId>
- <artifactId>org.apache.felix.gogo.runtime</artifactId>
- <version>0.10.0</version>
- </dependency>
- <dependency>
- <groupId>org.mockito</groupId>
- <artifactId>mockito-all</artifactId>
- <version>1.9.5</version>
- <scope>test</scope>
- </dependency>
- </dependencies>
- <build>
- <resources>
- <resource>
- <directory>.</directory>
- <targetPath>META-INF</targetPath>
- <includes>
- <include>LICENSE*</include>
- <include>NOTICE*</include>
- <include>DEPENDENCIES*</include>
- <include>*.txt</include>
- </includes>
- </resource>
- </resources>
- <pluginManagement>
- <plugins>
- <plugin>
- <groupId>org.apache.felix</groupId>
- <artifactId>maven-bundle-plugin</artifactId>
- <version>2.3.4</version>
- <extensions>true</extensions>
- </plugin>
- </plugins>
- </pluginManagement>
- <plugins>
- <plugin>
- <groupId>org.apache.maven.plugins</groupId>
- <artifactId>maven-compiler-plugin</artifactId>
- <configuration>
- <source>1.5</source>
- <target>1.5</target>
- </configuration>
- </plugin>
- <plugin>
- <groupId>org.apache.felix</groupId>
- <artifactId>maven-bundle-plugin</artifactId>
- <configuration>
- <instructions>
- <Bundle-SymbolicName>org.apache.felix.dependencymanager.shell</Bundle-SymbolicName>
- <Bundle-Activator>org.apache.felix.dm.shell.Activator</Bundle-Activator>
- <Bundle-Name>Apache Felix Dependency Manager Shell</Bundle-Name>
- <Bundle-Description>Shell command for the dependency manager.</Bundle-Description>
- <Bundle-Vendor>The Apache Software Foundation</Bundle-Vendor>
- <Export-Package />
- <Private-Package>org.apache.felix.dm.shell</Private-Package>
- <Import-Package>org.apache.felix.service.command;status=provisional, *</Import-Package>
- </instructions>
- </configuration>
- </plugin>
- </plugins>
- </build>
-</project>
diff --git a/dependencymanager/shell/src/main/java/org/apache/felix/dm/shell/Activator.java b/dependencymanager/shell/src/main/java/org/apache/felix/dm/shell/Activator.java
deleted file mode 100644
index 7181f16..0000000
--- a/dependencymanager/shell/src/main/java/org/apache/felix/dm/shell/Activator.java
+++ /dev/null
@@ -1,43 +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.felix.dm.shell;
-
-import java.util.Hashtable;
-
-import org.osgi.framework.BundleActivator;
-import org.osgi.framework.BundleContext;
-
-/**
- * Bundle activator for the dependency manager shell command.
- *
- * @author <a href="mailto:dev@felix.apache.org">Felix Project Team</a>
- */
-public class Activator implements BundleActivator {
- public void start(BundleContext context) throws Exception {
- // Provide DependencyManager shell commands for the Gogo Shell.
- Hashtable props = new Hashtable();
- props.put(org.apache.felix.service.command.CommandProcessor.COMMAND_SCOPE, "dependencymanager");
- props.put(org.apache.felix.service.command.CommandProcessor.COMMAND_FUNCTION,
- new String[] { "dm", });
- context.registerService(DMCommand.class.getName(), new DMCommand(context), props);
- }
-
- public void stop(BundleContext context) throws Exception {
- }
-}
diff --git a/dependencymanager/shell/src/main/java/org/apache/felix/dm/shell/ComponentId.java b/dependencymanager/shell/src/main/java/org/apache/felix/dm/shell/ComponentId.java
deleted file mode 100644
index 28d6d84..0000000
--- a/dependencymanager/shell/src/main/java/org/apache/felix/dm/shell/ComponentId.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.felix.dm.shell;
-
-public class ComponentId implements Comparable<ComponentId> {
- private final String name;
- private final String type;
- private final String bundleName;
-
- public ComponentId(String name, String type, String bundleName) {
- super();
- this.name = name;
- this.type = type;
- this.bundleName = bundleName;
- }
-
- public String getName() {
- return name;
- }
-
- public String getType() {
- return type;
- }
-
- public String getBundleName() {
- return bundleName;
- }
-
- @Override
- public int hashCode() {
- final int prime = 31;
- int result = 1;
- result = prime * result + ((bundleName == null) ? 0 : bundleName.hashCode());
- result = prime * result + ((name == null) ? 0 : name.hashCode());
- result = prime * result + ((type == null) ? 0 : type.hashCode());
- return result;
- }
-
- @Override
- public boolean equals(Object obj) {
- if (this == obj)
- return true;
- if (obj == null)
- return false;
- if (getClass() != obj.getClass())
- return false;
- ComponentId other = (ComponentId) obj;
- if (bundleName == null) {
- if (other.bundleName != null)
- return false;
- }
- else if (!bundleName.equals(other.bundleName))
- return false;
- if (name == null) {
- if (other.name != null)
- return false;
- }
- else if (!name.equals(other.name))
- return false;
- if (type == null) {
- if (other.type != null)
- return false;
- }
- else if (!type.equals(other.type))
- return false;
- return true;
- }
-
- @Override
- public String toString() {
- return "ComponentId [name=" + name + ", type=" + type + ", bundleName=" + bundleName + "]";
- }
-
- public int compareTo(ComponentId o) {
- return name.compareTo(o.name);
- }
-
-}
diff --git a/dependencymanager/shell/src/main/java/org/apache/felix/dm/shell/DMCommand.java b/dependencymanager/shell/src/main/java/org/apache/felix/dm/shell/DMCommand.java
deleted file mode 100644
index 1b16279..0000000
--- a/dependencymanager/shell/src/main/java/org/apache/felix/dm/shell/DMCommand.java
+++ /dev/null
@@ -1,726 +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.felix.dm.shell;
-
-import java.util.ArrayList;
-import java.util.Collections;
-import java.util.Comparator;
-import java.util.Dictionary;
-import java.util.Hashtable;
-import java.util.Iterator;
-import java.util.List;
-import java.util.Map.Entry;
-import java.util.Properties;
-import java.util.Set;
-import java.util.StringTokenizer;
-import java.util.TreeSet;
-
-import org.apache.felix.dm.Component;
-import org.apache.felix.dm.ComponentDeclaration;
-import org.apache.felix.dm.ComponentDependencyDeclaration;
-import org.apache.felix.dm.DependencyManager;
-import org.apache.felix.service.command.CommandSession;
-import org.apache.felix.service.command.Descriptor;
-import org.apache.felix.service.command.Parameter;
-import org.osgi.framework.Bundle;
-import org.osgi.framework.BundleContext;
-import org.osgi.framework.Constants;
-import org.osgi.framework.Filter;
-import org.osgi.framework.InvalidSyntaxException;
-
-/**
- * Shell command for showing all services and dependencies that are managed
- * by the dependency manager.
- *
- * @author <a href="mailto:dev@felix.apache.org">Felix Project Team</a>
- */
-@Descriptor("Commands used to dump all existing Dependency Manager components")
-public class DMCommand {
- /**
- * Bundle context used to create OSGI filters.
- */
- private final BundleContext m_context;
-
- /**
- * Sorter used to sort components.
- */
- private static final DependencyManagerSorter SORTER = new DependencyManagerSorter();
-
- /**
- * Constant used by the wtf command, when listing missing services.
- */
- private static final String SERVICE = "service";
-
- /**
- * Constant used by the wtf command, when listing missing configurations.
- */
- private static final String CONFIGURATION = "configuration";
-
- /**
- * Name of a specific gogo shell variable, which may be used to configure "compact" mode.
- * Example: g! dependencymanager.compact=true
- */
- private final static String ENV_COMPACT = "dependencymanager.compact";
-
- /**
- * Name of a specific gogo shell variable, which may be used to configure an OSGI filter, normally
- * passed to the "dm services" option. It is used to display only some service providing components
- * matching the given filter. The filter can contain an "objectClass" option.
- * Example:
- * g! dependencymanager.services="(protocol=http)"
- * g! dependencymanager.services="(&(objectClass=foo.Bar)(protocol=http))"
- */
- private final static String ENV_SERVICES = "dependencymanager.services";
-
- /**
- * Name of a specific gogo shell variable, which may be used to configure a filter on the
- * component implementation class name.
- * The value of this shell variable may contain multiple regex (space separated), and each regex can
- * be negated using "!".
- * Example: g! dependencymanager.components="foo.bar.* ga.bu.zo.*"
- */
- private final static String ENV_COMPONENTS = "dependencymanager.components";
-
- /**
- * Constructor.
- */
- public DMCommand(BundleContext context) {
- m_context = context;
- }
-
- /**
- * Dependency Manager "dm" command. We use gogo annotations, in order to automate documentation,
- * and also to automatically manage optional flags/options and parameters ordering.
- *
- * @param session the gogo command session, used to get some variables declared in the shell
- * This parameter is automatically passed by the gogo runtime.
- * @param nodeps false means that dependencies are not displayed
- * @param compact true means informations are displayed in a compact format. This parameter can also be
- * set using the "dependencymanager.compact" gogo shell variable.
- * @param notavail only unregistered components / unavailable dependencies are displayed
- * @param stats true means some statistics are displayed
- * @param services an osgi filter used to filter on some given osgi service properties. This parameter can also be
- * set using the "dependencymanager.services" gogo shell variable.
- * @param components a regular expression to match either component implementation class names. This parameter can also be
- * set using the "dependencymanager.components" gogo shell variable.
- * @param componentIds only components matching one of the specified components ids are displayed
- * @param bundleIds a list of bundle ids or symbolic names, used to filter on some given bundles
- */
- @Descriptor("List dependency manager components")
- public void dm(
- CommandSession session,
-
- @Descriptor("Hides component dependencies")
- @Parameter(names = {"nodeps", "nd"}, presentValue = "true", absentValue = "false")
- boolean nodeps,
-
- @Descriptor("Displays components using a compact form")
- @Parameter(names = {"compact", "cp"}, presentValue = "true", absentValue = "")
- String compact,
-
- @Descriptor("Only displays unavailable components")
- @Parameter(names = {"notavail", "na"}, presentValue = "true", absentValue = "false")
- boolean notavail,
-
- @Descriptor("Detects where are the root failures")
- @Parameter(names = {"wtf"}, presentValue = "true", absentValue = "false")
- boolean wtf,
-
- @Descriptor("Displays components statistics")
- @Parameter(names = {"stats", "st"}, presentValue = "true", absentValue = "false")
- boolean stats,
-
- @Descriptor("OSGi filter used to filter some service properties")
- @Parameter(names = {"services", "s"}, absentValue = "")
- String services,
-
- @Descriptor("Regex(s) used to filter on component implementation class names (comma separated, can be negated using \"!\" prefix)")
- @Parameter(names = {"components", "c"}, absentValue = "")
- String components,
-
- @Descriptor("Component identifiers to display (list of longs, comma separated)")
- @Parameter(names = {"componentIds", "cid", "ci"}, absentValue = "")
- String componentIds,
-
- @Descriptor("List of bundle ids or bundle symbolic names to display (comma separated)")
- @Parameter(names = {"bundleIds", "bid", "bi"}, absentValue = "")
- String bundleIds) {
-
- try {
- boolean comp = Boolean.parseBoolean(getParam(session, ENV_COMPACT, compact));
- services = getParam(session, ENV_SERVICES, services);
- String[] componentsRegex = getParams(session, ENV_COMPONENTS, components);
-
- ArrayList<String> bids = new ArrayList<String>(); // list of bundle ids or bundle symbolic names
- ArrayList<Long> cids = new ArrayList<Long>(); // list of component ids
-
- // Parse and check componentIds option
- StringTokenizer tok = new StringTokenizer(componentIds, ", ");
- while (tok.hasMoreTokens()) {
- try {
- cids.add(Long.parseLong(tok.nextToken()));
- } catch (NumberFormatException e) {
- System.out.println("Invalid value for componentIds option");
- return;
- }
- }
-
- // Parse services fitler
- Filter servicesFilter = null;
- try {
- if (services != null) {
- servicesFilter = m_context.createFilter(services);
- }
- } catch (InvalidSyntaxException e) {
- System.out.println("Invalid services OSGi filter: " + services);
- e.printStackTrace(System.err);
- return;
- }
-
- // Parse and check bundleIds option
- tok = new StringTokenizer(bundleIds, ", ");
- while (tok.hasMoreTokens()) {
- bids.add(tok.nextToken());
- }
-
- if (wtf) {
- wtf();
- return;
- }
-
- // lookup all dependency manager service components
- List<DependencyManager> managers = DependencyManager.getDependencyManagers();
- Collections.sort(managers, SORTER);
- Iterator<DependencyManager> iterator = managers.iterator();
- long numberOfComponents = 0;
- long numberOfDependencies = 0;
- long lastBundleId = -1;
- while (iterator.hasNext()) {
- DependencyManager manager = iterator.next();
- List<Component> complist = manager.getComponents();
- Iterator<Component> componentIterator = complist.iterator();
- while (componentIterator.hasNext()) {
- Component component = componentIterator.next();
- ComponentDeclaration sc = (ComponentDeclaration) component;
- String name = sc.getName();
- // check if this component is enabled or disabled.
- if (!mayDisplay(component, servicesFilter, componentsRegex, cids)) {
- continue;
- }
- int state = sc.getState();
- Bundle bundle = sc.getBundleContext().getBundle();
- if (matchBundle(bundle, bids)) {
- long bundleId = bundle.getBundleId();
- if (notavail) {
- if (sc.getState() != ComponentDeclaration.STATE_UNREGISTERED) {
- continue;
- }
- }
-
- numberOfComponents++;
- if (lastBundleId != bundleId) {
- lastBundleId = bundleId;
- if (comp) {
- System.out.println("[" + bundleId + "] " + compactName(bundle.getSymbolicName()));
- } else {
- System.out.println("[" + bundleId + "] " + bundle.getSymbolicName());
- }
- }
- if (comp) {
- System.out.print(" [" + sc.getId() + "] " + compactName(name) + " "
- + compactState(ComponentDeclaration.STATE_NAMES[state]));
- } else {
- System.out.println(" [" + sc.getId() + "] " + name + " "
- + ComponentDeclaration.STATE_NAMES[state]);
- }
- if (!nodeps) {
- ComponentDependencyDeclaration[] dependencies = sc.getComponentDependencies();
- if (dependencies != null && dependencies.length > 0) {
- numberOfDependencies += dependencies.length;
- if (comp) {
- System.out.print('(');
- }
- for (int j = 0; j < dependencies.length; j++) {
- ComponentDependencyDeclaration dep = dependencies[j];
- if (notavail && !isUnavailable(dep)) {
- continue;
- }
- String depName = dep.getName();
- String depType = dep.getType();
- int depState = dep.getState();
-
- if (comp) {
- if (j > 0) {
- System.out.print(' ');
- }
- System.out.print(compactName(depName) + " " + compactState(depType) + " "
- + compactState(ComponentDependencyDeclaration.STATE_NAMES[depState]));
- } else {
- System.out.println(" " + depName + " " + depType + " "
- + ComponentDependencyDeclaration.STATE_NAMES[depState]);
- }
- }
- if (comp) {
- System.out.print(')');
- }
- }
- }
- if (comp) {
- System.out.println();
- }
- }
- }
- }
-
- if (stats) {
- System.out.println("Statistics:");
- System.out.println(" - Dependency managers: " + managers.size());
- System.out.println(" - Components: " + numberOfComponents);
- if (!nodeps) {
- System.out.println(" - Dependencies: " + numberOfDependencies);
- }
- }
- } catch (Throwable t) {
- t.printStackTrace();
- }
- }
-
- private boolean isUnavailable(ComponentDependencyDeclaration dep) {
- switch (dep.getState()) {
- case ComponentDependencyDeclaration.STATE_UNAVAILABLE_OPTIONAL:
- case ComponentDependencyDeclaration.STATE_UNAVAILABLE_REQUIRED:
- return true;
- }
- return false;
- }
-
- private boolean matchBundle(Bundle bundle, List<String> ids) {
- if (ids.size() == 0) {
- return true;
- }
-
- for (int i = 0; i < ids.size(); i ++) {
- String id = ids.get(i);
- try {
- Long longId = Long.valueOf(id);
- if (longId == bundle.getBundleId()) {
- return true;
- }
- } catch (NumberFormatException e) {
- // must match symbolic name
- if (id.equals(bundle.getSymbolicName())) {
- return true;
- }
- }
- }
-
- return false;
- }
-
- /**
- * Returns the value of a command arg parameter, or from the gogo shell if the parameter is not passed to
- * the command.
- */
- private String getParam(CommandSession session, String param, String value) {
- if (value != null && value.length() > 0) {
- return value;
- }
- Object shellParamValue = session.get(param);
- return shellParamValue != null ? shellParamValue.toString() : null;
- }
-
- /**
- * Returns the value of a command arg parameter, or from the gogo shell if the parameter is not passed to
- * the command. The parameter value is meant to be a list of values separated by a blank or a comma.
- * The values are split and returned as an array.
- */
- private String[] getParams(CommandSession session, String name, String value) {
- String values = null;
- if (value == null || value.length() == 0) {
- value = (String) session.get(name);
- if (value != null) {
- values = value;
- }
- } else {
- values = value;
- }
- if (values == null) {
- return new String[0];
- }
- return values.trim().split(", ");
- }
-
- /**
- * Checks if a component can be displayed. We make a logical OR between the three following conditions:
- *
- * - the component service properties are matching a given service filter ("services" option)
- * - the component implementation class name is matching some regex ("components" option)
- * - the component declaration name is matching some regex ("names" option)
- *
- * If some component ids are provided, then the component must also match one of them.
- */
- private boolean mayDisplay(Component component, Filter servicesFilter, String[] components, List<Long> componentIds) {
- // Check component id
- if (componentIds.size() > 0) {
- long componentId = ((ComponentDeclaration) component).getId();
- if (componentIds.indexOf(componentId) == -1) {
- return false;
- }
- }
-
- if (servicesFilter == null && components.length == 0) {
- return true;
- }
-
- // Check component service properties
- boolean servicesMatches = servicesMatches(component, servicesFilter);
-
- // Check components regexs, which may match component implementation class name
- boolean componentsMatches = componentMatches(((ComponentDeclaration) component).getClassName(), components);
-
- // Logical OR between service properties match and component service/impl match.
- return servicesMatches || componentsMatches;
- }
-
- /**
- * Checks if a given filter is matching some service properties possibly provided by a component
- */
- private boolean servicesMatches(Component component, Filter servicesFilter) {
- boolean match = false;
- if (servicesFilter != null) {
- String[] services = ((ComponentDeclaration) component).getServices();
- if (services != null) {
- Dictionary<String, Object> properties = component.getServiceProperties();
- if (properties == null) {
- properties = new Hashtable<String, Object>();
- }
- if (properties.get(Constants.OBJECTCLASS) == null) {
- properties.put(Constants.OBJECTCLASS, services);
- }
- match = servicesFilter.match(properties);
- }
- }
- return match;
- }
-
- /**
- * Checks if the component implementation class name (or some possible provided services) are matching
- * some regular expressions.
- */
- private boolean componentMatches(String description, String[] names) {
- for (int i = 0; i < names.length; i ++) {
- String name = names[i];
- boolean not = false;
- if (name.startsWith("!")) {
- name = name.substring(1);
- not = true;
- }
- boolean match = false;
-
- if (description.matches(name)) {
- match = true;
- }
-
- if (not) {
- match = !match;
- }
-
- if (match) {
- return true;
- }
- }
-
- return false;
- }
-
- /**
- * Compact names that look like state strings. State strings consist of
- * one or more words. Each word will be shortened to the first letter,
- * all letters concatenated and uppercased.
- */
- private String compactState(String input) {
- StringBuffer output = new StringBuffer();
- StringTokenizer st = new StringTokenizer(input);
- while (st.hasMoreTokens()) {
- output.append(st.nextToken().toUpperCase().charAt(0));
- }
- return output.toString();
- }
-
- /**
- * Compacts names that look like fully qualified class names. All packages
- * will be shortened to the first letter, except for the last one. So
- * something like "org.apache.felix.MyClass" will become "o.a.f.MyClass".
- */
- private String compactName(String input) {
- StringBuffer output = new StringBuffer();
- int lastIndex = 0;
- for (int i = 0; i < input.length(); i++) {
- char c = input.charAt(i);
- switch (c) {
- case '.' :
- output.append(input.charAt(lastIndex));
- output.append('.');
- lastIndex = i + 1;
- break;
- case ' ' :
- case ',' :
- if (lastIndex < i) {
- output.append(input.substring(lastIndex, i));
- }
- output.append(c);
- lastIndex = i + 1;
- break;
- }
- }
- if (lastIndex < input.length()) {
- output.append(input.substring(lastIndex));
- }
- return output.toString();
- }
-
- protected void wtf() {
- List<ComponentDeclaration> downComponents = getDependenciesThatAreDown();
- if (downComponents.isEmpty()) {
- System.out.println("No missing dependencies found.");
- }
- else {
- System.out.println(downComponents.size() + " missing dependencies found.");
- System.out.println("-------------------------------------");
- }
- listResolvedBundles();
- listInstalledBundles();
- Set<ComponentId> downComponentsRoot = getTheRootCouses(downComponents);
- listAllMissingConfigurations(downComponentsRoot);
- listAllMissingServices(downComponents, downComponentsRoot);
- }
-
- private Set<ComponentId> getTheRootCouses(List<ComponentDeclaration> downComponents) {
- Set<ComponentId> downComponentsRoot = new TreeSet<ComponentId>();
- for (ComponentDeclaration c : downComponents) {
- List<ComponentId> root = getRoot(downComponents, c, new ArrayList<ComponentId>());
- downComponentsRoot.addAll(root);
- }
- return downComponentsRoot;
- }
-
- @SuppressWarnings("unchecked")
- private List<ComponentDeclaration> getDependenciesThatAreDown() {
- List<DependencyManager> dependencyManagers = DependencyManager.getDependencyManagers();
- List<ComponentDeclaration> downComponents = new ArrayList<ComponentDeclaration>();
- for (DependencyManager dm : dependencyManagers) {
- List<ComponentDeclaration> components = dm.getComponents();
- // first create a list of all down components
- for (ComponentDeclaration c : components) {
- if (c.getState() == ComponentDeclaration.STATE_UNREGISTERED) {
- downComponents.add(c);
- }
- }
- }
- return downComponents;
- }
-
- private void listResolvedBundles() {
- boolean areResolved = false;
- for (Bundle b : m_context.getBundles()) {
- if (b.getState() == Bundle.RESOLVED && !isFragment(b)) {
- areResolved = true;
- break;
- }
- }
- if (areResolved) {
- System.out.println("Please note that the following bundles are in the RESOLVED state:");
- for (Bundle b : m_context.getBundles()) {
- if (b.getState() == Bundle.RESOLVED && !isFragment(b)) {
- System.out.println(" * [" + b.getBundleId() + "] " + b.getSymbolicName());
- }
- }
- }
- }
-
- private void listInstalledBundles() {
- boolean areResolved = false;
- for (Bundle b : m_context.getBundles()) {
- if (b.getState() == Bundle.INSTALLED) {
- areResolved = true;
- break;
- }
- }
- if (areResolved) {
- System.out.println("Please note that the following bundles are in the INSTALLED state:");
- for (Bundle b : m_context.getBundles()) {
- if (b.getState() == Bundle.INSTALLED) {
- System.out.println(" * [" + b.getBundleId() + "] " + b.getSymbolicName());
- }
- }
- }
- }
-
- private boolean isFragment(Bundle b) {
- @SuppressWarnings("unchecked")
- Dictionary<String, String> headers = b.getHeaders();
- return headers.get("Fragment-Host") != null;
- }
-
- private void listAllMissingConfigurations(Set<ComponentId> downComponentsRoot) {
- if (hasMissingType(downComponentsRoot, CONFIGURATION)) {
- System.out.println("The following configuration(s) are missing: ");
- for (ComponentId s : downComponentsRoot) {
- if (CONFIGURATION.equals(s.getType())) {
- System.out.println(" * " + s.getName() + " for bundle " + s.getBundleName());
- }
- }
- }
- }
-
- private void listAllMissingServices(List<ComponentDeclaration> downComponents, Set<ComponentId> downComponentsRoot) {
- if (hasMissingType(downComponentsRoot, SERVICE)) {
- System.out.println("The following service(s) are missing: ");
- for (ComponentId s : downComponentsRoot) {
- if (SERVICE.equals(s.getType())) {
- System.out.print(" * " + s.getName());
- ComponentDeclaration component = getComponentDeclaration(s.getName(), downComponents);
- if (component == null) {
- System.out.println(" is not found in the service registry");
- } else {
- ComponentDependencyDeclaration[] componentDependencies = component.getComponentDependencies();
- System.out.println(" and needs:");
- for (ComponentDependencyDeclaration cdd : componentDependencies) {
- if (cdd.getState() == ComponentDependencyDeclaration.STATE_UNAVAILABLE_REQUIRED) {
- System.out.println(cdd.getName());
- }
- }
- System.out.println(" to work");
- }
- }
- }
- }
- }
-
- private boolean hasMissingType(Set<ComponentId> downComponentsRoot, String type) {
- for (ComponentId s : downComponentsRoot) {
- if (type.equals(s.getType())) {
- return true;
- }
- }
- return false;
- }
-
- private List<ComponentId> getRoot(List<ComponentDeclaration> downComponents, ComponentDeclaration c, List<ComponentId> backTrace) {
- ComponentDependencyDeclaration[] componentDependencies = c.getComponentDependencies();
- int downDeps = 0;
- List<ComponentId> result = new ArrayList<ComponentId>();
- for (ComponentDependencyDeclaration cdd : componentDependencies) {
- if (cdd.getState() == ComponentDependencyDeclaration.STATE_UNAVAILABLE_REQUIRED) {
- downDeps++;
- // Detect missing configuration dependency
- if (CONFIGURATION.equals(cdd.getType())) {
- String bsn = c.getBundleContext().getBundle().getSymbolicName();
- result.add(new ComponentId(cdd.getName(), cdd.getType(), bsn));
- continue;
- }
-
- // Detect if the missing dependency is a root cause failure
- ComponentDeclaration component = getComponentDeclaration(cdd.getName(), downComponents);
- if (component == null) {
- result.add(new ComponentId(cdd.getName(), cdd.getType(), null));
- continue;
- }
- // Detect circular dependency
- ComponentId componentId = new ComponentId(cdd.getName(), cdd.getType(), null);
- if (backTrace.contains(componentId)) {
- // We already got this one so its a circular dependency
- System.out.print("Circular dependency found:\n *");
- for (ComponentId cid : backTrace) {
- System.out.print(" -> " + cid.getName() + " ");
- }
- System.out.println(" -> " + componentId.getName());
- result.add(new ComponentId(c.getName(), SERVICE, c.getBundleContext().getBundle().getSymbolicName()));
- continue;
- }
- backTrace.add(componentId);
- return getRoot(downComponents, component, backTrace);
- }
- }
- if (downDeps > 0 && result.isEmpty()) {
- result.add(new ComponentId(c.getName(), SERVICE, c.getBundleContext().getBundle().getSymbolicName()));
- }
- return result;
- }
-
- private ComponentDeclaration getComponentDeclaration(final String fullName, List<ComponentDeclaration> list) {
- String simpleName = getSimpleName(fullName);
- Properties props = parseProperties(fullName);
- for (ComponentDeclaration c : list) {
- String serviceNames = c.getName();
- int cuttOff = serviceNames.indexOf("(");
- if (cuttOff != -1) {
- serviceNames = serviceNames.substring(0, cuttOff).trim();
- }
- for (String serviceName : serviceNames.split(",")) {
- if (simpleName.equals(serviceName.trim()) && doPropertiesMatch(props, parseProperties(c.getName()))) {
- return c;
- }
- }
- }
- return null;
- }
-
- private boolean doPropertiesMatch(Properties need, Properties provide) {
- for (Entry<Object, Object> entry : need.entrySet()) {
- Object prop = provide.get(entry.getKey());
- if (prop == null || !prop.equals(entry.getValue())) {
- return false;
- }
- }
- return true;
- }
-
- private String getSimpleName(String name) {
- int cuttOff = name.indexOf("(");
- if (cuttOff != -1) {
- return name.substring(0, cuttOff).trim();
- }
- return name.trim();
- }
-
- private Properties parseProperties(String name) {
- Properties result = new Properties();
- int cuttOff = name.indexOf("(");
- if (cuttOff != -1) {
- String propsText = name.substring(cuttOff + 1, name.indexOf(")"));
- String[] split = propsText.split(",");
- for (String prop : split) {
- String[] kv = prop.split("=");
- if (kv.length == 2) {
- result.put(kv[0], kv[1]);
- }
- }
- }
- return result;
- }
-
- public static class DependencyManagerSorter implements Comparator<DependencyManager> {
- public int compare(DependencyManager dm1, DependencyManager dm2) {
- long id1 = dm1.getBundleContext().getBundle().getBundleId();
- long id2 = dm2.getBundleContext().getBundle().getBundleId();
- return id1 > id2 ? 1 : -1;
- }
- }
-}
diff --git a/dependencymanager/shell/src/test/java/org/apache/felix/dm/shell/DMCommandTest.java b/dependencymanager/shell/src/test/java/org/apache/felix/dm/shell/DMCommandTest.java
deleted file mode 100644
index 3da016d..0000000
--- a/dependencymanager/shell/src/test/java/org/apache/felix/dm/shell/DMCommandTest.java
+++ /dev/null
@@ -1,289 +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.felix.dm.shell;
-
-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.when;
-
-import java.io.ByteArrayOutputStream;
-import java.io.PrintStream;
-import java.util.Properties;
-
-import javax.crypto.Cipher;
-
-import org.apache.felix.dm.Component;
-import org.apache.felix.dm.DependencyManager;
-import org.junit.After;
-import org.junit.Before;
-import org.junit.Test;
-import org.mockito.InjectMocks;
-import org.mockito.Mock;
-import org.mockito.Spy;
-import org.osgi.framework.Bundle;
-import org.osgi.framework.BundleContext;
-
-public class DMCommandTest {
-
- /** Setup a ByteArrayOutputStream to capture the system out printlines */
- private final ByteArrayOutputStream outContent = new ByteArrayOutputStream();
- private final ByteArrayOutputStream errContent = new ByteArrayOutputStream();
-
- private DependencyManager dm;
- @Spy @InjectMocks private DMCommand dme;
- @Mock private BundleContext m_bundleContext;
-
- @SuppressWarnings("unchecked")
- @Before
- public void setUp() {
- m_bundleContext = mock(BundleContext.class);
- Bundle bundle = mock(Bundle.class);
- when(m_bundleContext.getBundle()).thenReturn(bundle);
- System.setOut(new PrintStream(outContent));
- System.setErr(new PrintStream(errContent));
- dm = new DependencyManager(m_bundleContext);
- dme = new DMCommand(m_bundleContext);
- DependencyManager.getDependencyManagers().add(dm);
- }
-
- @After
- public void cleanUp() {
- System.setOut(null);
- System.setErr(null);
- DependencyManager.getDependencyManagers().remove(dm);
- }
-
- @Test
- public void testWithoutAnyDependcyManagersShouldNotCrash() {
- setupEmptyBundles();
-
- dme.wtf();
- assertEquals("No missing dependencies found.\n", outContent.toString());
- }
-
- @Test
- public void testASingleComponentShouldNotRegisterAsFailure() {
- setupEmptyBundles();
-
- dm.add(dm.createComponent()
- .setImplementation(Object.class)
- .setInterface(Object.class.getName(), null)
- );
- dme.wtf();
- assertEquals("No missing dependencies found.\n", outContent.toString());
- }
-
- @SuppressWarnings("unchecked")
- @Test
- public void testComponentThatDependsOnAOtheComponentShouldRegisterAsFailure() {
- setupEmptyBundles();
- DependencyManager dm = new DependencyManager(m_bundleContext);
- DependencyManager.getDependencyManagers().add(dm);
-
- Component component = dm.createComponent()
- .setImplementation(Object.class)
- .setInterface(Object.class.getName(), null)
- .add(dm.createServiceDependency().setService(Math.class).setRequired(true));
- dm.add(component);
-
- dme.wtf();
- String output = outContent.toString();
- assertTrue(output.contains("1 missing"));
- assertTrue(output.contains("java.lang.Math"));
-
- // remove the mess
- dm.remove(component);
- }
-
- @SuppressWarnings("unchecked")
- @Test
- public void testComponentThatHaveCycliclyDependencyOnAOtheComponentShouldRegisterAsFailure() {
- setupEmptyBundles();
- DependencyManager dm = new DependencyManager(m_bundleContext);
- DependencyManager.getDependencyManagers().add(dm);
-
- Component component1 = dm.createComponent()
- .setImplementation(Cipher.class)
- .setInterface(Cipher.class.getName(), null)
- .add(dm.createServiceDependency().setService(Math.class).setRequired(true));
- dm.add(component1);
-
- Component component2 = dm.createComponent()
- .setImplementation(Math.class)
- .setInterface(Math.class.getName(), null)
- .add(dm.createServiceDependency().setService(Cipher.class).setRequired(true));
- dm.add(component2);
-
- dme.wtf();
- String output = outContent.toString();
- assertTrue(output.contains("Circular dependency found:"));
- assertTrue(output.contains("-> java.lang.Math -> javax.crypto.Cipher -> java.lang.Math"));
-
- // remove the mess
- dm.remove(component1);
- dm.remove(component2);
- }
-
- @Test
- public void testCanFindRootFailure() {
- setupEmptyBundles();
-
- Component component1 = dm.createComponent()
- .setImplementation(Object.class)
- .setInterface(Object.class.getName(), null)
- .add(dm.createServiceDependency().setService(Math.class).setRequired(true));
- dm.add(component1);
-
- Component component2 = dm.createComponent()
- .setImplementation(Math.class)
- .setInterface(Math.class.getName(), null)
- .add(dm.createServiceDependency().setService(String.class).setRequired(true));
- dm.add(component2);
-
- dme.wtf();
- String output = outContent.toString();
- assertTrue(output.contains("2 missing"));
- assertTrue(output.contains("java.lang.String"));
-
- // remove the mess
- dm.remove(component1);
- dm.remove(component2);
- }
-
- @Test
- public void testCanFindRootFailureWithSecondair() {
- setupEmptyBundles();
-
- Component component1 = dm.createComponent()
- .setImplementation(Object.class)
- .setInterface(Object.class.getName(), null)
- .add(dm.createServiceDependency().setService(Math.class).setRequired(true));
- dm.add(component1);
-
- Component component2 = dm.createComponent()
- .setImplementation(Math.class)
- .setInterface(Math.class.getName(), null)
- .add(dm.createServiceDependency().setService(Float.class).setRequired(true));
- dm.add(component2);
-
- Component component3 = dm.createComponent()
- .setImplementation(Object.class)
- .setInterface(new String[] {Object.class.getName(), Float.class.getName()}, null)
- .add(dm.createServiceDependency().setService(String.class).setRequired(true));
- dm.add(component3);
-
- dme.wtf();
- String output = outContent.toString();
- assertTrue(output.contains("3 missing"));
- assertTrue(output.contains("java.lang.String"));
- assertFalse(output.contains("java.lang.Float"));
-
- // remove the mess
- dm.remove(component1);
- dm.remove(component2);
- dm.remove(component3);
- }
-
- @Test
- public void testCanFindRootFailureWithTwoFailures() {
- setupEmptyBundles();
-
- Component component1 = dm.createComponent()
- .setImplementation(Object.class)
- .setInterface(Object.class.getName(), null)
- .add(dm.createServiceDependency().setService(Math.class).setRequired(true))
- .add(dm.createServiceDependency().setService(Long.class).setRequired(true));
- dm.add(component1);
-
-
- dme.wtf();
- String output = outContent.toString();
- assertTrue(output.contains("1 missing"));
- assertTrue(output.contains("java.lang.Math"));
- assertTrue(output.contains("java.lang.Long"));
-
- // remove the mess
- dm.remove(component1);
- }
-
- @Test
- public void testInstalledBundleListing() {
- Bundle bundle1 = mock(Bundle.class);
- when(bundle1.getState()).thenReturn(Bundle.INSTALLED);
- when(bundle1.getSymbolicName()).thenReturn("BadBundle");
-
- setupBundles(bundle1);
-
- dme.wtf();
- String output = outContent.toString();
- assertTrue(output.contains("following bundles are in the INSTALLED"));
- assertTrue(output.contains("[0] BadBundle"));
- // Will print null if it gets bundle 2, that should not happen
- assertFalse(output.contains("null"));
- }
-
- @Test
- public void testResolvedBundleListing() {
- Bundle bundle1 = mock(Bundle.class);
- when(bundle1.getState()).thenReturn(Bundle.RESOLVED);
- when(bundle1.getSymbolicName()).thenReturn("BadBundle");
- Properties headers = new Properties();
- when(bundle1.getHeaders()).thenReturn(headers);
-
- setupBundles(bundle1);
-
- dme.wtf();
- String output = outContent.toString();
- assertTrue(output.contains("following bundles are in the RESOLVED"));
- assertTrue(output.contains("[0] BadBundle"));
- assertFalse(output.contains("null"));
- }
-
- @Test
- public void testResolvedBundleListingButNoFragements() {
- Bundle bundle1 = mock(Bundle.class);
- when(bundle1.getState()).thenReturn(Bundle.RESOLVED);
- when(bundle1.getSymbolicName()).thenReturn("BadBundle");
- Properties headers = new Properties();
- headers.put("Fragment-Host", "some value");
- when(bundle1.getHeaders()).thenReturn(headers);
- setupBundles(bundle1);
-
- dme.wtf();
- String output = outContent.toString();
- assertFalse(output.contains("following bundles are in the RESOLVED"));
- // Will print null if it gets bundle 2, that should not happen
- assertFalse(output.contains("null"));
- }
-
- private void setupBundles( Bundle bundle1) {
- Bundle bundle2 = mock(Bundle.class);
- when(bundle2.getState()).thenReturn(Bundle.ACTIVE);
-
- when(m_bundleContext.getBundles()).thenReturn(new Bundle[] { bundle1, bundle2});
- }
-
- /** Sets up the bundle context without any bundles */
- private void setupEmptyBundles() {
- when(m_bundleContext.getBundles()).thenReturn(new Bundle[] {});
- }
-
-}
diff --git a/dependencymanager/test/LICENSE b/dependencymanager/test/LICENSE
deleted file mode 100644
index d645695..0000000
--- a/dependencymanager/test/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/dependencymanager/test/NOTICE b/dependencymanager/test/NOTICE
deleted file mode 100644
index cfc3633..0000000
--- a/dependencymanager/test/NOTICE
+++ /dev/null
@@ -1,26 +0,0 @@
-Apache Felix Dependency Manager
-Copyright 2009 The Apache Software Foundation
-
-
-I. Included Software
-
-This product includes software developed at
-The Apache Software Foundation (http://www.apache.org/).
-Licensed under the Apache License 2.0.
-
-This product includes software developed at
-The OSGi Alliance (http://www.osgi.org/).
-Copyright (c) OSGi Alliance (2000, 2007).
-Licensed under the Apache License 2.0.
-
-
-II. Used Software
-
-This product uses software developed at
-The OSGi Alliance (http://www.osgi.org/).
-Copyright (c) OSGi Alliance (2000, 2007).
-Licensed under the Apache License 2.0.
-
-
-III. License Summary
-- Apache License 2.0
diff --git a/dependencymanager/test/pom.xml b/dependencymanager/test/pom.xml
deleted file mode 100644
index 07d53bb..0000000
--- a/dependencymanager/test/pom.xml
+++ /dev/null
@@ -1,234 +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/maven-v4_0_0.xsd">
- <modelVersion>4.0.0</modelVersion>
- <parent>
- <groupId>org.apache.felix</groupId>
- <artifactId>felix-parent</artifactId>
- <version>2.1</version>
- <relativePath>../../pom/pom.xml</relativePath>
- </parent>
-
- <artifactId>org.apache.felix.dependencymanager.test</artifactId>
- <version>3.2.1-SNAPSHOT</version>
- <packaging>bundle</packaging>
-
- <name>Apache Felix Dependency Manager Integration Tests</name>
-
- <properties>
- <bundle.build.name>
- ${basedir}/target
- </bundle.build.name>
- <bundle.file.name>
- ${bundle.build.name}/${project.build.finalName}.jar
- </bundle.file.name>
-
- <felix.build.source>5</felix.build.source>
- <felix.build.target>5</felix.build.target>
- <felix.java.signature.artifactId>java15</felix.java.signature.artifactId>
- <exam.version>3.0.0</exam.version>
- <url.version>1.5.2</url.version>
- </properties>
-
- <dependencies>
- <dependency>
- <groupId>org.osgi</groupId>
- <artifactId>org.osgi.core</artifactId>
- <version>5.0.0</version>
- <scope>provided</scope>
- </dependency>
- <dependency>
- <groupId>org.osgi</groupId>
- <artifactId>org.osgi.compendium</artifactId>
- <version>5.0.0</version>
- <scope>provided</scope>
- </dependency>
- <dependency>
- <groupId>org.apache.felix</groupId>
- <artifactId>org.apache.felix.dependencymanager</artifactId>
- <version>3.2.1-SNAPSHOT</version>
- <scope>provided</scope>
- </dependency>
- <dependency>
- <groupId>${pom.groupId}</groupId>
- <artifactId>org.apache.felix.gogo.runtime</artifactId>
- <version>0.10.0</version>
- <scope>provided</scope>
- </dependency>
- <dependency>
- <groupId>junit</groupId>
- <artifactId>junit</artifactId>
- <version>4.6</version>
- <scope>provided</scope>
- </dependency>
-
- <!-- Integration Testing with Pax Exam -->
- <!--
- <dependency>
- <groupId>org.ops4j.pax.exam</groupId>
- <artifactId>pax-exam-container-native</artifactId>
- <version>${exam.version}</version>
- <scope>test</scope>
- </dependency>
- -->
- <dependency>
- <groupId>org.ops4j.pax.exam</groupId>
- <artifactId>pax-exam-container-forked</artifactId>
- <version>${exam.version}</version>
- <scope>test</scope>
- </dependency>
-
- <dependency>
- <groupId>org.ops4j.pax.exam</groupId>
- <artifactId>pax-exam-junit4</artifactId>
- <version>${exam.version}</version>
- <scope>test</scope>
- </dependency>
-
- <dependency>
- <groupId>org.ops4j.pax.exam</groupId>
- <artifactId>pax-exam-link-mvn</artifactId>
- <version>${exam.version}</version>
- <scope>test</scope>
- </dependency>
-
- <dependency>
- <groupId>org.ops4j.pax.url</groupId>
- <artifactId>pax-url-aether</artifactId>
- <version>${url.version}</version>
- <scope>test</scope>
- </dependency>
-
- <dependency>
- <groupId>org.apache.felix</groupId>
- <artifactId>org.apache.felix.framework</artifactId>
- <version>4.2.1</version>
- <scope>test</scope>
- </dependency>
-
- <dependency>
- <groupId>ch.qos.logback</groupId>
- <artifactId>logback-core</artifactId>
- <version>0.9.29</version>
- <scope>test</scope>
- </dependency>
-
- <dependency>
- <groupId>ch.qos.logback</groupId>
- <artifactId>logback-classic</artifactId>
- <version>0.9.29</version>
- <scope>test</scope>
- </dependency>
-
- <!-- Dependency Manager Annotations -->
- <dependency>
- <groupId>org.apache.felix</groupId>
- <artifactId>org.apache.felix.dependencymanager.annotation</artifactId>
- <version>3.2.1-SNAPSHOT</version>
- </dependency>
- </dependencies>
-
- <build>
- <plugins>
- <!-- Build the bundle which contains various components used by integration tests -->
- <plugin>
- <groupId>org.apache.felix</groupId>
- <artifactId>maven-bundle-plugin</artifactId>
- <version>2.3.7</version>
- <extensions>true</extensions>
- <configuration>
- <instructions>
- <Bundle-Name>Apache Felix Dependency Manager Annotations Tests</Bundle-Name>
- <Bundle-SymbolicName>${pom.artifactId}</Bundle-SymbolicName>
- <Export-Package>org.apache.felix.dm.test.components</Export-Package>
- <Import-Package>org.apache.felix.service.command; status="provisional", *</Import-Package>
- </instructions>
- </configuration>
- </plugin>
-
- <!-- java 5 required for annotations support -->
- <plugin>
- <artifactId>maven-compiler-plugin</artifactId>
- <configuration>
- <source>1.5</source>
- <target>1.5</target>
- </configuration>
- </plugin>
-
- <!-- DM annotation plugin used to parse annotations from org.apache.felix.dm.test.components artifact -->
- <plugin>
- <groupId>org.apache.felix</groupId>
- <artifactId>org.apache.felix.dependencymanager.annotation</artifactId>
- <version>3.2.1-SNAPSHOT</version>
- <executions>
- <execution>
- <goals>
- <goal>scan</goal>
- </goals>
- <configuration>
- <log>debug</log>
- <!-- generated-output-dir>.</generated-output-dir> -->
- </configuration>
- </execution>
- </executions>
- </plugin>
-
- <!-- We have no unit tests, we only have integration tests -->
- <plugin>
- <artifactId>maven-surefire-plugin</artifactId>
- <executions>
- <execution>
- <id>surefire-it</id>
- <phase>integration-test</phase>
- <goals>
- <goal>test</goal>
- </goals>
- <configuration>
- <systemProperties>
- <property>
- <name>project.bundle.file</name>
- <value>${bundle.file.name}</value>
- </property>
- <property>
- <name>project.bundle.symbolicName</name>
- <value>${pom.artifactId}</value>
- </property>
- </systemProperties>
- <excludes>
- <exclude>**/components/*</exclude>
- <!-- <exclude>**/AspectRaceTest.java</exclude> -->
- </excludes>
- <includes>
- <!-- By default, all integration tests are run. For running a specific test,
- you can specify a given test below: for example:
- <include>**/integration/**/AspectBaseTest.java</include>
- -->
- <include>**/integration/**/*.java</include>
- </includes>
- </configuration>
- </execution>
- </executions>
- <configuration>
- <excludes>
- <exclude>**/integration/**</exclude>
- </excludes>
- </configuration>
- </plugin>
- </plugins>
- </build>
-</project>
diff --git a/dependencymanager/test/src/main/java/org/apache/felix/dm/test/components/AdapterAnnotation.java b/dependencymanager/test/src/main/java/org/apache/felix/dm/test/components/AdapterAnnotation.java
deleted file mode 100644
index c9e7947..0000000
--- a/dependencymanager/test/src/main/java/org/apache/felix/dm/test/components/AdapterAnnotation.java
+++ /dev/null
@@ -1,196 +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.felix.dm.test.components;
-
-import java.util.Map;
-
-import org.apache.felix.dm.DependencyManager;
-import org.apache.felix.dm.annotation.api.AdapterService;
-import org.apache.felix.dm.annotation.api.Component;
-import org.apache.felix.dm.annotation.api.Inject;
-import org.apache.felix.dm.annotation.api.Property;
-import org.apache.felix.dm.annotation.api.ServiceDependency;
-import org.apache.felix.dm.annotation.api.Start;
-import org.apache.felix.dm.annotation.api.Stop;
-import org.osgi.framework.BundleContext;
-
-public class AdapterAnnotation {
- public interface S1 {
- public void run();
- }
-
- public interface S2 {
- public void run2();
- }
-
- public interface S3 {
- public void run3();
- }
-
- @Component
- public static class S3Consumer {
- private volatile Map<String, String> m_serviceProperties;
- private volatile S3 m_s3;
-
- @ServiceDependency
- void bind(Map<String, String> serviceProperties, S3 s3) {
- m_serviceProperties = serviceProperties;
- m_s3 = s3;
- }
-
- @Start
- void start() {
- // The adapter service must inherit from adaptee service properties ...
- if ("value1".equals(m_serviceProperties.get("param1")) // adaptee properties
- && "true".equals(m_serviceProperties.get("adapter"))) // adapter properties
- {
- m_s3.run3();
- }
- }
- }
-
- @AdapterService(adapteeService = S1.class, properties = {@Property(name = "adapter", value = "true")})
- public static class S1ToS3AdapterAutoConfig implements S3 {
- public static final String ENSURE = "AdapterAnnotation.autoConfig";
-
- // This is the adapted service
- protected volatile S1 m_s1;
-
- @ServiceDependency(filter = "(name=" + ENSURE + ")")
- protected volatile Ensure m_sequencer;
-
- // Check auto config injections
- @Inject
- volatile BundleContext m_bc;
- BundleContext m_bcNotInjected;
-
- @Inject
- volatile DependencyManager m_dm;
- DependencyManager m_dmNotInjected;
-
- @Inject
- volatile org.apache.felix.dm.Component m_component;
- org.apache.felix.dm.Component m_componentNotInjected;
-
- public void run3() {
- checkInjectedFields();
- m_s1.run();
- m_sequencer.step(3);
- }
-
- private void checkInjectedFields() {
- if (m_bc == null) {
- m_sequencer.throwable(new Exception("Bundle Context not injected"));
- return;
- }
- if (m_bcNotInjected != null) {
- m_sequencer.throwable(new Exception("Bundle Context must not be injected"));
- return;
- }
-
- if (m_dm == null) {
- m_sequencer.throwable(new Exception("DependencyManager not injected"));
- return;
- }
- if (m_dmNotInjected != null) {
- m_sequencer.throwable(new Exception("DependencyManager must not be injected"));
- return;
- }
-
- if (m_component == null) {
- m_sequencer.throwable(new Exception("Component not injected"));
- return;
- }
- if (m_componentNotInjected != null) {
- m_sequencer.throwable(new Exception("Component must not be injected"));
- return;
- }
- }
- }
-
- @AdapterService(adapteeService = S1.class, properties = {@Property(name = "adapter", value = "true")}, field = "m_s1")
- public static class S1ToS3AdapterAutoConfigField implements S3 {
- public final static String ENSURE = "AdapterAnnotation.autoConfig.field";
- // This is the adapted service
- protected volatile S1 m_s1;
-
- @ServiceDependency(filter = "(name=" + ENSURE + ")")
- protected volatile Ensure m_sequencer;
-
- public void run3() {
- m_s1.run();
- m_sequencer.step(3);
- }
- }
-
- @AdapterService(adapteeService = S1.class, properties = {@Property(name = "adapter", value = "true")}, added = "bind", removed = "removed")
- public static class S1ToS3AdapterCallback implements S3 {
- public final static String ENSURE = "AdapterAnnotation.callback";
- // This is the adapted service
- protected Object m_s1;
-
- @ServiceDependency(filter = "(name=" + ENSURE + ")")
- protected Ensure m_sequencer;
-
- void bind(S1 s1) {
- m_s1 = s1;
- }
-
- public void run3() {
- ((S1) m_s1).run();
- }
-
- @Stop
- void stop() {
- m_sequencer.step(3);
- }
-
- void removed(S1 s1) {
- m_sequencer.step(4);
- }
- }
-
- @Component(properties = {@Property(name = "param1", value = "value1")})
- public static class S1Impl implements S1 {
- public final static String ENSURE = "AdapterAnnotation.S1Impl";
-
- @ServiceDependency(filter="(name=" + ENSURE + ")")
- protected Ensure m_sequencer;
-
- @ServiceDependency
- protected S2 m_s2;
-
- public void run() {
- m_sequencer.step(1);
- m_s2.run2();
- }
- }
-
- @Component
- public static class S2Impl implements S2 {
- public final static String ENSURE = "AdapterAnnotation.S2Impl";
-
- @ServiceDependency(filter="(name=" + ENSURE + ")")
- protected Ensure m_sequencer;
-
- public void run2() {
- m_sequencer.step(2);
- }
- }
-}
diff --git a/dependencymanager/test/src/main/java/org/apache/felix/dm/test/components/AdapterServiceTestWithPublisher.java b/dependencymanager/test/src/main/java/org/apache/felix/dm/test/components/AdapterServiceTestWithPublisher.java
deleted file mode 100644
index 50d3e1f..0000000
--- a/dependencymanager/test/src/main/java/org/apache/felix/dm/test/components/AdapterServiceTestWithPublisher.java
+++ /dev/null
@@ -1,120 +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.felix.dm.test.components;
-
-import java.util.HashMap;
-import java.util.Map;
-
-import org.apache.felix.dm.annotation.api.AdapterService;
-import org.apache.felix.dm.annotation.api.Component;
-import org.apache.felix.dm.annotation.api.Init;
-import org.apache.felix.dm.annotation.api.LifecycleController;
-import org.apache.felix.dm.annotation.api.Property;
-import org.apache.felix.dm.annotation.api.ServiceDependency;
-import org.apache.felix.dm.annotation.api.Start;
-
-/**
- * Test an AdapterService which provides its interface using a @ServiceLifecycle.
- */
-public class AdapterServiceTestWithPublisher {
- public static final String ENSURE = "AdapterServiceTestWithPublisher";
-
- public interface Provider {
- }
-
- public interface Provider2 {
- }
-
- @Component
- public static class Consumer {
- @ServiceDependency(filter = "(name=" + ENSURE + ")")
- volatile Ensure m_sequencer;
-
- @ServiceDependency(required = false, removed = "unbind")
- void bind(Map properties, Provider2 provider) {
- m_sequencer.step(1);
- // check ProviderImpl properties
- if ("bar".equals(properties.get("foo"))) {
- m_sequencer.step(2);
- }
- // check extra ProviderImpl properties (returned by start method)
- if ("bar2".equals(properties.get("foo2"))) {
- m_sequencer.step(3);
- }
- // check Provider2Impl properties
- if ("bar3".equals(properties.get("foo3"))) {
- m_sequencer.step(4);
- }
- // check extra Provider2Impl properties (returned by start method)
- if ("bar4".equals(properties.get("foo4"))) {
- m_sequencer.step(5);
- }
-
- }
-
- void unbind(Provider2 provider) {
- m_sequencer.step(6);
- }
- }
-
- @Component(properties = {@Property(name = "foo", value = "bar")})
- public static class ProviderImpl implements Provider {
- @Start
- Map start() {
- // Add some extra service properties ... they will be appended to the one we have defined
- // in the @Service annotation.
- return new HashMap() {
- {
- put("foo2", "bar2");
- }
- };
- }
- }
-
- @AdapterService(properties = {@Property(name = "foo3", value = "bar3")}, adapteeService = Provider.class)
- public static class Provider2Impl implements Provider2 {
- @LifecycleController
- volatile Runnable m_publisher; // injected and used to register our service
-
- @LifecycleController(start = false)
- volatile Runnable m_unpublisher; // injected and used to unregister our service
-
- @ServiceDependency(filter = "(name=" + ENSURE + ")")
- volatile Ensure m_sequencer;
-
- @Init
- void init() {
- // register service in 1 second
- Utils.schedule(m_publisher, 1000);
- // unregister the service in 2 seconds
- Utils.schedule(m_unpublisher, 2000);
- }
-
- @Start
- Map start() {
- // Add some extra service properties ... they will be appended to the one we have defined
- // in the @Service annotation.
- return new HashMap() {
- {
- put("foo4", "bar4");
- }
- };
- }
- }
-}
diff --git a/dependencymanager/test/src/main/java/org/apache/felix/dm/test/components/AspectAnnotation.java b/dependencymanager/test/src/main/java/org/apache/felix/dm/test/components/AspectAnnotation.java
deleted file mode 100644
index e9e63f1..0000000
--- a/dependencymanager/test/src/main/java/org/apache/felix/dm/test/components/AspectAnnotation.java
+++ /dev/null
@@ -1,233 +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.felix.dm.test.components;
-
-import org.apache.felix.dm.DependencyManager;
-import org.apache.felix.dm.annotation.api.AspectService;
-import org.apache.felix.dm.annotation.api.Component;
-import org.apache.felix.dm.annotation.api.Destroy;
-import org.apache.felix.dm.annotation.api.Init;
-import org.apache.felix.dm.annotation.api.Inject;
-import org.apache.felix.dm.annotation.api.ServiceDependency;
-import org.apache.felix.dm.annotation.api.Stop;
-import org.osgi.framework.BundleContext;
-import org.osgi.framework.ServiceRegistration;
-
-public class AspectAnnotation {
- public interface ServiceInterface {
- public void invoke(Runnable run);
- }
-
- @Component
- public static class ServiceProvider implements ServiceInterface {
- public final static String ENSURE = "AspectAnnotation.ServiceProvider";
-
- @ServiceDependency(filter = "(name=" + ENSURE + ")")
- protected volatile Ensure m_sequencer;
- // Injected by reflection.
- protected volatile ServiceRegistration m_sr;
-
- @Init
- void init() {
- System.out.println("ServiceProvider.init");
- }
-
- @Destroy
- void destroy() {
- System.out.println("ServiceProvider.destroy");
- }
-
- public void invoke(Runnable run) {
- run.run();
- m_sequencer.step(6);
- }
- }
-
- @AspectService(ranking = 20)
- public static class ServiceAspect2 implements ServiceInterface {
- public final static String ENSURE = "AspectAnnotation.ServiceAspect2";
-
- @ServiceDependency(filter = "(name=" + ENSURE + ")")
- protected volatile Ensure m_sequencer;
- // Injected by reflection.
- private volatile ServiceInterface m_parentService;
-
- // Check auto config injections
- @Inject
- volatile BundleContext m_bc;
- BundleContext m_bcNotInjected;
-
- @Inject
- volatile DependencyManager m_dm;
- DependencyManager m_dmNotInjected;
-
- @Inject
- volatile org.apache.felix.dm.Component m_component;
- org.apache.felix.dm.Component m_componentNotInjected;
-
- @Init
- void init() {
- System.out.println("ServiceAspect2.init");
- }
-
- @Destroy
- void destroy() {
- System.out.println("ServiceAspect2.destroy");
- }
-
- public void invoke(Runnable run) {
- checkInjectedFields();
- m_sequencer.step(3);
- m_parentService.invoke(run);
- }
-
- private void checkInjectedFields() {
- if (m_bc == null) {
- m_sequencer.throwable(new Exception("Bundle Context not injected"));
- return;
- }
- if (m_bcNotInjected != null) {
- m_sequencer.throwable(new Exception("Bundle Context must not be injected"));
- return;
- }
-
- if (m_dm == null) {
- m_sequencer.throwable(new Exception("DependencyManager not injected"));
- return;
- }
- if (m_dmNotInjected != null) {
- m_sequencer.throwable(new Exception("DependencyManager must not be injected"));
- return;
- }
-
- if (m_component == null) {
- m_sequencer.throwable(new Exception("Component not injected"));
- return;
- }
- if (m_componentNotInjected != null) {
- m_sequencer.throwable(new Exception("Component must not be injected"));
- return;
- }
- }
- }
-
- @AspectService(ranking = 30, added = "add")
- public static class ServiceAspect3 implements ServiceInterface {
- public final static String ENSURE = "AspectAnnotation.ServiceAspect3";
-
- @ServiceDependency(filter = "(name=" + ENSURE + ")")
- protected volatile Ensure m_sequencer;
- // Injected using add callback.
- private volatile ServiceInterface m_parentService;
-
- @Init
- void init() {
- System.out.println("ServiceAspect3.init");
- }
-
- @Destroy
- void destroy() {
- System.out.println("ServiceAspect3.destroy");
- }
-
- void add(ServiceInterface si) {
- m_parentService = si;
- }
-
- public void invoke(Runnable run) {
- m_sequencer.step(2);
- m_parentService.invoke(run);
- }
- }
-
- @AspectService(ranking = 10, added = "added", removed = "removed")
- public static class ServiceAspect1 implements ServiceInterface {
- public final static String ENSURE = "AspectAnnotation.ServiceAspect1";
-
- @ServiceDependency(filter = "(name=" + ENSURE + ")")
- protected volatile Ensure m_sequencer;
- // Injected by reflection.
- private volatile ServiceInterface m_parentService;
-
- @Init
- void init() {
- System.out.println("ServiceAspect1.init");
- }
-
- @Destroy
- void destroy() {
- System.out.println("ServiceAspect1.destroy");
- }
-
- void added(ServiceInterface si) {
- m_parentService = si;
- }
-
- @Stop
- void stop() {
- m_sequencer.step(7);
- }
-
- void removed(ServiceInterface si) {
- m_sequencer.step(8);
- }
-
- public void invoke(Runnable run) {
- m_sequencer.step(4);
- m_parentService.invoke(run);
- }
- }
-
- @Component
- public static class ServiceConsumer implements Runnable {
- public final static String ENSURE = "AspectAnnotation.ServiceConsumer";
-
- @ServiceDependency(filter = "(name=" + ENSURE + ")")
- protected volatile Ensure m_sequencer;
-
- @ServiceDependency
- private volatile ServiceInterface m_service;
-
- private Thread m_thread;
-
- @Init
- public void init() {
- m_thread = new Thread(this, "ServiceConsumer");
- m_thread.start();
- }
-
- public void run() {
- m_sequencer.waitForStep(1, 2000);
- m_service.invoke(new Runnable() {
- public void run() {
- m_sequencer.step(5);
- }
- });
- }
-
- @Destroy
- void destroy() {
- m_thread.interrupt();
- try {
- m_thread.join();
- } catch (InterruptedException e) {
- }
- }
- }
-}
diff --git a/dependencymanager/test/src/main/java/org/apache/felix/dm/test/components/AspectLifecycleAnnotation.java b/dependencymanager/test/src/main/java/org/apache/felix/dm/test/components/AspectLifecycleAnnotation.java
deleted file mode 100644
index 3a2e6f5..0000000
--- a/dependencymanager/test/src/main/java/org/apache/felix/dm/test/components/AspectLifecycleAnnotation.java
+++ /dev/null
@@ -1,98 +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.felix.dm.test.components;
-
-import org.apache.felix.dm.annotation.api.AspectService;
-import org.apache.felix.dm.annotation.api.Component;
-import org.apache.felix.dm.annotation.api.Destroy;
-import org.apache.felix.dm.annotation.api.Init;
-import org.apache.felix.dm.annotation.api.ServiceDependency;
-import org.apache.felix.dm.annotation.api.Start;
-import org.apache.felix.dm.annotation.api.Stop;
-
-public class AspectLifecycleAnnotation {
- public interface ServiceInterface {
- public void run();
- }
-
- /**
- * Tests an aspect service, and ensure that its lifecycle methods are properly invoked (init/start/stop/destroy)
- */
- @Component
- public static class AspectLifecycleTest {
- @ServiceDependency
- void bind(ServiceInterface service) {
- service.run();
- }
- }
-
- @Component
- public static class ServiceProvider implements ServiceInterface {
- public final static String ENSURE = "AspectLifecycleAnnotation.ServiceProvider";
-
- @ServiceDependency(filter = "(name=" + ENSURE + ")")
- protected volatile Ensure m_sequencer;
-
- public void run() {
- m_sequencer.step();
- }
- }
-
- @AspectService(ranking = 10)
- public static class ServiceProviderAspect implements ServiceInterface {
- public final static String ENSURE = "AspectLifecycleAnnotation.ServiceProviderAspect";
-
- protected volatile boolean m_initCalled;
- protected volatile Ensure m_sequencer;
-
- @ServiceDependency(filter = "(name=" + ENSURE + ")")
- protected void bind(Ensure sequencer) {
- m_sequencer = sequencer;
- m_sequencer.step(2);
- }
-
- @Init
- void init() {
- m_initCalled = true;
- }
-
- @Start
- void start() {
- if (!m_initCalled) {
- throw new IllegalStateException("start method called, but init method was not called");
- }
- m_sequencer.step(3);
- }
-
- public void run() {
- m_sequencer.step(4);
- }
-
- @Stop()
- void stop() {
- // At this point, the AspectLifecycleTest class has been rebound to the original ServiceProvider.
- m_sequencer.step(6);
- }
-
- @Destroy
- void destroy() {
- m_sequencer.step(7);
- }
- }
-}
diff --git a/dependencymanager/test/src/main/java/org/apache/felix/dm/test/components/AspectLifecycleWithDynamicProxyAnnotation.java b/dependencymanager/test/src/main/java/org/apache/felix/dm/test/components/AspectLifecycleWithDynamicProxyAnnotation.java
deleted file mode 100644
index 5af79b3..0000000
--- a/dependencymanager/test/src/main/java/org/apache/felix/dm/test/components/AspectLifecycleWithDynamicProxyAnnotation.java
+++ /dev/null
@@ -1,115 +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.felix.dm.test.components;
-
-import java.lang.reflect.InvocationHandler;
-import java.lang.reflect.Method;
-import java.lang.reflect.Proxy;
-
-import org.apache.felix.dm.annotation.api.AspectService;
-import org.apache.felix.dm.annotation.api.Component;
-import org.apache.felix.dm.annotation.api.Destroy;
-import org.apache.felix.dm.annotation.api.Init;
-import org.apache.felix.dm.annotation.api.ServiceDependency;
-import org.apache.felix.dm.annotation.api.Start;
-import org.apache.felix.dm.annotation.api.Stop;
-
-public class AspectLifecycleWithDynamicProxyAnnotation {
- public interface ServiceInterface {
- public void run();
- }
-
- /**
- * Tests an aspect service, and ensure that its lifecycle methods are properly invoked (init/start/stop/destroy)
- */
- @Component
- public static class AspectLifecycleTest {
- @ServiceDependency
- void bind(ServiceInterface service) {
- service.run();
- }
- }
-
- @Component
- public static class ServiceProvider implements ServiceInterface {
- public final static String ENSURE = "AspectLifecycleWithDynamicProxyAnnotation.ServiceProvider";
-
- @ServiceDependency(filter = "(name=" + ENSURE + ")")
- protected volatile Ensure m_sequencer;
-
- public void run() {
- m_sequencer.step();
- }
- }
-
- @AspectService(ranking = 10, service = ServiceInterface.class, factoryMethod = "create")
- public static class ServiceProviderAspect implements InvocationHandler {
- public final static String ENSURE = "AspectLifecycleWithDynamicProxyAnnotation.ServiceProviderAspect";
-
- protected volatile boolean m_initCalled;
- protected volatile Ensure m_sequencer;
-
- @ServiceDependency(filter = "(name=" + ENSURE + ")")
- protected void bind(Ensure sequencer) {
- m_sequencer = sequencer;
- m_sequencer.step(2);
- }
-
- public static Object create() {
- return Proxy.newProxyInstance(ServiceProviderAspect.class.getClassLoader(),
- new Class[]{ServiceInterface.class}, new ServiceProviderAspect());
- }
-
- @Init
- void init() {
- m_initCalled = true;
- }
-
- @Start
- void start() {
- if (!m_initCalled) {
- throw new IllegalStateException("start method called, but init method was not called");
- }
- m_sequencer.step(3);
- }
-
- public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
- if (method.getName().equals("toString")) {
- return "ServiceProviderAspect@" + System.identityHashCode(this);
- }
-
- if (!method.getName().equals("run")) {
- throw new IllegalStateException("wrong invoked method: " + method);
- }
- m_sequencer.step(4);
- return null;
- }
-
- @Stop()
- void stop() {
- // At this point, the AspectLifecycleTest class has been rebound to the original ServiceProvider.
- m_sequencer.step(6);
- }
-
- @Destroy
- void destroy() {
- m_sequencer.step(7);
- }
- }
-}
diff --git a/dependencymanager/test/src/main/java/org/apache/felix/dm/test/components/BundleAdapterServiceTestWithPublisher.java b/dependencymanager/test/src/main/java/org/apache/felix/dm/test/components/BundleAdapterServiceTestWithPublisher.java
deleted file mode 100644
index 0198cc3..0000000
--- a/dependencymanager/test/src/main/java/org/apache/felix/dm/test/components/BundleAdapterServiceTestWithPublisher.java
+++ /dev/null
@@ -1,102 +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.felix.dm.test.components;
-
-import java.util.HashMap;
-import java.util.Map;
-
-import org.apache.felix.dm.annotation.api.BundleAdapterService;
-import org.apache.felix.dm.annotation.api.Component;
-import org.apache.felix.dm.annotation.api.Init;
-import org.apache.felix.dm.annotation.api.LifecycleController;
-import org.apache.felix.dm.annotation.api.Property;
-import org.apache.felix.dm.annotation.api.ServiceDependency;
-import org.apache.felix.dm.annotation.api.Start;
-import org.osgi.framework.Bundle;
-
-/**
- * Test a BundleAdapterService which provides its interface using a @ServiceLifecycle.
- */
-public class BundleAdapterServiceTestWithPublisher {
- public static final String ENSURE = "BundleAdapterServiceTestWithPublisher";
-
- public interface Provider {
- }
-
- @Component
- public static class Consumer {
- @ServiceDependency(filter = "(name=" + ENSURE + ")")
- volatile Ensure m_sequencer;
-
- @ServiceDependency(required = false, removed = "unbind")
- void bind(Map properties, Provider provider) {
- m_sequencer.step(1);
- // check ProviderImpl properties
- if ("bar".equals(properties.get("foo"))) {
- m_sequencer.step(2);
- }
- // check extra ProviderImpl properties (returned by start method)
- if ("bar2".equals(properties.get("foo2"))) {
- m_sequencer.step(3);
- }
- // check properties propagated from bundle
- if ("org.apache.felix.dependencymanager".equals(properties.get("Bundle-SymbolicName"))) {
- m_sequencer.step(4);
- } else {
- System.out.println("Consumer.bind: properties=" + properties);
- }
- }
-
- void unbind(Provider provider) {
- m_sequencer.step(5);
- }
- }
-
- @BundleAdapterService(properties = {@Property(name = "foo", value = "bar")}, filter = "(Bundle-SymbolicName=org.apache.felix.dependencymanager)", stateMask = Bundle.INSTALLED
- | Bundle.RESOLVED | Bundle.ACTIVE, propagate = true)
- public static class ProviderImpl implements Provider {
- @LifecycleController
- volatile Runnable m_publisher; // injected and used to register our service
-
- @LifecycleController(start = false)
- volatile Runnable m_unpublisher; // injected and used to unregister our service
-
- @ServiceDependency(filter = "(name=" + ENSURE + ")")
- volatile Ensure m_sequencer;
-
- @Init
- void init() {
- // register service in 1 second
- Utils.schedule(m_publisher, 1000);
- // unregister the service in 2 seconds
- Utils.schedule(m_unpublisher, 2000);
- }
-
- @Start
- Map start() {
- // Add some extra service properties ... they will be appended to the one we have defined
- // in the @Service annotation.
- return new HashMap() {
- {
- put("foo2", "bar2");
- }
- };
- }
- }
-}
diff --git a/dependencymanager/test/src/main/java/org/apache/felix/dm/test/components/BundleDependencyAnnotation.java b/dependencymanager/test/src/main/java/org/apache/felix/dm/test/components/BundleDependencyAnnotation.java
deleted file mode 100644
index 7dc3c8e..0000000
--- a/dependencymanager/test/src/main/java/org/apache/felix/dm/test/components/BundleDependencyAnnotation.java
+++ /dev/null
@@ -1,166 +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.felix.dm.test.components;
-
-import org.apache.felix.dm.DependencyManager;
-import org.apache.felix.dm.annotation.api.BundleAdapterService;
-import org.apache.felix.dm.annotation.api.BundleDependency;
-import org.apache.felix.dm.annotation.api.Component;
-import org.apache.felix.dm.annotation.api.Inject;
-import org.apache.felix.dm.annotation.api.Property;
-import org.apache.felix.dm.annotation.api.ServiceDependency;
-import org.apache.felix.dm.annotation.api.Start;
-import org.apache.felix.dm.annotation.api.Stop;
-import org.osgi.framework.Bundle;
-import org.osgi.framework.BundleContext;
-
-public class BundleDependencyAnnotation {
- public static final String ENSURE_CONSUMER = "BundleDependencyAnnotation.consumer";
- public static final String ENSURE_ADAPTER = "BundleDependencyAnnotation.adapter";
-
- public interface ServiceInterface extends Runnable {
- }
-
- /**
- * Simple Consumer which has a BundleDependency dependency.
- */
- @Component
- public static class Consumer {
- protected volatile boolean m_added;
- protected volatile boolean m_removed;
-
- @ServiceDependency(filter = "(name=" + ENSURE_CONSUMER + ")")
- private volatile Ensure m_sequencer;
-
- @BundleDependency(required = false, removed = "removed", filter = "(Bundle-SymbolicName=org.apache.felix.dependencymanager)")
- public void add(Bundle b) {
- if (b != null && b.getSymbolicName().equals("org.apache.felix.dependencymanager")) {
- m_added = true;
- }
- }
-
- protected void removed(Bundle b) {
- m_removed = true;
- }
-
- @Start
- public void start() {
- m_sequencer.step(1);
- }
-
- @Stop
- public void stop() {
- if (!m_added) {
- throw new IllegalStateException("Did not get DependencyManager bundle");
- }
-
- if (!m_removed) {
- throw new IllegalStateException("Did not remove DependencyManager bundle");
- }
- m_sequencer.step(2);
- }
- }
-
- /**
- * ServiceInterface Consumer.
- */
- @Component
- public static class ServiceConsumer {
- @ServiceDependency(filter = "(name=" + ENSURE_ADAPTER + ")")
- volatile Ensure m_sequencer;
-
- @ServiceDependency
- volatile ServiceInterface m_service;
-
- @Start
- void start() {
- m_sequencer.step(2);
- m_service.run();
- }
- }
-
- /**
- * A BundleAdapter test, which adapts the dependency manager bundle to the ServiceInterface service.
- */
- @BundleAdapterService(filter = "(Bundle-SymbolicName=org.apache.felix.dependencymanager)", stateMask = Bundle.INSTALLED
- | Bundle.RESOLVED | Bundle.ACTIVE, propagate = true, properties = {@Property(name = "foo", value = "bar")})
- public static class ServiceProvider implements ServiceInterface {
- // Adapted bundle (injected by reflection).
- protected volatile Bundle m_bundle;
-
- // Our Sequencer required dependency
- @ServiceDependency(filter = "(name=" + ENSURE_ADAPTER + ")")
- volatile Ensure m_sequencer;
-
- // Check auto config injections
- @Inject
- volatile BundleContext m_bc;
- BundleContext m_bcNotInjected;
-
- @Inject
- volatile DependencyManager m_dm;
- DependencyManager m_dmNotInjected;
-
- @Inject
- volatile org.apache.felix.dm.Component m_component;
- org.apache.felix.dm.Component m_componentNotInjected;
-
- @Start
- void start() {
- checkInjectedFields();
- m_sequencer.step(1);
- }
-
- public void run() {
- if (m_bundle == null || !m_bundle.getSymbolicName().equals("org.apache.felix.dependencymanager")) {
- throw new IllegalStateException("ServiceProvider did not get proper bundle: " + m_bundle);
- }
- m_sequencer.step(3);
- }
-
- private void checkInjectedFields() {
- if (m_bc == null) {
- m_sequencer.throwable(new Exception("Bundle Context not injected"));
- return;
- }
- if (m_bcNotInjected != null) {
- m_sequencer.throwable(new Exception("Bundle Context must not be injected"));
- return;
- }
-
- if (m_dm == null) {
- m_sequencer.throwable(new Exception("DependencyManager not injected"));
- return;
- }
- if (m_dmNotInjected != null) {
- m_sequencer.throwable(new Exception("DependencyManager must not be injected"));
- return;
- }
-
- if (m_component == null) {
- m_sequencer.throwable(new Exception("Component not injected"));
- return;
- }
- if (m_componentNotInjected != null) {
- m_sequencer.throwable(new Exception("Component must not be injected"));
- return;
- }
- }
- }
-}
diff --git a/dependencymanager/test/src/main/java/org/apache/felix/dm/test/components/CompositeAnnotations.java b/dependencymanager/test/src/main/java/org/apache/felix/dm/test/components/CompositeAnnotations.java
deleted file mode 100644
index 9c2873d..0000000
--- a/dependencymanager/test/src/main/java/org/apache/felix/dm/test/components/CompositeAnnotations.java
+++ /dev/null
@@ -1,190 +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.felix.dm.test.components;
-
-import java.util.HashMap;
-import java.util.Map;
-
-import org.apache.felix.dm.annotation.api.Component;
-import org.apache.felix.dm.annotation.api.Composition;
-import org.apache.felix.dm.annotation.api.Destroy;
-import org.apache.felix.dm.annotation.api.Init;
-import org.apache.felix.dm.annotation.api.Property;
-import org.apache.felix.dm.annotation.api.Registered;
-import org.apache.felix.dm.annotation.api.ServiceDependency;
-import org.apache.felix.dm.annotation.api.Start;
-import org.apache.felix.dm.annotation.api.Stop;
-import org.osgi.framework.ServiceRegistration;
-
-public class CompositeAnnotations {
- public interface C1Service {
- }
-
- public interface Dependency extends Runnable {
- }
-
- /**
- * This service is also composed of the Component object.
- */
- @Component
- public static class C1 implements C1Service {
- public final static String ENSURE = "CompositeAnnotations.C1";
-
- /* We are composed of this object, which will also be injected with our dependencies */
- private final C2 m_c2 = new C2();
-
- /* This dependency filter will be configured from our init method */
- @ServiceDependency(name = "D")
- public volatile Dependency m_runnable;
-
- /* Object used to check that methods are called in the proper sequence */
- @ServiceDependency(filter = "(name=" + ENSURE + ")")
- private volatile Ensure m_sequencer;
-
- /**
- * Dynamically configure our "D" dependency, using a dependency customization map
- */
- @Init
- Map<String, String> init() {
- m_sequencer.step(1);
- // Configure a filter for our dependency whose name is "D"
- Map<String, String> customization = new HashMap<String, String>();
- customization.put("D.filter", "(foo=bar2)");
- customization.put("D.required", "true");
- return customization;
- }
-
- /**
- * Return the list of object our service is composed of
- */
- @Composition
- Object[] getComposition() {
- return new Object[]{this, m_c2};
- }
-
- /**
- * Our Service is starting, and our Composites will also be
- */
- @Start
- void start() {
- m_sequencer.step(3);
- m_runnable.run(); /* step 4 */
- // Our Component.start() method should be called once this method returns.
- }
-
- /**
- * Our provided service has been registered into the OSGi service registry.
- */
- @Registered
- void registered(ServiceRegistration sr) {
- m_sequencer.step(7);
- }
-
- /**
- * Our Service is stopping, and our Composites will also be
- */
- @Stop
- void stop() {
- m_sequencer.step(9);
- // Our Component.stop() method should be called once this method returns.
- }
-
- /**
- * Our Service is destroying, and our Composites will also be.
- */
- @Destroy
- void destroy() {
- m_sequencer.step(11);
- // Our Component.destroy() method should be called once this method returns.
- }
- }
-
- /**
- * The CompositeService is also made up of this Class.
- */
- public static class C2 {
- // Injected dependency (from CompositeService)
- private volatile Ensure m_sequencer;
-
- // Injected dependency (from CompositeService)
- public volatile Dependency m_runnable;
-
- // lifecycle callback (same method as the one from CompositeService)
- void init() {
- m_sequencer.step(2);
- }
-
- // lifecycle callback (same method as the one from CompositeService)
- void start() {
- m_sequencer.step(5);
- m_runnable.run(); /* step 6 */
- }
-
- void registered(ServiceRegistration sr) {
- if (sr == null) {
- m_sequencer.throwable(new Exception("null service registration"));
- }
- m_sequencer.step(8);
- }
-
- // lifecycle callback (same method as the one from CompositeService)
- void stop() {
- m_sequencer.step(10);
- }
-
- // lifecycle callback (same method as the one from CompositeService)
- void destroy() {
- m_sequencer.step(12);
- }
- }
-
- @Component(properties = @Property(name = "foo", value = "bar1"))
- public static class Dependency1 implements Dependency {
- public final static String ENSURE = "CompositeAnnotations.Dependency1";
-
- @ServiceDependency(filter = "(name=" + ENSURE + ")")
- volatile Ensure m_sequencer;
-
- @Start
- void start() {
- System.out.println("Dependency1.start");
- }
-
- public void run() {
- m_sequencer.step(Integer.MAX_VALUE); // Makes the test fail.
- }
- }
-
- @Component(properties = @Property(name = "foo", value = "bar2"))
- public static class Dependency2 implements Dependency {
- public final static String ENSURE = "CompositeAnnotations.Dependency2";
-
- @ServiceDependency(filter = "(name=" + ENSURE + ")")
- volatile Ensure m_sequencer;
-
- @Start
- void start() {
- System.out.println("Dependency2.start");
- }
-
- public void run() {
- m_sequencer.step();
- }
- }
-}
diff --git a/dependencymanager/test/src/main/java/org/apache/felix/dm/test/components/Ensure.java b/dependencymanager/test/src/main/java/org/apache/felix/dm/test/components/Ensure.java
deleted file mode 100644
index 2dbf9a4..0000000
--- a/dependencymanager/test/src/main/java/org/apache/felix/dm/test/components/Ensure.java
+++ /dev/null
@@ -1,172 +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.felix.dm.test.components;
-
-import java.io.PrintStream;
-
-import junit.framework.Assert;
-
-/**
- * Helper class to make sure that steps in a test happen in the correct order. Instantiate
- * this class and subsequently invoke <code>step(nr)</code> with steps starting at 1. You
- * can also have threads wait until you arrive at a certain step.
- */
-public class Ensure {
- private final boolean DEBUG;
- private static long INSTANCE = 0;
- private static final int RESOLUTION = 100;
- private static PrintStream STREAM = System.out;
- int step = 0;
- private Throwable m_throwable;
-
- public Ensure() {
- this(true);
- }
-
- public Ensure(boolean debug) {
- DEBUG = debug;
- if (DEBUG) {
- INSTANCE++;
- }
- }
-
- public void setStream(PrintStream output) {
- STREAM = output;
- }
-
- /**
- * Mark this point as step <code>nr</code>.
- *
- * @param nr the step we are in
- */
- public synchronized void step(int nr) {
- step ++;
- Assert.assertEquals(nr, step);
- if (DEBUG) {
- String info = getLineInfo(3);
- STREAM.println("[Ensure " + INSTANCE + "] step " + step + " [" + currentThread() + "] " + info);
- }
- notifyAll();
- }
-
- private String getLineInfo(int depth) {
- StackTraceElement[] trace = Thread.currentThread().getStackTrace();
- String info = trace[depth].getClassName() + "." + trace[depth].getMethodName() + ":" + trace[depth].getLineNumber();
- return info;
- }
-
- /**
- * Mark this point as the next step.
- */
- public synchronized void step() {
- step++;
- if (DEBUG) {
- String info = getLineInfo(3);
- STREAM.println("[Ensure " + INSTANCE + "] next step " + step + " [" + currentThread() + "] " + info);
- }
- notifyAll();
- }
-
- /**
- * Wait until we arrive at least at step <code>nr</code> in the process, or fail if that
- * takes more than <code>timeout</code> milliseconds. If you invoke wait on a thread,
- * you are effectively assuming some other thread will invoke the <code>step(nr)</code>
- * method.
- *
- * @param nr the step to wait for
- * @param timeout the number of milliseconds to wait
- */
- public synchronized void waitForStep(int nr, int timeout) {
- final int initialTimeout = timeout;
- if (DEBUG) {
- String info = getLineInfo(3);
- STREAM.println("[Ensure " + INSTANCE + "] waiting for step " + nr + " [" + currentThread() + "] " + info);
- }
- while (step < nr && timeout > 0) {
- try {
- wait(RESOLUTION);
- timeout -= RESOLUTION;
- }
- catch (InterruptedException e) {}
- }
- if (step < nr) {
- throw new IllegalStateException("Timed out waiting for " + initialTimeout + " ms for step " + nr + ", we are still at step " + step);
- }
- if (DEBUG) {
- String info = getLineInfo(3);
- STREAM.println("[Ensure " + INSTANCE + "] arrived at step " + nr + " [" + currentThread() + "] " + info);
- }
- }
-
- private String currentThread() {
- Thread thread = Thread.currentThread();
- return thread.getId() + " " + thread.getName();
- }
-
- public static Runnable createRunnableStep(final Ensure ensure, final int nr) {
- return new Runnable() { public void run() { ensure.step(nr); }};
- }
-
- public synchronized void steps(Steps steps) {
- steps.next(this);
- }
-
- /**
- * Helper class for naming a list of step numbers. If used with the steps(Steps) method
- * you can define at which steps in time this point should be passed. That means you can
- * check methods that will get invoked multiple times during a test.
- */
- public static class Steps {
- private final int[] m_steps;
- private int m_stepIndex;
-
- /**
- * Create a list of steps and initialize the step counter to zero.
- */
- public Steps(int... steps) {
- m_steps = steps;
- m_stepIndex = 0;
- }
-
- /**
- * Ensure we're at the right step. Will throw an index out of bounds exception if we enter this step more often than defined.
- */
- public void next(Ensure ensure) {
- ensure.step(m_steps[m_stepIndex++]);
- }
- }
-
- /**
- * Saves a thrown exception that occurred in a different thread. You can only save one exception
- * at a time this way.
- */
- public synchronized void throwable(Throwable throwable) {
- m_throwable = throwable;
- }
-
- /**
- * Throws a <code>Throwable</code> if one occurred in a different thread and that thread saved it
- * using the <code>throwable()</code> method.
- */
- public synchronized void ensure() throws Throwable {
- if (m_throwable != null) {
- throw m_throwable;
- }
- }
-}
diff --git a/dependencymanager/test/src/main/java/org/apache/felix/dm/test/components/ExtraAdapterServiceProperties.java b/dependencymanager/test/src/main/java/org/apache/felix/dm/test/components/ExtraAdapterServiceProperties.java
deleted file mode 100644
index 871d17a..0000000
--- a/dependencymanager/test/src/main/java/org/apache/felix/dm/test/components/ExtraAdapterServiceProperties.java
+++ /dev/null
@@ -1,89 +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.felix.dm.test.components;
-
-import java.util.HashMap;
-import java.util.Map;
-
-import org.apache.felix.dm.annotation.api.AdapterService;
-import org.apache.felix.dm.annotation.api.Component;
-import org.apache.felix.dm.annotation.api.Property;
-import org.apache.felix.dm.annotation.api.ServiceDependency;
-import org.apache.felix.dm.annotation.api.Start;
-
-/**
- * This test validates that an adapter Service may specify some extra service properties
- * from it's start callback
- */
-public class ExtraAdapterServiceProperties {
- public final static String ENSURE = "ExtraAdapterServiceProperties";
-
- public interface Provider {
- }
-
- public interface Provider2 {
- }
-
- @Component(properties = {@Property(name = "foo", value = "bar")})
- public static class ProviderImpl implements Provider {
- }
-
- @AdapterService(provides = Provider2.class, properties = {@Property(name = "foo2", value = "bar2")}, adapteeService = Provider.class)
- public static class Provider2Impl implements Provider2 {
- protected Provider m_adaptee;
-
- @Start
- Map<String, String> start() {
- return new HashMap<String, String>() {
- {
- put("foo3", "bar3");
- }
- };
- }
- }
-
- @Component
- public static class Consumer {
- @ServiceDependency(filter = "(name=" + ENSURE + ")")
- volatile Ensure m_sequencer;
-
- private volatile Map m_properties;
-
- @ServiceDependency
- void bind(Map properties, Provider2 provider2) {
- m_properties = properties;
- }
-
- @Start
- void start() {
- System.out.println("provider2 service properties: " + m_properties);
- if ("bar".equals(m_properties.get("foo"))) {
- m_sequencer.step(1);
- }
-
- if ("bar2".equals(m_properties.get("foo2"))) {
- m_sequencer.step(2);
- }
-
- if ("bar3".equals(m_properties.get("foo3"))) {
- m_sequencer.step(3);
- }
- }
- }
-}
diff --git a/dependencymanager/test/src/main/java/org/apache/felix/dm/test/components/ExtraAspectServiceProperties.java b/dependencymanager/test/src/main/java/org/apache/felix/dm/test/components/ExtraAspectServiceProperties.java
deleted file mode 100644
index 00c65a9..0000000
--- a/dependencymanager/test/src/main/java/org/apache/felix/dm/test/components/ExtraAspectServiceProperties.java
+++ /dev/null
@@ -1,84 +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.felix.dm.test.components;
-
-import java.util.HashMap;
-import java.util.Map;
-
-import org.apache.felix.dm.annotation.api.AspectService;
-import org.apache.felix.dm.annotation.api.Component;
-import org.apache.felix.dm.annotation.api.Property;
-import org.apache.felix.dm.annotation.api.ServiceDependency;
-import org.apache.felix.dm.annotation.api.Start;
-
-/**
- * This test validates that an adapter Service may specify some extra service properties
- * from it's start callback
- */
-public class ExtraAspectServiceProperties {
- public final static String ENSURE = "ExtraAspectServiceProperties";
-
- public interface Provider {
- }
-
- @Component(properties = {@Property(name = "foo", value = "bar")})
- public static class ProviderImpl implements Provider {
- }
-
- @AspectService(ranking = 10, properties = {@Property(name = "foo2", value = "bar2")})
- public static class ProviderAspectImpl implements Provider {
- @Start
- Map<String, String> start() {
- return new HashMap<String, String>() {
- {
- put("foo3", "aspect");
- }
- };
- }
- }
-
- @Component
- public static class Consumer {
- @ServiceDependency(filter = "(name=" + ENSURE + ")")
- volatile Ensure m_sequencer;
-
- private volatile Map m_properties;
-
- @ServiceDependency
- void bind(Map properties, Provider provider) {
- m_properties = properties;
- }
-
- @Start
- void start() {
- System.out.println("provider aspect service properties: " + m_properties);
- if ("bar".equals(m_properties.get("foo"))) {
- m_sequencer.step(1);
- }
-
- if ("bar2".equals(m_properties.get("foo2"))) {
- m_sequencer.step(2);
- }
-
- if ("aspect".equals(m_properties.get("foo3"))) {
- m_sequencer.step(3);
- }
- }
- }
-}
diff --git a/dependencymanager/test/src/main/java/org/apache/felix/dm/test/components/ExtraFactoryServiceProperties.java b/dependencymanager/test/src/main/java/org/apache/felix/dm/test/components/ExtraFactoryServiceProperties.java
deleted file mode 100644
index 2c29617..0000000
--- a/dependencymanager/test/src/main/java/org/apache/felix/dm/test/components/ExtraFactoryServiceProperties.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.felix.dm.test.components;
-
-import java.util.Dictionary;
-import java.util.HashMap;
-import java.util.Hashtable;
-import java.util.Map;
-import java.util.Set;
-
-import org.apache.felix.dm.annotation.api.Component;
-import org.apache.felix.dm.annotation.api.Property;
-import org.apache.felix.dm.annotation.api.ServiceDependency;
-import org.apache.felix.dm.annotation.api.Start;
-
-public class ExtraFactoryServiceProperties {
- public final static String FACTORYSET = "ExtraFactoryServiceProperties.FACTORYSET";
- public final static String ENSURE = "ExtraFactoryServiceProperties";
-
- public interface Provider {
- }
-
- @Component(properties = {@Property(name = "foo", value = "bar")}, factorySet = FACTORYSET)
- public static class ProviderImpl implements Provider {
- @Start
- Map<String, String> start() {
- return new HashMap<String, String>() {
- {
- put("foo2", "bar2");
- }
- };
- }
- }
-
- @Component
- public static class ProviderImplFactory {
- @ServiceDependency(filter = "(" + Component.FACTORY_NAME + "=" + FACTORYSET + ")")
- volatile Set<Dictionary> m_factory;
-
- @Start
- void start() {
- m_factory.add(new Hashtable() {
- {
- put("foo3", "bar3");
- }
- });
- }
- }
-
- @Component
- public static class Consumer {
- @ServiceDependency(filter = "(name=" + ENSURE + ")")
- volatile Ensure m_sequencer;
-
- private volatile Map m_properties;
-
- @ServiceDependency
- void bindProvider(Map properties, Provider m_provider) {
- m_properties = properties;
- }
-
- @Start
- void start() {
- System.out.println("provider service properties: " + m_properties);
- if ("bar".equals(m_properties.get("foo"))) {
- m_sequencer.step(1);
- }
-
- if ("bar2".equals(m_properties.get("foo2"))) {
- m_sequencer.step(2);
- }
-
- if ("bar3".equals(m_properties.get("foo3"))) {
- m_sequencer.step(3);
- }
- }
- }
-}
diff --git a/dependencymanager/test/src/main/java/org/apache/felix/dm/test/components/ExtraServiceProperties.java b/dependencymanager/test/src/main/java/org/apache/felix/dm/test/components/ExtraServiceProperties.java
deleted file mode 100644
index 54f1916..0000000
--- a/dependencymanager/test/src/main/java/org/apache/felix/dm/test/components/ExtraServiceProperties.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.felix.dm.test.components;
-
-import java.util.HashMap;
-import java.util.Map;
-
-import org.apache.felix.dm.annotation.api.Component;
-import org.apache.felix.dm.annotation.api.Property;
-import org.apache.felix.dm.annotation.api.ServiceDependency;
-import org.apache.felix.dm.annotation.api.Start;
-
-/**
- * This test validates that a basic Service may specify some extra service properties
- * from it's start callback
- */
-public class ExtraServiceProperties {
- public final static String ENSURE = "ExtraServiceProperties";
-
- public interface Provider {
- }
-
- @Component(properties = {@Property(name = "foo", value = "bar")})
- public static class ProviderImpl implements Provider {
- @Start
- Map<String, String> start() {
- return new HashMap<String, String>() {
- {
- put("foo2", "bar2");
- }
- };
- }
- }
-
- @Component
- public static class Consumer {
- @ServiceDependency(filter = "(name=" + ENSURE + ")")
- volatile Ensure m_sequencer;
-
- private volatile Map m_properties;
-
- @ServiceDependency
- void bindProvider(Map properties, Provider m_provider) {
- m_properties = properties;
- }
-
- @Start
- void start() {
- System.out.println("provider service properties: " + m_properties);
- if ("bar".equals(m_properties.get("foo"))) {
- m_sequencer.step(1);
- }
-
- if ("bar2".equals(m_properties.get("foo2"))) {
- m_sequencer.step(2);
- }
- }
- }
-}
diff --git a/dependencymanager/test/src/main/java/org/apache/felix/dm/test/components/FactoryConfigurationAdapterAnnotation.java b/dependencymanager/test/src/main/java/org/apache/felix/dm/test/components/FactoryConfigurationAdapterAnnotation.java
deleted file mode 100644
index 57ad770..0000000
--- a/dependencymanager/test/src/main/java/org/apache/felix/dm/test/components/FactoryConfigurationAdapterAnnotation.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.felix.dm.test.components;
-
-import java.util.Dictionary;
-import java.util.Map;
-
-import org.apache.felix.dm.DependencyManager;
-import org.apache.felix.dm.annotation.api.Component;
-import org.apache.felix.dm.annotation.api.FactoryConfigurationAdapterService;
-import org.apache.felix.dm.annotation.api.Inject;
-import org.apache.felix.dm.annotation.api.Property;
-import org.apache.felix.dm.annotation.api.Registered;
-import org.apache.felix.dm.annotation.api.ServiceDependency;
-import org.apache.felix.dm.annotation.api.Start;
-import org.apache.felix.dm.annotation.api.Stop;
-import org.osgi.framework.BundleContext;
-
-public class FactoryConfigurationAdapterAnnotation {
- public interface ServiceInterface {
- public void doService();
- }
-
- @Component
- public static class ServiceClient {
- @ServiceDependency(changed = "changeServiceProvider")
- void addServiceProvider(Map props, ServiceInterface si) {
- // props should contain foo=bar, foo2=bar2
- if (!"bar".equals(props.get("foo"))) {
- throw new IllegalArgumentException("configuration does not contain foo=bar: " + props);
- }
- if (!"bar2".equals(props.get("foo2"))) {
- throw new IllegalArgumentException("configuration does not contain foo2=bar2: " + props);
- }
- si.doService();
- }
-
- void changeServiceProvider(Map props, ServiceInterface si) {
- // props should contain foo=bar, foo2=bar2_modified
- if (!"bar".equals(props.get("foo"))) {
- throw new IllegalArgumentException("configuration does not contain foo=bar: " + props);
- }
- if (!"bar2_modified".equals(props.get("foo2"))) {
- throw new IllegalArgumentException("configuration does not contain foo2=bar2: " + props);
- }
- si.doService();
- }
- }
-
- /**
- * This service is instantiated when a factory configuration is created from ConfigAdmin
- */
- @FactoryConfigurationAdapterService(factoryPid = "FactoryPidTest", properties = {@Property(name = "foo", value = "bar")}, propagate = true)
- public static class ServiceProvider implements ServiceInterface {
- public final static String ENSURE = "FactoryConfigurationAdapterAnnotation.ServiceProvider";
-
- @ServiceDependency(filter="(name=" + ENSURE + ")")
- private volatile Ensure m_sequencer;
-
- private volatile boolean m_started;
-
- // Check auto config injections
- @Inject
- volatile BundleContext m_bc;
- BundleContext m_bcNotInjected;
-
- @Inject
- volatile DependencyManager m_dm;
- DependencyManager m_dmNotInjected;
-
- @Inject
- volatile org.apache.felix.dm.Component m_component;
- org.apache.felix.dm.Component m_componentNotInjected;
-
- // Either initial config, or an updated config
- protected void updated(Dictionary conf) {
- if (m_started) {
- // conf should contain foo2=bar2_modified
- if (!"bar2_modified".equals(conf.get("foo2"))) {
- m_sequencer.throwable(new Exception("configuration does not contain foo=bar"));
- }
- m_sequencer.step(4);
- } else {
- // conf should contain foo2=bar2
- if (!"bar2".equals(conf.get("foo2"))) {
- throw new IllegalArgumentException("configuration does not contain foo2=bar2: " + conf);
- }
- }
- }
-
- @Start
- void start() {
- checkInjectedFields();
- m_started = true;
- m_sequencer.step(1);
- }
-
- @Registered
- void registered() {
- m_sequencer.step(3);
- }
-
- // The ServiceClient is invoking our service
- public void doService() {
- m_sequencer.step(); /* 2 or 5 */
- }
-
- @Stop
- void stop() {
- m_sequencer.step(6);
- }
-
- private void checkInjectedFields() {
- if (m_bc == null) {
- m_sequencer.throwable(new Exception("Bundle Context not injected"));
- return;
- }
- if (m_bcNotInjected != null) {
- m_sequencer.throwable(new Exception("Bundle Context must not be injected"));
- return;
- }
-
- if (m_dm == null) {
- m_sequencer.throwable(new Exception("DependencyManager not injected"));
- return;
- }
- if (m_dmNotInjected != null) {
- m_sequencer.throwable(new Exception("DependencyManager must not be injected"));
- return;
- }
-
- if (m_component == null) {
- m_sequencer.throwable(new Exception("Component not injected"));
- return;
- }
- if (m_componentNotInjected != null) {
- m_sequencer.throwable(new Exception("Component must not be injected"));
- return;
- }
- }
- }
-}
diff --git a/dependencymanager/test/src/main/java/org/apache/felix/dm/test/components/FactoryConfigurationAdapterServiceTestWithPublisher.java b/dependencymanager/test/src/main/java/org/apache/felix/dm/test/components/FactoryConfigurationAdapterServiceTestWithPublisher.java
deleted file mode 100644
index 03b5b54..0000000
--- a/dependencymanager/test/src/main/java/org/apache/felix/dm/test/components/FactoryConfigurationAdapterServiceTestWithPublisher.java
+++ /dev/null
@@ -1,121 +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.felix.dm.test.components;
-
-import java.io.IOException;
-import java.util.Dictionary;
-import java.util.HashMap;
-import java.util.Hashtable;
-import java.util.Map;
-
-import org.apache.felix.dm.annotation.api.Component;
-import org.apache.felix.dm.annotation.api.FactoryConfigurationAdapterService;
-import org.apache.felix.dm.annotation.api.Init;
-import org.apache.felix.dm.annotation.api.LifecycleController;
-import org.apache.felix.dm.annotation.api.Property;
-import org.apache.felix.dm.annotation.api.ServiceDependency;
-import org.apache.felix.dm.annotation.api.Start;
-import org.osgi.service.cm.Configuration;
-import org.osgi.service.cm.ConfigurationAdmin;
-
-/**
- * Test a FactoryConfigurationAdapterService which provides its interface using a @ServiceLifecycle.
- */
-public class FactoryConfigurationAdapterServiceTestWithPublisher {
- public final static String PID="FactoryConfigurationAdapterServiceTestWithPublisher.PID";
- public final static String ENSURE = "FactoryConfigurationAdapterServiceTestWithPublisher";
-
- public interface Provider {
- }
-
- @Component
- public static class Consumer {
- @ServiceDependency(filter = "(name=" + ENSURE + ")")
- volatile Ensure m_sequencer;
-
- @ServiceDependency(required = false, removed = "unbind")
- void bind(Map properties, Provider provider) {
- m_sequencer.step(1);
- // check ProviderImpl properties
- if ("bar".equals(properties.get("foo"))) {
- m_sequencer.step(2);
- }
- // check extra ProviderImpl properties (returned by start method)
- if ("bar2".equals(properties.get("foo2"))) {
- m_sequencer.step(3);
- }
- // check Factory Configuration properties
- if ("bar3".equals(properties.get("foo3"))) {
- m_sequencer.step(4);
- }
- }
-
- void unbind(Provider provider) {
- m_sequencer.step(5);
- }
- }
-
- @Component
- public static class Configurator {
- @ServiceDependency
- void bind(ConfigurationAdmin cm) throws IOException {
- Configuration cf = cm.createFactoryConfiguration(PID, null);
- cf.update(new Hashtable() {
- {
- put("foo3", "bar3");
- }
- });
- }
- }
-
- @FactoryConfigurationAdapterService(propagate = true, properties = {@Property(name = "foo", value = "bar")}, factoryPid = PID, updated = "updated")
- public static class ProviderImpl implements Provider {
- @LifecycleController
- volatile Runnable m_publisher; // injected and used to register our service
-
- @LifecycleController(start = false)
- volatile Runnable m_unpublisher; // injected and used to unregister our service
-
- @ServiceDependency(filter = "(name=" + ENSURE + ")")
- volatile Ensure m_sequencer;
-
- void updated(Dictionary conf) {
- }
-
- @Init
- void init() {
- // register service in 1 second
- Utils.schedule(m_publisher, 1000);
- // unregister the service in 2 seconds
- Utils.schedule(m_unpublisher, 2000);
- }
-
- @Start
- Map start() {
- // Add some extra service properties ... they will be appended to the one we have defined
- // in the @Service annotation.
- return new HashMap() {
- {
- put("foo2", "bar2");
- }
- };
- }
-
- }
-}
diff --git a/dependencymanager/test/src/main/java/org/apache/felix/dm/test/components/FactoryServiceTestWthPublisher.java b/dependencymanager/test/src/main/java/org/apache/felix/dm/test/components/FactoryServiceTestWthPublisher.java
deleted file mode 100644
index c9f9574..0000000
--- a/dependencymanager/test/src/main/java/org/apache/felix/dm/test/components/FactoryServiceTestWthPublisher.java
+++ /dev/null
@@ -1,112 +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.felix.dm.test.components;
-
-import java.util.Dictionary;
-import java.util.HashMap;
-import java.util.Hashtable;
-import java.util.Map;
-import java.util.Set;
-
-import org.apache.felix.dm.annotation.api.Component;
-import org.apache.felix.dm.annotation.api.Init;
-import org.apache.felix.dm.annotation.api.LifecycleController;
-import org.apache.felix.dm.annotation.api.Property;
-import org.apache.felix.dm.annotation.api.ServiceDependency;
-import org.apache.felix.dm.annotation.api.Start;
-
-/**
- * A Service instantiated from a FactorySet, and which registers/unregisters its service,
- * using the @ServiceLifecycle annotation.
- */
-public class FactoryServiceTestWthPublisher {
- public final static String FACTORY_SET = "FactoryServiceTestWthPublisher.FACTORYSET";
- public final static String ENSURE = "FactoryServiceTestWthPublisher";
-
- public interface Provider {
- }
-
- @Component
- public static class Consumer {
- @ServiceDependency(filter = "(name=" + ENSURE + ")")
- volatile Ensure m_sequencer;
-
- @ServiceDependency(required = false, removed = "unbind")
- void bind(Map properties, Provider provider) {
- System.out.println("BIND: " + provider + ", map=" + properties);
- m_sequencer.step(1);
- if ("bar".equals(properties.get("foo"))) {
- m_sequencer.step(2);
- }
- if ("bar2".equals(properties.get("foo2"))) {
- m_sequencer.step(3);
- }
- if ("bar3".equals(properties.get("foo3"))) {
- m_sequencer.step(4);
- }
- }
-
- void unbind(Provider provider) {
- m_sequencer.step(5);
- }
- }
-
- @Component(factorySet = FACTORY_SET, properties = {@Property(name = "foo", value = "bar")})
- public static class ProviderImpl implements Provider {
- @LifecycleController
- volatile Runnable m_publisher; // injected and used to register our service
-
- @LifecycleController(start = false)
- volatile Runnable m_unpublisher; // injected and used to unregister our service
-
- @ServiceDependency(filter = "(name=" + ENSURE + ")")
- volatile Ensure m_sequencer;
-
- @Init
- void init() {
- // register service in 1 second
- Utils.schedule(m_publisher, 1000);
- // unregister the service in 2 seconds
- Utils.schedule(m_unpublisher, 2000);
- }
-
- @Start
- Map start() {
- // At this point, our service properties are the one specified in our @Service annotation + the one specified by our Factory.
- // We also append an extra service property here:
- return new HashMap() {
- {
- put("foo3", "bar3");
- }
- };
- }
- }
-
- @Component
- public static class ProviderImplFactory {
- @ServiceDependency(filter = "(" + Component.FACTORY_NAME + "=" + FACTORY_SET + ")")
- void bind(Set<Dictionary> m_providerImplFactory) {
- m_providerImplFactory.add(new Hashtable() {
- {
- put("foo2", "bar2");
- }
- });
- }
- }
-}
diff --git a/dependencymanager/test/src/main/java/org/apache/felix/dm/test/components/Felix4050.java b/dependencymanager/test/src/main/java/org/apache/felix/dm/test/components/Felix4050.java
deleted file mode 100644
index 2a19d87..0000000
--- a/dependencymanager/test/src/main/java/org/apache/felix/dm/test/components/Felix4050.java
+++ /dev/null
@@ -1,154 +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.felix.dm.test.components;
-
-import java.util.ArrayList;
-import java.util.HashMap;
-import java.util.Hashtable;
-import java.util.List;
-import java.util.Map;
-
-import org.apache.felix.dm.annotation.api.Component;
-import org.apache.felix.dm.annotation.api.Destroy;
-import org.apache.felix.dm.annotation.api.Init;
-import org.apache.felix.dm.annotation.api.Inject;
-import org.apache.felix.dm.annotation.api.Property;
-import org.apache.felix.dm.annotation.api.ServiceDependency;
-import org.apache.felix.dm.annotation.api.Start;
-import org.apache.felix.dm.annotation.api.Stop;
-import org.osgi.framework.BundleContext;
-import org.osgi.framework.ServiceRegistration;
-
-public class Felix4050 {
- public final static String ENSURE = "Felix4050";
-
- @Component(provides = {A.class})
- public static class A {
-
- }
-
- public interface B {
- void run();
- }
-
- @Component(properties = {@Property(name = "type", value = "b1")})
- public static class B1 implements B {
- public void run() {
- }
- }
-
- @Component(provides = {})
- public static class B2 implements B {
- @Inject
- volatile BundleContext _ctx;
-
- @ServiceDependency(filter = "(name=" + ENSURE + ")")
- volatile Ensure m_sequencer;
-
- @Start
- void start() {
- Thread t = new Thread(new Runnable() {
- public void run() {
- try {
- Thread.sleep(2000);
- } catch (InterruptedException e) {
- }
- System.out.println("Registering B2");
- ServiceRegistration sr = _ctx.registerService(B.class.getName(), B2.this, new Hashtable() {
- {
- put("type", "b2");
- }
- });
-
- try {
- Thread.sleep(1000);
- } catch (InterruptedException e) {
- }
- }
- });
- t.start();
- }
-
- public void run() {
- m_sequencer.step(3);
- }
- }
-
- @Component
- public static class S {
- @ServiceDependency(filter = "(name=" + ENSURE + ")")
- volatile Ensure m_sequencer;
-
- @Inject
- volatile org.apache.felix.dm.Component _component;
-
- volatile A m_a;
- volatile B m_b;
-
- void bind(A a) {
- System.out.println("bind(A): " + a);
- m_a = a;
- }
-
- @ServiceDependency(name = "B")
- void bind(B b) {
- System.out.println("bind(B): " + b);
- m_b = b;
- }
-
- @Init
- Map init() {
- m_sequencer.step(1);
-
- List l = new ArrayList();
- l.add(_component.getDependencyManager().createServiceDependency().setService(A.class).setRequired(true)
- .setCallbacks("bind", null).setInstanceBound(true));
- _component.add(l);
-
- return new HashMap() {
- {
- put("B.required", "true");
- put("B.filter", "(type=b2)");
- }
- };
- }
-
- @Start
- void start() {
- if (m_a == null) {
- throw new RuntimeException("A not injected");
- }
- if (m_b == null) {
- throw new RuntimeException("B not injected");
- }
- m_sequencer.step(2);
- m_b.run(); // step(3)
- }
-
- @Stop
- void stop() {
- m_sequencer.step(4);
- }
-
- @Destroy
- void destroy() {
- m_sequencer.step(5);
- }
- }
-}
diff --git a/dependencymanager/test/src/main/java/org/apache/felix/dm/test/components/Felix4357.java b/dependencymanager/test/src/main/java/org/apache/felix/dm/test/components/Felix4357.java
deleted file mode 100644
index e3917b5..0000000
--- a/dependencymanager/test/src/main/java/org/apache/felix/dm/test/components/Felix4357.java
+++ /dev/null
@@ -1,142 +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.felix.dm.test.components;
-
-import java.util.Collections;
-
-import junit.framework.Assert;
-
-import org.apache.felix.dm.annotation.api.Component;
-import org.apache.felix.dm.annotation.api.Property;
-import org.apache.felix.dm.annotation.api.Registered;
-import org.apache.felix.dm.annotation.api.ServiceDependency;
-import org.osgi.framework.ServiceReference;
-import org.osgi.framework.ServiceRegistration;
-
-import com.sun.org.apache.xpath.internal.operations.Bool;
-
-/**
- * Checks support of primitive types for @Property annotation.
- */
-@Component(properties={
- @Property(name="v1", value="s"),
- @Property(name="v2", value={"s1", "s2"}),
- @Property(name="v3", values={"s1", "s2"}),
-
- @Property(name="v4", value="1", type=Long.class),
- @Property(name="v5", longValue=1),
- @Property(name="v6", longValue={1, 2}),
-
- @Property(name="v7", value="1", type=Double.class),
- @Property(name="v8", doubleValue=1),
- @Property(name="v9", doubleValue={1, 2}),
-
- @Property(name="v10", value="1", type=Float.class),
- @Property(name="v11", floatValue=1),
- @Property(name="v12", floatValue={1, 2}),
-
- @Property(name="v13", value="1", type=Integer.class),
- @Property(name="v14", intValue=1),
- @Property(name="v15", intValue={1, 2}),
-
- @Property(name="v16", value="65", type=Byte.class),
- @Property(name="v17", byteValue=65),
- @Property(name="v18", byteValue={65, 66}),
-
- @Property(name="v19", value="A", type=Character.class),
- @Property(name="v20", charValue='A'),
- @Property(name="v21", charValue={'A', 'B'}),
-
- @Property(name="v22", value="true", type=Boolean.class),
- @Property(name="v23", booleanValue=true),
- @Property(name="v24", booleanValue={true, false}),
-
- @Property(name="v25", value="1", type=Short.class),
- @Property(name="v26", shortValue=1),
- @Property(name="v27", shortValue={1, 2}),
-
- @Property(name="v28", value="65", type=Character.class),
- @Property(name="v29", charValue=65),
- @Property(name="v30", charValue={65, 66}),
- },
- provides=Felix4357.class
-)
-public class Felix4357 {
- public final static String ENSURE = "Felix4357";
-
- @ServiceDependency(filter = "(name=" + ENSURE + ")")
- volatile Ensure m_ensure;
-
- @Registered
- void registered(ServiceRegistration<?> sr) {
- ServiceReference<?> ref = sr.getReference();
- assertEquals(ref, "v1", "s", 1);
- assertArrayEquals(ref, "v2", new String[] {"s1", "s2"}, 2);
- assertArrayEquals(ref, "v3", new String[] {"s1", "s2"}, 3);
- assertEquals(ref, "v4", new Long(1), 4);
- assertEquals(ref, "v5", new Long(1), 5);
- assertArrayEquals(ref, "v6", new Long[] { 1L, 2L } , 6);
- assertEquals(ref, "v7", new Double(1), 7);
- assertEquals(ref, "v8", new Double(1), 8);
- assertArrayEquals(ref, "v9", new Double[] { 1.0, 2.0 } , 9);
- assertEquals(ref, "v10", new Float(1), 10);
- assertEquals(ref, "v11", new Float(1), 11);
- assertArrayEquals(ref, "v12", new Float[] { 1.f, 2.f } , 12);
- assertEquals(ref, "v13", new Integer(1), 13);
- assertEquals(ref, "v14", new Integer(1), 14);
- assertArrayEquals(ref, "v15", new Integer[] { 1, 2 } , 15);
- assertEquals(ref, "v16", Byte.valueOf("65"), 16);
- assertEquals(ref, "v17", Byte.valueOf("65"), 17);
- assertArrayEquals(ref, "v18", new Byte[] { Byte.valueOf("65"), Byte.valueOf("66") } , 18);
- assertEquals(ref, "v19", Character.valueOf('A'), 19);
- assertEquals(ref, "v20", Character.valueOf('A'), 20);
- assertArrayEquals(ref, "v21", new Character[] { 'A', 'B' } , 21);
- assertEquals(ref, "v22", Boolean.valueOf(true), 22);
- assertEquals(ref, "v23", Boolean.valueOf(true), 23);
- assertArrayEquals(ref, "v24", new Boolean[] { true, false } , 24);
- assertEquals(ref, "v25", Short.valueOf((short) 1), 25);
- assertEquals(ref, "v26", Short.valueOf((short) 1), 26);
- assertArrayEquals(ref, "v27", new Short[] { 1, 2 } , 27);
- assertEquals(ref, "v28", Character.valueOf('A'), 28);
- assertEquals(ref, "v29", Character.valueOf('A'), 29);
- assertArrayEquals(ref, "v30", new Character[] { 'A', 'B' } , 30);
- }
-
- void assertEquals(ServiceReference<?> ref, String property, Object expected, int step) {
- Object value = ref.getProperty(property);
- Assert.assertNotNull(value);
- Assert.assertEquals(value.getClass(), expected.getClass());
- Assert.assertEquals(value, expected);
- m_ensure.step(step);
- }
-
- void assertArrayEquals(ServiceReference<?> ref, String property, Object[] expected, int step) {
- Object values = ref.getProperty(property);
- Assert.assertNotNull(values);
- Assert.assertTrue(values.getClass().isArray());
- Assert.assertEquals(values.getClass(), expected.getClass());
- Object[] array = (Object[]) values;
- Assert.assertEquals(array.length, expected.length);
- for (int i = 0; i < array.length; i ++) {
- Assert.assertEquals(array[i].getClass(), expected[i].getClass());
- Assert.assertEquals(array[i], expected[i]);
- }
- m_ensure.step(step);
- }
-}
diff --git a/dependencymanager/test/src/main/java/org/apache/felix/dm/test/components/MultipleAnnotations.java b/dependencymanager/test/src/main/java/org/apache/felix/dm/test/components/MultipleAnnotations.java
deleted file mode 100644
index eb6c90c..0000000
--- a/dependencymanager/test/src/main/java/org/apache/felix/dm/test/components/MultipleAnnotations.java
+++ /dev/null
@@ -1,131 +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.felix.dm.test.components;
-
-import org.apache.felix.dm.annotation.api.Component;
-import org.apache.felix.dm.annotation.api.Composition;
-import org.apache.felix.dm.annotation.api.Property;
-import org.apache.felix.dm.annotation.api.ServiceDependency;
-import org.apache.felix.dm.annotation.api.Start;
-import org.apache.felix.dm.annotation.api.Stop;
-
-public class MultipleAnnotations {
- public final static String ENSURE = "MultipleAnnotations";
-
- public static class Composite {
- void bind(Ensure seq) {
- seq.step(2);
- }
- }
-
- @Component
- public static class ServiceConsumer {
- @ServiceDependency(filter="(name=" + ENSURE + ")")
- volatile Ensure m_sequencer;
-
- @ServiceDependency(filter = "(foo=bar)")
- volatile ServiceInterface m_service;
-
- @Start
- void start() {
- m_sequencer.step(6);
- m_service.doService();
- }
-
- @Stop
- void stop() {
- m_sequencer.step(8);
- }
- }
-
- public interface ServiceInterface {
- public void doService();
- }
-
- @Component(properties = {@Property(name = "foo", value = "bar")})
- public static class ServiceProvider implements ServiceInterface {
- @ServiceDependency(filter="(name=" + ENSURE + ")")
- volatile Ensure m_sequencer;
-
- volatile ServiceProvider2 m_serviceProvider2;
-
- @ServiceDependency(removed = "unbind")
- void bind(ServiceProvider2 provider2) {
- m_serviceProvider2 = provider2;
- }
-
- @Start
- void start() {
- m_serviceProvider2.step(4);
- m_sequencer.step(5);
- }
-
- @Stop
- void stop() {
- m_sequencer.step(9);
- }
-
- void unbind(ServiceProvider2 provider2) {
- m_sequencer.step(10);
- }
-
- public void doService() {
- m_sequencer.step(7);
- }
- }
-
- @Component(provides = {ServiceProvider2.class}, factoryMethod = "create")
- public static class ServiceProvider2 {
- final Composite m_composite = new Composite();
- volatile Ensure m_sequencer;
-
- static ServiceProvider2 create() {
- return new ServiceProvider2();
- }
-
- @ServiceDependency(required = false, filter = "(foo=bar)") // NullObject
- volatile Runnable m_runnable;
-
- @ServiceDependency(service = Ensure.class, filter="(name=" + ENSURE + ")")
- void bind(Ensure seq) {
- m_sequencer = seq;
- m_sequencer.step(1);
- }
-
- @Start
- void start() {
- m_sequencer.step(3);
- m_runnable.run(); // NullObject
- }
-
- public void step(int step) { // called by ServiceProvider.start() method
- m_sequencer.step(step);
- }
-
- @Stop
- void stop() {
- m_sequencer.step(11);
- }
-
- @Composition
- Object[] getComposition() {
- return new Object[]{this, m_composite};
- }
- }
-}
diff --git a/dependencymanager/test/src/main/java/org/apache/felix/dm/test/components/PropagateAnnotation.java b/dependencymanager/test/src/main/java/org/apache/felix/dm/test/components/PropagateAnnotation.java
deleted file mode 100644
index e02f5a3..0000000
--- a/dependencymanager/test/src/main/java/org/apache/felix/dm/test/components/PropagateAnnotation.java
+++ /dev/null
@@ -1,67 +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.felix.dm.test.components;
-
-import java.util.Map;
-
-import org.apache.felix.dm.annotation.api.Component;
-import org.apache.felix.dm.annotation.api.Property;
-import org.apache.felix.dm.annotation.api.ServiceDependency;
-import org.apache.felix.dm.annotation.api.Start;
-
-/**
- * Verifies ServiceDependencyservice properties propagation.
- */
-public class PropagateAnnotation {
- public final static String ENSURE = "PropagateAnnotation";
-
- @Component
- public static class Consumer {
- private volatile Map m_producerProps;
-
- @ServiceDependency
- void bind(Map props, Producer producer) {
- m_producerProps = props;
- }
-
- @ServiceDependency(filter = "(name=" + ENSURE + ")")
- volatile Ensure m_sequencer;
-
- @Start
- void start() {
- m_sequencer.step(1);
- if ("bar".equals(m_producerProps.get("foo"))) {
- m_sequencer.step(2);
- }
- if ("bar2".equals(m_producerProps.get("foo2"))) {
- m_sequencer.step(3);
- }
- }
- }
-
- @Component(provides = {Producer.class}, properties = {@Property(name = "foo", value = "bar")})
- public static class Producer {
- @ServiceDependency(propagate = true)
- volatile Producer2 m_producer;
- }
-
- @Component(provides = {Producer2.class}, properties = {@Property(name = "foo2", value = "bar2")})
- public static class Producer2 {
- }
-}
diff --git a/dependencymanager/test/src/main/java/org/apache/felix/dm/test/components/ResourceAdapterServiceTestWithPublisher.java b/dependencymanager/test/src/main/java/org/apache/felix/dm/test/components/ResourceAdapterServiceTestWithPublisher.java
deleted file mode 100644
index 291d2a7..0000000
--- a/dependencymanager/test/src/main/java/org/apache/felix/dm/test/components/ResourceAdapterServiceTestWithPublisher.java
+++ /dev/null
@@ -1,193 +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.felix.dm.test.components;
-
-import java.net.URL;
-import java.util.HashMap;
-import java.util.Map;
-import java.util.Map.Entry;
-
-import junit.framework.Assert;
-
-import org.apache.felix.dm.ResourceHandler;
-import org.apache.felix.dm.ResourceUtil;
-import org.apache.felix.dm.annotation.api.Component;
-import org.apache.felix.dm.annotation.api.Destroy;
-import org.apache.felix.dm.annotation.api.Init;
-import org.apache.felix.dm.annotation.api.Inject;
-import org.apache.felix.dm.annotation.api.LifecycleController;
-import org.apache.felix.dm.annotation.api.Property;
-import org.apache.felix.dm.annotation.api.ResourceAdapterService;
-import org.apache.felix.dm.annotation.api.ServiceDependency;
-import org.apache.felix.dm.annotation.api.Start;
-import org.osgi.framework.BundleContext;
-import org.osgi.framework.Filter;
-import org.osgi.framework.InvalidSyntaxException;
-
-/**
- * Test a ResourceAdapterService which provides its interface using a @ServiceLifecycle.
- */
-public class ResourceAdapterServiceTestWithPublisher {
- public static final String ENSURE = "ResourceAdapterServiceTestWithPublisher";
-
- public interface Provider {
- }
-
- @Component
- public static class Consumer {
- @ServiceDependency(filter = "(name=" + ENSURE + ")")
- volatile Ensure m_sequencer;
-
- @ServiceDependency(required = false, removed = "unbind")
- void bind(Map properties, Provider provider) {
- m_sequencer.step(1);
- // check ProviderImpl properties
- if ("bar".equals(properties.get("foo"))) {
- m_sequencer.step(2);
- }
- // check extra ProviderImpl properties (returned by start method)
- if ("bar2".equals(properties.get("foo2"))) {
- m_sequencer.step(3);
- }
- // check properties propagated by the resource adapter
- if ("/path/to/test1.txt".equals(properties.get(ResourceHandler.PATH))) {
- m_sequencer.step(4);
- }
- if ("localhost".equals(properties.get(ResourceHandler.HOST))) {
- m_sequencer.step(5);
- }
- }
-
- void unbind(Provider provider) {
- m_sequencer.step(6);
- }
- }
-
- @Component
- public static class ResourceProvider {
- @ServiceDependency(filter = "(name=" + ENSURE + ")")
- volatile Ensure m_sequencer;
-
- @Inject
- private volatile BundleContext m_context;
- private final Map m_handlers = new HashMap();
- private URL[] m_resources;
-
- public ResourceProvider() throws Exception {
- m_resources = new URL[]{new URL("file://localhost/path/to/test1.txt"),
- new URL("file://localhost/path/to/test2.txt"), new URL("file://localhost/path/to/README.doc")};
- }
-
- /**
- * Handles a new Resource consumer
- * @param serviceProperties
- * @param handler
- */
- @ServiceDependency(removed = "remove", required = false)
- public void add(Map serviceProperties, ResourceHandler handler) {
- String filterString = (String) serviceProperties.get("filter");
- Filter filter = null;
- if (filterString != null) {
- try {
- filter = m_context.createFilter(filterString);
- } catch (InvalidSyntaxException e) {
- Assert.fail("Could not create filter for resource handler: " + e);
- return;
- }
- }
- synchronized (m_handlers) {
- m_handlers.put(handler, filter);
- }
- for (int i = 0; i < m_resources.length; i++) {
- if (filter == null || filter.match(ResourceUtil.createProperties(m_resources[i]))) {
- handler.added(m_resources[i]);
- }
- }
- }
-
- /**
- * Remove a Resource consumer.bar
- * @param handler
- */
- public void remove(ResourceHandler handler) {
- Filter filter;
- synchronized (m_handlers) {
- filter = (Filter) m_handlers.remove(handler);
- }
- removeResources(handler, filter);
- }
-
- private void removeResources(ResourceHandler handler, Filter filter) {
- for (int i = 0; i < m_resources.length; i++) {
- if (filter == null || filter.match(ResourceUtil.createProperties(m_resources[i]))) {
- handler.removed(m_resources[i]);
- }
- }
- }
-
- /**
- * Our component is being destroyed: notify all our registered Resource consumers that we don't
- * provide our Resources anymore.
- */
- @Destroy
- public void destroy() {
- Entry[] handlers;
- synchronized (m_handlers) {
- handlers = (Entry[]) m_handlers.entrySet().toArray(new Entry[m_handlers.size()]);
- }
- for (int i = 0; i < handlers.length; i++) {
- removeResources((ResourceHandler) handlers[i].getKey(), (Filter) handlers[i].getValue());
- }
- }
- }
-
- @ResourceAdapterService(filter = "(&(path=/path/to/test1.txt)(host=localhost))", properties = {@Property(name = "foo", value = "bar")}, propagate = true)
- public static class ProviderImpl implements Provider {
- @LifecycleController
- volatile Runnable m_publisher; // injected and used to register our service
-
- @LifecycleController(start = false)
- volatile Runnable m_unpublisher; // injected and used to unregister our service
-
- @ServiceDependency(filter = "(name=" + ENSURE + ")")
- volatile Ensure m_sequencer;
-
- // Injected by reflection
- volatile URL m_resource;
-
- @Init
- void init() {
- // register service in 1 second
- Utils.schedule(m_publisher, 1000);
- // unregister the service in 2 seconds
- Utils.schedule(m_unpublisher, 2000);
- }
-
- @Start
- Map start() {
- // Add some extra service properties ... they will be appended to the one we have defined
- // in the @Service annotation.
- return new HashMap() {
- {
- put("foo2", "bar2");
- }
- };
- }
- }
-}
diff --git a/dependencymanager/test/src/main/java/org/apache/felix/dm/test/components/ResourceAnnotation.java b/dependencymanager/test/src/main/java/org/apache/felix/dm/test/components/ResourceAnnotation.java
deleted file mode 100644
index 0204d4a..0000000
--- a/dependencymanager/test/src/main/java/org/apache/felix/dm/test/components/ResourceAnnotation.java
+++ /dev/null
@@ -1,287 +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.felix.dm.test.components;
-
-import java.net.URL;
-import java.util.HashMap;
-import java.util.Map;
-import java.util.Map.Entry;
-
-import junit.framework.Assert;
-
-import org.apache.felix.dm.DependencyManager;
-import org.apache.felix.dm.ResourceHandler;
-import org.apache.felix.dm.ResourceUtil;
-import org.apache.felix.dm.annotation.api.Component;
-import org.apache.felix.dm.annotation.api.Destroy;
-import org.apache.felix.dm.annotation.api.Init;
-import org.apache.felix.dm.annotation.api.Inject;
-import org.apache.felix.dm.annotation.api.Property;
-import org.apache.felix.dm.annotation.api.ResourceAdapterService;
-import org.apache.felix.dm.annotation.api.ResourceDependency;
-import org.apache.felix.dm.annotation.api.ServiceDependency;
-import org.apache.felix.dm.annotation.api.Start;
-import org.apache.felix.dm.annotation.api.Stop;
-import org.osgi.framework.BundleContext;
-import org.osgi.framework.Filter;
-import org.osgi.framework.InvalidSyntaxException;
-
-public class ResourceAnnotation {
- public final static String ENSURE_RESOURCE = "ResourceAnnotation.resource";
- public final static String ENSURE_FIELD = "ResourceAnnotation.field";
- public final static String ENSURE_ADAPTER = "ResourceAnnotation.adapter";
- public final static String ENSURE_PROVIDER = "ResourceAnnotation.provider";
-
- /**
- * A Service provided the ServiceProvider, which is a ResourceAdapter.
- */
- public interface ServiceInterface extends Runnable {
- }
-
- /**
- * A Component which has a resource dependency.
- */
- @Component
- public static class ResourceConsumer {
- @ServiceDependency(required = true, filter = "(name=" + ENSURE_RESOURCE + ")")
- volatile Ensure m_sequencer;
-
- private volatile int m_resourcesSeen;
-
- @Start
- void start() {
- System.out.println("ResourceConsumer.start: sequencer=" + m_sequencer);
- }
-
- @ResourceDependency(required = false, filter = "(&(path=/path/to/*.txt)(host=localhost))")
- public void add(URL resource) {
- System.out.println("ResourceConsumer.add: resource=" + resource + ", m_sequencer=" + m_sequencer);
- if (match(resource, "file://localhost/path/to/test1.txt")) {
- m_resourcesSeen++;
- return;
- }
-
- if (match(resource, "file://localhost/path/to/test2.txt")) {
- m_resourcesSeen++;
- return;
- }
-
- Assert.fail("Got unexpected resource: " + resource);
- }
-
- private boolean match(URL resource, String url) {
- return url.equals(resource.toString());
- }
-
- @Stop
- void stop() {
- System.out.println("ResourceConsumer.stop: m_sequencer=" + m_sequencer);
- Assert.assertEquals(2, m_resourcesSeen);
- m_sequencer.step(1);
- }
- }
-
- /**
- * A Component which as a resource dependency, using a class field.
- */
- @Component
- public static class ResourceConsumerField {
- @ServiceDependency(required = true, filter = "(name=" + ENSURE_FIELD + ")")
- volatile Ensure m_sequencer;
-
- @ResourceDependency(filter = "(&(path=*/test1.txt)(host=localhost))")
- URL m_resource;
-
- @Init
- void init() {
- if (m_resource != null) {
- Assert.assertTrue("file://localhost/path/to/test1.txt".equals(m_resource.toString()));
- m_sequencer.step(1);
- }
- }
- }
-
- /**
- * Provides some simple resources.
- */
- @Component
- public static class ResourceProvider {
- @ServiceDependency(required = true, filter = "(name=" + ENSURE_PROVIDER + ")")
- volatile Ensure m_sequencer;
-
- @Inject
- private volatile BundleContext m_context;
- private final Map m_handlers = new HashMap();
- private final URL[] m_resources;
-
- public ResourceProvider() throws Exception {
- m_resources = new URL[]{
- new URL("file://localhost/path/to/test1.txt"),
- new URL("file://localhost/path/to/test2.txt"),
- new URL("file://localhost/path/to/README.doc")};
- }
-
- /**
- * Handles a new Resource consumer
- * @param serviceProperties
- * @param handler
- */
- @ServiceDependency(removed = "remove", required = false)
- public void add(Map serviceProperties, ResourceHandler handler) {
- System.out.println("ResourceProvider.addResourceHandler " + handler);
- String filterString = (String) serviceProperties.get("filter");
- Filter filter = null;
- if (filterString != null) {
- try {
- filter = m_context.createFilter(filterString);
- } catch (InvalidSyntaxException e) {
- Assert.fail("Could not create filter for resource handler: " + e);
- return;
- }
- }
- synchronized (m_handlers) {
- m_handlers.put(handler, filter);
- }
- for (int i = 0; i < m_resources.length; i++) {
- if (filter == null || filter.match(ResourceUtil.createProperties(m_resources[i]))) {
- System.out.println("ResourceProvider: calling handled.added(" + m_resources[i] + ")");
- handler.added(m_resources[i], null);
- }
- }
- }
-
- /**
- * Remove a Resource consumer.
- * @param handler
- */
- public void remove(ResourceHandler handler) {
- System.out.println("ResourceProvider.removeResourceHandler " + handler);
-
- Filter filter;
- synchronized (m_handlers) {
- filter = (Filter) m_handlers.remove(handler);
- }
- removeResources(handler, filter);
- }
-
- private void removeResources(ResourceHandler handler, Filter filter) {
- for (int i = 0; i < m_resources.length; i++) {
- if (filter == null || filter.match(ResourceUtil.createProperties(m_resources[i]))) {
- handler.removed(m_resources[i], null);
- }
- }
- }
-
- /**
- * Our component is being destroyed: notify all our registered Resource consumers that we don't
- * provide our Resources anymore.
- */
- @Destroy
- public void destroy() {
- Entry[] handlers;
- synchronized (m_handlers) {
- handlers = (Entry[]) m_handlers.entrySet().toArray(new Entry[m_handlers.size()]);
- }
- for (int i = 0; i < handlers.length; i++) {
- removeResources((ResourceHandler) handlers[i].getKey(), (Filter) handlers[i].getValue());
- }
- }
- }
-
- /**
- * Our ServiceInterface provider, which service is activated by a ResourceAdapter.
- */
- @ResourceAdapterService(filter = "(&(path=/path/to/test1.txt)(host=localhost))", properties = {@Property(name = "foo", value = "bar")}, propagate = true)
- public static class ServiceProvider implements ServiceInterface {
- // Injected by reflection
- URL m_resource;
-
- @ServiceDependency(filter = "(name=" + ENSURE_ADAPTER + ")")
- Ensure m_sequencer;
-
- // Check auto config injections
- @Inject
- BundleContext m_bc;
- BundleContext m_bcNotInjected;
-
- @Inject
- DependencyManager m_dm;
- DependencyManager m_dmNotInjected;
-
- @Inject
- org.apache.felix.dm.Component m_component;
- org.apache.felix.dm.Component m_componentNotInjected;
-
- public void run() {
- checkInjectedFields();
- Assert.assertNotNull("Resource has not been injected in the adapter", m_resource);
- Assert.assertEquals("ServiceProvider did not get expected resource", "file://localhost/path/to/test1.txt",
- m_resource.toString());
- m_sequencer.step(2);
- }
-
- private void checkInjectedFields() {
- if (m_bc == null) {
- m_sequencer.throwable(new Exception("Bundle Context not injected"));
- return;
- }
- if (m_bcNotInjected != null) {
- m_sequencer.throwable(new Exception("Bundle Context must not be injected"));
- return;
- }
-
- if (m_dm == null) {
- m_sequencer.throwable(new Exception("DependencyManager not injected"));
- return;
- }
- if (m_dmNotInjected != null) {
- m_sequencer.throwable(new Exception("DependencyManager must not be injected"));
- return;
- }
-
- if (m_component == null) {
- m_sequencer.throwable(new Exception("Component not injected"));
- return;
- }
- if (m_componentNotInjected != null) {
- m_sequencer.throwable(new Exception("Component must not be injected"));
- return;
- }
- }
- }
-
- /**
- * A Component with a dependency over the ServiceInterface, which is actually provided
- * by a ResourceAdapter.
- */
- @Component
- public static class ServiceConsumer {
- @ServiceDependency
- ServiceInterface m_serviceInterface;
-
- @ServiceDependency(filter = "(name=" + ENSURE_ADAPTER + ")")
- Ensure m_sequencer;
-
- @Start
- void start() {
- m_sequencer.step(1);
- m_serviceInterface.run();
- }
- }
-}
diff --git a/dependencymanager/test/src/main/java/org/apache/felix/dm/test/components/ServiceFactoryAnnotation.java b/dependencymanager/test/src/main/java/org/apache/felix/dm/test/components/ServiceFactoryAnnotation.java
deleted file mode 100644
index 45f34f3..0000000
--- a/dependencymanager/test/src/main/java/org/apache/felix/dm/test/components/ServiceFactoryAnnotation.java
+++ /dev/null
@@ -1,176 +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.felix.dm.test.components;
-
-import java.util.Dictionary;
-import java.util.HashMap;
-import java.util.Map;
-
-import junit.framework.Assert;
-
-import org.apache.felix.dm.annotation.api.Component;
-import org.apache.felix.dm.annotation.api.Init;
-import org.apache.felix.dm.annotation.api.Property;
-import org.apache.felix.dm.annotation.api.ServiceDependency;
-import org.apache.felix.dm.annotation.api.Start;
-import org.apache.felix.dm.annotation.api.Stop;
-
-public class ServiceFactoryAnnotation {
- public final static String FACTORY = "ServiceFactoryAnnotation.Factory";
- public final static String ENSURE = "ServiceFactoryAnnotation.Ensure";
-
- public interface MyServiceInterface {
- public void added(String instanceId);
-
- public void changed(String modified);
-
- public void removed();
- }
-
- @Component(properties = @Property(name = "foo", value = "bar"))
- public static class ExtraDependency1 implements Runnable {
- public void run() {
- }
- }
-
- @Component(properties = @Property(name = "foo", value = "bar2"))
- public static class ExtraDependency2 implements Runnable {
- public void run() {
- System.out.println("ExtraDependency2.run()");
- }
- }
-
- /**
- * This service is instantiated using a "factory set" from the
- * ServiceFactoryAnnotationTest class.
- *
- * @see org.apache.felix.dm.test.annotation.ServiceFactoryAnnotationTest
- */
- @Component(factorySet = FACTORY, factoryConfigure = "configure", properties = {@Property(name = "foo", value = "bar")})
- public static class MyService implements MyServiceInterface {
- /**
- * The configuration provided by MyServiceFactory
- */
- @SuppressWarnings("unchecked")
- volatile Dictionary m_configuration;
-
- /**
- * Our sequencer.
- */
- @ServiceDependency(filter = "(name=" + ENSURE + ")")
- volatile Ensure m_sequencer;
-
- /**
- * An extra dependency (we'll dynamically configure the filter from our
- * init() method).
- */
- @ServiceDependency(name = "extra")
- Runnable m_extra;
-
- /**
- * This is the first method called: we are provided with the
- * MyServiceFactory configuration.
- */
- public void configure(Dictionary<?, ?> configuration) {
- if (m_configuration == null) {
- m_configuration = configuration;
- } else {
- m_sequencer.step(5);
- }
- }
-
- /**
- * Initialize our Service: we'll dynamically configure our dependency whose
- * name is "extra".
- */
- @Init
- Map init() {
- return new HashMap() {
- {
- put("extra.filter", "(foo=bar2)");
- put("extra.required", "true");
- }
- };
- }
-
- /**
- * our Service is starting: at this point, all required dependencies have
- * been injected.
- */
- @Start
- public void start() {
- Assert.assertNotNull("Extra dependency not injected", m_extra);
- m_extra.run();
- m_sequencer.step(2);
- }
-
- /**
- * Our service is stopping.
- */
- @Stop
- public void stop() {
- m_sequencer.step(10);
- }
-
- public void added(String instanceId) {
- if (instanceId.equals(m_configuration.get("instance.id"))) {
- m_sequencer.step(4);
- }
- }
-
- public void changed(String modified) {
- if (modified.equals(m_configuration.get("instance.modified"))) {
- m_sequencer.step(7);
- }
- }
-
- public void removed() {
- m_sequencer.step(9);
- }
- }
-
- @Component
- public static class MyServiceClient {
- @ServiceDependency(filter = "(name=" + ENSURE + ")")
- volatile Ensure m_sequencer;
-
- @Start
- void start() {
- m_sequencer.step(1);
- }
-
- @ServiceDependency(required = false, changed = "update", removed = "removed")
- void bind(Map serviceProperties, MyServiceInterface service) {
- m_sequencer.step(3);
- Assert.assertEquals("bar", serviceProperties.get("foo"));
- Assert.assertNull(serviceProperties.get(".private.param"));
- service.added((String) serviceProperties.get("instance.id"));
- }
-
- void update(Map serviceProperties, MyServiceInterface service) {
- m_sequencer.step(6);
- service.changed((String) serviceProperties.get("instance.modified"));
- }
-
- void removed(MyServiceInterface service) {
- m_sequencer.step(8);
- service.removed();
- }
- }
-}
diff --git a/dependencymanager/test/src/main/java/org/apache/felix/dm/test/components/ServiceTestWthPublisher.java b/dependencymanager/test/src/main/java/org/apache/felix/dm/test/components/ServiceTestWthPublisher.java
deleted file mode 100644
index eabd3ff..0000000
--- a/dependencymanager/test/src/main/java/org/apache/felix/dm/test/components/ServiceTestWthPublisher.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.felix.dm.test.components;
-
-import java.util.HashMap;
-import java.util.Map;
-
-import org.apache.felix.dm.annotation.api.Component;
-import org.apache.felix.dm.annotation.api.Init;
-import org.apache.felix.dm.annotation.api.LifecycleController;
-import org.apache.felix.dm.annotation.api.Property;
-import org.apache.felix.dm.annotation.api.ServiceDependency;
-import org.apache.felix.dm.annotation.api.Start;
-
-/**
- * A Service that just registers/unregisters its service, using the @ServiceLifecycle annotation.
- */
-public class ServiceTestWthPublisher {
- public final static String ENSURE = "ServiceTestWthPublisher";
-
- public interface Provider {
- }
-
- @Component
- public static class Consumer {
- @ServiceDependency(filter = "(name=" + ENSURE + ")")
- volatile Ensure m_sequencer;
-
- @ServiceDependency(required = false, removed = "unbind")
- void bind(Map properties, Provider provider) {
- m_sequencer.step(1);
- if ("bar".equals(properties.get("foo"))) {
- m_sequencer.step(2);
- }
- if ("bar2".equals(properties.get("foo2"))) {
- m_sequencer.step(3);
- }
- }
-
- void unbind(Provider provider) {
- m_sequencer.step(4);
- }
- }
-
- @Component(properties = {@Property(name = "foo", value = "bar")})
- public static class ProviderImpl implements Provider {
- @LifecycleController
- volatile Runnable m_publisher; // injected and used to register our service
-
- @LifecycleController(start = false)
- volatile Runnable m_unpublisher; // injected and used to unregister our service
-
- @ServiceDependency(filter = "(name=" + ENSURE + ")")
- volatile Ensure m_sequencer;
-
- @Init
- void init() {
- // register service in 1 second
- Utils.schedule(m_publisher, 1000);
- // unregister the service in 2 seconds
- Utils.schedule(m_unpublisher, 2000);
- }
-
- @Start
- Map start() {
- // Add some extra service properties ... they will be appended to the one we have defined
- // in the @Service annotation.
- return new HashMap() {
- {
- put("foo2", "bar2");
- }
- };
- }
- }
-}
diff --git a/dependencymanager/test/src/main/java/org/apache/felix/dm/test/components/SimpleAnnotations.java b/dependencymanager/test/src/main/java/org/apache/felix/dm/test/components/SimpleAnnotations.java
deleted file mode 100644
index 1ac78aa..0000000
--- a/dependencymanager/test/src/main/java/org/apache/felix/dm/test/components/SimpleAnnotations.java
+++ /dev/null
@@ -1,179 +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.felix.dm.test.components;
-
-import org.apache.felix.dm.DependencyManager;
-import org.apache.felix.dm.annotation.api.Component;
-import org.apache.felix.dm.annotation.api.Destroy;
-import org.apache.felix.dm.annotation.api.Init;
-import org.apache.felix.dm.annotation.api.Inject;
-import org.apache.felix.dm.annotation.api.Property;
-import org.apache.felix.dm.annotation.api.Registered;
-import org.apache.felix.dm.annotation.api.ServiceDependency;
-import org.apache.felix.dm.annotation.api.Start;
-import org.apache.felix.dm.annotation.api.Stop;
-import org.apache.felix.dm.annotation.api.Unregistered;
-import org.osgi.framework.BundleContext;
-import org.osgi.framework.ServiceRegistration;
-import org.osgi.service.log.LogService;
-
-public class SimpleAnnotations {
- /**
- * Provides a <code>Runnable</code> service, which is required by the
- * {@link Consumer} class.
- */
- @Component(properties = {@Property(name = "foo", value = "bar"), @Property(name="type", value="SimpleAnnotations")})
- public static class Producer implements Runnable {
- public final static String ENSURE = "SimpleAnnotations.Producer";
-
- @ServiceDependency(filter = "(name=" + ENSURE + ")")
- volatile Ensure _ensure;
-
- @ServiceDependency
- volatile LogService _logService;
-
- @Inject
- volatile BundleContext _ctx;
-
- @Init
- protected void init() {
- _logService.log(LogService.LOG_INFO, "producer.init");
- // Our component is initializing (at this point: all required
- // dependencies are injected).
- _ensure.step(1);
- }
-
- @Start
- protected void start() {
- // We are about to be registered in the OSGi registry.
- _ensure.step(2);
- }
-
- @Registered
- protected void registered(ServiceRegistration sr) {
- _logService.log(LogService.LOG_INFO, "Registered");
- if (sr == null) {
- _ensure.throwable(new Exception("ServiceRegistration is null"));
- }
- if (!"bar".equals(sr.getReference().getProperty("foo"))) {
- _ensure.throwable(new Exception("Invalid Service Properties"));
- }
- _ensure.step(3);
- }
-
- public void run() {
- _ensure.step(5);
- }
-
- @Stop
- protected void stop() {
- // We are about to be unregistered from the OSGi registry, and we
- // must stop.
- _ensure.step(8);
- }
-
- @Unregistered
- protected void stopped() {
- // We are unregistered from the OSGi registry.
- _ensure.step(9);
- }
-
- @Destroy
- public void destroy() {
- // Our component is shutting down.
- _ensure.step(10);
- }
- }
-
- /**
- * Consumes a service which is provided by the {@link Producer} class.
- */
- @Component
- public static class Consumer {
- public final static String ENSURE = "SimpleAnnotations.Consumer";
-
- @ServiceDependency
- volatile LogService _logService;
-
- @ServiceDependency(filter="(type=SimpleAnnotations)")
- volatile Runnable _runnable;
-
- @ServiceDependency(filter = "(name=" + ENSURE + ")")
- volatile Ensure _ensure;
-
- @Inject
- volatile BundleContext _bc;
- BundleContext _bcNotInjected;
-
- @Inject
- volatile DependencyManager _dm;
- DependencyManager _dmNotInjected;
-
- @Inject
- volatile org.apache.felix.dm.Component _component;
- org.apache.felix.dm.Component _componentNotInjected;
-
- @Start
- protected void start() {
- _logService.log(LogService.LOG_INFO, "Consumer.START: ");
- checkInjectedFields();
- _ensure.step(4);
- _runnable.run();
- }
-
- private void checkInjectedFields() {
- if (_bc == null) {
- _ensure.throwable(new Exception("Bundle Context not injected"));
- return;
- }
- if (_bcNotInjected != null) {
- _ensure.throwable(new Exception("Bundle Context must not be injected"));
- return;
- }
-
- if (_dm == null) {
- _ensure.throwable(new Exception("DependencyManager not injected"));
- return;
- }
- if (_dmNotInjected != null) {
- _ensure.throwable(new Exception("DependencyManager must not be injected"));
- return;
- }
-
- if (_component == null) {
- _ensure.throwable(new Exception("Component not injected"));
- return;
- }
- if (_componentNotInjected != null) {
- _ensure.throwable(new Exception("Component must not be injected"));
- return;
- }
- }
-
- @Stop
- protected void stop() {
- _ensure.step(6);
- }
-
- @Destroy
- void destroy() {
- _ensure.step(7);
- }
- }
-}
diff --git a/dependencymanager/test/src/main/java/org/apache/felix/dm/test/components/TemporalAnnotations.java b/dependencymanager/test/src/main/java/org/apache/felix/dm/test/components/TemporalAnnotations.java
deleted file mode 100644
index c022c45..0000000
--- a/dependencymanager/test/src/main/java/org/apache/felix/dm/test/components/TemporalAnnotations.java
+++ /dev/null
@@ -1,66 +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.felix.dm.test.components;
-
-import org.apache.felix.dm.annotation.api.Component;
-import org.apache.felix.dm.annotation.api.ServiceDependency;
-import org.apache.felix.dm.annotation.api.Start;
-import org.apache.felix.dm.annotation.api.Stop;
-
-/**
- * Service using an annotated Temporal Service dependency.
- */
-@Component(provides = {})
-public class TemporalAnnotations implements Runnable {
- public final static String ENSURE = "TemporalAnnotations";
- Thread m_thread;
-
- @ServiceDependency(filter = "(name=" + ENSURE + ")")
- volatile Ensure m_sequencer;
-
- @ServiceDependency(timeout = 1000L, filter = "(test=temporal)")
- volatile Runnable m_service;
-
- @Start
- protected void start() {
- m_thread = new Thread(this);
- m_thread.start();
- }
-
- @Stop
- protected void stop() {
- m_thread.interrupt();
- try {
- m_thread.join();
- } catch (InterruptedException e) {
- }
- }
-
- public void run() {
- m_service.run();
- m_sequencer.waitForStep(2, 15000);
- m_service.run(); // we should block here
- m_sequencer.waitForStep(4, 15000);
- try {
- m_service.run(); // should raise IllegalStateException
- } catch (IllegalStateException e) {
- m_sequencer.step(5);
- }
- }
-}
diff --git a/dependencymanager/test/src/main/java/org/apache/felix/dm/test/components/Utils.java b/dependencymanager/test/src/main/java/org/apache/felix/dm/test/components/Utils.java
deleted file mode 100644
index 98b5235..0000000
--- a/dependencymanager/test/src/main/java/org/apache/felix/dm/test/components/Utils.java
+++ /dev/null
@@ -1,36 +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.felix.dm.test.components;
-
-public class Utils {
- public static void schedule(final Runnable task, final long n) {
- Thread t = new Thread() {
- public void run() {
- try {
- sleep(n);
- } catch (InterruptedException e) {
- // TODO Auto-generated catch block
- e.printStackTrace();
- }
- task.run();
- }
- };
- t.start();
- }
-}
diff --git a/dependencymanager/test/src/test/java/org/apache/felix/dm/test/integration/annotations/AdapterAnnotationTest.java b/dependencymanager/test/src/test/java/org/apache/felix/dm/test/integration/annotations/AdapterAnnotationTest.java
deleted file mode 100644
index 34dcf64..0000000
--- a/dependencymanager/test/src/test/java/org/apache/felix/dm/test/integration/annotations/AdapterAnnotationTest.java
+++ /dev/null
@@ -1,90 +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.felix.dm.test.integration.annotations;
-
-import org.apache.felix.dm.test.components.Ensure;
-import org.apache.felix.dm.test.components.AdapterAnnotation.S1Impl;
-import org.apache.felix.dm.test.components.AdapterAnnotation.S1ToS3AdapterAutoConfig;
-import org.apache.felix.dm.test.components.AdapterAnnotation.S1ToS3AdapterAutoConfigField;
-import org.apache.felix.dm.test.components.AdapterAnnotation.S1ToS3AdapterCallback;
-import org.apache.felix.dm.test.components.AdapterAnnotation.S2Impl;
-import org.apache.felix.dm.test.integration.common.TestBase;
-import org.junit.Test;
-import org.junit.runner.RunWith;
-import org.ops4j.pax.exam.junit.PaxExam;
-import org.osgi.framework.ServiceRegistration;
-
-/**
- * Use case: Verify Aspect Annotations usage.
- */
-@RunWith(PaxExam.class)
-public class AdapterAnnotationTest extends TestBase {
- public AdapterAnnotationTest() {
- super(true /* start test components bundle */);
- }
-
- /**
- * Check if an adapter gets injected with its adaptee using default auto config mode.
- * @throws Throwable
- */
- @Test
- public void testAnnotatedAdapterAutoConfig() throws Throwable {
- Ensure e = new Ensure();
- ServiceRegistration sr1 = register(e, S1ToS3AdapterAutoConfig.ENSURE);
- ServiceRegistration sr2 = register(e, S1Impl.ENSURE);
- ServiceRegistration sr3 = register(e, S2Impl.ENSURE);
- e.waitForStep(3, 10000);
- e.ensure();
- sr1.unregister();
- sr2.unregister();
- sr3.unregister();
- }
-
- /**
- * Check if an adapter gets injected with its adaptee in a named class field.
- */
- @Test
- public void testAnnotatedAdapterAutoConfigField() throws Throwable {
- Ensure e = new Ensure();
- ServiceRegistration sr1 = register(e, S1ToS3AdapterAutoConfigField.ENSURE);
- ServiceRegistration sr2 = register(e, S1Impl.ENSURE);
- ServiceRegistration sr3 = register(e, S2Impl.ENSURE);
- e.waitForStep(3, 10000);
- e.ensure();
- sr1.unregister();
- sr2.unregister();
- sr3.unregister();
- }
-
- /**
- * Check if an adapter gets injected with its adaptee in a callback method.
- */
- @Test
- public void testAnnotatedAdapterCallback() {
- Ensure e = new Ensure();
- ServiceRegistration sr1 = register(e, S1ToS3AdapterCallback.ENSURE);
- ServiceRegistration sr2 = register(e, S1Impl.ENSURE);
- ServiceRegistration sr3 = register(e, S2Impl.ENSURE);
- e.waitForStep(2, 10000);
- sr1.unregister();
- e.waitForStep(4, 10000);
- sr2.unregister();
- sr3.unregister();
- }
-}
diff --git a/dependencymanager/test/src/test/java/org/apache/felix/dm/test/integration/annotations/AspectAnnotationTest.java b/dependencymanager/test/src/test/java/org/apache/felix/dm/test/integration/annotations/AspectAnnotationTest.java
deleted file mode 100644
index 6e7bdfe..0000000
--- a/dependencymanager/test/src/test/java/org/apache/felix/dm/test/integration/annotations/AspectAnnotationTest.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.felix.dm.test.integration.annotations;
-
-import org.apache.felix.dm.test.components.Ensure;
-import org.apache.felix.dm.test.components.AspectAnnotation.ServiceAspect1;
-import org.apache.felix.dm.test.components.AspectAnnotation.ServiceAspect2;
-import org.apache.felix.dm.test.components.AspectAnnotation.ServiceAspect3;
-import org.apache.felix.dm.test.components.AspectAnnotation.ServiceConsumer;
-import org.apache.felix.dm.test.components.AspectAnnotation.ServiceProvider;
-import org.apache.felix.dm.test.integration.common.TestBase;
-import org.junit.Test;
-import org.junit.runner.RunWith;
-import org.ops4j.pax.exam.junit.PaxExam;
-import org.osgi.framework.ServiceRegistration;
-
-/**
- * Use case: Verify Aspect Annotations usage.
- */
-@RunWith(PaxExam.class)
-public class AspectAnnotationTest extends TestBase {
- public AspectAnnotationTest() {
- super(true /* start test components bundle */);
- }
-
- @Test
- public void testAspectChain() throws Throwable {
- Ensure e = new Ensure();
- // Activate service consumer
- ServiceRegistration scSequencer = register(e, ServiceConsumer.ENSURE);
- // Activate service provider
- ServiceRegistration spSequencer = register(e, ServiceProvider.ENSURE);
- // Activate service aspect 2
- ServiceRegistration sa2Sequencer = register(e, ServiceAspect2.ENSURE);
- // Activate service aspect 3
- ServiceRegistration sa3Sequencer = register(e, ServiceAspect3.ENSURE);
- // Activate service aspect 1
- ServiceRegistration sa1Sequencer = register(e, ServiceAspect1.ENSURE);
-
- e.step();
- e.waitForStep(6, 10000);
-
- // Deactivate service provider
- spSequencer.unregister();
- // Make sure that service aspect 1 has been called in ts removed and stop callbacks
- e.waitForStep(8, 10000);
- e.ensure();
-
- scSequencer.unregister();
- sa1Sequencer.unregister();
- sa2Sequencer.unregister();
- sa3Sequencer.unregister();
- }
-}
diff --git a/dependencymanager/test/src/test/java/org/apache/felix/dm/test/integration/annotations/AspectLifecycleAnnotationTest.java b/dependencymanager/test/src/test/java/org/apache/felix/dm/test/integration/annotations/AspectLifecycleAnnotationTest.java
deleted file mode 100644
index 5d0e48e..0000000
--- a/dependencymanager/test/src/test/java/org/apache/felix/dm/test/integration/annotations/AspectLifecycleAnnotationTest.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.felix.dm.test.integration.annotations;
-
-import org.apache.felix.dm.test.components.Ensure;
-import org.apache.felix.dm.test.components.AspectLifecycleAnnotation.ServiceProvider;
-import org.apache.felix.dm.test.components.AspectLifecycleAnnotation.ServiceProviderAspect;
-import org.apache.felix.dm.test.integration.common.TestBase;
-import org.junit.Test;
-import org.junit.runner.RunWith;
-import org.ops4j.pax.exam.junit.PaxExam;
-import org.osgi.framework.ServiceRegistration;
-
-/**
- * Use case: Tests an aspect service, and ensure that its lifecycle methods are properly invoked
- * (init/start/stop/destroy methods).
- */
-@RunWith(PaxExam.class)
-public class AspectLifecycleAnnotationTest extends TestBase {
- public AspectLifecycleAnnotationTest() {
- super(true /* start test components bundle */);
- }
-
- @Test
- public void testAnnotatedAspect() {
- Ensure e = new Ensure();
- // Provide the Sequencer server to the ServiceProvider service
- ServiceRegistration sr1 = register(e, ServiceProvider.ENSURE);
- // Check if the ServiceProvider has been injected in the AspectTest service.
- e.waitForStep(1, 10000);
- // Provide the Sequencer server to the ServiceProviderAspect service
- ServiceRegistration sr2 = register(e, ServiceProviderAspect.ENSURE);
- // Check if the AspectTest has been injected with the aspect
- e.waitForStep(3, 10000);
- // Stop the ServiceProviderAspect service.
- sr2.unregister();
- // And check if the aspect has been called in its stop/destroy methods.
- e.waitForStep(7, 10000);
- sr1.unregister();
- }
-}
diff --git a/dependencymanager/test/src/test/java/org/apache/felix/dm/test/integration/annotations/AspectLifecycleWithDynamicProxyAnnotationTest.java b/dependencymanager/test/src/test/java/org/apache/felix/dm/test/integration/annotations/AspectLifecycleWithDynamicProxyAnnotationTest.java
deleted file mode 100644
index 0f25892..0000000
--- a/dependencymanager/test/src/test/java/org/apache/felix/dm/test/integration/annotations/AspectLifecycleWithDynamicProxyAnnotationTest.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.felix.dm.test.integration.annotations;
-
-import org.apache.felix.dm.test.components.Ensure;
-import org.apache.felix.dm.test.components.AspectLifecycleWithDynamicProxyAnnotation.ServiceProvider;
-import org.apache.felix.dm.test.components.AspectLifecycleWithDynamicProxyAnnotation.ServiceProviderAspect;
-import org.apache.felix.dm.test.integration.common.TestBase;
-import org.junit.Test;
-import org.junit.runner.RunWith;
-import org.ops4j.pax.exam.junit.PaxExam;
-import org.osgi.framework.ServiceRegistration;
-
-/**
- * Use case: Tests an aspect service implemented as a dynamic proxy, and ensure that its lifecycle methods are properly invoked
- * (init/start/stop/destroy methods).
- */
-@RunWith(PaxExam.class)
-public class AspectLifecycleWithDynamicProxyAnnotationTest extends TestBase {
- public AspectLifecycleWithDynamicProxyAnnotationTest() {
- super(true /* start test components bundle */);
- }
-
- @Test
- public void testAnnotatedAspect() {
- Ensure e = new Ensure();
- // Provide the Sequencer server to the ServiceProvider service
- ServiceRegistration sr1 = register(e, ServiceProvider.ENSURE);
- // Check if the ServiceProvider has been injected in the AspectTest service.
- e.waitForStep(1, 10000);
- // Provide the Sequencer server to the ServiceProviderAspect service
- ServiceRegistration sr2 = register(e, ServiceProviderAspect.ENSURE);
- // Check if the AspectTest has been injected with the aspect
- e.waitForStep(3, 10000);
- // Remove the ServiceProviderAspect service
- sr2.unregister();
- // And check if the aspect has been called in its stop/destroy methods.
- e.waitForStep(7, 10000);
- sr1.unregister();
- }
-}
diff --git a/dependencymanager/test/src/test/java/org/apache/felix/dm/test/integration/annotations/BundleDependencyAnnotationTest.java b/dependencymanager/test/src/test/java/org/apache/felix/dm/test/integration/annotations/BundleDependencyAnnotationTest.java
deleted file mode 100644
index 004a48d..0000000
--- a/dependencymanager/test/src/test/java/org/apache/felix/dm/test/integration/annotations/BundleDependencyAnnotationTest.java
+++ /dev/null
@@ -1,63 +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.felix.dm.test.integration.annotations;
-
-import org.apache.felix.dm.test.components.BundleDependencyAnnotation;
-import org.apache.felix.dm.test.components.Ensure;
-import org.apache.felix.dm.test.integration.common.TestBase;
-import org.junit.Test;
-import org.junit.runner.RunWith;
-import org.ops4j.pax.exam.junit.PaxExam;
-import org.osgi.framework.ServiceRegistration;
-
-/**
- * Use case: Verify Bundle Dependency annotations usage.
- */
-@RunWith(PaxExam.class)
-public class BundleDependencyAnnotationTest extends TestBase {
- public BundleDependencyAnnotationTest() {
- super(true /* start test components bundle */);
- }
-
- /**
- * Tests a simple Consumer, which has a BundleDependency over the dependency manager bundle.
- */
- @Test
- public void testBundleDependencyAnnotation() {
- Ensure e = new Ensure();
- ServiceRegistration sr = register(e, BundleDependencyAnnotation.ENSURE_CONSUMER);
- e.waitForStep(1, 10000);
- stopTestBundle();
- e.waitForStep(2, 10000);
- sr.unregister();
- }
-
- /**
- * Tests a Bundle Adapter, which adapts the dependency manager bundle to a "ServiceInterface" service.
- * @throws Throwable
- */
- @Test
- public void testBundleAdapterServiceAnnotation() throws Throwable {
- Ensure e = new Ensure();
- ServiceRegistration sr = register(e, BundleDependencyAnnotation.ENSURE_ADAPTER);
- e.waitForStep(3, 10000);
- e.ensure();
- sr.unregister();
- }
-}
diff --git a/dependencymanager/test/src/test/java/org/apache/felix/dm/test/integration/annotations/CompositeAnnotationsTest.java b/dependencymanager/test/src/test/java/org/apache/felix/dm/test/integration/annotations/CompositeAnnotationsTest.java
deleted file mode 100644
index c809bcb..0000000
--- a/dependencymanager/test/src/test/java/org/apache/felix/dm/test/integration/annotations/CompositeAnnotationsTest.java
+++ /dev/null
@@ -1,53 +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.felix.dm.test.integration.annotations;
-
-import org.apache.felix.dm.test.components.Ensure;
-import org.apache.felix.dm.test.components.CompositeAnnotations.C1;
-import org.apache.felix.dm.test.components.CompositeAnnotations.Dependency1;
-import org.apache.felix.dm.test.components.CompositeAnnotations.Dependency2;
-import org.apache.felix.dm.test.integration.common.TestBase;
-import org.junit.Test;
-import org.junit.runner.RunWith;
-import org.ops4j.pax.exam.junit.PaxExam;
-import org.osgi.framework.ServiceRegistration;
-
-/**
- * Use case: Verify Composite annotated services.
- */
-@RunWith(PaxExam.class)
-public class CompositeAnnotationsTest extends TestBase {
- public CompositeAnnotationsTest() {
- super(true /* start test components bundle */);
- }
-
- @Test
- public void testComposite() {
- Ensure e = new Ensure();
- ServiceRegistration sr1 = register(e, C1.ENSURE);
- ServiceRegistration sr2 = register(e, Dependency1.ENSURE);
- ServiceRegistration sr3 = register(e, Dependency2.ENSURE);
- e.waitForStep(4, 10000);
- stopTestBundle();
- e.waitForStep(12, 10000);
- sr3.unregister();
- sr2.unregister();
- sr1.unregister();
- }
-}
diff --git a/dependencymanager/test/src/test/java/org/apache/felix/dm/test/integration/annotations/ExtraServicePropertiesTest.java b/dependencymanager/test/src/test/java/org/apache/felix/dm/test/integration/annotations/ExtraServicePropertiesTest.java
deleted file mode 100644
index 0f32299..0000000
--- a/dependencymanager/test/src/test/java/org/apache/felix/dm/test/integration/annotations/ExtraServicePropertiesTest.java
+++ /dev/null
@@ -1,84 +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.felix.dm.test.integration.annotations;
-
-import org.apache.felix.dm.test.components.Ensure;
-import org.apache.felix.dm.test.components.ExtraAdapterServiceProperties;
-import org.apache.felix.dm.test.components.ExtraAspectServiceProperties;
-import org.apache.felix.dm.test.components.ExtraFactoryServiceProperties;
-import org.apache.felix.dm.test.components.ExtraServiceProperties;
-import org.apache.felix.dm.test.integration.common.TestBase;
-import org.junit.Test;
-import org.junit.runner.RunWith;
-import org.ops4j.pax.exam.junit.PaxExam;
-import org.osgi.framework.ServiceRegistration;
-
-/**
- * Use case: Verify the a Service may provide its service properties dynamically from its start method.
- */
-@RunWith(PaxExam.class)
-public class ExtraServicePropertiesTest extends TestBase {
- public ExtraServicePropertiesTest() {
- super(true /* start test components bundle */);
- }
-
- /**
- * Tests if a Service can provide its service properties from its start method.
- */
- @Test
- public void testExtraServiceProperties() {
- Ensure e = new Ensure();
- ServiceRegistration sr = register(e, ExtraServiceProperties.ENSURE);
- e.waitForStep(2, 10000);
- sr.unregister();
- }
-
- /**
- * Tests if a Service instantiated by a Factory can provide its service properties from its start method.
- */
- @Test
- public void testExtraFactoryServiceProperties() {
- Ensure e = new Ensure();
- ServiceRegistration sr = register(e, ExtraFactoryServiceProperties.ENSURE);
- e.waitForStep(3, 10000);
- sr.unregister();
- }
-
- /**
- * Tests if an AdapterService can provide its service properties from its start method.
- */
- @Test
- public void testExtraAdapterServiceProperties() {
- Ensure e = new Ensure();
- ServiceRegistration sr = register(e, ExtraAdapterServiceProperties.ENSURE);
- e.waitForStep(3, 10000);
- sr.unregister();
- }
-
- /**
- * Tests if an AspectService can provide its service properties from its start method.
- */
- @Test
- public void testExtraAspectServiceProperties() {
- Ensure e = new Ensure();
- ServiceRegistration sr = register(e, ExtraAspectServiceProperties.ENSURE);
- e.waitForStep(3, 10000);
- sr.unregister();
- }
-}
diff --git a/dependencymanager/test/src/test/java/org/apache/felix/dm/test/integration/annotations/FactoryConfigurationAdapterAnnotationTest.java b/dependencymanager/test/src/test/java/org/apache/felix/dm/test/integration/annotations/FactoryConfigurationAdapterAnnotationTest.java
deleted file mode 100644
index a6a2527..0000000
--- a/dependencymanager/test/src/test/java/org/apache/felix/dm/test/integration/annotations/FactoryConfigurationAdapterAnnotationTest.java
+++ /dev/null
@@ -1,80 +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.felix.dm.test.integration.annotations;
-
-import java.io.IOException;
-import java.util.Hashtable;
-
-import junit.framework.Assert;
-
-import org.apache.felix.dm.test.components.Ensure;
-import org.apache.felix.dm.test.components.FactoryConfigurationAdapterAnnotation.ServiceProvider;
-import org.apache.felix.dm.test.integration.common.TestBase;
-import org.junit.Test;
-import org.junit.runner.RunWith;
-import org.ops4j.pax.exam.junit.PaxExam;
-import org.osgi.framework.ServiceRegistration;
-import org.osgi.service.cm.ConfigurationAdmin;
-
-/**
- * Use case: Verify that an annotated Configuration Factory Adapter Service is properly created when a factory configuration
- * is created from Config Admin.
- */
-@RunWith(PaxExam.class)
-public class FactoryConfigurationAdapterAnnotationTest extends TestBase {
- public FactoryConfigurationAdapterAnnotationTest() {
- super(true /* start test components bundle */);
- }
-
- @Test
- public void testFactoryConfigurationAdapterAnnotation() throws Throwable {
- Ensure e = new Ensure();
- ServiceRegistration sr = register(e, ServiceProvider.ENSURE);
- ConfigurationAdmin cm = (ConfigurationAdmin) context.getService(context
- .getServiceReference(ConfigurationAdmin.class.getName()));
- try {
- // Create a factory configuration in order to instantiate the ServiceProvider
- org.osgi.service.cm.Configuration cf = cm.createFactoryConfiguration("FactoryPidTest", null);
- cf.update(new Hashtable() {
- {
- put("foo2", "bar2");
- }
- });
- // Wait for the ServiceProvider activation.
- e.waitForStep(2, 10000);
- // Update conf
- cf.update(new Hashtable() {
- {
- put("foo2", "bar2_modified");
- }
- });
- // Wait for effective update
- e.waitForStep(4, 10000);
- // Remove configuration.
- cf.delete();
- // Check if ServiceProvider has been stopped.
- e.waitForStep(6, 1000);
- e.ensure();
- sr.unregister();
- } catch (IOException err) {
- err.printStackTrace();
- Assert.fail("can't create factory configuration");
- }
- }
-}
diff --git a/dependencymanager/test/src/test/java/org/apache/felix/dm/test/integration/annotations/Felix4050Test.java b/dependencymanager/test/src/test/java/org/apache/felix/dm/test/integration/annotations/Felix4050Test.java
deleted file mode 100644
index d050d0c..0000000
--- a/dependencymanager/test/src/test/java/org/apache/felix/dm/test/integration/annotations/Felix4050Test.java
+++ /dev/null
@@ -1,51 +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.felix.dm.test.integration.annotations;
-
-import org.apache.felix.dm.test.components.Ensure;
-import org.apache.felix.dm.test.components.Felix4050;
-import org.apache.felix.dm.test.integration.common.TestBase;
-import org.junit.Test;
-import org.junit.runner.RunWith;
-import org.ops4j.pax.exam.junit.PaxExam;
-import org.osgi.framework.ServiceRegistration;
-
-/**
- * Test for FELIX-4050 issue: It validates that component state calculation does not mess up
- * when an @Init method adds an available dependency using the API, and also returns a Map for
- * configuring a named dependency.
- */
-@RunWith(PaxExam.class)
-public class Felix4050Test extends TestBase {
- public Felix4050Test() {
- super(true /* start test components bundle */);
- }
-
- @Test
- public void testFelix4050() {
- Ensure e = new Ensure();
- ServiceRegistration sr = register(e, Felix4050.ENSURE);
- // wait for S to be started
- e.waitForStep(3, 10000);
- // remove our sequencer: this will stop S
- sr.unregister();
- // ensure that S is stopped and destroyed
- e.waitForStep(5, 10000);
- }
-}
diff --git a/dependencymanager/test/src/test/java/org/apache/felix/dm/test/integration/annotations/Felix4357Test.java b/dependencymanager/test/src/test/java/org/apache/felix/dm/test/integration/annotations/Felix4357Test.java
deleted file mode 100644
index 01630f5..0000000
--- a/dependencymanager/test/src/test/java/org/apache/felix/dm/test/integration/annotations/Felix4357Test.java
+++ /dev/null
@@ -1,48 +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.felix.dm.test.integration.annotations;
-
-import org.apache.felix.dm.test.components.Ensure;
-import org.apache.felix.dm.test.components.Felix4357;
-import org.apache.felix.dm.test.integration.common.TestBase;
-import org.junit.Test;
-import org.junit.runner.RunWith;
-import org.ops4j.pax.exam.junit.PaxExam;
-import org.osgi.framework.ServiceRegistration;
-
-/**
- * Test for FELIX-4357 issue: It validates the types of some service component properties
- * defined with @Property annotation.
- */
-@RunWith(PaxExam.class)
-public class Felix4357Test extends TestBase {
- public Felix4357Test() {
- super(true /* start test components bundle */);
- }
-
- @Test
- public void testPropertiesWithTypes() {
- Ensure e = new Ensure();
- ServiceRegistration sr = register(e, Felix4357.ENSURE);
- // wait for S to be started
- e.waitForStep(30, 10000);
- // remove our sequencer: this will stop S
- sr.unregister();
- }
-}
diff --git a/dependencymanager/test/src/test/java/org/apache/felix/dm/test/integration/annotations/MultipleAnnotationsTest.java b/dependencymanager/test/src/test/java/org/apache/felix/dm/test/integration/annotations/MultipleAnnotationsTest.java
deleted file mode 100644
index f19dc43..0000000
--- a/dependencymanager/test/src/test/java/org/apache/felix/dm/test/integration/annotations/MultipleAnnotationsTest.java
+++ /dev/null
@@ -1,48 +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.felix.dm.test.integration.annotations;
-
-import org.apache.felix.dm.test.components.Ensure;
-import org.apache.felix.dm.test.components.MultipleAnnotations;
-import org.apache.felix.dm.test.integration.common.TestBase;
-import org.junit.Test;
-import org.junit.runner.RunWith;
-import org.ops4j.pax.exam.junit.PaxExam;
-import org.osgi.framework.ServiceRegistration;
-
-/**
- * Use case: Verify complex Annotation usage.
- */
-@RunWith(PaxExam.class)
-public class MultipleAnnotationsTest extends TestBase {
- public MultipleAnnotationsTest() {
- super(true /* start test components bundle */);
- }
-
- @Test
- public void testMultipleAnnotations() {
- Ensure e = new Ensure();
- ServiceRegistration sr = register(e, MultipleAnnotations.ENSURE);
- e.waitForStep(7, 10000);
- stopTestBundle();
- // And check if the test.annotation bundle has been deactivated orderly
- e.waitForStep(11, 10000);
- sr.unregister();
- }
-}
diff --git a/dependencymanager/test/src/test/java/org/apache/felix/dm/test/integration/annotations/PropagateAnnotationTest.java b/dependencymanager/test/src/test/java/org/apache/felix/dm/test/integration/annotations/PropagateAnnotationTest.java
deleted file mode 100644
index 0f87810..0000000
--- a/dependencymanager/test/src/test/java/org/apache/felix/dm/test/integration/annotations/PropagateAnnotationTest.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.felix.dm.test.integration.annotations;
-
-import org.apache.felix.dm.test.components.Ensure;
-import org.apache.felix.dm.test.components.PropagateAnnotation;
-import org.apache.felix.dm.test.integration.common.TestBase;
-import org.junit.Test;
-import org.junit.runner.RunWith;
-import org.ops4j.pax.exam.junit.PaxExam;
-import org.osgi.framework.ServiceRegistration;
-
-/**
- * Use case: Verify that dependency "propagate" option is properly propagating properties to provided service.
- */
-@RunWith(PaxExam.class)
-public class PropagateAnnotationTest extends TestBase {
- public PropagateAnnotationTest() {
- super(true /* start test components bundle */);
- }
-
- @Test
- public void testServiceDependencyPropagate() {
- Ensure e = new Ensure();
- ServiceRegistration sr = register(e, PropagateAnnotation.ENSURE);
- e.waitForStep(3, 10000);
- sr.unregister();
- }
-}
diff --git a/dependencymanager/test/src/test/java/org/apache/felix/dm/test/integration/annotations/PublisherAnnotationTest.java b/dependencymanager/test/src/test/java/org/apache/felix/dm/test/integration/annotations/PublisherAnnotationTest.java
deleted file mode 100644
index 2c7ad60..0000000
--- a/dependencymanager/test/src/test/java/org/apache/felix/dm/test/integration/annotations/PublisherAnnotationTest.java
+++ /dev/null
@@ -1,106 +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.felix.dm.test.integration.annotations;
-
-import org.apache.felix.dm.test.components.AdapterServiceTestWithPublisher;
-import org.apache.felix.dm.test.components.BundleAdapterServiceTestWithPublisher;
-import org.apache.felix.dm.test.components.Ensure;
-import org.apache.felix.dm.test.components.FactoryConfigurationAdapterServiceTestWithPublisher;
-import org.apache.felix.dm.test.components.FactoryServiceTestWthPublisher;
-import org.apache.felix.dm.test.components.ResourceAdapterServiceTestWithPublisher;
-import org.apache.felix.dm.test.components.ServiceTestWthPublisher;
-import org.apache.felix.dm.test.integration.common.TestBase;
-import org.junit.Test;
-import org.junit.runner.RunWith;
-import org.ops4j.pax.exam.junit.PaxExam;
-import org.osgi.framework.ServiceRegistration;
-
-@RunWith(PaxExam.class)
-public class PublisherAnnotationTest extends TestBase {
- public PublisherAnnotationTest() {
- super(true /* start test components bundle */);
- }
-
- /**
- * A Service that just registers/unregisters its service, using the @ServiceLifecycle annotation.
- */
- @Test
- public void testServiceWithPublisher() {
- Ensure e = new Ensure();
- ServiceRegistration sr = register(e, ServiceTestWthPublisher.ENSURE);
- e.waitForStep(4, 10000);
- sr.unregister();
- }
-
- /**
- * A Service instantiated from a FactorySet, and which registers/unregisters its service,
- * using the @ServiceLifecycle annotation.
- */
- @Test
- public void testFactoryServiceWithPublisher() {
- Ensure e = new Ensure();
- ServiceRegistration sr = register(e, FactoryServiceTestWthPublisher.ENSURE);
- e.waitForStep(5, 10000);
- sr.unregister();
- }
-
- /**
- * Test an AdapterService which provides its interface using a @ServiceLifecycle.
- */
- @Test
- public void testAdapterServiceWithPublisher() {
- Ensure e = new Ensure();
- ServiceRegistration sr = register(e, AdapterServiceTestWithPublisher.ENSURE);
- e.waitForStep(6, 10000);
- sr.unregister();
- }
-
- /**
- * Test a BundleAdapterService which provides its interface using a @ServiceLifecycle.
- */
- @Test
- public void testBundleAdapterServiceWithPublisher() {
- Ensure e = new Ensure();
- ServiceRegistration sr = register(e, BundleAdapterServiceTestWithPublisher.ENSURE);
- e.waitForStep(5, 10000);
- sr.unregister();
- }
-
- /**
- * Test a ResourceAdapterService which provides its interface using a @ServiceLifecycle.
- */
- @Test
- public void TestResourceAdapterServiceWithPublisher() {
- Ensure e = new Ensure();
- ServiceRegistration sr = register(e, ResourceAdapterServiceTestWithPublisher.ENSURE);
- e.waitForStep(5, 10000);
- sr.unregister();
- }
-
- /**
- * Test a FactoryConfigurationAdapterService which provides its interface using a @ServiceLifecycle.
- */
- @Test
- public void testFactoryAdapterServiceWithPublisher() {
- Ensure e = new Ensure();
- ServiceRegistration sr = register(e, FactoryConfigurationAdapterServiceTestWithPublisher.ENSURE);
- e.waitForStep(5, 10000);
- sr.unregister();
- }
-}
diff --git a/dependencymanager/test/src/test/java/org/apache/felix/dm/test/integration/annotations/ResourceAnnotationTest.java b/dependencymanager/test/src/test/java/org/apache/felix/dm/test/integration/annotations/ResourceAnnotationTest.java
deleted file mode 100644
index f71623c..0000000
--- a/dependencymanager/test/src/test/java/org/apache/felix/dm/test/integration/annotations/ResourceAnnotationTest.java
+++ /dev/null
@@ -1,82 +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.felix.dm.test.integration.annotations;
-
-import org.apache.felix.dm.test.components.Ensure;
-import org.apache.felix.dm.test.components.ResourceAnnotation;
-import org.apache.felix.dm.test.integration.common.TestBase;
-import org.junit.Test;
-import org.junit.runner.RunWith;
-import org.ops4j.pax.exam.junit.PaxExam;
-import org.osgi.framework.ServiceRegistration;
-
-/**
- * Use case: Verify Bundle Dependency annotations usage.
- */
-@RunWith(PaxExam.class)
-public class ResourceAnnotationTest extends TestBase {
- public ResourceAnnotationTest() {
- super(true /* start test components bundle */);
- }
-
- /**
- * Tests a simple ResourceConsumer
- * @param context
- */
- @Test
- public void testResourceAnnotation() {
- Ensure e = new Ensure();
- ServiceRegistration sr = register(e, ResourceAnnotation.ENSURE_RESOURCE);
- ServiceRegistration sr2 = register(e, ResourceAnnotation.ENSURE_PROVIDER);
- stopTestBundle();
- e.waitForStep(1, 10000);
- sr.unregister();
- sr2.unregister();
- }
-
- /**
- * Tests a simple ResourceConsumer using a class field for resource injection
- */
- @Test
- public void testResourceAnnotationAutoConfig() {
- Ensure e = new Ensure();
- ServiceRegistration sr = register(e, ResourceAnnotation.ENSURE_FIELD);
- ServiceRegistration sr2 = register(e, ResourceAnnotation.ENSURE_PROVIDER);
- stopTestBundle();
- e.waitForStep(1, 10000);
- sr.unregister();
- sr2.unregister();
- }
-
- /**
- * Tests a ResourceAdapter
- * @param context
- */
- @Test
- public void testResourceAdapterAnnotation() throws Throwable {
- Ensure e = new Ensure();
- ServiceRegistration sr = register(e, ResourceAnnotation.ENSURE_ADAPTER);
- ServiceRegistration sr2 = register(e, ResourceAnnotation.ENSURE_PROVIDER);
- stopTestBundle();
- e.waitForStep(2, 10000);
- e.ensure();
- sr.unregister();
- sr2.unregister();
- }
-}
diff --git a/dependencymanager/test/src/test/java/org/apache/felix/dm/test/integration/annotations/ServiceFactoryAnnotationTest.java b/dependencymanager/test/src/test/java/org/apache/felix/dm/test/integration/annotations/ServiceFactoryAnnotationTest.java
deleted file mode 100644
index 9cc0a5a..0000000
--- a/dependencymanager/test/src/test/java/org/apache/felix/dm/test/integration/annotations/ServiceFactoryAnnotationTest.java
+++ /dev/null
@@ -1,78 +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.felix.dm.test.integration.annotations;
-
-import java.util.Hashtable;
-import java.util.Set;
-
-import junit.framework.Assert;
-
-import org.apache.felix.dm.DependencyManager;
-import org.apache.felix.dm.annotation.api.Component;
-import org.apache.felix.dm.test.components.Ensure;
-import org.apache.felix.dm.test.components.ServiceFactoryAnnotation;
-import org.apache.felix.dm.test.integration.common.TestBase;
-import org.junit.Test;
-import org.junit.runner.RunWith;
-import org.ops4j.pax.exam.junit.PaxExam;
-import org.osgi.framework.ServiceRegistration;
-
-@RunWith(PaxExam.class)
-public class ServiceFactoryAnnotationTest extends TestBase {
- public ServiceFactoryAnnotationTest() {
- super(true /* start test components bundle */);
- }
-
- private final Ensure m_ensure = new Ensure();
- @Test
- public void testServiceFactory() {
- ServiceRegistration sr = register(m_ensure, ServiceFactoryAnnotation.ENSURE);
-
- DependencyManager m = new DependencyManager(context);
- // Wait for the factory.
- m.add(m.createComponent()
- .setImplementation(this)
- .add(m.createServiceDependency()
- .setService(Set.class,
- "(" + Component.FACTORY_NAME + "=" + ServiceFactoryAnnotation.FACTORY + ")")
- .setRequired(true).setCallbacks("bindFactory", null)));
-
- // Check if the test.annotation components have been initialized orderly
- m_ensure.waitForStep(10, 5000);
- m.clear();
- sr.unregister();
- }
-
- void bindFactory(Set factory) {
- // create a service instance with this configuration
- Hashtable conf = new Hashtable();
- conf.put("instance.id", "instance");
- conf.put(".private.param", "private");
- Assert.assertTrue(factory.add(conf));
- m_ensure.waitForStep(4, 5000);
-
- // update the service instance
- conf.put("instance.modified", "true");
- Assert.assertFalse(factory.add(conf));
- m_ensure.waitForStep(7, 5000);
-
- // remove instance
- Assert.assertTrue(factory.remove(conf));
- }
-}
diff --git a/dependencymanager/test/src/test/java/org/apache/felix/dm/test/integration/annotations/SimpleAnnotationsTest.java b/dependencymanager/test/src/test/java/org/apache/felix/dm/test/integration/annotations/SimpleAnnotationsTest.java
deleted file mode 100644
index cf7051a..0000000
--- a/dependencymanager/test/src/test/java/org/apache/felix/dm/test/integration/annotations/SimpleAnnotationsTest.java
+++ /dev/null
@@ -1,54 +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.felix.dm.test.integration.annotations;
-
-import org.apache.felix.dm.test.components.Ensure;
-import org.apache.felix.dm.test.components.SimpleAnnotations.Consumer;
-import org.apache.felix.dm.test.components.SimpleAnnotations.Producer;
-import org.apache.felix.dm.test.integration.common.TestBase;
-import org.junit.Test;
-import org.junit.runner.RunWith;
-import org.ops4j.pax.exam.junit.PaxExam;
-import org.osgi.framework.ServiceRegistration;
-
-/**
- * Use case: Ensure that a Provider can be injected into a Consumer, using simple DM annotations.
- */
-@RunWith(PaxExam.class)
-public class SimpleAnnotationsTest extends TestBase {
- public SimpleAnnotationsTest() {
- super(true /* start test components bundle */);
- }
-
- @Test
- public void testSimpleAnnotations() throws Throwable {
- Ensure e = new Ensure();
- ServiceRegistration er = register(e, Producer.ENSURE);
- e.waitForStep(3, 10000); // Producer registered
- ServiceRegistration er2 = register(e, Consumer.ENSURE);
-
- er2.unregister(); // stop consumer
- er.unregister(); // stop provider
-
- // And check if components have been deactivated orderly.
- e.waitForStep(10, 10000);
- e.ensure();
- stopTestBundle();
- }
-}
diff --git a/dependencymanager/test/src/test/java/org/apache/felix/dm/test/integration/annotations/TemporalAnnotationsTest.java b/dependencymanager/test/src/test/java/org/apache/felix/dm/test/integration/annotations/TemporalAnnotationsTest.java
deleted file mode 100644
index c5b736c..0000000
--- a/dependencymanager/test/src/test/java/org/apache/felix/dm/test/integration/annotations/TemporalAnnotationsTest.java
+++ /dev/null
@@ -1,66 +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.felix.dm.test.integration.annotations;
-
-import java.util.Dictionary;
-import java.util.Hashtable;
-
-import org.apache.felix.dm.test.components.Ensure;
-import org.apache.felix.dm.test.components.TemporalAnnotations;
-import org.apache.felix.dm.test.integration.common.TestBase;
-import org.junit.Test;
-import org.junit.runner.RunWith;
-import org.ops4j.pax.exam.junit.PaxExam;
-import org.osgi.framework.ServiceRegistration;
-
-/**
- * Use case: Verify Temporal Service dependency Annotations usage.
- */
-@RunWith(PaxExam.class)
-public class TemporalAnnotationsTest extends TestBase {
- public TemporalAnnotationsTest() {
- super(true /* start test components bundle */);
- }
-
- @Test
- public void testTemporalServiceDependency() {
- Ensure ensure = new Ensure();
- ServiceRegistration ensureReg = register(ensure, TemporalAnnotations.ENSURE);
- Dictionary props = new Hashtable() {
- {
- put("test", "temporal");
- }
- };
- Runnable r = Ensure.createRunnableStep(ensure, 1);
- ServiceRegistration sr = context.registerService(Runnable.class.getName(), r, props);
- ensure.waitForStep(1, 15000);
- System.out.println("unregistering R");
- sr.unregister();
- ensure.step(2);
- sleep(500);
- r = Ensure.createRunnableStep(ensure, 3);
- sr = context.registerService(Runnable.class.getName(), r, props);
- ensure.waitForStep(3, 15000);
- sr.unregister();
- ensure.step(4);
- sleep(1500);
- ensure.waitForStep(5, 15000);
- ensureReg.unregister();
- }
-}
diff --git a/dependencymanager/test/src/test/java/org/apache/felix/dm/test/integration/api/AbstractServiceDependencyTest.java b/dependencymanager/test/src/test/java/org/apache/felix/dm/test/integration/api/AbstractServiceDependencyTest.java
deleted file mode 100644
index 46f4cb9..0000000
--- a/dependencymanager/test/src/test/java/org/apache/felix/dm/test/integration/api/AbstractServiceDependencyTest.java
+++ /dev/null
@@ -1,109 +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.felix.dm.test.integration.api;
-
-import junit.framework.Assert;
-
-import org.apache.felix.dm.Component;
-import org.apache.felix.dm.DependencyManager;
-import org.apache.felix.dm.test.components.Ensure;
-import org.apache.felix.dm.test.integration.common.TestBase;
-import org.junit.Test;
-import org.junit.runner.RunWith;
-import org.ops4j.pax.exam.junit.PaxExam;
-
-@RunWith(PaxExam.class)
-public class AbstractServiceDependencyTest extends TestBase {
-
- @Test
- public void testAbstractClassDependency() {
- DependencyManager m = new DependencyManager(context);
- // helper class that ensures certain steps get executed in sequence
- Ensure e = new Ensure();
- // create a service provider and consumer
- Component sp = m.createComponent()
- .setInterface(ServiceAbstract.class.getName(), null)
- .setImplementation(new ServiceProvider(e))
- ;
- Component sc = m.createComponent()
- .setImplementation(new ServiceConsumer(e))
- .add(m.createServiceDependency()
- .setService(ServiceAbstract.class)
- .setRequired(true)
- .setCallbacks("bind", "unbind")
- );
- m.add(sp);
- m.add(sc);
- m.remove(sp);
- // ensure we executed all steps inside the component instance
- e.step(8);
- }
-
- static abstract class ServiceAbstract {
- public abstract void invoke();
- }
-
- static class ServiceProvider extends ServiceAbstract {
- private final Ensure m_ensure;
- public ServiceProvider(Ensure e) {
- m_ensure = e;
- }
-
- public void start() {
- m_ensure.step(1);
- }
-
- public void invoke() {
- m_ensure.step(4);
- }
-
- public void stop() {
- m_ensure.step(7);
- }
- }
-
- static class ServiceConsumer {
- private volatile ServiceAbstract m_service;
- private final Ensure m_ensure;
-
- public ServiceConsumer(Ensure e) {
- m_ensure = e;
- }
-
- public void bind(ServiceAbstract service) {
- m_ensure.step(2);
- m_service = service;
- }
-
- public void start() {
- m_ensure.step(3);
- m_service.invoke();
- }
-
- public void stop() {
- m_ensure.step(5);
- }
-
- public void unbind(ServiceAbstract service) {
- System.out.println("UNBINDDDDDDDDDDDDDDDDDDDDDDDDDDD");
- Assert.assertEquals(m_service, service);
- m_ensure.step(6);
- }
- }
-}
\ No newline at end of file
diff --git a/dependencymanager/test/src/test/java/org/apache/felix/dm/test/integration/api/AdapterAndConsumerTest.java b/dependencymanager/test/src/test/java/org/apache/felix/dm/test/integration/api/AdapterAndConsumerTest.java
deleted file mode 100644
index 6eab1db..0000000
--- a/dependencymanager/test/src/test/java/org/apache/felix/dm/test/integration/api/AdapterAndConsumerTest.java
+++ /dev/null
@@ -1,115 +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.felix.dm.test.integration.api;
-
-import org.apache.felix.dm.Component;
-import org.apache.felix.dm.DependencyManager;
-import org.apache.felix.dm.test.components.Ensure;
-import org.apache.felix.dm.test.integration.common.TestBase;
-import org.junit.Test;
-import org.junit.runner.RunWith;
-import org.ops4j.pax.exam.junit.PaxExam;
-
-@RunWith(PaxExam.class)
-public class AdapterAndConsumerTest extends TestBase {
-
- @Test
- public void testServiceWithAdapterAndConsumer() {
- DependencyManager m = new DependencyManager(context);
- // helper class that ensures certain steps get executed in sequence
- Ensure e = new Ensure();
-
- Component provider = m.createComponent()
- .setInterface(OriginalService.class.getName(), null)
- .setImplementation(new ServiceProvider(e));
-
- Component consumer = m.createComponent()
- .setImplementation(new ServiceConsumer(e))
- .add(m.createServiceDependency()
- .setService(AdaptedService.class)
- .setRequired(true)
- );
-
- Component adapter = m.createAdapterService(OriginalService.class, null)
- .setInterface(AdaptedService.class.getName(), null)
- .setImplementation(ServiceAdapter.class);
-
- // add the provider and the adapter
- m.add(provider);
- m.add(adapter);
- // add a consumer that will invoke the adapter
- // which will in turn invoke the original provider
- m.add(consumer);
- // now validate that both have been invoked in the right order
- e.waitForStep(2, 5000);
- // remove the provider again
- m.remove(provider);
- // ensure that the consumer is stopped
- e.waitForStep(3, 5000);
- // remove adapter and consumer
- m.remove(adapter);
- m.remove(consumer);
- }
-
- static interface OriginalService {
- public void invoke();
- }
-
- static interface AdaptedService {
- public void invoke();
- }
-
- static class ServiceProvider implements OriginalService {
- private final Ensure m_ensure;
- public ServiceProvider(Ensure e) {
- m_ensure = e;
- }
- public void invoke() {
- m_ensure.step(2);
- }
- }
-
- public static class ServiceAdapter implements AdaptedService {
- private volatile OriginalService m_originalService;
-
- public void start() { System.out.println("start"); }
- public void stop() { System.out.println("stop"); }
- public void invoke() {
- m_originalService.invoke();
- }
- }
-
- static class ServiceConsumer {
- private volatile AdaptedService m_service;
- private final Ensure m_ensure;
-
- public ServiceConsumer(Ensure e) {
- m_ensure = e;
- }
- public void start() {
- m_ensure.step(1);
- m_service.invoke();
- }
- public void stop() {
- m_ensure.step(3);
- }
- }
-}
-
-
diff --git a/dependencymanager/test/src/test/java/org/apache/felix/dm/test/integration/api/AdapterWithAspectCallbacksTest.java b/dependencymanager/test/src/test/java/org/apache/felix/dm/test/integration/api/AdapterWithAspectCallbacksTest.java
deleted file mode 100644
index 11106b5..0000000
--- a/dependencymanager/test/src/test/java/org/apache/felix/dm/test/integration/api/AdapterWithAspectCallbacksTest.java
+++ /dev/null
@@ -1,249 +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.felix.dm.test.integration.api;
-
-import java.util.ArrayList;
-import java.util.Dictionary;
-import java.util.Hashtable;
-import java.util.List;
-
-import org.apache.felix.dm.Component;
-import org.apache.felix.dm.DependencyManager;
-import org.apache.felix.dm.test.components.Ensure;
-import org.apache.felix.dm.test.integration.common.TestBase;
-import org.junit.Assert;
-import org.junit.Test;
-import org.junit.runner.RunWith;
-import org.ops4j.pax.exam.junit.PaxExam;
-import org.osgi.framework.ServiceReference;
-
-@RunWith(PaxExam.class)
-public class AdapterWithAspectCallbacksTest extends TestBase {
- @Test
- public void testAdapterWithAspectMultipleTimes() {
- DependencyManager m = new DependencyManager(context);
- // helper class that ensures certain steps get executed in sequence
- Ensure e = new Ensure();
-
- Component aspect1 = m.createAspectService(OriginalService.class, null, 10, null)
- .setImplementation(ServiceAspect.class);
-
- Component aspect2 = m.createAspectService(OriginalService.class, null, 15, null)
- .setImplementation(ServiceAspect.class);
-
- Component adapter = m.createAdapterService(OriginalService.class, null, "add", null, "remove", "swap")
- .setInterface(AdaptedService.class.getName(), null)
- .setImplementation(ServiceAdapter.class);
-
- m.add(adapter);
- m.add(aspect1);
-
- List originals = new ArrayList();
- List consumers = new ArrayList();
- int count = 100;
- for (int i = 0; i < count; i++) {
- // create a service provider and consumer
- Dictionary props = new Hashtable();
- props.put("number", "" + i);
- Component original = m.createComponent()
- .setImplementation(new ServiceProvider("" + i, e))
- .setInterface(OriginalService.class.getName(), props);
-
- Component consumer = m.createComponent()
- .setImplementation(new ServiceConsumer(e, "" + i))
- .add(m.createServiceDependency()
- .setService(AdaptedService.class, "(number=" + i + ")")
- .setCallbacks("add", null, "remove", "swap")
- .setRequired(true)
- );
-
- m.add(original);
- e.waitForStep(1 + i, 15000);
- originals.add(original);
-// m.add(consumer);
- consumers.add(consumer);
- }
-
- m.add(aspect2);
- e.waitForStep(2 + count, 15000);
- // dumpComponents(m)
-
- for (int i = 0; i < 1; i++) {
- for (Object original : originals) {
- m.remove((Component)original);
- }
- for (Object consumer : consumers) {
- m.remove((Component)consumer);
- }
- }
- m.remove(aspect1);
- m.remove(adapter);
-
- e.waitForStep(count * 3, 15000);
- m.remove(aspect2);
- e.step(count * 3 + 1);
- m.clear();
- }
-
- static interface OriginalService {
- public void invoke();
-
- public String getMessage();
-
- public Ensure getEnsure();
- }
-
- static interface AdaptedService {
- public void invoke();
-
- public String getMessage();
- }
-
- static class ServiceProvider implements OriginalService {
- private final String message;
- private final Ensure m_ensure;
-
- public ServiceProvider(String message, Ensure e) {
- this.message = message;
- this.m_ensure = e;
- }
- public void start() {
- System.out.println("...original starting");
- }
- public void invoke() {
- }
-
- @Override
- public String toString() {
- return "Original " + message;
- }
- public String getMessage() {
- return message;
- }
- public Ensure getEnsure() {
- return m_ensure;
- }
- }
-
- public static class ServiceAdapter implements AdaptedService {
- private volatile OriginalService m_originalService;
- private int m_nr;
-
- public ServiceAdapter() {
-
- }
-
- public void init() {
- }
- public void start() {
- System.out.println("...adapter starting");
- }
- public void invoke() {
- m_originalService.invoke();
- }
- public void stop() {
- System.out.println("...adapter stopping");
- }
-
- void add(ServiceReference ref, OriginalService originalService) {
- m_originalService = originalService;
- System.out.println("adapter add: " + originalService + " (" + System.identityHashCode(this) + ")");
- m_originalService.getEnsure().step();
- }
-
- void remove(ServiceReference ref, OriginalService originalService) {
- System.out.println("adapter rem: " + originalService + " (" + System.identityHashCode(this) + ")");
- m_originalService = null;
- }
-
- void swap(ServiceReference oldRef, OriginalService oldService, ServiceReference newRef, OriginalService newService) {
- m_originalService = newService;
- System.out.println("adapter swp: " + newService + " (" + System.identityHashCode(this) + ")");
- m_originalService.getEnsure().step();
- System.out.println("ensure: " + m_originalService.getEnsure());
- }
-
- @Override
- public String toString() {
- return "Adapter on " + m_originalService;
- }
- public String getMessage() {
- return m_originalService.getMessage();
- }
-
- }
-
-
- public static class ServiceAspect implements OriginalService {
- volatile OriginalService m_service;
-
- public void start() {
- System.out.println("...aspect starting: " + toString());
- }
-
- public void invoke() {
- m_service.invoke();
- }
-
- @Override
- public String toString() {
- return "Aspect on " + m_service;
- }
-
- public String getMessage() {
- return m_service.getMessage();
- }
-
- public Ensure getEnsure() {
- return m_service.getEnsure();
- }
- }
-
- public static class ServiceConsumer {
- Ensure m_ensure;
- volatile AdaptedService service;
- private final String expectedMessage;
-
- public ServiceConsumer(Ensure e, String expectedMessage) {
- m_ensure = e;
- this.expectedMessage = expectedMessage;
- }
-
- public void start() {
- String message = service.getMessage();
- Assert.assertEquals(expectedMessage, message);
- }
-
- public void stop() {
- }
-
- public void add(ServiceReference ref, AdaptedService service) {
- this.service = service;
- }
- public void remove(ServiceReference ref, AdaptedService service) {
- this.service = null;
- }
- public void swap(ServiceReference oldRef, AdaptedService oldService, ServiceReference newRef, AdaptedService newService) {
- this.service = newService;
- }
-
- }
-}
-
-
diff --git a/dependencymanager/test/src/test/java/org/apache/felix/dm/test/integration/api/AdapterWithAspectTest.java b/dependencymanager/test/src/test/java/org/apache/felix/dm/test/integration/api/AdapterWithAspectTest.java
deleted file mode 100644
index 9af51db..0000000
--- a/dependencymanager/test/src/test/java/org/apache/felix/dm/test/integration/api/AdapterWithAspectTest.java
+++ /dev/null
@@ -1,231 +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.felix.dm.test.integration.api;
-
-import org.apache.felix.dm.Component;
-import org.apache.felix.dm.DependencyManager;
-import org.apache.felix.dm.test.components.Ensure;
-import org.apache.felix.dm.test.integration.common.TestBase;
-import org.junit.Test;
-import org.junit.runner.RunWith;
-import org.ops4j.pax.exam.junit.PaxExam;
-import org.osgi.framework.ServiceReference;
-
-@RunWith(PaxExam.class)
-public class AdapterWithAspectTest extends TestBase {
-
- @Test
- public void testAdapterWithAspectMultipleTimes() {
- // TODO this test is broken, it assumes that the order in which listeners are added to the BundleContext will also
- // be the order in which they're invoked (which from a spec point of view is not true)
-
-
- DependencyManager m = new DependencyManager(context);
- // helper class that ensures certain steps get executed in sequence
- Ensure e = new Ensure();
-
- // create a service provider and consumer
- Component provider = m.createComponent()
- .setImplementation(new ServiceProvider())
- .setInterface(OriginalService.class.getName(), null);
-
- Component consumer = m.createComponent()
- .setImplementation(new ServiceConsumer(e))
- .add(m.createServiceDependency()
- .setService(AdaptedService.class)
- .setCallbacks("add", null, "remove", "swap")
- );
- Component adapter = m.createAdapterService(OriginalService.class, null, "add", null, "remove", "swap")
- .setInterface(AdaptedService.class.getName(), null)
- .setImplementation(new ServiceAdapter(e,1));
-
- Component adapter2 = m.createAdapterService(OriginalService.class, null, "add", null, "remove", "swap")
- .setInterface(AdaptedService.class.getName(), null)
- .setImplementation(new ServiceAdapter(e,2));
-
- Component aspect = m.createAspectService(OriginalService.class, null, 10, null)
- .setImplementation(ServiceAspect.class);
-
- m.add(provider);
-
- int stepsInLoop = 10;
- int loops = 10;
- for (int loop = 0; loop < loops; loop++) {
- int offset = stepsInLoop * loop;
-
- System.out.println("add adapter");
- m.add(adapter);
- System.out.println("add consumer");
- m.add(consumer);
- e.waitForStep(1 + offset, 5000);
- System.out.println("add aspect");
- m.add(aspect);
- // a swap is expected on the adapter
- e.waitForStep(2 + offset, 5000);
- System.out.println("add adapter2");
- m.add(adapter2);
- // another aspect adapter will appear
- e.waitForStep(4 + offset, 5000);
- System.out.println("remove provider");
- m.remove(provider);
- // two times:
- // the aspect adapter will disappear
- // the original adapter will (briefly) appear
- // the original adapter will disappear
-
- // TODO the test will fail somewhere here most of the time
-
- e.waitForStep(8 + offset, 5000);
- System.out.println("remove consumer");
- m.remove(consumer);
-
- // nothing should happen, all consumed services were already gone
- System.out.println("add provider");
- m.add(provider);
- // still nothing should happen
- System.out.println("remove adapter");
- m.remove(adapter);
- System.out.println("remove adapter2");
- m.remove(adapter2);
- System.out.println("remove aspect");
- m.remove(aspect);
- }
- m.remove(provider);
- e.waitForStep(stepsInLoop * loops, 5000);
- }
-
- static interface OriginalService {
- public void invoke();
- }
-
- static interface AdaptedService {
- public void invoke();
- }
-
- static class ServiceProvider implements OriginalService {
- public void start() {
- System.out.println("...provider started");
- }
- public void invoke() {
- }
-
- @Override
- public String toString() {
- return "Provider";
- }
- }
-
- public static class ServiceAdapter implements AdaptedService {
- private volatile OriginalService m_originalService;
- private final Ensure m_ensure;
- private final int m_nr;
-
- public ServiceAdapter(Ensure e, int nr) {
- this.m_ensure = e;
- this.m_nr = nr;
- }
- public void init() {
- }
- public void start() {
- System.out.println("...adapter started");
- }
- public void invoke() {
- m_originalService.invoke();
- }
- public void stop() {
- }
-
- void add(ServiceReference ref, OriginalService originalService) {
- m_originalService = originalService;
- m_ensure.step();
- System.out.println("adapter" + m_nr + " add: " + originalService);
- }
-
- void remove(ServiceReference ref, OriginalService originalService) {
- System.out.println("adapter" + m_nr + " rem: " + originalService);
- m_originalService = null;
- }
-
- void swap(ServiceReference oldRef, OriginalService oldService, ServiceReference newRef, OriginalService newService) {
- m_originalService = newService;
- m_ensure.step();
- System.out.println("adapter" + m_nr + " swp: " + newService);
- }
-
- @Override
- public String toString() {
- return "Adapter on " + m_originalService;
- }
- }
-
- public static class ServiceAspect implements OriginalService {
- volatile OriginalService m_service;
-
- public void start() {
- System.out.println("...aspect started");
- }
-
- public void invoke() {
- m_service.invoke();
- }
-
- @Override
- public String toString() {
- return "Aspect on " + m_service;
- }
- }
-
- public static class ServiceConsumer {
- Ensure m_ensure;
-
- public ServiceConsumer(Ensure e) {
- m_ensure = e;
- }
-
-// public void init() {
-// Thread t = new Thread(this);
-// t.start();
-// }
- public void start() {
- System.out.println("Consumer starting...");
- }
-
- int counter = 0;
- public void add(ServiceReference ref, AdaptedService service) {
- counter++;
- System.out.println("consumer add: " + counter + " " + service);
- m_ensure.step();
- }
- public void remove(ServiceReference ref, AdaptedService service) {
- counter--;
- System.out.println("consumer rem: " + counter + " " + service);
- m_ensure.step();
- }
- public void swap(ServiceReference oldRef, AdaptedService oldService, ServiceReference newRef, AdaptedService newService) {
- System.out.println("consumer swp: " + counter + " " + newService);
- m_ensure.step();
- }
-
-// public void run() {
-// m_service.invoke();
-// }
- }
-}
-
-
diff --git a/dependencymanager/test/src/test/java/org/apache/felix/dm/test/integration/api/AdapterWithExtraDependenciesTest.java b/dependencymanager/test/src/test/java/org/apache/felix/dm/test/integration/api/AdapterWithExtraDependenciesTest.java
deleted file mode 100644
index fcb82a5..0000000
--- a/dependencymanager/test/src/test/java/org/apache/felix/dm/test/integration/api/AdapterWithExtraDependenciesTest.java
+++ /dev/null
@@ -1,106 +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.felix.dm.test.integration.api;
-
-import org.apache.felix.dm.Component;
-import org.apache.felix.dm.DependencyManager;
-import org.apache.felix.dm.test.components.Ensure;
-import org.apache.felix.dm.test.integration.common.TestBase;
-import org.junit.Test;
-import org.junit.runner.RunWith;
-import org.ops4j.pax.exam.junit.PaxExam;
-
-@RunWith(PaxExam.class)
-public class AdapterWithExtraDependenciesTest extends TestBase {
- @Test
- public void testAdapterWithExtraDependenciesAndCallbacks() {
- DependencyManager m = new DependencyManager(context);
- // helper class that ensures certain steps get executed in sequence
- Ensure e = new Ensure();
-
- // create a service adapter that adapts to services S1 and has an optional dependency on services S2
- Component sa = m.createAdapterService(S1.class, null)
- .setImplementation(SA.class)
- .add(m.createServiceDependency().setService(S2.class).setCallbacks("add", "remove"));
- m.add(sa);
-
- // create a service S1, which triggers the creation of the first adapter instance (A1)
- Component s1 = m.createComponent().setInterface(S1.class.getName(), null).setImplementation(new S1Impl());
- m.add(s1);
-
- // create a service S2, which will be added to A1
- Component s2 = m.createComponent().setInterface(S2.class.getName(), null).setImplementation(new S2Impl(e));
- m.add(s2);
-
- // create a second service S1, which triggers the creation of the second adapter instance (A2)
- Component s1b = m.createComponent().setInterface(S1.class.getName(), null).setImplementation(new S1Impl());
- m.add(s1b);
-
- // observe that S2 is also added to A2
- e.waitForStep(2, 5000);
-
- // remove S2 again
- m.remove(s2);
-
- // make sure both adapters have their "remove" callbacks invoked
- e.waitForStep(4, 5000);
-
- m.remove(s1);
- m.remove(sa);
- }
-
- static interface S1 {
- }
- static interface S2 {
- public void invoke();
- }
- static class S1Impl implements S1 {
- }
- static class S2Impl implements S2 {
-
- private final Ensure m_e;
-
- public S2Impl(Ensure e) {
- m_e = e;
- }
-
- public void invoke() {
- m_e.step();
- }
- }
-
- public static class SA {
- volatile S2 s2;
-
- public SA() {
- System.out.println("Adapter created");
- }
- public void init() {
- System.out.println("Adapter init " + s2);
- }
- public void add(S2 s) {
- System.out.println("adding " + s);
- s.invoke();
- }
- public void remove(S2 s) {
- System.out.println("removing " + s);
- s.invoke();
- }
- }
-}
diff --git a/dependencymanager/test/src/test/java/org/apache/felix/dm/test/integration/api/AdapterWithInstanceBoundDependencyTest.java b/dependencymanager/test/src/test/java/org/apache/felix/dm/test/integration/api/AdapterWithInstanceBoundDependencyTest.java
deleted file mode 100644
index 6c8cc49..0000000
--- a/dependencymanager/test/src/test/java/org/apache/felix/dm/test/integration/api/AdapterWithInstanceBoundDependencyTest.java
+++ /dev/null
@@ -1,138 +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.felix.dm.test.integration.api;
-
-import org.apache.felix.dm.Component;
-import org.apache.felix.dm.DependencyManager;
-import org.apache.felix.dm.test.components.Ensure;
-import org.apache.felix.dm.test.integration.common.TestBase;
-import org.junit.Test;
-import org.junit.runner.RunWith;
-import org.ops4j.pax.exam.junit.PaxExam;
-
-@RunWith(PaxExam.class)
-public class AdapterWithInstanceBoundDependencyTest extends TestBase {
- @Test
- public void testInstanceBoundDependency() {
- DependencyManager m = new DependencyManager(context);
- // helper class that ensures certain steps get executed in sequence
- Ensure e = new Ensure();
- // create a service provider and consumer
- Component sp = m.createComponent()
- .setInterface(ServiceInterface.class.getName(), null)
- .setImplementation(new ServiceProvider(e));
- Component sp2 = m.createComponent()
- .setInterface(ServiceInterface2.class.getName(), null)
- .setImplementation(new ServiceProvider2(e));
- Component sc = m.createComponent()
- .setImplementation(new ServiceConsumer())
- .add(m.createServiceDependency()
- .setService(ServiceInterface3.class)
- .setRequired(true));
- Component sa = m.createAdapterService(ServiceInterface.class, null)
- .setInterface(ServiceInterface3.class.getName(), null)
- .setImplementation(new ServiceAdapter(e));
- m.add(sc);
- m.add(sp);
- m.add(sp2);
- m.add(sa);
- e.waitForStep(5, 15000);
- m.remove(sa);
- m.remove(sp2);
- m.remove(sp);
- m.remove(sc);
- }
-
- static interface ServiceInterface {
- public void invoke();
- }
-
- static interface ServiceInterface2 {
- public void invoke();
- }
-
- static interface ServiceInterface3 {
- public void invoke();
- }
-
- static class ServiceProvider2 implements ServiceInterface2 {
- private final Ensure m_ensure;
-
- public ServiceProvider2(Ensure ensure) {
- m_ensure = ensure;
- }
-
- public void invoke() {
- m_ensure.step(4);
- }
- }
-
- static class ServiceProvider implements ServiceInterface {
- private final Ensure m_ensure;
- public ServiceProvider(Ensure e) {
- m_ensure = e;
- }
- public void invoke() {
- m_ensure.step(5);
- }
- }
-
- static class ServiceAdapter implements ServiceInterface3 {
- private Ensure m_ensure;
- private volatile ServiceInterface m_originalService;
- private volatile ServiceInterface2 m_injectedService;
- private volatile Component m_service;
- private volatile DependencyManager m_manager;
-
- public ServiceAdapter(Ensure e) {
- m_ensure = e;
- }
- public void init() {
- m_ensure.step(1);
- m_service.add(m_manager.createServiceDependency().setInstanceBound(true).setRequired(true).setService(ServiceInterface2.class));
- }
- public void start() {
- m_ensure.step(2);
- }
- public void invoke() {
- m_ensure.step(3);
- m_injectedService.invoke();
- m_originalService.invoke();
- }
-
- public void stop() {
- m_ensure.step(6);
- }
- }
-
- static class ServiceConsumer implements Runnable {
- private volatile ServiceInterface3 m_service;
-
- public void init() {
- Thread t = new Thread(this);
- t.start();
- }
-
- public void run() {
- m_service.invoke();
- }
- }
-}
-
-
diff --git a/dependencymanager/test/src/test/java/org/apache/felix/dm/test/integration/api/AdapterWithModifiedInstanceBoundDependencyTest.java b/dependencymanager/test/src/test/java/org/apache/felix/dm/test/integration/api/AdapterWithModifiedInstanceBoundDependencyTest.java
deleted file mode 100644
index 450badc..0000000
--- a/dependencymanager/test/src/test/java/org/apache/felix/dm/test/integration/api/AdapterWithModifiedInstanceBoundDependencyTest.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.felix.dm.test.integration.api;
-
-import java.util.Dictionary;
-import java.util.Hashtable;
-import java.util.Map;
-
-import junit.framework.Assert;
-
-import org.apache.felix.dm.Component;
-import org.apache.felix.dm.DependencyManager;
-import org.apache.felix.dm.test.components.Ensure;
-import org.apache.felix.dm.test.integration.common.TestBase;
-import org.junit.Test;
-import org.junit.runner.RunWith;
-import org.ops4j.pax.exam.junit.PaxExam;
-
-/**
- * Test for FELIX-4334 issue.
- *
- * Three components: A, B and C
- *
- * - A provided with property foo=bar
- * - B adapts A, B has no filters on A, and B.init() method adds an instance bound required dependency to C.
- * - C depends on A(foo=bar)
- * - Now someone modifies the service properties of A: foo=bar2
- * - As a result of that, C becomes unavailable and is unbound from B.
- * - Since B has an instance bound required dependency to C: B should not be destroyed: it should be called in B.stop(), B.remove(C), B.change(A, "foo=bar2))
- *
- * @author <a href="mailto:dev@felix.apache.org">Felix Project Team</a>
- */
-@RunWith(PaxExam.class)
-public class AdapterWithModifiedInstanceBoundDependencyTest extends TestBase {
- public static interface A {
- }
-
- static class AImpl implements A {
- final Ensure m_e;
- AImpl(Ensure e) {
- m_e = e;
- }
- }
-
- public static interface C {
- }
-
- static class CImpl implements C {
- volatile A m_a;
- }
-
- public static interface B {
- }
-
- static class BImpl implements B {
- final Ensure m_e;
- volatile A m_a;
- volatile C m_c;
-
- BImpl(Ensure e) {
- m_e = e;
- }
-
- public void add(A a) {
- m_e.step(1);
- }
-
- void init(Component c) {
- m_e.step(2);
- DependencyManager dm = c.getDependencyManager();
- c.add(dm.createServiceDependency().setService(C.class).setRequired(true).setInstanceBound(true).setCallbacks("add", "remove"));
- }
-
- public void add(C c) {
- m_e.step(3);
- }
-
- public void start() {
- m_e.step(4);
- }
-
- public void stop() { // C becomes unsatisfied when A properties are changed to foo=bar2
- m_e.step(5);
- }
-
- public void remove(C c) {
- m_e.step(6);
- }
-
- public void change(Map properties, A a) {
- Assert.assertEquals("bar2", properties.get("foo"));
- m_e.step(7);
- }
-
- public void destroy() {
- m_e.step(8);
- }
-
- public void remove(A a) {
- m_e.step(9);
- }
- }
-
- @Test
- public void testAdapterWithChangedInstanceBoundDependency() {
- DependencyManager m = new DependencyManager(context);
- Ensure e = new Ensure();
-
- Dictionary props = new Hashtable();
- props.put("foo", "bar");
- Component a = m.createComponent()
- .setImplementation(new AImpl(e))
- .setInterface(A.class.getName(), props);
-
- Component b = m.createAdapterService(A.class, null, "add", "change", "remove")
- .setInterface(B.class.getName(), null)
- .setImplementation(new BImpl(e));
-
- Component c = m.createComponent()
- .setImplementation(new CImpl())
- .setInterface(C.class.getName(), null)
- .add(m.createServiceDependency().setService(A.class, "(foo=bar)").setRequired(true));
-
- m.add(a);
- m.add(c);
- m.add(b);
-
- e.waitForStep(4, 5000);
-
- System.out.println("changing A props ...");
- props = new Hashtable();
- props.put("foo", "bar2");
- a.setServiceProperties(props);
-
- e.waitForStep(7, 5000);
-
- m.remove(c);
- m.remove(a);
- m.remove(b);
-
- e.waitForStep(9, 5000);
- }
-}
diff --git a/dependencymanager/test/src/test/java/org/apache/felix/dm/test/integration/api/AdapterWithPropagationTest.java b/dependencymanager/test/src/test/java/org/apache/felix/dm/test/integration/api/AdapterWithPropagationTest.java
deleted file mode 100644
index 8518777..0000000
--- a/dependencymanager/test/src/test/java/org/apache/felix/dm/test/integration/api/AdapterWithPropagationTest.java
+++ /dev/null
@@ -1,137 +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.felix.dm.test.integration.api;
-
-import java.util.Dictionary;
-import java.util.Hashtable;
-import java.util.Map;
-
-import junit.framework.Assert;
-
-import org.apache.felix.dm.Component;
-import org.apache.felix.dm.DependencyManager;
-import org.apache.felix.dm.test.components.Ensure;
-import org.apache.felix.dm.test.integration.common.TestBase;
-import org.junit.Test;
-import org.junit.runner.RunWith;
-import org.ops4j.pax.exam.junit.PaxExam;
-
-/**
- * Checks if a service adapter propagates its service properties, if
- * the adapted service properties are changed:
- *
- * S1Impl provides S
- * S1Adapter adapts S1Impl(S) to S2
- * S3 depends on S2
- *
- * So, when S1Impl service properties are changed, S1Adapter shall propagate the changed properties to S3.
- *
- * @author <a href="mailto:dev@felix.apache.org">Felix Project Team</a>
- */
-@RunWith(PaxExam.class)
-public class AdapterWithPropagationTest extends TestBase {
- public static interface S1 {}
-
- static class S1Impl implements S1 {
- private Ensure m_ensure;
- public S1Impl(Ensure e) {
- m_ensure = e;
- }
-
- public void start() {
- m_ensure.step(1);
- }
- }
-
- public static interface S2 {}
-
- static class S1Adapter implements S2 {
- private Ensure m_ensure;
- public S1Adapter(Ensure e) {
- m_ensure = e;
- }
-
- public void add(Map properties, S1 s1) {
- Assert.assertTrue("bar".equals(properties.get("foo")));
- m_ensure.step(2);
- }
-
- public void change(Map properties, S1 s1) {
- Assert.assertTrue("bar2".equals(properties.get("foo")));
- m_ensure.step(4);
- }
- }
-
- static class S3 {
- private final Ensure m_ensure;
-
- public S3(Ensure e) {
- m_ensure = e;
- }
-
- public void add(Map properties, S2 s2) {
- Assert.assertTrue("bar".equals(properties.get("foo")));
- m_ensure.step(3);
- }
-
- public void change(Map properties, S2 s2) {
- Assert.assertTrue("bar2".equals(properties.get("foo")));
- m_ensure.step(5);
- }
- }
-
- @Test
- public void testAdapterWithPropagation() {
- DependencyManager m = new DependencyManager(context);
- // helper class that ensures certain steps get executed in sequence
- Ensure e = new Ensure();
-
- Dictionary s1Properties = new Hashtable();
- s1Properties.put("foo", "bar");
- Component s1 = m.createComponent()
- .setImplementation(new S1Impl(e))
- .setInterface(S1.class.getName(), s1Properties);
-
- Component s1Adapter = m.createAdapterService(S1.class, null, "add", "change", null)
- .setInterface(S2.class.getName(), null)
- .setImplementation(new S1Adapter(e));
-
- Component s3 = m.createComponent()
- .setImplementation(new S3(e))
- .add(m.createServiceDependency()
- .setService(S2.class)
- .setRequired(true)
- .setCallbacks("add", "change", null));
-
-
- m.add(s1);
- m.add(s1Adapter);
- m.add(s3);
-
- e.waitForStep(3, 5000);
-
- s1Properties = new Hashtable();
- s1Properties.put("foo", "bar2");
- s1.setServiceProperties(s1Properties);
-
- e.waitForStep(5, 5000);
-
- m.clear();
- }
-}
diff --git a/dependencymanager/test/src/test/java/org/apache/felix/dm/test/integration/api/AspectAwareServiceDependencyTest.java b/dependencymanager/test/src/test/java/org/apache/felix/dm/test/integration/api/AspectAwareServiceDependencyTest.java
deleted file mode 100644
index e4ee940..0000000
--- a/dependencymanager/test/src/test/java/org/apache/felix/dm/test/integration/api/AspectAwareServiceDependencyTest.java
+++ /dev/null
@@ -1,90 +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.felix.dm.test.integration.api;
-
-import org.apache.felix.dm.Component;
-import org.apache.felix.dm.DependencyManager;
-import org.apache.felix.dm.test.components.Ensure;
-import org.apache.felix.dm.test.integration.common.TestBase;
-import org.junit.Test;
-import org.junit.runner.RunWith;
-import org.ops4j.pax.exam.junit.PaxExam;
-
-@RunWith(PaxExam.class)
-public class AspectAwareServiceDependencyTest extends TestBase {
- @Test
- public void testServiceRegistrationAndConsumption() {
- DependencyManager m = new DependencyManager(context);
- // helper class that ensures certain steps get executed in sequence
- Ensure e = new Ensure();
- // create a service provider and consumer
- Component sp = m.createComponent().setImplementation(new ServiceProvider(e)).setInterface(ServiceInterface.class.getName(), null);
- Component sc = m.createComponent().setImplementation(new ServiceConsumerCallbacks(e)).add(m.createServiceDependency().setService(ServiceInterface.class).setRequired(false).setCallbacks("add", "change", "remove", "swap"));
- Component asp = m.createAspectService(ServiceInterface.class, null, 1000, null).setImplementation(ServiceProviderAspect.class);
- m.add(sp);
- m.add(sc);
- m.add(asp);
- m.remove(sc);
- m.remove(sp);
- // ensure we executed all steps inside the component instance
- e.step(4);
- }
-
- static interface ServiceInterface {
- public void invoke();
- }
-
- static class ServiceProvider implements ServiceInterface {
- private final Ensure m_ensure;
- public ServiceProvider(Ensure e) {
- m_ensure = e;
- }
- public void invoke() {
- }
- }
-
- static class ServiceConsumerCallbacks {
- private final Ensure m_ensure;
-
- public ServiceConsumerCallbacks(Ensure e) {
- m_ensure = e;
- }
-
- public void add(ServiceInterface service) {
- m_ensure.step(1);
- }
- public void remove(ServiceInterface service) {
- m_ensure.step(3);
- }
- public void swap(ServiceInterface oldService, ServiceInterface newService) {
- m_ensure.step(2);
- }
- }
-
- static class ServiceProviderAspect implements ServiceInterface {
- private volatile ServiceProvider serviceProvider;
-
- public ServiceProviderAspect() {
- }
-
- public void invoke() {
- serviceProvider.invoke();
- }
- }
-}
diff --git a/dependencymanager/test/src/test/java/org/apache/felix/dm/test/integration/api/AspectBaseTest.java b/dependencymanager/test/src/test/java/org/apache/felix/dm/test/integration/api/AspectBaseTest.java
deleted file mode 100644
index 07b6233..0000000
--- a/dependencymanager/test/src/test/java/org/apache/felix/dm/test/integration/api/AspectBaseTest.java
+++ /dev/null
@@ -1,225 +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.felix.dm.test.integration.api;
-
-import java.util.ArrayList;
-import java.util.List;
-import java.util.Properties;
-
-import junit.framework.Assert;
-
-import org.apache.felix.dm.Component;
-import org.apache.felix.dm.DependencyManager;
-import org.apache.felix.dm.ServiceUtil;
-import org.apache.felix.dm.test.components.Ensure;
-import org.apache.felix.dm.test.integration.common.TestBase;
-import org.junit.Test;
-import org.junit.runner.RunWith;
-import org.ops4j.pax.exam.junit.PaxExam;
-import org.osgi.framework.ServiceReference;
-import org.osgi.framework.ServiceRegistration;
-
-@RunWith(PaxExam.class)
-public class AspectBaseTest extends TestBase {
- @Test
- public void testSingleAspect() {
- DependencyManager m = new DependencyManager(context);
- // helper class that ensures certain steps get executed in sequence
- Ensure e = new Ensure();
-
- // create a service provider and consumer
- ServiceProvider p = new ServiceProvider(e, "a");
- ServiceConsumer c = new ServiceConsumer(e);
- Component sp = m.createComponent()
- .setInterface(ServiceInterface.class.getName(), new Properties() {{ put("name", "a"); }})
- .setImplementation(p);
- Component sc = m.createComponent()
- .setImplementation(c)
- .add(m.createServiceDependency()
- .setService(ServiceInterface.class)
- .setRequired(true)
- .setCallbacks("add", "remove")
- .setAutoConfig(true)
- );
- Component sa = m.createAspectService(ServiceInterface.class, null, 20, null)
- .setImplementation(ServiceAspect.class);
- m.add(sc);
- m.add(sp);
- // after the provider was added, the consumer's add should have been invoked once
- e.waitForStep(1, 2000);
- Assert.assertEquals("a", c.invoke());
- m.add(sa);
- // after the aspect was added, the consumer should get and add for the aspect and a remove
- // for the original service
- e.waitForStep(3, 2000);
- Assert.assertEquals("aa", c.invoke());
- m.remove(sa);
- // removing the aspect again should give a remove and add
- e.waitForStep(5, 2000);
- Assert.assertEquals("a", c.invoke());
- m.remove(sp);
- // finally removing the original service should give a remove
- e.waitForStep(6, 2000);
- m.remove(sc);
- e.step(7);
- }
-
- @Test
- public void testSingleAspectThatAlreadyExisted() {
- DependencyManager m = new DependencyManager(context);
- // helper class that ensures certain steps get executed in sequence
- Ensure e = new Ensure();
-
- // create a service provider and consumer
- ServiceProvider p = new ServiceProvider(e, "a");
- ServiceConsumer c = new ServiceConsumer(e);
- Component sp = m.createComponent().setImplementation(p).setInterface(ServiceInterface.class.getName(), new Properties() {{ put("name", "a"); }});
- Component sc = m.createComponent().setImplementation(c).add(m.createServiceDependency().setService(ServiceInterface.class).setRequired(true).setCallbacks("add", "remove").setAutoConfig(true));
- Component sa = m.createAspectService(ServiceInterface.class, null, 20, null).setImplementation(ServiceAspect.class);
- // we first add the aspect
- m.add(sa);
- // then the service provider
- m.add(sp);
- // finally the consumer
- m.add(sc);
-
- Assert.assertEquals("aa", c.invoke());
-
- // now the consumer's added should be invoked once, as the aspect is already available and should
- // directly hide the original service
- e.waitForStep(1, 2000);
- e.step(2);
-
- m.remove(sa);
- // after removing the aspect, the consumer should get the original service back, so
- // remove and add will be invoked
- e.waitForStep(4, 2000);
-
- Assert.assertEquals("a", c.invoke());
-
- m.remove(sp);
- // after removing the original service, the consumer's remove should be called once
- e.waitForStep(5, 2000);
-
- m.remove(sc);
- e.step(6);
- }
-
- @Test
- public void testMultipleAspects() {
- DependencyManager m = new DependencyManager(context);
- // helper class that ensures certain steps get executed in sequence
- Ensure e = new Ensure();
-
- // create service providers and consumers
- ServiceConsumer c = new ServiceConsumer(e);
- Component sp = m.createComponent().setImplementation(new ServiceProvider(e, "a")).setInterface(ServiceInterface.class.getName(), new Properties() {{ put("name", "a"); }});
- Component sp2 = m.createComponent().setImplementation(new ServiceProvider(e, "b")).setInterface(ServiceInterface.class.getName(), new Properties() {{ put("name", "b"); }});
- Component sc = m.createComponent().setImplementation(c).add(m.createServiceDependency().setService(ServiceInterface.class).setRequired(true).setCallbacks("add", "remove"));
- Component sa = m.createAspectService(ServiceInterface.class, null, 20, null).setImplementation(ServiceAspect.class);
- Component sa2 = m.createAspectService(ServiceInterface.class, null, 10, null).setImplementation(ServiceAspect.class);
- m.add(sp);
- m.add(sp2);
- m.add(sa);
- m.add(sa2);
- m.add(sc);
- // the consumer will monitor progress, it should get it's add invoked twice, once for every
- // (highest) aspect
- e.waitForStep(2, 2000);
- e.step(3);
-
- // now invoke all services the consumer collected
- List<String> list = c.invokeAll();
- // and make sure both of them are correctly invoked
- Assert.assertTrue(list.size() == 2);
- Assert.assertTrue(list.contains("aaa"));
- Assert.assertTrue(list.contains("bbb"));
-
- m.remove(sc);
- // removing the consumer now should get its removed method invoked twice
- e.waitForStep(5, 2000);
- e.step(6);
- m.remove(sa2);
- m.remove(sa);
- m.remove(sp2);
- m.remove(sp);
- e.step(7);
- }
-
- public static interface ServiceInterface {
- public String invoke(String input);
- }
-
- public static class ServiceProvider implements ServiceInterface {
- private final Ensure m_ensure;
- private final String m_name;
- public ServiceProvider(Ensure e, String name) {
- m_ensure = e;
- m_name = name;
- }
- public String invoke(String input) {
- return input + m_name;
- }
- }
-
- public static class ServiceAspect implements ServiceInterface {
- private volatile ServiceInterface m_originalService;
- private volatile ServiceRegistration m_registration;
-
- public String invoke(String input) {
- String result = m_originalService.invoke(input);
- String property = (String) m_registration.getReference().getProperty("name");
- return result + property;
- }
- }
-
- public static class ServiceConsumer {
- private final Ensure m_ensure;
- private volatile ServiceInterface m_service;
- private List<ServiceInterface> m_services = new ArrayList<ServiceInterface>();
-
- public ServiceConsumer(Ensure e) {
- m_ensure = e;
- }
-
- public void add(ServiceReference ref, ServiceInterface si) {
- System.out.println("add: " + ServiceUtil.toString(ref));
- m_services.add(si);
- m_ensure.step();
- }
-
- public void remove(ServiceReference ref, ServiceInterface si) {
- System.out.println("rem: " + ServiceUtil.toString(ref));
- m_services.remove(si);
- m_ensure.step();
- }
-
- public String invoke() {
- return m_service.invoke("");
- }
-
- public List<String> invokeAll() {
- List<String> results = new ArrayList<String>();
- for (ServiceInterface si : m_services) {
- results.add(si.invoke(""));
- }
- return results;
- }
- }
-}
diff --git a/dependencymanager/test/src/test/java/org/apache/felix/dm/test/integration/api/AspectChainTest.java b/dependencymanager/test/src/test/java/org/apache/felix/dm/test/integration/api/AspectChainTest.java
deleted file mode 100644
index 6eda2f4..0000000
--- a/dependencymanager/test/src/test/java/org/apache/felix/dm/test/integration/api/AspectChainTest.java
+++ /dev/null
@@ -1,111 +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.felix.dm.test.integration.api;
-
-import org.apache.felix.dm.Component;
-import org.apache.felix.dm.DependencyManager;
-import org.apache.felix.dm.test.components.Ensure;
-import org.apache.felix.dm.test.integration.common.TestBase;
-import org.junit.Test;
-import org.junit.runner.RunWith;
-import org.ops4j.pax.exam.junit.PaxExam;
-
-@RunWith(PaxExam.class)
-public class AspectChainTest extends TestBase {
- @Test
- public void testBuildAspectChain() {
- DependencyManager m = new DependencyManager(context);
- // helper class that ensures certain steps get executed in sequence
- Ensure e = new Ensure();
- // create a service provider and consumer
- Component sp = m.createComponent().setImplementation(new ServiceProvider(e)).setInterface(ServiceInterface.class.getName(), null);
- Component sc = m.createComponent().setImplementation(new ServiceConsumer(e)).add(m.createServiceDependency().setService(ServiceInterface.class).setRequired(true));
- Component sa2 = m.createAspectService(ServiceInterface.class, null, 20, null).setImplementation(new ServiceAspect(e, 3));
- Component sa3 = m.createAspectService(ServiceInterface.class, null, 30, null).setImplementation(new ServiceAspect(e, 2));
- Component sa1 = m.createAspectService(ServiceInterface.class, null, 10, null).setImplementation(new ServiceAspect(e, 4));
- m.add(sc);
-
- m.add(sp);
- m.add(sa2);
- m.add(sa3);
- m.add(sa1);
- e.step();
-
- m.remove(sa3);
- m.remove(sa2);
- m.remove(sa1);
- m.remove(sp);
-
- m.remove(sc);
- }
-
- static interface ServiceInterface {
- public void invoke(Runnable run);
- }
-
- static class ServiceProvider implements ServiceInterface {
- private final Ensure m_ensure;
- public ServiceProvider(Ensure e) {
- m_ensure = e;
- }
- public void invoke(Runnable run) {
- run.run();
- }
- }
-
- static class ServiceAspect implements ServiceInterface {
- private final Ensure m_ensure;
- private volatile ServiceInterface m_parentService;
- private final int m_step;
-
- public ServiceAspect(Ensure e, int step) {
- m_ensure = e;
- m_step = step;
- }
- public void start() {
- }
-
- public void invoke(Runnable run) {
- m_ensure.step(m_step);
- m_parentService.invoke(run);
- }
-
- public void stop() {
- }
- }
-
- static class ServiceConsumer implements Runnable {
- private volatile ServiceInterface m_service;
- private final Ensure m_ensure;
-
- public ServiceConsumer(Ensure e) {
- m_ensure = e;
- }
-
- public void init() {
- Thread t = new Thread(this);
- t.start();
- }
-
- public void run() {
- m_ensure.waitForStep(1, 2000);
- m_service.invoke(Ensure.createRunnableStep(m_ensure, 5));
- }
- }
-}
diff --git a/dependencymanager/test/src/test/java/org/apache/felix/dm/test/integration/api/AspectDynamicsTest.java b/dependencymanager/test/src/test/java/org/apache/felix/dm/test/integration/api/AspectDynamicsTest.java
deleted file mode 100644
index ccc636f..0000000
--- a/dependencymanager/test/src/test/java/org/apache/felix/dm/test/integration/api/AspectDynamicsTest.java
+++ /dev/null
@@ -1,171 +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.felix.dm.test.integration.api;
-
-import org.apache.felix.dm.Component;
-import org.apache.felix.dm.DependencyManager;
-import org.apache.felix.dm.test.components.Ensure;
-import org.apache.felix.dm.test.integration.common.TestBase;
-import org.junit.Test;
-import org.junit.runner.RunWith;
-import org.ops4j.pax.exam.junit.PaxExam;
-
-@RunWith(PaxExam.class)
-public class AspectDynamicsTest extends TestBase {
- @Test
- public void testDynamicallyAddAndRemoveAspect() {
- DependencyManager m = new DependencyManager(context);
- // helper class that ensures certain steps get executed in sequence
- Ensure e = new Ensure();
- // create a service provider and consumer
- Component provider = m.createComponent().setImplementation(new ServiceProvider(e)).setInterface(ServiceInterface.class.getName(), null);
- Component provider2 = m.createComponent().setImplementation(new ServiceProvider2(e)).setInterface(ServiceInterface2.class.getName(), null);
- Component consumer = m.createComponent().setImplementation(new ServiceConsumer(e)).add(m.createServiceDependency().setService(ServiceInterface.class).setRequired(true));
- Component aspect = m.createAspectService(ServiceInterface.class, null, 1, null).setImplementation(new ServiceAspect(e));
-
- m.add(consumer);
- m.add(provider);
- // the consumer should invoke the provider here, and when done, arrive at step 3
- // finally wait for step 6 before continuing
- e.waitForStep(3, 15000);
-
- m.add(aspect);
- // after adding the aspect, we wait for its init to be invoked, arriving at
- // step 4 after an instance bound dependency was added (on a service provided by
- // provider 2)
- e.waitForStep(4, 15000);
-
- m.add(provider2);
-
- // after adding provider 2, we should now see the aspect being started, so
- // we wait for step 5 to happen
- e.waitForStep(5, 15000);
-
- // now we continue with step 6, which will trigger the next part of the consumer's
- // run method to be executed
- e.step(6);
-
- // invoking step 7, 8 and 9 when invoking the aspect which in turn invokes the
- // dependency and the original service, so we wait for that to finish here, which
- // is after step 10 has been reached (the client will now wait for step 12)
- e.waitForStep(10, 15000);
-
- m.remove(aspect);
- // removing the aspect should trigger step 11 (in the stop method of the aspect)
- e.waitForStep(11, 15000);
-
- // step 12 triggers the client to continue
- e.step(12);
-
- // wait for step 13, the final invocation of the provided service (without aspect)
- e.waitForStep(13, 15000);
-
- // clean up
- m.remove(provider2);
- m.remove(provider);
- m.remove(consumer);
- }
-
- static interface ServiceInterface {
- public void invoke(Runnable run);
- }
-
- static interface ServiceInterface2 {
- public void invoke();
- }
-
- static class ServiceProvider2 implements ServiceInterface2 {
- private final Ensure m_ensure;
-
- public ServiceProvider2(Ensure ensure) {
- m_ensure = ensure;
- }
-
- public void invoke() {
- m_ensure.step(9);
- }
- }
-
- static class ServiceProvider implements ServiceInterface {
- private final Ensure m_ensure;
- public ServiceProvider(Ensure e) {
- m_ensure = e;
- }
- public void invoke(Runnable run) {
- run.run();
- }
- }
-
- static class ServiceAspect implements ServiceInterface {
- private final Ensure m_ensure;
- private volatile ServiceInterface m_originalService;
- private volatile ServiceInterface2 m_injectedService;
- private volatile Component m_service;
- private volatile DependencyManager m_manager;
-
- public ServiceAspect(Ensure e) {
- m_ensure = e;
- }
- public void init() {
- m_service.add(m_manager.createServiceDependency()
- .setService(ServiceInterface2.class)
- .setRequired(true)
- .setInstanceBound(true)
- );
- m_ensure.step(4);
- }
- public void start() {
- m_ensure.step(5);
- }
- public void invoke(Runnable run) {
- m_ensure.step(7);
- m_originalService.invoke(run);
- m_injectedService.invoke();
- }
-
- public void stop() {
- m_ensure.step(11);
- }
- }
-
- static class ServiceConsumer implements Runnable {
- private volatile ServiceInterface m_service;
- private final Ensure m_ensure;
-
- public ServiceConsumer(Ensure e) {
- m_ensure = e;
- }
-
- public void init() {
- Thread t = new Thread(this);
- t.start();
- }
-
- public void run() {
- m_ensure.step(1);
- m_service.invoke(Ensure.createRunnableStep(m_ensure, 2));
- m_ensure.step(3);
- m_ensure.waitForStep(6, 15000);
- m_service.invoke(Ensure.createRunnableStep(m_ensure, 8));
- m_ensure.step(10);
- m_ensure.waitForStep(12, 15000);
- m_service.invoke(Ensure.createRunnableStep(m_ensure, 13));
- }
- }
-}
diff --git a/dependencymanager/test/src/test/java/org/apache/felix/dm/test/integration/api/AspectWhiteboardTest.java b/dependencymanager/test/src/test/java/org/apache/felix/dm/test/integration/api/AspectWhiteboardTest.java
deleted file mode 100644
index 96fc74e..0000000
--- a/dependencymanager/test/src/test/java/org/apache/felix/dm/test/integration/api/AspectWhiteboardTest.java
+++ /dev/null
@@ -1,202 +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.felix.dm.test.integration.api;
-
-import java.util.ArrayList;
-import java.util.List;
-
-import junit.framework.Assert;
-
-import org.apache.felix.dm.Component;
-import org.apache.felix.dm.DependencyManager;
-import org.apache.felix.dm.ServiceUtil;
-import org.apache.felix.dm.test.components.Ensure;
-import org.apache.felix.dm.test.integration.common.TestBase;
-import org.junit.Test;
-import org.junit.runner.RunWith;
-import org.ops4j.pax.exam.junit.PaxExam;
-import org.osgi.framework.Constants;
-import org.osgi.framework.ServiceReference;
-
-@RunWith(PaxExam.class)
-public class AspectWhiteboardTest extends TestBase {
- @Test
- public void testWhiteboardConsumer() {
- DependencyManager m = new DependencyManager(context);
- // helper class that ensures certain steps get executed in sequence
- Ensure e = new Ensure();
- // create service providers and consumer
- Component sp1 = m.createComponent().setImplementation(new ServiceProvider(e)).setInterface(ServiceInterface.class.getName(), null);
- Component sp2 = m.createComponent().setImplementation(new ServiceProvider(e)).setInterface(ServiceInterface.class.getName(), null);
- ServiceConsumer sci = new ServiceConsumer(e);
- Component sc = m.createComponent().setImplementation(sci).add(m.createServiceDependency().setService(ServiceInterface.class).setRequired(false).setCallbacks("add", "remove"));
- Component sa2 = m.createAspectService(ServiceInterface.class, null, 20, null).setImplementation(new ServiceAspect(e, 3));
- Component sa1 = m.createAspectService(ServiceInterface.class, null, 10, null).setImplementation(new ServiceAspect(e, 4));
-
- // start with a service consumer
- System.out.println("Adding consumer");
- m.add(sc);
-
- // then add two providers, so the consumer will see two services
- System.out.println("Adding 2 providers");
- m.add(sp1);
- m.add(sp2);
-
- // make sure consumer sees both services
- Assert.assertEquals(2, sci.services());
-
- // add an aspect with ranking 20
- System.out.println("Adding aspect with rank 20");
- m.add(sa2);
-
- // make sure the consumer sees the two new aspects and no longer sees the two original services
- Assert.assertEquals(2, sci.services());
- Assert.assertEquals(20, sci.highestRanking());
- Assert.assertEquals(20, sci.lowestRanking());
-
- // add an aspect with ranking 10
- System.out.println("Adding aspect with rank 10");
- m.add(sa1);
-
- // make sure the consumer still sees the two aspects with ranking 20
- Assert.assertEquals(2, sci.services());
- Assert.assertEquals(20, sci.highestRanking());
- Assert.assertEquals(20, sci.lowestRanking());
-
- // remove the aspect with ranking 20
- System.out.println("Removing aspect with rank 20");
- m.remove(sa2);
-
- // make sure the consumer now sees the aspects with ranking 10
- Assert.assertEquals(2, sci.services());
- Assert.assertEquals(10, sci.highestRanking());
- Assert.assertEquals(10, sci.lowestRanking());
-
- // remove one of the original services
- System.out.println("Removing 1 service");
- m.remove(sp1);
-
- // make sure the aspect of that service goes away
- Assert.assertEquals(1, sci.services());
- Assert.assertEquals(10, sci.highestRanking());
- Assert.assertEquals(10, sci.lowestRanking());
-
- // remove the aspect with ranking 10
- System.out.println("Removing aspect with rank 10");
- m.remove(sa1);
-
- // make sure only the original service remains
- Assert.assertEquals(1, sci.services());
- Assert.assertEquals(0, sci.highestRanking());
- Assert.assertEquals(0, sci.lowestRanking());
-
- System.out.println("Done with test");
-
- // end of test
- m.remove(sa2);
- m.remove(sp2);
- m.remove(sc);
- }
-
- static interface ServiceInterface {
- public void invoke(Runnable run);
- }
-
- static class ServiceProvider implements ServiceInterface {
- private final Ensure m_ensure;
- public ServiceProvider(Ensure e) {
- m_ensure = e;
- }
- public void invoke(Runnable run) {
- run.run();
- }
- }
-
- static class ServiceAspect implements ServiceInterface {
- private final Ensure m_ensure;
- private volatile ServiceInterface m_parentService;
- private final int m_step;
-
- public ServiceAspect(Ensure e, int step) {
- m_ensure = e;
- m_step = step;
- }
- public void start() {
- }
-
- public void invoke(Runnable run) {
- m_ensure.step(m_step);
- m_parentService.invoke(run);
- }
-
- public void stop() {
- }
- }
-
- static class ServiceConsumer implements Runnable {
- private List m_services = new ArrayList();
- private final Ensure m_ensure;
-
- public ServiceConsumer(Ensure e) {
- m_ensure = e;
- }
-
- public void init() {
- Thread t = new Thread(this);
- t.start();
- }
-
- public void run() {
- }
-
- public int services() {
- return m_services.size();
- }
-
- public int highestRanking() {
- int ranking = Integer.MIN_VALUE;
- for (int i = 0; i < m_services.size(); i++) {
- ServiceReference ref = (ServiceReference) m_services.get(i);
- Integer r = (Integer) ref.getProperty(Constants.SERVICE_RANKING);
- int rank = r == null ? 0 : r.intValue();
- ranking = Math.max(ranking, rank);
- }
- return ranking;
- }
- public int lowestRanking() {
- int ranking = Integer.MAX_VALUE;
- for (int i = 0; i < m_services.size(); i++) {
- ServiceReference ref = (ServiceReference) m_services.get(i);
- Integer r = (Integer) ref.getProperty(Constants.SERVICE_RANKING);
- int rank = r == null ? 0 : r.intValue();
- ranking = Math.min(ranking, rank);
- }
- return ranking;
- }
-
- public void add(ServiceReference ref, ServiceInterface svc) {
- System.out.println("Added: " + ServiceUtil.toString(ref));
- m_services.add(ref);
- }
- public void remove(ServiceReference ref, ServiceInterface svc) {
- System.out.println("Removed: " + ServiceUtil.toString(ref));
- m_services.remove(ref);
- }
- }
-}
diff --git a/dependencymanager/test/src/test/java/org/apache/felix/dm/test/integration/api/AspectWithPropagationTest.java b/dependencymanager/test/src/test/java/org/apache/felix/dm/test/integration/api/AspectWithPropagationTest.java
deleted file mode 100644
index 6561618..0000000
--- a/dependencymanager/test/src/test/java/org/apache/felix/dm/test/integration/api/AspectWithPropagationTest.java
+++ /dev/null
@@ -1,686 +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.felix.dm.test.integration.api;
-
-import java.util.Dictionary;
-import java.util.Enumeration;
-import java.util.HashMap;
-import java.util.HashSet;
-import java.util.Hashtable;
-import java.util.Map;
-import java.util.Random;
-import java.util.Set;
-
-import junit.framework.Assert;
-
-import org.apache.felix.dm.Component;
-import org.apache.felix.dm.DependencyManager;
-import org.apache.felix.dm.ServiceUtil;
-import org.apache.felix.dm.test.components.Ensure;
-import org.apache.felix.dm.test.integration.common.TestBase;
-import org.junit.Test;
-import org.junit.runner.RunWith;
-import org.ops4j.pax.exam.junit.PaxExam;
-import org.osgi.framework.ServiceReference;
-import org.osgi.framework.ServiceRegistration;
-
-/**
- * Test for aspects with service properties propagations.
- *
- * @author <a href="mailto:dev@felix.apache.org">Felix Project Team</a>
- */
-@RunWith(PaxExam.class)
-public class AspectWithPropagationTest extends TestBase {
- private final static int ASPECTS = 3;
- private final Set<Integer> _randoms = new HashSet<Integer>();
- private final Random _rnd = new Random();
- private static Ensure m_invokeStep;
- private static Ensure m_changeStep;
-
- /**
- * This test does the following:
- *
- * - Create S service
- * - Create some S Aspects
- * - Create a Client, depending on S (actually, on the top-level S aspect)
- * - Client has a "change" callack in order to track S service properties modifications.
- * - First, invoke Client.invoke(): all S aspects, and finally original S service must be invoked orderly.
- * - Modify S original service properties, and check if all aspects, and the client has been orderly called in their "change" callback.
- * - Modify the First lowest ranked aspect (rank=1), and check if all aspects, and client have been orderly called in their "change" callback.
- */
- @Test
- public void testAspectsWithPropagation() {
- System.out.println("----------- Running testAspectsWithPropagation ...");
- DependencyManager m = new DependencyManager(context);
- // helper class that ensures certain steps get executed in sequence
- m_invokeStep = new Ensure();
-
- // Create our original "S" service.
- Dictionary props = new Hashtable();
- props.put("foo", "bar");
- Component s = m.createComponent()
- .setImplementation(new SImpl())
- .setInterface(S.class.getName(), props);
-
- // Create an aspect aware client, depending on "S" service.
- Client clientImpl;
- Component client = m.createComponent()
- .setImplementation((clientImpl = new Client()))
- .add(m.createServiceDependency()
- .setService(S.class)
- .setRequired(true)
- .setDebug("client")
- .setCallbacks("add", "change", "remove", "swap"));
-
- // Create some "S" aspects
- Component[] aspects = new Component[ASPECTS];
- for (int rank = 1; rank <= ASPECTS; rank ++) {
- aspects[rank-1] = m.createAspectService(S.class, null, rank, "add", "change", "remove", "swap")
- .setImplementation(new A("A" + rank, rank));
- props = new Hashtable();
- props.put("a" + rank, "v" + rank);
- aspects[rank-1].setServiceProperties(props);
- }
-
- // Register client
- m.add(client);
-
- // Randomly register aspects and original service
- boolean originalServiceAdded = false;
- for (int i = 0; i < ASPECTS; i ++) {
- int index = getRandomAspect();
- m.add(aspects[index]);
- if (_rnd.nextBoolean()) {
- m.add(s);
- originalServiceAdded = true;
- }
- }
- if (! originalServiceAdded) {
- m.add(s);
- }
-
- // All set, check if client has inherited from top level aspect properties + original service properties
- Map check = new HashMap();
- check.put("foo", "bar");
- for (int i = 1; i < (ASPECTS - 1); i ++) {
- check.put("a" + i, null); // we must not inherit from lower ranks, only from the top-level aspect.
- }
- check.put("a" + ASPECTS, "v" + ASPECTS);
- checkServiceProperties(check, clientImpl.getServiceProperties());
-
- // Now invoke client, which orderly calls all aspects in the chain, and finally the original service "S".
- System.out.println("-------------------------- Invoking client.");
- clientImpl.invoke();
- m_invokeStep.waitForStep(ASPECTS+1, 5000);
-
- // Now, change original service "S" properties: this will orderly trigger "change" callbacks on aspects, and on client.
- System.out.println("-------------------------- Modifying original service properties.");
- m_changeStep = new Ensure();
- props = new Hashtable();
- props.put("foo", "barModified");
- s.setServiceProperties(props);
-
- // Check if aspects and client have been orderly called in their "changed" callback
- m_changeStep.waitForStep(ASPECTS+1, 5000);
-
- // Check if modified "foo" original service property has been propagated
- check = new HashMap();
- check.put("foo", "barModified");
- for (int i = 1; i < (ASPECTS - 1); i ++) {
- check.put("a" + i, null); // we must not inherit from lower ranks, only from the top-level aspect.
- }
- check.put("a" + ASPECTS, "v" + ASPECTS); // we only see top-level aspect service properties
- checkServiceProperties(check, clientImpl.getServiceProperties());
-
- // Now, change the top-level ranked aspect: it must propagate to all upper aspects, as well as to the client
- System.out.println("-------------------------- Modifying top-level aspect service properties.");
-
- m_changeStep = new Ensure();
- for (int i = 1; i <= ASPECTS; i ++) {
- m_changeStep.step(i); // only client has to be changed.
- }
- props = new Hashtable();
- props.put("a" + ASPECTS, "v" + ASPECTS + "-Modified");
- aspects[ASPECTS-1].setServiceProperties(props); // That triggers change callbacks for upper aspects (with rank >= 2)
- m_changeStep.waitForStep(ASPECTS+1, 5000); // check if client have been changed.
-
- // Check if top level aspect service properties have been propagated up to the client.
- check = new HashMap();
- check.put("foo", "barModified");
- for (int i = 1; i < (ASPECTS - 1); i ++) {
- check.put("a" + i, null); // we must not inherit from lower ranks, only from the top-level aspect.
- }
- check.put("a" + ASPECTS, "v" + ASPECTS + "-Modified");
- checkServiceProperties(check, clientImpl.getServiceProperties());
-
- // Clear all components.
- m_changeStep = null;
- m.clear();
- }
-
- /**
- * This test does the following:
- *
- * - Create S service
- * - Create some S Aspects without any callbacks (add/change/remove/swap)
- * - Create a Client, depending on S (actually, on the top-level S aspect)
- * - Client has a "change" callack in order to track S service properties modifications.
- * - First, invoke Client.invoke(): all S aspects, and finally original S service must be invoked orderly.
- * - Modify S original service properties, and check if the client has been called in its "change" callback.
- */
- @Test
- public void testAspectsWithPropagationAndNoCallbacks() {
- System.out.println("----------- Running testAspectsWithPropagation ...");
- DependencyManager m = new DependencyManager(context);
- // helper class that ensures certain steps get executed in sequence
- m_invokeStep = new Ensure();
-
- // Create our original "S" service.
- Dictionary props = new Hashtable();
- props.put("foo", "bar");
- Component s = m.createComponent()
- .setImplementation(new SImpl())
- .setInterface(S.class.getName(), props);
-
- // Create an aspect aware client, depending on "S" service.
- Client clientImpl;
- Component client = m.createComponent()
- .setImplementation((clientImpl = new Client()))
- .add(m.createServiceDependency()
- .setService(S.class)
- .setRequired(true)
- .setDebug("client")
- .setCallbacks("add", "change", "remove"));
-
- // Create some "S" aspects
- Component[] aspects = new Component[ASPECTS];
- for (int rank = 1; rank <= ASPECTS; rank ++) {
- aspects[rank-1] = m.createAspectService(S.class, null, rank)
- .setImplementation(new A("A" + rank, rank));
- props = new Hashtable();
- props.put("a" + rank, "v" + rank);
- aspects[rank-1].setServiceProperties(props);
- }
-
- // Register client
- m.add(client);
-
- // Randomly register aspects and original service
- boolean originalServiceAdded = false;
- for (int i = 0; i < ASPECTS; i ++) {
- int index = getRandomAspect();
- m.add(aspects[index]);
- if (_rnd.nextBoolean()) {
- m.add(s);
- originalServiceAdded = true;
- }
- }
- if (! originalServiceAdded) {
- m.add(s);
- }
-
- // All set, check if client has inherited from top level aspect properties + original service properties
- Map check = new HashMap();
- check.put("foo", "bar");
- for (int i = 1; i < (ASPECTS - 1); i ++) {
- check.put("a" + i, null); // we must not inherit from lower ranks, only from the top-level aspect.
- }
- check.put("a" + ASPECTS, "v" + ASPECTS);
- checkServiceProperties(check, clientImpl.getServiceProperties());
-
- // Now invoke client, which orderly calls all aspects in the chain, and finally the original service "S".
- System.out.println("-------------------------- Invoking client.");
- clientImpl.invoke();
- m_invokeStep.waitForStep(ASPECTS+1, 5000);
-
- // Now, change original service "S" properties: this will orderly trigger "change" callbacks on aspects, and on client.
- System.out.println("-------------------------- Modifying original service properties.");
- m_changeStep = new Ensure();
- for (int i = 1; i <= ASPECTS; i ++) {
- m_changeStep.step(i); // skip aspects, which have no "change" callbacks.
- }
- props = new Hashtable();
- props.put("foo", "barModified");
- s.setServiceProperties(props);
-
- // Check if aspects and client have been orderly called in their "changed" callback
- m_changeStep.waitForStep(ASPECTS+1, 5000);
-
- // Check if modified "foo" original service property has been propagated
- check = new HashMap();
- check.put("foo", "barModified");
- for (int i = 1; i < (ASPECTS - 1); i ++) {
- check.put("a" + i, null); // we must not inherit from lower ranks, only from the top-level aspect.
- }
- check.put("a" + ASPECTS, "v" + ASPECTS); // we only see top-level aspect service properties
- checkServiceProperties(check, clientImpl.getServiceProperties());
-
- // Clear all components.
- m_changeStep = null;
- m.clear();
- }
-
- /**
- * This test does the following:
- *
- * - Create S service
- * - Create some S Aspects
- * - Create S2 Adapter, which adapts S to S2
- * - Create Client2, which depends on S2. Client2 listens to S2 property change events.
- * - Now, invoke Client2.invoke(): all S aspects, and finally original S service must be invoked orderly.
- * - Modify S original service properties, and check if all aspects, S2 Adapter, and Client2 have been orderly called in their "change" callback.
- */
- @Test
- public void testAdapterWithAspectsAndPropagation() {
- System.out.println("----------- Running testAdapterWithAspectsAndPropagation ...");
-
- DependencyManager m = new DependencyManager(context);
- m_invokeStep = new Ensure();
-
- // Create our original "S" service.
- Dictionary props = new Hashtable();
- props.put("foo", "bar");
- Component s = m.createComponent()
- .setImplementation(new SImpl())
- .setInterface(S.class.getName(), props);
-
- // Create some "S" aspects
- Component[] aspects = new Component[ASPECTS];
- for (int rank = 1; rank <= ASPECTS; rank ++) {
- aspects[rank-1] = m.createAspectService(S.class, null, rank, "add", "change", "remove", "swap")
- .setImplementation(new A("A" + rank, rank));
- props = new Hashtable();
- props.put("a" + rank, "v" + rank);
- aspects[rank-1].setServiceProperties(props);
- }
-
- // Create S2 adapter (which adapts S1 to S2 interface)
- Component adapter = m.createAdapterService(S.class, null, "add", "change", "remove", "swap")
- .setInterface(S2.class.getName(), null)
- .setImplementation(new S2Impl());
-
- // Create Client2, which depends on "S2" service.
- Client2 client2Impl;
- Component client2 = m.createComponent()
- .setImplementation((client2Impl = new Client2()))
- .add(m.createServiceDependency()
- .setService(S2.class)
- .setRequired(true)
- .setDebug("client")
- .setCallbacks("add", "change", null));
-
- // Register client2
- m.add(client2);
-
- // Register S2 adapter
- m.add(adapter);
-
- // Randomly register aspects, original service
- boolean originalServiceAdded = false;
- for (int i = 0; i < ASPECTS; i ++) {
- int index = getRandomAspect();
- m.add(aspects[index]);
- if (_rnd.nextBoolean()) {
- m.add(s);
- originalServiceAdded = true;
- }
- }
- if (! originalServiceAdded) {
- m.add(s);
- }
-
- // Now invoke client2, which orderly calls all S1 aspects, then S1Impl, and finally S2 service
- System.out.println("-------------------------- Invoking client2.");
- client2Impl.invoke2();
- m_invokeStep.waitForStep(ASPECTS+2, 5000);
-
- // Now, change original service "S" properties: this will orderly trigger "change" callbacks on aspects, S2Impl, and Client2.
- System.out.println("-------------------------- Modifying original service properties.");
- m_changeStep = new Ensure();
- props = new Hashtable();
- props.put("foo", "barModified");
- s.setServiceProperties(props);
-
- // Check if aspects and Client2 have been orderly called in their "changed" callback
- m_changeStep.waitForStep(ASPECTS+2, 5000);
-
- // Check if modified "foo" original service property has been propagated to Client2
- Map check = new HashMap();
- check.put("foo", "barModified");
- for (int i = 1; i < (ASPECTS - 1); i ++) {
- check.put("a" + i, null); // we must not inherit from lower ranks, only from the top-level aspect.
- }
- check.put("a" + ASPECTS, "v" + ASPECTS);
- checkServiceProperties(check, client2Impl.getServiceProperties());
-
- // Clear all components.
- m_changeStep = null;
- m.clear();
- }
-
- /**
- * This test does the following:
- *
- * - Create S service
- * - Create some S Aspects without any callbacks (add/change/remove)
- * - Create S2 Adapter, which adapts S to S2 (but does not have any add/change/remove callbacks)
- * - Create Client2, which depends on S2. Client2 listens to S2 property change events.
- * - Now, invoke Client2.invoke(): all S aspects, and finally original S service must be invoked orderly.
- * - Modify S original service properties, and check if all aspects, S2 Adapter, and Client2 have been orderly called in their "change" callback.
- */
- @Test
- public void testAdapterWithAspectsAndPropagationNoCallbacks() {
- System.out.println("----------- Running testAdapterWithAspectsAndPropagationNoCallbacks ...");
-
- DependencyManager m = new DependencyManager(context);
- m_invokeStep = new Ensure();
-
- // Create our original "S" service.
- Dictionary props = new Hashtable();
- props.put("foo", "bar");
- Component s = m.createComponent()
- .setImplementation(new SImpl())
- .setInterface(S.class.getName(), props);
-
- // Create some "S" aspects
- Component[] aspects = new Component[ASPECTS];
- for (int rank = 1; rank <= ASPECTS; rank ++) {
- aspects[rank-1] = m.createAspectService(S.class, null, rank)
- .setImplementation(new A("A" + rank, rank));
- props = new Hashtable();
- props.put("a" + rank, "v" + rank);
- aspects[rank-1].setServiceProperties(props);
- }
-
- // Create S2 adapter (which adapts S1 to S2 interface)
- Component adapter = m.createAdapterService(S.class, null)
- .setInterface(S2.class.getName(), null)
- .setImplementation(new S2Impl());
-
- // Create Client2, which depends on "S2" service.
- Client2 client2Impl;
- Component client2 = m.createComponent()
- .setImplementation((client2Impl = new Client2()))
- .add(m.createServiceDependency()
- .setService(S2.class)
- .setRequired(true)
- .setDebug("client")
- .setCallbacks("add", "change", "remove"));
-
- // Register client2
- m.add(client2);
-
- // Register S2 adapter
- m.add(adapter);
-
- // Randomly register aspects, original service
- boolean originalServiceAdded = false;
- for (int i = 0; i < ASPECTS; i ++) {
- int index = getRandomAspect();
- m.add(aspects[index]);
- if (_rnd.nextBoolean()) {
- m.add(s);
- originalServiceAdded = true;
- }
- }
- if (! originalServiceAdded) {
- m.add(s);
- }
-
- // Now invoke client2, which orderly calls all S1 aspects, then S1Impl, and finally S2 service
- System.out.println("-------------------------- Invoking client2.");
- client2Impl.invoke2();
- m_invokeStep.waitForStep(ASPECTS+2, 5000);
-
- // Now, change original service "S" properties: this will orderly trigger "change" callbacks on aspects, S2Impl, and Client2.
- System.out.println("-------------------------- Modifying original service properties.");
- m_changeStep = new Ensure();
- for (int i = 1; i <= ASPECTS+1; i ++) {
- m_changeStep.step(i); // skip all aspects and the adapter
- }
- props = new Hashtable();
- props.put("foo", "barModified");
- s.setServiceProperties(props);
-
- // Check if Client2 has been called in its "changed" callback
- m_changeStep.waitForStep(ASPECTS+2, 5000);
-
- // Check if modified "foo" original service property has been propagated to Client2
- Map check = new HashMap();
- check.put("foo", "barModified");
- for (int i = 1; i < (ASPECTS - 1); i ++) {
- check.put("a" + i, null); // we must not inherit from lower ranks, only from the top-level aspect.
- }
- check.put("a" + ASPECTS, "v" + ASPECTS);
- checkServiceProperties(check, client2Impl.getServiceProperties());
-
- // Clear all components.
- m_changeStep = null;
- m.clear();
- }
-
- private void checkServiceProperties(Map<?, ?> check, Dictionary properties) {
- for (Object key : check.keySet()) {
- Object val = check.get(key);
- if (val == null) {
- Assert.assertNull(properties.get(key));
- } else {
- Assert.assertEquals(val, properties.get(key));
- }
- }
- }
-
- private int getRandomAspect() {
- int index = 0;
- do {
- index = _rnd.nextInt(ASPECTS);
- } while (_randoms.contains(new Integer(index)));
- _randoms.add(new Integer(index));
- return index;
- }
-
- // S Service
- public static interface S {
- public void invoke();
- }
-
- // S ServiceImpl
- static class SImpl implements S {
- public SImpl() {
- }
-
- public String toString() {
- return "S";
- }
-
- public void invoke() {
- m_invokeStep.step(ASPECTS+1);
- }
- }
-
- // S Aspect
- static class A implements S {
- private final String m_name;
- private volatile ServiceRegistration m_registration;
- private volatile S m_next;
- private final int m_rank;
-
- public A(String name, int rank) {
- m_name = name;
- m_rank = rank;
- }
-
- public String toString() {
- return m_name;
- }
-
- public void invoke() {
- int rank = ServiceUtil.getRanking(m_registration.getReference());
- m_invokeStep.step(ASPECTS - rank + 1);
- m_next.invoke();
- }
-
- public void add(ServiceReference ref, S s) {
- System.out.println("+++ A" + m_rank + ".add:" + s + "/" + ServiceUtil.toString(ref));
- m_next = s;
- }
-
- public void swap(ServiceReference oldSRef, S oldS, ServiceReference newSRef, S newS) {
- System.out.println("+++ A" + m_rank + ".swap: new=" + newS + ", props=" + ServiceUtil.toString(newSRef));
- Assert.assertTrue(m_next == oldS);
- m_next = newS;
- }
-
- public void change(ServiceReference props, S s) {
- System.out.println("+++ A" + m_rank + ".change: s=" + s + ", props=" + ServiceUtil.toString(props));
- if (m_changeStep != null) {
- int rank = ServiceUtil.getRanking(m_registration.getReference());
- m_changeStep.step(rank);
- }
- }
-
- public void remove(ServiceReference props, S s) {
- System.out.println("+++ A" + m_rank + ".remove: " + s + ", props=" + ServiceUtil.toString(props));
- }
- }
-
- // Aspect aware client, depending of "S" service aspects.
- static class Client {
- private volatile S m_s;
- private volatile ServiceReference m_sRef;
-
- public Client() {
- }
-
- public Dictionary getServiceProperties() {
- Dictionary props = new Hashtable();
- for (String key : m_sRef.getPropertyKeys()) {
- props.put(key, m_sRef.getProperty(key));
- }
- return props;
- }
-
- public void invoke() {
- m_s.invoke();
- }
-
- public String toString() {
- return "Client";
- }
-
- public void add(ServiceReference ref, S s) {
- System.out.println("+++ Client.add: " + s + "/" + ServiceUtil.toString(ref));
- m_s = s;
- m_sRef = ref;
- }
-
- public void swap(ServiceReference oldSRef, S oldS, ServiceReference newSRef, S newS) {
- System.out.println("+++ Client.swap: m_s = " + m_s + ", old=" + oldS + ", oldProps=" + ServiceUtil.toString(oldSRef) + ", new=" + newS + ", props=" + ServiceUtil.toString(newSRef));
- Assert.assertTrue(m_s == oldS);
- m_s = newS;
- m_sRef = newSRef;
- }
-
- public void change(ServiceReference properties, S s) {
- System.out.println("+++ Client.change: s=" + s + ", props=" + ServiceUtil.toString(properties));
- if (m_changeStep != null) {
- m_changeStep.step(ASPECTS+1);
- }
- }
-
- public void remove(ServiceReference props, S s) {
- System.out.println("+++ Client.remove: " + s + ", props=" + ServiceUtil.toString(props));
- }
- }
-
- // S2 Service
- public static interface S2 {
- public void invoke2();
- }
-
- // S2 impl, which adapts S1 interface to S2 interface
- static class S2Impl implements S2 {
- private volatile S m_s; // we shall see top-level aspect on S service
-
- public void add(ServiceReference ref, S s) {
- System.out.println("+++ S2Impl.add: " + s + "/" + ServiceUtil.toString(ref));
- m_s = s;
- }
-
- public void swap(ServiceReference oldSRef, S oldS, ServiceReference newSRef, S newS) {
- System.out.println("+++ S2Impl.swap: new=" + newS + ", props=" + ServiceUtil.toString(newSRef));
- m_s = newS;
- }
-
- public void change(ServiceReference properties, S s) {
- System.out.println("+++ S2Impl.change: s=" + s + ", props=" + ServiceUtil.toString(properties));
- if (m_changeStep != null) {
- m_changeStep.step(ASPECTS+1);
- }
- }
-
- public void remove(ServiceReference props, S s) {
- System.out.println("+++ S2Impl.remove: " + s + ", props=" + ServiceUtil.toString(props));
- }
-
- public void invoke2() {
- m_s.invoke();
- m_invokeStep.step(ASPECTS + 2); // All aspects, and S1Impl have been invoked
- }
-
- public String toString() {
- return "S2";
- }
- }
-
- // Client2 depending on S2.
- static class Client2 {
- private volatile S2 m_s2;
- private volatile ServiceReference m_s2Ref;
-
- public Dictionary getServiceProperties() {
- Dictionary props = new Hashtable();
- for (String key : m_s2Ref.getPropertyKeys()) {
- props.put(key, m_s2Ref.getProperty(key));
- }
- return props;
- }
-
- public void invoke2() {
- m_s2.invoke2();
- }
-
- public String toString() {
- return "Client2";
- }
-
- public void add(ServiceReference ref, S2 s2) {
- System.out.println("+++ Client2.add: " + s2 + "/" + ServiceUtil.toString(ref));
- m_s2 = s2;
- m_s2Ref = ref;
- }
-
- public void change(ServiceReference props, S2 s2) {
- System.out.println("+++ Client2.change: s2=" + s2 + ", props=" + ServiceUtil.toString(props));
- if (m_changeStep != null) {
- m_changeStep.step(ASPECTS + 2); // S1Impl, all aspects, and S2 adapters have been changed before us.
- }
- }
- }
-}
diff --git a/dependencymanager/test/src/test/java/org/apache/felix/dm/test/integration/api/BundleDependencyTest.java b/dependencymanager/test/src/test/java/org/apache/felix/dm/test/integration/api/BundleDependencyTest.java
deleted file mode 100644
index bf3c4ee..0000000
--- a/dependencymanager/test/src/test/java/org/apache/felix/dm/test/integration/api/BundleDependencyTest.java
+++ /dev/null
@@ -1,142 +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.felix.dm.test.integration.api;
-
-import junit.framework.Assert;
-
-import org.apache.felix.dm.Component;
-import org.apache.felix.dm.DependencyManager;
-import org.apache.felix.dm.test.components.Ensure;
-import org.apache.felix.dm.test.integration.common.TestBase;
-import org.junit.Test;
-import org.junit.runner.RunWith;
-import org.ops4j.pax.exam.junit.PaxExam;
-import org.osgi.framework.Bundle;
-
-@RunWith(PaxExam.class)
-public class BundleDependencyTest extends TestBase {
- @Test
- public void testBundleDependencies() {
- DependencyManager m = new DependencyManager(context);
- // create a service provider and consumer
- Consumer c = new Consumer();
- Component consumer = m.createComponent().setImplementation(c).add(m.createBundleDependency().setCallbacks("add", "remove"));
- // add the service consumer
- m.add(consumer);
- // check if at least one bundle was found
- c.check();
- // remove the consumer again
- m.remove(consumer);
- // check if all bundles were removed correctly
- c.doubleCheck();
-
- // helper class that ensures certain steps get executed in sequence
- Ensure e = new Ensure();
- Component consumerWithFilter = m.createComponent().setImplementation(new FilteredConsumer(e)).add(m.createBundleDependency().setFilter("(Bundle-SymbolicName=org.apache.felix.dependencymanager)").setCallbacks("add", "remove"));
- // add a consumer with a filter
- m.add(consumerWithFilter);
- e.step(2);
- // remove the consumer again
- m.remove(consumerWithFilter);
- e.step(4);
- }
-
- @Test
- public void testRequiredBundleDependency() {
- DependencyManager m = new DependencyManager(context);
- // create a service provider and consumer
- Consumer c = new Consumer();
-
- // helper class that ensures certain steps get executed in sequence
- Ensure e = new Ensure();
- Component consumerWithFilter = m.createComponent()
- .setImplementation(new FilteredConsumerRequired(e))
- .add(m.createBundleDependency()
- .setRequired(true)
- .setFilter("(Bundle-SymbolicName=org.apache.felix.dependencymanager)")
- .setCallbacks("add", "remove")
- );
- // add a consumer with a filter
- m.add(consumerWithFilter);
- e.waitForStep(1, 10000);
- // remove the consumer again
- m.remove(consumerWithFilter);
- e.waitForStep(2, 10000);
- }
-
- static class Consumer {
- private volatile int m_count = 0;
-
- public void add(Bundle b) {
- Assert.assertNotNull("bundle instance must not be null", b);
- m_count++;
- }
-
- public void check() {
- Assert.assertTrue("we should have found at least one bundle", m_count > 0);
- }
-
- public void remove(Bundle b) {
- m_count--;
- }
-
- public void doubleCheck() {
- Assert.assertEquals("all bundles we found should have been removed again", 0, m_count);
- }
- }
-
- static class FilteredConsumer {
- private final Ensure m_ensure;
-
- public FilteredConsumer(Ensure e) {
- m_ensure = e;
- }
-
- public void add(Bundle b) {
- m_ensure.step(1);
- }
-
- public void remove(Bundle b) {
- m_ensure.step(3);
- }
- }
-
- static class FilteredConsumerRequired {
- private final Ensure m_ensure;
-
- public FilteredConsumerRequired(Ensure e) {
- m_ensure = e;
- }
-
- public void add(Bundle b) {
- System.out.println("Bundle is " + b);
-// Assert.assertNotNull(b);
- if (b.getSymbolicName().equals("org.apache.felix.dependencymanager")) {
- m_ensure.step(1);
- }
- }
-
- public void remove(Bundle b) {
- Assert.assertNotNull(b);
- if (b.getSymbolicName().equals("org.apache.felix.dependencymanager")) {
- m_ensure.step(2);
- }
- }
- }
-}
diff --git a/dependencymanager/test/src/test/java/org/apache/felix/dm/test/integration/api/ComponentLifeCycleTest.java b/dependencymanager/test/src/test/java/org/apache/felix/dm/test/integration/api/ComponentLifeCycleTest.java
deleted file mode 100644
index ce129f9..0000000
--- a/dependencymanager/test/src/test/java/org/apache/felix/dm/test/integration/api/ComponentLifeCycleTest.java
+++ /dev/null
@@ -1,343 +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.felix.dm.test.integration.api;
-
-import junit.framework.Assert;
-
-import org.apache.felix.dm.Component;
-import org.apache.felix.dm.ComponentStateListener;
-import org.apache.felix.dm.DependencyManager;
-import org.apache.felix.dm.test.components.Ensure;
-import org.apache.felix.dm.test.integration.common.TestBase;
-import org.junit.Test;
-import org.junit.runner.RunWith;
-import org.ops4j.pax.exam.junit.PaxExam;
-import org.osgi.framework.ServiceReference;
-import org.osgi.framework.ServiceRegistration;
-
-@RunWith(PaxExam.class)
-public class ComponentLifeCycleTest extends TestBase {
- @Test
- public void testComponentLifeCycleCallbacks() {
- DependencyManager m = new DependencyManager(context);
- // helper class that ensures certain steps get executed in sequence
- Ensure e = new Ensure();
- // create a simple service component
- Component s = m.createComponent()
- .setImplementation(new ComponentInstance(e));
- // add it, and since it has no dependencies, it should be activated immediately
- m.add(s);
- // remove it so it gets destroyed
- m.remove(s);
- // ensure we executed all steps inside the component instance
- e.step(6);
- }
-
- static class ComponentInstance {
- private final Ensure m_ensure;
- public ComponentInstance(Ensure e) {
- m_ensure = e;
- m_ensure.step(1);
- }
- public void init() {
- m_ensure.step(2);
- }
- public void start() {
- m_ensure.step(3);
- }
- public void stop() {
- m_ensure.step(4);
- }
- public void destroy() {
- m_ensure.step(5);
- }
- }
-
- @Test
- public void testCustomComponentLifeCycleCallbacks() {
- DependencyManager m = new DependencyManager(context);
- // helper class that ensures certain steps get executed in sequence
- Ensure e = new Ensure();
- // create a simple service component
- Component s = m.createComponent()
- .setImplementation(new CustomComponentInstance(e))
- .setCallbacks("a", "b", "c", "d");
- // add it, and since it has no dependencies, it should be activated immediately
- m.add(s);
- // remove it so it gets destroyed
- m.remove(s);
- // ensure we executed all steps inside the component instance
- e.step(6);
- }
-
- static class CustomComponentInstance {
- private final Ensure m_ensure;
- public CustomComponentInstance(Ensure e) {
- m_ensure = e;
- m_ensure.step(1);
- }
- public void a() {
- m_ensure.step(2);
- }
- public void b() {
- m_ensure.step(3);
- }
- public void c() {
- m_ensure.step(4);
- }
- public void d() {
- m_ensure.step(5);
- }
- }
-
-
-
- @Test
- public void testComponentStateListingLifeCycle() {
- DependencyManager m = new DependencyManager(context);
- // helper class that ensures certain steps get executed in sequence
- Ensure e = new Ensure();
- // create a simple service component
- ComponentStateListeningInstance implementation = new ComponentStateListeningInstance(e);
- Component s = m.createComponent()
- .setInterface(MyInterface.class.getName(), null)
- .setImplementation(implementation);
- // add the state listener
- s.addStateListener(implementation);
- // add it, and since it has no dependencies, it should be activated immediately
- m.add(s);
- // remove it so it gets destroyed
- m.remove(s);
- // remove the state listener
- s.removeStateListener(implementation);
- // ensure we executed all steps inside the component instance
- e.step(10);
- }
-
- public static interface MyInterface {}
-
- static class ComponentStateListeningInstance implements MyInterface, ComponentStateListener {
- volatile ServiceRegistration m_registration;
- private final Ensure m_ensure;
-
- public ComponentStateListeningInstance(Ensure e) {
- m_ensure = e;
- m_ensure.step(1);
- }
-
- private void debug() {
- StackTraceElement[] stackTrace = Thread.currentThread().getStackTrace();
- System.out.println("AT: " + stackTrace[2].getClassName() + "." + stackTrace[2].getMethodName() + "():" + stackTrace[2].getLineNumber());
- }
-
- public void init(Component c) {
- debug();
- m_ensure.step(2);
- }
-
- public void start(Component c) {
- debug();
- m_ensure.step(4);
- }
- public void stop(Component c) {
- debug();
- m_ensure.step(7);
- }
-
- public void destroy(Component c) {
- debug();
- m_ensure.step(9);
- }
-
- public void starting(Component component) {
- debug();
- m_ensure.step(3);
- }
-
- public void started(Component component) {
- debug();
- m_ensure.step(5);
- ServiceReference reference = m_registration.getReference();
- Assert.assertNotNull("Service not yet registered.", reference);
- }
-
- public void stopping(Component component) {
- debug();
- m_ensure.step(6);
- }
-
- public void stopped(Component component) {
- debug();
- m_ensure.step(8);
- }
- }
-
-
-
- @Test
- public void testDynamicComponentStateListingLifeCycle() {
- DependencyManager m = new DependencyManager(context);
- // helper class that ensures certain steps get executed in sequence
- Ensure e = new Ensure();
- // create a simple service component
- Component s = m.createComponent()
- .setInterface(MyInterface.class.getName(), null)
- .setImplementation(new DynamicComponentStateListeningInstance(e));
- // add it, and since it has no dependencies, it should be activated immediately
- m.add(s);
- // remove it so it gets destroyed
- m.remove(s);
- // ensure we executed all steps inside the component instance
- e.step(10);
- }
-
- static class DynamicComponentStateListeningInstance implements MyInterface, ComponentStateListener {
- volatile ServiceRegistration m_registration;
- private final Ensure m_ensure;
-
- public DynamicComponentStateListeningInstance(Ensure e) {
- m_ensure = e;
- m_ensure.step(1);
- }
-
- private void debug() {
- StackTraceElement[] stackTrace = Thread.currentThread().getStackTrace();
- System.out.println("AT: " + stackTrace[2].getClassName() + "." + stackTrace[2].getMethodName() + "():" + stackTrace[2].getLineNumber());
- }
-
- public void init(Component c) {
- debug();
- m_ensure.step(2);
- c.addStateListener(this);
- }
-
- public void start(Component c) {
- debug();
- m_ensure.step(4);
- }
- public void stop(Component c) {
- debug();
- m_ensure.step(7);
- }
-
- public void destroy(Component c) {
- debug();
- m_ensure.step(9);
- c.removeStateListener(this);
- }
-
- public void starting(Component component) {
- debug();
- m_ensure.step(3);
- }
-
- public void started(Component component) {
- debug();
- m_ensure.step(5);
- ServiceReference reference = m_registration.getReference();
- Assert.assertNotNull("Service not yet registered.", reference);
- }
-
- public void stopping(Component component) {
- debug();
- m_ensure.step(6);
- }
-
- public void stopped(Component component) {
- debug();
- m_ensure.step(8);
- }
- }
-
-
- @Test
- public void testDynamicComponentStateListingLifeCycle2() {
- DependencyManager m = new DependencyManager(context);
- // helper class that ensures certain steps get executed in sequence
- Ensure e = new Ensure();
- // create a simple service component
- Component s = m.createComponent()
- .setInterface(MyInterface.class.getName(), null)
- .setImplementation(new DynamicComponentStateListeningInstance2(e));
- // add it, and since it has no dependencies, it should be activated immediately
- m.add(s);
- // remove it so it gets destroyed
- m.remove(s);
- // ensure we executed all steps inside the component instance
- e.step(10);
- }
-
- static class DynamicComponentStateListeningInstance2 implements MyInterface, ComponentStateListener {
- volatile ServiceRegistration m_registration;
- private final Ensure m_ensure;
-
- public DynamicComponentStateListeningInstance2(Ensure e) {
- m_ensure = e;
- m_ensure.step(1);
- }
-
- private void debug() {
- StackTraceElement[] stackTrace = Thread.currentThread().getStackTrace();
- System.out.println("AT: " + stackTrace[2].getClassName() + "." + stackTrace[2].getMethodName() + "():" + stackTrace[2].getLineNumber());
- }
-
- public void init(Component c) {
- debug();
- m_ensure.step(2);
- }
-
- public void start(Component c) {
- debug();
- m_ensure.step(3);
- c.addStateListener(this);
- }
- public void stop(Component c) {
- debug();
- m_ensure.step(7);
- c.removeStateListener(this);
- }
-
- public void destroy(Component c) {
- debug();
- m_ensure.step(9);
- }
-
- public void starting(Component component) {
- debug();
- m_ensure.step(4);
- }
-
- public void started(Component component) {
- debug();
- m_ensure.step(5);
- ServiceReference reference = m_registration.getReference();
- Assert.assertNotNull("Service not yet registered.", reference);
- }
-
- public void stopping(Component component) {
- debug();
- m_ensure.step(6);
- }
-
- public void stopped(Component component) {
- debug();
- m_ensure.step(8);
- }
- }
-}
diff --git a/dependencymanager/test/src/test/java/org/apache/felix/dm/test/integration/api/CompositionTest.java b/dependencymanager/test/src/test/java/org/apache/felix/dm/test/integration/api/CompositionTest.java
deleted file mode 100644
index 0ce920e..0000000
--- a/dependencymanager/test/src/test/java/org/apache/felix/dm/test/integration/api/CompositionTest.java
+++ /dev/null
@@ -1,108 +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.felix.dm.test.integration.api;
-
-import org.apache.felix.dm.Component;
-import org.apache.felix.dm.DependencyManager;
-import org.apache.felix.dm.test.components.Ensure;
-import org.apache.felix.dm.test.integration.common.TestBase;
-import org.junit.Test;
-import org.junit.runner.RunWith;
-import org.ops4j.pax.exam.junit.PaxExam;
-
-@RunWith(PaxExam.class)
-public class CompositionTest extends TestBase {
- @Test
- public void testComposition() {
- DependencyManager m = new DependencyManager(context);
- // helper class that ensures certain steps get executed in sequence
- Ensure e = new Ensure();
- // create a service provider and consumer
- Component sp = m.createComponent().setImplementation(new ServiceProvider(e)).setInterface(ServiceInterface.class.getName(), null);
- Component sc = m.createComponent().setImplementation(new ServiceConsumer(e))
- .setComposition("getComposition")
- .add(m.createServiceDependency().setService(ServiceInterface.class).setRequired(true).setCallbacks("add", null));
- m.add(sp);
- m.add(sc);
- // ensure we executed all steps inside the component instance
- e.step(6);
- m.clear();
- }
-
- static interface ServiceInterface {
- public void invoke();
- }
-
- static class ServiceProvider implements ServiceInterface {
- private final Ensure m_ensure;
- public ServiceProvider(Ensure e) {
- m_ensure = e;
- }
- public void invoke() {
- m_ensure.step(4);
- }
- }
-
- static class ServiceConsumer {
- private final Ensure m_ensure;
- private ServiceConsumerComposite m_composite;
- private ServiceInterface m_service;
-
- public ServiceConsumer(Ensure e) {
- m_ensure = e;
- m_composite = new ServiceConsumerComposite(m_ensure);
- }
-
- public Object[] getComposition() {
- return new Object[] { this, m_composite };
- }
-
- void add(ServiceInterface service) {
- m_ensure.step(1);
- m_service = service; // This method seems to not being called anymore
- }
-
- void start() {
- m_composite.invoke();
- m_ensure.step(5);
- }
- }
-
- static class ServiceConsumerComposite {
- ServiceInterface m_service;
- private Ensure m_ensure;
-
- ServiceConsumerComposite(Ensure ensure)
- {
- m_ensure = ensure;
- }
-
- void add(ServiceInterface service) {
-
- m_ensure.step(2);
- m_service = service;
- }
-
- void invoke()
- {
- m_ensure.step(3);
- m_service.invoke();
- }
- }
-}
diff --git a/dependencymanager/test/src/test/java/org/apache/felix/dm/test/integration/api/ConfigurationDependencyTest.java b/dependencymanager/test/src/test/java/org/apache/felix/dm/test/integration/api/ConfigurationDependencyTest.java
deleted file mode 100644
index 628ec47..0000000
--- a/dependencymanager/test/src/test/java/org/apache/felix/dm/test/integration/api/ConfigurationDependencyTest.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.felix.dm.test.integration.api;
-
-import java.io.IOException;
-import java.util.Dictionary;
-import java.util.Hashtable;
-import java.util.Properties;
-
-import junit.framework.Assert;
-
-import org.apache.felix.dm.Component;
-import org.apache.felix.dm.DependencyManager;
-import org.apache.felix.dm.test.components.Ensure;
-import org.apache.felix.dm.test.integration.common.TestBase;
-import org.junit.Test;
-import org.junit.runner.RunWith;
-import org.ops4j.pax.exam.junit.PaxExam;
-import org.osgi.service.cm.ConfigurationAdmin;
-import org.osgi.service.cm.ConfigurationException;
-import org.osgi.service.cm.ManagedService;
-
-
-@RunWith(PaxExam.class)
-public class ConfigurationDependencyTest extends TestBase {
- @Test
- public void testComponentWithRequiredConfigurationAndServicePropertyPropagation() {
- DependencyManager m = new DependencyManager(context);
- // helper class that ensures certain steps get executed in sequence
- Ensure e = new Ensure();
- // create a service provider and consumer
- Component s1 = m.createComponent().setImplementation(new ConfigurationConsumer(e)).setInterface(Runnable.class.getName(), null).add(m.createConfigurationDependency().setPid("test").setPropagate(true));
- Component s2 = m.createComponent().setImplementation(new ConfigurationCreator(e)).add(m.createServiceDependency().setService(ConfigurationAdmin.class).setRequired(true));
- Component s3 = m.createComponent().setImplementation(new ConfiguredServiceConsumer(e)).add(m.createServiceDependency().setService(Runnable.class, ("(testkey=testvalue)")).setRequired(true));
- m.add(s1);
- m.add(s2);
- m.add(s3);
- e.waitForStep(4, 15000);
- m.remove(s1);
- m.remove(s2);
- m.remove(s3);
- // ensure we executed all steps inside the component instance
- e.step(5);
- }
-
- @Test
- public void testFELIX2987() {
- // mimics testComponentWithRequiredConfigurationAndServicePropertyPropagation
- DependencyManager m = new DependencyManager(context);
- // helper class that ensures certain steps get executed in sequence
- Ensure e = new Ensure();
- // create a service provider and consumer
- Component s1 = m.createComponent().setImplementation(new ConfigurationConsumer2(e)).setInterface(Runnable.class.getName(), null).add(m.createConfigurationDependency().setPid("test").setPropagate(true));
- Component s2 = m.createComponent().setImplementation(new ConfigurationCreator(e)).add(m.createServiceDependency().setService(ConfigurationAdmin.class).setRequired(true));
- Component s3 = m.createComponent().setImplementation(new ConfiguredServiceConsumer(e)).add(m.createServiceDependency().setService(Runnable.class, ("(testkey=testvalue)")).setRequired(true));
- m.add(s1);
- m.add(s2);
- m.add(s3);
- e.waitForStep(4, 15000);
- m.remove(s1);
- m.remove(s2);
- m.remove(s3);
- // ensure we executed all steps inside the component instance
- e.step(5);
- }
-
-
- static class ConfigurationCreator {
- private volatile ConfigurationAdmin m_ca;
- private final Ensure m_ensure;
-
- public ConfigurationCreator(Ensure e) {
- m_ensure = e;
- }
-
- public void init() {
- try {
- m_ensure.step(1);
- org.osgi.service.cm.Configuration conf = m_ca.getConfiguration("test", null);
- Hashtable props = new Properties();
- props.put("testkey", "testvalue");
- conf.update(props);
- }
- catch (IOException e) {
- Assert.fail("Could not create configuration: " + e.getMessage());
- }
- }
- }
-
- static class ConfigurationConsumer2 extends ConfigurationConsumer {
- public ConfigurationConsumer2(Ensure e) {
- super(e);
- }
- }
-
- static class ConfigurationConsumer implements ManagedService, Runnable {
- private final Ensure m_ensure;
-
- public ConfigurationConsumer(Ensure e) {
- m_ensure = e;
- }
-
- public void updated(Dictionary props) throws ConfigurationException {
- if (props != null) {
- m_ensure.step(2);
- if (!"testvalue".equals(props.get("testkey"))) {
- Assert.fail("Could not find the configured property.");
- }
- }
- }
-
- public void run() {
- m_ensure.step(4);
- }
- }
-
- static class ConfiguredServiceConsumer {
- private final Ensure m_ensure;
- private volatile Runnable m_runnable;
-
- public ConfiguredServiceConsumer(Ensure e) {
- m_ensure = e;
- }
-
- public void init() {
- m_ensure.step(3);
- m_runnable.run();
- }
- }
-}
diff --git a/dependencymanager/test/src/test/java/org/apache/felix/dm/test/integration/api/CustomDependencyTest.java b/dependencymanager/test/src/test/java/org/apache/felix/dm/test/integration/api/CustomDependencyTest.java
deleted file mode 100644
index 8f54268..0000000
--- a/dependencymanager/test/src/test/java/org/apache/felix/dm/test/integration/api/CustomDependencyTest.java
+++ /dev/null
@@ -1,204 +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.felix.dm.test.integration.api;
-
-import java.util.ArrayList;
-import java.util.Dictionary;
-import java.util.List;
-
-import org.apache.felix.dm.Dependency;
-import org.apache.felix.dm.DependencyActivation;
-import org.apache.felix.dm.DependencyManager;
-import org.apache.felix.dm.DependencyService;
-import org.apache.felix.dm.test.components.Ensure;
-import org.apache.felix.dm.test.integration.common.TestBase;
-import org.junit.Test;
-import org.junit.runner.RunWith;
-import org.ops4j.pax.exam.junit.PaxExam;
-
-@RunWith(PaxExam.class)
-public class CustomDependencyTest extends TestBase {
- @Test
- public void testCustomDependency() {
- Ensure e = new Ensure();
- DependencyManager dm = new DependencyManager(context);
-
- // create a toggle that can be used to turn on/off our custom dependency
- Toggle toggle = new Toggle();
-
- // create a service that has our custom dependency as its only dependency
- dm.add(dm.createComponent()
- .setImplementation(new ServiceImpl(e))
- .add(new CustomDependency(toggle))
- );
-
- // make the toggle, therefore the dependency, therefore the service available
- toggle.setAvailable(true);
- e.waitForStep(1, 1000);
-
- // make the toggle unavailable again
- toggle.setAvailable(false);
- e.waitForStep(2, 1000);
- }
-
- /** A toggle implementation that invokes a callback on every change. */
- public static class Toggle {
- private boolean m_isAvailable;
- private Runnable m_runnable;
-
- public boolean isAvailable() {
- return m_isAvailable;
- }
- public void setAvailable(boolean isAvailable) {
- boolean changed = m_isAvailable != isAvailable;
- m_isAvailable = isAvailable;
- Runnable r = m_runnable;
- if (r != null && changed) {
- r.run();
- }
- }
- public void setRunnable(Runnable runnable) {
- m_runnable = runnable;
- }
- }
-
- /** Our custom dependency, which is less configurable than most, but that's okay for this test. */
- public static class CustomDependency implements Dependency, DependencyActivation, Runnable {
- private final Toggle m_toggle;
- private final List m_services = new ArrayList();
-
- public CustomDependency(Toggle toggle) {
- m_toggle = toggle;
- }
-
- public Dependency createCopy() {
- return new CustomDependency(m_toggle);
- }
-
- public Object getAutoConfigInstance() {
- return "" + m_toggle.isAvailable();
- }
-
- public String getAutoConfigName() {
- return null;
- }
-
- public Class getAutoConfigType() {
- return String.class;
- }
-
- public Dictionary getProperties() {
- return null;
- }
-
- public void run() {
- // invoked on every change
- if (m_toggle.isAvailable()) {
- Object[] services = m_services.toArray();
- for (int i = 0; i < services.length; i++) {
- DependencyService ds = (DependencyService) services[i];
- ds.dependencyAvailable(this);
- if (!isRequired()) {
- invokeAdded(ds);
- }
- }
- }
- else {
- Object[] services = m_services.toArray();
- for (int i = 0; i < services.length; i++) {
- DependencyService ds = (DependencyService) services[i];
- ds.dependencyUnavailable(this);
- if (!isRequired()) {
- invokeRemoved(ds);
- }
- }
- }
- }
-
- public void invokeAdded(DependencyService service) {
- invoke(service, "added");
- }
-
- public void invokeRemoved(DependencyService service) {
- invoke(service, "removed");
- }
-
- public void invoke(DependencyService dependencyService, String name) {
- if (name != null) {
- dependencyService.invokeCallbackMethod(getCallbackInstances(dependencyService), name,
- new Class[][] {{String.class}, {Object.class}, {}},
- new Object[][] {{getAutoConfigInstance()}, {getAutoConfigInstance()}, {}}
- );
- }
- }
-
- private synchronized Object[] getCallbackInstances(DependencyService dependencyService) {
- return dependencyService.getCompositionInstances();
- }
-
- public boolean isAutoConfig() {
- return true;
- }
-
- public boolean isAvailable() {
- return m_toggle.isAvailable();
- }
-
- public boolean isInstanceBound() {
- return false;
- }
-
- public boolean isPropagated() {
- return false;
- }
-
- public boolean isRequired() {
- return true;
- }
-
- public void start(DependencyService service) {
- synchronized (this) {
- m_services.add(service);
- }
- m_toggle.setRunnable(this);
- }
-
- public void stop(DependencyService service) {
- synchronized (this) {
- m_services.remove(service);
- }
- m_toggle.setRunnable(null);
- }
- }
-
- public static class ServiceImpl {
- private final Ensure m_e;
- public ServiceImpl(Ensure e) {
- m_e = e;
- }
- public void init() {
- System.out.println("init");
- m_e.step(1);
- }
- public void destroy() {
- System.out.println("destroy");
- m_e.step(2);
- }
- }
-}
diff --git a/dependencymanager/test/src/test/java/org/apache/felix/dm/test/integration/api/DynamicProxyAspectTest.java b/dependencymanager/test/src/test/java/org/apache/felix/dm/test/integration/api/DynamicProxyAspectTest.java
deleted file mode 100644
index 0024295..0000000
--- a/dependencymanager/test/src/test/java/org/apache/felix/dm/test/integration/api/DynamicProxyAspectTest.java
+++ /dev/null
@@ -1,200 +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.felix.dm.test.integration.api;
-
-import java.lang.reflect.InvocationHandler;
-import java.lang.reflect.Method;
-import java.lang.reflect.Proxy;
-
-import junit.framework.Assert;
-
-import org.apache.felix.dm.Component;
-import org.apache.felix.dm.DependencyManager;
-import org.apache.felix.dm.test.components.Ensure;
-import org.apache.felix.dm.test.integration.common.TestBase;
-import org.junit.Test;
-import org.junit.runner.RunWith;
-import org.ops4j.pax.exam.junit.PaxExam;
-
-@RunWith(PaxExam.class)
-public class DynamicProxyAspectTest extends TestBase {
- @Test
- public void testImplementGenericAspectWithDynamicProxy() {
- DependencyManager m = new DependencyManager(context);
- // helper class that ensures certain steps get executed in sequence
- Ensure e = new Ensure();
-
- // create two service providers, each providing a different service interface
- Component sp1 = m.createComponent().setImplementation(new ServiceProvider(e)).setInterface(ServiceInterface.class.getName(), null);
- Component sp2 = m.createComponent().setImplementation(new ServiceProvider2(e)).setInterface(ServiceInterface2.class.getName(), null);
-
- // create a dynamic proxy based aspect and hook it up to both services
- Component a1 = m.createAspectService(ServiceInterface.class, null, 10, "m_service")
- .setFactory(new Factory(e, ServiceInterface.class, "ServiceInterfaceProxy"), "create");
- Component a2 = m.createAspectService(ServiceInterface2.class, null, 10, "m_service")
- .setFactory(new Factory(e, ServiceInterface2.class, "ServiceInterfaceProxy2"), "create");
-
- // create a client that invokes a method on boths services, validate that it goes
- // through the proxy twice
- Component sc = m.createComponent()
- .setImplementation(new ServiceConsumer(e))
- .add(m.createServiceDependency().setService(ServiceInterface.class).setRequired(true))
- .add(m.createServiceDependency().setService(ServiceInterface2.class).setRequired(true))
- ;
-
- // register both producers, validate that both services are started
- m.add(sp1);
- e.waitForStep(1, 2000);
- m.add(sp2);
- e.waitForStep(2, 2000);
-
- // add both aspects, and validate that both instances have been created
- m.add(a1);
- m.add(a2);
- e.waitForStep(4, 4000);
-
- // add the client, which will automatically invoke both services
- m.add(sc);
-
- // wait until both services have been invoked
- e.waitForStep(6, 4000);
-
- // make sure the proxy has been called twice
- Assert.assertEquals("Proxy should have been invoked this many times.", 2, DynamicProxyHandler.getCounter());
-
- m.remove(sc);
- m.remove(a2);
- m.remove(a1);
- m.remove(sp2);
- m.remove(sp1);
- m.remove(a2);
- m.remove(a1);
-
- try {
- Thread.sleep(2000);
- }
- catch (InterruptedException e1) {
- // TODO Auto-generated catch block
- e1.printStackTrace();
- }
- }
-
- static interface ServiceInterface {
- public void invoke(Runnable run);
- }
-
- static interface ServiceInterface2 {
- public void invoke(Runnable run);
- }
-
- static class ServiceProvider implements ServiceInterface {
- private final Ensure m_ensure;
- public ServiceProvider(Ensure e) {
- m_ensure = e;
- }
- public void start() {
- m_ensure.step(1);
- }
- public void invoke(Runnable run) {
- run.run();
- }
- }
-
- static class ServiceProvider2 implements ServiceInterface2 {
- private final Ensure m_ensure;
- public ServiceProvider2(Ensure ensure) {
- m_ensure = ensure;
- }
- public void start() {
- m_ensure.step(2);
- }
- public void invoke(Runnable run) {
- run.run();
- }
- }
-
- static class ServiceConsumer implements Runnable {
- private volatile ServiceInterface m_service;
- private volatile ServiceInterface2 m_service2;
- private final Ensure m_ensure;
-
- public ServiceConsumer(Ensure e) {
- m_ensure = e;
- }
-
- public void init() {
- Thread t = new Thread(this);
- t.start();
- }
-
- public void run() {
- m_service.invoke(Ensure.createRunnableStep(m_ensure, 5));
- m_service2.invoke(Ensure.createRunnableStep(m_ensure, 6));
- }
- }
-
- static class DynamicProxyHandler implements InvocationHandler {
- public volatile Object m_service; // ISSUE, we cannot inject into "Object" at the moment
- private final String m_label;
- private static volatile int m_counter = 0;
-
- public DynamicProxyHandler(String label) {
- m_label = label;
- }
-
- public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
- System.out.println("IIIIIIINVOKE--------------------------" + method.getName());
- if (m_service == null) {
- Assert.fail("No service was injected into dynamic proxy handler " + m_label);
- }
- Method m = m_service.getClass().getMethod(method.getName(), method.getParameterTypes());
- if (m == null) {
- Assert.fail("No method " + method.getName() + " was found in instance " + m_service + " in dynamic proxy handler " + m_label);
- }
- if (method.getName().equals("invoke")) {
- // only count methods called 'invoke' because those are actually the ones
- // both interfaces implement (and the dynamic proxy might be invoked for
- // other methods, such as toString() as well)
- m_counter++;
- }
- return m.invoke(m_service, args);
- }
-
- public static int getCounter() {
- return m_counter;
- }
- }
-
- static class Factory {
- private final String m_label;
- private Class m_class;
- private final Ensure m_ensure;
-
- public Factory(Ensure ensure, Class clazz, String label) {
- m_ensure = ensure;
- m_class = clazz;
- m_label = label;
- }
-
- public Object create() {
- m_ensure.step();
- return Proxy.newProxyInstance(m_class.getClassLoader(), new Class[] { m_class }, new DynamicProxyHandler(m_label));
- }
- }
-}
diff --git a/dependencymanager/test/src/test/java/org/apache/felix/dm/test/integration/api/FELIX2078_ServiceDependencyTest.java b/dependencymanager/test/src/test/java/org/apache/felix/dm/test/integration/api/FELIX2078_ServiceDependencyTest.java
deleted file mode 100644
index 435a628..0000000
--- a/dependencymanager/test/src/test/java/org/apache/felix/dm/test/integration/api/FELIX2078_ServiceDependencyTest.java
+++ /dev/null
@@ -1,102 +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.felix.dm.test.integration.api;
-
-import org.apache.felix.dm.Component;
-import org.apache.felix.dm.DependencyManager;
-import org.apache.felix.dm.test.components.Ensure;
-import org.apache.felix.dm.test.integration.common.TestBase;
-import org.junit.Test;
-import org.junit.runner.RunWith;
-import org.ops4j.pax.exam.junit.PaxExam;
-
-@RunWith(PaxExam.class)
-public class FELIX2078_ServiceDependencyTest extends TestBase {
- @Test
- public void testRequiredServiceRegistrationAndConsumption() {
- DependencyManager m = new DependencyManager(context);
- // helper class that ensures certain steps get executed in sequence
- Ensure e = new Ensure();
- // create a service provider and consumer
- Component sp = m.createComponent().setImplementation(new ServiceProvider(e)).setInterface(ServiceInterface.class.getName(), null);
- Component sp2 = m.createComponent().setImplementation(new ServiceProvider(e)).setInterface(ServiceInterface.class.getName(), null);
- Component sc = m.createComponent().setImplementation(new ServiceConsumer(e)).add(m.createServiceDependency().setService(ServiceInterface.class).setRequired(true).setCallbacks("add", "remove"));
- m.add(sp);
- m.add(sp2);
- System.out.println("adding client");
- m.add(sc);
- System.out.println("waiting");
- // wait until both services have been added to our consumer
- e.waitForStep(2, 5000);
- m.remove(sc);
- m.remove(sp2);
- m.remove(sp);
- // ensure we executed all steps inside the component instance
- }
-
- @Test
- public void testOptionalServiceRegistrationAndConsumption() {
- DependencyManager m = new DependencyManager(context);
- // helper class that ensures certain steps get executed in sequence
- Ensure e = new Ensure();
- // create a service provider and consumer
- Component sp = m.createComponent().setImplementation(new ServiceProvider(e)).setInterface(ServiceInterface.class.getName(), null);
- Component sp2 = m.createComponent().setImplementation(new ServiceProvider(e)).setInterface(ServiceInterface.class.getName(), null);
- Component sc = m.createComponent().setImplementation(new ServiceConsumer(e)).add(m.createServiceDependency().setService(ServiceInterface.class).setRequired(false).setCallbacks("add", "remove"));
- m.add(sp);
- m.add(sp2);
- m.add(sc);
- // wait until both services have been added to our consumer
- e.waitForStep(2, 5000);
- m.remove(sc);
- m.remove(sp2);
- m.remove(sp);
- // ensure we executed all steps inside the component instance
- }
-
- static interface ServiceInterface {
- public void invoke();
- }
-
- static class ServiceProvider implements ServiceInterface {
- private final Ensure m_ensure;
- public ServiceProvider(Ensure e) {
- m_ensure = e;
- }
- public void invoke() {
- }
- }
-
- static class ServiceConsumer {
- private final Ensure m_ensure;
-
- public ServiceConsumer(Ensure e) {
- m_ensure = e;
- }
-
- public void add(ServiceInterface i) {
- System.out.println("add " + i);
- m_ensure.step();
- }
-
- public void remove(ServiceInterface i) {
-
- }
- }
-}
diff --git a/dependencymanager/test/src/test/java/org/apache/felix/dm/test/integration/api/FELIX2344_ExtraDependencyWithAutoConfigTest.java b/dependencymanager/test/src/test/java/org/apache/felix/dm/test/integration/api/FELIX2344_ExtraDependencyWithAutoConfigTest.java
deleted file mode 100644
index ed77679..0000000
--- a/dependencymanager/test/src/test/java/org/apache/felix/dm/test/integration/api/FELIX2344_ExtraDependencyWithAutoConfigTest.java
+++ /dev/null
@@ -1,107 +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.felix.dm.test.integration.api;
-
-import junit.framework.Assert;
-
-import org.apache.felix.dm.Component;
-import org.apache.felix.dm.DependencyManager;
-import org.apache.felix.dm.test.components.Ensure;
-import org.apache.felix.dm.test.integration.common.TestBase;
-import org.junit.Test;
-import org.junit.runner.RunWith;
-import org.ops4j.pax.exam.junit.PaxExam;
-
-@RunWith(PaxExam.class)
-public class FELIX2344_ExtraDependencyWithAutoConfigTest extends TestBase {
- /**
- * Test if an auto config extra dependency is injected in the expected order.
- */
- @Test
- public void testExtraDependencyWithAutoConfig() {
- DependencyManager m = new DependencyManager(context);
- // Helper class that ensures certain steps get executed in sequence
- Ensure e = new Ensure();
- // Create a service provider
- Component sp = m.createComponent().setInterface(ProviderInterface.class.getName(), null).setImplementation(ProviderImpl.class);
- // Create a service consumer with a required/autoconfig dependency over the service provider.
- Client c1;
- Component sc1 = m.createComponent().setImplementation((c1 = new Client(e, true, 1)));
- // Create a second service consumer with an optional/autoconfig dependency over the service provider.
- Client c2;
- Component sc2 = m.createComponent().setImplementation(c2 = new Client(e, false, 3));
-
- // Add service provider and consumer sc1 (required dependency over provider)
- m.add(sc1);
- m.add(sp);
- e.waitForStep(2, 5000);
-
- // Remove provider and consumer
- m.remove(sc1);
- m.remove(sp);
-
- // Add consumer sc2 (optional dependency over provider)
- m.add(sc2);
- e.waitForStep(4, 5000);
- }
-
- public interface ProviderInterface {
- public boolean action();
- }
-
- public static class ProviderImpl implements ProviderInterface {
- public boolean action()
- {
- return true;
- }
- }
-
- // This client is not using callbacks, but instead, it uses auto config.
- public static class Client {
- volatile ProviderInterface m_provider;
- private Ensure m_ensure;
- private final boolean m_required;
- private final int m_startStep;
-
- public Client(Ensure e, boolean required, int startStep) {
- m_ensure = e;
- m_required = required;
- m_startStep = startStep;
- }
-
- public void init(Component s) {
- DependencyManager dm = s.getDependencyManager();
- s.add(dm.createServiceDependency()
- .setInstanceBound(true)
- .setService(ProviderInterface.class)
- .setRequired(m_required)
- .setAutoConfig("m_provider"));
- m_ensure.step(m_startStep);
- }
-
- public void start() {
- // if required dependency: we must have been injected with the service provider
- // else, we have been injected with a null object.
- Assert.assertNotNull("provider has not been injected", m_provider);
- Assert.assertEquals(m_required, m_provider.action()); // action returns false if null object
- m_ensure.step();
- }
- }
-}
-
diff --git a/dependencymanager/test/src/test/java/org/apache/felix/dm/test/integration/api/FELIX2344_ExtraDependencyWithCallbackTest.java b/dependencymanager/test/src/test/java/org/apache/felix/dm/test/integration/api/FELIX2344_ExtraDependencyWithCallbackTest.java
deleted file mode 100644
index 0879784..0000000
--- a/dependencymanager/test/src/test/java/org/apache/felix/dm/test/integration/api/FELIX2344_ExtraDependencyWithCallbackTest.java
+++ /dev/null
@@ -1,118 +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.felix.dm.test.integration.api;
-
-import junit.framework.Assert;
-
-import org.apache.felix.dm.Component;
-import org.apache.felix.dm.DependencyManager;
-import org.apache.felix.dm.test.components.Ensure;
-import org.apache.felix.dm.test.integration.common.TestBase;
-import org.junit.Test;
-import org.junit.runner.RunWith;
-/**
- * Tests for extra dependencies which are declared from service's init method.
- */
-import org.ops4j.pax.exam.junit.PaxExam;
-
-@RunWith(PaxExam.class)
-public class FELIX2344_ExtraDependencyWithCallbackTest extends TestBase {
- /**
- * Checks if an extra optional/required dependency is properly injected into a consumer, using callbacks.
- */
- @Test
- public void testExtraDependencyWithCallback() {
- DependencyManager m = new DependencyManager(context);
- // helper class that ensures certain steps get executed in sequence
- Ensure e = new Ensure();
- // create a service consumer and provider
- Component sp = m.createComponent().setInterface(ProviderInterface.class.getName(), null).setImplementation(ProviderImpl.class);
- Component sc = m.createComponent().setImplementation(new Client(e, false, 1));
- Component sc2 = m.createComponent().setImplementation(new Client(e, true, 5));
- Component sc3 = m.createComponent().setImplementation(new Client(e, true, 9));
-
- // add the provider first, then add the consumer which initially will have no dependencies
- // but via the init() method an optional dependency with a callback method will be added
- m.add(sp);
- m.add(sc);
- // remove the consumer again
- m.remove(sc);
- e.waitForStep(4, 5000);
-
- // next up, add a second consumer, identical to the first, but with a required dependency
- // with a callback method which will be added in the init() method
- m.add(sc2);
- // remove the consumer again
- m.remove(sc2);
- e.waitForStep(8, 5000);
-
- // now remove the provider, add a third consumer, identical to the second, and after the
- // consumer has started, add the provider again
- m.remove(sp);
- m.add(sc3);
- m.add(sp);
- e.waitForStep(12, 5000);
- m.clear();
- }
-
- public interface ProviderInterface {
- }
-
- public static class ProviderImpl implements ProviderInterface {
- }
-
- public static class Client {
- ProviderInterface m_provider;
- private Ensure m_ensure;
- private final boolean m_required;
- private final int m_startStep;
-
- public Client(Ensure e, boolean required, int startStep) {
- m_ensure = e;
- m_required = required;
- m_startStep = startStep;
- }
-
- public void init(Component s) {
- DependencyManager dm = s.getDependencyManager();
- m_ensure.step(m_startStep);
- s.add(dm.createServiceDependency()
- .setInstanceBound(true)
- .setService(ProviderInterface.class)
- .setRequired(m_required)
- .setCallbacks("bind", null));
- }
-
- // called before start() for required dependency, or after start for optional dependency
- void bind(ProviderInterface provider) {
- System.out.println("bind");
- m_ensure.step(m_required ? m_startStep + 1 : m_startStep + 3);
- m_provider = provider;
- }
-
- public void start() {
- System.out.println("start");
- m_ensure.step(m_required ? m_startStep + 2: m_startStep + 1);
- if (m_required) {
- Assert.assertNotNull("Dependendency should have been injected", m_provider);
- }
- m_ensure.step(m_required ? m_startStep + 3: m_startStep + 2);
- }
- }
-}
diff --git a/dependencymanager/test/src/test/java/org/apache/felix/dm/test/integration/api/FELIX2348_ResourceAdapterTest.java b/dependencymanager/test/src/test/java/org/apache/felix/dm/test/integration/api/FELIX2348_ResourceAdapterTest.java
deleted file mode 100644
index 9e5ffd6..0000000
--- a/dependencymanager/test/src/test/java/org/apache/felix/dm/test/integration/api/FELIX2348_ResourceAdapterTest.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.felix.dm.test.integration.api;
-
-import java.io.FileNotFoundException;
-import java.io.IOException;
-import java.io.InputStream;
-import java.net.MalformedURLException;
-import java.net.URL;
-import java.util.HashMap;
-import java.util.Map;
-import java.util.Map.Entry;
-
-import junit.framework.Assert;
-
-import org.apache.felix.dm.DependencyManager;
-import org.apache.felix.dm.ResourceHandler;
-import org.apache.felix.dm.ResourceUtil;
-import org.apache.felix.dm.test.components.Ensure;
-import org.apache.felix.dm.test.integration.common.TestBase;
-import org.junit.Test;
-import org.junit.runner.RunWith;
-import org.ops4j.pax.exam.junit.PaxExam;
-import org.osgi.framework.BundleContext;
-import org.osgi.framework.Filter;
-import org.osgi.framework.InvalidSyntaxException;
-import org.osgi.framework.ServiceReference;
-
-@RunWith(PaxExam.class)
-public class FELIX2348_ResourceAdapterTest extends TestBase {
- @Test
- public void testBasicResourceAdapter() throws Exception {
- DependencyManager m = new DependencyManager(context);
- // helper class that ensures certain steps get executed in sequence
- Ensure e = new Ensure();
- m.add(m.createResourceAdapterService("(&(path=/path/to/*.txt)(host=localhost))", false, null, "changed")
- .setImplementation(new ResourceAdapter(e)));
- m.add(m.createComponent().setImplementation(new ResourceProvider(e)).add(m.createServiceDependency().setService(ResourceHandler.class).setCallbacks("add", "remove")));
- e.waitForStep(3, 5000);
- m.clear();
- }
-
- static class ResourceAdapter {
- protected URL m_resource; // injected by reflection.
- private Ensure m_ensure;
-
- ResourceAdapter(Ensure e) {
- m_ensure = e;
- }
-
- public void start() {
- m_ensure.step(1);
- Assert.assertNotNull("resource not injected", m_resource);
- m_ensure.step(2);
- try {
- InputStream in = m_resource.openStream();
- }
- catch (FileNotFoundException e) {
- m_ensure.step(3);
- }
- catch (IOException e) {
- Assert.fail("We should not have gotten this exception.");
- }
- }
- }
-
- static class ResourceProvider {
- private volatile BundleContext m_context;
- private final Ensure m_ensure;
- private final Map m_handlers = new HashMap();
- private URL[] m_resources;
-
- public ResourceProvider(Ensure ensure) throws MalformedURLException {
- m_ensure = ensure;
- m_resources = new URL[] {
- new URL("file://localhost/path/to/file1.txt")
- };
- }
-
- public void add(ServiceReference ref, ResourceHandler handler) {
- String filterString = (String) ref.getProperty("filter");
- Filter filter = null;
- if (filterString != null) {
- try {
- filter = m_context.createFilter(filterString);
- }
- catch (InvalidSyntaxException e) {
- Assert.fail("Could not create filter for resource handler: " + e);
- return;
- }
- }
- synchronized (m_handlers) {
- m_handlers.put(handler, filter);
- }
- for (int i = 0; i < m_resources.length; i++) {
- if (filter == null || filter.match(ResourceUtil.createProperties(m_resources[i]))) {
- handler.added(m_resources[i]);
- }
- }
- }
-
- public void remove(ServiceReference ref, ResourceHandler handler) {
- Filter filter;
- synchronized (m_handlers) {
- filter = (Filter) m_handlers.remove(handler);
- }
- removeResources(handler, filter);
- }
-
- private void removeResources(ResourceHandler handler, Filter filter) {
- for (int i = 0; i < m_resources.length; i++) {
- if (filter == null || filter.match(ResourceUtil.createProperties(m_resources[i]))) {
- handler.removed(m_resources[i]);
- }
- }
- }
-
- public void destroy() {
- Entry[] handlers;
- synchronized (m_handlers) {
- handlers = (Entry[]) m_handlers.entrySet().toArray(new Entry[m_handlers.size()]);
- }
- for (int i = 0; i < handlers.length; i++) {
- removeResources((ResourceHandler) handlers[i].getKey(), (Filter) handlers[i].getValue());
- }
-
- System.out.println("DESTROY..." + m_handlers.size());
- }
- }
-}
diff --git a/dependencymanager/test/src/test/java/org/apache/felix/dm/test/integration/api/FELIX2369_ExtraDependencyTest.java b/dependencymanager/test/src/test/java/org/apache/felix/dm/test/integration/api/FELIX2369_ExtraDependencyTest.java
deleted file mode 100644
index ca59474..0000000
--- a/dependencymanager/test/src/test/java/org/apache/felix/dm/test/integration/api/FELIX2369_ExtraDependencyTest.java
+++ /dev/null
@@ -1,117 +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.felix.dm.test.integration.api;
-
-import java.util.Arrays;
-import java.util.List;
-
-import junit.framework.Assert;
-
-import org.apache.felix.dm.Component;
-import org.apache.felix.dm.DependencyManager;
-import org.apache.felix.dm.ServiceDependency;
-import org.apache.felix.dm.test.components.Ensure;
-import org.apache.felix.dm.test.integration.common.TestBase;
-import org.junit.Test;
-import org.junit.runner.RunWith;
-/**
- * This testcase verify that a Service is not started if one of its extra required dependencies
- * is unavailable.
- */
-import org.ops4j.pax.exam.junit.PaxExam;
-
-@RunWith(PaxExam.class)
-public class FELIX2369_ExtraDependencyTest extends TestBase
-{
- @Test
- public void testExtraDependencies() {
- DependencyManager m = new DependencyManager(context);
- // helper class that ensures certain steps get executed in sequence
- Ensure e = new Ensure();
- // create a service consumer and provider
- Component sp1 = m.createComponent().setInterface(MyService1.class.getName(), null).setImplementation(new MyService1Impl());
- Component sc = m.createComponent().setImplementation(new MyClient(e, 1));
-
- // provides the MyService1 service (but not the MyService2, which is required by MyClient).
- m.add(sp1);
- // add MyClient (it should not be invoked in its start() method because MyService2 is not there
- m.add(sc);
- // remove MyClient (it should not be invoked in its stop() method because it should not be active, since MyService2 is not there.
- m.remove(sc);
- e.waitForStep(2, 5000);
- }
-
- public interface MyService1 {
- }
-
- public interface MyService2 {
- }
-
- public static class MyService1Impl implements MyService1 {
- }
-
- public static class MyService2Impl implements MyService2 {
- }
-
- // This client is not using callbacks, but instead, it uses auto config.
- public static class MyClient {
- MyService1 m_myService2; // required/unavailable
- private Ensure m_ensure;
- private final int m_startStep;
-
- public MyClient(Ensure e, int startStep) {
- m_ensure = e;
- m_startStep = startStep;
- }
-
- public void init(Component s) {
- DependencyManager dm = s.getDependencyManager();
- m_ensure.step(m_startStep);
- List extra = Arrays.asList(new ServiceDependency[] {
- dm.createServiceDependency() // this dependency is available at this point
- .setInstanceBound(true)
- .setService(MyService1.class)
- .setRequired(false)
- .setCallbacks("bind", null),
- dm.createServiceDependency() // not available: we should not be started
- .setInstanceBound(true)
- .setService(MyService2.class)
- .setRequired(true)
- .setAutoConfig("m_myService2")
- });
- s.add(extra);
- }
-
- public void start() {
- Assert.fail("start should not be called since MyService2 is unavailable");
- }
-
- void bind(MyService1 s1) { // optional/available
- System.out.println("bound MyService1");
- }
-
- public void stop() {
- Assert.fail("stop should not be called since we should not be active at this point");
- }
-
- public void destroy() {
- m_ensure.step(m_startStep+1);
- }
- }
-}
diff --git a/dependencymanager/test/src/test/java/org/apache/felix/dm/test/integration/api/FELIX2696_ConfigurationAndServiceDependencyTest.java b/dependencymanager/test/src/test/java/org/apache/felix/dm/test/integration/api/FELIX2696_ConfigurationAndServiceDependencyTest.java
deleted file mode 100644
index 241e40c..0000000
--- a/dependencymanager/test/src/test/java/org/apache/felix/dm/test/integration/api/FELIX2696_ConfigurationAndServiceDependencyTest.java
+++ /dev/null
@@ -1,119 +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.felix.dm.test.integration.api;
-
-import java.io.IOException;
-import java.util.Dictionary;
-import java.util.Hashtable;
-
-import junit.framework.Assert;
-
-import org.apache.felix.dm.Component;
-import org.apache.felix.dm.DependencyManager;
-import org.apache.felix.dm.test.components.Ensure;
-import org.apache.felix.dm.test.integration.common.TestBase;
-import org.junit.Test;
-import org.junit.runner.RunWith;
-import org.ops4j.pax.exam.junit.PaxExam;
-import org.osgi.service.cm.ConfigurationAdmin;
-import org.osgi.service.cm.ConfigurationException;
-import org.osgi.service.cm.ManagedService;
-
-
-@RunWith(PaxExam.class)
-public class FELIX2696_ConfigurationAndServiceDependencyTest extends TestBase {
- @Test
- public void testComponentWithRequiredConfigurationAndServicePropertyPropagation() {
- DependencyManager m = new DependencyManager(context);
- // helper class that ensures certain steps get executed in sequence
- Ensure e = new Ensure();
- // create a service provider and consumer
- Component s1 = m.createComponent()
- .setImplementation(new ConfigurationConsumer(e))
- .add(m.createServiceDependency().setService(ServiceInterface.class).setRequired(true))
- .add(m.createConfigurationDependency().setPid("test"));
- Component s2 = m.createComponent()
- .setImplementation(new ConfigurationCreator(e))
- .add(m.createServiceDependency().setService(ConfigurationAdmin.class).setRequired(true));
- Component s3 = m.createComponent()
- .setInterface(ServiceInterface.class.getName(), null)
- .setImplementation(DependentServiceProvider.class);
- m.add(s1);
- m.add(s2);
- m.add(s3);
- e.waitForStep(2, 5000);
- m.remove(s3);
- m.add(s3);
- // after adding the required dependency again, the issue in FELIX-2696 means that the
- // updated() method is not invoked for the new instance, and init() is, so our step
- // count will only go up to 3 (not 4) causing this test to fail
- e.waitForStep(4, 5000);
- m.remove(s3);
- m.remove(s2);
- m.remove(s1);
- }
-
- public static class ConfigurationCreator {
- private volatile ConfigurationAdmin m_ca;
- private final Ensure m_ensure;
-
- public ConfigurationCreator(Ensure e) {
- m_ensure = e;
- }
-
- public void init() {
- try {
- org.osgi.service.cm.Configuration conf = m_ca.getConfiguration("test", null);
- Hashtable props = new Hashtable();
- props.put("testkey", "testvalue");
- conf.update(props);
- }
- catch (IOException e) {
- Assert.fail("Could not create configuration: " + e.getMessage());
- }
- }
- }
-
- public static class ConfigurationConsumer implements ManagedService {
- private final Ensure m_ensure;
-
- public ConfigurationConsumer(Ensure e) {
- m_ensure = e;
- }
-
- public void updated(Dictionary props) throws ConfigurationException {
- if (props != null) {
- if (!"testvalue".equals(props.get("testkey"))) {
- Assert.fail("Could not find the configured property.");
- }
- m_ensure.step();
- }
- }
-
- public void init() {
- m_ensure.step();
- }
- }
-
- public static interface ServiceInterface {
- }
-
- public static class DependentServiceProvider implements ServiceInterface {
- }
-}
diff --git a/dependencymanager/test/src/test/java/org/apache/felix/dm/test/integration/api/FELIX2955_ShellCommandTest.java b/dependencymanager/test/src/test/java/org/apache/felix/dm/test/integration/api/FELIX2955_ShellCommandTest.java
deleted file mode 100644
index f0b3f31..0000000
--- a/dependencymanager/test/src/test/java/org/apache/felix/dm/test/integration/api/FELIX2955_ShellCommandTest.java
+++ /dev/null
@@ -1,153 +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.felix.dm.test.integration.api;
-
-import java.io.ByteArrayOutputStream;
-import java.io.PrintStream;
-import java.util.regex.Pattern;
-
-import junit.framework.Assert;
-
-import org.apache.felix.dm.Component;
-import org.apache.felix.dm.DependencyManager;
-import org.apache.felix.dm.test.components.Ensure;
-import org.apache.felix.dm.test.integration.common.TestBase;
-import org.apache.felix.service.command.CommandProcessor;
-import org.apache.felix.service.command.CommandSession;
-import org.junit.Test;
-import org.junit.runner.RunWith;
-import org.ops4j.pax.exam.junit.PaxExam;
-import org.osgi.framework.Bundle;
-
-@RunWith(PaxExam.class)
-public class FELIX2955_ShellCommandTest extends TestBase {
- private long m_testBundleId;
- private Bundle m_deploymentAdmin;
-
- @Test
- public void testShellCommands() throws Throwable {
- m_testBundleId = context.getBundle().getBundleId();
- for (Bundle b : context.getBundles()) {
- if (b.getSymbolicName().equals("org.apache.felix.deploymentadmin")) {
- m_deploymentAdmin = b;
- break;
- }
- }
- DependencyManager m = new DependencyManager(context);
- // helper class that ensures certain steps get executed in sequence
- Ensure e = new Ensure();
-
- Component shellClient = m.createComponent()
- .setImplementation(new ShellClient(e))
- .add(m.createServiceDependency()
- .setService(CommandProcessor.class)
- .setRequired(true)
- );
- m.add(shellClient);
- e.waitForStep(3, 5000);
- // now create a component with a missing dependency
- Component missing = m.createComponent()
- .setImplementation(new Object() { public String toString() { return "Object"; }})
- .add(m.createServiceDependency()
- .setService(Object.class)
- .setRequired(true)
- );
- m.add(missing);
- e.step(4);
- e.waitForStep(5, 5000);
- m.remove(missing);
- // now start/stop deploymentadmin, which we use here because it's a bundle that
- // publishes a service that uses the dependency manager (saving us from having to
- // create a bundle that does that on the fly)
- m_deploymentAdmin.start();
- m_deploymentAdmin.stop();
- e.step(6);
- e.waitForStep(7, 5000);
- e.ensure();
- m.remove(shellClient);
-
- }
-
- public class ShellClient {
- volatile CommandProcessor m_commandProcessor;
- private final Ensure m_ensure;
-
- public ShellClient(Ensure e) {
- m_ensure = e;
- }
-
- public void start() {
- Thread t = new Thread("Shell Client") {
- public void run() {
- m_ensure.step(1);
- execute("dm bid " + m_testBundleId,
- "\\[" + m_testBundleId + "\\] PAXEXAM-PROBE.*\n" +
- " \\[.*\\] ShellClient registered\n" +
- " org.apache.felix.service.command.CommandProcessor service required available\n",
- "");
-
- m_ensure.step(2);
- // see if there's anything that's not available
- execute("dm notavail bid " + m_testBundleId,
- "",
- "");
- m_ensure.step(3);
- // check again, now there should be something missing
- m_ensure.waitForStep(4, 5000);
- execute("dm notavail bid " + m_testBundleId,
- "\\[" + m_testBundleId + "\\] PAXEXAM-PROBE.*\n" +
- " \\[.*\\] Object unregistered\n" +
- " java.lang.Object service required unavailable\n",
- "");
- m_ensure.step(5);
- m_ensure.waitForStep(6, 5000);
- // this next step actually triggers the bug in FELIX-2955
- execute("dm notavail bid " + m_testBundleId,
- "",
- "");
- m_ensure.step(7);
- };
- };
- t.start();
- }
-
- @Override
- public String toString() {
- return "ShellClient";
- }
-
- public void execute(String command, String expectedOutput, String expectedError) {
- try {
- ByteArrayOutputStream output = new ByteArrayOutputStream();
- ByteArrayOutputStream error = new ByteArrayOutputStream();
- CommandSession session = m_commandProcessor.createSession(System.in, new PrintStream(output), new PrintStream(error));
- session.execute(command);
-
- String out = output.toString();
- Pattern p = Pattern.compile(expectedOutput, Pattern.MULTILINE);
-
- Assert.assertTrue("\n\nexpected:\n\n" + expectedOutput + "\nbut got:\n\n" + out, p.matcher(out).matches());
- Assert.assertEquals(expectedError, error.toString());
- }
- catch (Throwable throwable) {
- m_ensure.throwable(throwable);
- }
- }
- }
-}
diff --git a/dependencymanager/test/src/test/java/org/apache/felix/dm/test/integration/api/FELIX3008_FilterIndexStartupTest.java b/dependencymanager/test/src/test/java/org/apache/felix/dm/test/integration/api/FELIX3008_FilterIndexStartupTest.java
deleted file mode 100644
index 92f9c99..0000000
--- a/dependencymanager/test/src/test/java/org/apache/felix/dm/test/integration/api/FELIX3008_FilterIndexStartupTest.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.felix.dm.test.integration.api;
-//import static org.ops4j.pax.exam.CoreOptions.waitForFrameworkStartupFor;
-//import static org.ops4j.pax.exam.container.def.PaxRunnerOptions.vmOption;
-
-import junit.framework.Assert;
-
-import org.apache.felix.dm.Component;
-import org.apache.felix.dm.DependencyManager;
-import org.apache.felix.dm.test.components.Ensure;
-import org.apache.felix.dm.test.integration.common.TestBase;
-import org.junit.Test;
-import org.junit.runner.RunWith;
-import org.ops4j.pax.exam.junit.PaxExam;
-import org.osgi.framework.Bundle;
-
-@RunWith(PaxExam.class)
-public class FELIX3008_FilterIndexStartupTest extends TestBase {
- @Test
- public void testNormalStart() throws Exception {
- System.setProperty("org.apache.felix.dependencymanager.filterindex", "objectClass");
- DependencyManager m = new DependencyManager(context);
- // helper class that ensures certain steps get executed in sequence
- Ensure e = new Ensure();
- // create a provider
- Provider provider = new Provider();
- // activate it
- Component p = m.createComponent()
- .setInterface(Service.class.getName(), null)
- .setImplementation(provider);
-
- Consumer consumer = new Consumer(e);
- Component c = m.createComponent()
- .setImplementation(consumer)
- .add(m.createServiceDependency()
- .setService(Service.class)
- .setRequired(true)
- );
-
- m.add(p);
- m.add(c);
- e.waitForStep(1, 5000);
- m.remove(p);
- e.waitForStep(2, 5000);
- m.remove(c);
-
- Assert.assertEquals("Dependency manager bundle should be active.", Bundle.ACTIVE, context.getBundle().getState());
- }
-
- public static class Consumer {
- volatile Service m_service;
- private final Ensure m_ensure;
-
- public Consumer(Ensure e) {
- m_ensure = e;
- }
-
- public void start() {
- System.out.println("start");
- m_ensure.step(1);
- }
-
- public void stop() {
- System.out.println("stop");
- m_ensure.step(2);
- }
- }
-
- public static interface Service {
- }
-
- public static class Provider implements Service {
- }
-}
diff --git a/dependencymanager/test/src/test/java/org/apache/felix/dm/test/integration/api/FELIX3057_EmptyServiceReferenceArray.java b/dependencymanager/test/src/test/java/org/apache/felix/dm/test/integration/api/FELIX3057_EmptyServiceReferenceArray.java
deleted file mode 100644
index 21188e3..0000000
--- a/dependencymanager/test/src/test/java/org/apache/felix/dm/test/integration/api/FELIX3057_EmptyServiceReferenceArray.java
+++ /dev/null
@@ -1,55 +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.felix.dm.test.integration.api;
-//import static org.ops4j.pax.exam.CoreOptions.waitForFrameworkStartupFor;
-//import static org.ops4j.pax.exam.container.def.PaxRunnerOptions.vmOption;
-
-import junit.framework.Assert;
-
-import org.apache.felix.dm.DependencyManager;
-import org.apache.felix.dm.test.integration.common.TestBase;
-import org.junit.Test;
-import org.junit.runner.RunWith;
-import org.ops4j.pax.exam.junit.PaxExam;
-import org.osgi.framework.BundleContext;
-import org.osgi.framework.InvalidSyntaxException;
-
-@RunWith(PaxExam.class)
-public class FELIX3057_EmptyServiceReferenceArray extends TestBase {
- @Test
- public void testWithoutIndex() throws Exception {
- executeTest(context);
- }
-
- @Test
- public void testWithIndex() throws Exception {
- System.setProperty(DependencyManager.SERVICEREGISTRY_CACHE_INDICES, "objectClass");
- executeTest(context);
- }
-
- private void executeTest(BundleContext context) throws InvalidSyntaxException {
- DependencyManager m = new DependencyManager(context);
- Assert.assertNull("Looking up a non-existing service should return null.", m.getBundleContext().getServiceReferences(Service.class.getName(), "(objectClass=*)"));
- Assert.assertNull("Looking up a non-existing service should return null.", m.getBundleContext().getAllServiceReferences(Service.class.getName(), "(objectClass=*)"));
- Assert.assertNull("Looking up a non-existing service should return null.", m.getBundleContext().getServiceReference(Service.class.getName()));
- }
-
- /** Dummy interface for lookup. */
- public static interface Service {}
-}
diff --git a/dependencymanager/test/src/test/java/org/apache/felix/dm/test/integration/api/FELIX3186_AspectAdapterTest.java b/dependencymanager/test/src/test/java/org/apache/felix/dm/test/integration/api/FELIX3186_AspectAdapterTest.java
deleted file mode 100644
index 64fdf87..0000000
--- a/dependencymanager/test/src/test/java/org/apache/felix/dm/test/integration/api/FELIX3186_AspectAdapterTest.java
+++ /dev/null
@@ -1,152 +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.felix.dm.test.integration.api;
-
-import org.apache.felix.dm.Component;
-import org.apache.felix.dm.DependencyManager;
-import org.apache.felix.dm.test.components.Ensure;
-import org.apache.felix.dm.test.integration.common.TestBase;
-import org.junit.Test;
-import org.junit.runner.RunWith;
-import org.ops4j.pax.exam.junit.PaxExam;
-import org.osgi.framework.ServiceReference;
-
-/**
- * Scenario:
- *
- * A service consumer consumes an adapter service. The adapter service adapts a service provider.
- * An aspect is added to the service provider. This should not impact the service consumer.
- * Expected behavior is transparent replacement of the service the adapter adapts with the aspect service.
- *
- */
-@RunWith(PaxExam.class)
-public class FELIX3186_AspectAdapterTest extends TestBase {
- @Test
- public void testAdapterWithAspectMultipleTimes() throws Exception {
- // TODO this test is broken, it assumes that the order in which listeners are added to the BundleContext will also
- // be the order in which they're invoked (which from a spec point of view is not true)
-
-
- DependencyManager m = new DependencyManager(context);
- // helper class that ensures certain steps get executed in sequence
- Ensure e = new Ensure();
-
- // create a service provider
- Component provider = m.createComponent()
- .setImplementation(new ServiceProvider())
- .setInterface(OriginalService.class.getName(), null);
-
- // create a adapter on the provider
- Component adapter = m.createAdapterService(OriginalService.class, null)
- .setInterface(AdaptedService.class.getName(), null)
- .setImplementation(ServiceAdapter.class);
-
- // create a consumer for the adapted service
- Component consumer = m.createComponent()
- .setImplementation(new ServiceConsumer(e))
- .add(m.createServiceDependency()
- .setService(AdaptedService.class)
- .setCallbacks("add", "remove")
- .setRequired(true)
- );
-
- // create an aspect on the service provider
- Component aspect = m.createAspectService(OriginalService.class, null, 10, null)
- .setImplementation(ServiceAspect.class);
-
- // we first start the provider, the adapter and the consumer
- m.add(provider);
- m.add(adapter);
- m.add(consumer);
- // now wait until the callback method is invoked on the consumer
- e.waitForStep(1, 5000);
- // now we add an aspect on top of the provided service, which
- // should not affect our consumer at all
- m.add(aspect);
- m.remove(aspect);
- // now we remove the consumer, adapter and provider
- m.remove(consumer);
- m.remove(adapter);
- m.remove(provider);
- // that should have triggered step 2
- e.waitForStep(2, 5000);
- // make sure we don't have extra steps by explicitly going to step 3
- e.step(3);
- }
-
- static interface OriginalService {
- public void invoke();
- }
-
- static interface AdaptedService {
- public void invoke();
- }
-
- static class ServiceProvider implements OriginalService {
- public void invoke() {
- }
-
- @Override
- public String toString() {
- return "Provider";
- }
- }
-
- public static class ServiceAdapter implements AdaptedService {
- private volatile OriginalService m_originalService;
-
- public void invoke() {
- m_originalService.invoke();
- }
- @Override
- public String toString() {
- return "Adapter on " + m_originalService;
- }
- }
-
- public static class ServiceAspect implements OriginalService {
- volatile OriginalService m_service;
-
- public void invoke() {
- m_service.invoke();
- }
-
- @Override
- public String toString() {
- return "Aspect on " + m_service;
- }
- }
-
- public static class ServiceConsumer {
- Ensure m_ensure;
-
- public ServiceConsumer(Ensure e) {
- m_ensure = e;
- }
-
- public void add(ServiceReference ref, AdaptedService service) {
- m_ensure.step();
- }
- public void remove(ServiceReference ref, AdaptedService service) {
- m_ensure.step();
- }
- }
-}
-
-
diff --git a/dependencymanager/test/src/test/java/org/apache/felix/dm/test/integration/api/FELIX3337_UpdatedConfigurationDependencyWithPropagationTest.java b/dependencymanager/test/src/test/java/org/apache/felix/dm/test/integration/api/FELIX3337_UpdatedConfigurationDependencyWithPropagationTest.java
deleted file mode 100644
index f6c1bb4..0000000
--- a/dependencymanager/test/src/test/java/org/apache/felix/dm/test/integration/api/FELIX3337_UpdatedConfigurationDependencyWithPropagationTest.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.felix.dm.test.integration.api;
-
-import java.io.IOException;
-import java.util.Dictionary;
-import java.util.Hashtable;
-import java.util.Properties;
-
-import junit.framework.Assert;
-
-import org.apache.felix.dm.Component;
-import org.apache.felix.dm.DependencyManager;
-import org.apache.felix.dm.test.components.Ensure;
-import org.apache.felix.dm.test.integration.common.TestBase;
-import org.junit.Test;
-import org.junit.runner.RunWith;
-import org.ops4j.pax.exam.junit.PaxExam;
-import org.osgi.service.cm.ConfigurationAdmin;
-import org.osgi.service.cm.ConfigurationException;
-import org.osgi.service.cm.ManagedService;
-
-
-/**
- * This test validates the following scenario:
- * - Service S1 depends on a ConfigurationDependency with propagate = true
- * - Service S2 depends on S1 (and has access to the S1 configuration using the S1 service
- * properties (because the ConfigurationDependency is propagated)
- * - then the S1 PID is updated from ConfigAdmin
- * - S1 is then called in its updated callback
- * - S2 is called in its "change" callback.
- */
-@RunWith(PaxExam.class)
-public class FELIX3337_UpdatedConfigurationDependencyWithPropagationTest extends TestBase {
- /*
- * This Pojo creates the configuration pid "test".
- */
- static class ConfigurationCreator {
- private volatile ConfigurationAdmin m_ca;
- org.osgi.service.cm.Configuration m_conf;
-
- public void init() {
- try {
- m_conf = m_ca.getConfiguration("test", null);
- Hashtable props = new Properties();
- props.put("testkey", "testvalue");
- m_conf.update(props);
- }
- catch (IOException e) {
- Assert.fail("Could not create configuration: " + e.getMessage());
- }
- }
-
- public void update() {
- try {
- Hashtable props = new Properties();
- props.put("testkey", "testvalue");
- props.put("testkey2", "testvalue2");
- m_conf.update(props);
- } catch (IOException e) {
- Assert.fail("Could not update the configured property: " + e.toString());
- }
- }
- }
-
- static class S1 implements ManagedService {
- private Ensure m_ensure;
- private boolean m_initialized;
-
- public S1(Ensure e) {
- m_ensure = e;
- }
-
- public void updated(Dictionary props) throws ConfigurationException {
- if (! m_initialized) {
- m_ensure.step(1);
- m_initialized = true;
- } else {
- // we are updated
- m_ensure.step(3);
- }
- }
- }
-
- static class S2 {
- private final Ensure m_ensure;
-
- public S2(Ensure e) {
- m_ensure = e;
- }
-
- public void add(S1 s1) {
- m_ensure.step(2);
- }
-
- public void change(S1 runnable) {
- m_ensure.step(4);
- }
- }
-
- @Test
- public void testComponentWithRequiredUpdatedConfigurationAndServicePropertyPropagation() {
- DependencyManager m = new DependencyManager(context);
- // helper class that ensures certain steps get executed in sequence
- Ensure e = new Ensure();
- ConfigurationCreator confCreator = new ConfigurationCreator();
- Component s1 = m.createComponent()
- .setImplementation(new S1(e))
- .setInterface(S1.class.getName(), null)
- .add(m.createConfigurationDependency()
- .setPid("test")
- .setPropagate(true));
- Component s2 = m.createComponent()
- .setImplementation(new S2(e))
- .add(m.createServiceDependency()
- .setService(S1.class, ("(testkey=testvalue)"))
- .setRequired(true)
- .setCallbacks("add", "change", null));
- Component s3 = m.createComponent()
- .setImplementation(confCreator)
- .add(m.createServiceDependency()
- .setService(ConfigurationAdmin.class)
- .setRequired(true));
-
- m.add(s1);
- m.add(s2);
- m.add(s3);
- e.waitForStep(2, 15000);
- confCreator.update();
- e.waitForStep(4, 15000);
- m.remove(s1);
- m.remove(s2);
- m.remove(s3);
- }
-}
diff --git a/dependencymanager/test/src/test/java/org/apache/felix/dm/test/integration/api/FELIX4361_ConcurrentComponentListingTest.java b/dependencymanager/test/src/test/java/org/apache/felix/dm/test/integration/api/FELIX4361_ConcurrentComponentListingTest.java
deleted file mode 100644
index e93bda2..0000000
--- a/dependencymanager/test/src/test/java/org/apache/felix/dm/test/integration/api/FELIX4361_ConcurrentComponentListingTest.java
+++ /dev/null
@@ -1,108 +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.felix.dm.test.integration.api;
-
-import java.util.Iterator;
-import java.util.List;
-import java.util.concurrent.Callable;
-import java.util.concurrent.ExecutorService;
-import java.util.concurrent.Executors;
-import java.util.concurrent.TimeUnit;
-import java.util.concurrent.atomic.AtomicBoolean;
-import java.util.concurrent.atomic.AtomicInteger;
-
-import junit.framework.Assert;
-
-import org.apache.felix.dm.DependencyManager;
-import org.apache.felix.dm.test.integration.common.TestBase;
-import org.junit.Test;
-import org.junit.runner.RunWith;
-import org.ops4j.pax.exam.junit.PaxExam;
-
-/**
- * Test for FELIX-4361 The DependencyManager.getComponents method failed in a concurrent situation on iterating the
- * result of the method.
- */
-@RunWith(PaxExam.class)
-public class FELIX4361_ConcurrentComponentListingTest extends TestBase {
-
- @Test
- public void testConcurrentGetComponentsManipulation() {
- DependencyManager dm = new DependencyManager(context);
- dm.add(dm.createComponent().setImplementation(Object.class));
- Iterator iterator = dm.getComponents().iterator();
- dm.add(dm.createComponent().setImplementation(Object.class));
- iterator.next();
- }
-
- @Test
- public void testConcurrentGetComponentsMultipleThreads() {
- final DependencyManager m = new DependencyManager(context);
- final AtomicInteger errors = new AtomicInteger(0);
- final AtomicInteger componentsAdded = new AtomicInteger(0);
- final int max = 10000;
- final AtomicBoolean isRunning = new AtomicBoolean(true);
-
- ExecutorService executorService = Executors.newFixedThreadPool(Runtime.getRuntime().availableProcessors() + 1);
- Runnable readTask = new Runnable() {
- public void run() {
- while (isRunning.get()) {
- try {
- List components = m.getComponents();
- for (Object component : components) {
- // Just iterating the components should check for concurrent modifications
- }
- }
- catch (Exception ex) {
- errors.addAndGet(1);
- ex.printStackTrace();
- }
- }
- }
- };
-
- Callable<Boolean> modifyTask = new Callable<Boolean>() {
- public Boolean call() throws Exception {
- try {
- m.add(m.createComponent().setImplementation(Object.class));
- componentsAdded.addAndGet(1);
- return true;
- }
- catch (Exception ex) {
- return false;
- }
- }
- };
-
- executorService.submit(readTask);
- for (int i = 0; i < max; i++) {
- executorService.submit(modifyTask);
- }
- isRunning.set(false);
- executorService.shutdown();
-
- try {
- executorService.awaitTermination(30, TimeUnit.SECONDS);
- }
- catch (InterruptedException e) {
- }
- Assert.assertEquals(0, errors.get());
- Assert.assertEquals(max, componentsAdded.get());
- }
-}
diff --git a/dependencymanager/test/src/test/java/org/apache/felix/dm/test/integration/api/FactoryConfigurationAdapterTest.java b/dependencymanager/test/src/test/java/org/apache/felix/dm/test/integration/api/FactoryConfigurationAdapterTest.java
deleted file mode 100644
index 89dd853..0000000
--- a/dependencymanager/test/src/test/java/org/apache/felix/dm/test/integration/api/FactoryConfigurationAdapterTest.java
+++ /dev/null
@@ -1,226 +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.felix.dm.test.integration.api;
-
-import java.io.IOException;
-import java.util.Dictionary;
-import java.util.Hashtable;
-import java.util.Map;
-import java.util.Properties;
-
-import junit.framework.Assert;
-
-import org.apache.felix.dm.Component;
-import org.apache.felix.dm.DependencyManager;
-import org.apache.felix.dm.test.components.Ensure;
-import org.apache.felix.dm.test.integration.common.TestBase;
-import org.junit.Test;
-import org.junit.runner.RunWith;
-import org.ops4j.pax.exam.junit.PaxExam;
-import org.osgi.service.cm.ConfigurationAdmin;
-
-@RunWith(PaxExam.class)
-public class FactoryConfigurationAdapterTest extends TestBase
-{
- private static Ensure m_ensure;
-
- @Test
- public void testFactoryConfigurationAdapter() {
- DependencyManager m = new DependencyManager(context);
- // helper class that ensures certain steps get executed in sequence
- m_ensure = new Ensure();
-
- // Create a Configuration instance, which will create/update/remove a configuration for factoryPid "MyFactoryPid"
- ConfigurationCreator configurator = new ConfigurationCreator("MyFactoryPid", "key", "value1");
- Component s1 = m.createComponent()
- .setImplementation(configurator)
- .add(m.createServiceDependency()
- .setService(ConfigurationAdmin.class)
- .setRequired(true));
-
- // Create an Adapter that will be instantiated, once the configuration is created.
- // This Adapter provides an AdapterService, and depends on an AdapterExtraDependency service.
- Component s2 = m.createFactoryConfigurationAdapterService("MyFactoryPid", "updated", true /* propagate CM settings */)
- .setInterface(AdapterService.class.getName(), new Properties() {{ put("foo", "bar"); }})
- .setImplementation(Adapter.class);
-
- s2.add(m.createServiceDependency()
- .setService(AdapterExtraDependency.class)
- .setRequired(true)
- .setAutoConfig(true));
-
- // Create extra adapter service dependency upon which our adapter depends on.
- Component s3 = m.createComponent()
- .setImplementation(new AdapterExtraDependency())
- .setInterface(AdapterExtraDependency.class.getName(), null);
-
- // Create an AdapterService Consumer
- Component s4 = m.createComponent()
- .setImplementation(AdapterServiceConsumer.class)
- .add(m.createServiceDependency()
- .setService(AdapterService.class)
- .setRequired(true)
- .setCallbacks("bind", "change", "remove"));
-
- // Start services
- m.add(s1);
- m.add(s2);
- m.add(s3);
- m.add(s4);
-
- // Wait for step 8: the AdapterService consumer has been injected with the AdapterService, and has called the doService method.
- m_ensure.waitForStep(8, 10000);
-
- // Modify configuration.
- configurator.update("key", "value2");
-
- // Wait for step 13: the AdapterService has been updated, and the AdapterService consumer has seen the change
- m_ensure.waitForStep(13, 10000);
-
- // Remove the configuration
- m.remove(s1); // The stop method will remove the configuration
- m_ensure.waitForStep(16, 10000);
- m.clear();
- }
-
- public static class ConfigurationCreator {
- private volatile ConfigurationAdmin m_ca;
- private String m_key;
- private String m_value;
- private org.osgi.service.cm.Configuration m_conf;
- private String m_factoryPid;
-
- public ConfigurationCreator(String factoryPid, String key, String value) {
- m_factoryPid = factoryPid;
- m_key = key;
- m_value = value;
- }
-
- public void start() {
- try {
- m_ensure.step(1);
- m_conf = m_ca.createFactoryConfiguration(m_factoryPid, null);
- Hashtable props = new Hashtable();
- props.put(m_key, m_value);
- m_conf.update(props);
- }
- catch (IOException e) {
- Assert.fail("Could not create configuration: " + e.getMessage());
- }
- }
-
- public void update(String key, String val) {
- Hashtable props = new Hashtable();
- props.put(key, val);
- try {
- m_conf.update(props);
- }
- catch (IOException e) {
- Assert.fail("Could not update configuration: " + e.getMessage());
- }
- }
-
- public void stop() {
- try
- {
- m_conf.delete();
- }
- catch (IOException e)
- {
- Assert.fail("Could not remove configuration: " + e.toString());
- }
- }
- }
-
- public interface AdapterService {
- public void doService();
- }
-
- public static class AdapterExtraDependency {
- }
-
- public static class Adapter implements AdapterService {
- volatile AdapterExtraDependency m_extraDependency; // extra dependency.
- private int updateCount;
-
- void updated(Dictionary settings) {
- updateCount ++;
- if (updateCount == 1) {
- m_ensure.step(2);
- Assert.assertEquals(true, "value1".equals(settings.get("key")));
- m_ensure.step(3);
- } else if (updateCount == 2) {
- m_ensure.step(9);
- Assert.assertEquals(true, "value2".equals(settings.get("key")));
- m_ensure.step(10);
- } else {
- Assert.fail("wrong call to updated method: count=" + updateCount);
- }
- }
-
- public void doService() {
- m_ensure.step(8);
- }
-
- public void start() {
- m_ensure.step(4);
- Assert.assertNotNull(m_extraDependency);
- m_ensure.step(5);
- }
-
- public void stop() {
- m_ensure.step(16);
- }
- }
-
- public static class AdapterServiceConsumer {
- private AdapterService m_adapterService;
- private Map m_adapterServiceProperties;
-
- void bind(Map serviceProperties, AdapterService adapterService) {
- m_ensure.step(6);
- m_adapterService = adapterService;
- m_adapterServiceProperties = serviceProperties;
- }
-
- void change(Map serviceProperties, AdapterService adapterService) {
- m_ensure.step(11);
- Assert.assertEquals(true, "value2".equals(m_adapterServiceProperties.get("key")));
- m_ensure.step(12);
- Assert.assertEquals(true, "bar".equals(m_adapterServiceProperties.get("foo")));
- m_ensure.step(13);
- }
-
- public void start() {
- m_ensure.step(7);
- Assert.assertNotNull(m_adapterService);
- Assert.assertEquals(true, "value1".equals(m_adapterServiceProperties.get("key")));
- Assert.assertEquals(true, "bar".equals(m_adapterServiceProperties.get("foo")));
- m_adapterService.doService();
- }
-
- public void stop() {
- m_ensure.step(14);
- }
-
- void remove(AdapterService adapterService) {
- m_ensure.step(15);
- }
- }
-}
diff --git a/dependencymanager/test/src/test/java/org/apache/felix/dm/test/integration/api/FilterIndexResourceAdapterTest.java b/dependencymanager/test/src/test/java/org/apache/felix/dm/test/integration/api/FilterIndexResourceAdapterTest.java
deleted file mode 100644
index c97c686..0000000
--- a/dependencymanager/test/src/test/java/org/apache/felix/dm/test/integration/api/FilterIndexResourceAdapterTest.java
+++ /dev/null
@@ -1,179 +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.felix.dm.test.integration.api;
-//import static org.ops4j.pax.exam.CoreOptions.waitForFrameworkStartupFor;
-//import static org.ops4j.pax.exam.container.def.PaxRunnerOptions.vmOption;
-
-import java.io.FileNotFoundException;
-import java.io.IOException;
-import java.io.InputStream;
-import java.net.MalformedURLException;
-import java.net.URL;
-import java.util.HashMap;
-import java.util.Map;
-import java.util.Map.Entry;
-
-import junit.framework.Assert;
-
-import org.apache.felix.dm.DependencyManager;
-import org.apache.felix.dm.ResourceHandler;
-import org.apache.felix.dm.ResourceUtil;
-import org.apache.felix.dm.ServiceUtil;
-import org.apache.felix.dm.test.components.Ensure;
-import org.apache.felix.dm.test.integration.common.TestBase;
-import org.junit.Test;
-import org.junit.runner.RunWith;
-import org.ops4j.pax.exam.junit.PaxExam;
-import org.osgi.framework.BundleContext;
-import org.osgi.framework.Filter;
-import org.osgi.framework.InvalidSyntaxException;
-import org.osgi.framework.ServiceReference;
-
-@RunWith(PaxExam.class)
-public class FilterIndexResourceAdapterTest extends TestBase {
- @Test
- public void testBasicResourceAdapter() throws Exception {
- System.setProperty("org.apache.felix.dependencymanager.filterindex", "objectClass");
- DependencyManager m = new DependencyManager(context);
- // helper class that ensures certain steps get executed in sequence
- Ensure e = new Ensure();
- // create a resource provider
- ResourceProvider provider = new ResourceProvider(e);
- // activate it
- m.add(m.createComponent().setImplementation(provider).add(m.createServiceDependency().setService(ResourceHandler.class).setCallbacks("add", "remove")));
- // create a resource adapter for our single resource
- // note that we can provide an actual implementation instance here because there will be only one
- // adapter, normally you'd want to specify a Class here
- m.add(m.createResourceAdapterService("(&(path=/path/to/*.txt)(host=localhost))", false, null, "changed")
- .setImplementation(new ResourceAdapter(e)));
- // wait until the single resource is available
- e.waitForStep(3, 5000);
- // trigger a 'change' in our resource
- provider.change();
- // wait until the changed callback is invoked
- e.waitForStep(4, 5000);
- m.clear();
- }
-
- static class ResourceAdapter {
- protected URL m_resource; // injected by reflection.
- private Ensure m_ensure;
-
- ResourceAdapter(Ensure e) {
- m_ensure = e;
- }
-
- public void start() {
- m_ensure.step(1);
- Assert.assertNotNull("resource not injected", m_resource);
- m_ensure.step(2);
- try {
- InputStream in = m_resource.openStream();
- }
- catch (FileNotFoundException e) {
- m_ensure.step(3);
- }
- catch (IOException e) {
- Assert.fail("We should not have gotten this exception.");
- }
- }
-
- public void changed() {
- m_ensure.step(4);
- }
- }
-
- static class ResourceProvider {
- private volatile BundleContext m_context;
- private final Ensure m_ensure;
- private final Map m_handlers = new HashMap();
- private URL[] m_resources;
-
- public ResourceProvider(Ensure ensure) throws MalformedURLException {
- m_ensure = ensure;
- m_resources = new URL[] {
- new URL("file://localhost/path/to/file1.txt")
- };
- }
-
- public void change() {
- ResourceHandler[] handlers;
- synchronized (m_handlers) {
- handlers = (ResourceHandler[]) m_handlers.keySet().toArray(new ResourceHandler[m_handlers.size()]);
- }
- for (int i = 0; i < m_resources.length; i++) {
- for (int j = 0; j < handlers.length; j++) {
- ResourceHandler handler = handlers[j];
- handler.changed(m_resources[i]);
- }
- }
- }
-
- public void add(ServiceReference ref, ResourceHandler handler) {
- System.out.println("RP.add: " + ServiceUtil.toString(ref));
- String filterString = (String) ref.getProperty("filter");
- Filter filter = null;
- if (filterString != null) {
- try {
- filter = m_context.createFilter(filterString);
- }
- catch (InvalidSyntaxException e) {
- Assert.fail("Could not create filter for resource handler: " + e);
- return;
- }
- }
- synchronized (m_handlers) {
- m_handlers.put(handler, filter);
- }
- for (int i = 0; i < m_resources.length; i++) {
- if (filter == null || filter.match(ResourceUtil.createProperties(m_resources[i]))) {
- handler.added(m_resources[i]);
- }
- }
- }
-
- public void remove(ServiceReference ref, ResourceHandler handler) {
- Filter filter;
- synchronized (m_handlers) {
- filter = (Filter) m_handlers.remove(handler);
- }
- removeResources(handler, filter);
- }
-
- private void removeResources(ResourceHandler handler, Filter filter) {
- for (int i = 0; i < m_resources.length; i++) {
- if (filter == null || filter.match(ResourceUtil.createProperties(m_resources[i]))) {
- handler.removed(m_resources[i]);
- }
- }
- }
-
- public void destroy() {
- Entry[] handlers;
- synchronized (m_handlers) {
- handlers = (Entry[]) m_handlers.entrySet().toArray(new Entry[m_handlers.size()]);
- }
- for (int i = 0; i < handlers.length; i++) {
- removeResources((ResourceHandler) handlers[i].getKey(), (Filter) handlers[i].getValue());
- }
-
- System.out.println("DESTROY..." + m_handlers.size());
- }
- }
-}
diff --git a/dependencymanager/test/src/test/java/org/apache/felix/dm/test/integration/api/ModifiedBundleDependencyTest.java b/dependencymanager/test/src/test/java/org/apache/felix/dm/test/integration/api/ModifiedBundleDependencyTest.java
deleted file mode 100644
index 2edd8d8..0000000
--- a/dependencymanager/test/src/test/java/org/apache/felix/dm/test/integration/api/ModifiedBundleDependencyTest.java
+++ /dev/null
@@ -1,145 +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.felix.dm.test.integration.api;
-
-import junit.framework.Assert;
-
-import org.apache.felix.dm.Component;
-import org.apache.felix.dm.DependencyManager;
-import org.apache.felix.dm.test.components.Ensure;
-import org.apache.felix.dm.test.integration.common.TestBase;
-import org.junit.Test;
-import org.junit.runner.RunWith;
-import org.ops4j.pax.exam.junit.PaxExam;
-import org.osgi.framework.Bundle;
-import org.osgi.framework.BundleException;
-
-/**
- * Test for FELIX-4334 issue.
- *
- * Two components: A, B
- *
- * - A provided.
- * - B has a bundle dependency on the dependency manager shell bundle, which is currently stopped.
- * - B has an instance bound dependency on A.
- * - Now unregister A.
- * - As a result of that, B becomes unavailable and is unbound from A. But B is not destroyed, because A dependency
- * is "instance bound". So B is still bound to the bundle dependency.
- * - Now, someone starts the dependency manager shell bundle: B then shall be called in its "changed" callback.
- *
- * @author <a href="mailto:dev@felix.apache.org">Felix Project Team</a>
- */
-@RunWith(PaxExam.class)
-public class ModifiedBundleDependencyTest extends TestBase {
- public static interface A {
- }
-
- static class AImpl implements A {
- }
-
- public static interface B {
- }
-
- static class BImpl implements B {
- final Ensure m_e;
-
- BImpl(Ensure e) {
- m_e = e;
- }
-
- public void add(Bundle dmTest) {
- m_e.step(1);
- }
-
- void init(Component c) {
- m_e.step(2);
- DependencyManager dm = c.getDependencyManager();
- c.add(dm.createServiceDependency().setService(A.class).setRequired(true).setInstanceBound(true).setCallbacks("add", "remove"));
- }
-
- public void add(A a) {
- m_e.step(3);
- }
-
- public void start() {
- m_e.step(4);
- }
-
- public void stop() {
- m_e.step(5);
- }
-
- public void remove(A a) {
- m_e.step(6);
- }
-
- public void change(Bundle dmTest) { // called two times: one for STARTING, one for STARTED
- m_e.step();
- }
-
- public void destroy() {
- m_e.step(9);
- }
-
- public void remove(Bundle dmTest) {
- m_e.step(10);
- }
- }
-
- @Test
- public void testAdapterWithChangedInstanceBoundDependency() {
- DependencyManager m = new DependencyManager(context);
- Ensure e = new Ensure();
-
- Component a = m.createComponent()
- .setImplementation(new AImpl())
- .setInterface(A.class.getName(), null);
-
- Component b = m.createComponent()
- .setInterface(B.class.getName(), null)
- .setImplementation(new BImpl(e))
- .add(m.createBundleDependency()
- .setFilter("(Bundle-SymbolicName=org.apache.felix.dependencymanager.shell)")
- .setStateMask(Bundle.INSTALLED|Bundle.ACTIVE|Bundle.RESOLVED|Bundle.STARTING)
- .setRequired(true)
- .setCallbacks("add", "change", "remove"));
-
- Bundle dmtest = getBundle("org.apache.felix.dependencymanager.shell");
- try {
- dmtest.stop();
- } catch (BundleException e1) {
- Assert.fail("couold not find dependencymanager shell bundle");
- }
-
- m.add(a);
- m.add(b);
-
- e.waitForStep(4, 5000);
- m.remove(a); // B will loose A and will enter into "waiting for required (instantiated)" state.
- System.out.println("Starting dependency manager shell ...");
- try {
- dmtest.start();
- } catch (BundleException e1) {
- Assert.fail("could not start dependencymanager shell bundle");
- }
- e.waitForStep(7, 5000);
- m.remove(b);
- e.waitForStep(10, 5000);
- }
-}
diff --git a/dependencymanager/test/src/test/java/org/apache/felix/dm/test/integration/api/MultipleExtraDependenciesTest.java b/dependencymanager/test/src/test/java/org/apache/felix/dm/test/integration/api/MultipleExtraDependenciesTest.java
deleted file mode 100644
index 7868795..0000000
--- a/dependencymanager/test/src/test/java/org/apache/felix/dm/test/integration/api/MultipleExtraDependenciesTest.java
+++ /dev/null
@@ -1,220 +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.felix.dm.test.integration.api;
-
-import java.util.ArrayList;
-import java.util.Hashtable;
-import java.util.List;
-
-import org.apache.felix.dm.Component;
-import org.apache.felix.dm.DependencyManager;
-import org.apache.felix.dm.test.components.Ensure;
-import org.apache.felix.dm.test.integration.common.TestBase;
-import org.junit.Test;
-import org.junit.runner.RunWith;
-import org.ops4j.pax.exam.junit.PaxExam;
-
-@RunWith(PaxExam.class)
-public class MultipleExtraDependenciesTest extends TestBase {
- /**
- * Check that list of extra dependencies (defined from init method) are handled properly.
- * The extra dependencies are added using a List object (Component.add(List)).
- * A component c1 will define two extra dependencies over *available* c4/c5 services.
- */
- @Test
- public void testWithTwoAvailableExtraDependency() {
- DependencyManager m = new DependencyManager(context);
- // Helper class that ensures certain steps get executed in sequence
- Ensure e = new Ensure();
- Component c1 = m.createComponent()
- .setInterface(Service1.class.getName(), null)
- .setImplementation(new MyComponent1(e))
- .add(m.createServiceDependency()
- .setService(Service2.class)
- .setRequired(true)
- .setAutoConfig("m_service2"));
-
- Component c2 = m.createComponent()
- .setImplementation(new MyComponent2(e))
- .add(m.createServiceDependency()
- .setService(Service1.class)
- .setRequired(false)
- .setAutoConfig(false)
- .setCallbacks("added", null, null));
-
- Component c3 = m.createComponent()
- .setInterface(Service2.class.getName(), null)
- .setImplementation(Service2Impl.class);
-
- Hashtable h = new Hashtable();
- h.put("type", "xx");
- Component c4 = m.createComponent()
- .setInterface(Service3.class.getName(), h)
- .setImplementation(Service3Impl1.class);
-
- h = new Hashtable();
- h.put("type", "yy");
- Component c5 = m.createComponent()
- .setInterface(Service3.class.getName(), h)
- .setImplementation(Service3Impl2.class);
-
-
- System.out.println("\n+++ Adding c2 / MyComponent2");
- m.add(c2);
- System.out.println("\n+++ Adding c3 / Service2");
- m.add(c3);
- System.out.println("\n+++ Adding c4 / Service3(xx)");
- m.add(c4);
- System.out.println("\n+++ Adding c5 / Service3(yy)");
- m.add(c5);
- System.out.println("\n+++ Adding c1 / MyComponent1");
- // c1 have declared two extra dependency on Service3 (xx/yy).
- // both extra dependencies are available, so the c1 component should be started immediately.
- m.add(c1);
- e.waitForStep(3, 3000);
- m.clear();
- }
-
- /**
- * Check that list of extra dependencies (defined from init method) are handled properly.
- * The extra dependencies are added using a List object (Component.add(List)).
- * A component c1 will define two extra dependencies over c4/c5. At the point c1.init()
- * is adding the two extra dependencies from its init method, c4 is available, but not c5.
- * So, c1 is not yet activated.
- * Then c5 is added, and it triggers the c1 activation ...
- */
- @Test
- public void testWithOneAvailableExtraDependency() {
- DependencyManager m = new DependencyManager(context);
- // Helper class that ensures certain steps get executed in sequence
- Ensure e = new Ensure();
- Component c1 = m.createComponent()
- .setInterface(Service1.class.getName(), null)
- .setImplementation(new MyComponent1(e))
- .add(m.createServiceDependency()
- .setService(Service2.class)
- .setRequired(true)
- .setAutoConfig("m_service2"));
-
- Component c2 = m.createComponent()
- .setImplementation(new MyComponent2(e))
- .add(m.createServiceDependency()
- .setService(Service1.class)
- .setRequired(false)
- .setAutoConfig(false)
- .setCallbacks("added", null, null));
-
- Component c3 = m.createComponent()
- .setInterface(Service2.class.getName(), null)
- .setImplementation(Service2Impl.class);
-
- Hashtable h = new Hashtable();
- h.put("type", "xx");
- Component c4 = m.createComponent()
- .setInterface(Service3.class.getName(), h)
- .setImplementation(Service3Impl1.class);
-
- h = new Hashtable();
- h.put("type", "yy");
- Component c5 = m.createComponent()
- .setInterface(Service3.class.getName(), h)
- .setImplementation(Service3Impl2.class);
-
-
- System.out.println("\n+++ Adding c2 / MyComponent2");
- m.add(c2);
- System.out.println("\n+++ Adding c3 / Service2");
- m.add(c3);
- System.out.println("\n+++ Adding c4 / Service3(xx)");
- m.add(c4);
- System.out.println("\n+++ Adding c1 / MyComponent1");
- m.add(c1);
-
- // c1 have declared two extra dependency on Service3 (xx/yy).
- // So, because we have not yet added c5 (yy), c1 should not be started currently.
- // But, now, we'll add c5 (Service3/yy) and c1 should then be started ...
- System.out.println("\n+++ Adding c5 / Service3(yy)");
- m.add(c5);
- e.waitForStep(3, 3000);
- m.clear();
- }
-
-
- public interface Service1 {}
- public interface Service2 {}
- public interface Service3 {}
-
- public static class Service2Impl implements Service2 {}
- public static class Service3Impl1 implements Service3 {}
- public static class Service3Impl2 implements Service3 {}
-
- public static class MyComponent1 implements Service1 {
- Service1 m_service2;
- Service2 m_service3_xx;
- Service2 m_service3_yy;
- Ensure m_ensure;
-
- public MyComponent1(Ensure e) {
- m_ensure = e;
- }
-
- void init(Component c) {
- m_ensure.step(1);
- DependencyManager dm = c.getDependencyManager();
- List l = new ArrayList();
- // Service3/xx currently available
- l.add(dm.createServiceDependency()
- .setInstanceBound(true)
- .setService(Service3.class, "(type=xx)")
- .setRequired(true)
- .setAutoConfig("m_service3_xx"));
-
- // Service3/yy not yet available
- l.add(dm.createServiceDependency()
- .setInstanceBound(true)
- .setService(Service3.class, "(type=yy)")
- .setRequired(true)
- .setAutoConfig("m_service3_yy"));
- c.add(l);
- }
-
- void start() {
- System.out.println("MyComponent1.start");
- m_ensure.step(2);
- }
- }
-
- public static class MyComponent2 {
- Service1 m_service1;
- Ensure m_ensure;
-
- public MyComponent2(Ensure e) {
- m_ensure = e;
- }
-
- void added(Service1 s1) {
- System.out.println("MyComponent2.bind(" + s1 + ")");
- m_ensure.step(3);
- }
-
- void start() {
- System.out.println("MyComponent2.start");
- }
- }
-}
diff --git a/dependencymanager/test/src/test/java/org/apache/felix/dm/test/integration/api/MultipleExtraDependencyTest.java b/dependencymanager/test/src/test/java/org/apache/felix/dm/test/integration/api/MultipleExtraDependencyTest.java
deleted file mode 100644
index 2ff18b0..0000000
--- a/dependencymanager/test/src/test/java/org/apache/felix/dm/test/integration/api/MultipleExtraDependencyTest.java
+++ /dev/null
@@ -1,229 +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.felix.dm.test.integration.api;
-
-import java.util.Hashtable;
-
-import org.apache.felix.dm.Component;
-import org.apache.felix.dm.DependencyManager;
-import org.apache.felix.dm.test.components.Ensure;
-import org.apache.felix.dm.test.integration.common.TestBase;
-import org.junit.Test;
-import org.junit.runner.RunWith;
-/**
- * Test which validates multi-dependencies combination.
- */
-import org.ops4j.pax.exam.junit.PaxExam;
-
-@RunWith(PaxExam.class)
-public class MultipleExtraDependencyTest extends TestBase {
- @Test
- public void testMultipleExtraDependencies()
- {
- DependencyManager m = new DependencyManager(context);
- Ensure e = new Ensure();
-
- Component sp2 = m.createComponent()
- .setImplementation(ServiceProvider2.class).setInterface(ServiceProvider2.class.getName(), null)
- .add(m.createServiceDependency()
- .setService(Runnable.class, "(foo=bar)")
- .setRequired(false)
- .setAutoConfig("m_runnable"))
- .add(m.createServiceDependency()
- .setService(Sequencer.class)
- .setRequired(true)
- .setCallbacks("bind", null))
- .setCallbacks(null, "start", "stop", null)
- .setComposition("getComposition");
-
- Component sp = m.createComponent()
- .setImplementation(ServiceProvider.class)
- .setInterface(ServiceInterface.class.getName(),
- new Hashtable() {{ put("foo", "bar"); }})
- .add(m.createServiceDependency()
- .setService(Sequencer.class)
- .setRequired(true)
- .setAutoConfig("m_sequencer"))
- .add(m.createServiceDependency()
- .setService(ServiceProvider2.class)
- .setRequired(true)
- .setCallbacks("bind", "unbind"))
- .setCallbacks(null, "start", "stop", null);
-
- Component sc = m.createComponent()
- .setImplementation(ServiceConsumer.class)
- .add(m.createServiceDependency()
- .setService(Sequencer.class)
- .setRequired(true)
- .setAutoConfig("m_sequencer"))
- .add(m.createServiceDependency()
- .setService(ServiceInterface.class, "(foo=bar)")
- .setRequired(true)
- .setAutoConfig("m_service"))
- .setCallbacks(null, "start", "stop", null);
-
- // Provide the Sequencer service to the MultipleAnnotationsTest class.
- Component sequencer =
- m.createComponent().setImplementation(new SequencerImpl(e))
- .setInterface(Sequencer.class.getName(), null);
- m.add(sp2);
- m.add(sp);
- m.add(sc);
- m.add(sequencer);
-
- // Check if the test.annotation components have been initialized orderly
- e.waitForStep(7, 10000);
-
- // Stop the test.annotation bundle
- m.remove(sequencer);
- m.remove(sp);
- m.remove(sp2);
- m.remove(sc);
-
- // And check if the test.annotation bundle has been deactivated orderly
- e.waitForStep(11, 10000);
- }
-
- public interface Sequencer
- {
- void step();
- void step(int step);
- void waitForStep(int step, int timeout);
- }
-
- public static class SequencerImpl implements Sequencer {
- Ensure m_ensure;
-
- public SequencerImpl(Ensure e)
- {
- m_ensure = e;
- }
-
- public void step()
- {
- m_ensure.step();
- }
-
- public void step(int step)
- {
- m_ensure.step(step);
- }
-
- public void waitForStep(int step, int timeout)
- {
- m_ensure.waitForStep(step, timeout);
- }
- }
-
- public interface ServiceInterface
- {
- public void doService();
- }
-
- public static class ServiceConsumer
- {
- volatile Sequencer m_sequencer;
- volatile ServiceInterface m_service;
-
- void start()
- {
- m_sequencer.step(6);
- m_service.doService();
- }
-
- void stop()
- {
- m_sequencer.step(8);
- }
- }
-
- public static class ServiceProvider implements ServiceInterface
- {
- Sequencer m_sequencer;
- ServiceProvider2 m_serviceProvider2;
-
- void bind(ServiceProvider2 provider2)
- {
- m_serviceProvider2 = provider2;
- }
-
- void start()
- {
- m_serviceProvider2.step(4);
- m_sequencer.step(5);
- }
-
- void stop()
- {
- m_sequencer.step(9);
- }
-
- void unbind(ServiceProvider2 provider2)
- {
- m_sequencer.step(10);
- }
-
- public void doService()
- {
- m_sequencer.step(7);
- }
- }
-
- public static class ServiceProvider2
- {
- Composite m_composite = new Composite();
- Sequencer m_sequencer;
- Runnable m_runnable;
-
- void bind(Sequencer seq)
- {
- m_sequencer = seq;
- m_sequencer.step(1);
- }
-
- void start()
- {
- m_sequencer.step(3);
- m_runnable.run(); // NullObject
- }
-
- public void step(int step) // called by ServiceProvider.start() method
- {
- m_sequencer.step(step);
- }
-
- void stop()
- {
- m_sequencer.step(11);
- }
-
- Object[] getComposition()
- {
- return new Object[] { this, m_composite };
- }
- }
-
- public static class Composite
- {
- void bind(Sequencer seq)
- {
- seq.step(2);
- }
- }
-}
diff --git a/dependencymanager/test/src/test/java/org/apache/felix/dm/test/integration/api/MultipleExtraDependencyTest2.java b/dependencymanager/test/src/test/java/org/apache/felix/dm/test/integration/api/MultipleExtraDependencyTest2.java
deleted file mode 100644
index ff12601..0000000
--- a/dependencymanager/test/src/test/java/org/apache/felix/dm/test/integration/api/MultipleExtraDependencyTest2.java
+++ /dev/null
@@ -1,272 +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.felix.dm.test.integration.api;
-
-import java.util.ArrayList;
-import java.util.Hashtable;
-import java.util.List;
-
-import org.apache.felix.dm.Component;
-import org.apache.felix.dm.DependencyManager;
-import org.apache.felix.dm.ServiceDependency;
-import org.apache.felix.dm.test.components.Ensure;
-import org.apache.felix.dm.test.integration.common.TestBase;
-import org.junit.Test;
-import org.junit.runner.RunWith;
-import org.ops4j.pax.exam.junit.PaxExam;
-
-
-/**
- * Tests for extra dependencies which are declared from service's init method.
- */
-@RunWith(PaxExam.class)
-public class MultipleExtraDependencyTest2 extends TestBase {
- @Test
- public void testMultipleExtraDependencies()
- {
- DependencyManager m = new DependencyManager(context);
- Ensure e = new Ensure();
-
- Component sp2 = m.createComponent()
- .setImplementation(ServiceProvider2.class).setInterface(ServiceProvider2.class.getName(), null)
- .setCallbacks("init", "start", "stop", null)
- .setComposition("getComposition");
-
- Component sp = m.createComponent()
- .setImplementation(ServiceProvider.class)
- .setInterface(ServiceInterface.class.getName(), new Hashtable() {{ put("foo", "bar"); }})
- .setCallbacks("init", "start", "stop", null);
-
- Component sc = m.createComponent()
- .setImplementation(ServiceConsumer.class)
- .setCallbacks("init", "start", "stop", null);
-
- // Provide the Sequencer service to the MultipleAnnotationsTest class.
- Component sequencer =
- m.createComponent().setImplementation(new SequencerImpl(e))
- .setInterface(Sequencer.class.getName(), null);
- m.add(sp2);
- m.add(sp);
- m.add(sc);
- m.add(sequencer);
-
- // Check if the test.annotation components have been initialized orderly
- e.waitForStep(7, 10000);
-
- // Stop the test.annotation bundle
- m.remove(sequencer);
- m.remove(sp);
- m.remove(sp2);
- m.remove(sc);
-
-// m.remove(sp2);
-// m.remove(sc);
-// m.remove(sp);
-// m.remove(sequencer);
-
-
-
- // And check if the test.annotation bundle has been deactivated orderly
- e.waitForStep(11, 10000);
- m.clear();
- }
-
- public interface Sequencer
- {
- void step();
- void step(int step);
- void waitForStep(int step, int timeout);
- }
-
- public static class SequencerImpl implements Sequencer {
- final Ensure m_ensure;
-
- public SequencerImpl(Ensure e)
- {
- m_ensure = e;
- }
-
- public void step()
- {
- m_ensure.step();
- }
-
- public void step(int step)
- {
- m_ensure.step(step);
- }
-
- public void waitForStep(int step, int timeout)
- {
- m_ensure.waitForStep(step, timeout);
- }
- }
-
- public interface ServiceInterface
- {
- public void doService();
- }
-
- public static class ServiceConsumer {
- volatile Sequencer m_sequencer;
- volatile ServiceInterface m_service;
- volatile ServiceDependency m_d1, m_d2;
-
- public void init(Component s) {
- DependencyManager m = s.getDependencyManager();
- s.add(m_d1 = m.createServiceDependency()
- .setService(Sequencer.class)
- .setRequired(true)
- .setInstanceBound(true)
- .setAutoConfig("m_sequencer"));
- s.add(m_d2 = m.createServiceDependency()
- .setService(ServiceInterface.class, "(foo=bar)")
- .setRequired(true)
- .setInstanceBound(true)
- .setAutoConfig("m_service"));
- }
-
- void start() {
- m_sequencer.step(6);
- m_service.doService();
- }
-
- void stop() {
- m_sequencer.step(8);
- }
- }
-
- public static class ServiceProvider implements ServiceInterface
- {
- volatile Sequencer m_sequencer;
- volatile ServiceProvider2 m_serviceProvider2;
- volatile ServiceDependency m_d1, m_d2;
-
- public void init(Component c)
- {
- DependencyManager m = c.getDependencyManager();
- List<ServiceDependency> l = new ArrayList<ServiceDependency>();
- l.add(m_d1 = m.createServiceDependency()
- .setService(Sequencer.class)
- .setRequired(true)
- .setInstanceBound(true)
- .setAutoConfig("m_sequencer"));
- l.add(m_d2 = m.createServiceDependency()
- .setService(ServiceProvider2.class)
- .setRequired(true)
- .setInstanceBound(true)
- .setCallbacks("bind", "unbind"));
- c.add(l);
- }
-
- void bind(ServiceProvider2 provider2)
- {
- m_serviceProvider2 = provider2;
- }
-
- void start()
- {
- m_d1.setInstanceBound(false);
- m_d2.setInstanceBound(false);
- m_serviceProvider2.step(4);
- m_sequencer.step(5);
- }
-
- void stop()
- {
- m_sequencer.step(9);
- }
-
- void unbind(ServiceProvider2 provider2)
- {
- m_sequencer.step(10);
- }
-
- public void doService()
- {
- m_sequencer.step(7);
- }
- }
-
- public static class ServiceProvider2
- {
- final Composite m_composite = new Composite();
- volatile Sequencer m_sequencer;
- volatile Runnable m_runnable;
- volatile ServiceDependency m_d1, m_d2;
-
- public void init(Component c)
- {
- System.out.println("ServiceProvider2.init");
- DependencyManager m = c.getDependencyManager();
- List<ServiceDependency> l = new ArrayList<ServiceDependency>();
-
- l.add(m_d1 = m.createServiceDependency()
- .setService(Runnable.class, "(foo=bar)")
- .setRequired(false)
- .setInstanceBound(true)
- .setAutoConfig("m_runnable"));
- l.add(m_d2 = m.createServiceDependency()
- .setService(Sequencer.class)
- .setRequired(true)
- .setInstanceBound(true)
- .setCallbacks("bind", null));
- c.add(l);
- }
-
- void bind(Sequencer seq)
- {
- System.out.println("ServiceProvider2.bind(" + seq + ")");
- m_sequencer = seq;
- m_sequencer.step(1);
- }
-
- void start()
- {
- System.out.println("ServiceProvider2.start: m_runnable=" + m_runnable + ", m_sequencer = " + m_sequencer);
- m_d1.setInstanceBound(false);
- m_d2.setInstanceBound(false);
- m_sequencer.step(3);
- m_runnable.run(); // NullObject
- }
-
- public void step(int step) // called by ServiceProvider.start() method
- {
- m_sequencer.step(step);
- }
-
- void stop()
- {
- m_sequencer.step(11);
- }
-
- Object[] getComposition()
- {
- return new Object[] { this, m_composite };
- }
- }
-
- public static class Composite
- {
- void bind(Sequencer seq)
- {
- seq.step(2);
- }
- }
-}
diff --git a/dependencymanager/test/src/test/java/org/apache/felix/dm/test/integration/api/MultipleServiceDependencyTest.java b/dependencymanager/test/src/test/java/org/apache/felix/dm/test/integration/api/MultipleServiceDependencyTest.java
deleted file mode 100644
index d606e83..0000000
--- a/dependencymanager/test/src/test/java/org/apache/felix/dm/test/integration/api/MultipleServiceDependencyTest.java
+++ /dev/null
@@ -1,150 +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.felix.dm.test.integration.api;
-
-import java.util.Properties;
-
-import org.apache.felix.dm.Component;
-import org.apache.felix.dm.DependencyManager;
-import org.apache.felix.dm.test.components.Ensure;
-import org.apache.felix.dm.test.integration.common.TestBase;
-import org.junit.Test;
-import org.junit.runner.RunWith;
-import org.ops4j.pax.exam.junit.PaxExam;
-import org.osgi.framework.Constants;
-
-@RunWith(PaxExam.class)
-public class MultipleServiceDependencyTest extends TestBase {
- @Test
- public void testMultipleServiceRegistrationAndConsumption() {
- DependencyManager m = new DependencyManager(context);
- // helper class that ensures certain steps get executed in sequence
- Ensure e = new Ensure();
- // create a service provider and consumer
- Component provider = m.createComponent().setImplementation(new ServiceProvider(e)).setInterface(ServiceInterface.class.getName(), null);
- Component providerWithHighRank = m.createComponent().setImplementation(new ServiceProvider2(e)).setInterface(ServiceInterface.class.getName(), new Properties() {{ put(Constants.SERVICE_RANKING, Integer.valueOf(5)); }});
- Component consumer = m.createComponent().setImplementation(new ServiceConsumer(e)).add(m.createServiceDependency().setService(ServiceInterface.class).setRequired(true));
- m.add(provider);
- m.add(providerWithHighRank);
- m.add(consumer);
- e.waitForStep(3, 15000);
- m.remove(providerWithHighRank);
- e.step(4);
- e.waitForStep(5, 15000);
- m.remove(provider);
- m.remove(consumer);
- e.waitForStep(6, 15000);
- }
-
- @Test
- public void testReplacementAutoConfig() {
- DependencyManager m = new DependencyManager(context);
- // helper class that ensures certain steps get executed in sequence
- Ensure e = new Ensure();
- // create a service provider and consumer
- Component provider = m.createComponent().setImplementation(new ServiceProvider(e)).setInterface(ServiceInterface.class.getName(), null);
- Component provider2 = m.createComponent().setImplementation(new ServiceProvider2(e)).setInterface(ServiceInterface.class.getName(), null);
- Component consumer = m.createComponent().setImplementation(new ServiceConsumer(e)).add(m.createServiceDependency().setService(ServiceInterface.class).setRequired(true));
- m.add(provider2);
- m.add(consumer);
- e.waitForStep(3, 15000);
- m.add(provider);
- m.remove(provider2);
- e.step(4);
- e.waitForStep(5, 15000);
- m.remove(provider);
- m.remove(consumer);
- e.waitForStep(6, 15000);
- }
-
- @Test
- public void testReplacementCallbacks() {
- DependencyManager m = new DependencyManager(context);
- // helper class that ensures certain steps get executed in sequence
- Ensure e = new Ensure();
- // create a service provider and consumer
- Component provider = m.createComponent().setImplementation(new ServiceProvider(e)).setInterface(ServiceInterface.class.getName(), null);
- Component provider2 = m.createComponent().setImplementation(new ServiceProvider2(e)).setInterface(ServiceInterface.class.getName(), null);
- Component consumer = m.createComponent().setImplementation(new ServiceConsumer(e))
- .add(m.createServiceDependency()
- .setService(ServiceInterface.class)
- .setRequired(true)
- .setCallbacks("add", "remove"));
- m.add(provider2);
- m.add(consumer);
- e.waitForStep(3, 15000);
- m.add(provider);
- m.remove(provider2);
- e.step(4);
- e.waitForStep(5, 15000);
- m.remove(provider);
- m.remove(consumer);
- e.waitForStep(6, 15000);
- }
-
- static interface ServiceInterface {
- public void invoke();
- }
-
- static class ServiceProvider implements ServiceInterface {
- private final Ensure m_ensure;
- public ServiceProvider(Ensure e) {
- m_ensure = e;
- }
- public void invoke() {
- m_ensure.step(5);
- }
- }
-
- static class ServiceProvider2 implements ServiceInterface {
- private final Ensure m_ensure;
- public ServiceProvider2(Ensure e) {
- m_ensure = e;
- }
- public void invoke() {
- m_ensure.step(2);
- }
- }
-
- static class ServiceConsumer implements Runnable {
- private volatile ServiceInterface m_service;
- private final Ensure m_ensure;
-
- private void add(ServiceInterface service) { m_service = service; }
- private void remove(ServiceInterface service) { if (m_service == service) { m_service = null; }};
- public ServiceConsumer(Ensure e) { m_ensure = e; }
-
- public void start() {
- Thread t = new Thread(this);
- t.start();
- }
-
- public void run() {
- m_ensure.step(1);
- m_service.invoke();
- m_ensure.step(3);
- m_ensure.waitForStep(4, 15000);
- m_service.invoke();
- }
-
- public void stop() {
- m_ensure.step(6);
- }
- }
-}
diff --git a/dependencymanager/test/src/test/java/org/apache/felix/dm/test/integration/api/ResourceAdapterDependencyAddAndRemoveTest.java b/dependencymanager/test/src/test/java/org/apache/felix/dm/test/integration/api/ResourceAdapterDependencyAddAndRemoveTest.java
deleted file mode 100644
index 52f6fd6..0000000
--- a/dependencymanager/test/src/test/java/org/apache/felix/dm/test/integration/api/ResourceAdapterDependencyAddAndRemoveTest.java
+++ /dev/null
@@ -1,271 +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.felix.dm.test.integration.api;
-
-import java.net.MalformedURLException;
-import java.net.URL;
-import java.util.HashMap;
-import java.util.Map;
-import java.util.Map.Entry;
-
-import junit.framework.Assert;
-
-import org.apache.felix.dm.Component;
-import org.apache.felix.dm.ComponentStateListener;
-import org.apache.felix.dm.Dependency;
-import org.apache.felix.dm.DependencyManager;
-import org.apache.felix.dm.ResourceHandler;
-import org.apache.felix.dm.ResourceUtil;
-import org.apache.felix.dm.ServiceDependency;
-import org.apache.felix.dm.test.components.Ensure;
-import org.apache.felix.dm.test.integration.common.TestBase;
-import org.junit.Test;
-import org.junit.runner.RunWith;
-import org.ops4j.pax.exam.junit.PaxExam;
-import org.osgi.framework.BundleContext;
-import org.osgi.framework.Filter;
-import org.osgi.framework.InvalidSyntaxException;
-import org.osgi.framework.ServiceReference;
-
-@RunWith(PaxExam.class)
-public class ResourceAdapterDependencyAddAndRemoveTest extends TestBase {
- @Test
- public void testBasicResourceAdapter() throws Exception {
- DependencyManager m = new DependencyManager(context);
- // helper class that ensures certain steps get executed in sequence
- Ensure e = new Ensure();
-
- // create and add a service provider
- m.add(m.createComponent()
- .setInterface(ServiceInterface.class.getName(), null)
- .setImplementation(new ServiceProvider(e)));
-
- // create and add a resource provider
- ResourceProvider provider = new ResourceProvider(e);
- m.add(m.createComponent()
- .setImplementation(provider)
- .add(m.createServiceDependency()
- .setService(ResourceHandler.class)
- .setCallbacks("add", "remove"))
- );
-
- // create a resource adapter for our single resource
- // note that we can provide an actual implementation instance here because there will be only one
- // adapter, normally you'd want to specify a Class here
- // also, create a callback instance which will be used for both callbacks on resource changes and
- // life cycle callbacks on the adapters themselves
- CallbackInstance callbackInstance = new CallbackInstance(e);
- Component component = m.createResourceAdapterService("(&(path=/path/to/*.txt)(host=localhost))", false, callbackInstance, "changed")
- .setImplementation(new ResourceAdapter(e))
- .setCallbacks(callbackInstance, "init", "start", "stop", "destroy")
- .add(m.createServiceDependency()
- .setService(ServiceInterface.class)
- .setRequired(true)
- .setInstanceBound(true));
- // add a component state listener
- component.addStateListener(new ComponentStateListenerImpl(e));
- // add the resource adapter
- m.add(component);
- // wait until the single resource is available (the adapter has been started)
- e.waitForStep(1, 5000);
- // trigger a 'change' in our resource
- provider.change();
- // wait until the changed callback is invoked
- e.waitForStep(2, 5000);
- // and has completed (ensuring no "extra" steps are invoked in the mean time)
- e.waitForStep(3, 5000);
-
- // remove the resource adapter again
- m.remove(component);
-
- // wait for the stopped callback in the state listener
- e.waitForStep(4, 5000);
- }
-
- static class ResourceAdapter {
- protected URL m_resource; // injected by reflection.
- private Ensure m_ensure;
-
- ResourceAdapter(Ensure e) {
- m_ensure = e;
- }
-
- }
-
- static class ResourceProvider {
- private volatile BundleContext m_context;
- private final Ensure m_ensure;
- private final Map m_handlers = new HashMap();
- private URL[] m_resources;
-
- public ResourceProvider(Ensure ensure) throws MalformedURLException {
- m_ensure = ensure;
- m_resources = new URL[] {
- new URL("file://localhost/path/to/file1.txt")
- };
- }
-
- public void change() {
- ResourceHandler[] handlers;
- synchronized (m_handlers) {
- handlers = (ResourceHandler[]) m_handlers.keySet().toArray(new ResourceHandler[m_handlers.size()]);
- }
- for (int i = 0; i < m_resources.length; i++) {
- for (int j = 0; j < handlers.length; j++) {
- ResourceHandler handler = handlers[j];
- handler.changed(m_resources[i]);
- }
- }
- }
-
- public void add(ServiceReference ref, ResourceHandler handler) {
- String filterString = (String) ref.getProperty("filter");
- Filter filter = null;
- if (filterString != null) {
- try {
- filter = m_context.createFilter(filterString);
- }
- catch (InvalidSyntaxException e) {
- Assert.fail("Could not create filter for resource handler: " + e);
- return;
- }
- }
- synchronized (m_handlers) {
- m_handlers.put(handler, filter);
- }
- for (int i = 0; i < m_resources.length; i++) {
- if (filter == null || filter.match(ResourceUtil.createProperties(m_resources[i]))) {
- handler.added(m_resources[i]);
- }
- }
- }
-
- public void remove(ServiceReference ref, ResourceHandler handler) {
- Filter filter;
- synchronized (m_handlers) {
- filter = (Filter) m_handlers.remove(handler);
- }
- removeResources(handler, filter);
- }
-
- private void removeResources(ResourceHandler handler, Filter filter) {
- for (int i = 0; i < m_resources.length; i++) {
- if (filter == null || filter.match(ResourceUtil.createProperties(m_resources[i]))) {
- handler.removed(m_resources[i]);
- }
- }
- }
-
- public void destroy() {
- Entry[] handlers;
- synchronized (m_handlers) {
- handlers = (Entry[]) m_handlers.entrySet().toArray(new Entry[m_handlers.size()]);
- }
- for (int i = 0; i < handlers.length; i++) {
- removeResources((ResourceHandler) handlers[i].getKey(), (Filter) handlers[i].getValue());
- }
-
- System.out.println("DESTROY..." + m_handlers.size());
- }
- }
-
- static interface ServiceInterface {
- public void invoke();
- }
-
- static class ServiceProvider implements ServiceInterface {
- private final Ensure m_ensure;
- public ServiceProvider(Ensure e) {
- m_ensure = e;
- }
- public void invoke() {
- }
- }
-
- static class CallbackInstance {
-
- private final Ensure m_ensure;
-
- public CallbackInstance(Ensure e) {
- m_ensure = e;
- }
-
- void init() {
- System.out.println("init");
- }
-
- void start() {
- System.out.println("start");
- m_ensure.step(1);
- }
-
- void stop() {
- System.out.println("stop");
- }
-
- void destroy() {
- System.out.println("destroy");
- }
-
- void changed(Component component) {
- m_ensure.step(2);
- Dependency oldDependency = null;
-
- for (Object dependency : component.getDependencies()) {
- if (dependency instanceof ServiceDependency) {
- // remove the dependency
- oldDependency = (Dependency) dependency;
- }
- }
-
- // and add a new dependency
- component.add(component.getDependencyManager().createServiceDependency().setService(ServiceInterface.class).setRequired(true).setInstanceBound(true));
- // remove the old dependency
- component.remove(oldDependency);
- System.out.println("Changed the dependencies");
- m_ensure.step(3);
- }
- }
-
- static class ComponentStateListenerImpl implements ComponentStateListener {
-
- private final Ensure m_ensure;
-
- public ComponentStateListenerImpl(Ensure e) {
- this.m_ensure = e;
- }
-
- public void started(Component c) {
- System.out.println("started");
- }
-
- public void starting(Component c) {
- System.out.println("starting");
- }
-
- public void stopped(Component c) {
- System.out.println("stopped");
- m_ensure.step(4);
- }
-
- public void stopping(Component c) {
- System.out.println("stopping");
- }
- }
-}
diff --git a/dependencymanager/test/src/test/java/org/apache/felix/dm/test/integration/api/ResourceAdapterDependencyAddAndRemoveTest2.java b/dependencymanager/test/src/test/java/org/apache/felix/dm/test/integration/api/ResourceAdapterDependencyAddAndRemoveTest2.java
deleted file mode 100644
index 79c08ec..0000000
--- a/dependencymanager/test/src/test/java/org/apache/felix/dm/test/integration/api/ResourceAdapterDependencyAddAndRemoveTest2.java
+++ /dev/null
@@ -1,272 +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.felix.dm.test.integration.api;
-
-import java.net.MalformedURLException;
-import java.net.URL;
-import java.util.HashMap;
-import java.util.Map;
-import java.util.Map.Entry;
-import java.util.Properties;
-
-import junit.framework.Assert;
-
-import org.apache.felix.dm.Component;
-import org.apache.felix.dm.ComponentStateListener;
-import org.apache.felix.dm.Dependency;
-import org.apache.felix.dm.DependencyManager;
-import org.apache.felix.dm.ResourceHandler;
-import org.apache.felix.dm.ResourceUtil;
-import org.apache.felix.dm.ServiceDependency;
-import org.apache.felix.dm.test.components.Ensure;
-import org.apache.felix.dm.test.integration.common.TestBase;
-import org.junit.Test;
-import org.junit.runner.RunWith;
-import org.ops4j.pax.exam.junit.PaxExam;
-import org.osgi.framework.BundleContext;
-import org.osgi.framework.Filter;
-import org.osgi.framework.InvalidSyntaxException;
-import org.osgi.framework.ServiceReference;
-
-@RunWith(PaxExam.class)
-public class ResourceAdapterDependencyAddAndRemoveTest2 extends TestBase {
- @Test
- public void testBasicResourceAdapter() throws Exception {
- DependencyManager m = new DependencyManager(context);
- // helper class that ensures certain steps get executed in sequence
- Ensure e = new Ensure();
- // create a resource provider
- ResourceProvider provider = new ResourceProvider(e);
- // activate it
- Properties props = new Properties();
- props.setProperty("id", "1");
- m.add(m.createComponent()
- .setInterface(ServiceInterface.class.getName(), props)
- .setImplementation(new ServiceProvider(e))
- );
-
- props = new Properties();
- props.setProperty("id", "2");
- m.add(m.createComponent()
- .setInterface(ServiceInterface.class.getName(), props)
- .setImplementation(new ServiceProvider(e))
- );
-
- m.add(m.createComponent()
- .setImplementation(provider)
- .add(m.createServiceDependency()
- .setService(ResourceHandler.class)
- .setCallbacks("add", "remove")
- )
- );
-
- // create a resource adapter for our single resource
- // note that we can provide an actual implementation instance here because there will be only one
- // adapter, normally you'd want to specify a Class here
- ResourceAdapter service = new ResourceAdapter(e);
- CallbackInstance callbackInstance = new CallbackInstance(e);
- Component component = m.createResourceAdapterService("(&(path=/path/to/*.txt)(host=localhost))", false, callbackInstance, "changed")
- .setImplementation(new ResourceAdapter(e))
- .setCallbacks(callbackInstance, "init", "start", "stop", "destroy")
- .add(m.createServiceDependency()
- .setService(ServiceInterface.class, "(id=1)")
- .setRequired(true)
- .setInstanceBound(true)
- );
- component.addStateListener(new ComponentStateListenerImpl(e));
- m.add(component);
- // wait until the single resource is available
- e.waitForStep(1, 5000);
- // trigger a 'change' in our resource
- provider.change();
- // wait until the changed callback is invoked
- e.waitForStep(2, 5000);
-
- System.out.println("Done!");
- m.clear();
- }
-
- static class ResourceAdapter {
- protected URL m_resource; // injected by reflection.
- private Ensure m_ensure;
-
- ResourceAdapter(Ensure e) {
- m_ensure = e;
- }
- }
-
- static class ResourceProvider {
- private volatile BundleContext m_context;
- private final Ensure m_ensure;
- private final Map m_handlers = new HashMap();
- private URL[] m_resources;
-
- public ResourceProvider(Ensure ensure) throws MalformedURLException {
- m_ensure = ensure;
- m_resources = new URL[] {
- new URL("file://localhost/path/to/file1.txt")
- };
- }
-
- public void change() {
- ResourceHandler[] handlers;
- synchronized (m_handlers) {
- handlers = (ResourceHandler[]) m_handlers.keySet().toArray(new ResourceHandler[m_handlers.size()]);
- }
- for (int i = 0; i < m_resources.length; i++) {
- for (int j = 0; j < handlers.length; j++) {
- ResourceHandler handler = handlers[j];
- handler.changed(m_resources[i]);
- }
- }
- }
-
- public void add(ServiceReference ref, ResourceHandler handler) {
- String filterString = (String) ref.getProperty("filter");
- Filter filter = null;
- if (filterString != null) {
- try {
- filter = m_context.createFilter(filterString);
- }
- catch (InvalidSyntaxException e) {
- Assert.fail("Could not create filter for resource handler: " + e);
- return;
- }
- }
- synchronized (m_handlers) {
- m_handlers.put(handler, filter);
- }
- for (int i = 0; i < m_resources.length; i++) {
- if (filter == null || filter.match(ResourceUtil.createProperties(m_resources[i]))) {
- handler.added(m_resources[i]);
- }
- }
- }
-
- public void remove(ServiceReference ref, ResourceHandler handler) {
- Filter filter;
- synchronized (m_handlers) {
- filter = (Filter) m_handlers.remove(handler);
- }
- removeResources(handler, filter);
- }
-
- private void removeResources(ResourceHandler handler, Filter filter) {
- for (int i = 0; i < m_resources.length; i++) {
- if (filter == null || filter.match(ResourceUtil.createProperties(m_resources[i]))) {
- handler.removed(m_resources[i]);
- }
- }
- }
-
- public void destroy() {
- Entry[] handlers;
- synchronized (m_handlers) {
- handlers = (Entry[]) m_handlers.entrySet().toArray(new Entry[m_handlers.size()]);
- }
- for (int i = 0; i < handlers.length; i++) {
- removeResources((ResourceHandler) handlers[i].getKey(), (Filter) handlers[i].getValue());
- }
- }
- }
-
- static interface ServiceInterface {
- public void invoke();
- }
-
- static class ServiceProvider implements ServiceInterface {
- private final Ensure m_ensure;
- public ServiceProvider(Ensure e) {
- m_ensure = e;
- }
- public void invoke() {
- }
- }
-
- static class CallbackInstance {
-
- private final Ensure m_ensure;
-
- public CallbackInstance(Ensure e) {
- m_ensure = e;
- }
-
- void init() {
- System.out.println("init");
- m_ensure.step(1);
- }
-
- void start() {
- System.out.println("start");
- }
-
- void stop() {
- System.out.println("stop");
- }
-
- void destroy() {
- System.out.println("destroy");
- }
-
- void changed(Component component) {
- m_ensure.step(2);
- System.out.println("Changing the dependencies");
- Dependency oldDependency = null;
-
- for (Object dependency : component.getDependencies()) {
- if (dependency instanceof ServiceDependency) {
- // remove the dependency
- oldDependency = (Dependency) dependency;
- System.out.println("Old dependency props: " + oldDependency.getProperties());
- }
- }
-
- // and add a new dependency
- component.add(component.getDependencyManager().createServiceDependency().setService(ServiceInterface.class, "(id=2)").setRequired(true).setInstanceBound(true));
- // remove the old dependency
- component.remove(oldDependency);
- System.out.println("Changed the dependencies");
- }
- }
-
- static class ComponentStateListenerImpl implements ComponentStateListener {
-
- private final Ensure m_ensure;
-
- public ComponentStateListenerImpl(Ensure e) {
- this.m_ensure = e;
- }
-
- public void started(Component c) {
- System.out.println("started");
- }
-
- public void starting(Component c) {
- System.out.println("starting");
- }
-
- public void stopped(Component c) {
- System.out.println("stopped");
- }
-
- public void stopping(Component c) {
- System.out.println("stopping");
- }
- }
-}
diff --git a/dependencymanager/test/src/test/java/org/apache/felix/dm/test/integration/api/ResourceAdapterTest.java b/dependencymanager/test/src/test/java/org/apache/felix/dm/test/integration/api/ResourceAdapterTest.java
deleted file mode 100644
index 32a48e4..0000000
--- a/dependencymanager/test/src/test/java/org/apache/felix/dm/test/integration/api/ResourceAdapterTest.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.felix.dm.test.integration.api;
-
-import java.io.FileNotFoundException;
-import java.io.IOException;
-import java.io.InputStream;
-import java.net.MalformedURLException;
-import java.net.URL;
-import java.util.HashMap;
-import java.util.Map;
-import java.util.Map.Entry;
-
-import junit.framework.Assert;
-
-import org.apache.felix.dm.DependencyManager;
-import org.apache.felix.dm.ResourceHandler;
-import org.apache.felix.dm.ResourceUtil;
-import org.apache.felix.dm.test.components.Ensure;
-import org.apache.felix.dm.test.integration.common.TestBase;
-import org.junit.Test;
-import org.junit.runner.RunWith;
-import org.ops4j.pax.exam.junit.PaxExam;
-import org.osgi.framework.BundleContext;
-import org.osgi.framework.Filter;
-import org.osgi.framework.InvalidSyntaxException;
-import org.osgi.framework.ServiceReference;
-
-@RunWith(PaxExam.class)
-public class ResourceAdapterTest extends TestBase {
- @Test
- public void testBasicResourceAdapter() throws Exception {
- DependencyManager m = new DependencyManager(context);
- // helper class that ensures certain steps get executed in sequence
- Ensure e = new Ensure();
- // create a resource provider
- ResourceProvider provider = new ResourceProvider(e);
- // activate it
- m.add(m.createComponent().setImplementation(provider).add(m.createServiceDependency().setService(ResourceHandler.class).setCallbacks("add", "remove")));
- // create a resource adapter for our single resource
- // note that we can provide an actual implementation instance here because there will be only one
- // adapter, normally you'd want to specify a Class here
- m.add(m.createResourceAdapterService("(&(path=/path/to/*.txt)(host=localhost))", false, null, "changed")
- .setImplementation(new ResourceAdapter(e)));
- // wait until the single resource is available
- e.waitForStep(3, 5000);
- // trigger a 'change' in our resource
- provider.change();
- // wait until the changed callback is invoked
- e.waitForStep(4, 5000);
- m.clear();
- }
-
- static class ResourceAdapter {
- protected URL m_resource; // injected by reflection.
- private Ensure m_ensure;
-
- ResourceAdapter(Ensure e) {
- m_ensure = e;
- }
-
- public void start() {
- m_ensure.step(1);
- Assert.assertNotNull("resource not injected", m_resource);
- m_ensure.step(2);
- try {
- InputStream in = m_resource.openStream();
- }
- catch (FileNotFoundException e) {
- m_ensure.step(3);
- }
- catch (IOException e) {
- Assert.fail("We should not have gotten this exception.");
- }
- }
-
- public void changed() {
- m_ensure.step(4);
- }
- }
-
- static class ResourceProvider {
- private volatile BundleContext m_context;
- private final Ensure m_ensure;
- private final Map m_handlers = new HashMap();
- private URL[] m_resources;
-
- public ResourceProvider(Ensure ensure) throws MalformedURLException {
- m_ensure = ensure;
- m_resources = new URL[] {
- new URL("file://localhost/path/to/file1.txt")
- };
- }
-
- public void change() {
- ResourceHandler[] handlers;
- synchronized (m_handlers) {
- handlers = (ResourceHandler[]) m_handlers.keySet().toArray(new ResourceHandler[m_handlers.size()]);
- }
- for (int i = 0; i < m_resources.length; i++) {
- for (int j = 0; j < handlers.length; j++) {
- ResourceHandler handler = handlers[j];
- handler.changed(m_resources[i]);
- }
- }
- }
-
- public void add(ServiceReference ref, ResourceHandler handler) {
- String filterString = (String) ref.getProperty("filter");
- Filter filter = null;
- if (filterString != null) {
- try {
- filter = m_context.createFilter(filterString);
- }
- catch (InvalidSyntaxException e) {
- Assert.fail("Could not create filter for resource handler: " + e);
- return;
- }
- }
- synchronized (m_handlers) {
- m_handlers.put(handler, filter);
- }
- for (int i = 0; i < m_resources.length; i++) {
- if (filter == null || filter.match(ResourceUtil.createProperties(m_resources[i]))) {
- handler.added(m_resources[i]);
- }
- }
- }
-
- public void remove(ServiceReference ref, ResourceHandler handler) {
- Filter filter;
- synchronized (m_handlers) {
- filter = (Filter) m_handlers.remove(handler);
- }
- removeResources(handler, filter);
- }
-
- private void removeResources(ResourceHandler handler, Filter filter) {
- for (int i = 0; i < m_resources.length; i++) {
- if (filter == null || filter.match(ResourceUtil.createProperties(m_resources[i]))) {
- handler.removed(m_resources[i]);
- }
- }
- }
-
- public void destroy() {
- Entry[] handlers;
- synchronized (m_handlers) {
- handlers = (Entry[]) m_handlers.entrySet().toArray(new Entry[m_handlers.size()]);
- }
- for (int i = 0; i < handlers.length; i++) {
- removeResources((ResourceHandler) handlers[i].getKey(), (Filter) handlers[i].getValue());
- }
-
- System.out.println("DESTROY..." + m_handlers.size());
- }
- }
-}
diff --git a/dependencymanager/test/src/test/java/org/apache/felix/dm/test/integration/api/ResourceDependencyTest.java b/dependencymanager/test/src/test/java/org/apache/felix/dm/test/integration/api/ResourceDependencyTest.java
deleted file mode 100644
index abfa09e..0000000
--- a/dependencymanager/test/src/test/java/org/apache/felix/dm/test/integration/api/ResourceDependencyTest.java
+++ /dev/null
@@ -1,235 +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.felix.dm.test.integration.api;
-
-import java.lang.reflect.InvocationHandler;
-import java.lang.reflect.Method;
-import java.lang.reflect.Proxy;
-import java.net.MalformedURLException;
-import java.net.URL;
-import java.util.HashMap;
-import java.util.Map;
-import java.util.Map.Entry;
-
-import junit.framework.Assert;
-
-import org.apache.felix.dm.Component;
-import org.apache.felix.dm.DependencyManager;
-import org.apache.felix.dm.ResourceHandler;
-import org.apache.felix.dm.ResourceUtil;
-import org.apache.felix.dm.test.components.Ensure;
-import org.apache.felix.dm.test.integration.common.TestBase;
-import org.junit.Test;
-import org.junit.runner.RunWith;
-import org.ops4j.pax.exam.junit.PaxExam;
-import org.osgi.framework.BundleContext;
-import org.osgi.framework.Filter;
-import org.osgi.framework.InvalidSyntaxException;
-import org.osgi.framework.ServiceReference;
-
-@RunWith(PaxExam.class)
-public class ResourceDependencyTest extends TestBase {
- @Test
- public void testResourceDependency() {
- DependencyManager m = new DependencyManager(context);
- // helper class that ensures certain steps get executed in sequence
- Ensure e = new Ensure();
- // create a service provider and consumer
- ResourceConsumer c = new ResourceConsumer(e);
- Component consumer = m.createComponent()
- .setImplementation(c)
- .add(m.createResourceDependency()
- .setFilter("(&(path=/path/to/*.txt)(host=localhost))")
- .setCallbacks("add", "change", "remove"));
- Component dynamicProxyConsumer = m.createComponent()
- .setFactory(new ResourceConsumerFactory(e), "create")
- .add(m.createResourceDependency()
- .setFilter("(path=*.doc)")
- .setCallbacks("add", null));
- ResourceProvider provider = new ResourceProvider(e);
- Component resourceProvider = m.createComponent()
- .setImplementation(provider)
- .add(m.createServiceDependency()
- .setService(ResourceHandler.class)
- .setCallbacks("add", "remove"));
-
- // first add the consumer
- m.add(consumer);
- // then the resource provider, which will provide 3 resources,
- // 2 of which match the consumers filter conditions
- m.add(resourceProvider);
- // make sure our consumer invoked openStream() on both resources,
- // increasing the step counter to 2
- e.step(3);
-
- // now add another consumer, that matches only one resource, and uses
- // a dynamic proxy as its implementation
- m.add(dynamicProxyConsumer);
- // ensure the resource was injected properly
- e.waitForStep(4, 5000);
-
- // now change a resource and see if it gets propagated to the consumer
- provider.changeResource();
-
- // wait for change callback
- e.waitForStep(5, 5000);
- e.step(6);
-
- // cleanup
- m.remove(dynamicProxyConsumer);
- m.remove(resourceProvider);
- m.remove(consumer);
-
- // validate that all consumed resources are "unconsumed" again
- c.ensure();
- }
-
- static class ResourceConsumer {
- private volatile int m_counter;
- private Ensure m_ensure;
-
- public ResourceConsumer(Ensure ensure) {
- m_ensure = ensure;
- }
-
- public void add(URL resource) {
- m_counter++;
- m_ensure.step();
- }
- public void change(URL resource) {
- m_ensure.step();
- }
- public void remove(URL resource) {
- m_counter--;
- }
- public void ensure() {
- Assert.assertTrue("all resources should have been added and removed at this point, but " + m_counter + " are remaining", m_counter == 0);
- }
- }
-
- static class ResourceProvider {
- private volatile BundleContext m_context;
- private final Ensure m_ensure;
- private final Map<ResourceHandler, Filter> m_handlers = new HashMap<ResourceHandler, Filter>();
- private URL[] m_resources;
-
- public ResourceProvider(Ensure ensure) {
- m_ensure = ensure;
- try {
- m_resources = new URL[] {
- new URL("file://localhost/path/to/file1.txt"),
- new URL("file://localhost/path/to/file2.txt"),
- new URL("file://localhost/path/to/file3.doc")
- };
- }
- catch (MalformedURLException e) {
- throw new IllegalStateException(e);
- }
- }
-
- public void add(ServiceReference ref, ResourceHandler handler) {
- String filterString = (String) ref.getProperty("filter");
- Filter filter;
- try {
- filter = m_context.createFilter(filterString);
- }
- catch (InvalidSyntaxException e) {
- Assert.fail("Could not create filter for resource handler: " + e);
- return;
- }
- synchronized (m_handlers) {
- m_handlers.put(handler, filter);
- }
- for (int i = 0; i < m_resources.length; i++) {
- if (filter.match(ResourceUtil.createProperties(m_resources[i]))) {
- handler.added(m_resources[i]);
- }
- }
- }
-
- public void changeResource() {
- Filter filter;
- for (Entry<ResourceHandler, Filter> entry : m_handlers.entrySet()) {
- for (int i = 0; i < m_resources.length; i++) {
- if (i == 0) {
- if (entry.getValue().match(ResourceUtil.createProperties(m_resources[i]))) {
- entry.getKey().changed(m_resources[i]);
- }
- }
- }
- }
- }
-
- public void remove(ServiceReference ref, ResourceHandler handler) {
- Filter filter;
- synchronized (m_handlers) {
- filter = (Filter) m_handlers.remove(handler);
- }
- removeResources(handler, filter);
- }
-
- private void removeResources(ResourceHandler handler, Filter filter) {
- for (int i = 0; i < m_resources.length; i++) {
- if (filter.match(ResourceUtil.createProperties(m_resources[i]))) {
- handler.removed(m_resources[i]);
- }
- }
- }
-
- public void destroy() {
- Entry[] handlers;
- synchronized (m_handlers) {
- handlers = (Entry[]) m_handlers.entrySet().toArray(new Entry[m_handlers.size()]);
- }
- for (int i = 0; i < handlers.length; i++) {
- removeResources((ResourceHandler) handlers[i].getKey(), (Filter) handlers[i].getValue());
- }
- }
- }
-
- static class ResourceConsumerFactory {
- private final Ensure m_ensure;
- public ResourceConsumerFactory(Ensure ensure) {
- m_ensure = ensure;
- }
- public Object create() {
- ResourceConsumer resourceConsumer = new ResourceConsumer(m_ensure);
- // create a dynamic proxy for the ResourceProvider
- return Proxy.newProxyInstance(resourceConsumer.getClass().getClassLoader(), resourceConsumer.getClass().getInterfaces(), new DynamicProxyHandler(resourceConsumer, m_ensure));
- }
- }
-
- static class DynamicProxyHandler implements InvocationHandler {
- Ensure m_ensure;
- ResourceConsumer resourceConsumer = null;
-
- public DynamicProxyHandler(ResourceConsumer resourceConsumer, Ensure ensure) {
- this.resourceConsumer = resourceConsumer;
- m_ensure = ensure;
- }
-
- public void add(URL resource) {
- m_ensure.step(4);
- }
-
- public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
- return method.invoke(resourceConsumer, args);
- }
- }
-}
diff --git a/dependencymanager/test/src/test/java/org/apache/felix/dm/test/integration/api/ServiceDependencyComponentLifeCycleTest.java b/dependencymanager/test/src/test/java/org/apache/felix/dm/test/integration/api/ServiceDependencyComponentLifeCycleTest.java
deleted file mode 100644
index ae8122e..0000000
--- a/dependencymanager/test/src/test/java/org/apache/felix/dm/test/integration/api/ServiceDependencyComponentLifeCycleTest.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.felix.dm.test.integration.api;
-//import static org.ops4j.pax.exam.CoreOptions.waitForFrameworkStartupFor;
-//import static org.ops4j.pax.exam.container.def.PaxRunnerOptions.vmOption;
-
-import junit.framework.Assert;
-
-import org.apache.felix.dm.Component;
-import org.apache.felix.dm.DependencyManager;
-import org.apache.felix.dm.ServiceDependency;
-import org.apache.felix.dm.test.components.Ensure;
-import org.apache.felix.dm.test.integration.common.TestBase;
-import org.junit.Test;
-import org.junit.runner.RunWith;
-import org.ops4j.pax.exam.junit.PaxExam;
-import org.osgi.util.tracker.ServiceTracker;
-
-@RunWith(PaxExam.class)
-public class ServiceDependencyComponentLifeCycleTest extends TestBase {
- @Test
- public void testComponentLifeCycleWhenAddingAndRemovingDependencies() throws Exception {
- DependencyManager m = new DependencyManager(context);
- // helper class that ensures certain steps get executed in sequence
- Ensure e = new Ensure();
- // create a resource provider
-
- Component component = m.createComponent().setInterface(MyService2.class.getName(), null).setImplementation(new MyComponent(e));
- ServiceDependency dependency = m.createServiceDependency().setService(MyService.class).setRequired(true);
- ServiceDependency dependency2 = m.createServiceDependency().setService(MyService.class).setRequired(true);
- ServiceTracker st = new ServiceTracker(context, MyService2.class.getName(), null);
- st.open();
- Component component2 = m.createComponent().setInterface(MyService.class.getName(), null).setImplementation(new MyImpl(e));
-
- // add the component: it has no dependencies so it should be activated immediately
- m.add(component);
- Assert.assertNotNull("service should be available", st.getService());
-
- // add a required dependency that is not available, so the component should be deactivated
- component.add(dependency);
- Assert.assertNull("service should no longer be available", st.getService());
- // remove the dependency again, so the component should be activated again
- component.remove(dependency);
- Assert.assertNotNull("service should be available", st.getService());
- // make the dependency instance bound
- dependency.setInstanceBound(true);
-
- // add it again, the component was already active so even though the dependency
- // is required, the component will *NOT* go through the destroy life cycle methods
- component.add(dependency);
- Assert.assertNull("service should no longer be available", st.getService());
- component.remove(dependency);
- Assert.assertNotNull("service should be available", st.getService());
-
- // make the second dependency instance bound too
- dependency2.setInstanceBound(true);
-
- // activate the service we depend on
- m.add(component2);
- // init and start should be invoked here, so wait for them to complete
- e.waitForStep(10, 5000);
-
- component.add(dependency);
- Assert.assertNotNull("service should be available", st.getService());
- component.add(dependency2);
- Assert.assertNotNull("service should be available", st.getService());
- component.remove(dependency);
- Assert.assertNotNull("service should be available", st.getService());
-
- e.step(11);
-
- // remove the service again, the component still has an instance bound
- // dependency on it, so stop() should be invoked, but the component
- // should not be destroyed
- m.remove(component2);
- e.step(15);
- Assert.assertNull("service should no longer be available", st.getService());
- component.remove(dependency2);
- Assert.assertNotNull("service should be available", st.getService());
- m.remove(component);
- e.step(19);
- }
-
- public static class MyComponent implements MyService2 {
- private final Ensure m_ensure;
- private final Ensure.Steps m_initSteps = new Ensure.Steps(1, 5);
- private final Ensure.Steps m_startSteps = new Ensure.Steps(2, 6, 8, 16);
- private final Ensure.Steps m_stopSteps = new Ensure.Steps(3, 7, 12, 17);
- private final Ensure.Steps m_destroySteps = new Ensure.Steps(4, 18);
-
- public MyComponent(Ensure e) {
- m_ensure = e;
- }
-
- public void init() {
- System.out.println("init");
- m_ensure.steps(m_initSteps);
- }
-
- public void start() {
- System.out.println("start");
- m_ensure.steps(m_startSteps);
- }
-
- public void stop() {
- System.out.println("stop");
- m_ensure.steps(m_stopSteps);
- }
-
- public void destroy() {
- System.out.println("destroy");
- m_ensure.steps(m_destroySteps);
- }
- }
-
- public static interface MyService2 {
- }
-
- public static interface MyService {
- }
-
- public static class MyImpl implements MyService {
- private final Ensure m_ensure;
-
- public MyImpl(Ensure e) {
- m_ensure = e;
- }
-
- public void init() {
- m_ensure.step(9);
- }
- public void start() {
- m_ensure.step(10);
- }
- public void stop() {
- m_ensure.step(13);
- }
- public void destroy() {
- m_ensure.step(14);
- }
- }
-}
diff --git a/dependencymanager/test/src/test/java/org/apache/felix/dm/test/integration/api/ServiceDependencyInjectionTest.java b/dependencymanager/test/src/test/java/org/apache/felix/dm/test/integration/api/ServiceDependencyInjectionTest.java
deleted file mode 100644
index 6f61524..0000000
--- a/dependencymanager/test/src/test/java/org/apache/felix/dm/test/integration/api/ServiceDependencyInjectionTest.java
+++ /dev/null
@@ -1,115 +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.felix.dm.test.integration.api;
-
-import junit.framework.Assert;
-
-import org.apache.felix.dm.Component;
-import org.apache.felix.dm.DependencyManager;
-import org.apache.felix.dm.test.components.Ensure;
-import org.apache.felix.dm.test.integration.common.TestBase;
-import org.junit.Test;
-import org.junit.runner.RunWith;
-import org.ops4j.pax.exam.junit.PaxExam;
-
-@RunWith(PaxExam.class)
-public class ServiceDependencyInjectionTest extends TestBase {
- @Test
- public void testServiceInjection() {
- DependencyManager m = new DependencyManager(context);
- Ensure e = new Ensure();
- // create a service provider and consumer
- ServiceProvider provider = new ServiceProvider(e);
- Component sp = m.createComponent().setImplementation(provider).setInterface(ServiceInterface2.class.getName(), null);
- Component sc = m.createComponent().setImplementation(new ServiceConsumer()).add(m.createServiceDependency().setService(ServiceInterface2.class).setRequired(true));
- Component sc2 = m.createComponent()
- .setImplementation(new ServiceConsumerNamedInjection())
- .add(m.createServiceDependency().setService(ServiceInterface2.class).setRequired(false).setAutoConfig("m_service"))
- .add(m.createServiceDependency().setService(ServiceInterface2.class).setRequired(false).setAutoConfig("m_service2"))
- .add(m.createServiceDependency().setService(ServiceInterface2.class).setRequired(false).setAutoConfig("m_service3"))
- ;
- m.add(sp);
- m.add(sc);
- m.remove(sc);
- m.add(sc2);
- m.remove(sc2);
- m.remove(sp);
- e.waitForStep(5, 5000);
- }
-
- static interface ServiceInterface {
- public void invoke();
- }
-
- static interface ServiceInterface2 extends ServiceInterface {
- public void invoke2();
- }
-
- static class ServiceProvider implements ServiceInterface2 {
- private final Ensure m_ensure;
- private Ensure.Steps m_invokeSteps = new Ensure.Steps(4, 5);
- private Ensure.Steps m_invoke2Steps = new Ensure.Steps(1, 2, 3);
-
- public ServiceProvider(Ensure e) {
- m_ensure = e;
- }
-
- public void invoke() {
- System.out.println("invoke");
- m_ensure.steps(m_invokeSteps);
- }
-
- public void invoke2() {
- System.out.println("invoke2");
- m_ensure.steps(m_invoke2Steps);
- }
- }
-
- static class ServiceConsumer {
- private volatile ServiceInterface2 m_service;
- private volatile ServiceInterface2 m_service2;
-
- public void init() {
- // invoke the second method of the interface via both injected members, to ensure
- // neither of them is a null object (or null)
- m_service.invoke2();
- m_service2.invoke2();
- Assert.assertEquals("Both members should have been injected with the same service.", m_service, m_service2);
- }
- }
-
- static class ServiceConsumerNamedInjection {
- private volatile ServiceInterface2 m_service;
- private volatile ServiceInterface m_service2;
- private volatile Object m_service3;
-
- public void init() {
- // invoke the second method
- m_service.invoke2();
- // invoke the first method (twice)
- m_service2.invoke();
- ((ServiceInterface) m_service3).invoke();
- Assert.assertNotNull("Should have been injected", m_service);
- Assert.assertNotNull("Should have been injected", m_service2);
- Assert.assertNotNull("Should have been injected", m_service3);
- Assert.assertEquals("Members should have been injected with the same service.", m_service, m_service2);
- Assert.assertEquals("Members should have been injected with the same service.", m_service, m_service3);
- }
- }
-}
diff --git a/dependencymanager/test/src/test/java/org/apache/felix/dm/test/integration/api/ServiceDependencyPropagateTest.java b/dependencymanager/test/src/test/java/org/apache/felix/dm/test/integration/api/ServiceDependencyPropagateTest.java
deleted file mode 100644
index de31eab..0000000
--- a/dependencymanager/test/src/test/java/org/apache/felix/dm/test/integration/api/ServiceDependencyPropagateTest.java
+++ /dev/null
@@ -1,136 +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.felix.dm.test.integration.api;
-
-import java.util.Dictionary;
-import java.util.Hashtable;
-import java.util.Map;
-
-import org.apache.felix.dm.Component;
-import org.apache.felix.dm.DependencyManager;
-import org.apache.felix.dm.test.components.Ensure;
-import org.apache.felix.dm.test.integration.common.TestBase;
-import org.junit.Test;
-import org.junit.runner.RunWith;
-import org.ops4j.pax.exam.junit.PaxExam;
-import org.osgi.framework.ServiceReference;
-
-/**
- * Validates ServiceDependency service properties propagation.
- */
-@RunWith(PaxExam.class)
-public class ServiceDependencyPropagateTest extends TestBase {
- /**
- * Checks that a ServiceDependency propagates the dependency service properties to the provided service properties.
- */
- @Test
- public void testServiceDependencyPropagate() {
- DependencyManager m = new DependencyManager(context);
- // helper class that ensures certain steps get executed in sequence
- Ensure e = new Ensure();
- Component c1 = m.createComponent()
- .setImplementation(new C1(e))
- .add(m.createServiceDependency().setService(C2.class).setRequired(true).setCallbacks("bind", null));
-
- Component c2 = m.createComponent()
- .setInterface(C2.class.getName(), new Hashtable() {{ put("foo", "bar"); }})
- .setImplementation(new C2())
- .add(m.createServiceDependency().setService(C3.class).setRequired(true).setPropagate(true));
-
- Component c3 = m.createComponent()
- .setInterface(C3.class.getName(), new Hashtable() {{ put("foo2", "bar2"); }})
- .setImplementation(new C3());
-
- m.add(c1);
- m.add(c2);
- m.add(c3);
-
- e.waitForStep(3, 10000);
-
- m.remove(c3);
- m.remove(c2);
- m.remove(c1);
- m.clear();
- }
-
- /**
- * Checks that a ServiceDependency propagates the dependency service properties to the provided service properties,
- * using a callback method.
- */
- @Test
- public void testServiceDependencyPropagateCallback() {
- DependencyManager m = new DependencyManager(context);
- // helper class that ensures certain steps get executed in sequence
- Ensure e = new Ensure();
- Component c1 = m.createComponent()
- .setImplementation(new C1(e))
- .add(m.createServiceDependency().setService(C2.class).setRequired(true).setCallbacks("bind", null));
-
- C2 c2Impl = new C2();
- Component c2 = m.createComponent()
- .setInterface(C2.class.getName(), new Hashtable() {{ put("foo", "bar"); }})
- .setImplementation(c2Impl)
- .add(m.createServiceDependency().setService(C3.class).setRequired(true).setPropagate(c2Impl, "getServiceProperties"));
-
- Component c3 = m.createComponent()
- .setInterface(C3.class.getName(), null)
- .setImplementation(new C3());
-
- m.add(c1);
- m.add(c2);
- m.add(c3);
-
- e.waitForStep(3, 10000);
- m.clear();
- }
-
- public static class C1 {
- private Map m_props;
- private Ensure m_ensure;
-
- C1(Ensure ensure) {
- m_ensure = ensure;
- }
-
- void bind(Map props, C2 c2) {
- m_props = props;
- }
-
- void start() {
- m_ensure.step(1);
- if ("bar".equals(m_props.get("foo"))) {
- m_ensure.step(2);
- }
- if ("bar2".equals(m_props.get("foo2"))) {
- m_ensure.step(3);
- }
- }
- }
-
- public static class C2 {
- C3 m_c3;
-
- public Dictionary getServiceProperties(ServiceReference ref) {
- return new Hashtable() {{ put("foo2", "bar2"); }};
- }
- }
-
- public static class C3 {
- }
-}
diff --git a/dependencymanager/test/src/test/java/org/apache/felix/dm/test/integration/api/ServiceDependencyTest.java b/dependencymanager/test/src/test/java/org/apache/felix/dm/test/integration/api/ServiceDependencyTest.java
deleted file mode 100644
index b1720c7..0000000
--- a/dependencymanager/test/src/test/java/org/apache/felix/dm/test/integration/api/ServiceDependencyTest.java
+++ /dev/null
@@ -1,96 +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.felix.dm.test.integration.api;
-
-import org.apache.felix.dm.Component;
-import org.apache.felix.dm.DependencyManager;
-import org.apache.felix.dm.test.components.Ensure;
-import org.apache.felix.dm.test.integration.common.TestBase;
-import org.junit.Test;
-import org.junit.runner.RunWith;
-import org.ops4j.pax.exam.junit.PaxExam;
-
-@RunWith(PaxExam.class)
-public class ServiceDependencyTest extends TestBase {
- @Test
- public void testServiceRegistrationAndConsumption() {
- DependencyManager m = new DependencyManager(context);
- // helper class that ensures certain steps get executed in sequence
- Ensure e = new Ensure();
- // create a service provider and consumer
- Component sp = m.createComponent().setImplementation(new ServiceProvider(e)).setInterface(ServiceInterface.class.getName(), null);
- Component sc = m.createComponent().setImplementation(new ServiceConsumer(e)).add(m.createServiceDependency().setService(ServiceInterface.class).setRequired(true));
- Component sc2 = m.createComponent().setImplementation(new ServiceConsumerCallbacks(e)).add(m.createServiceDependency().setService(ServiceInterface.class).setRequired(false).setCallbacks("add", "remove"));
- m.add(sp);
- m.add(sc);
- m.remove(sc);
- m.add(sc2);
- m.remove(sp);
- m.remove(sc2);
- // ensure we executed all steps inside the component instance
- e.step(6);
- }
-
- static interface ServiceInterface {
- public void invoke();
- }
-
- static class ServiceProvider implements ServiceInterface {
- private final Ensure m_ensure;
- public ServiceProvider(Ensure e) {
- m_ensure = e;
- }
- public void invoke() {
- m_ensure.step(2);
- }
- }
-
- static class ServiceConsumer {
- private volatile ServiceInterface m_service;
- private final Ensure m_ensure;
-
- public ServiceConsumer(Ensure e) {
- m_ensure = e;
- }
-
- public void init() {
- m_ensure.step(1);
- m_service.invoke();
- }
-
- public void destroy() {
- m_ensure.step(3);
- }
- }
-
- static class ServiceConsumerCallbacks {
- private final Ensure m_ensure;
-
- public ServiceConsumerCallbacks(Ensure e) {
- m_ensure = e;
- }
-
- public void add(ServiceInterface service) {
- m_ensure.step(4);
- }
- public void remove(ServiceInterface service) {
- m_ensure.step(5);
- }
- }
-}
diff --git a/dependencymanager/test/src/test/java/org/apache/felix/dm/test/integration/api/ServiceDependencyThroughCallbackInstanceTest.java b/dependencymanager/test/src/test/java/org/apache/felix/dm/test/integration/api/ServiceDependencyThroughCallbackInstanceTest.java
deleted file mode 100644
index d25fac0..0000000
--- a/dependencymanager/test/src/test/java/org/apache/felix/dm/test/integration/api/ServiceDependencyThroughCallbackInstanceTest.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.felix.dm.test.integration.api;
-
-import junit.framework.Assert;
-
-import org.apache.felix.dm.DependencyManager;
-import org.apache.felix.dm.test.integration.common.TestBase;
-import org.junit.Test;
-import org.junit.runner.RunWith;
-import org.ops4j.pax.exam.junit.PaxExam;
-import org.osgi.framework.BundleContext;
-
-@RunWith(PaxExam.class)
-public class ServiceDependencyThroughCallbackInstanceTest extends TestBase {
- @Test
- public void testServiceWithCallbacksAndOneDependency() {
- invokeTest(context, 1);
- }
-
- @Test
- public void testServiceWithCallbacksAndThreeDependencies() {
- invokeTest(context, 3);
- }
-
- private void invokeTest(BundleContext context, int numberOfServices) {
- DependencyManager m = new DependencyManager(context);
- // create a number of services
- for (int i = 0; i < numberOfServices; i++) {
- final int num = i;
- m.add(m.createComponent()
- .setInterface(Service.class.getName(), null)
- .setImplementation(new Service() {
- public String toString() {
- return "A" + num;
- }
- }
- )
- );
- }
-
- // create a service with dependency which will be invoked on a callback instance
- CallbackInstance instance = new CallbackInstance();
- m.add(m.createComponent()
- .setImplementation(new SimpleService() {})
- .add(m.createServiceDependency()
- .setService(Service.class)
- .setCallbacks(instance, "added", "removed")
- .setRequired(true)
- )
- );
-
- Assert.assertEquals(numberOfServices, instance.getCount());
- m.clear();
- }
-
- public static interface Service {
- }
-
- public static interface SimpleService {
- }
-
- public static class CallbackInstance {
- int m_count = 0;
-
- void added(Service service) {
- System.out.println("added " + service);
- m_count++;
- }
-
- void removed(Service service) {
- }
-
- int getCount() {
- return m_count;
- }
- }
-}
diff --git a/dependencymanager/test/src/test/java/org/apache/felix/dm/test/integration/api/ServiceTrackerTest.java b/dependencymanager/test/src/test/java/org/apache/felix/dm/test/integration/api/ServiceTrackerTest.java
deleted file mode 100644
index e90c3bd..0000000
--- a/dependencymanager/test/src/test/java/org/apache/felix/dm/test/integration/api/ServiceTrackerTest.java
+++ /dev/null
@@ -1,117 +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.felix.dm.test.integration.api;
-
-import java.util.Hashtable;
-
-import junit.framework.Assert;
-
-import org.apache.felix.dm.DependencyManager;
-import org.apache.felix.dm.ServiceUtil;
-import org.apache.felix.dm.test.integration.common.TestBase;
-import org.apache.felix.dm.tracker.ServiceTracker;
-import org.junit.Test;
-import org.junit.runner.RunWith;
-import org.ops4j.pax.exam.junit.PaxExam;
-import org.osgi.framework.Constants;
-import org.osgi.framework.ServiceRegistration;
-
-@RunWith(PaxExam.class)
-public class ServiceTrackerTest extends TestBase {
- @Test
- public void testPlainServiceTracker() {
- ServiceTracker st = new ServiceTracker(context, ServiceInterface.class.getName(), null);
- st.open();
- ServiceRegistration sr = context.registerService(ServiceInterface.class.getName(), new ServiceProvider(), null);
- Assert.assertEquals("There should be one service that matches the tracker", 1, st.getServices().length);
- sr.unregister();
- Assert.assertNull("There should be no service that matches the tracker", st.getServices());
- st.close();
- }
-
- @Test
- public void testAspectServiceTracker() {
- ServiceTracker st = new ServiceTracker(context, ServiceInterface.class.getName(), null);
- st.open();
-
- ServiceRegistration sr = context.registerService(ServiceInterface.class.getName(), new ServiceProvider(), null);
- Assert.assertEquals("There should be one service that matches the tracker", 1, st.getServices().length);
-
- final long sid = ServiceUtil.getServiceId(sr.getReference());
- ServiceRegistration asr = context.registerService(ServiceInterface.class.getName(), new ServiceProvider(),
- new Hashtable() {{ put(DependencyManager.ASPECT, sid); put(Constants.SERVICE_RANKING, 10); }});
- Assert.assertEquals("There should be one service that matches the tracker", 1, st.getServices().length);
- Assert.assertEquals("Service ranking should be 10", Integer.valueOf(10), (Integer) st.getServiceReference().getProperty(Constants.SERVICE_RANKING));
-
- ServiceRegistration asr2 = context.registerService(ServiceInterface.class.getName(), new ServiceProvider(),
- new Hashtable() {{ put(DependencyManager.ASPECT, sid); put(Constants.SERVICE_RANKING, 20); }});
- Assert.assertEquals("There should be one service that matches the tracker", 1, st.getServices().length);
- Assert.assertEquals("Service ranking should be 20", Integer.valueOf(20), (Integer) st.getServiceReference().getProperty(Constants.SERVICE_RANKING));
-
- asr.unregister();
- Assert.assertEquals("There should be one service that matches the tracker", 1, st.getServices().length);
- Assert.assertEquals("Service ranking should be 20", Integer.valueOf(20), (Integer) st.getServiceReference().getProperty(Constants.SERVICE_RANKING));
-
- asr2.unregister();
- Assert.assertEquals("There should be one service that matches the tracker", 1, st.getServices().length);
- Assert.assertNull("Service should not have a ranking", st.getServiceReference().getProperty(Constants.SERVICE_RANKING));
-
- sr.unregister();
- Assert.assertNull("There should be no service that matches the tracker", st.getServices());
-
- st.close();
- }
-
- @Test
- public void testExistingAspectServiceTracker() {
- ServiceTracker st = new ServiceTracker(context, ServiceInterface.class.getName(), null);
- ServiceRegistration sr = context.registerService(ServiceInterface.class.getName(), new ServiceProvider(), null);
- final long sid = ServiceUtil.getServiceId(sr.getReference());
- ServiceRegistration asr = context.registerService(ServiceInterface.class.getName(), new ServiceProvider(),
- new Hashtable() {{ put(DependencyManager.ASPECT, sid); put(Constants.SERVICE_RANKING, 10); }});
- ServiceRegistration asr2 = context.registerService(ServiceInterface.class.getName(), new ServiceProvider(),
- new Hashtable() {{ put(DependencyManager.ASPECT, sid); put(Constants.SERVICE_RANKING, 20); }});
-
- st.open();
- Assert.assertEquals("There should be one service that matches the tracker", 1, st.getServices().length);
- Assert.assertEquals("Service ranking should be 20", Integer.valueOf(20), (Integer) st.getServiceReference().getProperty(Constants.SERVICE_RANKING));
-
- asr2.unregister();
- Assert.assertEquals("There should be one service that matches the tracker", 1, st.getServices().length);
- Assert.assertEquals("Service ranking should be 10", Integer.valueOf(10), (Integer) st.getServiceReference().getProperty(Constants.SERVICE_RANKING));
-
- asr.unregister();
- Assert.assertEquals("There should be one service that matches the tracker", 1, st.getServices().length);
- Assert.assertNull("Service should not have a ranking", st.getServiceReference().getProperty(Constants.SERVICE_RANKING));
-
- sr.unregister();
- Assert.assertNull("There should be no service that matches the tracker", st.getServices());
-
- st.close();
- }
-
- static interface ServiceInterface {
- public void invoke();
- }
-
- static class ServiceProvider implements ServiceInterface {
- public void invoke() {
- }
- }
-}
diff --git a/dependencymanager/test/src/test/java/org/apache/felix/dm/test/integration/api/ServiceUpdateTest.java b/dependencymanager/test/src/test/java/org/apache/felix/dm/test/integration/api/ServiceUpdateTest.java
deleted file mode 100644
index 95b1a7d..0000000
--- a/dependencymanager/test/src/test/java/org/apache/felix/dm/test/integration/api/ServiceUpdateTest.java
+++ /dev/null
@@ -1,244 +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.felix.dm.test.integration.api;
-
-import java.net.MalformedURLException;
-import java.net.URL;
-import java.util.Dictionary;
-import java.util.Enumeration;
-import java.util.HashMap;
-import java.util.Map;
-import java.util.Map.Entry;
-import java.util.Properties;
-
-import junit.framework.Assert;
-
-import org.apache.felix.dm.Component;
-import org.apache.felix.dm.DependencyManager;
-import org.apache.felix.dm.ResourceHandler;
-import org.apache.felix.dm.ResourceUtil;
-import org.apache.felix.dm.test.components.Ensure;
-import org.apache.felix.dm.test.integration.common.TestBase;
-import org.junit.Test;
-import org.junit.runner.RunWith;
-import org.ops4j.pax.exam.junit.PaxExam;
-import org.osgi.framework.BundleContext;
-import org.osgi.framework.Filter;
-import org.osgi.framework.InvalidSyntaxException;
-import org.osgi.framework.ServiceReference;
-
-@RunWith(PaxExam.class)
-public class ServiceUpdateTest extends TestBase {
- @Test
- public void testServiceUpdate() throws Exception {
- DependencyManager m = new DependencyManager(context);
- // helper class that ensures certain steps get executed in sequence
- Ensure e = new Ensure();
- // create a resource provider
- ResourceProvider provider = new ResourceProvider(e);
- // activate it
- m.add(m.createComponent()
- .setImplementation(new ServiceProvider(e))
- .add(m.createServiceDependency()
- .setService(ServiceInterface.class)
- .setRequired(true)
- .setCallbacks("add", "change", "remove")
- )
- );
-
- m.add(m.createComponent()
- .setImplementation(provider)
- .add(m.createServiceDependency()
- .setService(ResourceHandler.class)
- .setCallbacks("add", "remove")
- )
- );
-
- // create a resource adapter for our single resource
- // note that we can provide an actual implementation instance here because there will be only one
- // adapter, normally you'd want to specify a Class here
- CallbackInstance callbackInstance = new CallbackInstance(e);
- Properties serviceProps = new Properties();
- serviceProps.setProperty("number", "1");
- Component component = m.createResourceAdapterService("(&(path=/path/to/*.txt)(host=localhost))", false, callbackInstance, "changed")
- .setImplementation(new ResourceAdapter(e))
- .setInterface(ServiceInterface.class.getName(), serviceProps)
- .setCallbacks(callbackInstance, "init", "start", "stop", "destroy");
- m.add(component);
- // wait until the single resource is available
- e.waitForStep(1, 5000);
- // wait until the component gets the dependency injected
- e.waitForStep(2, 5000);
- // trigger a 'change' in our resource
- provider.change();
- // wait until the changed callback is invoked
- e.waitForStep(3, 5000);
- // wait until the changed event arrived at the component
- e.waitForStep(4, 5000);
- System.out.println("Done!");
- m.clear();
- }
-
- static class ResourceAdapter implements ServiceInterface {
- protected URL m_resource; // injected by reflection.
- private Ensure m_ensure;
-
- ResourceAdapter(Ensure e) {
- m_ensure = e;
- }
-
- public void invoke() {
- // TODO Auto-generated method stub
-
- }
- }
-
- static class ResourceProvider {
- private volatile BundleContext m_context;
- private final Ensure m_ensure;
- private final Map m_handlers = new HashMap();
- private URL[] m_resources;
-
- public ResourceProvider(Ensure ensure) throws MalformedURLException {
- m_ensure = ensure;
- m_resources = new URL[] {
- new URL("file://localhost/path/to/file1.txt")
- };
- }
-
- public void change() {
- ResourceHandler[] handlers;
- synchronized (m_handlers) {
- handlers = (ResourceHandler[]) m_handlers.keySet().toArray(new ResourceHandler[m_handlers.size()]);
- }
- for (int i = 0; i < m_resources.length; i++) {
- for (int j = 0; j < handlers.length; j++) {
- ResourceHandler handler = handlers[j];
- handler.changed(m_resources[i]);
- }
- }
- }
-
- public void add(ServiceReference ref, ResourceHandler handler) {
- String filterString = (String) ref.getProperty("filter");
- Filter filter = null;
- if (filterString != null) {
- try {
- filter = m_context.createFilter(filterString);
- }
- catch (InvalidSyntaxException e) {
- Assert.fail("Could not create filter for resource handler: " + e);
- return;
- }
- }
- synchronized (m_handlers) {
- m_handlers.put(handler, filter);
- }
- for (int i = 0; i < m_resources.length; i++) {
- if (filter == null || filter.match(ResourceUtil.createProperties(m_resources[i]))) {
- handler.added(m_resources[i]);
- }
- }
- }
-
- public void remove(ServiceReference ref, ResourceHandler handler) {
- Filter filter;
- synchronized (m_handlers) {
- filter = (Filter) m_handlers.remove(handler);
- }
- removeResources(handler, filter);
- }
-
- private void removeResources(ResourceHandler handler, Filter filter) {
- for (int i = 0; i < m_resources.length; i++) {
- if (filter == null || filter.match(ResourceUtil.createProperties(m_resources[i]))) {
- handler.removed(m_resources[i]);
- }
- }
- }
-
- public void destroy() {
- Entry[] handlers;
- synchronized (m_handlers) {
- handlers = (Entry[]) m_handlers.entrySet().toArray(new Entry[m_handlers.size()]);
- }
- for (int i = 0; i < handlers.length; i++) {
- removeResources((ResourceHandler) handlers[i].getKey(), (Filter) handlers[i].getValue());
- }
- }
- }
-
- static interface ServiceInterface {
- public void invoke();
- }
-
- static class ServiceProvider {
- private final Ensure m_ensure;
- public ServiceProvider(Ensure e) {
- m_ensure = e;
- }
- void add(ServiceInterface i) {
- m_ensure.step(2);
- }
- void change(ServiceInterface i) {
- System.out.println("Change...");
- m_ensure.step(4);
- }
- void remove(ServiceInterface i) {
- System.out.println("Remove...");
- }
- }
-
- static class CallbackInstance {
- private final Ensure m_ensure;
- public CallbackInstance(Ensure e) {
- m_ensure = e;
- }
-
- void init() {
- System.out.println("init");
- }
- void start() {
- System.out.println("start");
- m_ensure.step(1);
- }
- void stop() {
- System.out.println("stop");
- }
- void destroy() {
- System.out.println("destroy");
- }
- void changed(Component component) {
- System.out.println("resource changed");
- m_ensure.step(3);
-
- Properties newProps = new Properties();
- // update the component's service properties
- Dictionary dict = component.getServiceProperties();
- Enumeration e = dict.keys();
- while (e.hasMoreElements()) {
- String key = (String) e.nextElement();
- String value = (String) dict.get(key);
- newProps.setProperty(key, value);
- }
- newProps.setProperty("new-property", "2");
- component.getServiceRegistration().setProperties(newProps);
- }
- }
-}
diff --git a/dependencymanager/test/src/test/java/org/apache/felix/dm/test/integration/api/SharingDependenciesWithMultipleServicesTest.java b/dependencymanager/test/src/test/java/org/apache/felix/dm/test/integration/api/SharingDependenciesWithMultipleServicesTest.java
deleted file mode 100644
index 608f7ff..0000000
--- a/dependencymanager/test/src/test/java/org/apache/felix/dm/test/integration/api/SharingDependenciesWithMultipleServicesTest.java
+++ /dev/null
@@ -1,273 +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.felix.dm.test.integration.api;
-
-import java.net.URL;
-import java.util.Dictionary;
-import java.util.Hashtable;
-
-import org.apache.felix.dm.BundleDependency;
-import org.apache.felix.dm.Component;
-import org.apache.felix.dm.ConfigurationDependency;
-import org.apache.felix.dm.DependencyManager;
-import org.apache.felix.dm.ResourceDependency;
-import org.apache.felix.dm.ResourceHandler;
-import org.apache.felix.dm.ResourceUtil;
-import org.apache.felix.dm.ServiceDependency;
-import org.apache.felix.dm.test.components.Ensure;
-import org.apache.felix.dm.test.integration.common.TestBase;
-import org.junit.Test;
-import org.junit.runner.RunWith;
-import org.ops4j.pax.exam.junit.PaxExam;
-import org.osgi.framework.BundleContext;
-import org.osgi.framework.Filter;
-import org.osgi.framework.InvalidSyntaxException;
-import org.osgi.framework.ServiceReference;
-import org.osgi.service.cm.ConfigurationAdmin;
-import org.osgi.service.cm.ConfigurationException;
-import org.osgi.service.cm.ManagedService;
-
-@RunWith(PaxExam.class)
-public class SharingDependenciesWithMultipleServicesTest extends TestBase {
- @Test
- public void testShareServiceDependencyWithMultipleServices() {
- DependencyManager m = new DependencyManager(context);
- // helper class that ensures certain steps get executed in sequence
- Ensure e = new Ensure();
- // create a service provider and consumer
- Component provider = m.createComponent().setImplementation(new ServiceProvider()).setInterface(ServiceInterface.class.getName(), null);
- ServiceDependency dependency = m.createServiceDependency().setService(ServiceInterface.class).setRequired(true);
- Component consumer1 = m.createComponent().setImplementation(new ServiceConsumer(e, 1)).add(dependency);
- Component consumer2 = m.createComponent().setImplementation(new ServiceConsumer(e, 4)).add(dependency);
-
- m.add(provider);
- m.add(consumer1);
- e.waitForStep(3, 15000);
- m.add(consumer2);
- e.waitForStep(6, 15000);
- m.remove(provider);
- m.remove(consumer1);
- m.remove(consumer2);
- }
-
- @Test
- public void testShareConfigurationDependencyWithMultipleServices() {
- DependencyManager m = new DependencyManager(context);
- // helper class that ensures certain steps get executed in sequence
- Ensure e = new Ensure();
- // create a service provider and consumer
- Component provider = m.createComponent().setImplementation(new ConfigurationProvider(e)).add(m.createServiceDependency().setService(ConfigurationAdmin.class).setRequired(true));
- ConfigurationDependency dependency = m.createConfigurationDependency().setPid("test");
- Component consumer1 = m.createComponent().setImplementation(new ConfigurationConsumer(e, 2)).add(dependency);
- Component consumer2 = m.createComponent().setImplementation(new ConfigurationConsumer(e, 3)).add(dependency);
-
- // add the configuration provider that should publish the configuration as step 1
- m.add(provider);
- // add the first consumer, and wait until its updated() method is invoked
- m.add(consumer1);
- e.waitForStep(2, 15000);
-
- // add the second consumer, and wait until its updated() method is invoked
- m.add(consumer2);
- e.waitForStep(3, 15000);
-
- // break down the test again
- m.remove(consumer2);
- m.remove(consumer1);
- m.remove(provider);
- }
-
- @Test
- public void testShareBundleDependencyWithMultipleServices() {
- DependencyManager m = new DependencyManager(context);
- // helper class that ensures certain steps get executed in sequence
- Ensure e = new Ensure();
- // create a service provider and consumer
- BundleDependency dependency = m.createBundleDependency().setFilter("(Bundle-SymbolicName=org.apache.felix.dependencymanager)").setRequired(true);
- Component consumer1 = m.createComponent().setImplementation(new BundleConsumer(e, 1)).add(dependency);
- Component consumer2 = m.createComponent().setImplementation(new BundleConsumer(e, 2)).add(dependency);
-
- m.add(consumer1);
- e.waitForStep(1, 15000);
- m.add(consumer2);
- e.waitForStep(2, 15000);
- m.remove(consumer2);
- m.remove(consumer1);
- }
-
- @Test
- public void testShareResourceDependencyWithMultipleServices() throws Exception {
- DependencyManager m = new DependencyManager(context);
- // helper class that ensures certain steps get executed in sequence
- Ensure e = new Ensure();
- // create a service provider and consumer
- ResourceDependency dependency = m.createResourceDependency().setFilter("(" + ResourceHandler.HOST + "=localhost)").setRequired(true);
- Component consumer1 = m.createComponent().setImplementation(new ResourceConsumer(e, 1)).add(dependency);
- Component consumer2 = m.createComponent().setImplementation(new ResourceConsumer(e, 2)).add(dependency);
- Component resourceProvider = m.createComponent().setImplementation(new ResourceProvider()).add(m.createServiceDependency().setService(ResourceHandler.class).setCallbacks("add", "remove"));;
- m.add(resourceProvider);
- m.add(consumer1);
- e.waitForStep(1, 15000);
- m.add(consumer2);
- e.waitForStep(2, 15000);
- m.remove(consumer2);
- m.remove(consumer1);
- m.remove(resourceProvider);
- }
-
-
- static interface ServiceInterface {
- public void invoke(Runnable r);
- }
-
- static class ServiceProvider implements ServiceInterface {
- public void invoke(Runnable r) {
- r.run();
- }
- }
-
- static class ServiceConsumer implements Runnable {
- private volatile ServiceInterface m_service;
- private final Ensure m_ensure;
- private int m_step;
-
- public ServiceConsumer(Ensure e, int step) {
- m_ensure = e;
- m_step = step;
- }
-
- public void start() {
- Thread t = new Thread(this);
- t.start();
- }
-
- public void run() {
- m_ensure.step(m_step);
- m_service.invoke(new Runnable() { public void run() { m_ensure.step(m_step + 1); } });
- m_ensure.step(m_step + 2);
- }
- }
-
- static class ConfigurationConsumer implements ManagedService {
- private final Ensure m_ensure;
- private int m_step;
-
- public ConfigurationConsumer(Ensure e, int step) {
- m_ensure = e;
- m_step = step;
- }
-
- public void updated(Dictionary properties) throws ConfigurationException {
- if (properties != null) {
- m_ensure.step(m_step);
- }
- }
- }
-
- static class ConfigurationProvider {
- private final Ensure m_ensure;
- private volatile ConfigurationAdmin m_configAdmin;
-
- public ConfigurationProvider(Ensure ensure) {
- m_ensure = ensure;
- }
-
- public void init() {
- try {
- org.osgi.service.cm.Configuration conf = m_configAdmin.getConfiguration("test", null);
- conf.update(new Hashtable() {{ put("testkey", "testvalue"); }} );
- m_ensure.step(1);
- }
- catch (Exception e) {
- e.printStackTrace();
- }
- }
- }
-
- static class BundleConsumer {
- private final Ensure m_ensure;
- private int m_step;
-
- public BundleConsumer(Ensure e, int step) {
- m_ensure = e;
- m_step = step;
- }
-
- public void start() {
- m_ensure.step(m_step);
- }
- }
-
- static class ResourceConsumer {
- private final Ensure m_ensure;
- private int m_step;
-
- public ResourceConsumer(Ensure e, int step) {
- m_ensure = e;
- m_step = step;
- }
-
- public void start() {
- m_ensure.step(m_step);
- }
- }
-
- static class ResourceProvider {
- private volatile BundleContext m_context;
- private URL[] m_resources;
-
- public ResourceProvider() throws Exception {
- m_resources = new URL[] {
- new URL("file://localhost/path/to/test1.txt"),
- new URL("file://localhost/path/to/test2.txt")
- };
-
- }
-
- public void add(ServiceReference ref, ResourceHandler handler) {
- String filterString = (String) ref.getProperty("filter");
- try {
- Filter filter = m_context.createFilter(filterString);
- for (int i = 0; i < m_resources.length; i++) {
- if (filter.match(ResourceUtil.createProperties(m_resources[i]))) {
- handler.added(m_resources[i]);
- }
- }
- }
- catch (InvalidSyntaxException e) {
- e.printStackTrace();
- }
- }
-
- public void remove(ServiceReference ref, ResourceHandler handler) {
- String filterString = (String) ref.getProperty("filter");
- try {
- Filter filter = m_context.createFilter(filterString);
- for (int i = 0; i < m_resources.length; i++) {
- if (filter.match(ResourceUtil.createProperties(m_resources[i]))) {
- handler.removed(m_resources[i]);
- }
- }
- }
- catch (InvalidSyntaxException e) {
- e.printStackTrace();
- }
- }
- }
-}
diff --git a/dependencymanager/test/src/test/java/org/apache/felix/dm/test/integration/api/TemporalServiceDependencyTest.java b/dependencymanager/test/src/test/java/org/apache/felix/dm/test/integration/api/TemporalServiceDependencyTest.java
deleted file mode 100644
index c7bf84b..0000000
--- a/dependencymanager/test/src/test/java/org/apache/felix/dm/test/integration/api/TemporalServiceDependencyTest.java
+++ /dev/null
@@ -1,107 +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.felix.dm.test.integration.api;
-
-import org.apache.felix.dm.Component;
-import org.apache.felix.dm.DependencyManager;
-import org.apache.felix.dm.test.components.Ensure;
-import org.apache.felix.dm.test.integration.common.TestBase;
-import org.junit.Test;
-import org.junit.runner.RunWith;
-import org.ops4j.pax.exam.junit.PaxExam;
-
-@RunWith(PaxExam.class)
-public class TemporalServiceDependencyTest extends TestBase {
- @Test
- public void testServiceConsumptionAndIntermittentAvailability() {
- DependencyManager m = new DependencyManager(context);
- // helper class that ensures certain steps get executed in sequence
- Ensure e = new Ensure();
- // create a service provider and consumer
- Component sp = m.createComponent().setImplementation(new TemporalServiceProvider(e)).setInterface(TemporalServiceInterface.class.getName(), null);
- Component sp2 = m.createComponent().setImplementation(new TemporalServiceProvider2(e)).setInterface(TemporalServiceInterface.class.getName(), null);
- Component sc = m.createComponent().setImplementation(new TemporalServiceConsumer(e)).add(m.createTemporalServiceDependency().setService(TemporalServiceInterface.class).setRequired(true));
- // add the service consumer
- m.add(sc);
- // now add the first provider
- m.add(sp);
- e.waitForStep(2, 15000);
- // and remove it again (this should not affect the consumer yet)
- m.remove(sp);
- // now add the second provider
- m.add(sp2);
- e.step(3);
- e.waitForStep(4, 15000);
- // and remove it again
- m.remove(sp2);
- // finally remove the consumer
- m.remove(sc);
- // ensure we executed all steps inside the component instance
- e.step(6);
- }
-
- static interface TemporalServiceInterface {
- public void invoke();
- }
-
- static class TemporalServiceProvider implements TemporalServiceInterface {
- private final Ensure m_ensure;
- public TemporalServiceProvider(Ensure e) {
- m_ensure = e;
- }
- public void invoke() {
- m_ensure.step(2);
- }
- }
-
- static class TemporalServiceProvider2 implements TemporalServiceInterface {
- private final Ensure m_ensure;
- public TemporalServiceProvider2(Ensure e) {
- m_ensure = e;
- }
- public void invoke() {
- m_ensure.step(4);
- }
- }
-
- static class TemporalServiceConsumer implements Runnable {
- private volatile TemporalServiceInterface m_service;
- private final Ensure m_ensure;
-
- public TemporalServiceConsumer(Ensure e) {
- m_ensure = e;
- }
-
- public void init() {
- m_ensure.step(1);
- Thread t = new Thread(this);
- t.start();
- }
-
- public void run() {
- m_service.invoke();
- m_ensure.waitForStep(3, 15000);
- m_service.invoke();
- }
-
- public void destroy() {
- m_ensure.step(5);
- }
- }
-}
diff --git a/dependencymanager/test/src/test/java/org/apache/felix/dm/test/integration/common/TestBase.java b/dependencymanager/test/src/test/java/org/apache/felix/dm/test/integration/common/TestBase.java
deleted file mode 100644
index 18fb633..0000000
--- a/dependencymanager/test/src/test/java/org/apache/felix/dm/test/integration/common/TestBase.java
+++ /dev/null
@@ -1,393 +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.felix.dm.test.integration.common;
-
-import static org.ops4j.pax.exam.CoreOptions.bundle;
-import static org.ops4j.pax.exam.CoreOptions.bootDelegationPackages;
-import static org.ops4j.pax.exam.CoreOptions.cleanCaches;
-import static org.ops4j.pax.exam.CoreOptions.junitBundles;
-import static org.ops4j.pax.exam.CoreOptions.mavenBundle;
-import static org.ops4j.pax.exam.CoreOptions.options;
-import static org.ops4j.pax.exam.CoreOptions.systemProperty;
-import static org.ops4j.pax.exam.CoreOptions.systemTimeout;
-import static org.ops4j.pax.exam.CoreOptions.vmOption;
-import static org.ops4j.pax.exam.CoreOptions.workingDirectory;
-
-import java.io.File;
-import java.io.PrintWriter;
-import java.io.StringWriter;
-import java.util.Hashtable;
-
-import javax.inject.Inject;
-
-import org.apache.felix.dm.test.components.Ensure;
-import org.junit.After;
-import org.junit.Before;
-import org.ops4j.pax.exam.Configuration;
-import org.ops4j.pax.exam.Option;
-import org.ops4j.pax.exam.OptionUtils;
-import org.ops4j.pax.exam.ProbeBuilder;
-import org.ops4j.pax.exam.TestProbeBuilder;
-import org.osgi.framework.Bundle;
-import org.osgi.framework.BundleContext;
-import org.osgi.framework.BundleException;
-import org.osgi.framework.Constants;
-import org.osgi.framework.FrameworkEvent;
-import org.osgi.framework.FrameworkListener;
-import org.osgi.framework.ServiceReference;
-import org.osgi.framework.ServiceRegistration;
-import org.osgi.service.log.LogService;
-import org.slf4j.LoggerFactory;
-
-import ch.qos.logback.classic.Level;
-import ch.qos.logback.classic.Logger;
-
-/**
- * Base class for all integration tests.
- */
-public abstract class TestBase implements LogService, FrameworkListener {
- // Default OSGI log service level.
- private final static int LOG_LEVEL = LogService.LOG_WARNING;
-
- // Flag used to check if some errors have been logged during the execution of a given test.
- private volatile boolean m_errorsLogged;
-
- // The name of the system property providing the bundle file to be installed and tested.
- protected static final String TESTBUNDLE_FILE = "project.bundle.file";
-
- // The default bundle jar file name
- protected static final String TESTBUNDLE_FILE_DEF = "target/org.apache.felix.dependencymanager.test-3.2.0-SNAPSHOT.jar";
-
- // The name of the system property providing the test bundle symbolic name.
- protected static final String TESTBUNDLE_SN = "project.bundle.symbolicName";
-
- // The default symbolic name for our test bundle
- protected static final String TESTBUNDLE_SN_DEF = "org.apache.felix.dependencymanager.test";
-
- // The package exported by our test bundle, which we import from all integration tests.
- private static final String TESTBUNDLE_PACKAGE = "org.apache.felix.dm.test.components, org.apache.felix.service.command;status=provisional";
-
- // The actual JVM option set, extensions may implement a static
- // initializer overwriting this value to have the configuration()
- // method include it when starting the OSGi framework JVM
- protected static String paxRunnerVmOption = null;
-
- // Bundle context injected by pax-exam for each integration test.
- @Inject
- protected BundleContext context;
-
- // We implement OSGI log service.
- protected ServiceRegistration logService;
-
- // Flag used to check if our test bundle (src/main/java/**/*) bundle must be started
- // (true for annotation based integration tests)
- private final boolean m_startTestBundle;
-
- /**
- * Default constructor. By default, we don't start the bundle generated by this project.
- * (the test bundle (src/main/java/...) contains some annotated components only meant to be
- * used by annotation based tests.
- */
- public TestBase() {
- this(false);
- }
-
- /**
- * Creates a new TestBase instance.
- * @param startTestBundle true if the test bundle must be started, false if not.
- */
- public TestBase(boolean startTestBundle) {
- m_startTestBundle = startTestBundle;
- }
-
- /**
- * Pax Exam Configuration.
- */
- @Configuration
- public Option[] configuration() {
- final String testBundle = System.getProperty(TESTBUNDLE_FILE, TESTBUNDLE_FILE_DEF);
- final File testBundleFile = new File(testBundle);
- if (!testBundleFile.canRead()) {
- throw new IllegalArgumentException("Cannot read from test bundle file " + testBundle
- + " specified in the " + TESTBUNDLE_FILE + " system property");
- }
-
- // Reduce pax exam log level.
- Logger root = (Logger) LoggerFactory.getLogger(Logger.ROOT_LOGGER_NAME);
- root.setLevel(Level.WARN);
-
- final Option[] base = options(
- workingDirectory("target/paxexam/"),
- systemProperty("dm.runtime.log").value("false"),
- systemProperty("org.ops4j.pax.logging.DefaultServiceLog.level").value("WARN"),
- //vmOption("-Xrunjdwp:transport=dt_socket,server=y,suspend=y,address=5005"),
- systemTimeout(15000),
- cleanCaches(true),
- junitBundles(),
- bootDelegationPackages("org.netbeans.*"), // For jvisualvm
- mavenBundle("org.apache.felix", "org.apache.felix.metatype", "1.0.8"),
- mavenBundle("org.apache.felix", "org.apache.felix.configadmin", "1.8.0"),
- mavenBundle("org.apache.felix", "org.apache.felix.eventadmin", "1.3.2"),
- mavenBundle("org.apache.felix", "org.apache.felix.gogo.runtime", "0.10.0"),
- mavenBundle("org.apache.felix", "org.apache.felix.deploymentadmin", "0.9.0").start(false),
- mavenBundle("org.ops4j.pax.tinybundles", "tinybundles", "1.0.0"),
- mavenBundle("org.apache.felix", "org.apache.felix.dependencymanager","3.2.1-SNAPSHOT"),
- mavenBundle("org.apache.felix", "org.apache.felix.dependencymanager.shell", "3.2.1-SNAPSHOT"),
- mavenBundle("org.apache.felix", "org.apache.felix.dependencymanager.runtime", "3.2.1-SNAPSHOT"),
- bundle(testBundleFile.toURI().toString()).start(m_startTestBundle));
- final Option option = (paxRunnerVmOption != null) ? vmOption(paxRunnerVmOption) : null;
- return OptionUtils.combine(base, option);
- }
-
- /**
- * pax exam hook used to customize the OSGI manifest of the bundle generated for each integration test.
- */
- @ProbeBuilder
- public TestProbeBuilder buildProbe(TestProbeBuilder builder) {
- // We import the package exported by our test bundle (src/main/java/*), which contains:
- //
- // - the Ensure helper (used by ALL tests)
- // - some Annotated components (only used by annotation based tests).
- return builder.setHeader(Constants.IMPORT_PACKAGE, TESTBUNDLE_PACKAGE);
- }
-
- /**
- * Test initialization.
- */
- @Before
- public void setUp() {
- logService = context.registerService(LogService.class.getName(), this, null);
- context.addFrameworkListener(this);
- }
-
- /**
- * Test shutdown
- */
- @After
- public void tearDown() throws BundleException {
- logService.unregister();
- context.removeFrameworkListener(this);
- }
-
- /**
- * Creates and provides an Ensure object with a name service property into the OSGi service registry.
- */
- protected ServiceRegistration register(Ensure e, String name) {
- Hashtable<String, String> props = new Hashtable<String, String>();
- props.put("name", name);
- return context.registerService(Ensure.class.getName(), e, props);
- }
-
- /**
- * Helper method used to stop a given bundle.
- *
- * @param symbolicName
- * the symbolic name of the bundle to be stopped.
- */
- protected void stopBundle(String symbolicName) {
- // Stop the test.annotation bundle
- boolean found = false;
- for (Bundle b : context.getBundles()) {
- if (b.getSymbolicName().equals(symbolicName)) {
- try {
- found = true;
- b.stop();
- } catch (BundleException e) {
- e.printStackTrace();
- }
- }
- }
- if (!found) {
- throw new IllegalStateException("bundle " + symbolicName + " not found");
- }
- }
-
- /**
- * Helper method used to get a given bundle.
- *
- * @param symbolicName
- * the symbolic name of the bundle to get.
- */
- protected Bundle getBundle(String symbolicName) {
- for (Bundle b : context.getBundles()) {
- if (b.getSymbolicName().equals(symbolicName)) {
- return b;
- }
- }
- throw new IllegalStateException("bundle " + symbolicName + " not found");
- }
-
- /**
- * Stops our test bundle.
- */
- protected void stopTestBundle() {
- stopBundle(System.getProperty(TESTBUNDLE_SN, TESTBUNDLE_SN_DEF));
- }
-
- /**
- * Suspend the current thread for a while.
- *
- * @param n
- * the number of milliseconds to wait for.
- */
- protected void sleep(int ms) {
- try {
- Thread.sleep(ms);
- } catch (InterruptedException e) {
- }
- }
-
- public void log(int level, String message) {
- checkError(level, null);
- if (LOG_LEVEL >= level) {
- System.out.println(getLevel(level) + " - " + Thread.currentThread().getName() + " : " + message);
- }
- }
-
- public void log(int level, String message, Throwable exception) {
- checkError(level, exception);
- if (LOG_LEVEL >= level) {
- StringBuilder sb = new StringBuilder();
- sb.append(getLevel(level) + " - " + Thread.currentThread().getName() + " : ");
- sb.append(message);
- parse(sb, exception);
- System.out.println(sb.toString());
- }
- }
-
- public void log(ServiceReference sr, int level, String message) {
- checkError(level, null);
- if (LOG_LEVEL >= level) {
- StringBuilder sb = new StringBuilder();
- sb.append(getLevel(level) + " - " + Thread.currentThread().getName() + " : ");
- sb.append(message);
- System.out.println(sb.toString());
- }
- }
-
- public void log(ServiceReference sr, int level, String message, Throwable exception) {
- checkError(level, exception);
- if (LOG_LEVEL >= level) {
- StringBuilder sb = new StringBuilder();
- sb.append(getLevel(level) + " - " + Thread.currentThread().getName() + " : ");
- sb.append(message);
- parse(sb, exception);
- System.out.println(sb.toString());
- }
- }
-
- protected boolean errorsLogged() {
- return m_errorsLogged;
- }
-
- private void parse(StringBuilder sb, Throwable t) {
- if (t != null) {
- sb.append(" - ");
- StringWriter buffer = new StringWriter();
- PrintWriter pw = new PrintWriter(buffer);
- t.printStackTrace(pw);
- sb.append(buffer.toString());
- m_errorsLogged = true;
- }
- }
-
- private String getLevel(int level) {
- switch (level) {
- case LogService.LOG_DEBUG :
- return "DEBUG";
- case LogService.LOG_ERROR :
- return "ERROR";
- case LogService.LOG_INFO :
- return "INFO";
- case LogService.LOG_WARNING :
- return "WARN";
- default :
- return "";
- }
- }
-
- private void checkError(int level, Throwable exception) {
- if (level <= LOG_ERROR) {
- m_errorsLogged = true;
- }
- if (exception != null) {
- m_errorsLogged = true;
- }
- }
-
- public void frameworkEvent(FrameworkEvent event) {
- int eventType = event.getType();
- String msg = getFrameworkEventMessage(eventType);
- int level = (eventType == FrameworkEvent.ERROR) ? LOG_ERROR : LOG_WARNING;
- if (msg != null) {
- log(level, msg, event.getThrowable());
- } else {
- log(level, "Unknown fwk event: " + event);
- }
- }
-
- private String getFrameworkEventMessage(int event) {
- switch (event) {
- case FrameworkEvent.ERROR :
- return "FrameworkEvent: ERROR";
- case FrameworkEvent.INFO :
- return "FrameworkEvent INFO";
- case FrameworkEvent.PACKAGES_REFRESHED :
- return "FrameworkEvent: PACKAGE REFRESHED";
- case FrameworkEvent.STARTED :
- return "FrameworkEvent: STARTED";
- case FrameworkEvent.STARTLEVEL_CHANGED :
- return "FrameworkEvent: STARTLEVEL CHANGED";
- case FrameworkEvent.WARNING :
- return "FrameworkEvent: WARNING";
- default :
- return null;
- }
- }
-
- protected void warn(String msg, Object ... params) {
- if (LOG_LEVEL >= LogService.LOG_WARNING) {
- log(LogService.LOG_WARNING, params.length > 0 ? String.format(msg, params) : msg);
- }
- }
-
- protected void info(String msg, Object ... params) {
- if (LOG_LEVEL >= LogService.LOG_INFO) {
- log(LogService.LOG_INFO, params.length > 0 ? String.format(msg, params) : msg);
- }
- }
-
- protected void debug(String msg, Object ... params) {
- if (LOG_LEVEL >= LogService.LOG_DEBUG) {
- log(LogService.LOG_DEBUG, params.length > 0 ? String.format(msg, params) : msg);
- }
- }
-
- protected void error(String msg, Object ... params) {
- log(LogService.LOG_ERROR, params.length > 0 ? String.format(msg, params) : msg);
- }
-
- protected void error(String msg, Throwable err, Object ... params) {
- log(LogService.LOG_ERROR, params.length > 0 ? String.format(msg, params) : msg, err);
- }
-
- protected void error(Throwable err) {
- log(LogService.LOG_ERROR, "error", err);
- }
-}