cocoon-cvs mailing list archives

Site index · List index
Message view « Date » · « Thread »
Top « Date » · « Thread »
From dani...@apache.org
Subject svn commit: r567386 - in /cocoon/whiteboard/osgi-component-manager/src/main/java/org/apache/cocoon/core/osgi: ./ OSGiBootstrapEnvironment.java OSGiCoreServiceManager.java OSGiLoggerManager.java OSGiServiceManager.java ServiceManagerActivator.java
Date Sun, 19 Aug 2007 12:20:07 GMT
Author: danielf
Date: Sun Aug 19 05:20:05 2007
New Revision: 567386

URL: http://svn.apache.org/viewvc?view=rev&rev=567386
Log:
Some old OSGi container bridge code kept for reference.

Added:
    cocoon/whiteboard/osgi-component-manager/src/main/java/org/apache/cocoon/core/osgi/
    cocoon/whiteboard/osgi-component-manager/src/main/java/org/apache/cocoon/core/osgi/OSGiBootstrapEnvironment.java
    cocoon/whiteboard/osgi-component-manager/src/main/java/org/apache/cocoon/core/osgi/OSGiCoreServiceManager.java
    cocoon/whiteboard/osgi-component-manager/src/main/java/org/apache/cocoon/core/osgi/OSGiLoggerManager.java
    cocoon/whiteboard/osgi-component-manager/src/main/java/org/apache/cocoon/core/osgi/OSGiServiceManager.java
    cocoon/whiteboard/osgi-component-manager/src/main/java/org/apache/cocoon/core/osgi/ServiceManagerActivator.java

