incubator-sling-commits mailing list archives

Site index · List index
Message view « Date » · « Thread »
Top « Date » · « Thread »
From jus...@apache.org
Subject svn commit: r941044 - in /sling/trunk: bundles/scripting/api/ bundles/scripting/api/src/main/java/org/apache/sling/scripting/api/ bundles/scripting/core/ bundles/scripting/core/src/main/java/org/apache/sling/scripting/core/impl/ bundles/scripting/core/...
Date Tue, 04 May 2010 21:16:48 GMT
Author: justin
Date: Tue May  4 21:16:46 2010
New Revision: 941044

URL: http://svn.apache.org/viewvc?rev=941044&view=rev
Log:
SLING-1510 - reimplemented solution as a standalone service of ScriptEngineManager support
into a separate component

Added:
    sling/trunk/bundles/scripting/core/src/main/java/org/apache/sling/scripting/core/impl/ScriptEngineManagerFactory.java
    sling/trunk/bundles/scripting/core/src/test/java/org/apache/sling/scripting/core/impl/DummyScriptEngineFactory.java
    sling/trunk/bundles/scripting/core/src/test/java/org/apache/sling/scripting/core/impl/ScriptEngineManagerFactoryTest.java
Removed:
    sling/trunk/bundles/scripting/api/src/main/java/org/apache/sling/scripting/api/ScriptEngineManagerFactory.java
Modified:
    sling/trunk/bundles/scripting/api/pom.xml
    sling/trunk/bundles/scripting/core/pom.xml
    sling/trunk/bundles/scripting/core/src/main/java/org/apache/sling/scripting/core/impl/ScriptEngineConsolePlugin.java
    sling/trunk/bundles/scripting/core/src/main/java/org/apache/sling/scripting/core/impl/SlingScriptAdapterFactory.java
    sling/trunk/launchpad/builder/src/main/bundles/list.xml

Modified: sling/trunk/bundles/scripting/api/pom.xml
URL: http://svn.apache.org/viewvc/sling/trunk/bundles/scripting/api/pom.xml?rev=941044&r1=941043&r2=941044&view=diff
==============================================================================
--- sling/trunk/bundles/scripting/api/pom.xml (original)
+++ sling/trunk/bundles/scripting/api/pom.xml Tue May  4 21:16:46 2010
@@ -55,7 +55,7 @@
                 <configuration>
                     <instructions>
                         <Export-Package>
-                            org.apache.sling.scripting.api;version=2.2.0,
+                            org.apache.sling.scripting.api;version=2.1.0,
                             javax.script
                         </Export-Package>
                         <Private-Package>

Modified: sling/trunk/bundles/scripting/core/pom.xml
URL: http://svn.apache.org/viewvc/sling/trunk/bundles/scripting/core/pom.xml?rev=941044&r1=941043&r2=941044&view=diff
==============================================================================
--- sling/trunk/bundles/scripting/core/pom.xml (original)
+++ sling/trunk/bundles/scripting/core/pom.xml Tue May  4 21:16:46 2010
@@ -103,7 +103,7 @@
         <dependency>
             <groupId>org.apache.sling</groupId>
             <artifactId>org.apache.sling.scripting.api</artifactId>
-            <version>2.1.1-SNAPSHOT</version>
+            <version>2.1.0</version>
             <scope>provided</scope>
         </dependency>
         <dependency>
@@ -132,5 +132,23 @@
             <artifactId>junit</artifactId>
         </dependency>
 
+        <dependency>
+            <groupId>org.jmock</groupId>
+            <artifactId>jmock-junit4</artifactId>
+        </dependency>
+
+        <dependency>
+        	<groupId>org.slf4j</groupId>
+        	<artifactId>slf4j-simple</artifactId>
+        	<version>1.5.2</version>
+        	<scope>test</scope>
+        </dependency>
+
+        <dependency>
+        	<groupId>org.apache.sling</groupId>
+        	<artifactId>org.apache.sling.commons.testing</artifactId>
+        	<version>2.0.4-incubator</version>
+        	<scope>test</scope>
+        </dependency>
     </dependencies>
 </project>

Modified: sling/trunk/bundles/scripting/core/src/main/java/org/apache/sling/scripting/core/impl/ScriptEngineConsolePlugin.java
URL: http://svn.apache.org/viewvc/sling/trunk/bundles/scripting/core/src/main/java/org/apache/sling/scripting/core/impl/ScriptEngineConsolePlugin.java?rev=941044&r1=941043&r2=941044&view=diff
==============================================================================
--- sling/trunk/bundles/scripting/core/src/main/java/org/apache/sling/scripting/core/impl/ScriptEngineConsolePlugin.java
(original)
+++ sling/trunk/bundles/scripting/core/src/main/java/org/apache/sling/scripting/core/impl/ScriptEngineConsolePlugin.java
Tue May  4 21:16:46 2010
@@ -39,10 +39,10 @@ public class ScriptEngineConsolePlugin i
     private static ScriptEngineConsolePlugin INSTANCE;
 
     static void initPlugin(BundleContext context,
-            SlingScriptAdapterFactory scriptAdapterFactory) {
+            ScriptEngineManagerFactory scriptEngineManagerFactory) {
         if (INSTANCE == null) {
             ScriptEngineConsolePlugin tmp = new ScriptEngineConsolePlugin(
-                scriptAdapterFactory);
+                    scriptEngineManagerFactory);
             tmp.activate(context);
             INSTANCE = tmp;
         }
@@ -60,12 +60,12 @@ public class ScriptEngineConsolePlugin i
 
     private ServiceRegistration serviceRegistration;
 
