You are viewing a plain text version of this content. The canonical link for it is here.
Posted to commits@felix.apache.org by pd...@apache.org on 2010/05/23 10:20:51 UTC
svn commit: r947379 [2/2] - in /felix/trunk/dependencymanager: annotation/
annotation/src/main/java/org/apache/felix/dm/annotation/api/
annotation/src/main/java/org/apache/felix/dm/annotation/api/dependency/
annotation/src/main/java/org/apache/felix/dm...
Added: felix/trunk/dependencymanager/runtime/src/main/java/org/apache/felix/dm/runtime/DependencyBuilder.java
URL: http://svn.apache.org/viewvc/felix/trunk/dependencymanager/runtime/src/main/java/org/apache/felix/dm/runtime/DependencyBuilder.java?rev=947379&view=auto
==============================================================================
--- felix/trunk/dependencymanager/runtime/src/main/java/org/apache/felix/dm/runtime/DependencyBuilder.java (added)
+++ felix/trunk/dependencymanager/runtime/src/main/java/org/apache/felix/dm/runtime/DependencyBuilder.java Sun May 23 08:20:50 2010
@@ -0,0 +1,250 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS 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.DependencyManager;
+import org.apache.felix.dm.dependencies.BundleDependency;
+import org.apache.felix.dm.dependencies.ConfigurationDependency;
+import org.apache.felix.dm.dependencies.Dependency;
+import org.apache.felix.dm.dependencies.ResourceDependency;
+import org.apache.felix.dm.dependencies.ServiceDependency;
+import org.apache.felix.dm.dependencies.TemporalServiceDependency;
+import org.osgi.framework.Bundle;
+
+/**
+ * Class used to build a concrete dependency from meta data.
+ */
+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, false, instanceBound);
+ break;
+
+ case TemporalServiceDependency:
+ dp = createServiceDependency(b, dm, true, instanceBound);
+ break;
+
+ case ConfigurationDependency:
+ dp = createConfigurationDependency(dm, instanceBound);
+ break;
+
+ case BundleDependency:
+ dp = createBundleDependency(dm, instanceBound);
+ break;
+
+ case ResourceDependency:
+ dp = createResourceDependency(dm, instanceBound);
+ break;
+ }
+ return dp;
+ }
+
+ private Dependency createServiceDependency(Bundle b, DependencyManager dm, boolean temporal,
+ 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);
+ String changed = temporal ? null : m_metaData.getString(Params.changed, null);
+ String removed = temporal ? 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"));
+ String timeout = m_metaData.getString(Params.timeout, null);
+
+ Dependency dp = createServiceDependency(dm, temporal, serviceClass,
+ serviceFilter, defaultServiceImplClass, added, changed,
+ removed, autoConfigField, timeout, required, instanceBound);
+ return dp;
+ }
+
+ private Dependency createServiceDependency(DependencyManager dm, boolean temporal,
+ Class<?> serviceClass, String serviceFilter, Class<?> defaultServiceImplClass, String added,
+ String changed, String removed, String autoConfigField, String timeout, boolean required,
+ boolean instanceBound)
+ {
+ ServiceDependency sd = temporal ? 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 (temporal)
+ {
+ // Set the timeout value for a temporal service dependency
+ if (timeout != null)
+ {
+ ((TemporalServiceDependency) sd).setTimeout(Long.parseLong(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);
+ 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"));
+
+ Dependency dp = createResourceDependency(dm, added, changed, removed, required, filter, propagate, instanceBound);
+ return dp;
+ }
+
+ private Dependency createResourceDependency(DependencyManager dm, String added,
+ String changed, String removed, boolean required, String filter, boolean propagate, boolean instanceBound)
+ {
+ ResourceDependency rd = dm.createResourceDependency();
+ rd.setCallbacks(added, changed, removed);
+ rd.setRequired(required);
+ if (filter != null)
+ {
+ rd.setFilter(filter);
+ }
+ rd.setPropagate(propagate);
+ rd.setInstanceBound(instanceBound);
+ return rd;
+ }
+}
Added: felix/trunk/dependencymanager/runtime/src/main/java/org/apache/felix/dm/runtime/DependencyManagerRuntime.java
URL: http://svn.apache.org/viewvc/felix/trunk/dependencymanager/runtime/src/main/java/org/apache/felix/dm/runtime/DependencyManagerRuntime.java?rev=947379&view=auto
==============================================================================
--- felix/trunk/dependencymanager/runtime/src/main/java/org/apache/felix/dm/runtime/DependencyManagerRuntime.java (added)
+++ felix/trunk/dependencymanager/runtime/src/main/java/org/apache/felix/dm/runtime/DependencyManagerRuntime.java Sun May 23 08:20:50 2010
@@ -0,0 +1,218 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS 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.DependencyManager;
+import org.apache.felix.dm.service.Service;
+import org.osgi.framework.Bundle;
+import org.osgi.framework.BundleContext;
+import org.osgi.framework.BundleEvent;
+import org.osgi.framework.SynchronousBundleListener;
+import org.osgi.service.log.LogService;
+
+/**
+ * This class parses service descriptors generated by the annotation bnd processor.
+ * The descriptors are located under OSGI-INF/dependencymanager directory. Such files are actually
+ * referenced by a specific "DependendencyManager-Component" manifest header.
+ */
+public class DependencyManagerRuntime implements SynchronousBundleListener
+{
+ private ConcurrentHashMap<Bundle, DependencyManager> m_managers = new ConcurrentHashMap<Bundle, DependencyManager>();
+ private static LogService m_log; // Injected
+ private BundleContext m_bctx; // Injected
+ private DescriptorParser m_parser;
+
+ /**
+ * 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()
+ {
+ // Register our log service.
+ Log.instance().setLogService(m_log);
+
+ // Instantiates our descriptor parser, and register our service builders into it.
+ m_parser = new DescriptorParser();
+ m_parser.addBuilder(new ServiceBuilder());
+ 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());
+
+ // Load already started bundles
+ for (Bundle b: m_bctx.getBundles())
+ {
+ if (b.getState() == Bundle.ACTIVE)
+ {
+ bundleChanged(new BundleEvent(Bundle.ACTIVE, b));
+ }
+ }
+
+ // Track bundles
+ m_bctx.addBundleListener(this);
+ }
+
+ /**
+ * Stops our service. We'll stop all activated DependencyManager services.
+ */
+ @SuppressWarnings("unchecked")
+ protected void stop()
+ {
+ m_log.log(LogService.LOG_INFO, "DependencyManager Runtime stopping: removing services");
+
+ for (DependencyManager dm: m_managers.values())
+ {
+ List<Service> services = new ArrayList<Service>(dm.getServices());
+ for (Service service: services)
+ {
+ m_log.log(LogService.LOG_INFO, "DependencyManager Runtime stopping: removing service: "
+ + service);
+ dm.remove(service);
+ }
+ }
+
+ m_managers.clear();
+ }
+
+ /**
+ * Register a LogService, so other components may use it
+ */
+ protected void bind(LogService logService) {
+ m_log = logService;
+ Log.instance().setLogService(logService);
+ }
+
+ /**
+ * Handle a bundle event, and eventually parse started bundles.
+ */
+ public void bundleChanged(BundleEvent event)
+ {
+ Bundle b = event.getBundle();
+ if (b.getState() == Bundle.ACTIVE)
+ {
+ bundleStarted(b);
+ }
+ else if (b.getState() == Bundle.STOPPING)
+ {
+ bundleStopping(b);
+ }
+ }
+
+ /**
+ * Checks if a started bundle have some DependencyManager descriptors
+ * referenced in the "DependencyManager-Component" OSGi header.
+ * @param b the started bundle.
+ */
+ void bundleStarted(Bundle b)
+ {
+ String descriptorPaths = (String) b.getHeaders().get("DependencyManager-Component");
+ if (descriptorPaths == null)
+ {
+ return;
+ }
+
+ for (String descriptorPath: descriptorPaths.split(","))
+ {
+ URL descriptorURL = b.getEntry(descriptorPath);
+ if (descriptorURL == null)
+ {
+ m_log.log(LogService.LOG_ERROR,
+ "DependencyManager component descriptor not found: " + descriptorPath);
+ continue;
+ }
+ loadDescriptor(b, descriptorURL);
+ }
+ }
+
+ /**
+ * Unregisters all services for a stopping bundle.
+ * @param b
+ */
+ @SuppressWarnings("unchecked")
+ private void bundleStopping(Bundle b)
+ {
+ m_log.log(LogService.LOG_INFO, "Removing services from stopping bundle: " + b.getSymbolicName());
+ DependencyManager dm = m_managers.remove(b);
+ if (dm != null)
+ {
+ List<Service> services = new ArrayList(dm.getServices());
+ for (Service service: services)
+ {
+ m_log.log(LogService.LOG_INFO, "Removing service service: " + service);
+ dm.remove(service);
+ }
+ }
+ }
+
+ /**
+ * Load a DependencyManager component descriptor from a given bundle.
+ * @param b
+ * @param descriptorURL
+ */
+ private void loadDescriptor(Bundle b, URL descriptorURL)
+ {
+ m_log.log(LogService.LOG_DEBUG, "Parsing descriptor " + descriptorURL
+ + " from bundle " + 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);
+ m_managers.put(b, dm);
+ }
+
+ catch (Throwable t)
+ {
+ m_log.log(LogService.LOG_ERROR, "Error while parsing descriptor "
+ + descriptorURL + " from bundle " + b.getSymbolicName(), t);
+ }
+
+ finally
+ {
+ if (in != null)
+ {
+ try
+ {
+ in.close();
+ }
+ catch (IOException ignored)
+ {
+ }
+ }
+ }
+ }
+}
\ No newline at end of file
Modified: felix/trunk/dependencymanager/runtime/src/main/java/org/apache/felix/dm/runtime/DescriptorParser.java
URL: http://svn.apache.org/viewvc/felix/trunk/dependencymanager/runtime/src/main/java/org/apache/felix/dm/runtime/DescriptorParser.java?rev=947379&r1=947378&r2=947379&view=diff
==============================================================================
--- felix/trunk/dependencymanager/runtime/src/main/java/org/apache/felix/dm/runtime/DescriptorParser.java (original)
+++ felix/trunk/dependencymanager/runtime/src/main/java/org/apache/felix/dm/runtime/DescriptorParser.java Sun May 23 08:20:50 2010
@@ -18,323 +18,58 @@
*/
package org.apache.felix.dm.runtime;
+import java.io.BufferedReader;
import java.util.ArrayList;
-import java.util.Arrays;
-import java.util.Dictionary;
import java.util.HashMap;
-import java.util.Hashtable;
import java.util.List;
import java.util.Map;
-import java.util.regex.Matcher;
-import java.util.regex.Pattern;
+import org.apache.felix.dm.DependencyManager;
+import org.json.JSONObject;
+import org.osgi.framework.Bundle;
import org.osgi.service.log.LogService;
/**
* This class parses files generated in OSGI-INF/*.dm by the DependencyManager bnd plugin.
- * Each descriptor contains the definition of a Service, along with its corresponding service dependency or configuration dependencies.
- * Here is an example of a typical descriptor syntax:
- *
- * Service: start=start; stop=stop; impl=org.apache.felix.dm.test.annotation.ServiceConsumer;
- * ServiceDependency: service=org.apache.felix.dm.test.annotation.ServiceInterface; autoConfig=m_service;
- * ServiceDependency: added=bind; service=org.apache.felix.dm.test.annotation.ServiceInterface;
- *
- * Notice that the descriptor must start with a "Service" definition. (Dependencies must be declared after the "Service" entry).
- * <p>
- *
- * Now, here is the formal BNF definition of the descriptor syntax:
- *
- * line := <type> ':' <params>
- *
- * type := service|aspectservice|serviceDependency|configurationDependency|temporalServiceDependency
- * service := 'Service'
- * aspectservice := 'AspectService'
- * serviceDependency := 'ServiceDependency'
- * configurationDependency := 'ConfigurationDependency'
- * temporalServiceDependency := 'TemporalServiceDependency'
- *
- * params := paramName '=' paramValue ( ';' paramName '=' paramValue )*
- *
- * paramName := init | start | stop | destroy | impl | provide | properties | factory | factoryMethod | composition | service | filter |
- * defaultImpl | required | added | changed | removed | autoConfig | pid | propagate | updated | timeout |
- * adapterService | adapterProperties | adapteeService | adapteeFilter
- * init := 'init'
- * start := 'start'
- * stop := 'stop'
- * destroy := 'destroy'
- * impl := 'impl'
- * provide := 'provide'
- * properties := 'properties'
- * factory := 'factory'
- * factoryMethod := 'factoryMethod'
- * composition := 'composition'
- * service := 'service'
- * filter := 'filter'
- * defaultImpl := 'defaultImpl'
- * required := 'required'
- * added := 'added'
- * changed := 'changed'
- * removed := 'removed'
- * autoConfig := 'autoConfig'
- * pid := 'pid'
- * propagate := 'propagate'
- * updated := 'updated'
- * timeout := 'timeout'
- * adapterService := 'adapterService'
- * adapterProperties := 'adapterProperties'
- * adapteeService := 'adapteeService'
- * adapteeFilter := 'adapteeFilter'
- *
- * paramValue := strings | attributes
- * strings := string ( ',' string )*
- * attributes := string ':' string ( ',' string : string )*
- * string := [alphanum string]
+ * Each descriptor contains a JSON definition of a Service, along with its corresponding service dependency or configuration dependencies.
*/
public class DescriptorParser
{
- private LogService m_logService;
- private Map<DescriptorParam, Object> m_params = new HashMap<DescriptorParam, Object>();
+ private Map<String, ServiceComponentBuilder> m_builders = new HashMap<String, ServiceComponentBuilder>();
- private final static Pattern linePattern = Pattern.compile("(\\w+):\\s*(.*)", Pattern.COMMENTS);
- private final static Pattern paramPattern = Pattern.compile("([^=]+)=([^;]+);?");
- private final static Pattern stringsPattern = Pattern.compile("([^,]+)");
- private final static Pattern attributesPattern = Pattern.compile("([^:]+):([^,]+),?");
-
- public DescriptorParser(LogService service)
- {
- m_logService = service;
- }
-
- /*
- * Parses a DependencyManager component descriptor entry (either a Service, a ServiceDependency, or a ConfigurationDependency entry).
- * @return DescriptorEntry.Service, DescriptorEntry.ServiceDependency, or DescriptorEntry.ConfigurationDependency
- */
- public DescriptorEntry parse(String line)
- {
- m_params.clear();
- Matcher lineMatcher = linePattern.matcher(line);
- if (lineMatcher.matches())
- {
- DescriptorEntry entry = DescriptorEntry.valueOf(lineMatcher.group(1).trim());
- Matcher paramMatcher = paramPattern.matcher(lineMatcher.group(2).trim());
- while (paramMatcher.find())
- {
- DescriptorParam paramName = DescriptorParam.valueOf(paramMatcher.group(1).trim());
- String paramValue = paramMatcher.group(2).trim();
- Matcher attributesMatcher = attributesPattern.matcher(paramValue);
- boolean matched = false;
-
- Hashtable<String, String> attributes = new Hashtable<String, String>();
- while (attributesMatcher.find())
- {
- matched = true;
- attributes.put(attributesMatcher.group(1).trim(),
- attributesMatcher.group(2).trim());
- }
- m_params.put(paramName, attributes);
-
- if (!matched)
- {
- Matcher stringsMatcher = stringsPattern.matcher(paramValue);
- if (stringsMatcher.groupCount() > 0)
- {
- List<String> strings = new ArrayList<String>();
- while (stringsMatcher.find())
- {
- strings.add(stringsMatcher.group(1).trim());
- }
- m_params.put(paramName, strings.toArray(new String[strings.size()]));
- }
- }
- }
-
- m_logService.log(LogService.LOG_DEBUG, "Parsed " + entry + ": " + toString());
- return entry;
- }
- else
- {
- throw new IllegalArgumentException("Invalid descriptor entry: " + line);
- }
- }
-
- /**
- * Once a component descriptor entry line is parsed, you can retrieve entry attributes using this method.
- * @param param
- * @return
- */
- public String getString(DescriptorParam param)
- {
- Object value = m_params.get(param);
- if (value == null)
- {
- throw new IllegalArgumentException("Parameter " + param + " not found");
- }
- if (!(value instanceof String[]))
- {
- throw new IllegalArgumentException("Parameter " + param + " not a String array");
- }
- String[] array = (String[]) value;
- if (array.length < 1)
- {
- throw new IllegalArgumentException("Parameter " + param + " not found");
- }
- return (array[0]);
- }
-
- /**
- * Once a component descriptor entry line is parsed, you can retrieve entry attributes using this method.
- *
- * @param param
- * @param def
- * @return
- */
- public String getString(DescriptorParam param, String def)
- {
- try
- {
- return getString(param);
- }
- catch (IllegalArgumentException e)
- {
- return def;
- }
- }
-
- /**
- * Once a component descriptor entry line is parsed, you can retrieve entry attributes using this method.
- *
- * @param param
- * @param def
- * @return
- */
- public int getInt(DescriptorParam param)
+ public void addBuilder(ServiceComponentBuilder sb)
{
- String value = getString(param, null);
- if (value != null)
- {
- try
- {
- return Integer.parseInt(value);
- }
- catch (NumberFormatException e)
- {
- throw new IllegalArgumentException("parameter " + param + " is not an int value: "
- + value);
- }
- }
- else
- {
- throw new IllegalArgumentException("missing " + param + " parameter from annotation");
- }
+ m_builders.put(sb.getType(), sb);
}
- /**
- * Once a component descriptor entry line is parsed, you can retrieve entry attributes using this method.
- *
- * @param param
- * @param def
- * @return
- */
- public int getInt(DescriptorParam param, int def)
+ public void parse(BufferedReader reader, Bundle b, DependencyManager dm) throws Exception
{
- String value = getString(param, null);
- if (value != null)
- {
- try
- {
- return Integer.parseInt(value);
- }
- catch (NumberFormatException e)
- {
- throw new IllegalArgumentException("parameter " + param + " is not an int value: "
- + value);
- }
- }
- else
- {
- return def;
- }
- }
+ String line;
- /**
- * Once a component descriptor entry line is parsed, you can retrieve entry attributes using this method.
- * @param param
- * @return
- */
- public String[] getStrings(DescriptorParam param)
- {
- Object value = m_params.get(param);
- if (value == null)
- {
- throw new IllegalArgumentException("Parameter " + param + " not found");
- }
- if (!(value instanceof String[]))
- {
- throw new IllegalArgumentException("Parameter " + param + " not a String array");
- }
- return (String[]) value;
- }
+ // The first line is a Service Component (a Service, an Aspect Service, etc ...)
+ line = reader.readLine();
+ Log.instance().log(LogService.LOG_DEBUG, "Parsing destriptor entry line: " + line);
+ JSONObject json = new JSONObject(line);
+ JSONMetaData serviceMetaData = new JSONMetaData(json);
- /**
- * Once a component descriptor entry line is parsed, you can retrieve entry attributes using this method.
- * @param param
- * @return
- */
- public String[] getStrings(DescriptorParam param, String[] def)
- {
- try
+ String type = (String) json.get("type");
+ ServiceComponentBuilder builder = m_builders.get(type);
+ if (builder == null)
{
- return getStrings(param);
+ throw new IllegalArgumentException("Invalid descriptor"
+ + ": no \"type\" parameter found in first line");
}
- catch (IllegalArgumentException e)
- {
- return def;
- }
- }
- /**
- * Once a component descriptor entry line is parsed, you can retrieve entry attributes using this method.
- * @param param
- * @return
- */
- @SuppressWarnings("unchecked")
- public Dictionary<String, String> getDictionary(DescriptorParam param, Dictionary<String, String> def)
- {
- Object value = m_params.get(param);
- if (value == null)
- {
- return def;
- }
- if (!(value instanceof Dictionary))
+ // Parse the rest of the lines (dependencies)
+ List<MetaData> serviceDependencies = new ArrayList<MetaData>();
+ while ((line = reader.readLine()) != null)
{
- throw new IllegalArgumentException("Parameter " + param + " not Dictionary");
+ Log.instance().log(LogService.LOG_DEBUG, "Parsing destriptor entry line: " + line);
+ JSONObject dep = new JSONObject(line);
+ serviceDependencies.add(new JSONMetaData(dep));
}
- return (Dictionary<String, String>) value;
- }
- @Override
- public String toString()
- {
- StringBuilder sb = new StringBuilder();
- for (Map.Entry<DescriptorParam, Object> entry : m_params.entrySet())
- {
- sb.append(entry.getKey());
- sb.append("=");
- Object val = entry.getValue();
- if (val instanceof String || val instanceof Dictionary<?, ?>)
- {
- sb.append(val.toString());
- }
- else if (val instanceof String[])
- {
- sb.append(Arrays.toString((String[]) val));
- }
- else
- {
- sb.append(val.toString());
- }
- sb.append(";");
- }
- return sb.toString();
+ // and Invoke the builder
+ builder.buildService(serviceMetaData, serviceDependencies, b, dm);
}
}
Added: felix/trunk/dependencymanager/runtime/src/main/java/org/apache/felix/dm/runtime/FactoryConfigurationAdapterServiceBuilder.java
URL: http://svn.apache.org/viewvc/felix/trunk/dependencymanager/runtime/src/main/java/org/apache/felix/dm/runtime/FactoryConfigurationAdapterServiceBuilder.java?rev=947379&view=auto
==============================================================================
--- felix/trunk/dependencymanager/runtime/src/main/java/org/apache/felix/dm/runtime/FactoryConfigurationAdapterServiceBuilder.java (added)
+++ felix/trunk/dependencymanager/runtime/src/main/java/org/apache/felix/dm/runtime/FactoryConfigurationAdapterServiceBuilder.java Sun May 23 08:20:50 2010
@@ -0,0 +1,59 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS 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.DependencyManager;
+import org.apache.felix.dm.dependencies.Dependency;
+import org.apache.felix.dm.service.Service;
+import org.osgi.framework.Bundle;
+
+public class FactoryConfigurationAdapterServiceBuilder extends ServiceComponentBuilder
+{
+ private final static String TYPE = "FactoryConfigurationAdapterService";
+
+ @Override
+ public String getType()
+ {
+ return TYPE;
+ }
+
+ @Override
+ public void buildService(MetaData serviceMetaData,
+ List<MetaData> serviceDependencies,
+ Bundle b, DependencyManager dm) throws Exception
+ {
+ Class<?> impl = b.loadClass(serviceMetaData.getString(Params.impl));
+ String factoryPid = serviceMetaData.getString(Params.factoryPid);
+ String updated = serviceMetaData.getString(Params.updated);
+ String[] services = serviceMetaData.getStrings(Params.service, null);
+ Dictionary<String, Object> properties = serviceMetaData.getDictionary(Params.properties, null);
+ boolean propagate = "true".equals(serviceMetaData.getString(Params.propagate, "false"));
+ Service srv = dm.createFactoryConfigurationAdapterService(factoryPid, updated, impl, services, properties, propagate);
+ setCommonServiceParams(srv, serviceMetaData);
+ for (MetaData dependencyMetaData: serviceDependencies)
+ {
+ Dependency dp = new DependencyBuilder(dependencyMetaData).build(b, dm);
+ srv.add(dp);
+ }
+ dm.add(srv);
+ }
+}
Added: felix/trunk/dependencymanager/runtime/src/main/java/org/apache/felix/dm/runtime/JSONMetaData.java
URL: http://svn.apache.org/viewvc/felix/trunk/dependencymanager/runtime/src/main/java/org/apache/felix/dm/runtime/JSONMetaData.java?rev=947379&view=auto
==============================================================================
--- felix/trunk/dependencymanager/runtime/src/main/java/org/apache/felix/dm/runtime/JSONMetaData.java (added)
+++ felix/trunk/dependencymanager/runtime/src/main/java/org/apache/felix/dm/runtime/JSONMetaData.java Sun May 23 08:20:50 2010
@@ -0,0 +1,259 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS 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.HashMap;
+import java.util.Hashtable;
+import java.util.Iterator;
+
+import org.json.JSONArray;
+import org.json.JSONException;
+import org.json.JSONObject;
+
+/**
+ * A JSON MetaData.
+ */
+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 a JSON metadata for either a Service or a Dependency descriptor entry.
+ * The JSON object values contains either some of the following types: a String, a String[], or a Dictionary of String/String[].
+ * @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)
+ {
+ String[] array = decodeStringArray((JSONArray) value);
+ m_metadata.put(key, array);
+ }
+ else if (value instanceof JSONObject)
+ {
+ Hashtable<String, Object> h = new Hashtable<String, Object>();
+ JSONObject obj = ((JSONObject) value);
+ Iterator<String> it2 = obj.keys();
+ while (it2.hasNext())
+ {
+ String key2 = it2.next();
+ Object value2 = obj.get(key2);
+ if (value2 instanceof String)
+ {
+ h.put(key2, value2);
+ }
+ else if (value2 instanceof JSONArray)
+ {
+ String[] array = decodeStringArray((JSONArray) value2);
+ h.put(key2, array);
+ }
+ else
+ {
+ throw new IllegalArgumentException("Could not decode JSON metadata: key " + key +
+ "contains an invalid dictionary key: " + key
+ + " (the value is neither a String nor a String[]).");
+ }
+ }
+ m_metadata.put(key, h);
+ }
+ }
+ }
+
+ /**
+ * 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)
+ {
+ String value = (String) m_metadata.get(key.toString());
+ if (value == null)
+ {
+ throw new IllegalArgumentException("Parameter " + key + " not found");
+ }
+ return value;
+ }
+
+ public String getString(Params key, String def)
+ {
+ try
+ {
+ return getString(key);
+ }
+ catch (IllegalArgumentException e)
+ {
+ return def;
+ }
+ }
+
+ public int getInt(Params key)
+ {
+ String value = getString(key, null);
+ if (value != null)
+ {
+ try
+ {
+ return Integer.parseInt(value);
+ }
+ 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)
+ {
+ String value = getString(key, null);
+ if (value != null)
+ {
+ try
+ {
+ return Integer.parseInt(value);
+ }
+ catch (NumberFormatException e)
+ {
+ throw new IllegalArgumentException("parameter " + key
+ + " is not an int 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;
+ }
+}
Added: felix/trunk/dependencymanager/runtime/src/main/java/org/apache/felix/dm/runtime/Log.java
URL: http://svn.apache.org/viewvc/felix/trunk/dependencymanager/runtime/src/main/java/org/apache/felix/dm/runtime/Log.java?rev=947379&view=auto
==============================================================================
--- felix/trunk/dependencymanager/runtime/src/main/java/org/apache/felix/dm/runtime/Log.java (added)
+++ felix/trunk/dependencymanager/runtime/src/main/java/org/apache/felix/dm/runtime/Log.java Sun May 23 08:20:50 2010
@@ -0,0 +1,60 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS 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.framework.ServiceReference;
+import org.osgi.service.log.LogService;
+
+public class Log implements LogService
+{
+ /** The log service */
+ private static LogService m_logService;
+
+ /** Our sole instance */
+ private static Log m_instance = new Log();
+
+ public static Log instance()
+ {
+ return m_instance;
+ }
+
+ public void setLogService(LogService logService) {
+ m_logService = logService;
+ }
+
+ public void log(int level, String message, Throwable exception)
+ {
+ m_logService.log(level, message, exception);
+ }
+
+ public void log(int level, String message)
+ {
+ m_logService.log(level, message);
+ }
+
+ public void log(ServiceReference sr, int level, String message, Throwable exception)
+ {
+ m_logService.log(sr, level, message, exception);
+ }
+
+ public void log(ServiceReference sr, int level, String message)
+ {
+ m_logService.log(sr, level, message);
+ }
+}
Added: felix/trunk/dependencymanager/runtime/src/main/java/org/apache/felix/dm/runtime/MetaData.java
URL: http://svn.apache.org/viewvc/felix/trunk/dependencymanager/runtime/src/main/java/org/apache/felix/dm/runtime/MetaData.java?rev=947379&view=auto
==============================================================================
--- felix/trunk/dependencymanager/runtime/src/main/java/org/apache/felix/dm/runtime/MetaData.java (added)
+++ felix/trunk/dependencymanager/runtime/src/main/java/org/apache/felix/dm/runtime/MetaData.java Sun May 23 08:20:50 2010
@@ -0,0 +1,77 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS 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.
+ */
+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 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);
+}
Added: felix/trunk/dependencymanager/runtime/src/main/java/org/apache/felix/dm/runtime/Params.java
URL: http://svn.apache.org/viewvc/felix/trunk/dependencymanager/runtime/src/main/java/org/apache/felix/dm/runtime/Params.java?rev=947379&view=auto
==============================================================================
--- felix/trunk/dependencymanager/runtime/src/main/java/org/apache/felix/dm/runtime/Params.java (added)
+++ felix/trunk/dependencymanager/runtime/src/main/java/org/apache/felix/dm/runtime/Params.java Sun May 23 08:20:50 2010
@@ -0,0 +1,57 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS 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.
+ */
+public enum Params
+{
+ type,
+ init,
+ start,
+ stop,
+ destroy,
+ impl,
+ provide,
+ properties,
+ composition,
+ service,
+ filter,
+ defaultImpl,
+ required,
+ added,
+ changed,
+ removed,
+ autoConfig,
+ pid,
+ propagate,
+ updated,
+ timeout,
+ adapterService,
+ adapterProperties,
+ adapteeService,
+ adapteeFilter,
+ stateMask,
+ ranking,
+ factoryPid,
+ factory,
+ factoryConfigure,
+ name
+}
Added: felix/trunk/dependencymanager/runtime/src/main/java/org/apache/felix/dm/runtime/ResourceAdapterServiceBuilder.java
URL: http://svn.apache.org/viewvc/felix/trunk/dependencymanager/runtime/src/main/java/org/apache/felix/dm/runtime/ResourceAdapterServiceBuilder.java?rev=947379&view=auto
==============================================================================
--- felix/trunk/dependencymanager/runtime/src/main/java/org/apache/felix/dm/runtime/ResourceAdapterServiceBuilder.java (added)
+++ felix/trunk/dependencymanager/runtime/src/main/java/org/apache/felix/dm/runtime/ResourceAdapterServiceBuilder.java Sun May 23 08:20:50 2010
@@ -0,0 +1,58 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS 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.DependencyManager;
+import org.apache.felix.dm.dependencies.Dependency;
+import org.apache.felix.dm.service.Service;
+import org.osgi.framework.Bundle;
+
+public class ResourceAdapterServiceBuilder extends ServiceComponentBuilder
+{
+ private final static String TYPE = "ResourceAdapterService";
+
+ @Override
+ public String getType()
+ {
+ return TYPE;
+ }
+
+ @Override
+ public void buildService(MetaData serviceMetaData,
+ List<MetaData> serviceDependencies,
+ Bundle b, DependencyManager dm) throws Exception
+ {
+ String filter = serviceMetaData.getString(Params.filter, null);
+ Class<?> impl = b.loadClass(serviceMetaData.getString(Params.impl));
+ String[] service = serviceMetaData.getStrings(Params.service, null);
+ Dictionary<String, Object> properties = serviceMetaData.getDictionary(Params.properties, null);
+ boolean propagate = "true".equals(serviceMetaData.getString(Params.propagate, "false"));
+ Service srv = dm.createResourceAdapterService(filter, null, service, properties, impl, propagate);
+ setCommonServiceParams(srv, serviceMetaData);
+ for (MetaData dependencyMetaData: serviceDependencies)
+ {
+ Dependency dp = new DependencyBuilder(dependencyMetaData).build(b, dm);
+ srv.add(dp);
+ }
+ dm.add(srv);
+ }
+}
Added: felix/trunk/dependencymanager/runtime/src/main/java/org/apache/felix/dm/runtime/ServiceBuilder.java
URL: http://svn.apache.org/viewvc/felix/trunk/dependencymanager/runtime/src/main/java/org/apache/felix/dm/runtime/ServiceBuilder.java?rev=947379&view=auto
==============================================================================
--- felix/trunk/dependencymanager/runtime/src/main/java/org/apache/felix/dm/runtime/ServiceBuilder.java (added)
+++ felix/trunk/dependencymanager/runtime/src/main/java/org/apache/felix/dm/runtime/ServiceBuilder.java Sun May 23 08:20:50 2010
@@ -0,0 +1,114 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS 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.DependencyManager;
+import org.apache.felix.dm.dependencies.Dependency;
+import org.apache.felix.dm.service.Service;
+import org.osgi.framework.Bundle;
+import org.osgi.service.log.LogService;
+
+public class ServiceBuilder extends ServiceComponentBuilder
+{
+ private final static String TYPE = "Service";
+
+ @Override
+ public String getType()
+ {
+ return TYPE;
+ }
+
+ @Override
+ public void buildService(MetaData srvMeta, List<MetaData> srvDeps, Bundle b, DependencyManager dm)
+ throws Exception
+ {
+ Log.instance().log(LogService.LOG_DEBUG, "building service: service metadata=" + srvMeta
+ + ", dependencyMetaData=" + srvDeps);
+
+ // Get service parameters (lifecycle callbacks, composition, factory, etc ...)
+
+ Service service = dm.createService();
+ String factory = srvMeta.getString(Params.factory, null);
+ String factoryConfigure = srvMeta.getString(Params.factoryConfigure, null);
+ String impl = srvMeta.getString(Params.impl);
+ String init = srvMeta.getString(Params.init, null);
+ String start = srvMeta.getString(Params.start, null);
+ String stop = srvMeta.getString(Params.stop, null);
+ String destroy = srvMeta.getString(Params.destroy, null);
+ String composition = srvMeta.getString(Params.composition, null);
+ Dictionary<String, Object> serviceProperties = srvMeta.getDictionary(Params.properties, null);
+ String[] provide = srvMeta.getStrings(Params.provide, null);
+
+ // Check if we must provide a Set Factory.
+ if (factory == null)
+ {
+ // No: instantiate the service.
+ service.setImplementation(b.loadClass(impl));
+ if (composition != null)
+ {
+ service.setComposition(composition);
+ }
+ if (provide != null)
+ {
+ service.setInterface(provide, serviceProperties);
+ }
+
+ // Creates a ServiceHandler, which will filter all service lifecycle callbacks.
+ /*
+ ServiceLifecycleHandler lfcleHandler = new ServiceLifecycleHandler(service, b, dm, srvMeta,
+ srvDeps);
+ service.setCallbacks(lfcleHandler, "init", "start", "stop", "destroy");
+ String confDependency = DependencyBuilder.DependencyType.ConfigurationDependency.toString();
+ */
+ // TODO REMOVE
+ for (MetaData depMeta: srvDeps)
+ {
+ Dependency dp = new DependencyBuilder(depMeta).build(b, dm);
+ service.add(dp);
+ }
+ }
+ else
+ {
+ // 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 use registers some
+ // service configurations into it in order to fire some service instantiations.
+
+ ServiceFactory serviceFactory = new ServiceFactory(b.loadClass(impl), init, start, stop, destroy,
+ composition, serviceProperties, provide,
+ factoryConfigure);
+ for (MetaData dependencyMetaData: srvDeps)
+ {
+ Dependency dp = new DependencyBuilder(dependencyMetaData).build(b, dm);
+ serviceFactory.addDependency(dp);
+ }
+ service.setImplementation(serviceFactory);
+ service.setCallbacks(null, "start", "stop", null);
+ Hashtable<String, String> props = new Hashtable<String, String>();
+ props.put("dm.factory.name", factory);
+ service.setInterface(Set.class.getName(), props);
+ }
+
+ dm.add(service);
+ }
+}
Added: felix/trunk/dependencymanager/runtime/src/main/java/org/apache/felix/dm/runtime/ServiceComponentBuilder.java
URL: http://svn.apache.org/viewvc/felix/trunk/dependencymanager/runtime/src/main/java/org/apache/felix/dm/runtime/ServiceComponentBuilder.java?rev=947379&view=auto
==============================================================================
--- felix/trunk/dependencymanager/runtime/src/main/java/org/apache/felix/dm/runtime/ServiceComponentBuilder.java (added)
+++ felix/trunk/dependencymanager/runtime/src/main/java/org/apache/felix/dm/runtime/ServiceComponentBuilder.java Sun May 23 08:20:50 2010
@@ -0,0 +1,63 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS 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.List;
+
+import org.apache.felix.dm.DependencyManager;
+import org.apache.felix.dm.service.Service;
+import org.osgi.framework.Bundle;
+
+/**
+ * The builder which creates a DependencyManager Service (a Service and all its derived classes (Aspect/Adapters).
+ */
+public abstract class ServiceComponentBuilder
+{
+ /**
+ * 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 buildService(MetaData serviceMetaData, List<MetaData> serviceDependencies, Bundle b,
+ DependencyManager dm)
+ throws Exception;
+
+ /**
+ * Set common Service parameters, if provided from our Component descriptor
+ */
+ protected void setCommonServiceParams(Service service, MetaData serviceMetaData)
+ throws Exception
+ {
+ String init = serviceMetaData.getString(Params.init, null);
+ String start = serviceMetaData.getString(Params.start, null);
+ String stop = serviceMetaData.getString(Params.stop, null);
+ String destroy = serviceMetaData.getString(Params.destroy, null);
+ service.setCallbacks(init, start, stop, destroy);
+ String composition = serviceMetaData.getString(Params.composition, null);
+ if (composition != null)
+ {
+ service.setComposition(composition);
+ }
+ }
+}
Added: felix/trunk/dependencymanager/runtime/src/main/java/org/apache/felix/dm/runtime/ServiceLifecycleHandler.java
URL: http://svn.apache.org/viewvc/felix/trunk/dependencymanager/runtime/src/main/java/org/apache/felix/dm/runtime/ServiceLifecycleHandler.java?rev=947379&view=auto
==============================================================================
--- felix/trunk/dependencymanager/runtime/src/main/java/org/apache/felix/dm/runtime/ServiceLifecycleHandler.java (added)
+++ felix/trunk/dependencymanager/runtime/src/main/java/org/apache/felix/dm/runtime/ServiceLifecycleHandler.java Sun May 23 08:20:50 2010
@@ -0,0 +1,203 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS 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.util.ArrayList;
+import java.util.Collection;
+import java.util.HashMap;
+import java.util.List;
+import java.util.Map;
+
+import org.apache.felix.dm.DependencyManager;
+import org.apache.felix.dm.dependencies.Dependency;
+import org.apache.felix.dm.service.Service;
+import org.osgi.framework.Bundle;
+
+/**
+ * This class acts as a service implementation lifecycle handler. If the actual service implementation
+ * init method returns a Map, then this map will is inspected for dependency filters, which will be
+ * applied to the dependencies specified in the service.
+ */
+public class ServiceLifecycleHandler
+{
+ private String m_init;
+ private String m_start;
+ private String m_stop;
+ private String m_destroy;
+ private List<MetaData> m_dependencies = new ArrayList<MetaData>();
+ private Map<String, MetaData> m_namedDependencies = new HashMap<String, MetaData>();
+ private Bundle m_bundle;
+
+ public ServiceLifecycleHandler(Service srv, Bundle srvBundle, DependencyManager dm,
+ MetaData srvMetaData, List<MetaData> srvDep)
+ throws Exception
+ {
+ m_init = srvMetaData.getString(Params.init, null);
+ m_start = srvMetaData.getString(Params.start, null);
+ m_stop = srvMetaData.getString(Params.stop, null);
+ m_destroy = srvMetaData.getString(Params.destroy, null);
+ m_bundle = srvBundle;
+
+ String confDependency = DependencyBuilder.DependencyType.ConfigurationDependency.toString();
+ for (MetaData depMeta: srvDep)
+ {
+ if (depMeta.getString(Params.type).equals(confDependency))
+ {
+ // Register Configuration dependencies now
+ Dependency dp = new DependencyBuilder(depMeta).build(m_bundle, dm);
+ srv.add(dp);
+ }
+ else
+ {
+ String name = depMeta.getString(Params.name, null);
+ if (name != null)
+ {
+ m_namedDependencies.put(name, depMeta);
+ }
+ else
+ {
+ m_dependencies.add(depMeta);
+ }
+ }
+ }
+
+ }
+
+ @SuppressWarnings("unchecked")
+ public void init(Object serviceInstance, DependencyManager dm, Service service)
+ throws Exception
+ {
+ // Invoke the service instance actual init method.
+ Object o = invokeMethod(serviceInstance, m_init, dm, service);
+
+ // If the init method returned a Map, then apply all filters found from it into
+ // the service dependencies. Keys = Dependency name / values = Dependency filter
+ if (o != null && Map.class.isAssignableFrom(o.getClass()))
+ {
+ Map<String, String> filters = (Map<String, String>) o;
+ for (Map.Entry<String, String> entry: filters.entrySet())
+ {
+ String name = entry.getKey();
+ String filter = entry.getValue();
+
+ MetaData dependency = m_namedDependencies.remove(name);
+ if (dependency != null)
+ {
+ dependency.setString(Params.filter, filter);
+ DependencyBuilder depBuilder = new DependencyBuilder(dependency);
+ Dependency d = depBuilder.build(m_bundle, dm, true);
+ service.add(d);
+ }
+ else
+ {
+ throw new IllegalArgumentException("Invalid filter Map: the filter key " + name
+ + " does not correspond " +
+ " to a known Dependency.");
+ }
+ }
+ }
+
+ plugDependencies(m_namedDependencies.values(), dm, service);
+ plugDependencies(m_dependencies, dm, service);
+ }
+
+ public void start(Object serviceInstance, DependencyManager dm, Service service)
+ throws IllegalArgumentException, IllegalAccessException, InvocationTargetException
+ {
+ invokeMethod(serviceInstance, m_start, dm, service);
+ }
+
+ public void stop(Object serviceInstance, DependencyManager dm, Service service)
+ throws IllegalArgumentException, IllegalAccessException, InvocationTargetException
+ {
+ invokeMethod(serviceInstance, m_stop, dm, service);
+ }
+
+ public void destroy(Object serviceInstance, DependencyManager dm, Service service)
+ throws IllegalArgumentException, IllegalAccessException, InvocationTargetException
+ {
+ invokeMethod(serviceInstance, m_destroy, dm, service);
+ }
+
+ private Object invokeMethod(Object serviceInstance, String method, DependencyManager dm, Service service)
+ throws IllegalArgumentException, IllegalAccessException, InvocationTargetException
+ {
+ return invokeMethod(serviceInstance,
+ method,
+ new Class[][] {
+ { Object.class, DependencyManager.class, Service.class },
+ { DependencyManager.class, Service.class },
+ { Object.class },
+ {}
+ },
+ new Object[][] {
+ { serviceInstance, dm, service },
+ { dm, service },
+ { serviceInstance },
+ {}
+ });
+ }
+
+ private Object invokeMethod(Object instance, String method, Class<?>[][] signatures, Object[][] params)
+ throws IllegalArgumentException, IllegalAccessException, InvocationTargetException
+ {
+ if (method == null)
+ {
+ // The annotated class did not provide an annotation for this lifecycle callback.
+ return null;
+ }
+
+ Class clazz = instance.getClass();
+
+ while (clazz != null)
+ {
+ for (int i = 0; i < signatures.length; i++)
+ {
+ Class<?>[] signature = signatures[i];
+ try
+ {
+ // Don't use getMethod because getMethod only look for public methods !
+ Method m = instance.getClass().getDeclaredMethod(method, signature);
+ m.setAccessible(true);
+ return m.invoke(instance, params[i]);
+ }
+ catch (NoSuchMethodException e)
+ {
+ // ignore this and keep looking
+ }
+ }
+ clazz = clazz.getSuperclass();
+ }
+
+ return null;
+ }
+
+ private void plugDependencies(Collection<MetaData> dependencies, DependencyManager dm, Service service)
+ throws Exception
+ {
+ for (MetaData dependency: dependencies)
+ {
+ DependencyBuilder depBuilder = new DependencyBuilder(dependency);
+ Dependency d = depBuilder.build(m_bundle, dm, true);
+ service.add(d);
+ }
+ }
+}