Added: cocoon/whiteboard/osgi-component-manager/src/main/java/org/apache/cocoon/core/osgi/OSGiBootstrapEnvironment.java
URL: http://svn.apache.org/viewvc/cocoon/whiteboard/osgi-component-manager/src/main/java/org/apache/cocoon/core/osgi/OSGiBootstrapEnvironment.java?view=auto&rev=567386
==============================================================================
--- cocoon/whiteboard/osgi-component-manager/src/main/java/org/apache/cocoon/core/osgi/OSGiBootstrapEnvironment.java
(added)
+++ cocoon/whiteboard/osgi-component-manager/src/main/java/org/apache/cocoon/core/osgi/OSGiBootstrapEnvironment.java
Sun Aug 19 05:20:05 2007
@@ -0,0 +1,248 @@
+/*
+ * Copyright 1999-2005 The Apache Software Foundation.
+ * 
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ * 
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ * 
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.apache.cocoon.core.osgi;
+
+import java.io.File;
+import java.io.FileNotFoundException;
+import java.io.InputStream;
+import java.io.IOException;
+import java.net.MalformedURLException;
+import java.net.URL;
+import java.util.Enumeration;
+import java.util.Hashtable;
+
+import org.apache.avalon.excalibur.logger.LoggerManager;
+import org.apache.avalon.framework.context.DefaultContext;
+import org.apache.avalon.framework.logger.Logger;
+import org.apache.cocoon.core.BootstrapEnvironment;
+import org.apache.cocoon.core.MutableSettings;
+import org.apache.cocoon.core.Settings;
+import org.apache.cocoon.environment.Context;
+import org.apache.cocoon.environment.impl.AbstractContext;
+import org.osgi.framework.Bundle;
+import org.osgi.framework.BundleContext;
+import org.osgi.framework.Constants;
+import org.osgi.service.log.LogService;
+
+public class OSGiBootstrapEnvironment
+    implements BootstrapEnvironment {
+    
+    private final String configuration = "/WEB-INF/block.xml";
+    private final ClassLoader classLoader;
+    public Logger logger = null;
+    private final String contextPath;
+    private final Context environmentContext;
+
+    public OSGiBootstrapEnvironment(ClassLoader classLoader, BundleContext bc)
+        throws Exception {
+        this.classLoader = classLoader;
+
+        // Create a logger manager that delegates to OSGi
+        // FIXME: have the maximum level as a property of the bundle
+        LoggerManager logManager = new OSGiLoggerManager(bc, LogService.LOG_DEBUG);
+        this.logger = logManager.getDefaultLogger();
+
+        Bundle bundle = getSitemapBundle(bc, this.logger); //bc.getBundle();
+        if (bundle == null)
+            throw new Exception("No sitemap bundle");
+        // Try to figure out the path of the root from that of /WEB-INF/block.xml
+        URL pathURL = bundle.getResource(this.configuration);
+        if (pathURL == null)
+            throw new FileNotFoundException("Unable to get resource '/WEB-INF/block.xml'
from bundle ." + bundle);
+        String path = pathURL.toString();
+        path = path.substring(0, path.length() - (this.configuration.length() - 1));
+        this.contextPath = path;
+
+        this.environmentContext = new OSGiContext(bundle);
+    }
+
+    /**
+     * @see org.apache.cocoon.core.BootstrapEnvironment#getBootstrapLogger(org.apache.cocoon.core.BootstrapEnvironment.LogLevel)
+     */
+    public Logger getBootstrapLogger(LogLevel logLevel) {
+        return this.logger;
+    }
+
+    /** Log a message during bootstrapping. This is used to log
+     * information before the logging system is setup.
+     * @param message A message.
+     */
+    public void log(String message) {
+        this.logger.info(message);
+    }
+
+    /** Log a message during bootstrapping. This is used to log
+     * information before the logging system is setup.
+     * @param message A message.
+     * @param error   An error.
+     */
+    public void log(String message, Throwable error) {
+        this.logger.info(message, error);
+    }
+
+    /**
+     * Pass the root logger back to the environment. As soon as the
+     * logging system is set up, this method is called.
+     * @param rootLogger The root logger.
+     */
+    public void setLogger(Logger rootLogger) {
+        this.logger = rootLogger;
+    }
+
+    /**
+     * Get the input stream from a resource at the given
+     * path. Only paths relative to the bootstrap context are
+     * supported. Returns null if no resource exists at the
+     * specified path
+     */
+    public InputStream getInputStream(String path) {
+        try {
+            return (new URL(this.contextPath + path)).openStream();
+        } catch (IOException e) {
+            this.log("Couldn't open " + this.contextPath + path);
+            return null;
+        }
+    }
+    
+    public void configure(MutableSettings settings) {
+        // FIXME: Should be found from block.xml
+        settings.setConfiguration("/WEB-INF/cocoon.xconf");
+        settings.setWorkDirectory("work");
+        settings.setInitClassloader(true);
+        settings.setLoggingConfiguration("/WEB-INF/logkit.xconf");
+    }
+
+    public void configureLoggingContext(DefaultContext context) {
+        // simply do nothing
+    }
+
+    public void configure(DefaultContext context) {
+    }
+
+    public ClassLoader getInitClassLoader() {
+        return this.classLoader;
+    }
+
+    public Context getEnvironmentContext() {
+        return this.environmentContext;
+    }
+    
+    /**
+     * Returns the URL to the application context.
+     */
+    public String getContextURL() {
+        return this.contextPath;
+    }
+
+    /**
+     * Returns a file to the application context.
+     * @return A file pointing to the context or null if the context is not
+     *         writeable.
+     */
+    public File getContextForWriting() {
+        return null;
+    }
+
+    /**
+     * Set the ConfigFile for the Cocoon object.
+     *
+     * @param configFileName The file location for the cocoon.xconf
+     *
+     * @throws Exception
+     */
+    public URL getConfigFile(String configFileName) throws Exception {
+        this.logger.debug("getConfigFile: contextPath=" + this.contextPath +
+                          " configFileName=" + configFileName);
+        return new URL(this.contextPath + configFileName);
+    }
+
+    public String getClassPath(Settings settings) {
+        return null;
+    }
+
+    private Bundle getSitemapBundle(BundleContext bc, Logger log) {
+        String SITEMAP = "sitemap";
+        Bundle[] bundles = bc.getBundles();
+        for (int i = 0; i < bundles.length; i++) {
+            Bundle bundle = bundles[i];
+            try {
+                log.info("checking bundle " + bundle + " name=" + bundle.getHeaders().get(Constants.BUNDLE_NAME)
+ " category=" + bundle.getHeaders().get(Constants.BUNDLE_CATEGORY) + " state=" + bundle.getState());
+                if ((bundle.getState() == Bundle.INSTALLED ||
+                     bundle.getState() == Bundle.RESOLVED ||
+                     bundle.getState() == Bundle.ACTIVE)) {
+                    log.info("ok state");
+                    if (SITEMAP.equals(bundle.getHeaders().get(Constants.BUNDLE_CATEGORY)))
{
+                        log.info("sitemap");
+                        return bundle;
+                    }
+                }
+            } catch (NullPointerException e) {
+                // BUNDLE_CATEGORY not present in the headers of the
+                // bundle, nothing to do.
+            }
+        }
+        return null;
+    }
+
+    public class OSGiContext extends AbstractContext {
+
+        Bundle bundle;
+        private Hashtable attributes = new Hashtable();
+        private Hashtable initparameters = new Hashtable();
+
+        public OSGiContext(Bundle bundle) {
+            this.bundle = bundle;
+            this.initparameters.put("init-classloader", "true");
+            this.initparameters.put("work-directory", "work");
+        }
+
+        public Object getAttribute(String name) {
+            return attributes.get(name);
+        }
+
+        public void setAttribute(String name, Object value) {
+            attributes.put(name, value);
+        }
+
+        public void removeAttribute(String name) {
+            attributes.remove(name);
+        }
+
+        public Enumeration getAttributeNames() {
+            return attributes.keys();
+        }
+
+        public URL getResource(String path) throws MalformedURLException {
+            return this.bundle.getResource(path);
+        }
+
+        public String getRealPath(String path) {
+            return null;
+        }
+
+        public String getMimeType(String file) {
+            return null;
+        }
+
+        public String getInitParameter(String name) {
+            return (String)initparameters.get(name);
+        }
+
+        public InputStream getResourceAsStream(String path) {
+            return null;
+        }
+    }
+}