-    private final SlingScriptAdapterFactory scriptAdapterFactory;
+    private final ScriptEngineManagerFactory scriptEngineManagerFactory;
 
     // private constructor to force using static setup and shutdown
     private ScriptEngineConsolePlugin(
-            SlingScriptAdapterFactory scriptAdapterFactory) {
-        this.scriptAdapterFactory = scriptAdapterFactory;
+            ScriptEngineManagerFactory scriptEngineManagerFactory) {
+        this.scriptEngineManagerFactory = scriptEngineManagerFactory;
     }
 
     public String getTitle() {
@@ -76,7 +76,7 @@ public class ScriptEngineConsolePlugin i
         pw.println("Available Script Engines");
         pw.println("========================");
 
-        ScriptEngineManager manager = scriptAdapterFactory.getScriptEngineManager();
+        ScriptEngineManager manager = scriptEngineManagerFactory.getScriptEngineManager();
         List<?> factories = manager.getEngineFactories();
         for (Iterator<?> fi = factories.iterator(); fi.hasNext();) {
 

Added: sling/trunk/bundles/scripting/core/src/main/java/org/apache/sling/scripting/core/impl/ScriptEngineManagerFactory.java
URL: http://svn.apache.org/viewvc/sling/trunk/bundles/scripting/core/src/main/java/org/apache/sling/scripting/core/impl/ScriptEngineManagerFactory.java?rev=941044&view=auto
==============================================================================
--- sling/trunk/bundles/scripting/core/src/main/java/org/apache/sling/scripting/core/impl/ScriptEngineManagerFactory.java
(added)
+++ sling/trunk/bundles/scripting/core/src/main/java/org/apache/sling/scripting/core/impl/ScriptEngineManagerFactory.java
Tue May  4 21:16:46 2010
@@ -0,0 +1,276 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with this
+ * work for additional information regarding copyright ownership. The ASF
+ * licenses this file to You under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
+ * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
+ * License for the specific language governing permissions and limitations under
+ * the License.
+ */
+package org.apache.sling.scripting.core.impl;
+
+import java.io.BufferedReader;
+import java.io.IOException;
+import java.io.InputStream;
+import java.io.InputStreamReader;
+import java.net.URL;
+import java.util.Collection;
+import java.util.Dictionary;
+import java.util.Hashtable;
+import java.util.LinkedList;
+import java.util.List;
+import java.util.SortedSet;
+import java.util.TreeSet;
+
+import javax.script.ScriptEngine;
+import javax.script.ScriptEngineFactory;
+import javax.script.ScriptEngineManager;
+
+import org.apache.sling.api.scripting.SlingScriptConstants;
+import org.apache.sling.scripting.core.impl.helper.SlingScriptEngineManager;
+import org.osgi.framework.Bundle;
+import org.osgi.framework.BundleContext;
+import org.osgi.framework.BundleEvent;
+import org.osgi.framework.BundleListener;
+import org.osgi.framework.ServiceRegistration;
+import org.osgi.service.component.ComponentContext;
+import org.osgi.service.event.Event;
+import org.osgi.service.event.EventAdmin;
+import org.osgi.util.tracker.ServiceTracker;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+/**
+ * Component which exposes a ScriptEngineManager service.
+ *
+ * @scr.component metatype="no" immediate="true"
+ * @scr.reference name="ScriptEngineFactory"
+ *                interface="javax.script.ScriptEngineFactory"
+ *                cardinality="0..n" policy="dynamic"
+ */
+public class ScriptEngineManagerFactory implements BundleListener {
+
+    private final Logger log = LoggerFactory.getLogger(ScriptEngineManagerFactory.class);
+
+    private static final String ENGINE_FACTORY_SERVICE = "META-INF/services/" + ScriptEngineFactory.class.getName();
+
+    private BundleContext bundleContext;
+
+    /**
+     * The service tracker for the event admin
+     */
+    private ServiceTracker eventAdminTracker;
+
+    private ScriptEngineManager scriptEngineManager;
+
+    private List<Bundle> engineSpiBundles = new LinkedList<Bundle>();
+
+    private List<ScriptEngineFactory> engineSpiServices = new LinkedList<ScriptEngineFactory>();
+
+    private ServiceRegistration scriptEngineManagerRegistration;
+
+    @SuppressWarnings("unchecked")
+    private void refreshScriptEngineManager() {
+        if (scriptEngineManagerRegistration != null) {
+            scriptEngineManagerRegistration.unregister();
+        }
+        // create (empty) script engine manager
+        ClassLoader loader = getClass().getClassLoader();
+        SlingScriptEngineManager tmp = new SlingScriptEngineManager(loader);
+
+        // register script engines from bundles
+        final SortedSet<Object> extensions = new TreeSet<Object>();
+        for (Bundle bundle : engineSpiBundles) {
+            extensions.addAll(registerFactories(tmp, bundle));
+        }
+
+        // register script engines from registered services
+        for (ScriptEngineFactory factory : engineSpiServices) {
+            extensions.addAll(registerFactory(tmp, factory));
+        }
+
+        scriptEngineManager = tmp;
+        scriptEngineManagerRegistration = bundleContext.registerService(ScriptEngineManager.class.getName(),
+                scriptEngineManager, new Hashtable());
+
+        // Log messages to verify which ScriptEngine is actually used
+        // for our registered extensions
+        if (log.isInfoEnabled()) {
+            for (Object o : extensions) {
+                final String ext = o.toString();
+                final ScriptEngine e = scriptEngineManager.getEngineByExtension(ext);
+                if (e == null) {
+                    log.warn("No ScriptEngine found for extension '{}' that was just registered",
ext);
+                } else {
+                    log.info("Script extension '{}' is now handled by ScriptEngine '{}',
version='{}', class='{}'", new Object[] { ext,
+                            e.getFactory().getEngineName(), e.getFactory().getEngineVersion(),
e.getClass().getName() });
+                }
+            }
+        }
+    }
+
+    @SuppressWarnings("unchecked")
+    private Collection<?> registerFactories(SlingScriptEngineManager mgr, Bundle bundle)
{
+        URL url = bundle.getEntry(ENGINE_FACTORY_SERVICE);
+        InputStream ins = null;
+        final SortedSet<String> extensions = new TreeSet<String>();
+        try {
+            ins = url.openStream();
+            BufferedReader reader = new BufferedReader(new InputStreamReader(ins));
+            String line;
+            while ((line = reader.readLine()) != null) {
+                try {
+                    Class<ScriptEngineFactory> clazz = bundle.loadClass(line);
+                    ScriptEngineFactory spi = clazz.newInstance();
+                    registerFactory(mgr, spi);
+                    extensions.addAll(spi.getExtensions());
+                } catch (Throwable t) {
+                    log.error("Cannot register ScriptEngineFactory " + line, t);
+                }
+            }
+        } catch (IOException ioe) {
+        } finally {
+            if (ins != null) {
+                try {
+                    ins.close();
+                } catch (IOException ioe) {
+                }
+            }
+        }
+
+        return extensions;
+    }
+
+    private Collection<?> registerFactory(SlingScriptEngineManager mgr, ScriptEngineFactory
factory) {
+        log.info("Adding ScriptEngine {}, {} for language {}, {}", new Object[] { factory.getEngineName(),
factory.getEngineVersion(),
+                factory.getLanguageName(), factory.getLanguageVersion() });
+
+        mgr.registerScriptEngineFactory(factory);
+
+        return factory.getExtensions();
+    }
+
+    // ---------- BundleListener interface -------------------------------------
+
+    public void bundleChanged(BundleEvent event) {
+        if (event.getType() == BundleEvent.STARTED && event.getBundle().getEntry(ENGINE_FACTORY_SERVICE)
!= null) {
+
+            engineSpiBundles.add(event.getBundle());
+            refreshScriptEngineManager();
+
+        } else if (event.getType() == BundleEvent.STOPPED && engineSpiBundles.remove(event.getBundle()))
{
+
+            refreshScriptEngineManager();
+
+        }
+    }
+
+    // ---------- SCR integration ----------------------------------------------
+
+    protected void activate(ComponentContext context) {
+        this.bundleContext = context.getBundleContext();
+
+        // setup tracker first as this is used in the bind/unbind methods
+        this.eventAdminTracker = new ServiceTracker(this.bundleContext, EventAdmin.class.getName(),
null);
+        this.eventAdminTracker.open();
+
+
+
+        this.bundleContext.addBundleListener(this);
+
+        Bundle[] bundles = this.bundleContext.getBundles();
+        for (Bundle bundle : bundles) {
+            if (bundle.getState() == Bundle.ACTIVE && bundle.getEntry(ENGINE_FACTORY_SERVICE)
!= null) {
+                engineSpiBundles.add(bundle);
+            }
+        }
+
+        try {
+            org.apache.sling.scripting.core.impl.ScriptEngineConsolePlugin.initPlugin(context.getBundleContext(),
this);
+        } catch (Throwable t) {
+            // so what ?
+        }
+
+        refreshScriptEngineManager();
+    }
+
+    protected void deactivate(ComponentContext context) {
+        try {
+            org.apache.sling.scripting.core.impl.ScriptEngineConsolePlugin.destroyPlugin();
+        } catch (Throwable t) {
+            // so what ?
+        }
+
+        context.getBundleContext().removeBundleListener(this);
+
+        engineSpiBundles.clear();
+        engineSpiServices.clear();
+        scriptEngineManager = null;
+        if (scriptEngineManagerRegistration != null) {
+            scriptEngineManagerRegistration.unregister();
+        }
+        if (this.eventAdminTracker != null) {
+            this.eventAdminTracker.close();
+            this.eventAdminTracker = null;
+        }
+        this.bundleContext = null;
+    }
+
+
+
+    protected void bindScriptEngineFactory(ScriptEngineFactory scriptEngineFactory) {
+        engineSpiServices.add(scriptEngineFactory);
+        refreshScriptEngineManager();
+        // send event
+        postEvent(SlingScriptConstants.TOPIC_SCRIPT_ENGINE_FACTORY_ADDED, scriptEngineFactory);
+    }
+
+    protected void unbindScriptEngineFactory(ScriptEngineFactory scriptEngineFactory) {
+        engineSpiServices.remove(scriptEngineFactory);
+        refreshScriptEngineManager();
+        // send event
+        postEvent(SlingScriptConstants.TOPIC_SCRIPT_ENGINE_FACTORY_REMOVED, scriptEngineFactory);
+    }
+
+    /**
+     * Get the event admin.
+     *
+     * @return The event admin or <code>null</code>
+     */
+    private EventAdmin getEventAdmin() {
+        return (EventAdmin) (this.eventAdminTracker != null ? this.eventAdminTracker.getService()
: null);
+    }
+
+    @SuppressWarnings("unchecked")
+    private String[] toArray(List list) {
+        return (String[]) list.toArray(new String[list.size()]);
+    }
+
+    private void postEvent(final String topic, final ScriptEngineFactory scriptEngineFactory)
{
+        final EventAdmin localEA = this.getEventAdmin();
+        if (localEA != null) {
+            final Dictionary<String, Object> props = new Hashtable<String, Object>();
+            props.put(SlingScriptConstants.PROPERTY_SCRIPT_ENGINE_FACTORY_NAME, scriptEngineFactory.getEngineName());
+            props.put(SlingScriptConstants.PROPERTY_SCRIPT_ENGINE_FACTORY_VERSION, scriptEngineFactory.getEngineVersion());
+            props.put(SlingScriptConstants.PROPERTY_SCRIPT_ENGINE_FACTORY_EXTENSIONS, toArray(scriptEngineFactory.getExtensions()));
+            props.put(SlingScriptConstants.PROPERTY_SCRIPT_ENGINE_FACTORY_LANGUAGE_NAME,
scriptEngineFactory.getLanguageName());
+            props.put(SlingScriptConstants.PROPERTY_SCRIPT_ENGINE_FACTORY_LANGUAGE_VERSION,
scriptEngineFactory.getLanguageVersion());
+            props.put(SlingScriptConstants.PROPERTY_SCRIPT_ENGINE_FACTORY_MIME_TYPES, toArray(scriptEngineFactory.getMimeTypes()));
+            localEA.postEvent(new Event(topic, props));
+        }
+    }
+
+
+    ScriptEngineManager getScriptEngineManager() {
+        return scriptEngineManager;
+    }
+
+
+}

Modified: sling/trunk/bundles/scripting/core/src/main/java/org/apache/sling/scripting/core/impl/SlingScriptAdapterFactory.java
URL: http://svn.apache.org/viewvc/sling/trunk/bundles/scripting/core/src/main/java/org/apache/sling/scripting/core/impl/SlingScriptAdapterFactory.java?rev=941044&r1=941043&r2=941044&view=diff
==============================================================================
--- sling/trunk/bundles/scripting/core/src/main/java/org/apache/sling/scripting/core/impl/SlingScriptAdapterFactory.java
(original)
+++ sling/trunk/bundles/scripting/core/src/main/java/org/apache/sling/scripting/core/impl/SlingScriptAdapterFactory.java
Tue May  4 21:16:46 2010
@@ -16,22 +16,12 @@
  */
 package org.apache.sling.scripting.core.impl;
 
-import java.io.BufferedReader;
-import java.io.IOException;
-import java.io.InputStream;
-import java.io.InputStreamReader;
-import java.net.URL;
 import java.util.ArrayList;
 import java.util.Arrays;
 import java.util.Collection;
-import java.util.Dictionary;
 import java.util.HashMap;
-import java.util.Hashtable;
-import java.util.LinkedList;
 import java.util.List;
 import java.util.Map;
-import java.util.SortedSet;
-import java.util.TreeSet;
 
 import javax.script.Bindings;
 import javax.script.ScriptEngine;
@@ -40,22 +30,14 @@ import javax.script.ScriptEngineManager;
 
 import org.apache.sling.api.adapter.AdapterFactory;
 import org.apache.sling.api.resource.Resource;
-import org.apache.sling.api.scripting.SlingScriptConstants;
 import org.apache.sling.commons.mime.MimeTypeProvider;
 import org.apache.sling.scripting.api.BindingsValuesProvider;
-import org.apache.sling.scripting.api.ScriptEngineManagerFactory;
-import org.apache.sling.scripting.core.impl.helper.SlingScriptEngineManager;
-import org.osgi.framework.Bundle;
 import org.osgi.framework.BundleContext;
-import org.osgi.framework.BundleEvent;
-import org.osgi.framework.BundleListener;
 import org.osgi.framework.Constants;
 import org.osgi.framework.Filter;
 import org.osgi.framework.InvalidSyntaxException;
 import org.osgi.framework.ServiceReference;
 import org.osgi.service.component.ComponentContext;
-import org.osgi.service.event.Event;
-import org.osgi.service.event.EventAdmin;
 import org.osgi.util.tracker.ServiceTracker;
 import org.osgi.util.tracker.ServiceTrackerCustomizer;
 import org.slf4j.Logger;
@@ -74,35 +56,18 @@ import org.slf4j.LoggerFactory;
  *               values.0="org.apache.sling.api.scripting.SlingScript"
  *               values.1="javax.servlet.Servlet"
  * @scr.service interface="org.apache.sling.api.adapter.AdapterFactory"
- * @scr.service interface="org.apache.sling.scripting.api.ScriptEngineManagerFactory"
  * @scr.service interface="org.apache.sling.commons.mime.MimeTypeProvider"
- * @scr.reference name="ScriptEngineFactory"
- *                interface="javax.script.ScriptEngineFactory"
- *                cardinality="0..n" policy="dynamic"
  */
-public class SlingScriptAdapterFactory implements AdapterFactory, MimeTypeProvider, BundleListener,
ScriptEngineManagerFactory {
+public class SlingScriptAdapterFactory implements AdapterFactory, MimeTypeProvider {
 
     private final Logger log = LoggerFactory.getLogger(SlingScriptAdapterFactory.class);
 
-    private static final String ENGINE_FACTORY_SERVICE = "META-INF/services/" + ScriptEngineFactory.class.getName();
-
     /** list of service property values which indicate 'any' script engine */
     private static final List<String> ANY_ENGINE = Arrays.asList("*", "ANY");
 
-    private ScriptEngineManager scriptEngineManager;
-
-    private List<Bundle> engineSpiBundles = new LinkedList<Bundle>();
-
-    private List<ScriptEngineFactory> engineSpiServices = new LinkedList<ScriptEngineFactory>();
-
     private BundleContext bundleContext;
 
     /**
-     * The service tracker for the event admin
-     */
-    private ServiceTracker eventAdminTracker;
-
-    /**
      * The service tracker for BindingsValuesProvider impls
      */
     private ServiceTracker bindingsValuesProviderTracker;
@@ -127,6 +92,13 @@ public class SlingScriptAdapterFactory i
      */
     private ServiceCache serviceCache;
 
+    /**
+     * The script engine manager.
+     *
+     * @scr.reference
+     */
+    private ScriptEngineManager scriptEngineManager;
+
     // ---------- AdapterFactory -----------------------------------------------
 
     @SuppressWarnings("unchecked")
@@ -136,7 +108,7 @@ public class SlingScriptAdapterFactory i
         String path = resource.getPath();
         String ext = path.substring(path.lastIndexOf('.') + 1);
 
-        ScriptEngine engine = getScriptEngineManager().getEngineByExtension(ext);
+        ScriptEngine engine = scriptEngineManager.getEngineByExtension(ext);
         if (engine != null) {
             Collection<BindingsValuesProvider> bindingsValuesProviders = getBindingsValuesProviders(engine.getFactory());
             // unchecked cast
@@ -147,100 +119,6 @@ public class SlingScriptAdapterFactory i
         return null;
     }
 
-    public ScriptEngineManager getScriptEngineManager() {
-        if (scriptEngineManager == null) {
-
-            // create (empty) script engine manager
-            ClassLoader loader = getClass().getClassLoader();
-            SlingScriptEngineManager tmp = new SlingScriptEngineManager(loader);
-
-            // register script engines from bundles
-            final SortedSet<Object> extensions = new TreeSet<Object>();
-            for (Bundle bundle : engineSpiBundles) {
-                extensions.addAll(registerFactories(tmp, bundle));
-            }
-
-            // register script engines from registered services
-            for (ScriptEngineFactory factory : engineSpiServices) {
-                extensions.addAll(registerFactory(tmp, factory));
-            }
-
-            scriptEngineManager = tmp;
-
-            // Log messages to verify which ScriptEngine is actually used
-            // for our registered extensions
-            if (log.isInfoEnabled()) {
-                for (Object o : extensions) {
-                    final String ext = o.toString();
-                    final ScriptEngine e = scriptEngineManager.getEngineByExtension(ext);
-                    if (e == null) {
-                        log.warn("No ScriptEngine found for extension '{}' that was just
registered", ext);
-                    } else {
-                        log.info("Script extension '{}' is now handled by ScriptEngine '{}',
version='{}', class='{}'", new Object[] { ext,
-                                e.getFactory().getEngineName(), e.getFactory().getEngineVersion(),
e.getClass().getName() });
-                    }
-                }
-            }
-        }
-        return scriptEngineManager;
-    }
-
-    @SuppressWarnings("unchecked")
-    private Collection<?> registerFactories(SlingScriptEngineManager mgr, Bundle bundle)
{
-        URL url = bundle.getEntry(ENGINE_FACTORY_SERVICE);
-        InputStream ins = null;
-        final SortedSet<String> extensions = new TreeSet<String>();
-        try {
-            ins = url.openStream();
-            BufferedReader reader = new BufferedReader(new InputStreamReader(ins));
-            String line;
-            while ((line = reader.readLine()) != null) {
-                try {
-                    Class<ScriptEngineFactory> clazz = bundle.loadClass(line);
-                    ScriptEngineFactory spi = clazz.newInstance();
-                    registerFactory(mgr, spi);
-                    extensions.addAll(spi.getExtensions());
-                } catch (Throwable t) {
-                    log.error("Cannot register ScriptEngineFactory " + line, t);
-                }
-            }
-        } catch (IOException ioe) {
-        } finally {
-            if (ins != null) {
-                try {
-                    ins.close();
-                } catch (IOException ioe) {
-                }
-            }
-        }
-
-        return extensions;
-    }
-
-    private Collection<?> registerFactory(SlingScriptEngineManager mgr, ScriptEngineFactory
factory) {
-        log.info("Adding ScriptEngine {}, {} for language {}, {}", new Object[] { factory.getEngineName(),
factory.getEngineVersion(),
-                factory.getLanguageName(), factory.getLanguageVersion() });
-
-        mgr.registerScriptEngineFactory(factory);
-
-        return factory.getExtensions();
-    }
-
-    // ---------- BundleListener interface -------------------------------------
-
-    public void bundleChanged(BundleEvent event) {
-        if (event.getType() == BundleEvent.STARTED && event.getBundle().getEntry(ENGINE_FACTORY_SERVICE)
!= null) {
-
-            engineSpiBundles.add(event.getBundle());
-            scriptEngineManager = null;
-
-        } else if (event.getType() == BundleEvent.STOPPED && engineSpiBundles.remove(event.getBundle()))
{
-
-            scriptEngineManager = null;
-
-        }
-    }
-
     // ---------- MimeTypeProvider
 
     /**
@@ -257,7 +135,7 @@ public class SlingScriptAdapterFactory i
      */
     public String getMimeType(String name) {
         name = name.substring(name.lastIndexOf('.') + 1);
-        ScriptEngine se = getScriptEngineManager().getEngineByExtension(name);
+        ScriptEngine se = scriptEngineManager.getEngineByExtension(name);
         if (se != null) {
             List<?> mimeTypes = se.getFactory().getMimeTypes();
             if (mimeTypes != null && mimeTypes.size() > 0) {
@@ -278,7 +156,7 @@ public class SlingScriptAdapterFactory i
      * @param mimeType The MIME type to be mapped to an extension.
      */
     public String getExtension(String mimeType) {
-        ScriptEngine se = getScriptEngineManager().getEngineByMimeType(mimeType);
+        ScriptEngine se = scriptEngineManager.getEngineByMimeType(mimeType);
         if (se != null) {
             List<?> extensions = se.getFactory().getExtensions();
             if (extensions != null && extensions.size() > 0) {
@@ -294,10 +172,6 @@ public class SlingScriptAdapterFactory i
     protected void activate(ComponentContext context) {
         this.bundleContext = context.getBundleContext();
 
-        // setup tracker first as this is used in the bind/unbind methods
-        this.eventAdminTracker = new ServiceTracker(this.bundleContext, EventAdmin.class.getName(),
null);
-        this.eventAdminTracker.open();
-
         this.genericBindingsValuesProviders = new HashMap<Object, BindingsValuesProvider>();
         this.langBindingsValuesProviders = new HashMap<String, Map<Object, BindingsValuesProvider>>();
 
@@ -315,21 +189,6 @@ public class SlingScriptAdapterFactory i
         } catch (InvalidSyntaxException e) {
             log.warn("Unable to create ServiceTracker for Map-based script bindiings", e);
         }
-
-        this.bundleContext.addBundleListener(this);
-
-        Bundle[] bundles = this.bundleContext.getBundles();
-        for (Bundle bundle : bundles) {
-            if (bundle.getState() == Bundle.ACTIVE && bundle.getEntry(ENGINE_FACTORY_SERVICE)
!= null) {
-                engineSpiBundles.add(bundle);
-            }
-        }
-
-        try {
-            org.apache.sling.scripting.core.impl.ScriptEngineConsolePlugin.initPlugin(context.getBundleContext(),
this);
-        } catch (Throwable t) {
-            // so what ?
-        }
         this.serviceCache = new ServiceCache(this.bundleContext);
     }
 
@@ -337,21 +196,6 @@ public class SlingScriptAdapterFactory i
         this.serviceCache.dispose();
         this.serviceCache = null;
 
-        try {
-            org.apache.sling.scripting.core.impl.ScriptEngineConsolePlugin.destroyPlugin();
-        } catch (Throwable t) {
-            // so what ?
-        }
-
-        context.getBundleContext().removeBundleListener(this);
-
-        engineSpiBundles.clear();
-        engineSpiServices.clear();
-        scriptEngineManager = null;
-        if (this.eventAdminTracker != null) {
-            this.eventAdminTracker.close();
-            this.eventAdminTracker = null;
-        }
         if (this.bindingsValuesProviderTracker != null) {
             this.bindingsValuesProviderTracker.close();
             this.bindingsValuesProviderTracker = null;
@@ -363,34 +207,6 @@ public class SlingScriptAdapterFactory i
         this.bundleContext = null;
     }
 
-    /**
-     * Get the event admin.
-     *
-     * @return The event admin or <code>null</code>
-     */
-    private EventAdmin getEventAdmin() {
-        return (EventAdmin) (this.eventAdminTracker != null ? this.eventAdminTracker.getService()
: null);
-    }
-
-    @SuppressWarnings("unchecked")
-    private String[] toArray(List list) {
-        return (String[]) list.toArray(new String[list.size()]);
-    }
-
-    private void postEvent(final String topic, final ScriptEngineFactory scriptEngineFactory)
{
-        final EventAdmin localEA = this.getEventAdmin();
-        if (localEA != null) {
-            final Dictionary<String, Object> props = new Hashtable<String, Object>();
-            props.put(SlingScriptConstants.PROPERTY_SCRIPT_ENGINE_FACTORY_NAME, scriptEngineFactory.getEngineName());
-            props.put(SlingScriptConstants.PROPERTY_SCRIPT_ENGINE_FACTORY_VERSION, scriptEngineFactory.getEngineVersion());
-            props.put(SlingScriptConstants.PROPERTY_SCRIPT_ENGINE_FACTORY_EXTENSIONS, toArray(scriptEngineFactory.getExtensions()));
-            props.put(SlingScriptConstants.PROPERTY_SCRIPT_ENGINE_FACTORY_LANGUAGE_NAME,
scriptEngineFactory.getLanguageName());
-            props.put(SlingScriptConstants.PROPERTY_SCRIPT_ENGINE_FACTORY_LANGUAGE_VERSION,
scriptEngineFactory.getLanguageVersion());
-            props.put(SlingScriptConstants.PROPERTY_SCRIPT_ENGINE_FACTORY_MIME_TYPES, toArray(scriptEngineFactory.getMimeTypes()));
-            localEA.postEvent(new Event(topic, props));
-        }
-    }
-
     private Collection<BindingsValuesProvider> getBindingsValuesProviders(ScriptEngineFactory
scriptEngineFactory) {
         List<BindingsValuesProvider> results = new ArrayList<BindingsValuesProvider>();
         results.addAll(genericBindingsValuesProviders.values());
@@ -403,20 +219,6 @@ public class SlingScriptAdapterFactory i
         return results;
     }
 
-    protected void bindScriptEngineFactory(ScriptEngineFactory scriptEngineFactory) {
-        engineSpiServices.add(scriptEngineFactory);
-        scriptEngineManager = null;
-        // send event
-        postEvent(SlingScriptConstants.TOPIC_SCRIPT_ENGINE_FACTORY_ADDED, scriptEngineFactory);
-    }
-
-    protected void unbindScriptEngineFactory(ScriptEngineFactory scriptEngineFactory) {
-        engineSpiServices.remove(scriptEngineFactory);
-        scriptEngineManager = null;
-        // send event
-        postEvent(SlingScriptConstants.TOPIC_SCRIPT_ENGINE_FACTORY_REMOVED, scriptEngineFactory);
-    }
-
     private class BindingsValuesProviderCustomizer implements ServiceTrackerCustomizer {
 
         @SuppressWarnings("unchecked")

Added: sling/trunk/bundles/scripting/core/src/test/java/org/apache/sling/scripting/core/impl/DummyScriptEngineFactory.java
URL: http://svn.apache.org/viewvc/sling/trunk/bundles/scripting/core/src/test/java/org/apache/sling/scripting/core/impl/DummyScriptEngineFactory.java?rev=941044&view=auto
==============================================================================
--- sling/trunk/bundles/scripting/core/src/test/java/org/apache/sling/scripting/core/impl/DummyScriptEngineFactory.java
(added)
+++ sling/trunk/bundles/scripting/core/src/test/java/org/apache/sling/scripting/core/impl/DummyScriptEngineFactory.java
Tue May  4 21:16:46 2010
@@ -0,0 +1,145 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with this
+ * work for additional information regarding copyright ownership. The ASF
+ * licenses this file to You under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
+ * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
+ * License for the specific language governing permissions and limitations under
+ * the License.
+ */
+package org.apache.sling.scripting.core.impl;
+
+import java.io.Reader;
+import java.util.Arrays;
+import java.util.Collections;
+import java.util.List;
+
+import javax.script.Bindings;
+import javax.script.ScriptContext;
+import javax.script.ScriptEngine;
+import javax.script.ScriptEngineFactory;
+import javax.script.ScriptException;
+import javax.script.SimpleBindings;
+
+/**
+ * A dummy script engine factory.
+ *
+ */
+public class DummyScriptEngineFactory implements ScriptEngineFactory {
+
+    class DummyScriptEngine implements ScriptEngine {
+
+        public Bindings createBindings() {
+            return new SimpleBindings();
+        }
+
+        public Object eval(String arg0) throws ScriptException {
+            throw new UnsupportedOperationException();
+        }
+
+        public Object eval(Reader arg0) throws ScriptException {
+            throw new UnsupportedOperationException();
+        }
+
+        public Object eval(String arg0, ScriptContext arg1) throws ScriptException {
+            throw new UnsupportedOperationException();
+        }
+
+        public Object eval(Reader arg0, ScriptContext arg1) throws ScriptException {
+            throw new UnsupportedOperationException();
+        }
+
+        public Object eval(String arg0, Bindings arg1) throws ScriptException {
+            throw new UnsupportedOperationException();
+        }
+
+        public Object eval(Reader arg0, Bindings arg1) throws ScriptException {
+            throw new UnsupportedOperationException();
+        }
+
+        public Object get(String arg0) {
+            throw new UnsupportedOperationException();
+        }
+
+        public Bindings getBindings(int arg0) {
+            throw new UnsupportedOperationException();
+        }
+
+        public ScriptContext getContext() {
+            throw new UnsupportedOperationException();
+        }
+
+        public ScriptEngineFactory getFactory() {
+            return DummyScriptEngineFactory.this;
+        }
+
+        public void put(String arg0, Object arg1) {
+            // NO-OP
+        }
+
+        public void setBindings(Bindings arg0, int arg1) {
+            // NO-OP
+        }
+
+        public void setContext(ScriptContext arg0) {
+            // NO-OP
+        }
+
+    }
+
+    public String getEngineName() {
+        return "Dummy Scripting Engine";
+    }
+
+    public String getEngineVersion() {
+        return "1.0";
+    }
+
+    public List<String> getExtensions() {
+        return Arrays.asList("dum", "dummy");
+    }
+
+    public String getLanguageName() {
+        return "dummy";
+    }
+
+    public String getLanguageVersion() {
+        return "2.0";
+    }
+
+    public String getMethodCallSyntax(String arg0, String arg1, String... arg2) {
+        throw new UnsupportedOperationException();
+    }
+
+    public List<String> getMimeTypes() {
+        return Collections.singletonList("application/x-dummy");
+    }
+
+    public List<String> getNames() {
+        return Arrays.asList("Dummy", "dummy");
+    }
+
+    public String getOutputStatement(String arg0) {
+        throw new UnsupportedOperationException();
+    }
+
+    public Object getParameter(String arg0) {
+        throw new UnsupportedOperationException();
+    }
+
+    public String getProgram(String... arg0) {
+        throw new UnsupportedOperationException();
+    }
+
+    public ScriptEngine getScriptEngine() {
+        return new DummyScriptEngine();
+    }
+
+}

Added: sling/trunk/bundles/scripting/core/src/test/java/org/apache/sling/scripting/core/impl/ScriptEngineManagerFactoryTest.java
URL: http://svn.apache.org/viewvc/sling/trunk/bundles/scripting/core/src/test/java/org/apache/sling/scripting/core/impl/ScriptEngineManagerFactoryTest.java?rev=941044&view=auto
==============================================================================
--- sling/trunk/bundles/scripting/core/src/test/java/org/apache/sling/scripting/core/impl/ScriptEngineManagerFactoryTest.java
(added)
+++ sling/trunk/bundles/scripting/core/src/test/java/org/apache/sling/scripting/core/impl/ScriptEngineManagerFactoryTest.java
Tue May  4 21:16:46 2010
@@ -0,0 +1,167 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with this
+ * work for additional information regarding copyright ownership. The ASF
+ * licenses this file to You under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
+ * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
+ * License for the specific language governing permissions and limitations under
+ * the License.
+ */
+package org.apache.sling.scripting.core.impl;
+
+import static org.junit.Assert.*;
+
+import java.io.File;
+import java.io.FileOutputStream;
+import java.io.IOException;
+import java.util.Dictionary;
+
+import javax.script.ScriptEngineManager;
+
+import org.jmock.Expectations;
+import org.jmock.Mockery;
+import org.jmock.integration.junit4.JMock;
+import org.jmock.integration.junit4.JUnit4Mockery;
+import org.junit.Before;
+import org.junit.Test;
+import org.junit.runner.RunWith;
+import org.osgi.framework.Bundle;
+import org.osgi.framework.BundleContext;
+import org.osgi.framework.BundleEvent;
+import org.osgi.framework.BundleListener;
+import org.osgi.framework.ServiceListener;
+import org.osgi.framework.ServiceReference;
+import org.osgi.framework.ServiceRegistration;
+import org.osgi.service.component.ComponentContext;
+
+/**
+ * Test of the ScriptEngineManagerFactory.
+ */
+@RunWith(JMock.class)
+public class ScriptEngineManagerFactoryTest {
+
+    private static Class<?> SCRIPT_ENGINE_FACTORY = DummyScriptEngineFactory.class;
+
+    private Mockery context = new JUnit4Mockery();
+
+    private ComponentContext componentCtx;
+
+    private BundleContext bundleCtx;
+
+    @Before
+    public void setup() throws Exception {
+        componentCtx = context.mock(ComponentContext.class);
+        bundleCtx = context.mock(BundleContext.class);
+        context.checking(new Expectations(){{
+            atLeast(1).of(componentCtx).getBundleContext();
+            will(returnValue(bundleCtx));
+
+            allowing(bundleCtx).createFilter(with(any(String.class)));
+            allowing(bundleCtx).addServiceListener(with(any(ServiceListener.class)));
+            allowing(bundleCtx).addServiceListener(with(any(ServiceListener.class)), with(any(String.class)));
+            allowing(bundleCtx).getServiceReferences(with(any(String.class)), with(aNull(String.class)));
+            allowing(bundleCtx).getServiceReferences(with(aNull(String.class)), with(aNull(String.class)));
+            allowing(bundleCtx).getServiceReferences(with(any(String.class)), with(any(String.class)));
+            allowing(bundleCtx).getServiceReferences(with(aNull(String.class)), with(any(String.class)));
+
+            one(bundleCtx).addBundleListener(with(any(BundleListener.class)));
+            one(bundleCtx).getBundles();
+            will(returnValue(new Bundle[0]));
+
+            allowing(bundleCtx).registerService(with(equal("org.apache.felix.webconsole.ConfigurationPrinter")),
with(any(Object.class)), with(any(Dictionary.class)));
+            will(returnValue(new MockServiceRegistration()));
+
+
+        }});
+    }
+
+
+    @Test
+    public void checkNonNullManagerAfterActivate() throws Exception  {
+        context.checking(new Expectations(){{
+            one(bundleCtx).registerService(with(equal("javax.script.ScriptEngineManager")),
with(any(Object.class)), with(any(Dictionary.class)));
+            will(returnValue(new MockServiceRegistration()));
+        }});
+
+        ScriptEngineManagerFactory factory = new ScriptEngineManagerFactory();
+        factory.activate(componentCtx);
+
+        assertNotNull(factory.getScriptEngineManager());
+    }
+
+    @Test
+    public void checkAddingScriptBundle() throws Exception {
+        context.checking(new Expectations(){{
+            exactly(2).of(bundleCtx).registerService(with(equal("javax.script.ScriptEngineManager")),
with(any(Object.class)), with(any(Dictionary.class)));
+            will(returnValue(new MockServiceRegistration()));
+        }});
+
+        ScriptEngineManagerFactory factory = new ScriptEngineManagerFactory();
+        factory.activate(componentCtx);
+
+        ScriptEngineManager first = factory.getScriptEngineManager();
+
+        assertNull(first.getEngineByName("dummy"));
+
+        final Bundle bundle  = context.mock(Bundle.class);
+
+        final File factoryFile = createFactoryFile();
+
+        context.checking(new Expectations() {{
+
+            atLeast(1).of(bundle).getEntry("META-INF/services/javax.script.ScriptEngineFactory");
+            will(returnValue(factoryFile.toURI().toURL()));
+
+            atLeast(1).of(bundle).loadClass(SCRIPT_ENGINE_FACTORY.getName());
+            will(returnValue(SCRIPT_ENGINE_FACTORY));
+        }});
+
+        factory.bundleChanged(new BundleEvent(BundleEvent.STARTED, bundle));
+
+        ScriptEngineManager second = factory.getScriptEngineManager();
+        assertNotSame(first, second);
+
+        assertNotNull(second.getEngineByName("dummy"));
+    }
+
+    private File createFactoryFile() throws IOException {
+        File tempFile = File.createTempFile("scriptEngine", "tmp");
+        tempFile.deleteOnExit();
+
+        FileOutputStream fos = null;
+        try {
+            fos = new FileOutputStream(tempFile);
+            fos.write(SCRIPT_ENGINE_FACTORY.getName().getBytes());
+        } finally {
+            if (fos != null) {
+                fos.close();
+            }
+        }
+        return tempFile;
+    }
+
+    private class MockServiceRegistration implements ServiceRegistration {
+
+        public ServiceReference getReference() {
+            throw new UnsupportedOperationException();
+        }
+
+        @SuppressWarnings("unchecked")
+        public void setProperties(Dictionary properties) {
+            // NO-OP
+        }
+
+        public void unregister() {
+            // NO-OP
+        }
+
+    }
+
+}

Modified: sling/trunk/launchpad/builder/src/main/bundles/list.xml
URL: http://svn.apache.org/viewvc/sling/trunk/launchpad/builder/src/main/bundles/list.xml?rev=941044&r1=941043&r2=941044&view=diff
==============================================================================
--- sling/trunk/launchpad/builder/src/main/bundles/list.xml (original)
+++ sling/trunk/launchpad/builder/src/main/bundles/list.xml Tue May  4 21:16:46 2010
@@ -125,7 +125,7 @@
         <bundle>
             <groupId>org.apache.sling</groupId>
             <artifactId>org.apache.sling.scripting.api</artifactId>
-            <version>2.1.1-SNAPSHOT</version>
+            <version>2.1.0</version>
         </bundle>
         <bundle>
             <groupId>org.apache.sling</groupId>



Mime
View raw message