Added: cocoon/whiteboard/osgi-component-manager/src/main/java/org/apache/cocoon/core/osgi/OSGiCoreServiceManager.java
URL: http://svn.apache.org/viewvc/cocoon/whiteboard/osgi-component-manager/src/main/java/org/apache/cocoon/core/osgi/OSGiCoreServiceManager.java?view=auto&rev=567386
==============================================================================
--- cocoon/whiteboard/osgi-component-manager/src/main/java/org/apache/cocoon/core/osgi/OSGiCoreServiceManager.java
(added)
+++ cocoon/whiteboard/osgi-component-manager/src/main/java/org/apache/cocoon/core/osgi/OSGiCoreServiceManager.java
Sun Aug 19 05:20:05 2007
@@ -0,0 +1,110 @@
+/*
+ * Copyright 2002-2005 The Apache Software Foundation
+ * Licensed  under the  Apache License,  Version 2.0  (the "License");
+ * you may not use  this file  except in  compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *   http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed  under the  License is distributed on an "AS IS" BASIS,
+ * WITHOUT  WARRANTIES OR CONDITIONS  OF ANY KIND, either  express  or
+ * implied.
+ *
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.apache.cocoon.core.osgi;
+
+import java.util.Dictionary;
+import java.util.Hashtable;
+
+import org.apache.avalon.framework.configuration.Configuration;
+import org.apache.avalon.framework.configuration.ConfigurationException;
+import org.apache.avalon.framework.service.ServiceManager;
+import org.apache.cocoon.components.ComponentInfo;
+import org.apache.cocoon.core.container.CoreServiceManager;
+import org.apache.cocoon.core.container.handler.ComponentHandler;
+import org.osgi.framework.Bundle;
+import org.osgi.framework.BundleContext;
+import org.osgi.framework.ServiceFactory;
+import org.osgi.framework.ServiceRegistration;
+
+/**
+ * An extension of {@link org.apache.cocoon.core.container.CoreServiceManager} that registers
some
+ * of its components as OSGi services.
+ * <p>
+ * The component role is used to find a component's interface. If the role is a hinted one
(e.g.
+ * "org.apache.cocoon.generation.Generator/file", then the hint is registered as the "component.hint"
+ * property of the OSGi service.
+ * <p>
+ * Only those components whose configuration has an <code>exported="true"</code>
attribute are exported.
+ * An important constraint is that such components be singleton (either real singletons or
singleton proxies
+ * to non-singleton components).
+ * 
+ * @version $Id: OSGiCoreServiceManager.java 225154 2005-07-25 17:28:56Z sylvain $
+ */
+public class OSGiCoreServiceManager extends CoreServiceManager {
+    
+    BundleContext ctx;
+    
+    public OSGiCoreServiceManager(ServiceManager parent, ClassLoader classloader, BundleContext
ctx) {
+        super(parent, classloader);
+        this.ctx = ctx;
+    }
+
+    /**
+     * Catch component declarations and register exported ones as OSGi services.
+     */
+    public void addComponent(String role, String className, Configuration configuration,
ComponentInfo info) throws ConfigurationException {
+        super.addComponent(role, className, configuration, info);
+        if (configuration.getAttributeAsBoolean("exported", false)) {
+            ComponentHandler handler = (ComponentHandler)super.componentHandlers.get(role);
+            if (!handler.isSingleton()) {
+                throw new ConfigurationException("Only singleton services can be exported
as OSGi services, at " +
+                        configuration.getLocation());
+            }
+            
+            String itfName = OSGiServiceManager.getServiceInterface(role);
+            String hint = OSGiServiceManager.getServiceHint(role);
+            Dictionary dict = null;
+            if (hint != null) {
+                dict = new Hashtable();
+                dict.put(OSGiServiceManager.HINT_PROPERTY, hint);
+            }
+            
+            Object service = new ComponentHandlerFactory(handler);
+            ctx.registerService(itfName, service, dict);
+        }
+    }
+    
+    /**
+     * An OSGi service factory implemented on top of a {@link ComponentHandler}.
+     * @author sylvain
+     *
+     */
+    public static class ComponentHandlerFactory implements ServiceFactory {
+        
+        private ComponentHandler handler;
+
+        public ComponentHandlerFactory(ComponentHandler handler) {
+            this.handler = handler;
+        }
+
+        public Object getService(Bundle bundle, ServiceRegistration reg) {
+            try {
+                return handler.get();
+            } catch (Exception e) {
+                throw new RuntimeException("Cannot get service", e);
+            }
+        }
+
+        public void ungetService(Bundle bundle, ServiceRegistration reg, Object obj) {
+            try {
+                handler.put(obj);
+            } catch (Exception e) {
+                throw new RuntimeException("Cannot unget service", e);
+            }
+        }
+    }
+}

Added: cocoon/whiteboard/osgi-component-manager/src/main/java/org/apache/cocoon/core/osgi/OSGiLoggerManager.java
URL: http://svn.apache.org/viewvc/cocoon/whiteboard/osgi-component-manager/src/main/java/org/apache/cocoon/core/osgi/OSGiLoggerManager.java?view=auto&rev=567386
==============================================================================
--- cocoon/whiteboard/osgi-component-manager/src/main/java/org/apache/cocoon/core/osgi/OSGiLoggerManager.java
(added)
+++ cocoon/whiteboard/osgi-component-manager/src/main/java/org/apache/cocoon/core/osgi/OSGiLoggerManager.java
Sun Aug 19 05:20:05 2007
@@ -0,0 +1,180 @@
+/*
+ * Copyright 2005 The Apache Software Foundation
+ * Licensed  under the  Apache License,  Version 2.0  (the "License");
+ * you may not use  this file  except in  compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *   http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed  under the  License is distributed on an "AS IS" BASIS,
+ * WITHOUT  WARRANTIES OR CONDITIONS  OF ANY KIND, either  express  or
+ * implied.
+ *
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.apache.cocoon.core.osgi;
+
+import java.util.Collections;
+import java.util.HashMap;
+import java.util.Map;
+
+import org.apache.avalon.excalibur.logger.LoggerManager;
+import org.apache.avalon.framework.logger.Logger;
+import org.osgi.framework.BundleContext;
+import org.osgi.framework.BundleEvent;
+import org.osgi.framework.BundleListener;
+import org.osgi.framework.ServiceReference;
+import org.osgi.service.log.LogService;
+
+/**
+ * An implementation of Avalon's <code>LoggerManager</code> on top of OSGi's
<code>LogService</code>.
+ * OSGi's service provides no way to check if a particular log level is enabled. Rather than
always
+ * considering all levels to be enabled, which can lead to useless expensive expressions,
the maximum
+ * log level is given at manager creation time, and is uses by all log categories within
the bundle.
+ * 
+ * @version $Id: OSGiLoggerManager.java 225154 2005-07-25 17:28:56Z sylvain $
+ */
+public class OSGiLoggerManager implements LoggerManager {
+    
+    LogService logService;
+    int maxLevel;
+    
+    /**
+     * Create an <code>OSGiLoggerManager</code>.
+     * 
+     * @param ctx the <code>BundleContext</code> used to get the <code>LogService</code>
+     * @param maxLevel the maximum log level (error is the lowest, debug the highest).
+     */
+    public OSGiLoggerManager(final BundleContext ctx, int maxLevel) {
+        this.maxLevel = maxLevel;
+        
+        // Lookup the log service
+        final ServiceReference logRef = ctx.getServiceReference(LogService.class.getName());
+        this.logService = (LogService)ctx.getService(logRef);
+        
+        // FIXME: check if we need this
+        ctx.addBundleListener(new BundleListener() {
+
+            public void bundleChanged(BundleEvent ev) {
+                if (ev.getType() == BundleEvent.STOPPED) {
+                    // release the log service.
+                    ctx.ungetService(logRef);
+                }
+            }
+        });
+    }
+
+    /** Loggers by category */
+    private Map loggers = Collections.synchronizedMap(new HashMap());
+
+    public Logger getLoggerForCategory(String category) {
+        Logger result = (Logger)loggers.get(category);
+        if (result == null) {
+            result = new OSGiLogger(category);
+            loggers.put(category, result);
+        }
+        return result;
+    }
+
+    public Logger getDefaultLogger() {
+        return getLoggerForCategory("");
+    }
+    
+    /**
+     * A Logger delegating to OSGi's LogService
+     */
+    private class OSGiLogger implements Logger {
+        
+        private String category;
+
+        OSGiLogger(String category) {
+            this.category = category;
+        }
+        
+        private void log(int level, String msg) {
+            if (level <= maxLevel) {
+                logService.log(level, "[" + category + "] " + msg);
+            }
+        }
+        
+        private void log(int level, String msg, Throwable thr) {
+            if (level <= maxLevel) {
+                logService.log(level, msg, thr);
+            }
+        }
+        
+        public Logger getChildLogger(String category) {
+            return getLoggerForCategory(this.category.length() == 0 ? category : this.category
+ "." + category);
+        }
+        
+        private boolean isLevelEnabled(int level) {
+            return level <= maxLevel;
+        }
+
+        public void debug(String msg) {
+            log(LogService.LOG_DEBUG, msg);
+        }
+
+        public void debug(String msg, Throwable thr) {
+            log(LogService.LOG_DEBUG, msg, thr);
+            
+        }
+
+        public boolean isDebugEnabled() {
+            return isLevelEnabled(LogService.LOG_DEBUG);
+        }
+
+        public void info(String msg) {
+            log(LogService.LOG_INFO, msg);
+        }
+
+        public void info(String msg, Throwable thr) {
+            log(LogService.LOG_INFO, msg, thr);
+        }
+
+        public boolean isInfoEnabled() {
+            return isLevelEnabled(LogService.LOG_INFO);
+        }
+
+        public void warn(String msg) {
+            log(LogService.LOG_WARNING, msg);
+        }
+
+        public void warn(String msg, Throwable thr) {
+            log(LogService.LOG_WARNING, msg, thr);
+        }
+
+        public boolean isWarnEnabled() {
+            return isLevelEnabled(LogService.LOG_WARNING);
+        }
+
+        public void error(String msg) {
+            log(LogService.LOG_ERROR, msg);
+        }
+
+        public void error(String msg, Throwable thr) {
+            log(LogService.LOG_ERROR, msg, thr);
+        }
+
+        public boolean isErrorEnabled() {
+            return isLevelEnabled(LogService.LOG_ERROR);
+        }
+
+        public void fatalError(String msg) {
+            // OSGi has no "fatal" level
+            log(LogService.LOG_ERROR, msg);
+        }
+
+        public void fatalError(String msg, Throwable thr) {
+            // OSGi has no "fatal" level
+            log(LogService.LOG_ERROR, msg, thr);
+        }
+
+        public boolean isFatalErrorEnabled() {
+            // OSGi has no "fatal" level
+           return isLevelEnabled(LogService.LOG_ERROR);
+        }
+    }
+}

Added: cocoon/whiteboard/osgi-component-manager/src/main/java/org/apache/cocoon/core/osgi/OSGiServiceManager.java
URL: http://svn.apache.org/viewvc/cocoon/whiteboard/osgi-component-manager/src/main/java/org/apache/cocoon/core/osgi/OSGiServiceManager.java?view=auto&rev=567386
==============================================================================
--- cocoon/whiteboard/osgi-component-manager/src/main/java/org/apache/cocoon/core/osgi/OSGiServiceManager.java
(added)
+++ cocoon/whiteboard/osgi-component-manager/src/main/java/org/apache/cocoon/core/osgi/OSGiServiceManager.java
Sun Aug 19 05:20:05 2007
@@ -0,0 +1,134 @@
+/*
+ * Copyright 2005 The Apache Software Foundation
+ * Licensed  under the  Apache License,  Version 2.0  (the "License");
+ * you may not use  this file  except in  compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *   http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed  under the  License is distributed on an "AS IS" BASIS,
+ * WITHOUT  WARRANTIES OR CONDITIONS  OF ANY KIND, either  express  or
+ * implied.
+ *
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package org.apache.cocoon.core.osgi;
+
+import java.util.IdentityHashMap;
+import java.util.Map;
+
+import org.apache.avalon.framework.service.ServiceException;
+import org.apache.avalon.framework.service.ServiceManager;
+import org.osgi.framework.BundleContext;
+import org.osgi.framework.InvalidSyntaxException;
+import org.osgi.framework.ServiceReference;
+
+/**
+ * A <code>ServiceManager</code> that looks up components by getting OSGi services.
+ * <p>
+ * Roles are supposed to be interface names, which the OSGi framework will use. As some
+ * roles may contain hints (e.g. "org.apache.cocoon.generation.Generator/file"), in such
+ * cases the interface name is extracted, and the hint is expected to be found in the
+ * "<code>component.hint</code>" service property.
+ *
+ * @version SVN $Id: OSGiServiceManager.java 225154 2005-07-25 17:28:56Z sylvain $
+ */
+public class OSGiServiceManager implements ServiceManager {
+    
+    /**
+     * The property that's used to hold component hints in component selectors.
+     */
+    public static final String HINT_PROPERTY = "component.hint";
+    
+    private BundleContext context;
+
+    /** Mapping from service instance to ServiceReference */
+    private Map serviceReferences = new IdentityHashMap();
+
+    public OSGiServiceManager(BundleContext context) {
+        this.context = context;
+    }
+
+    public Object lookup(String role) throws ServiceException {
+        // Get the service
+        ServiceReference ref;
+        try {
+            ref = getServiceReference(this.context, role);
+        } catch (InvalidSyntaxException e) {
+            throw new ServiceException(role, "Cannot lookup OSGi service", e);
+        }
+
+        if (ref == null) {
+            throw new ServiceException(role, "OSGi service not available");
+        }
+        
+        // Important hypothesis: for a given (role, requesting bundle) value, OSGi
+        // always returns the same service instance. This seems to be implied by the
+        // specification, and how the knopflerfish implementation behaves.
+        Object service = context.getService(ref);
+        
+        // Keep track of its reference
+        synchronized(this) {
+            this.serviceReferences.put(service, ref);
+        }
+
+        return service;
+    }
+
+    public boolean hasService(String role) {
+        try {
+            return getServiceReference(this.context, role) != null;
+        } catch (InvalidSyntaxException e) {
+            return false;
+        }
+   }
+
+    public void release(Object obj) {
+        ServiceReference ref = (ServiceReference)this.serviceReferences.get(obj);
+        
+        if (ref == null) {
+            // not handled here
+            return;
+        }
+        
+        synchronized(this) {
+            if (this.context.ungetService(ref)) {
+                // No more used here: remove it from our map.
+                this.serviceReferences.remove(obj);
+            }
+        }
+    }
+    
+    public static ServiceReference getServiceReference(BundleContext ctx, String role) throws
InvalidSyntaxException {
+        ServiceReference result;
+
+        int pos = role.indexOf('/');
+
+        if (pos == -1) {
+            // Single interface role
+            result = ctx.getServiceReference(role);
+        } else {
+            // Hinted role: split it
+            String itf = role.substring(0, pos);
+            String query = "(" + HINT_PROPERTY + "=" + role.substring(pos + 1) + ")";
+            ServiceReference[] results = ctx.getServiceReferences(itf, query);
+            result = (results != null && results.length > 1) ? results[0] : null;
+        }
+
+        return result;
+    }
+    
+    public static String getServiceInterface(String role) {
+        int pos = role.indexOf('/');
+        
+        return pos == -1 ? role : role.substring(0, pos);
+    }
+    
+    public static String getServiceHint(String role) {
+        int pos = role.indexOf('/');
+        return pos == -1 ? null : role.substring(pos+1);
+    }
+}

Added: cocoon/whiteboard/osgi-component-manager/src/main/java/org/apache/cocoon/core/osgi/ServiceManagerActivator.java
URL: http://svn.apache.org/viewvc/cocoon/whiteboard/osgi-component-manager/src/main/java/org/apache/cocoon/core/osgi/ServiceManagerActivator.java?view=auto&rev=567386
==============================================================================
--- cocoon/whiteboard/osgi-component-manager/src/main/java/org/apache/cocoon/core/osgi/ServiceManagerActivator.java
(added)
+++ cocoon/whiteboard/osgi-component-manager/src/main/java/org/apache/cocoon/core/osgi/ServiceManagerActivator.java
Sun Aug 19 05:20:05 2007
@@ -0,0 +1,97 @@
+/*
+ * Copyright 2005 The Apache Software Foundation
+ * Licensed  under the  Apache License,  Version 2.0  (the "License");
+ * you may not use  this file  except in  compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *   http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed  under the  License is distributed on an "AS IS" BASIS,
+ * WITHOUT  WARRANTIES OR CONDITIONS  OF ANY KIND, either  express  or
+ * implied.
+ *
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.apache.cocoon.core.osgi;
+
+import java.net.URL;
+
+import org.apache.avalon.excalibur.logger.LoggerManager;
+import org.apache.avalon.framework.configuration.DefaultConfiguration;
+import org.apache.avalon.framework.context.DefaultContext;
+import org.apache.avalon.framework.service.ServiceManager;
+import org.apache.cocoon.components.container.ComponentContext;
+import org.osgi.framework.BundleActivator;
+import org.osgi.framework.BundleContext;
+import org.osgi.service.log.LogService;
+
+public class ServiceManagerActivator implements BundleActivator {
+
+
+//  Registering services must go through the ServiceFactory class wrapping the componentHandler
+    
+    private OSGiCoreServiceManager manager;
+
+    public void start(final BundleContext ctx) throws Exception {
+        
+        // Create a logger manager that delegates to OSGi
+        // FIXME: have the maximum level as a property of the bundle
+        LoggerManager logManager = new OSGiLoggerManager(ctx, LogService.LOG_DEBUG);
+
+        // Create a parent manager that will lookup registered OSGi services
+        ServiceManager parentManager = new OSGiServiceManager(ctx);
+        
+        // Create a regular manager
+        this.manager = new OSGiCoreServiceManager(parentManager, this.getClass().getClassLoader(),
ctx) {
+        };
+        
+        //---- LogEnabled
+        this.manager.enableLogging(logManager.getDefaultLogger());
+        
+        //---- Contextualizable
+        DefaultContext avalonCtx = new ComponentContext();
+        // Context entries defined in CocoonServlet/CoreUtil:
+        // "servlet-config"
+        // "servlet-context"
+        // ContextHelper.CONTEXT_ROOT_URL
+        // Constants.CONTEXT_ENVIRONMENT_CONTEXT
+        // Constants.CONTEXT_WORK_DIR
+        // Constants.CONTEXT_UPLOAD_DIR
+        // Constants.CONTEXT_CACHE_DIR
+        // Constants.CONTEXT_CONFIG_URL
+        // Constants.CONTEXT_DEFAULT_ENCODING
+        // Constants.CONTEXT_CLASS_LOADER
+        // Core.ROLE (???)
+        // Constants.CONTEXT_CLASSPATH
+
+        this.manager.contextualize(avalonCtx);
+        
+        //---- LoggerManager
+        this.manager.setLoggerManager(logManager);
+        
+        //---- RoleManager
+        // No parent role manager
+        this.manager.setRoleManager(null);
+        
+        //---- Configurable
+        // Create a configuration object with one include directive. ECM++ will do the rest!
+        DefaultConfiguration config = new DefaultConfiguration("cocoon");
+        DefaultConfiguration include = new DefaultConfiguration("include");
+        URL confURL = ctx.getBundle().getResource("/BLOCK-INF/block.xconf");
+        include.setAttribute("src", confURL.toExternalForm());
+        config.addChild(include);
+        
+        this.manager.configure(config);
+        
+        //---- Initializable
+        this.manager.initialize();
+
+    }
+
+    public void stop(BundleContext ctx) throws Exception {
+        // Dispose the ServiceManager
+        this.manager.dispose();
+    }
+}



Mime
View raw message